Compare commits

...
Author SHA1 Message Date
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
95 changed files with 4079 additions and 539 deletions

No files matched your search

+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"
```
+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}")
+50 -1
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")
@@ -306,3 +307,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"))
+14 -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,7 +241,18 @@ 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:
+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"
+166 -37
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:
"""
@@ -216,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()
+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()
+93 -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")
@@ -283,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()
@@ -323,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()
+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)
+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):
@@ -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()
+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(
+48 -1
View File
@@ -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")
@@ -502,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
@@ -571,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(
@@ -601,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
@@ -620,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:
+29 -7
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:
@@ -234,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:
"""
+87 -20
View File
@@ -38,10 +38,13 @@
│ (jobs) │ │ (files) │ │ (API keys) │ │ Worker (*) │
└──────────┘ └──────────┘ └──────────────┘ └──────────────┘
(*) GCE Encoding Worker: c4d-highcpu-32 VM with AMD EPYC 9B45 (Turin) for
high-performance FFmpeg encoding (4.92x faster than previous c4-standard-8).
(*) GCE Encoding Worker: a ranked pool of 6 x86_64 32-vCPU highcpu machine
families (c4d/c4/n4d/c2d/n2d/n2). c4d-highcpu-32 (AMD EPYC Turin) is the
fastest and stays the primary/preferred pick; the other families are
stockout-resilience fallbacks selected fastest-first with a capacity cooldown.
Used for both final video encoding and preview video generation.
Uses immutable deployment pattern - see infrastructure/encoding-worker/README.md.
Uses immutable deployment pattern - see infrastructure/encoding-worker/README.md
and the "Encoding Worker" section below.
```
### Error Monitor
@@ -292,33 +295,82 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
**Worker Logs**: Stored in subcollection (`jobs/{job_id}/logs`) instead of embedded array to avoid Firestore's 1MB document size limit. TTL policy auto-deletes logs after 30 days. Feature flag: `USE_LOG_SUBCOLLECTION` (default: true). See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#firestore-document-1mb-limit-with-embedded-arrays).
## Encoding Worker Blue-Green Deployment
## Encoding Worker: blue-green primary pair + multi-family fallback pool
The GCE encoding worker uses a blue-green deployment pattern with two named VMs (`encoding-worker-a` and `encoding-worker-b`).
The GCE encoding worker is a **blue-green primary pair** (`encoding-worker-a`/`-b`,
both c4d-highcpu-32 in us-central1-c) plus a **ranked pool of stockout-resilience
fallback VMs** spanning 6 x86_64 machine families (see "Multi-instance-type pool"
below). **10 VMs total**, all TERMINATED by default and started on demand.
### Architecture
```text
Frontend → Backend (Cloud Run) → Firestore config → Primary VM (encoding-worker-a or b)
↑
Frontend → Backend (Cloud Run) → Firestore config → active worker (primary, or a
↑ capacity-fallback "override")
Cloud Scheduler (5 min) → Cloud Function → checks idle + stops VMs
↑
CI (GitHub Actions) → deploys to secondary → health check → swap Firestore → stop old
CI (GitHub Actions) → selects a fresh "green" (ranked pool) → health + encode test
→ promote (swap primary OR set active_override) → stop old
```
### Multi-instance-type pool (stockout resilience, v0.195.0)
A single machine family can hit a region-wide `ZONE_RESOURCE_POOL_EXHAUSTED`
stockout across every zone at once. To survive that, the fallback fleet spans
**6 families** (c4d, c4, n4d, c2d, n2d, n2 — all `-highcpu-32`, ≥32 GB) across
zones a/b/c/f: `encoding-worker-fallback-a`/`-b` (c4d), `-n2c`/`-n2f` (n2),
`-c4a` (c4), `-n4db` (n4d), `-c2df` (c2d), `-n2da` (n2d).
**Candidate ordering is one shared pure module**,
`backend/services/encoding_worker_preference.py::ordered_candidates(pool, capacity_state)`,
used by BOTH runtime selection and deploy green selection so they can't drift:
- **Fastest-first** by `SPEED_RANK` (c4d preferred whenever it can start).
- **Availability-aware**: a family that recently hit a capacity/stockout error is
recorded in the Firestore `capacity_state` map and **demoted for a 15-min
cooldown**, then re-probed — so we stop wasting ~2 min probing a dead family but
snap back to c4d the moment capacity returns.
The fallback fleet is defined in `infrastructure/config.py::EncodingWorkerConfig.FALLBACKS`
and published to the backend/idle-fn via the `encoding-worker-fallback-vms` secret
(entries: `{vm, zone, ip, machine_type}`).
### Key Components
**Two VMs (a/b)**: Both VMs are TERMINATED by default. One is designated "primary" and serves all encoding traffic. The secondary VM exists solely to receive new deployments before they go live.
**Primary pair + fallback fleet**: All VMs TERMINATED by default. The primary pair
(a/b) does blue-green deploys; the 8 fallbacks absorb capacity stockouts. Runtime
warmup (`encoding_worker_manager.ensure_any_running`) tries the ranked candidates
in order, falling through on stockout and recording an `active_override` when it
lands on a fallback.
**Firestore config doc** (`config/encoding-worker`): Single source of truth for routing. Fields: `primary` (a or b), `ip_a`, `ip_b`, `deploy_in_progress` flag, `activity_a`/`activity_b` timestamps.
**Firestore config doc** (`config/encoding-worker`): source of truth for routing.
Fields: `primary_vm`/`primary_ip`/`primary_version`, `secondary_vm`/…, the
capacity-fallback pointer `active_override_vm`/`_ip`/`_zone`/`_version` (set when a
fallback is serving), `deploy_in_progress`, `last_activity_at`, and the
`capacity_state` map (`{"<machine_type>@<zone>": last_stockout_iso}`). `active_url`
= override IP if set, else primary IP.
**Backend routing** (`encoding_interface.py`): Reads the primary IP from the Firestore config doc with a 30-second TTL cache. All encoding requests route to the current primary.
**Backend routing** (`encoding_interface.py`): reads the active worker IP from the
config doc with a 30-second TTL cache.
**JIT startup**: When a user enters the lyrics review page, the backend starts the primary VM on demand. This gives ~60 seconds of natural warmup time before encoding is needed, avoiding both 24/7 costs and noticeable cold-start latency for the user.
**JIT startup**: entering the lyrics-review page starts the worker on demand
(~60 s natural warmup), avoiding 24/7 cost and cold-start latency.
**Idle auto-shutdown**: A Cloud Function (triggered every 5 minutes by Cloud Scheduler) checks the `activity_*` timestamps in Firestore and stops any VM that has been idle for more than 15 minutes. This is external to the VM — if the encoding worker code itself has a bug, the Cloud Function still shuts it down.
**Idle auto-shutdown**: a Cloud Function (every 5 min) stops idle VMs (primary,
secondary, and every fallback in the secret) based on Firestore activity — external
to the VM so a sick worker still gets stopped.
**Blue-green deploys**: CI builds a new wheel, deploys it to the secondary VM (not the live primary), runs a real encode test against the secondary, then atomically swaps the `primary` field in Firestore to point to the secondary. The old primary is stopped after the swap. If the health check fails, the primary is never updated.
**Capacity-aware deploys**: CI selects a FRESH "green" from the ranked pool via
`deploy_promote.select_green_candidates` (the same preference module) — the c4d
secondary if it can start, else a fallback family, never the currently-serving
override. After a real encode test on the green, it promotes: a c4d-secondary green
does the classic primary swap (and clears any stale override); a fallback green
becomes the `active_override`. The retired VM is drained + stopped; a failed health
check never promotes. Override routing keys off an explicit `is_primary` flag, not
list position. See `infrastructure/encoding-worker/deploy_promote.py`.
**Self-sufficient image**: the Packer image (`infrastructure/packer/scripts/provision.sh`)
bakes the full karaoke-gen dependency tree with **CPU-only torch**, so a fresh VM of
any family boots ready to encode (no first-job dependency install).
### Seeding the Config
@@ -327,17 +379,32 @@ Initial setup or reset:
python scripts/seed-encoding-worker-config.py <ip-a> <ip-b>
```
### Deploy Flow
### Deploy Flow (capacity-aware, v0.194.2+)
```text
1. CI builds new karaoke-gen wheel + pushes to GCS
2. CI starts secondary VM, waits for /health to respond
3. CI runs real encode test against secondary VM
4. If test passes: CI writes secondary name to Firestore `primary` field
5. CI stops the old primary VM
6. If test fails: CI stops secondary VM, primary unchanged
2. CI picks a FRESH "green" from the ranked pool (select_green_candidates →
ordered_candidates): the c4d secondary if it can start, else the fastest
available fallback family — never the currently-serving active_override.
3. CI starts the green, waits for /health, runs a real encode test against it.
4. If the test FAILS: CI stops the green; primary/override unchanged (no promote).
5. If the test PASSES: CI promotes the green:
- green is the c4d secondary → swap it to `primary_vm` (classic blue-green)
AND clear any stale `active_override_*` so
traffic returns to the fresh c4d primary.
- green is a fallback family → set it as `active_override_*` (the serving
worker); leave primary/secondary so c4d
resumes as primary when its capacity returns.
6. CI drains (waits active_jobs==0, bounded) + stops the retired VM — never the
promoted green.
7. Last resort (no separate green can start, e.g. deep stockout): in-place restart
of the current serving override — a brief blip, covered by client auto-resubmit.
```
Override routing keys off an explicit `is_primary` flag (not list position), so a
fallback ranked ahead of a stocked-out primary is still routed correctly. Pure
decision logic + unit tests: `infrastructure/encoding-worker/deploy_promote.py`.
## Video Worker Orchestrator
The Video Worker uses an orchestrator pattern to ensure all features work regardless of encoding backend (local Cloud Run or GCE VM).
+1 -1
View File
@@ -209,7 +209,7 @@ TESTMAIL_NAMESPACE=... # testmail.app namespace
## Encoding Worker Operations
The encoding worker uses a blue-green deployment with two GCE VMs (`encoding-worker-a`, `encoding-worker-b`). See [ARCHITECTURE.md](ARCHITECTURE.md#encoding-worker-blue-green-deployment) for the full design.
The encoding worker is a blue-green primary pair (`encoding-worker-a`/`-b`, c4d) plus a ranked pool of 8 stopped fallback VMs spanning 6 machine families (c4d/c4/n4d/c2d/n2d/n2) for stockout resilience — 10 VMs total. Candidate ordering (runtime + deploy) is the shared `backend/services/encoding_worker_preference.py`. See [ARCHITECTURE.md](ARCHITECTURE.md#encoding-worker-blue-green-primary-pair--multi-family-fallback-pool) for the full design.
### Seed Firestore config (initial setup or reset)
+18 -11
View File
@@ -79,19 +79,26 @@ The `concurrency=1` setting may have been added deliberately for performance rea
### 🔍 GCE Encoding Worker
**Current State:**
- c4d-highcpu-32 VM running 24/7
- Cost: ~$700/month
**Current State (updated v0.195.0 — the opportunities below are largely SHIPPED):**
- No longer a single 24/7 VM. It is a pool of **on-demand** VMs: a c4d-highcpu-32
blue-green primary pair + 8 stopped fallbacks across 6 machine families
(c4d/c4/n4d/c2d/n2d/n2) for stockout resilience.
- **Idle auto-shutdown is live** (JIT start on the lyrics-review page; a Cloud
Function stops idle VMs after 15 min). When idle, cost is just boot disks
(~$10/VM/mo); compute is billed only while encoding — so the historical
"~$700/mo running 24/7" no longer applies.
**Opportunities:**
1. **Spot Instance:** Could save 60-91% (~$420-630/month savings)
- Risk: May be preempted during video encoding jobs
- Mitigation: Implement job restart logic
2. **Auto-scaling:** Start/stop based on video queue depth
- Could scale to zero when no jobs queued
- Startup time: ~2-3 minutes (acceptable for async processing)
**Opportunities (status):**
1. **Spot Instance:** Could save 60-91% — NOT adopted; on-demand chosen so a
fallback can always be *started* when needed (Spot preemption would undermine
the anti-stockout pool during the industry-wide crunch). Kept as a future lever.
2. **Auto-scaling / scale-to-zero:** ✅ IMPLEMENTED via JIT start + idle-shutdown
Cloud Function (start/stop on demand rather than queue-depth-based).
**Recommendation:** Test Spot instance first (lower risk), then consider auto-scaling
**Recommendation:** Stay on-demand (already scales to zero via idle-shutdown, which
captured most of the savings). Do NOT move to Spot for now — Spot preemption plus
the industry-wide stockout would undermine the anti-stockout fallback pool. Revisit
Spot only as a future experiment once capacity/resiliency is validated.
### 🔧 Artifact Registry Cleanup (Quick Win)
+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.
+55
View File
@@ -6,6 +6,51 @@ 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
@@ -406,6 +451,16 @@ When two sequential human review steps can be combined into one, do it. We origi
### Machine-family diversification (August 2026)
> **Superseded by v0.195.0** — the "Multi-instance-type encode pool" lesson at the
> top of this file. The 2-family fallback fleet (c4d + n2) described below was
> broadened to a **ranked 6-family pool** (c4d/c4/n4d/c2d/n2d/n2), and runtime +
> deploy selection now route through the shared
> `backend/services/encoding_worker_preference.py` (fastest-first + 15-min capacity
> cooldown), not "primary first, fallbacks in declared order". The incident + root
> lesson below remain accurate history; the "Fix (Option B)" and "Architecture
> summary" specifics (2 families / 6 VMs / declared-order iteration) are outdated —
> see the v0.195.0 lesson for the current mechanism.
**Incident 2026-08-12:** `c4d-highcpu-32` hit a **region-wide `ZONE_RESOURCE_POOL_EXHAUSTED` stockout across `us-central1-a`, `-b` AND `-c` simultaneously.** Because the primary pair *and* both fallbacks were all the same machine family, every lane in `ensure_any_running` failed at once. Effects:
- **Preview** (`POST /api/review/{id}/preview-video`) fell through to slow local Cloud-Run encoding (~130–160 s), which **exceeds Cloudflare's ~100 s edge timeout** → browser got a **524 / "NetworkError when attempting to fetch resource"** even though the backend actually returned 200. The 524 and the NetworkError are the same event; backend logs showing 200 are misleading because the client was already disconnected.
- **Render** parked in `RENDER_PENDING_CAPACITY` and auto-retried (safe only if capacity returns within 24 h).
+19 -8
View File
@@ -64,7 +64,7 @@ Since v0.184.2, in-flight status polls are also **pinned to the worker that acce
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 — the c4d secondary if it starts, else a different n2 fallback (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).
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).
---
@@ -94,13 +94,18 @@ The script is idempotent — re-running it skips regeneration if the CDG ZIP alr
**Cause:** Worker picks up a new deploy but doesn't restart automatically.
Target the **currently-serving** VM — `active_override_vm` in `config/encoding-worker`
if set, else `primary_vm` (with its zone). There is no VM literally named
`encoding-worker`; the examples below use the primary `encoding-worker-a` — swap in
the active VM/zone if a fallback is serving.
```bash
# Check current wheel version
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
# Check current wheel version (example: the primary a in us-central1-c)
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
--command="curl -s http://localhost:8080/health | python3 -m json.tool"
# Restart to pick up latest wheel
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
```
@@ -110,7 +115,9 @@ gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
**Symptoms:** A render fails with `OutputGenerator not available: No module named 'tenacity'. The karaoke-gen wheel must be installed. Check that ensure_latest_wheel() succeeded.` (or another missing package). Retries hit the same VM and fail identically.
**Cause:** A freshly-provisioned encoding-worker VM comes up with only a handful of packages baked into the Packer image, and boot installs the wheel with `--no-deps`. The full karaoke-gen dependency tree (torch, langchain, tenacity, …) is installed lazily at the first job by `ensure_latest_wheel()`. If that install fails or partially completes, the venv is left importable-but-incomplete and the render dies on the first missing import. First seen 2026-08-13 (job 233b9536) on a fresh `n2-highcpu-32` fallback added in #903.
**Largely fixed in v0.195.0 (dep-bake):** the Packer image now bakes the **full** karaoke-gen dependency tree (with CPU-only torch) into the venv at build time, so a freshly-provisioned VM of any family boots self-sufficient — no first-job dependency install. This failure mode should now only appear on a VM whose boot disk predates the dep-bake image, or a venv left partial by an interrupted repair. The `ensure_latest_wheel()` runtime backstop below still exists for those cases.
**Original cause (pre-v0.195.0):** A freshly-provisioned VM came up with only a handful of packages baked in, and boot installed the wheel with `--no-deps`. The full dependency tree (torch, langchain, tenacity, …) was installed lazily at the first job by `ensure_latest_wheel()`; a failed/partial install left the venv importable-but-incomplete and the render died on the first missing import. First seen 2026-08-13 (job 233b9536) on a fresh `n2-highcpu-32` fallback added in #903.
**Fixed in v0.192.7:** `ensure_latest_wheel()` now downloads only the single latest wheel (was: copying the entire ~6 GiB `wheels/` dir every job with a 60 s timeout), retries the install (3× at 900 s), and **verifies the render/encode import chain** before returning — a clean `pip` exit is no longer trusted. Callers fail the job with a clear retryable error instead of proceeding. Fresh workers pick this up via the wheel-at-boot.
@@ -281,7 +288,7 @@ gcloud compute instances describe encoding-worker-a \
**Background — what this state means:** GCE returned `ZONE_RESOURCE_POOL_EXHAUSTED` or transient `503 SERVICE_UNAVAILABLE` from `compute.instances.start` on every encoding-worker VM. The render worker parks the job in `RENDER_PENDING_CAPACITY` instead of failing it; Cloud Scheduler retries it every 5 min via `/api/internal/retry-pending-render-jobs`. Hard timeout is 24 hours (then transitions to `failed` with a clear permanent-failure message).
The fallback fleet is diversified by **machine family** (since incident 2026-08-12): `c4d-highcpu-32` primaries in `us-central1-c` + `c4d` fallbacks in `-a`/`-b` + `n2-highcpu-32` fallbacks (`encoding-worker-fallback-n2c`/`-n2f`) in `-c`/`-f`. The n2 pool is much deeper, so a full `c4d` region-wide stockout (which took out a/b/c at once on 2026-08-12) should now still find n2 capacity. If you see EVERY candidate (c4d **and** n2) return stockout, that's a genuinely severe regional event — wait, or add a cross-region fallback.
The fallback fleet is diversified across **6 machine families** (broadened to the full pool in v0.195.0): `c4d-highcpu-32` primaries (`encoding-worker-a`/`-b`) in `us-central1-c`, plus 8 stopped fallbacks — `c4d` (`-fallback-a`/`-b`, zones a/b), `n2` (`-n2c`/`-n2f`, zones c/f), `c4` (`-c4a`, zone a), `n4d` (`-n4db`, zone b), `c2d` (`-c2df`, zone f), `n2d` (`-n2da`, zone a). Candidates are tried **fastest-first with a 15-min capacity cooldown** (a family that stocks out is demoted, then re-probed) — see `backend/services/encoding_worker_preference.py`. A single-family region-wide stockout (which took out c4d a/b/c at once on 2026-08-12) now still finds capacity in the 5 other families. If you see EVERY family return stockout, that's a genuinely severe regional event — wait, or add a cross-region fallback. NOTE: creating a *new* fallback VM (or re-creating a deleted one) still needs a one-time boot allocation, so a deep enough crunch can even block provisioning — a `pulumi up` may show the missing VM as "to create / errored" until capacity returns.
**Related symptom — preview 524 / "NetworkError":** the same capacity exhaustion also makes `POST /api/review/{id}/preview-video` fall back to slow local encoding (~130–160 s), which exceeds Cloudflare's ~100 s edge timeout → the browser shows a **524** or Firefox *"NetworkError when attempting to fetch resource"* even though the backend returns 200. If a user reports the review preview failing, check for a concurrent stockout; the already-rendered preview mp4 (if any) is fetchable via `GET /api/review/{id}/preview-video/{hash}` (302 → signed GCS URL) with a Bearer admin token. Completing the review does **not** require the preview.
@@ -309,14 +316,18 @@ gcloud logging read 'protoPayload.methodName:"instances.start" AND "ZONE_RESOURC
--project=nomadkaraoke --freshness=30m --limit=5 \
--format='value(timestamp, protoPayload.resourceName)'
# Try starting a fallback in each family; if BOTH c4d and n2 refuse, it's severe — wait.
# Try starting a fallback in each of the 6 families; if ALL refuse, it's severe — wait.
# Synchronous (no --async) so the start op surfaces stockout inline, and we capture
# gcloud's own exit status rather than piping (a pipe would return sed's status).
for VM_ZONE in \
"encoding-worker-fallback-a:us-central1-a" \
"encoding-worker-fallback-b:us-central1-b" \
"encoding-worker-fallback-n2c:us-central1-c" \
"encoding-worker-fallback-n2f:us-central1-f"; do
"encoding-worker-fallback-n2f:us-central1-f" \
"encoding-worker-fallback-c4a:us-central1-a" \
"encoding-worker-fallback-n4db:us-central1-b" \
"encoding-worker-fallback-c2df:us-central1-f" \
"encoding-worker-fallback-n2da:us-central1-a"; do
VM="${VM_ZONE%%:*}"; ZONE="${VM_ZONE##*:}"
if OUT=$(gcloud compute instances start "$VM" --zone="$ZONE" --project=nomadkaraoke 2>&1); then
echo "$VM: OK (started — remember to stop it)"
@@ -0,0 +1,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.
@@ -2,7 +2,32 @@
**Date:** 2026-08-15
**Branch:** `feat/sess-20260815-1915-encoding-instance-type-diversity`
**Status:** IMPLEMENTED (v0.195.0) — code + IaC + Packer landed; operator rollout steps below still pending.
**Status:** SHIPPED (v0.195.0 #911 + v0.195.1 #912) — code + IaC + Packer merged & rolled out.
## Rollout outcome (2026-08-16)
- ✅ Backend 0.195.1 live on Cloud Run; encode path healthy (c4d primary `encoding-worker-a`
RUNNING 0.195.1 after c4d capacity returned to us-central1-c). `capacity_state` field live.
- ✅ Encoding-worker image rebuilt with the CPU-torch dep-bake; **validated end-to-end** — a fresh
`c4a` booted healthy in ~24s and encoded a preview in <6s (no first-job dep install).
- ✅ **All 8 fallback VMs provisioned** (stopped), so the full 6-family pool is live:
`-a`/`-b` (c4d), `-n2c`/`-n2f` (n2), `-c4a` (c4), `-n2da` (n2d), `-c2df` (c2d), `-n4db` (n4d).
Pulumi state consistent (`c4a`, orphaned by a killed apply, was `pulumi import`ed + reconciled).
Secret at **version 5** (8 entries, all with `machine_type`).
- ⏳→✅ **`c2df` + `n4db` were initially deferred** (created stopped VM still needs a one-time boot
allocation, so the 2026-08-15 stockout in zones f/b blocked provisioning). An autonomous
10-minute retry loop finished them on **2026-08-16 ~07:48** when zones f/b left stockout, and
added both to the secret (v5). **Historical note for a future crunch:** if a fallback VM is
missing/deleted, re-create it with the FULL Pulumi URNs (not an ellipsis) — e.g.
`cd infrastructure && pulumi up --yes --target 'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:compute/instance:Instance::encoding-worker-fallback-c2df' --target 'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:compute/instance:Instance::encoding-worker-fallback-n4db'`
(use the write-token env from the rollout notes) — then add it to the `encoding-worker-fallback-vms`
secret with its `machine_type`, but **never add a VM to the secret before it exists** (a
non-existent candidate → `get_vm_status` 404 → breaks warmup).
- Not done: measured `SPEED_RANK` benchmark run (arch-seeded; a 2026-08-16 benchmark was too noisy
to apply — see the CPU-platform-variance findings); MIG; reservations.
---
**Context:** memory `project_gen_encoding_instance_type_diversity` + `_worker_serialization` + `_machine_family_diversity` + `_wheel_deps_missing`
## Goal
@@ -0,0 +1,214 @@
# Handoff: Investigate prod finalization CPU efficiency / utilization — 2026-08-16
**Status:** ✅ RESOLVED 2026-08-16 — outcome (a): CPU already well-utilized (NOT
capped at 8 cores); removed dead `ffmpeg_threads` config. Empirical measurement +
resolution appended at the bottom under "RESOLUTION". The original investigation
brief follows unchanged for context.
**Status (original):** OPEN investigation (not started). Written for a fresh Claude session —
self-contained; all facts you need are inlined below or in the linked repo docs.
**Origin:** surfaced by the encode-worker multi-instance-type benchmark
(`docs/archive/2026-08-15-encoding-instance-type-diversity-plan.md`; benchmark
baselines inlined under "Reproducing the benchmark" below).
## The question
Prod video **finalization** (the `/encode` path that produces
`mp4_4k_lossless + mp4_4k_lossy + mp4_720p`) — is it using the 32-vCPU
`*-highcpu-32` workers efficiently? The trigger was the stale
`"ffmpeg_threads": 8` (with a comment referencing the retired `c4-standard-8`)
in the job config, which looked like it might cap ffmpeg to 8 of 32 cores.
**Static analysis has already answered the first-order question (do NOT re-derive
it — verify then move on):** `ffmpeg_threads` is **dead config**. It is set at
`backend/workers/video_worker.py:131` but **no code reads it** (grep for consumers
returns nothing; `run_encoding()`'s `EncodingConfig(...)` at
`backend/services/gce_encoding/main.py:1111` never passes it), and the actual
finalization ffmpeg commands in `backend/services/local_encoding_service.py`
(`encode_all_formats` → `encode_lossless_mp4`/`encode_lossy_mp4`/`encode_720p`,
around lines 343 / 396 / 471) carry **no `-threads` flag at all** → ffmpeg falls
back to its default (`-threads 0`, i.e. auto ≈ all cores). So finalization is
**almost certainly NOT capped at 8 cores**; the "leaving 75% idle" fear is likely
unfounded. (Separate, unrelated paths that DO hardcode threads — don't confuse
them: `main.py:372` uses `-threads 8` in the **preview** `/encode-preview`
480×270 path; `local_preview_encoding_service.py:310` uses `-threads 0`.)
So this is now a **narrower efficiency + cleanup** task, not a "fix the cap" task.
## What to determine (in order)
1. **Confirm the static finding empirically** (x264's `-threads 0` "auto" is a
heuristic — it does NOT always scale to all cores; historically it caps frame
threads, with diminishing returns past ~16). Drive a real finalization and
capture **process-level** evidence, not just host-wide load:
- the **deployed ffmpeg argv** for each format (`ps -eo pid,args | grep ffmpeg`
on the worker mid-encode, or add a log line) — confirm no `-threads` and see
what x264 chose;
- **per-process / per-thread** CPU% and RSS (`top -H -p <ffmpeg-pid>`,
`pidstat -t -p <pid> 2`), NOT `mpstat -P ALL` alone — host-wide utilization
can't tell an 8-thread cap from serial `encode_all_formats` stages or
unrelated work;
- **per-format stage timings** (which of lossless/lossy/720p dominates).
Run all of this against the SAME worker you drive the encode to (see the
binding note in "Reproducing the benchmark").
2. **Check whether the 3 formats encode SERIALLY or in PARALLEL** in
`encode_all_formats` (`backend/services/local_encoding_service.py`). If serial,
wall-time ≈ sum of the three even if each saturates the cores — the real lever
may be **overlapping independent format encodes** rather than more threads. But
see the RAM constraint below before parallelizing.
3. **Decide the fix (likely small) and validate it:**
- **Cleanup regardless:** remove the dead `ffmpeg_threads` field + stale comment
at `backend/workers/video_worker.py:131` (it misleads; that is the "documentation-
only" close-out CodeRabbit flagged). If you'd rather *use* it, wire it through
`EncodingConfig` → the `local_encoding_service.py` ffmpeg commands as an explicit
`-threads`; otherwise delete it.
- If step 1 shows real idle cores (x264 auto under-scales), the win is an explicit
high `-threads` (or `-x264-params threads=N`) or overlapping formats — validate
with a before/after re-benchmark on the SAME input+VM.
- If step 1 shows cores already saturated, close this out as "already efficient;
removed dead config" and stop.
## Hard constraints — do NOT regress these
- **Heavy-lane serialization stays.** `ENCODING_HEAVY_CONCURRENCY=1` (one heavy
encode at a time per worker) exists because 3 **concurrent** 4K encodes OOM-killed
the 32 GB worker (incident 2026-08-15; full write-up in `docs/LESSONS-LEARNED.md`
→ "Concurrent encodes OOM-killed the worker → lost renders").
Raising *threads within a single encode* is **orthogonal** to that and does not
reintroduce concurrency — but it DOES raise a single encode's **peak RAM** (more
parallel ffmpeg slices / parallel format encodes). Watch RSS on a 32 GB floor VM
(n2/n2d fallbacks are 32 GB; c4d/c4/n4d are 60–64 GB). A single 4K lossless encode
was ~18 GB; leave headroom.
- **Lossless 4K is the heavy one** (`pcm_s16le`, huge intermediate) — profile that
format specifically.
## Reproducing the benchmark (for before/after numbers)
The benchmark used a real completed job's inputs as a canonical `/encode` input.
It was deleted after the run (`gs://…/bench/` cleaned up). To recreate:
```bash
J=gs://karaoke-gen-storage-nomadkaraoke/jobs/ffc17eb7 # "Glen Campbell - A Better Place"
I=gs://karaoke-gen-storage-nomadkaraoke/bench/encode-input
gsutil -q cp "$J/videos/with_vocals.mkv" "$I/videos/with_vocals.mkv" # 119 MB rendered 4K karaoke video
gsutil -q cp "$J/screens/title.png" "$I/screens/title.png"
gsutil -q cp "$J/screens/end.png" "$I/screens/end.png"
gsutil -q cp "$J/stems/instrumental_clean.flac" "$I/stems/instrumental_clean.flac"
gsutil -q cp "$J/style/style_params.json" "$I/style/style_params.json"
gsutil -q cp "$J/lyrics/karaoke.ass" "$I/lyrics/karaoke.ass"
```
**Bind the encode to the worker you observe.** Pick ONE stopped fallback (e.g.
`encoding-worker-fallback-c4a`, us-central1-a), start it, and send BOTH the
`/encode` POST and the `/status` polls **directly to that worker's external IP**
(`http://<IP>:8080/…`, not through the backend/`api.nomadkaraoke.com` — the
backend may route to a different active worker). SSH the SAME VM for the
process-level probes in step 1, so the CPU/RSS you measure is the encode you drove.
Get the IP: `gcloud compute instances describe <vm> --zone=<z>
--format='value(networkInterfaces[0].accessConfigs[0].natIP)'`.
`POST http://<IP>:8080/encode` body (`X-API-Key` from
`gcloud secrets versions access latest --secret=encoding-worker-api-key`):
```json
{"job_id":"cpu-probe-1","input_gcs_path":"gs://…/bench/encode-input/",
"output_gcs_path":"gs://…/bench/out/probe/",
"encoding_config":{"formats":["mp4_4k_lossless","mp4_4k_lossy","mp4_720p"],
"base_name":"Glen Campbell - A Better Place","artist":"Glen Campbell",
"title":"A Better Place","instrumental_selection":"clean",
"existing_instrumental":null}}
```
(`ffmpeg_threads` deliberately omitted from the body above — it is dead config;
see "The question".) Poll `GET http://<IP>:8080/status/{job_id}` to `complete`. Baseline medians from 2026-08-16 (full
3-format finalization of this ~4-min song; the runs sent `ffmpeg_threads:8` in the
body but the worker ignored it, so these reflect ffmpeg's default all-core threading):
c4-Emerald ≈ **139s**, n2d-Milan ≈ **139s**, n2-CascadeLake ≈ **247s**, n2-IceLake
≈ **92s** (c4d unmeasured — could not start a 2nd c4d in the stockout). The huge
n2 spread — **92s vs 247s for the identical `n2-highcpu-32` SKU** — is because n2
spans Intel Ice Lake (fast) and Cascade Lake (slow) and GCE assigns either; that
intra-family variance exceeds the between-family differences. Separate actionable
finding: pin `min_cpu_platform` (e.g. "Intel Ice Lake" / "AMD Milan") on n2/n2d
fallbacks for predictable speed, or rank them lower to reflect the gamble. Also
note the counterintuitive result that c4 (newest Intel Emerald) ≈ n2d (Milan) and
did NOT beat n2 Ice Lake for this lossless-4K-heavy workload — so "newest = fastest"
does not hold here; measure, don't assume.
**Operational hygiene:** benchmark VMs are stopped fallbacks — start, probe, then
STOP them (never the live-serving primary; the idle-shutdown fn also handles it).
Delete `gs://…/bench/**` when done. Auth for VM start/stop: `gcloud` as
`admin@nomadkaraoke.com`.
## Expected outcome
Either: (a) confirm CPU is already saturated (`ffmpeg_threads` is dead config) →
close this out and just fix the stale comment; or (b) confirm an ~2–4× idle-core
gap → raise threads / parallelize formats, validate the speedup and RAM headroom,
ship it. Bump `pyproject.toml` version; if the fix is in the wheel's
`LocalEncodingService`, it ships via the normal wheel → `ensure_latest_wheel` path.
---
## RESOLUTION (2026-08-16) — outcome (a): already efficient; dead config removed
**Verdict: the "leaving 75% idle" fear is unfounded. Finalization uses ~21–25 of a
worker's 32 vCPUs during every heavy libx264 stage. No threading fix warranted.**
### 1. `ffmpeg_threads` is dead config — confirmed statically AND empirically
- Before this change, `grep -rn ffmpeg_threads backend/` returned exactly one hit —
the setter `"ffmpeg_threads": 8` in the `encoding_config` dict at
`video_worker.py:131` — with zero consumers; `EncodingConfig(...)` at
`gce_encoding/main.py:1111` never passes it. This change removes that setter
(line 131 is now the explanatory NOTE comment), so grep now returns no setter.
- **Empirically**, the deployed ffmpeg argv captured mid-encode (`ps`/probe on the
worker) carry **no `-threads` flag** on any finalization command — x264 runs its
all-core auto default. Sample argv observed:
- `… -i with_vocals.mkv -c:v libx264 -c:a copy … (With Vocals).mp4`
- `… concat=n=3… -c:v libx264 -c:a pcm_s16le … (Final Karaoke Lossless 4k).mp4`
- `… -i …Lossless 4k.mp4 -c:v copy -c:a aac … (Lossy 4k).mp4`
- `… -c:v libx264 -vf scale=1280:720 -preset medium -tune animation … (Lossy 720p).mp4`
### 2. Process-level CPU measurement (the point of this task)
Method: started `encoding-worker-fallback-c4a` (c4-highcpu-32, 32 vCPU / 62 GB),
recreated the bench input, POSTed `/encode` **directly to the VM IP**, and sampled
`top -bH -d 2` on that same VM for the whole run. The authoritative signal is the
system-wide `%Cpu(s)` summary line (0–100% across all 32 cores):
| Stage (serial) | ffmpeg cmd | `%Cpu us` (of 32) | ≈cores busy | peak RSS | ~duration |
|---------------------------|------------------------------------|-------------------|-------------|----------|-----------|
| "With Vocals" mp4 convert | `libx264 -c:a copy` (mkv→mp4) | 64–70% | ~21 | ~11 GB | ~59 s |
| **Lossless 4K concat** | `libx264 -c:a pcm_s16le` | 72–75% | ~23 | ~9 GB | ~45 s |
| Lossy 4K | `-c:v copy -c:a aac` (stream copy) | 3–5% | I/O-bound | <0.1 GB | ~4 s |
| MKV (YouTube) | `-c:v copy -c:a flac` (copy) | low | I/O-bound | — | ~2 s |
| 720p | `libx264 scale=1280:720 -preset medium` | 76–78% | ~25 | ~1.2 GB | ~12 s |
Full run: ~122 s of encoding + ~35 s GCS download/upload = **~158 s wall** (matches
the ~139 s c4 baseline plus I/O). An 8-core cap would show `us≈25%, idle≈75%`; we
observed the **opposite** (`us≈66–78%, idle≈22–34%`). Not capped.
### 3. Why the residual ~25–30% idle is NOT recoverable by more threads
The heavy processes already spawn 90–162 OS threads (`nlwp`); x264's auto default is
~1.5×cores. The idle is the structural ceiling of x264 **frame-threading**
(inter-frame dependencies + a partially-serial lookahead), not a thread cap. Forcing
`-threads 32`/`-x264-params threads=N` above auto gives negligible speed and can hurt
quality. **Formats are serial and dependency-chained** (`encode_all_formats` steps
3→{4,5,6}; lossy/mkv/720p all consume the lossless output), and the only overlap-able
work after lossless is two near-free stream copies (lossy, mkv) — so parallelizing
formats buys ~nothing and would raise peak RAM against the 32 GB fallback floor +
the `ENCODING_HEAVY_CONCURRENCY=1` OOM constraint. Not worth it.
### 4. What shipped
- Removed the dead `"ffmpeg_threads": 8` field + stale `c4-standard-8` comment at
`video_worker.py:131`, replaced with a NOTE explaining the measured all-core
behaviour (so nobody re-opens this). No behaviour change. Version bump only.
### 5. Follow-up worth its own task (NOT done here — out of scope, needs verification)
The single biggest CPU cost is the **"With Vocals" preview** — a full 4K libx264
re-encode (~59 s, longer than the lossless master itself). The source
`with_vocals.mkv` is **already H.264** (High 4:4:4 Predictive, 3840×2160, `yuv444p`).
If nothing downstream needs a re-encode / a different `pix_fmt`, this could become a
container remux (`-c:v copy`) and save ~40–50 s/job — a far bigger win than any
threading tweak. Requires confirming: (a) do players/consumers need `yuv420p` (4:4:4
mp4 is poorly supported), and (b) does `convert_mov_to_mp4` intentionally normalize
pix_fmt? Left for a dedicated investigation.
### Operational note
Bench VM stopped, `gs://…/bench/**` deleted after the run, per hygiene.
@@ -0,0 +1,71 @@
# "With Vocals" preview encode — faster, smaller, more portable (2026-08-16)
**Status:** ✅ SHIPPED (v0.196.0). Follow-up from the finalization-CPU investigation
(`2026-08-16-finalization-cpu-efficiency-handoff.md`), which identified the "With
Vocals" conversion as the single longest finalization stage.
## Problem
`convert_mov_to_mp4` produces the **"(With Vocals).mp4"** sing-along deliverable from
the renderer's source video. Process-level measurement on a live c4-highcpu-32 worker
showed this was the **longest single finalization stage (~59s)** — longer than the
lossless master itself.
Probing a real prod job (`faafd5ad`) revealed the encode was *accidentally* bad:
- **No `-pix_fmt`** → inherited the renderer's `High 4:4:4 Predictive / yuv444p`. This
is the **only** 4:4:4 file in the deliverable set (every other output is `yuv420p`),
and 4:4:4 H.264 is rejected by many browsers/TVs/phones.
- **Default `medium` preset** → slow.
- **`-c:a copy`** (LocalEncodingService path) → **FLAC-in-MP4**, which is non-standard,
despite the customer-facing spec (`template_service.py`) documenting the file as
"4k H264/**AAC**".
## Safety check — is the "With Vocals" mp4 used downstream?
**No.** Confirmed in both encode paths (cloud `encode_all_formats` and local
`KaraokeFinalise.remux_and_encode_output_video_files`): every later output (Karaoke.mp4,
Lossless/Lossy/720p, MKV) derives from the **source** `with_vocals` file (via
`remux_with_instrumental` → `Karaoke.mp4` → concat) and carries the **instrumental**
audio. YouTube upload uses `final_karaoke_lossless_mkv`. The "(With Vocals).mp4" is
written once and only uploaded/delivered — a leaf. So its encode can be chosen purely
for the deliverable.
## Fix
`convert_mov_to_mp4` software (CPU) command — the path that runs on prod workers
(no NVENC) — changed to:
```
-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):
- `backend/services/local_encoding_service.py::LocalEncodingService.convert_mov_to_mp4`
(cloud worker — prod)
- `karaoke_gen/karaoke_finalise/karaoke_finalise.py::KaraokeFinalise.convert_mov_to_mp4`
(local CLI; already emitted AAC, now also 4:2:0 + veryfast + 320k)
GPU/NVENC command: emits AAC 320k; `h264_nvenc` encodes 4:2:0 natively so no `-pix_fmt`
needed. (Prod workers are CPU-only; NVENC is a local/GPU path.)
## Measured result (real source: Arctic Monkeys – Riot Van, 138s 4K)
| 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 gets **smaller** (AAC 320k ≪ FLAC ~639k, and 4:2:0
< 4:4:4), so there is no size/CPU tradeoff — every axis improves, plus universal
playback and spec-alignment.
## Notes / non-goals
- Quality: for karaoke content (static background + text) `veryfast` vs `medium` is
visually negligible; CRF-based, comparable bitrate.
- The finalise-only **user-upload** path (a user's own `.mov`/`.mkv`, arbitrary codec)
still re-encodes correctly — the command is codec-agnostic (no stream-copy assumption).
- Not touched: whether a "reference" file needs to be 4K at all (a 1080p variant would
be smaller still) — a product decision, left for later.
@@ -0,0 +1,204 @@
# Plan: Fix visibility-change redistribution + make sequence-gap alerts recycle-aware
**Created:** 2026-08-18
**Branch:** feat/sess-20260818-1124-visibility-recycle-dataloss
**Status:** Draft
## Overview
Investigation of a "GDrive Validation: missing 1537" alert traced to a **public→private
visibility change** on NOMAD-1537 (`Alma Nocturna – Mejor Cállate`, job `25d076e5`),
not a brand-code allocation race. Two real defects and one policy gap were found:
1. **`redistribute_video` always crashes** on `complete → packaging`
(`video_worker_orchestrator.py:661`), so **every** public→private conversion silently
fails its private-side redistribution — the track is never archived to the
`Tracks-NonPublished` Dropbox and never gets a `NOMADNP` code. It looks fine to the
customer because downloads serve from GCS finals.
2. **`change_to_private` deletes first, rebuilds second, with no rollback**
(`visibility_change_service.py:74-114`): it deletes YouTube/Dropbox/GDrive + recycles
the public number, *then* calls the (always-failing) redistribution. Each failure also
**leaks a `NOMADNP` code** (allocated, never saved, never recycled — e.g. `NOMADNP-0214`).
3. **The gdrive-validator has no awareness of intentionally-vacated numbers.** Going-private
recycles the public number (kept behaviour — see Decisions). Between recycle and the next
public job reusing it, the number is legitimately absent from the public share, so the
daily validator fires a false "missing" alert. (Here, `e921ab26 / Luvcat – Spider` later
reused 1537, closing the gap ~5h after the alert.)
### Root-cause timeline (UTC 2026-08-18, confirmed from logs)
- `00:05:54–58` — public→private on `25d076e5`: deleted YouTube `TJUKJRyb5MQ`, Dropbox folder,
GDrive public-share files for 1537; recycled `NOMAD-1537`; cleared distribution state.
- `00:06:07` — allocated `NOMADNP-0214`, started distribution, crashed
`Invalid state transition … complete -> packaging`; redistribution aborted, **no rollback**.
- `01:00:11` — gdrive-validator daily run reports `CDG/MP4/MP4-720p: missing 1537` → the alert.
- `05:5x` — unrelated public job `e921ab26` (Luvcat – Spider) allocated the recycled `1537`
and published under it.
- `07:0x` — GCS/divebar mirror pulled `NOMAD-1537 - Luvcat - Spider.*` → gap closed.
Customer impact: **none** — `25d076e5` is a healthy private track (GCS-backed downloads work).
Internal impact: no `Tracks-NonPublished` archive / `NOMADNP` code for it; one leaked private
code; spurious operator alert.
## Decisions (from product owner, 2026-08-18)
- **Number policy: recycle & reuse (keep current).** A vacated public number returns to the
pool and the next public job fills it.
- **Validator: leave as-is — the transient gap warning is DESIRED.** Going-private is rare, the
gap fills naturally on the next public track, and the owner explicitly wants the alert even
in that case. → **Part E is dropped**; no change to `gdrive_validator/main.py` or
`check_public_share.py`. Do not add anything to static `KNOWN_GAPS` either.
- **Private archive: yes — fix redistribution.** Going-private must archive to
`Tracks-NonPublished` with a `NOMADNP` code, consistent with native-private jobs, and must
be atomic (public outputs removed only after the private archive succeeds).
Scope is therefore **A–D only** (fix + harden the redistribution path and recover the one
affected job); the alerting pipeline is intentionally untouched.
## Requirements
- [ ] **A.** `redistribute_video` runs org+distribution+notifications on a `complete` job
without an illegal status transition; job remains `complete` throughout.
- [ ] **B.** `change_to_private` is **distribute-then-delete**: private redistribution +
`NOMADNP` allocation succeed *before* public YouTube/Dropbox/GDrive deletion + public
number recycle. On any failure: no public deletion, no leaked private code, job stays
fully public and `complete`.
- [ ] **C.** No leaked `NOMADNP` codes: a private code allocated during a redistribution that
later fails is recycled (or not allocated until the success path).
- [ ] **D.** Recover `25d076e5` (create its NonPublished archive + `NOMADNP` code) and recycle
the leaked `NOMADNP-0214`.
- [ ] Regression tests for A, B, C. All existing `test_change_visibility.py` tests still pass.
- [ ] Validator and `KNOWN_GAPS` unchanged (transient going-private alert is desired).
**Out of scope (explicitly not doing):** ~~E — recycle-aware validator~~. The owner wants to keep
receiving the gap warning for going-private events; it self-resolves on the next public track.
## Technical Approach
### A. Fix the `complete → packaging` crash (proximate bug)
`redistribute_video` (`backend/workers/video_worker.py:481`) reuses
`VideoWorkerOrchestrator._run_organization/_run_distribution/_run_notifications`;
`_run_distribution` calls `self._update_progress(JobStatus.PACKAGING, 90, …)`
(`video_worker_orchestrator.py:661`), which invokes `JobManager.transition_status(...,
raise_on_invalid=True)`. From `complete` that's illegal (`models/job.py:193`:
`COMPLETE → [AWAITING_REVIEW, LYRICS_COMPLETE]`).
**Chosen fix:** add a `redistribute_mode: bool = False` flag to `OrchestratorConfig`
(or an `update_status: bool` param threaded to `_update_progress`). When set, `_update_progress`
updates the progress **percentage/message only** and **skips the status write**, leaving the job
`complete`. Rationale: a redistribution is not a lifecycle change; the job is and remains
complete. Avoids polluting `STATE_TRANSITIONS` with a `COMPLETE↔PACKAGING` round-trip that other
call sites could misuse.
- Guard: keep `raise_on_invalid=True` for the normal pipeline; the flag only bypasses the write.
- Verify no other stage in the redistribute-only path (`_run_organization`, `_run_distribution`,
`_run_notifications`) performs a status transition that assumes a fresh pipeline.
### B. Distribute-then-delete + rollback (`change_to_private`) — as implemented
1. **Capture the public output references** (`youtube_url`, `brand_code`, `gdrive_files`,
`dropbox_path`, artist/title) from the job snapshot *before* anything mutates state —
redistribution overwrites `state_data` with the new private values.
2. Set the guard flag **and** `is_private=True` up front (a *temporary* flag) so
`get_effective_distribution_for_job()` selects the private destination during redistribution.
No "changed to private" timeline event yet.
3. **Redistribute to the private destination** (`redistribute_video`): reuse GCS finals
(`keep_gcs_finals` stays true — never deleted for this path), upload to `Tracks-NonPublished`,
allocate `NOMADNP` code. Public outputs are still live at this point.
4. **If redistribution fails** (raises or returns False): revert `is_private=False`, clear the
guard flag, re-raise `RuntimeError("Redistribution failed …")`. No public output was touched,
and `redistribute_video` already recycled any `NOMADNP` code it allocated (C) — a failed
going-private is a clean no-op.
5. **On success**, the private archive exists and the move has committed — from here we do
**not** revert to public. Delete the *public* outputs (YouTube, public Dropbox folder, public
GDrive files) via `_delete_public_outputs` (best-effort, never raises) and **recycle the public
`NOMAD` number** — but only if every public deletion succeeded (else keep the number reserved
to avoid a future duplicate). Then record the "changed to private" timeline event and clear the
guard flag.
Note the YouTube deletion is irreversible, which is *why* it must be last — the old delete-first
order could never be safely rolled back. `redistribute_video` additionally verifies the archive
actually materialized (brand code allocated + Dropbox upload not failed) before returning success,
because the orchestrator swallows brand-code/Dropbox failures as warnings; without this a false
"success" would delete the public outputs against a non-existent private archive.
### C. No leaked private codes
Two options; prefer (i):
- (i) Allocate the `NOMADNP` code inside the redistribution success path only; if redistribution
fails before it is persisted, nothing to recycle. Where allocation already happens early
(orchestrator `_run_organization`), wrap the redistribute call so a failure recycles
`orchestrator.result.brand_code` if one was allocated.
- (ii) Always recycle `orchestrator.result.brand_code` in the `except` path of `change_to_private`.
### D. Recovery (operational, after A–C deployed)
- **`25d076e5`:** re-run the fixed private redistribution (finals + packages confirmed present in
`gs://…/jobs/25d076e5/{finals,packages}/`). Produces the NonPublished archive + `NOMADNP` code.
Use the admin re-distribute path or a one-off `redistribute_video('25d076e5')` invocation.
- **Leaked `NOMADNP-0214`:** recycle into `brand_code_counters/NOMADNP.recycled` (currently
`next_number=216, recycled=[215]`), or leave — private prefixes aren't validated. Recycle for
hygiene.
- No action needed on `NOMAD-1537` (already correctly reused by Luvcat, gap closed).
### E. (dropped)
Recycle-aware validator suppression is intentionally **not** implemented — see Decisions. The
transient going-private gap warning is desired and self-resolves on the next public track. The
post-job re-validation trigger (`video_worker_orchestrator.py:305`, gated on `gdrive_folder_id`)
is correct as-is for private conversions (no public folder to re-check).
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/workers/video_worker_orchestrator.py` | Modify | `redistribute_mode`/`update_status` flag; `_update_progress` skips status write when set |
| `backend/workers/video_worker.py` | Modify | `redistribute_video` passes the flag; recycle allocated code on failure |
| `backend/services/visibility_change_service.py` | Modify | Reorder `change_to_private` to distribute-then-delete; split `_delete_distributed_outputs`; recycle-on-failure |
| `backend/models/job.py` | Review | Confirm no `STATE_TRANSITIONS` change needed (preferred: none) |
| `backend/tests/test_change_visibility.py` | Modify | Real distribute-then-delete + rollback assertions (not just guard-flag) |
| `backend/tests/test_video_worker_redistribute.py` | Create | `redistribute_video` on `complete` job succeeds, no illegal transition |
| `docs/GDRIVE-VALIDATOR.md` | Modify | Add incident to History; note going-private is a legitimate (alerting) cause of gaps |
| `pyproject.toml` | Modify | Version bump |
## Testing Strategy
Follow `docs/TESTING.md`; backend unit/integration in `backend/tests/` (mock GCP), validator
unit in `infrastructure/functions/gdrive_validator/test_main.py`.
- **A:** `redistribute_video` on a `complete` job runs all three stages and does **not** raise
`InvalidStateTransitionError`; job status stays `complete`; brand_code/dropbox_link written.
- **B:** `change_to_private` — (a) success path: private redistribute called *before* any public
delete; public delete + public-code recycle happen only after; (b) failure path: redistribution
raises → **assert public YouTube/Dropbox/GDrive delete were NOT called**, `is_private` stays
False, guard flag cleared, exception re-raised. Strengthen the existing
`test_rollback_on_redistribute_failure` (today only checks the guard flag).
- **C:** redistribution failure → allocated `NOMADNP` code is recycled exactly once.
- **Regression:** full `test_change_visibility.py` + `test_brand_code_service.py` green.
- **Post-deploy (once):** re-run `python scripts/check_public_share.py` → clean; recover
`25d076e5` and confirm NonPublished archive + `NOMADNP` code appear.
## Recovery Runbook (D)
```python
# After A–C deployed. Recover the private archive for 25d076e5 (finals present in GCS).
from backend.workers.video_worker import redistribute_video
await redistribute_video("25d076e5") # job already is_private=True → NonPublished + NOMADNP
# Recycle the leaked private code
from backend.services.brand_code_service import get_brand_code_service
get_brand_code_service().recycle_brand_code("NOMADNP", 214)
```
## Open Questions
- [ ] Preferred A mechanism: config `redistribute_mode` flag vs. threading `update_status=False`
through `_update_progress`? (Leaning: config flag — single choke point.)
- [ ] For B, is it acceptable for the private `Tracks-NonPublished` archive to exist *simultaneously*
with the still-live public outputs for the few seconds before public deletion? (Expected: yes.)
## Rollback Plan
- Pure backend code; no schema changes, no infra/validator changes. Revert the PR to restore prior
behaviour.
- `redistribute_mode` is opt-in (only the redistribute path sets it); the normal pipeline is
unaffected, so A/B cannot regress fresh-job distribution.
- Recovery step (D) is idempotent-ish: re-running `redistribute_video` re-uploads from GCS finals;
safe to retry.
```
@@ -0,0 +1,94 @@
# Health-check alert noise + frontend graceful degradation (2026-08-22)
## Trigger
A "Karaoke Backend - Service Unavailable" uptime alert fired at 06:06 UTC on
2026-08-22 and auto-recovered ~1m41s later. Investigation of the noise, plus a
follow-on request to make the frontend degrade gracefully during such blips.
## Root cause of the alert
**A routine, platform-initiated Cloud Run instance recycle — not a crash.**
- The backend runs on `--min-instances 1` (a deliberate cost choice).
- At 06:01:53 UTC Cloud Run reaped the single warm instance (which had run ~9.6h
since the previous evening's deploy) and started a replacement
(`Reason: MANUAL_OR_CUSTOMER_MIN_INSTANCE`, then `AUTOSCALING`). The new
container's STARTUP probe passed ~06:03:13.
- During the ~80s gap (06:02:30–06:03:50) there was **no warm origin**, so
Cloudflare failed the health check from **all 6** uptime checker regions
simultaneously. Zero `/api/health` requests reached the origin in that window;
no `SIGTERM`/OOM/error was logged (platform reaps leave no teardown log).
- The uptime alert (reworked 2026-08-19 to page only when >1 checker location
fails) did its job — it caught a genuine, if brief, hard-down.
- A second, related failure mode was also observed (00:11–00:12 UTC): the single
instance's event loop stalled (orchestrating an encoding-worker fallback
cold-start with blocking timeouts), so health probes queued past the 10s
uptime timeout across regions, then flushed at once.
Blast radius of such a blip: ~80s of API unavailability. The **frontend still
loads** (static Cloudflare Pages export), **Cloud Run Jobs** (video renders) and
**GCE encoding-worker** executions already in flight **keep running**; only
backend-side orchestration is briefly paused and self-heals via Cloud
Tasks/Scheduler retries + the recover-stuck-jobs / retry-pending-render crons.
## Change 1 — soften the alert (server-side)
`infrastructure/modules/monitoring.py`: the "Service Unavailable" condition
`duration` 60s → **300s**. A sub-5-min self-healing recycle/stall no longer
pages; a sustained hard-down still fires (~5–6 min). The read-retry budget in the
frontend (`lib/backend-status.ts`) is aligned to the same ~10s escalation.
We deliberately did **not** raise `--min-instances` to 2 (cost choice). If real
outages ever slip through undetected, that is the cheaper-detection lever and it
removes both failure modes at the source.
## Change 2 — graceful degradation (frontend)
Goal: during a blip, retry transparently and show one reassuring app-wide message
instead of every screen throwing a generic error.
- **`lib/backend-status.ts`** — framework-agnostic connectivity store
(`online | reconnecting | unavailable`) + `useBackendStatus()`. **Status is
derived purely from how long the OLDEST in-flight tracked read has been
outstanding** (`beginRequest`/`endRequest`): `reconnecting` at
`STALL_RECONNECTING_MS` (10s), `unavailable` at `STALL_UNAVAILABLE_MS` (20s),
back to `online` the instant the stalled read settles.
- **`lib/api.ts` — `apiFetch`** wraps every backend call (drop-in for `fetch`;
internals use `globalThis.fetch`). Design decisions:
- **The banner keys on a genuine STALL, not slowness.** A read that completes —
even a normal-slow 3–5s one — surfaces nothing; only a read still outstanding
past 10s shows the hint. (The original 2.5s "slow-request" hint was too
trigger-happy — it fired during normal lyrics-review loads.)
- **Only GETs are tracked, and only GETs get a hard-timeout (45s) backstop.**
Long-running POSTs (preview video, generate, search, auto-correct) are
legitimately slow: they must never trip the banner nor be aborted mid-encode.
Callers can opt a slow read out with `opts.trackConnectivity: false`, or
time-box any request with `opts.timeoutMs`.
- **Retries GET only** (idempotent); **never auto-retries non-GET** (a replayed
create/submit/payment could double-charge). GETs retry within a ~2s budget,
then throw `BackendUnavailableError`.
- Transient = 502/503/504 + Cloudflare 520–524. Third-party hosts (GCS
signed-URL uploads) pass straight through untouched.
- **`components/backend-status-banner.tsx`** — the two UX states; mounted in
`app/[locale]/layout.tsx` so it covers all customer-facing surfaces (landing,
logged-in dashboard, review screens) with full i18n. `/admin/*` is intentionally
not covered (internal, English-only).
- **i18n** — `backendStatus` namespace added to `messages/en.json` and translated
to all 32 other locales.
### Copy (en)
> **We're having trouble reaching our servers**
> This is usually temporary — please try again in a couple of minutes.
> Any karaoke videos currently being created are unaffected and will keep processing.
## Tests
- `__tests__/backend-status.test.ts` — store transitions + timer escalation.
- `__tests__/api-fetch.test.ts` — GET retry→unavailable, transient-503 retry,
transparent recovery, non-GET no-retry, GCS passthrough, caller-abort passthrough.
- `lib/__tests__/api.test.ts` — updated `completeJobUpload` assertion (network
failure now maps to `BackendUnavailableError` preserving `.cause`).
- Banner verified visually (reconnecting + unavailable, en + es) via local dev.
- Full suite: 1129 passing.
+223
View File
@@ -0,0 +1,223 @@
/**
* @jest-environment jsdom
*
* Tests for apiFetch — the timeout + safe-retry wrapper that all backend calls go
* through (lib/api.ts). In jsdom the hostname is "localhost", so API_BASE_URL is ""
* and backend calls are addressed with relative "/api/..." URLs.
*/
import { apiFetch, BackendUnavailableError } from '@/lib/api'
import {
getBackendStatus,
STALL_RECONNECTING_MS,
STALL_UNAVAILABLE_MS,
} from '@/lib/backend-status'
function mockResponse(status: number, body: unknown = {}): Response {
return {
ok: status >= 200 && status < 300,
status,
json: async () => body,
} as unknown as Response
}
/** A fetch mock that returns a promise you resolve/reject by hand, so a request can
* be held "in flight" under fake timers and then settled to clean up. */
function deferredFetch() {
let settle!: (r: Response) => void
let fail!: (e: unknown) => void
const fn = jest.fn(
() =>
new Promise<Response>((res, rej) => {
settle = res
fail = rej
}),
)
return { fn, settle: (r: Response) => settle(r), fail: (e: unknown) => fail(e) }
}
describe('apiFetch', () => {
const fetchMock = jest.fn()
beforeEach(() => {
fetchMock.mockReset()
;(globalThis as unknown as { fetch: unknown }).fetch = fetchMock
})
afterEach(() => {
jest.useRealTimers()
})
it('returns the response and stays online on a fast successful GET', async () => {
fetchMock.mockResolvedValue(mockResponse(200, { ok: true }))
const res = await apiFetch('/api/jobs/abc')
expect(res.status).toBe(200)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('does NOT retry a deterministic 404 and stays online', async () => {
fetchMock.mockResolvedValue(mockResponse(404))
const res = await apiFetch('/api/jobs/missing')
expect(res.status).toBe(404)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('retries a GET on repeated network failure, then throws BackendUnavailableError', async () => {
jest.useFakeTimers()
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
const p = apiFetch('/api/jobs/abc')
const assertion = expect(p).rejects.toBeInstanceOf(BackendUnavailableError)
await jest.advanceTimersByTimeAsync(600)
await jest.advanceTimersByTimeAsync(1500)
await assertion
expect(fetchMock).toHaveBeenCalledTimes(3)
// A fast total failure (~2s) is NOT a stall, so the banner never appears.
expect(getBackendStatus()).toBe('online')
})
it('retries a GET that keeps returning a transient 503, then throws', async () => {
jest.useFakeTimers()
fetchMock.mockResolvedValue(mockResponse(503))
const p = apiFetch('/api/jobs/abc')
const assertion = expect(p).rejects.toBeInstanceOf(BackendUnavailableError)
await jest.advanceTimersByTimeAsync(600)
await jest.advanceTimersByTimeAsync(1500)
await assertion
expect(fetchMock).toHaveBeenCalledTimes(3)
expect(getBackendStatus()).toBe('online')
})
it('recovers transparently when a retried GET succeeds on a later attempt', async () => {
jest.useFakeTimers()
fetchMock
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockResolvedValueOnce(mockResponse(200, { ok: true }))
const p = apiFetch('/api/jobs/abc')
await jest.advanceTimersByTimeAsync(600)
const res = await p
expect(res.status).toBe(200)
expect(fetchMock).toHaveBeenCalledTimes(2)
expect(getBackendStatus()).toBe('online')
})
it('surfaces the banner only once a GET has STALLED past the thresholds, then clears', async () => {
jest.useFakeTimers()
const d = deferredFetch()
fetchMock.mockImplementation(d.fn)
const p = apiFetch('/api/jobs/abc')
p.catch(() => {}) // avoid unhandled rejection if it ever fails
expect(getBackendStatus()).toBe('online')
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('reconnecting')
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('unavailable')
d.settle(mockResponse(200, { ok: true }))
await p
expect(getBackendStatus()).toBe('online')
})
it('never surfaces the banner for a slow POST (mutations are not tracked)', async () => {
jest.useFakeTimers()
const d = deferredFetch()
fetchMock.mockImplementation(d.fn)
const p = apiFetch('/api/jobs/create-from-url', { method: 'POST', body: '{}' })
p.catch(() => {})
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 5000)
expect(getBackendStatus()).toBe('online')
d.settle(mockResponse(200, { ok: true }))
await p
})
it('does NOT impose a hard timeout on a long-running POST (e.g. preview render)', async () => {
jest.useFakeTimers()
let capturedSignal: AbortSignal | undefined
const d = deferredFetch()
fetchMock.mockImplementation((_url: unknown, init: RequestInit) => {
capturedSignal = init.signal ?? undefined
return d.fn()
})
const p = apiFetch('/api/review/abc/preview-video', { method: 'POST', body: '{}' })
p.catch(() => {})
// Well past the GET hard-timeout (45s): a POST must still be running, unaborted.
await jest.advanceTimersByTimeAsync(60_000)
expect(capturedSignal?.aborted).toBe(false)
d.settle(mockResponse(200, { ok: true }))
await expect(p).resolves.toBeDefined()
})
it('never auto-retries a non-GET, even on network failure', async () => {
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
await expect(
apiFetch('/api/jobs/create-from-url', { method: 'POST', body: '{}' }),
).rejects.toBeInstanceOf(BackendUnavailableError)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('reads method + signal from a Request input (a POST Request is not retried)', async () => {
// jsdom has no global Request; provide a minimal stand-in with the fields
// apiFetch reads (url/method/signal) so `input instanceof Request` engages.
class FakeRequest {
url: string
method: string
signal?: AbortSignal
constructor(url: string, init?: { method?: string; signal?: AbortSignal }) {
this.url = url
this.method = init?.method ?? 'GET'
this.signal = init?.signal
}
}
;(globalThis as unknown as { Request: unknown }).Request = FakeRequest
try {
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
const req = new FakeRequest('http://localhost/api/jobs/create-from-url', {
method: 'POST',
})
await expect(apiFetch(req as unknown as Request)).rejects.toBeInstanceOf(
BackendUnavailableError,
)
expect(fetchMock).toHaveBeenCalledTimes(1)
} finally {
delete (globalThis as unknown as { Request?: unknown }).Request
}
})
it('passes non-backend URLs (e.g. GCS uploads) straight through with the original error', async () => {
const gcsError = new TypeError('gcs unreachable')
fetchMock.mockRejectedValue(gcsError)
await expect(
apiFetch('https://storage.googleapis.com/bucket/obj', { method: 'PUT', body: 'x' }),
).rejects.toBe(gcsError)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('propagates a caller-initiated abort without surfacing the banner', async () => {
const abortErr = new DOMException('Aborted', 'AbortError')
fetchMock.mockRejectedValue(abortErr)
const controller = new AbortController()
controller.abort()
await expect(
apiFetch('/api/jobs/abc', { signal: controller.signal }),
).rejects.toBe(abortErr)
expect(getBackendStatus()).toBe('online')
})
})
+90
View File
@@ -0,0 +1,90 @@
/**
* @jest-environment jsdom
*
* Tests for the backend-connectivity status store (lib/backend-status.ts).
* Status is derived from how long the OLDEST in-flight tracked read has been
* outstanding — a read that completes promptly never surfaces the banner.
*/
import {
getBackendStatus,
beginRequest,
endRequest,
STALL_RECONNECTING_MS,
STALL_UNAVAILABLE_MS,
} from '@/lib/backend-status'
describe('backend-status store (stall-based)', () => {
let open: number[] = []
beforeEach(() => {
jest.useFakeTimers()
open = []
})
afterEach(() => {
// Settle anything still in flight so the module singleton resets to online.
open.forEach((id) => endRequest(id))
jest.clearAllTimers()
jest.useRealTimers()
})
it('starts online', () => {
expect(getBackendStatus()).toBe('online')
})
it('stays online while a read is young, then escalates as it stalls', async () => {
open.push(beginRequest())
expect(getBackendStatus()).toBe('online')
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS - 1000)
expect(getBackendStatus()).toBe('online')
await jest.advanceTimersByTimeAsync(1000) // cross the reconnecting threshold
expect(getBackendStatus()).toBe('reconnecting')
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('unavailable')
})
it('returns to online the moment the stalled read settles', async () => {
const id = beginRequest()
open.push(id)
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 100)
expect(getBackendStatus()).toBe('unavailable')
endRequest(id)
open = []
expect(getBackendStatus()).toBe('online')
})
it('a read that completes quickly never surfaces the banner', async () => {
const id = beginRequest()
await jest.advanceTimersByTimeAsync(3000) // 3s — normal-slow, not a stall
endRequest(id)
expect(getBackendStatus()).toBe('online')
// ...and nothing appears later either (nothing is in flight).
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS)
expect(getBackendStatus()).toBe('online')
})
it('tracks the OLDEST outstanding read, not the newest', async () => {
const a = beginRequest()
open.push(a)
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('reconnecting')
const b = beginRequest() // fresh read starts while `a` is still stalled
open.push(b)
expect(getBackendStatus()).toBe('reconnecting')
endRequest(b) // settling the young one doesn't clear the old stall
open = [a]
expect(getBackendStatus()).toBe('reconnecting')
endRequest(a)
open = []
expect(getBackendStatus()).toBe('online')
})
})
@@ -0,0 +1,93 @@
import { render, screen, waitFor } from '@testing-library/react'
import { SystemStatusModal } from '@/components/system-status-modal'
import type { SystemStatus } from '@/lib/api'
// Mock the API layer so the modal renders against controlled status payloads.
const getSystemStatus = jest.fn()
jest.mock('@/lib/api', () => ({
api: {
getSystemStatus: () => getSystemStatus(),
},
}))
function baseStatus(overrides: Partial<SystemStatus['services']> = {}): SystemStatus {
return {
services: {
frontend: { status: 'ok', version: '0.196.3' },
backend: { status: 'ok', version: '0.196.3' },
encoder: { status: 'ok', version: '0.196.3' },
flacfetch: { status: 'ok', version: '0.21.1' },
separator: { status: 'offline' },
...overrides,
},
}
}
describe('SystemStatusModal', () => {
beforeEach(() => {
getSystemStatus.mockReset()
})
it('shows the live encoding worker instance type on the primary (no fallback)', async () => {
getSystemStatus.mockResolvedValue(
baseStatus({
encoder: {
status: 'ok',
version: '0.196.3',
admin_details: {
primary_vm: 'encoding-worker-a',
active_vm: 'encoding-worker-a',
active_zone: 'us-central1-c',
active_machine_type: 'c4d-highcpu-32',
on_fallback: false,
},
},
}),
)
render(<SystemStatusModal open onClose={() => {}} />)
// Instance type + serving VM are surfaced for the live worker.
expect(await screen.findByText('c4d-highcpu-32')).toBeInTheDocument()
expect(screen.getByText(/encoding-worker-a · us-central1-c/)).toBeInTheDocument()
// No fallback badge/notice when serving the primary.
expect(screen.queryByText('Fallback')).not.toBeInTheDocument()
})
it('flags a capacity fallback with the fallback badge and notice', async () => {
getSystemStatus.mockResolvedValue(
baseStatus({
encoder: {
status: 'ok',
version: '0.196.3',
admin_details: {
primary_vm: 'encoding-worker-a',
active_vm: 'encoding-worker-fallback-n2c',
active_zone: 'us-central1-a',
active_machine_type: 'n2-highcpu-32',
on_fallback: true,
},
},
}),
)
render(<SystemStatusModal open onClose={() => {}} />)
expect(await screen.findByText('n2-highcpu-32')).toBeInTheDocument()
expect(screen.getByText('Fallback')).toBeInTheDocument()
expect(
screen.getByText(/Primary capacity unavailable/i),
).toBeInTheDocument()
})
it('omits the live-worker section for non-admins (no admin_details)', async () => {
getSystemStatus.mockResolvedValue(baseStatus())
render(<SystemStatusModal open onClose={() => {}} />)
// Encoder card still renders, but there is no live-worker detail.
await waitFor(() => expect(getSystemStatus).toHaveBeenCalled())
expect(screen.queryByText('Live worker:')).not.toBeInTheDocument()
expect(screen.queryByText('Fallback')).not.toBeInTheDocument()
})
})
+34 -7
View File
@@ -131,13 +131,25 @@ describe('TenantJobFlow — error handling', () => {
jest.clearAllMocks()
})
// Mirrors handleSubmit's catch mapping in TenantJobFlow.tsx, using the en
// jobFlow strings that t('submitError') / t('submitNetworkError') resolve to.
const SUBMIT_ERROR = 'Something went wrong. Please try again.'
const SUBMIT_NETWORK_ERROR = 'Network error — please check your connection and try again.'
function mapSubmitError(err: any): string {
const { ApiError } = require('@/lib/api')
if (err instanceof ApiError) return err.message
if (err instanceof TypeError || /network|failed to fetch|load failed/i.test(String(err?.message ?? ''))) {
return SUBMIT_NETWORK_ERROR
}
return SUBMIT_ERROR
}
it('ApiError message is surfaced when createJobWithUploadUrls fails', async () => {
const { ApiError } = require('@/lib/api')
mockApi.createJobWithUploadUrls.mockRejectedValue(
new ApiError('Tenant file upload is not enabled', 403),
)
// Simulate handleSubmit error path
let errorMessage = ''
try {
await api.createJobWithUploadUrls('Artist', 'Title', [], {
@@ -145,16 +157,15 @@ describe('TenantJobFlow — error handling', () => {
existing_instrumental: true,
})
} catch (err: any) {
errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'
errorMessage = mapSubmitError(err)
}
expect(errorMessage).toBe('Tenant file upload is not enabled')
})
it('generic errors get fallback message', async () => {
mockApi.createJobWithUploadUrls.mockRejectedValue(new TypeError('Network error'))
it('network-level failures map to the network error message', async () => {
mockApi.createJobWithUploadUrls.mockRejectedValue(new TypeError('Failed to fetch'))
const { ApiError } = require('@/lib/api')
let errorMessage = ''
try {
await api.createJobWithUploadUrls('Artist', 'Title', [], {
@@ -162,10 +173,26 @@ describe('TenantJobFlow — error handling', () => {
existing_instrumental: true,
})
} catch (err: any) {
errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'
errorMessage = mapSubmitError(err)
}
expect(errorMessage).toBe('Something went wrong. Please try again.')
expect(errorMessage).toBe(SUBMIT_NETWORK_ERROR)
})
it('non-network, non-ApiError failures get the generic fallback message', async () => {
mockApi.createJobWithUploadUrls.mockRejectedValue(new Error('boom'))
let errorMessage = ''
try {
await api.createJobWithUploadUrls('Artist', 'Title', [], {
is_private: true,
existing_instrumental: true,
})
} catch (err: any) {
errorMessage = mapSubmitError(err)
}
expect(errorMessage).toBe(SUBMIT_ERROR)
})
it('missing upload URL throws ApiError', async () => {
+2
View File
@@ -5,6 +5,7 @@ import { hasLocale } from 'next-intl';
import { notFound } from 'next/navigation';
import { routing } from '@/i18n/routing';
import { ReferralCapture } from '@/components/ReferralCapture';
import { BackendStatusBanner } from '@/components/backend-status-banner';
export function generateStaticParams() {
return routing.locales.map((locale) => ({ locale }));
@@ -37,6 +38,7 @@ export default async function LocaleLayout({
<Suspense fallback={null}>
<ReferralCapture />
</Suspense>
<BackendStatusBanner />
{children}
</NextIntlClientProvider>
);
@@ -0,0 +1,88 @@
"use client"
import { useEffect, useState } from "react"
import { useTranslations } from "next-intl"
import { Loader2, CloudOff, X } from "lucide-react"
import {
useBackendStatus,
__installBackendStatusDevHook,
} from "@/lib/backend-status"
/**
* App-wide, non-blocking banner that reacts to backend connectivity (see
* lib/backend-status.ts). During a brief origin blip — e.g. Cloud Run recycling its
* single min-instance — the API is momentarily unreachable even though nothing is
* broken and any in-flight karaoke renders keep running. Rather than every screen
* showing its own scary error, this shows a single reassuring message:
*
* - "reconnecting": a subtle pill with a spinner while we transparently retry.
* - "unavailable": a gentle card explaining it's temporary and that ongoing jobs
* are unaffected, once trouble persists past the threshold.
*
* It floats over content (no layout shift) and disappears the instant connectivity
* is restored.
*/
export function BackendStatusBanner() {
const status = useBackendStatus()
const t = useTranslations("backendStatus")
const [dismissed, setDismissed] = useState(false)
// Expose the dev/preview trigger (window.__nkBackendStatus) for manual UX review.
useEffect(() => {
__installBackendStatusDevHook()
}, [])
// Re-arm the dismiss so a *later* outage episode shows again.
useEffect(() => {
if (status === "online") setDismissed(false)
}, [status])
if (status === "online") return null
if (status === "reconnecting") {
return (
<div
className="fixed top-3 left-1/2 z-[60] -translate-x-1/2 pointer-events-none"
role="status"
aria-live="polite"
>
<div className="flex items-center gap-2 rounded-full border border-amber-500/30 bg-amber-950/80 px-3.5 py-1.5 text-xs text-amber-200 shadow-lg backdrop-blur">
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" />
<span>{t("reconnecting")}</span>
</div>
</div>
)
}
// status === "unavailable"
if (dismissed) return null
return (
<div
className="fixed top-3 left-1/2 z-[60] w-[calc(100%-1.5rem)] max-w-md -translate-x-1/2"
role="alert"
aria-live="assertive"
>
<div className="relative rounded-xl border border-amber-500/40 bg-amber-950/90 px-4 py-3 pr-9 text-amber-100 shadow-2xl backdrop-blur">
<button
type="button"
onClick={() => setDismissed(true)}
aria-label={t("dismiss")}
className="absolute right-2 top-2 rounded-md p-1 text-amber-300/70 transition-colors hover:bg-amber-800/50 hover:text-amber-100"
>
<X className="h-4 w-4" />
</button>
<div className="flex items-start gap-3">
<CloudOff className="mt-0.5 h-5 w-5 shrink-0 text-amber-300" />
<div className="space-y-1">
<p className="text-sm font-semibold text-amber-50">{t("unavailable.title")}</p>
<p className="text-xs leading-relaxed text-amber-200/90">{t("unavailable.body")}</p>
<p className="text-xs leading-relaxed text-amber-200/70">
{t("unavailable.reassurance")}
</p>
</div>
</div>
</div>
</div>
)
}
+15 -3
View File
@@ -119,9 +119,21 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
setPhase("done")
onJobCreated()
} catch (err: any) {
const message = err instanceof ApiError
? err.message
: "Something went wrong. Please try again."
// Surface the real cause for debugging — the generic user-facing string
// below hides which step failed (create / upload / complete).
console.error("[TenantJobFlow] submit failed:", err)
let message: string
if (err instanceof ApiError) {
message = err.message
} else if (
err instanceof TypeError ||
/network|failed to fetch|load failed/i.test(String(err?.message ?? ""))
) {
// fetch()/XHR network-level failure (offline, connection reset, CORS).
message = t('submitNetworkError')
} else {
message = t('submitError')
}
setError(message)
setPhase("idle")
setUploadProgress(0)
+40 -6
View File
@@ -59,7 +59,7 @@ function ServiceCard({
className="rounded-lg border p-4"
style={{
borderColor: "var(--card-border)",
backgroundColor: "var(--card-bg)",
backgroundColor: "var(--card)",
}}
>
<div className="flex items-center justify-between mb-1">
@@ -106,6 +106,38 @@ function ServiceCard({
);
}
function LiveWorkerSection({ details }: { details: NonNullable<ServiceStatus["admin_details"]> }) {
const t = useTranslations('status');
return (
<div className="mt-2 text-xs">
<div className="flex items-center gap-1.5 flex-wrap">
<span className="opacity-60">{t('liveWorker')}:</span>
<span className="font-mono font-medium">{details.active_machine_type}</span>
{details.on_fallback && (
<span
className="rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-amber-400"
style={{ backgroundColor: "rgba(251,191,36,0.12)" }}
>
{t('fallbackBadge')}
</span>
)}
</div>
{details.active_vm && (
<div className="mt-0.5 font-mono opacity-50">
{details.active_vm}
{details.active_zone ? ` · ${details.active_zone}` : ""}
</div>
)}
{details.on_fallback && (
<div className="mt-1 opacity-50 text-[10px] leading-snug">
{t('fallbackNote')}
</div>
)}
</div>
);
}
function BlueGreenSection({ details }: { details: NonNullable<ServiceStatus["admin_details"]> }) {
const t = useTranslations('status');
const [expanded, setExpanded] = useState(false);
@@ -216,7 +248,7 @@ export function SystemStatusModal({ open, onClose }: SystemStatusModalProps) {
return (
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
<DialogContent className="sm:max-w-lg" style={{ backgroundColor: "var(--card-bg)", borderColor: "var(--card-border)" }}>
<DialogContent className="sm:max-w-lg" style={{ backgroundColor: "var(--bg)", borderColor: "var(--card-border)" }}>
<DialogHeader>
<DialogTitle className="text-foreground">{t('systemStatus')}</DialogTitle>
</DialogHeader>
@@ -234,10 +266,12 @@ export function SystemStatusModal({ open, onClose }: SystemStatusModalProps) {
<ServiceCard name={t('frontend')} service={frontendService} />
<ServiceCard name={t('backend')} service={services.backend} />
<ServiceCard name={t('encoder')} service={services.encoder}>
{services.encoder.admin_details &&
services.encoder.admin_details.primary_vm && (
<BlueGreenSection details={services.encoder.admin_details} />
)}
{services.encoder.admin_details?.active_machine_type && (
<LiveWorkerSection details={services.encoder.admin_details} />
)}
{services.encoder.admin_details?.primary_vm && (
<BlueGreenSection details={services.encoder.admin_details} />
)}
</ServiceCard>
<ServiceCard name={t('flacfetch')} service={services.flacfetch} />
<ServiceCard name={t('separator')} service={services.separator} />
+175 -81
View File
@@ -1,15 +1,28 @@
// frontend/e2e/helpers/stripe-checkout.ts
import { Page } from '@playwright/test';
import { Page, Frame, Locator } from '@playwright/test';
/**
* Automate Stripe's hosted checkout page (checkout.stripe.com).
*
* Stripe Checkout (as of April 2026) shows:
* - "Pay with Link" / "Pay with Klarna" buttons at top
* - Payment method radio buttons: Card, Cash App Pay, Klarna, Bank
* - Clicking "Card" reveals card input fields (number, expiry, CVC)
* - Card fields are inside iframes within the page
* - A "Pay" button at the bottom
* ⚠️ Stripe changes this page's structure without notice — likely A/B testing
* or staged rollouts, so BOTH the old and new layouts can appear on any given
* day (and can flip back). We have observed at least three variants:
* 1. Multi-method accordion of *radios* (Card / Cash App / Klarna / Bank),
* card fields inside iframes, Pay button in the top frame. (Apr 2026)
* 2. Single method (Card only): card fields render as *direct* textboxes in
* the top document, no chooser at all. (#916, Aug 17)
* 3. Multi-method Payment Element where the chooser is *buttons* (not radios)
* and the whole element — chooser, card fields AND the "Pay" button — is
* rendered inside a nested same-origin iframe. (Aug 19-20)
*
* DO NOT narrow this helper to a single layout — it must tolerate all of the
* above. It does so by being layout-agnostic:
* - `page.getByRole(...)` only sees the top frame, so we search EVERY frame
* (top + nested iframes) for each element via `locateVisibleInFrames`.
* - The "Card" chooser is matched as a radio OR a button.
* - Card fields are matched whether direct inputs or iframe-nested.
* If Stripe introduces yet another layout, extend the locators here rather than
* assuming a single shape.
*
* Environment variables:
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY,
@@ -38,6 +51,32 @@ function getCardDetailsFromEnv(): CardDetails {
return { number, expiry, cvc, name };
}
/**
* Poll every frame (top document + nested iframes) for the first locator that
* is visible, returning it (or null on timeout). Playwright's Page-level
* locators only see the top frame; Stripe's Payment Element lives in a nested
* iframe, so we must look frame-by-frame.
*/
async function locateVisibleInFrames(
page: Page,
make: (frame: Frame) => Locator,
timeout = 30_000
): Promise<Locator | null> {
const deadline = Date.now() + timeout;
do {
for (const frame of page.frames()) {
if (frame.isDetached()) continue;
const loc = make(frame).first();
// isVisible() rejects if the frame detaches mid-check — treat as "not here".
if (await loc.isVisible({ timeout: 1_000 }).catch(() => false)) {
return loc;
}
}
await page.waitForTimeout(300);
} while (Date.now() < deadline);
return null;
}
/**
* Complete the Stripe Checkout page with card details from environment.
*
@@ -50,75 +89,128 @@ export async function completeStripeCheckout(page: Page): Promise<void> {
// Step 1: Wait for Stripe Checkout page to fully load
console.log(' Waiting for Stripe Checkout page...');
await page.waitForURL(/checkout\.stripe\.com/, { timeout: 30_000 });
// Wait for the page to be fully interactive — look for the "Pay" button
// which is one of the last elements to render
await page.getByRole('button', { name: /^Pay$/i }).waitFor({
state: 'visible',
timeout: 30_000,
});
// The "Pay" button is one of the last elements to render and confirms the
// Payment Element is interactive. It may be in the top frame (single-method
// layout) or a nested iframe (multi-method layout). Match it exactly so the
// "Pay with Link" / "Pay with Klarna" express buttons don't shadow it.
const payButton = await locateVisibleInFrames(
page,
(f) => f.getByRole('button', { name: /^Pay$/i }),
30_000
);
if (!payButton) {
await page.screenshot({ path: 'test-results/stripe-no-pay-button.png' });
throw new Error('Stripe "Pay" button not visible in any frame after 30s');
}
await page.screenshot({ path: 'test-results/stripe-checkout-loaded.png' });
console.log(' Stripe Checkout loaded');
// Step 2: Select "Card" payment method
// Stripe uses an accordion with radio buttons overlaid by buttons.
// Use force:true to bypass the overlay interception.
// Step 2: Ensure the card fields are shown. In the single-method layout they
// are already visible; in the multi-method accordion we must expand "Card"
// (rendered as a button or radio depending on Stripe's variant).
console.log(' Selecting Card payment method...');
const cardRadio = page.getByRole('radio', { name: 'Card' });
await cardRadio.check({ force: true, timeout: 10_000 });
console.log(' Card payment method selected');
let cardNumberField = await locateVisibleInFrames(
page,
(f) => cardFieldLocator(f, 'cardNumber'),
5_000
);
// Wait for card input fields to appear after selecting Card
// Stripe renders card fields inside iframes after the radio is clicked
await page.waitForTimeout(2000);
if (cardNumberField) {
console.log(' Card fields already visible — no chooser to expand');
} else {
const cardChoice = await locateVisibleInFrames(
page,
(f) =>
f
.getByRole('radio', { name: /^Card$/i })
.or(f.getByRole('button', { name: /^Card$/i })),
5_000
);
if (cardChoice) {
// force:true bypasses any overlay/accordion animation intercepting clicks.
await cardChoice.click({ force: true }).catch(() => {});
console.log(' Card payment method selected');
} else {
console.log(' No Card chooser found — waiting for card fields to render...');
}
cardNumberField = await locateVisibleInFrames(
page,
(f) => cardFieldLocator(f, 'cardNumber'),
15_000
);
if (!cardNumberField) {
console.log(' WARNING: card number field not visible after selecting Card');
}
}
await page.waitForTimeout(1000);
await page.screenshot({ path: 'test-results/stripe-card-selected.png' });
// Step 3: Fill card number
// After clicking "Card", Stripe shows card input fields.
// These may be direct inputs (#cardNumber) or inside iframes.
// Step 3-5: Fill card number, expiry, CVC
console.log(' Filling card number...');
await fillCardField(page, 'cardNumber', card.number);
// Step 4: Fill expiry
console.log(' Filling card expiry...');
await fillCardField(page, 'cardExpiry', card.expiry);
// Step 5: Fill CVC
console.log(' Filling CVC...');
await fillCardField(page, 'cardCvc', card.cvc);
// Step 6: Fill cardholder name if field exists
// Step 6: Fill cardholder name if the field exists (any frame)
if (card.name) {
const nameInput = page.locator('#billingName, input[name="billingName"]');
if (await nameInput.isVisible({ timeout: 2000 }).catch(() => false)) {
const nameInput = await locateVisibleInFrames(
page,
(f) =>
f
.locator('#billingName, input[name="billingName"], input[placeholder="Full name on card"]')
.or(f.getByRole('textbox', { name: /cardholder name/i })),
2_000
);
if (nameInput) {
console.log(' Filling cardholder name...');
await nameInput.fill(card.name);
}
}
// Step 6b: Fill ZIP code (required for US cards)
const zipInput = page.locator('#billingPostalCode, input[name="billingPostalCode"], input[placeholder="ZIP"]');
if (await zipInput.isVisible({ timeout: 2000 }).catch(() => false)) {
// Step 6b: Fill ZIP code (required for US cards) — search any frame
const zipInput = await locateVisibleInFrames(
page,
(f) =>
f
.locator('#billingPostalCode, input[name="billingPostalCode"], input[placeholder="ZIP"]')
.or(f.getByRole('textbox', { name: /^zip$|postal code/i })),
2_000
);
if (zipInput) {
console.log(' Filling ZIP code...');
await zipInput.fill(process.env.E2E_STRIPE_ZIP || '10001');
}
// Step 6c: Uncheck "Save my information" to avoid phone number requirement
const saveCheckbox = page.getByRole('checkbox', { name: /save my information/i });
if (await saveCheckbox.isVisible({ timeout: 2000 }).catch(() => false)) {
if (await saveCheckbox.isChecked()) {
console.log(' Unchecking "Save my information"...');
await saveCheckbox.uncheck({ force: true });
}
// Step 6c: Uncheck "Save my information" to avoid a phone-number requirement
const saveCheckbox = await locateVisibleInFrames(
page,
(f) => f.getByRole('checkbox', { name: /save my information/i }),
2_000
);
if (saveCheckbox && (await saveCheckbox.isChecked().catch(() => false))) {
console.log(' Unchecking "Save my information"...');
await saveCheckbox.uncheck({ force: true }).catch(() => {});
}
await page.screenshot({ path: 'test-results/stripe-checkout-filled.png' });
console.log(' Card details filled');
// Step 7: Click "Pay" button
// Step 7: Click "Pay" button (re-locate in case the frame re-rendered)
console.log(' Clicking Pay button...');
const payButton = page.getByRole('button', { name: /^Pay$/i });
await payButton.waitFor({ state: 'visible', timeout: 10_000 });
await payButton.click();
const finalPay = await locateVisibleInFrames(
page,
(f) => f.getByRole('button', { name: /^Pay$/i }),
10_000
);
if (!finalPay) {
await page.screenshot({ path: 'test-results/stripe-no-pay-button-final.png' });
throw new Error('Stripe "Pay" button not visible when ready to submit');
}
await finalPay.click();
console.log(' Payment submitted, waiting for redirect...');
// Wait for redirect back to our site
@@ -130,42 +222,44 @@ export async function completeStripeCheckout(page: Page): Promise<void> {
}
/**
* Fill a card field by name. Tries direct input first, then iframe-based.
*
* Stripe Checkout card fields use IDs like #cardNumber, #cardExpiry, #cardCvc
* when rendered as direct inputs, or are inside iframes when using Elements.
* Accessible-name and placeholder metadata for each Stripe card field, used to
* build robust locators that work whether Stripe renders the field as a direct
* input (single-payment-method layout) or inside an iframe.
*/
const CARD_FIELD_META: Record<string, { name: RegExp; placeholder?: string }> = {
cardNumber: { name: /card number/i, placeholder: '1234 1234 1234 1234' },
cardExpiry: { name: /expiration|expiry/i, placeholder: 'MM / YY' },
cardCvc: { name: /^cvc$|security code/i },
};
/**
* Locator for a Stripe card field within a given frame. Matches by Stripe's
* stable field-name attribute, element id, input name, placeholder, or
* accessible name — whichever the current Checkout layout uses.
*/
function cardFieldLocator(frame: Frame, fieldName: string): Locator {
const meta = CARD_FIELD_META[fieldName];
const selectors = [
`[data-elements-stable-field-name="${fieldName}"]`,
`#${fieldName}`,
`input[name="${fieldName}"]`,
];
if (meta?.placeholder) selectors.push(`input[placeholder="${meta.placeholder}"]`);
let loc = frame.locator(selectors.join(', '));
if (meta) loc = loc.or(frame.getByRole('textbox', { name: meta.name }));
return loc.first();
}
/**
* Fill a card field by name, searching every frame (top document + nested
* iframes). Stripe renders card fields either as direct inputs (single-payment-
* method layout) or inside the Payment Element iframe (multi-method layout).
*/
async function fillCardField(page: Page, fieldName: string, value: string): Promise<void> {
// Try 1: Direct input by ID
const directInput = page.locator(`#${fieldName}`);
if (await directInput.isVisible({ timeout: 3000 }).catch(() => false)) {
await directInput.click();
await directInput.type(value, { delay: 50 });
return;
const input = await locateVisibleInFrames(page, (f) => cardFieldLocator(f, fieldName), 15_000);
if (!input) {
throw new Error(`Could not find card field: ${fieldName} in any frame`);
}
// Try 2: Direct input by data attribute
const dataInput = page.locator(`[data-elements-stable-field-name="${fieldName}"]`);
if (await dataInput.isVisible({ timeout: 2000 }).catch(() => false)) {
await dataInput.click();
await dataInput.type(value, { delay: 50 });
return;
}
// Try 3: Input inside an iframe (Stripe Elements)
// Find all iframes and try each one for the card input
const iframes = page.locator('iframe');
const iframeCount = await iframes.count();
for (let i = 0; i < iframeCount; i++) {
const frame = iframes.nth(i).contentFrame();
// Look for inputs inside this iframe
const input = frame.locator(`input[name="${fieldName}"], input[autocomplete*="cc"]`).first();
if (await input.isVisible({ timeout: 1000 }).catch(() => false)) {
await input.type(value, { delay: 50 });
console.log(` Found ${fieldName} in iframe ${i}`);
return;
}
}
throw new Error(`Could not find card field: ${fieldName} (tried direct input, data attribute, and ${iframeCount} iframes)`);
await input.click();
await input.type(value, { delay: 50 });
}
+43 -1
View File
@@ -2,7 +2,7 @@
* Tests for API client
*/
import { api, ApiError, extractErrorMessage } from "../api"
import { api, ApiError, BackendUnavailableError, extractErrorMessage } from "../api"
// Mock fetch globally
global.fetch = jest.fn()
@@ -293,6 +293,48 @@ describe("API Client", () => {
const body = JSON.parse(call[1].body)
expect(body.uploaded_files).toEqual(["audio"])
})
it("retries on a transient network failure and then succeeds", async () => {
const mockResponse = { status: "success", message: "Processing started" }
;(global.fetch as jest.Mock)
.mockRejectedValueOnce(new TypeError("Failed to fetch"))
.mockResolvedValueOnce({ ok: true, json: async () => mockResponse })
const result = await api.completeJobUpload("job-789", ["audio"])
expect(result).toEqual(mockResponse)
expect(global.fetch).toHaveBeenCalledTimes(2)
})
it("gives up after 3 network failures with BackendUnavailableError (preserving the cause)", async () => {
const networkError = new TypeError("Failed to fetch")
;(global.fetch as jest.Mock).mockRejectedValue(networkError)
// apiFetch maps a network-level failure to a typed BackendUnavailableError
// (which drives the app-wide connectivity banner) while keeping the original
// error as `.cause`, so nothing is silently swallowed.
const err = await api
.completeJobUpload("job-789", ["audio"])
.catch((e) => e)
expect(err).toBeInstanceOf(BackendUnavailableError)
expect(err.cause).toBe(networkError)
expect(global.fetch).toHaveBeenCalledTimes(3)
})
it("does NOT retry on an HTTP error response (deterministic)", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: false,
status: 400,
json: async () => ({ detail: "Job is not in pending state" }),
})
await expect(api.completeJobUpload("job-789", ["audio"])).rejects.toBeInstanceOf(
ApiError
)
// A 4xx is not a transient failure — it must not be retried.
expect(global.fetch).toHaveBeenCalledTimes(1)
})
})
describe("uploadJobSmart", () => {
+389 -172
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -9,6 +9,7 @@
* flows through the existing corrections/complete paths.
*/
import type { LyricsSegment, ReferenceSource } from '@/lib/lyrics-review/types'
import { apiFetch } from '@/lib/api'
const API_BASE =
process.env.NEXT_PUBLIC_API_BASE ?? 'https://api.nomadkaraoke.com'
@@ -100,7 +101,7 @@ export async function fetchAutoCorrectSuggestions(
}
if (token) headers.Authorization = `Bearer ${token}`
const response = await fetch(
const response = await apiFetch(
`${API_BASE}/api/review/${encodeURIComponent(jobId)}/auto-correct`,
{
method: 'POST',
+3 -1
View File
@@ -7,6 +7,8 @@
* preview. Persistence still flows through the existing replace-segments
* Save path.
*/
import { apiFetch } from '@/lib/api'
const API_BASE =
process.env.NEXT_PUBLIC_API_BASE ?? 'https://api.nomadkaraoke.com'
@@ -95,7 +97,7 @@ export async function generateCustomLyrics(
const headers: Record<string, string> = {}
if (token) headers.Authorization = `Bearer ${token}`
const response = await fetch(
const response = await apiFetch(
`${API_BASE}/api/review/${encodeURIComponent(jobId)}/custom-lyrics/generate`,
{ method: 'POST', body: form, headers, signal },
)
+144
View File
@@ -0,0 +1,144 @@
'use client'
/**
* Global backend-connectivity status.
*
* The backend runs on Cloud Run with `--min-instances 1`. When Cloud Run recycles
* that single instance (routine host maintenance / instance max-lifetime), there is
* a brief window where the origin is unreachable and requests HANG (Cloud Run holds
* them during the cold start) even though nothing is actually broken — and any
* karaoke jobs already rendering keep running untouched.
*
* We want ONE reassuring app-wide banner during those blips, but only when there's
* real evidence of a problem — NOT merely because a request was a little slow. So
* status is derived purely from **how long the oldest in-flight backend GET has been
* outstanding**: a read that completes (even a slowish 3–5s one) shows nothing; only
* a read stalled past STALL_RECONNECTING_MS surfaces the hint, escalating past
* STALL_UNAVAILABLE_MS to the full message. This matches "only tell the user once
* something has genuinely been trying to load for >10s / timed out."
*
* Only GETs are tracked: reads are what a page waits on during a recycle, and long
* POSTs (search, generate, auto-correct) are legitimately slow and must never trip
* the banner. See lib/api.ts (apiFetch) for the begin/endRequest wiring.
*/
import { useSyncExternalStore } from 'react'
export type BackendStatus =
/** No stalled reads — everything is completing in a reasonable time. */
| 'online'
/** A read has been outstanding a while; show a subtle "reconnecting" hint. */
| 'reconnecting'
/** A read has been stalled long enough to show the full "temporarily unavailable". */
| 'unavailable'
/** A tracked read must be outstanding at least this long before we show ANYTHING —
* so a normal slow-but-successful load never surfaces the banner. */
export const STALL_RECONNECTING_MS = 10_000
/** ...and this long before we escalate to the full assertive message. */
export const STALL_UNAVAILABLE_MS = 20_000
let nextId = 1
/** id -> startedAt (ms) for every tracked backend GET currently in flight. */
const inFlight = new Map<number, number>()
/** Dev/preview override: when non-null, forces the reported status. */
let devOverride: BackendStatus | null = null
let status: BackendStatus = 'online'
let ticker: ReturnType<typeof setInterval> | null = null
const listeners = new Set<() => void>()
function emit() {
listeners.forEach((l) => l())
}
function setStatus(next: BackendStatus) {
if (status === next) return
status = next
emit()
}
function computeFromStalls(): BackendStatus {
if (inFlight.size === 0) return 'online'
let oldest = Infinity
for (const startedAt of inFlight.values()) {
if (startedAt < oldest) oldest = startedAt
}
const age = Date.now() - oldest
if (age >= STALL_UNAVAILABLE_MS) return 'unavailable'
if (age >= STALL_RECONNECTING_MS) return 'reconnecting'
return 'online'
}
function recompute() {
setStatus(devOverride ?? computeFromStalls())
// Stop the clock once nothing is outstanding (and no dev override needs it).
if (inFlight.size === 0 && devOverride === null && ticker) {
clearInterval(ticker)
ticker = null
}
}
function ensureTicker() {
if (ticker) return
// Re-evaluate every second so a request that keeps hanging escalates over time.
ticker = setInterval(recompute, 1000)
}
/**
* Mark a tracked backend read as started. Returns an id to pass to `endRequest` when
* it settles (success OR failure — either way it's no longer outstanding).
*/
export function beginRequest(): number {
const id = nextId++
inFlight.set(id, Date.now())
ensureTicker()
recompute()
return id
}
/** Mark a tracked read as settled. */
export function endRequest(id: number): void {
if (inFlight.delete(id)) recompute()
}
export function getBackendStatus(): BackendStatus {
return status
}
function subscribe(listener: () => void): () => void {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
/**
* React hook: subscribe to the current backend connectivity status. Server render
* always yields "online" so the banner never appears in the static HTML.
*/
export function useBackendStatus(): BackendStatus {
return useSyncExternalStore(subscribe, getBackendStatus, () => 'online')
}
/**
* Dev/preview-only escape hatch so the outage UX can be demoed without waiting on a
* real stall. Exposed on `window.__nkBackendStatus` and no-ops on the production
* consumer host. Not referenced by app code paths.
*/
export function __installBackendStatusDevHook() {
if (typeof window === 'undefined') return
if (window.location.hostname === 'gen.nomadkaraoke.com') return
const simulate = (s: BackendStatus | null) => {
devOverride = s
if (s !== null) ensureTicker()
recompute()
}
;(window as unknown as { __nkBackendStatus?: unknown }).__nkBackendStatus = {
reconnecting: () => simulate('reconnecting'),
unavailable: () => simulate('unavailable'),
online: () => simulate(null),
get: () => getBackendStatus(),
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "الخلفية",
"encoder": "المشفر",
"flacfetch": "Flacfetch",
"separator": "الفاصل"
"separator": "الفاصل",
"fallbackBadge": "احتياطي",
"fallbackNote": "السعة الأساسية غير متوفرة — تم التوجيه إلى خادم احتياطي.",
"liveWorker": "عامل نشط"
},
"credits": {
"title": "شراء المزيد من الأرصدة",
@@ -549,7 +552,9 @@
"matchUseCorrection": "استخدام التصحيح",
"matchUseTidied": "استخدام النسخة المنقحة",
"matchUsingTyped": "استخدام ما كتبته: {value}",
"checkingUrl": "جاري التحقق..."
"checkingUrl": "جاري التحقق...",
"submitNetworkError": "خطأ في الشبكة — يرجى التحقق من اتصالك والمحاولة مرة أخرى.",
"submitError": "حدث خطأ ما. يرجى المحاولة مرة أخرى."
},
"jobStatus": {
"settingUp": "جاري الإعداد",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} إضافي",
"variantOriginal": "أصلي",
"variantReissue": "إعادة إصدار"
},
"backendStatus": {
"reconnecting": "جارٍ إعادة الاتصال…",
"unavailable": {
"body": "هذا عادةً ما يكون مؤقتاً — يرجى المحاولة مرة أخرى بعد بضع دقائق.",
"reassurance": "أي مقاطع فيديو كاريوكي يتم إنشاؤها حالياً لن تتأثر وستستمر قيد المعالجة.",
"title": "نواجه مشكلة في الوصول إلى خوادمنا"
},
"dismiss": "تجاهل"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Codificador",
"flacfetch": "Flacfetch",
"separator": "Separador"
"separator": "Separador",
"fallbackBadge": "De reserva",
"fallbackNote": "Capacitat principal no disponible — s'ha redirigit a un tipus d'instància de reserva.",
"liveWorker": "Procés actiu"
},
"credits": {
"title": "Compra més crèdits",
@@ -549,7 +552,9 @@
"matchUseCorrection": "utilitza la correcció",
"matchUseTidied": "utilitza la versió polida",
"matchUsingTyped": "Utilitzant el que has escrit: {value}",
"checkingUrl": "Comprovant…"
"checkingUrl": "Comprovant…",
"submitNetworkError": "Error de xarxa — si us plau, comprova la teva connexió i torna-ho a provar.",
"submitError": "Alguna cosa ha anat malament. Torna-ho a provar."
},
"jobStatus": {
"settingUp": "Configurant",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Reedició"
},
"backendStatus": {
"reconnecting": "Reconnectant…",
"unavailable": {
"body": "Això sol ser temporal — si us plau, torna-ho a provar d'aquí a un parell de minuts.",
"reassurance": "Els vídeos de karaoke que s'estiguin creant ara mateix no es veuran afectats i es continuaran processant.",
"title": "Tenim problemes per connectar amb els nostres servidors"
},
"dismiss": "Descarta"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Enkodér",
"flacfetch": "Flacfetch",
"separator": "Separátor"
"separator": "Separátor",
"fallbackBadge": "Záložní",
"fallbackNote": "Primární kapacita je nedostupná — přesměrováno na záložní typ instance.",
"liveWorker": "Aktivní worker"
},
"credits": {
"title": "Koupit další kredity",
@@ -549,7 +552,9 @@
"matchUseCorrection": "použít opravu",
"matchUseTidied": "použít upravenou verzi",
"matchUsingTyped": "Používám to, co jsi zadal: {value}",
"checkingUrl": "Probíhá kontrola…"
"checkingUrl": "Probíhá kontrola…",
"submitNetworkError": "Chyba sítě — zkontroluj prosím své připojení a zkus to znovu.",
"submitError": "Něco se pokazilo. Zkus to prosím znovu."
},
"jobStatus": {
"settingUp": "Nastavování",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Originál",
"variantReissue": "Reedice"
},
"backendStatus": {
"reconnecting": "Obnovování připojení…",
"unavailable": {
"body": "Většinou jde o dočasný problém — zkus to prosím znovu za pár minut.",
"reassurance": "Právě vytvářená karaoke videa nejsou nijak ovlivněna a budou se nadále zpracovávat.",
"title": "Nedaří se nám spojit s našimi servery"
},
"dismiss": "Zavřít"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Primær kapacitet utilgængelig — omdirigeret til en fallback-instanstype.",
"liveWorker": "Live worker"
},
"credits": {
"title": "Køb flere credits",
@@ -549,7 +552,9 @@
"matchUseCorrection": "brug rettelsen",
"matchUseTidied": "brug den tilrettede version",
"matchUsingTyped": "Bruger det, du indtastede: {value}",
"checkingUrl": "Tjekker…"
"checkingUrl": "Tjekker…",
"submitNetworkError": "Netværksfejl — tjek venligst din forbindelse, og prøv igen.",
"submitError": "Noget gik galt. Prøv venligst igen."
},
"jobStatus": {
"settingUp": "Sætter op",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Genudgivelse"
},
"backendStatus": {
"reconnecting": "Genopretter forbindelse…",
"unavailable": {
"body": "Dette er som regel midlertidigt — prøv igen om et par minutter.",
"reassurance": "Eventuelle karaokevideoer, der i øjeblikket bliver lavet, påvirkes ikke og vil fortsat blive behandlet.",
"title": "Vi har problemer med at få forbindelse til vores servere"
},
"dismiss": "Afvis"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Primäre Kapazität nicht verfügbar — auf einen Fallback-Instanztyp umgeleitet.",
"liveWorker": "Live-Worker"
},
"credits": {
"title": "Mehr Guthaben kaufen",
@@ -549,7 +552,9 @@
"matchUseCorrection": "Korrektur verwenden",
"matchUseTidied": "bereinigte Version verwenden",
"matchUsingTyped": "Verwende deine Eingabe: {value}",
"checkingUrl": "Überprüfen…"
"checkingUrl": "Überprüfen…",
"submitNetworkError": "Netzwerkfehler — bitte überprüfe deine Verbindung und versuche es erneut.",
"submitError": "Etwas ist schiefgelaufen. Bitte versuche es erneut."
},
"jobStatus": {
"settingUp": "Richte ein",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} Bonus",
"variantOriginal": "Original",
"variantReissue": "Neuauflage"
},
"backendStatus": {
"reconnecting": "Verbindung wird wiederhergestellt…",
"unavailable": {
"body": "Dies ist meist nur vorübergehend — bitte versuche es in ein paar Minuten noch einmal.",
"reassurance": "Alle Karaoke-Videos, die gerade erstellt werden, sind davon nicht betroffen und werden weiterverarbeitet.",
"title": "Wir haben Probleme, unsere Server zu erreichen"
},
"dismiss": "Ausblenden"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Εφεδρικό",
"fallbackNote": "Η κύρια χωρητικότητα δεν είναι διαθέσιμη — δρομολογήθηκε σε εφεδρικό τύπο instance.",
"liveWorker": "Ενεργός worker"
},
"credits": {
"title": "Αγόρασε Περισσότερες Μονάδες",
@@ -549,7 +552,9 @@
"matchUseCorrection": "χρησιμοποίησε τη διόρθωση",
"matchUseTidied": "χρησιμοποίησε την καθαρισμένη έκδοση",
"matchUsingTyped": "Χρησιμοποιείται αυτό που πληκτρολόγησες: {value}",
"checkingUrl": "Έλεγχος…"
"checkingUrl": "Έλεγχος…",
"submitNetworkError": "Σφάλμα δικτύου — παρακαλούμε έλεγξε τη σύνδεσή σου και δοκίμασε ξανά.",
"submitError": "Κάτι πήγε στραβά. Παρακαλώ δοκίμασε ξανά."
},
"jobStatus": {
"settingUp": "Ρύθμιση",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} μπόνους",
"variantOriginal": "Πρωτότυπο",
"variantReissue": "Επανέκδοση"
},
"backendStatus": {
"reconnecting": "Επανασύνδεση…",
"unavailable": {
"body": "Αυτό είναι συνήθως προσωρινό — παρακαλούμε δοκίμασε ξανά σε λίγα λεπτά.",
"reassurance": "Τυχόν βίντεο καραόκε που δημιουργούνται αυτήν τη στιγμή δεν επηρεάζονται και η επεξεργασία τους θα συνεχιστεί.",
"title": "Αντιμετωπίζουμε πρόβλημα σύνδεσης με τους διακομιστές μας"
},
"dismiss": "Απόρριψη"
}
}
+14
View File
@@ -357,6 +357,15 @@
"almostThere": "Almost there...",
"firstLoadNote": "First load can take up to 30 seconds"
},
"backendStatus": {
"reconnecting": "Reconnecting…",
"unavailable": {
"title": "We're having trouble reaching our servers",
"body": "This is usually temporary — please try again in a couple of minutes.",
"reassurance": "Any karaoke videos currently being created are unaffected and will keep processing."
},
"dismiss": "Dismiss"
},
"status": {
"queued": "Queued",
"processing": "Processing",
@@ -373,6 +382,9 @@
"secondaryStopped": "Secondary (stopped)",
"lastSwap": "Last swap: {time}",
"activeJobs": "Active jobs: {count}",
"liveWorker": "Live worker",
"fallbackBadge": "Fallback",
"fallbackNote": "Primary capacity unavailable — routed to a fallback instance type.",
"systemStatus": "System Status",
"frontend": "Frontend",
"backend": "Backend",
@@ -541,6 +553,8 @@
"missingAudioSource": "Missing audio source. Please go back and try again.",
"searchExpired": "Your search results expired. Please search again — your song info is still saved.",
"failedToStartProcessing": "Failed to start processing. Please try again.",
"submitError": "Something went wrong. Please try again.",
"submitNetworkError": "Network error — please check your connection and try again.",
"trackSubmitted": "Track Submitted",
"lyricsTranscription": "Lyrics transcription",
"lyricsTranscriptionDesc": "We transcribe and sync lyrics from your audio. ~5 minutes",
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Codificador",
"flacfetch": "Flacfetch",
"separator": "Separador"
"separator": "Separador",
"fallbackBadge": "Respaldo",
"fallbackNote": "Capacidad principal no disponible — redirigido a un tipo de instancia de respaldo.",
"liveWorker": "Worker activo"
},
"credits": {
"title": "Comprar más créditos",
@@ -549,7 +552,9 @@
"matchUseCorrection": "usar la corrección",
"matchUseTidied": "usar la versión arreglada",
"matchUsingTyped": "Usando lo que escribiste: {value}",
"checkingUrl": "Comprobando…"
"checkingUrl": "Comprobando…",
"submitNetworkError": "Error de red — por favor, revisa tu conexión y vuelve a intentarlo.",
"submitError": "Algo salió mal. Por favor, inténtalo de nuevo."
},
"jobStatus": {
"settingUp": "Configurando",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Reedición"
},
"backendStatus": {
"reconnecting": "Reconectando…",
"unavailable": {
"body": "Esto suele ser temporal — por favor, inténtalo de nuevo en un par de minutos.",
"reassurance": "Los videos de karaoke que se estén creando en este momento no se verán afectados y seguirán procesándose.",
"title": "Tenemos problemas para conectar con nuestros servidores"
},
"dismiss": "Descartar"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Varajärjestelmä",
"fallbackNote": "Ensisijainen kapasiteetti ei ole käytettävissä — ohjattu varainstanssiin.",
"liveWorker": "Live-työprosessi"
},
"credits": {
"title": "Osta lisää krediittejä",
@@ -549,7 +552,9 @@
"matchUseCorrection": "käytä korjausta",
"matchUseTidied": "käytä siistittyä versiota",
"matchUsingTyped": "Käytetään kirjoittamaasi: {value}",
"checkingUrl": "Tarkistetaan…"
"checkingUrl": "Tarkistetaan…",
"submitNetworkError": "Verkkovirhe — tarkista yhteytesi ja yritä uudelleen.",
"submitError": "Jotain meni pieleen. Yritä uudelleen."
},
"jobStatus": {
"settingUp": "Asetetaan",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonusta",
"variantOriginal": "Alkuperäinen",
"variantReissue": "Uudelleenjulkaisu"
},
"backendStatus": {
"reconnecting": "Yhdistetään uudelleen…",
"unavailable": {
"body": "Tämä on yleensä väliaikaista — yritä uudelleen parin minuutin kuluttua.",
"reassurance": "Tämä ei vaikuta parhaillaan luotaviin karaokevideoihin, vaan niiden käsittely jatkuu normaalisti.",
"title": "Palvelimiimme yhdistämisessä on ongelmia"
},
"dismiss": "Ohita"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encodeur",
"flacfetch": "Flacfetch",
"separator": "Séparateur"
"separator": "Séparateur",
"fallbackBadge": "Secours",
"fallbackNote": "Capacité principale indisponible — redirection vers un type d'instance de secours.",
"liveWorker": "Worker actif"
},
"credits": {
"title": "Acheter plus de crédits",
@@ -549,7 +552,9 @@
"matchUseCorrection": "utiliser la correction",
"matchUseTidied": "utiliser la version nettoyée",
"matchUsingTyped": "Utilisation de ce que tu as tapé : {value}",
"checkingUrl": "Vérification…"
"checkingUrl": "Vérification…",
"submitNetworkError": "Erreur réseau — vérifie ta connexion et réessaie.",
"submitError": "Quelque chose s'est mal passé. Réessaie."
},
"jobStatus": {
"settingUp": "Configuration",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Originale",
"variantReissue": "Réédition"
},
"backendStatus": {
"reconnecting": "Reconnexion…",
"unavailable": {
"body": "C'est généralement temporaire — réessaie dans quelques minutes.",
"reassurance": "Les vidéos de karaoké en cours de création ne sont pas affectées et continueront d'être traitées.",
"title": "Nous avons des difficultés à joindre nos serveurs"
},
"dismiss": "Ignorer"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "צד שרת",
"encoder": "מקודד",
"flacfetch": "Flacfetch",
"separator": "מפריד"
"separator": "מפריד",
"fallbackBadge": "גיבוי",
"fallbackNote": "הקיבולת הראשית אינה זמינה — נותב לסוג מופע גיבוי.",
"liveWorker": "תהליך פעיל"
},
"credits": {
"title": "קנה עוד קרדיטים",
@@ -549,7 +552,9 @@
"matchUseCorrection": "להשתמש בתיקון",
"matchUseTidied": "להשתמש בגרסה המסודרת",
"matchUsingTyped": "משתמשים במה שהקלדת: {value}",
"checkingUrl": "בודק…"
"checkingUrl": "בודק…",
"submitNetworkError": "שגיאת רשת — אנא בדוק את החיבור שלך ונסה שוב.",
"submitError": "משהו השתבש. אנא נסה שוב."
},
"jobStatus": {
"settingUp": "מגדיר",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} בונוס",
"variantOriginal": "מקורי",
"variantReissue": "הוצאה מחודשת"
},
"backendStatus": {
"reconnecting": "מתחבר מחדש…",
"unavailable": {
"body": "זה בדרך כלל זמני — אנא נסו שוב בעוד מספר דקות.",
"reassurance": "סרטוני קריוקי שנוצרים כרגע לא יושפעו וימשיכו בתהליך העיבוד.",
"title": "אנחנו מתקשים להתחבר לשרתים שלנו"
},
"dismiss": "התעלם"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "बैकएंड",
"encoder": "एनकोडर",
"flacfetch": "Flacfetch",
"separator": "सेपरेटर"
"separator": "सेपरेटर",
"fallbackBadge": "फ़ॉलबैक",
"fallbackNote": "प्राथमिक क्षमता उपलब्ध नहीं है — फ़ॉलबैक इंस्टेंस प्रकार पर रूट किया गया।",
"liveWorker": "लाइव वर्कर"
},
"credits": {
"title": "और क्रेडिट्स खरीदो",
@@ -549,7 +552,9 @@
"matchUseCorrection": "सुधार का इस्तेमाल करो",
"matchUseTidied": "व्यवस्थित वर्शन का इस्तेमाल करो",
"matchUsingTyped": "जो तुमने टाइप किया है, उसका इस्तेमाल हो रहा है: {value}",
"checkingUrl": "चेक किया जा रहा है…"
"checkingUrl": "चेक किया जा रहा है…",
"submitNetworkError": "नेटवर्क एरर — कृपया अपना कनेक्शन चेक करो और फिर से कोशिश करो।",
"submitError": "कुछ गलत हो गया। कृपया फिर से कोशिश करो।"
},
"jobStatus": {
"settingUp": "सेटअप हो रहा है",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} बोनस",
"variantOriginal": "मूल",
"variantReissue": "रीइश्यू"
},
"backendStatus": {
"reconnecting": "फिर से कनेक्ट हो रहा है…",
"unavailable": {
"body": "यह आमतौर पर अस्थायी होता है — कृपया कुछ मिनट बाद फिर से कोशिश करो।",
"reassurance": "अभी बन रहे किसी भी कराओके वीडियो पर कोई असर नहीं पड़ा है और उनकी प्रोसेसिंग जारी रहेगी।",
"title": "हमें अपने सर्वर तक पहुँचने में परेशानी हो रही है"
},
"dismiss": "हटाओ"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Enkoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Pričuva",
"fallbackNote": "Primarni kapacitet nije dostupan — preusmjereno na pričuvnu vrstu instance.",
"liveWorker": "Aktivni radnik"
},
"credits": {
"title": "Kupi još kredita",
@@ -549,7 +552,9 @@
"matchUseCorrection": "koristi ispravak",
"matchUseTidied": "koristi uređenu verziju",
"matchUsingTyped": "Koristimo ono što si upisao: {value}",
"checkingUrl": "Provjera…"
"checkingUrl": "Provjera…",
"submitNetworkError": "Mrežna pogreška — molim te, provjeri svoju vezu i pokušaj ponovno.",
"submitError": "Nešto je pošlo po zlu. Pokušaj ponovno."
},
"jobStatus": {
"settingUp": "Postavljanje",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Reizdanje"
},
"backendStatus": {
"reconnecting": "Ponovno povezivanje…",
"unavailable": {
"body": "Ovo je obično privremeno — molim te pokušaj ponovno za nekoliko minuta.",
"reassurance": "Ovo ne utječe na karaoke videozapise koji se trenutno izrađuju i njihova će se obrada nastaviti.",
"title": "Imamo problema s povezivanjem na naše servere"
},
"dismiss": "Odbaci"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Kódoló",
"flacfetch": "Flacfetch",
"separator": "Szétválasztó"
"separator": "Szétválasztó",
"fallbackBadge": "Tartalék",
"fallbackNote": "Az elsődleges kapacitás nem elérhető — átirányítva egy tartalék példánytípusra.",
"liveWorker": "Élő feldolgozó"
},
"credits": {
"title": "Vásárolj több kreditet",
@@ -549,7 +552,9 @@
"matchUseCorrection": "javítás használata",
"matchUseTidied": "letisztított verzió használata",
"matchUsingTyped": "Az általad beírtak használata: {value}",
"checkingUrl": "Ellenőrzés…"
"checkingUrl": "Ellenőrzés…",
"submitNetworkError": "Hálózati hiba — kérlek, ellenőrizd a kapcsolatodat, és próbáld újra.",
"submitError": "Valami hiba történt. Kérlek, próbáld újra."
},
"jobStatus": {
"settingUp": "Beállítás",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bónusz",
"variantOriginal": "Eredeti",
"variantReissue": "Újrakiadás"
},
"backendStatus": {
"reconnecting": "Újracsatlakozás…",
"unavailable": {
"body": "Ez általában átmeneti — kérlek, próbáld újra néhány perc múlva.",
"reassurance": "A jelenleg készülő karaoke videókat ez nem érinti, a feldolgozásuk zavartalanul folytatódik.",
"title": "Nem tudjuk elérni a szervereinket"
},
"dismiss": "Elvetés"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Pemisah"
"separator": "Pemisah",
"fallbackBadge": "Cadangan",
"fallbackNote": "Kapasitas utama tidak tersedia — dialihkan ke tipe instans cadangan.",
"liveWorker": "Pekerja aktif"
},
"credits": {
"title": "Beli Lebih Banyak Kredit",
@@ -549,7 +552,9 @@
"matchUseCorrection": "gunakan koreksi",
"matchUseTidied": "gunakan versi yang dirapikan",
"matchUsingTyped": "Menggunakan yang Anda ketik: {value}",
"checkingUrl": "Memeriksa…"
"checkingUrl": "Memeriksa…",
"submitNetworkError": "Kesalahan jaringan — silakan periksa koneksi Anda dan coba lagi.",
"submitError": "Terjadi kesalahan. Silakan coba lagi."
},
"jobStatus": {
"settingUp": "Menyiapkan",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Rilis ulang"
},
"backendStatus": {
"reconnecting": "Menghubungkan kembali…",
"unavailable": {
"body": "Biasanya ini hanya sementara — silakan coba lagi dalam beberapa menit.",
"reassurance": "Video karaoke yang sedang dibuat tidak akan terpengaruh dan akan terus diproses.",
"title": "Kami kesulitan terhubung ke server"
},
"dismiss": "Abaikan"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separatore"
"separator": "Separatore",
"fallbackBadge": "Fallback",
"fallbackNote": "Capacità principale non disponibile — reindirizzato a un tipo di istanza di fallback.",
"liveWorker": "Worker live"
},
"credits": {
"title": "Acquista altri crediti",
@@ -549,7 +552,9 @@
"matchUseCorrection": "usa la correzione",
"matchUseTidied": "usa la versione ripulita",
"matchUsingTyped": "Uso quello che hai digitato: {value}",
"checkingUrl": "Controllo in corso…"
"checkingUrl": "Controllo in corso…",
"submitNetworkError": "Errore di rete — controlla la tua connessione e riprova.",
"submitError": "Qualcosa è andato storto. Riprova."
},
"jobStatus": {
"settingUp": "Configurazione",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Originale",
"variantReissue": "Ristampa"
},
"backendStatus": {
"reconnecting": "Riconnessione…",
"unavailable": {
"body": "Di solito è un problema temporaneo — riprova tra un paio di minuti.",
"reassurance": "I video karaoke attualmente in fase di creazione non subiranno interruzioni e continueranno a essere elaborati.",
"title": "Abbiamo problemi a raggiungere i nostri server"
},
"dismiss": "Ignora"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "バックエンド",
"encoder": "エンコーダー",
"flacfetch": "Flacfetch",
"separator": "セパレーター"
"separator": "セパレーター",
"fallbackBadge": "フォールバック",
"fallbackNote": "プライマリ容量が利用できないため、フォールバックのインスタンスタイプにルーティングされました。",
"liveWorker": "稼働中のワーカー"
},
"credits": {
"title": "クレジットを追加購入",
@@ -549,7 +552,9 @@
"matchUseCorrection": "修正を適用する",
"matchUseTidied": "整形版を使用する",
"matchUsingTyped": "入力された内容を使用します: {value}",
"checkingUrl": "確認中…"
"checkingUrl": "確認中…",
"submitNetworkError": "ネットワークエラーが発生しました。接続を確認して、もう一度お試しください。",
"submitError": "問題が発生しました。もう一度お試しください。"
},
"jobStatus": {
"settingUp": "セットアップ中",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} ボーナス",
"variantOriginal": "オリジナル",
"variantReissue": "リイシュー"
},
"backendStatus": {
"reconnecting": "再接続中…",
"unavailable": {
"body": "通常は一時的な問題ですので、数分後にもう一度お試しください。",
"reassurance": "現在作成中のカラオケ動画に影響はありません。そのまま処理が継続されます。",
"title": "サーバーへの接続に問題が発生しています"
},
"dismiss": "閉じる"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "백엔드",
"encoder": "인코더",
"flacfetch": "Flacfetch",
"separator": "분리기"
"separator": "분리기",
"fallbackBadge": "대체",
"fallbackNote": "기본 용량을 사용할 수 없어 대체 인스턴스 유형으로 연결되었습니다.",
"liveWorker": "라이브 워커"
},
"credits": {
"title": "크레딧 추가 구매",
@@ -549,7 +552,9 @@
"matchUseCorrection": "수정본 사용하기",
"matchUseTidied": "정리된 버전 사용하기",
"matchUsingTyped": "입력한 내용 사용: {value}",
"checkingUrl": "확인 중…"
"checkingUrl": "확인 중…",
"submitNetworkError": "네트워크 오류 — 연결 상태를 확인하고 다시 시도해 주세요.",
"submitError": "문제가 발생했습니다. 다시 시도해 주세요."
},
"jobStatus": {
"settingUp": "설정 중",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} 보너스",
"variantOriginal": "오리지널",
"variantReissue": "재발매"
},
"backendStatus": {
"reconnecting": "다시 연결하는 중…",
"unavailable": {
"body": "대부분 일시적인 현상이니 몇 분 후에 다시 시도해 주세요.",
"reassurance": "현재 생성 중인 노래방 영상은 영향을 받지 않고 정상적으로 처리됩니다.",
"title": "서버에 연결하는 데 문제가 발생했습니다"
},
"dismiss": "닫기"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Bahagian Belakang",
"encoder": "Pengekod",
"flacfetch": "Flacfetch",
"separator": "Pemisah"
"separator": "Pemisah",
"fallbackBadge": "Sandaran",
"fallbackNote": "Kapasiti utama tidak tersedia — dihalakan ke jenis sandaran.",
"liveWorker": "Pekerja aktif"
},
"credits": {
"title": "Beli Lebih Banyak Kredit",
@@ -549,7 +552,9 @@
"matchUseCorrection": "gunakan pembetulan",
"matchUseTidied": "gunakan versi yang dikemaskan",
"matchUsingTyped": "Menggunakan apa yang anda taip: {value}",
"checkingUrl": "Menyemak…"
"checkingUrl": "Menyemak…",
"submitNetworkError": "Ralat rangkaian — sila semak sambungan anda dan cuba lagi.",
"submitError": "Sesuatu yang tidak kena berlaku. Sila cuba lagi."
},
"jobStatus": {
"settingUp": "Menyediakan",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Asal",
"variantReissue": "Keluaran semula"
},
"backendStatus": {
"reconnecting": "Menyambung semula…",
"unavailable": {
"body": "Ini biasanya sementara — sila cuba lagi dalam beberapa minit.",
"reassurance": "Sebarang video karaoke yang sedang dihasilkan tidak terjejas dan akan terus diproses.",
"title": "Kami menghadapi masalah menyambung ke pelayan kami"
},
"dismiss": "Tutup"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Koder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Reserve",
"fallbackNote": "Primærkapasitet er utilgjengelig — omdirigert til en reserveinstans.",
"liveWorker": "Aktiv arbeider"
},
"credits": {
"title": "Kjøp flere kreditter",
@@ -549,7 +552,9 @@
"matchUseCorrection": "bruk rettelsen",
"matchUseTidied": "bruk oppryddet versjon",
"matchUsingTyped": "Bruker det du skrev inn: {value}",
"checkingUrl": "Sjekker…"
"checkingUrl": "Sjekker…",
"submitNetworkError": "Nettverksfeil — vennligst sjekk tilkoblingen din og prøv igjen.",
"submitError": "Noe gikk galt. Vennligst prøv igjen."
},
"jobStatus": {
"settingUp": "Setter opp",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Nyutgivelse"
},
"backendStatus": {
"reconnecting": "Kobler til på nytt…",
"unavailable": {
"body": "Dette er vanligvis midlertidig — prøv igjen om et par minutter.",
"reassurance": "Eventuelle karaokevideoer som lages akkurat nå påvirkes ikke, og vil fortsette å behandles.",
"title": "Vi har problemer med å nå serverne våre"
},
"dismiss": "Lukk"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Primaire capaciteit niet beschikbaar — omgeleid naar een fallback-instancetype.",
"liveWorker": "Live worker"
},
"credits": {
"title": "Koop meer credits",
@@ -549,7 +552,9 @@
"matchUseCorrection": "gebruik de correctie",
"matchUseTidied": "gebruik opgeschoonde versie",
"matchUsingTyped": "We gebruiken wat je hebt getypt: {value}",
"checkingUrl": "Controleren…"
"checkingUrl": "Controleren…",
"submitNetworkError": "Netwerkfout — controleer je verbinding en probeer het opnieuw.",
"submitError": "Er is iets misgegaan. Probeer het opnieuw."
},
"jobStatus": {
"settingUp": "Instellen",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Origineel",
"variantReissue": "Heruitgave"
},
"backendStatus": {
"reconnecting": "Opnieuw verbinden…",
"unavailable": {
"body": "Dit is meestal tijdelijk — probeer het over een paar minuten opnieuw.",
"reassurance": "Karaokevideo's die momenteel worden gemaakt, ondervinden hier geen hinder van en worden gewoon verder verwerkt.",
"title": "We kunnen onze servers even niet bereiken"
},
"dismiss": "Sluiten"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Koder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Zapasowy",
"fallbackNote": "Główne zasoby niedostępne — przekierowano do zapasowego typu instancji.",
"liveWorker": "Aktywny proces roboczy"
},
"credits": {
"title": "Kup więcej kredytów",
@@ -549,7 +552,9 @@
"matchUseCorrection": "użyj poprawki",
"matchUseTidied": "użyj uporządkowanej wersji",
"matchUsingTyped": "Używam wpisanego tekstu: {value}",
"checkingUrl": "Sprawdzanie…"
"checkingUrl": "Sprawdzanie…",
"submitNetworkError": "Błąd sieci — sprawdź połączenie i spróbuj ponownie.",
"submitError": "Coś poszło nie tak. Spróbuj ponownie."
},
"jobStatus": {
"settingUp": "Konfigurowanie",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Oryginał",
"variantReissue": "Reedycja"
},
"backendStatus": {
"reconnecting": "Ponowne łączenie…",
"unavailable": {
"body": "To zazwyczaj problem tymczasowy — spróbuj ponownie za kilka minut.",
"reassurance": "Obecnie tworzone filmy karaoke są bezpieczne i będą nadal przetwarzane.",
"title": "Mamy problem z połączeniem z naszymi serwerami"
},
"dismiss": "Zamknij"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Capacidade principal indisponível — redirecionado para um tipo de instância de fallback.",
"liveWorker": "Worker ativo"
},
"credits": {
"title": "Comprar Mais Créditos",
@@ -549,7 +552,9 @@
"matchUseCorrection": "usar a correção",
"matchUseTidied": "usar a versão ajustada",
"matchUsingTyped": "Usando o que você digitou: {value}",
"checkingUrl": "Verificando…"
"checkingUrl": "Verificando…",
"submitNetworkError": "Erro de rede — por favor, verifique sua conexão e tente novamente.",
"submitError": "Algo deu errado. Tente novamente."
},
"jobStatus": {
"settingUp": "Configurando",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bônus",
"variantOriginal": "Original",
"variantReissue": "Reedição"
},
"backendStatus": {
"reconnecting": "Reconectando…",
"unavailable": {
"body": "Isso geralmente é temporário — por favor, tente novamente em alguns minutos.",
"reassurance": "Os vídeos de karaokê que estão sendo criados no momento não serão afetados e continuarão sendo processados.",
"title": "Estamos com problemas para acessar nossos servidores"
},
"dismiss": "Dispensar"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Rezervă",
"fallbackNote": "Capacitatea principală este indisponibilă — redirecționată către un tip de instanță de rezervă.",
"liveWorker": "Worker activ"
},
"credits": {
"title": "Cumpără mai multe credite",
@@ -549,7 +552,9 @@
"matchUseCorrection": "folosește corecția",
"matchUseTidied": "folosește versiunea curățată",
"matchUsingTyped": "Folosim ce ai tastat: {value}",
"checkingUrl": "Se verifică…"
"checkingUrl": "Se verifică…",
"submitNetworkError": "Eroare de rețea — te rugăm să verifici conexiunea și să încerci din nou.",
"submitError": "Ceva nu a mers bine. Te rog să încerci din nou."
},
"jobStatus": {
"settingUp": "Se configurează",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Reeditare"
},
"backendStatus": {
"reconnecting": "Se reconectează…",
"unavailable": {
"body": "Această situație este de obicei temporară — încearcă din nou în câteva minute.",
"reassurance": "Videoclipurile de karaoke aflate în curs de creare nu sunt afectate și vor continua să fie procesate.",
"title": "Întâmpinăm probleme la conectarea cu serverele noastre"
},
"dismiss": "Închide"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Бэкенд",
"encoder": "Кодировщик",
"flacfetch": "Flacfetch",
"separator": "Разделитель"
"separator": "Разделитель",
"fallbackBadge": "Резерв",
"fallbackNote": "Основные ресурсы недоступны — перенаправлено на резервный тип инстанса.",
"liveWorker": "Активный воркер"
},
"credits": {
"title": "Купить еще кредиты",
@@ -549,7 +552,9 @@
"matchUseCorrection": "использовать исправление",
"matchUseTidied": "использовать отформатированную версию",
"matchUsingTyped": "Используем твой вариант: {value}",
"checkingUrl": "Проверка…"
"checkingUrl": "Проверка…",
"submitNetworkError": "Ошибка сети — пожалуйста, проверь подключение и попробуй еще раз.",
"submitError": "Что-то пошло не так. Пожалуйста, попробуй еще раз."
},
"jobStatus": {
"settingUp": "Настройка",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} бонус",
"variantOriginal": "Оригинал",
"variantReissue": "Переиздание"
},
"backendStatus": {
"reconnecting": "Переподключение…",
"unavailable": {
"body": "Обычно это временно — пожалуйста, попробуй еще раз через пару минут.",
"reassurance": "Это не повлияет на караоке-видео, которые сейчас создаются — они продолжат обрабатываться.",
"title": "Возникли проблемы с подключением к нашим серверам"
},
"dismiss": "Скрыть"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Enkodér",
"flacfetch": "Flacfetch",
"separator": "Separátor"
"separator": "Separátor",
"fallbackBadge": "Záloha",
"fallbackNote": "Primárna kapacita je nedostupná — presmerovaná na záložný typ inštancie.",
"liveWorker": "Aktívny worker"
},
"credits": {
"title": "Kúpiť viac kreditov",
@@ -549,7 +552,9 @@
"matchUseCorrection": "použiť opravu",
"matchUseTidied": "použiť upravenú verziu",
"matchUsingTyped": "Používam to, čo si zadal: {value}",
"checkingUrl": "Kontroluje sa…"
"checkingUrl": "Kontroluje sa…",
"submitNetworkError": "Chyba siete — skontroluj pripojenie a skús to znova.",
"submitError": "Niečo sa pokazilo. Skús to znova."
},
"jobStatus": {
"settingUp": "Nastavuje sa",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Originál",
"variantReissue": "Reedícia"
},
"backendStatus": {
"reconnecting": "Obnovuje sa pripojenie…",
"unavailable": {
"body": "Zvyčajne ide len o dočasný problém — skús to znova o pár minút.",
"reassurance": "Karaoke videá, ktoré sa práve vytvárajú, to neovplyvní a ich spracovanie bude pokračovať.",
"title": "Máme problémy s pripojením k našim serverom"
},
"dismiss": "Zavrieť"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Primär kapacitet är otillgänglig — omdirigerad till en fallback-instans.",
"liveWorker": "Live-worker"
},
"credits": {
"title": "Köp fler krediter",
@@ -549,7 +552,9 @@
"matchUseCorrection": "använd korrigeringen",
"matchUseTidied": "använd rensad version",
"matchUsingTyped": "Använder det du skrev: {value}",
"checkingUrl": "Kontrollerar…"
"checkingUrl": "Kontrollerar…",
"submitNetworkError": "Nätverksfel — kontrollera din anslutning och försök igen.",
"submitError": "Något gick fel. Försök igen."
},
"jobStatus": {
"settingUp": "Ställer in",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Nyutgåva"
},
"backendStatus": {
"reconnecting": "Återansluter…",
"unavailable": {
"body": "Detta är oftast tillfälligt — försök igen om ett par minuter.",
"reassurance": "Karaokevideor som håller på att skapas påverkas inte, utan fortsätter att bearbetas.",
"title": "Vi har problem med att nå våra servrar"
},
"dismiss": "Avfärda"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "สำรอง",
"fallbackNote": "ทรัพยากรหลักไม่พร้อมใช้งาน — เปลี่ยนเส้นทางไปยังอินสแตนซ์สำรองแล้ว",
"liveWorker": "เวิร์กเกอร์ที่ทำงานอยู่"
},
"credits": {
"title": "ซื้อเครดิตเพิ่ม",
@@ -549,7 +552,9 @@
"matchUseCorrection": "ใช้ตามที่แก้ไข",
"matchUseTidied": "ใช้เวอร์ชันที่จัดระเบียบแล้ว",
"matchUsingTyped": "ใช้ข้อความที่คุณพิมพ์: {value}",
"checkingUrl": "กำลังตรวจสอบ…"
"checkingUrl": "กำลังตรวจสอบ…",
"submitNetworkError": "เกิดข้อผิดพลาดของเครือข่าย — โปรดตรวจสอบการเชื่อมต่อของคุณแล้วลองใหม่อีกครั้ง",
"submitError": "เกิดข้อผิดพลาดบางอย่าง โปรดลองอีกครั้ง"
},
"jobStatus": {
"settingUp": "กำลังตั้งค่า",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} โบนัส",
"variantOriginal": "ต้นฉบับ",
"variantReissue": "วางจำหน่ายใหม่"
},
"backendStatus": {
"reconnecting": "กำลังเชื่อมต่อใหม่…",
"unavailable": {
"body": "ปัญหานี้มักเกิดขึ้นเพียงชั่วคราว — กรุณาลองใหม่อีกครั้งในอีกสองสามนาที",
"reassurance": "วิดีโอคาราโอเกะที่กำลังสร้างอยู่จะไม่ได้รับผลกระทบ และจะประมวลผลต่อไป",
"title": "เราพบปัญหาในการเชื่อมต่อกับเซิร์ฟเวอร์"
},
"dismiss": "ปิดทิ้ง"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Hindi available ang pangunahing kapasidad — inilipat sa isang fallback instance type.",
"liveWorker": "Live worker"
},
"credits": {
"title": "Bumili ng Higit Pang Credits",
@@ -549,7 +552,9 @@
"matchUseCorrection": "gamitin ang itinama",
"matchUseTidied": "gamitin ang inayos na bersyon",
"matchUsingTyped": "Ginagamit ang iyong nai-type: {value}",
"checkingUrl": "Sinusuri…"
"checkingUrl": "Sinusuri…",
"submitNetworkError": "Error sa network — paki-check ang iyong koneksyon at subukang muli.",
"submitError": "May nangyaring mali. Pakisubukan muli."
},
"jobStatus": {
"settingUp": "Sine-set up",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Orihinal",
"variantReissue": "Muling inilabas"
},
"backendStatus": {
"reconnecting": "Kumokonekta muli…",
"unavailable": {
"body": "Kadalasan ay pansamantala lamang ito — pakisubukan muli pagkalipas ng ilang minuto.",
"reassurance": "Ang anumang karaoke video na kasalukuyang ginagawa ay hindi maaapektuhan at patuloy na ipoproseso.",
"title": "Nahihirapan kaming kumonekta sa aming mga server"
},
"dismiss": "I-dismiss"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Arkayüz",
"encoder": "Kodlayıcı",
"flacfetch": "Flacfetch",
"separator": "Ayırıcı"
"separator": "Ayırıcı",
"fallbackBadge": "Yedek",
"fallbackNote": "Ana kapasite kullanılamıyor — yedek bir sunucu tipine yönlendirildi.",
"liveWorker": "Canlı işlemci"
},
"credits": {
"title": "Daha Fazla Kredi Al",
@@ -549,7 +552,9 @@
"matchUseCorrection": "düzeltmeyi kullan",
"matchUseTidied": "düzenlenmiş sürümü kullan",
"matchUsingTyped": "Yazdığın kullanılıyor: {value}",
"checkingUrl": "Kontrol ediliyor…"
"checkingUrl": "Kontrol ediliyor…",
"submitNetworkError": "Ağ hatası — lütfen bağlantını kontrol et ve tekrar dene.",
"submitError": "Bir şeyler ters gitti. Lütfen tekrar dene."
},
"jobStatus": {
"settingUp": "Ayarlanıyor",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Orijinal",
"variantReissue": "Yeniden basım"
},
"backendStatus": {
"reconnecting": "Yeniden bağlanıyor…",
"unavailable": {
"body": "Bu genellikle geçici bir durum — lütfen birkaç dakika sonra tekrar dene.",
"reassurance": "Şu anda oluşturulmakta olan karaoke videoları bu durumdan etkilenmez ve işlenmeye devam eder.",
"title": "Sunucularımıza ulaşmakta sorun yaşıyoruz"
},
"dismiss": "Kapat"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Бекенд",
"encoder": "Кодувальник",
"flacfetch": "Flacfetch",
"separator": "Розділювач"
"separator": "Розділювач",
"fallbackBadge": "Резерв",
"fallbackNote": "Основні потужності недоступні — перенаправлено на резервний тип інстансу.",
"liveWorker": "Активний воркер"
},
"credits": {
"title": "Купити більше кредитів",
@@ -549,7 +552,9 @@
"matchUseCorrection": "використати виправлення",
"matchUseTidied": "використати впорядковану версію",
"matchUsingTyped": "Використовуємо введений тобою текст: {value}",
"checkingUrl": "Перевірка…"
"checkingUrl": "Перевірка…",
"submitNetworkError": "Помилка мережі — будь ласка, перевір з'єднання і спробуй ще раз.",
"submitError": "Щось пішло не так. Будь ласка, спробуй ще раз."
},
"jobStatus": {
"settingUp": "Налаштування",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} бонус",
"variantOriginal": "Оригінал",
"variantReissue": "Перевидання"
},
"backendStatus": {
"reconnecting": "Відновлення з'єднання…",
"unavailable": {
"body": "Зазвичай це тимчасово — будь ласка, спробуй ще раз за кілька хвилин.",
"reassurance": "Це не вплине на караоке-відео, які зараз створюються, їхня обробка продовжиться.",
"title": "Виникли проблеми зі зв'язком із нашими серверами"
},
"dismiss": "Закрити"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Dự phòng",
"fallbackNote": "Tài nguyên chính không khả dụng — đã chuyển hướng sang máy chủ dự phòng.",
"liveWorker": "Worker đang hoạt động"
},
"credits": {
"title": "Mua thêm credit",
@@ -549,7 +552,9 @@
"matchUseCorrection": "sử dụng bản sửa đổi",
"matchUseTidied": "sử dụng bản đã tinh chỉnh",
"matchUsingTyped": "Sử dụng nội dung bạn đã nhập: {value}",
"checkingUrl": "Đang kiểm tra…"
"checkingUrl": "Đang kiểm tra…",
"submitNetworkError": "Lỗi mạng — vui lòng kiểm tra kết nối của bạn và thử lại.",
"submitError": "Đã xảy ra lỗi. Vui lòng thử lại."
},
"jobStatus": {
"settingUp": "Đang thiết lập",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} tặng kèm",
"variantOriginal": "Bản gốc",
"variantReissue": "Tái bản"
},
"backendStatus": {
"reconnecting": "Đang kết nối lại…",
"unavailable": {
"body": "Sự cố này thường chỉ là tạm thời — vui lòng thử lại sau vài phút.",
"reassurance": "Các video karaoke đang được tạo sẽ không bị ảnh hưởng và vẫn tiếp tục được xử lý.",
"title": "Chúng tôi đang gặp sự cố khi kết nối với máy chủ"
},
"dismiss": "Bỏ qua"
}
}
+16 -2
View File
@@ -378,7 +378,10 @@
"backend": "后端",
"encoder": "编码器",
"flacfetch": "Flacfetch",
"separator": "分离器"
"separator": "分离器",
"fallbackBadge": "备用",
"fallbackNote": "主容量不可用 — 已切换至备用实例类型。",
"liveWorker": "在线工作节点"
},
"credits": {
"title": "购买更多积分",
@@ -549,7 +552,9 @@
"matchUseCorrection": "使用修正内容",
"matchUseTidied": "使用整理后的版本",
"matchUsingTyped": "使用您输入的内容:{value}",
"checkingUrl": "检查中…"
"checkingUrl": "检查中…",
"submitNetworkError": "网络错误 —— 请检查您的网络连接并重试。",
"submitError": "出了点问题,请重试。"
},
"jobStatus": {
"settingUp": "设置中",
@@ -1678,5 +1683,14 @@
"variantBonus": "+{count} 附加曲目",
"variantOriginal": "原版",
"variantReissue": "再版"
},
"backendStatus": {
"reconnecting": "重新连接中…",
"unavailable": {
"body": "这通常是暂时现象,请几分钟后再试。",
"reassurance": "当前正在制作的卡拉OK视频不会受到影响,系统将继续进行处理。",
"title": "我们连接服务器时遇到了一些问题"
},
"dismiss": "忽略"
}
}
+17
View File
@@ -104,6 +104,23 @@ def create_database() -> dict:
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Jobs: query by request_metadata.client_id + tenant_id, order by created_at.
# Powers GET /api/jobs?client_id= — the idempotency lookup for externally
# created jobs (the Fiverr agent tags jobs client_id="fiverr:{order_id}").
# Without it that query 400s ("The query requires an index").
resources["firestore_index_jobs_client_id"] = firestore.Index(
"firestore-index-jobs-client-id",
project=PROJECT_ID,
database=firestore_db.name,
collection="jobs",
fields=[
firestore.IndexFieldArgs(field_path="request_metadata.client_id", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="tenant_id", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Sessions: query by user_email + is_active, order by created_at
resources["firestore_index_sessions_active"] = firestore.Index(
"firestore-index-sessions-active",
+109 -8
View File
@@ -194,23 +194,124 @@ def create_alert_policies(
)
# Alert: Cloud Run Service Unavailable
#
# HISTORY — why this is NOT an instance-count-absence alert anymore:
# The original condition used `condition_absent` on
# `run.googleapis.com/container/instance_count` ("No healthy instances").
# That metric is a *sampled* series: for a min-instances=1, low-traffic
# service it legitimately stops reporting for short stretches even while
# the single instance is alive and serving 200s. On 2026-08-19 03:15 UTC it
# fired + auto-resolved in ~85s while the same instanceId was actively
# answering the scheduled recover-stuck-jobs / retry-pending-render crons
# with HTTP 200 — a pure metric blink, not an outage. Absence of an
# instance-count sample is simply the wrong signal for "is the API down".
#
# Fix: measure reachability directly with a Cloud Monitoring uptime check
# against the public health endpoint (through the Cloudflare edge, exactly
# the path real users take), and page only when it FAILS from more than one
# checker location — so a single flaky checker can't page us, but a genuine
# hard-down (every checker failing) does after the retest window (~5-6 min
# with the 300s `duration`; see the HISTORY note on that below).
#
# NOTE on granularity: with selected_regions unset the check runs from all
# of Google's checker locations (several are in the USA alone). The
# condition counts failing *checker locations* (REDUCE_COUNT_FALSE grouped
# by host), NOT broad geographic regions — two failed US checkers is enough
# to fire. That is intentional: >1 failing location is a real reachability
# problem worth paging, and requiring >1 filters out single-checker noise.
#
# HISTORY — why `duration` is 300s, not 60s:
# The service runs on `--min-instances 1` (a single warm instance). Two
# self-healing failure modes each briefly take health checks down from ALL
# checker locations at once, tripping the >1-location threshold:
# (a) Instance recycle. Cloud Run periodically replaces the lone instance
# (host maintenance / max-lifetime). On 2026-08-22 06:02:30–06:03:50
# UTC the instance was replaced (log: "Starting new instance …
# MIN_INSTANCE" then AUTOSCALING; STARTUP probe ready ~06:03:13),
# leaving ~80s with no warm origin — every uptime checker failed, then
# it self-healed. The alert fired at 06:06 and auto-cleared in ~1m41s.
# (b) Event-loop stall. The single instance can block on synchronous-ish
# work (e.g. orchestrating an encoding-worker fallback cold-start with
# blocking timeouts, seen 2026-08-22 00:11–00:12 UTC where four queued
# health probes all flushed at the same instant), so probes queue past
# the 10s uptime timeout across regions until it frees up.
# Both clear on their own well under 5 minutes. Rather than pay for a second
# always-on instance, we require the >1-location failure to PERSIST for 300s
# before paging: sub-5-min blips are suppressed, a genuine sustained hard-down
# still pages (at ~5–6 min instead of ~1–2). If real outages ever slip
# through undetected, the cheaper-detection lever is `--min-instances 2`
# (ci.yml) — that removes both failure modes at the source.
uptime_health = gcp.monitoring.UptimeCheckConfig(
"backend-health-uptime-check",
display_name="Karaoke Backend - /api/health",
timeout="10s",
period="60s",
monitored_resource=gcp.monitoring.UptimeCheckConfigMonitoredResourceArgs(
type="uptime_url",
labels={"project_id": PROJECT_ID, "host": "api.nomadkaraoke.com"},
),
http_check=gcp.monitoring.UptimeCheckConfigHttpCheckArgs(
path="/api/health",
port=443,
use_ssl=True,
validate_ssl=True,
request_method="GET",
accepted_response_status_codes=[
gcp.monitoring.UptimeCheckConfigHttpCheckAcceptedResponseStatusCodeArgs(
status_value=200,
),
],
),
# Body must actually contain the health marker — guards against an edge
# that returns 200 with an error/placeholder page instead of the app.
content_matchers=[
gcp.monitoring.UptimeCheckConfigContentMatcherArgs(
content="healthy",
matcher="CONTAINS_STRING",
),
],
)
alerts["health_uptime_check"] = uptime_health
# Build the alert filter once the check id is known. `check_id` in the metric
# label is the short id exposed as `.uptime_check_id`.
_uptime_filter = uptime_health.uptime_check_id.apply(
lambda check_id: (
'resource.type="uptime_url" '
'AND metric.type="monitoring.googleapis.com/uptime_check/check_passed" '
f'AND metric.label.check_id="{check_id}"'
)
)
alerts["service_unavailable"] = gcp.monitoring.AlertPolicy(
"service-unavailable-alert",
display_name="Karaoke Backend - Service Unavailable",
combiner="OR",
conditions=[
gcp.monitoring.AlertPolicyConditionArgs(
display_name="No healthy instances",
condition_absent=gcp.monitoring.AlertPolicyConditionConditionAbsentArgs(
filter='resource.type="cloud_run_revision" AND resource.labels.service_name="karaoke-backend" AND metric.type="run.googleapis.com/container/instance_count"',
display_name="Health check failing from >1 checker location",
condition_threshold=gcp.monitoring.AlertPolicyConditionConditionThresholdArgs(
filter=_uptime_filter,
# Count how many checker locations reported a *failed* check
# over the window; fire when more than one location is failing.
comparison="COMPARISON_GT",
threshold_value=1,
# Require the >1-location failure to persist for 5 minutes
# before paging. Filters out sub-5-min self-healing blips on
# the single min-instance (recycle gap + event-loop stall);
# see the HISTORY note above. A sustained hard-down still fires.
duration="300s",
aggregations=[
gcp.monitoring.AlertPolicyConditionConditionAbsentAggregationArgs(
alignment_period="60s",
per_series_aligner="ALIGN_MEAN",
cross_series_reducer="REDUCE_SUM",
gcp.monitoring.AlertPolicyConditionConditionThresholdAggregationArgs(
alignment_period="1200s",
per_series_aligner="ALIGN_NEXT_OLDER",
cross_series_reducer="REDUCE_COUNT_FALSE",
group_by_fields=["resource.label.host"],
),
],
trigger=gcp.monitoring.AlertPolicyConditionConditionThresholdTriggerArgs(
count=1,
),
),
),
],
@@ -218,7 +319,7 @@ def create_alert_policies(
auto_close="1800s",
),
documentation=gcp.monitoring.AlertPolicyDocumentationArgs(
content="Karaoke backend service appears to be down - no healthy Cloud Run instances detected.\n\nImmediate actions:\n1. Check Cloud Run logs for crash reasons\n2. Verify recent deployments\n3. Check external dependencies (Modal, AudioShake)\n\nService URL: https://api.nomadkaraoke.com/api/health",
content="Karaoke backend health check (https://api.nomadkaraoke.com/api/health) is failing from multiple checker locations - the API is likely unreachable or erroring.\n\nImmediate actions:\n1. Check Cloud Run logs for crash reasons\n2. Verify recent deployments\n3. Check the Cloudflare edge (api.nomadkaraoke.com) and external dependencies (Modal, AudioShake)\n\nService URL: https://api.nomadkaraoke.com/api/health",
mime_type="text/markdown",
),
enabled=True,
+13 -4
View File
@@ -1816,11 +1816,20 @@ def create_audio_fetcher(
logger=logger,
)
elif api_url and not api_key:
if logger:
logger.warning("FLACFETCH_API_URL is set but FLACFETCH_API_KEY is not - falling back to local mode")
# Half-configured remote flacfetch is almost always a deploy/secret typo.
# Silently using local mode masks the misconfiguration — fail loudly so
# the operator fixes it. (Fallback audit 2026-06-09, Theme 1.)
raise AudioFetcherError(
"FLACFETCH_API_URL is set but FLACFETCH_API_KEY is not. Remote flacfetch "
"is half-configured — set both (or neither, for local mode). Refusing to "
"silently fall back to local mode and mask the misconfiguration."
)
elif api_key and not api_url:
if logger:
logger.warning("FLACFETCH_API_KEY is set but FLACFETCH_API_URL is not - falling back to local mode")
raise AudioFetcherError(
"FLACFETCH_API_KEY is set but FLACFETCH_API_URL is not. Remote flacfetch "
"is half-configured — set both (or neither, for local mode). Refusing to "
"silently fall back to local mode and mask the misconfiguration."
)
# Use local flacfetch library
return FlacFetchAudioFetcher(
@@ -886,19 +886,28 @@ class KaraokeFinalise:
self.execute_command(ffmpeg_command, "Remuxing video with instrumental audio")
def convert_mov_to_mp4(self, input_file, output_file):
"""Convert MOV file to MP4 format with hardware acceleration support"""
# Hardware-accelerated version
"""Convert the source "With Vocals" video (MOV/MKV) to a standard, portable MP4.
Produces the "(With Vocals).mp4" sing-along deliverable — a leaf output (no
later encode reads it). ``-preset veryfast`` roughly halves this stage (the
longest finalization stage) with negligible quality impact for karaoke content;
AAC 320k keeps the audio portable. yuv420p (playback compatibility) comes from
``self.mp4_flags``, which already carries ``-pix_fmt yuv420p``. Kept in sync
with LocalEncodingService.convert_mov_to_mp4 (whose MP4_FLAGS lacks pix_fmt, so
that variant sets ``-pix_fmt yuv420p`` explicitly).
"""
# Hardware-accelerated version (pix_fmt yuv420p supplied via self.mp4_flags)
gpu_command = (
f'{self.ffmpeg_base_command} {self.hwaccel_decode_flags} -i "{input_file}" '
f'-c:v {self.video_encoder} {self.get_nvenc_quality_settings("high")} -c:a {self.aac_codec} -ar 48000 {self.mp4_flags} "{output_file}"'
f'-c:v {self.video_encoder} {self.get_nvenc_quality_settings("high")} -c:a {self.aac_codec} -ar 48000 -b:a 320k {self.mp4_flags} "{output_file}"'
)
# Software fallback version
cpu_command = (
f'{self.ffmpeg_base_command} -i "{input_file}" '
f'-c:v libx264 -c:a {self.aac_codec} -ar 48000 {self.mp4_flags} "{output_file}"'
f'-c:v libx264 -preset veryfast -c:a {self.aac_codec} -ar 48000 -b:a 320k {self.mp4_flags} "{output_file}"'
)
self.execute_command_with_fallback(gpu_command, cpu_command, "Converting MOV video to MP4")
def encode_lossless_mp4(self, title_mov_file, karaoke_mp4_file, env_mov_input, ffmpeg_filter, output_file):
+11 -1
View File
@@ -414,7 +414,17 @@ class VideoGenerator:
karaoke_styles = self.styles.get("karaoke", {})
font_path = karaoke_styles.get("font_path")
if font_path and os.path.isfile(font_path):
if font_path:
if not os.path.isfile(font_path):
# The theme specifies a branded karaoke font but the file is
# missing. Refuse to silently render the whole song with a libass
# system-fallback font on a paid deliverable — mirrors the
# background-image check in __init__. (Fallback audit, Theme 4.)
raise FileNotFoundError(
f"Karaoke font not found: {font_path}. The theme specifies a "
"branded font but the file is missing — refusing to silently "
"render with a system fallback font."
)
font_dir = os.path.dirname(font_path)
escaped_font_dir = self._escape_ffmpeg_filter_path(font_dir)
ass_filter += f":fontsdir={escaped_font_dir}"
+14 -3
View File
@@ -367,9 +367,20 @@ class VideoGenerator:
def _create_background(self, format, resolution):
"""Create or load the background image."""
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.info(f"Using background image file: {format['background_image']}")
background = Image.open(format["background_image"])
background_image = format["background_image"]
if background_image:
if not os.path.exists(background_image):
# A themed background was specified but the file is missing.
# Refuse to silently fall back to a flat color on a paid title/end
# card — mirrors the karaoke video path, which raises on a missing
# background image. (Fallback audit, Theme 4.)
raise FileNotFoundError(
f"Background image not found: {background_image}. The theme "
"specifies a background image but the file is missing — refusing "
"to silently render a flat color instead."
)
self.logger.info(f"Using background image file: {background_image}")
background = Image.open(background_image)
else:
self.logger.info(f"Using background color: {format['background_color']}")
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.195.1"
version = "0.196.8"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
+8 -8
View File
@@ -2342,20 +2342,20 @@ class TestCreateAudioFetcherRemoteSelection:
assert fetcher.api_key == "custom_key"
@patch.dict(os.environ, {"FLACFETCH_API_URL": "http://localhost:8080"}, clear=False)
def test_falls_back_to_local_without_api_key(self):
"""Test factory falls back to local when only URL is set."""
def test_half_configured_url_only_raises(self):
"""Half-configured remote (URL only) must fail loudly, not silently use local."""
# Clear FLACFETCH_API_KEY if it exists
with patch.dict(os.environ, {"FLACFETCH_API_KEY": ""}, clear=False):
fetcher = create_audio_fetcher()
assert isinstance(fetcher, FlacFetchAudioFetcher)
with pytest.raises(AudioFetcherError, match="FLACFETCH_API_KEY is not"):
create_audio_fetcher()
@patch.dict(os.environ, {"FLACFETCH_API_KEY": "test_key"}, clear=False)
def test_falls_back_to_local_without_api_url(self):
"""Test factory falls back to local when only key is set."""
def test_half_configured_key_only_raises(self):
"""Half-configured remote (key only) must fail loudly, not silently use local."""
# Clear FLACFETCH_API_URL if it exists
with patch.dict(os.environ, {"FLACFETCH_API_URL": ""}, clear=False):
fetcher = create_audio_fetcher()
assert isinstance(fetcher, FlacFetchAudioFetcher)
with pytest.raises(AudioFetcherError, match="FLACFETCH_API_URL is not"):
create_audio_fetcher()
@patch.dict(os.environ, {}, clear=True)
def test_creates_local_fetcher_by_default(self):
+65
View File
@@ -0,0 +1,65 @@
"""
Fallback audit (Theme 4): a *configured* branded render asset that is missing
must fail loudly rather than silently substituting a different font/background on
a paid deliverable. Mirrors the existing background-image check in
lyrics_transcriber/output/video.VideoGenerator.__init__ (which already raises).
Scope: only the cleanest "configured-but-missing → raise" cases were changed
(4.1 final-MP4 karaoke font dir, 4.3 themed title/end background). Font
*substitution* paths (title/end font, CDG arial, measurement font) were left as
graceful fallbacks because they overlap with legitimate CJK font handling.
"""
import pytest
from unittest.mock import MagicMock
from karaoke_gen.lyrics_transcriber.output.video import VideoGenerator as AssVideoGenerator
from karaoke_gen.video_generator import VideoGenerator as ScreenVideoGenerator
# ---- 4.1: final-MP4 karaoke font dir ----
def _make_ass_generator(styles):
"""Build just enough of the ASS VideoGenerator to exercise _build_ass_filter."""
gen = AssVideoGenerator.__new__(AssVideoGenerator)
gen.styles = styles
gen.logger = MagicMock()
return gen
def test_build_ass_filter_raises_when_configured_font_missing():
"""A theme font that's set but missing must raise, not silently drop fontsdir."""
gen = _make_ass_generator({"karaoke": {"font_path": "/nonexistent/Branded.ttf"}})
with pytest.raises(FileNotFoundError, match="Karaoke font not found"):
gen._build_ass_filter("/tmp/lyrics.ass")
def test_build_ass_filter_ok_when_no_font_configured():
"""No font configured is legitimate — no fontsdir, no raise."""
gen = _make_ass_generator({"karaoke": {}})
result = gen._build_ass_filter("/tmp/lyrics.ass")
assert "fontsdir" not in result
assert result.startswith("ass=")
# ---- 4.3: themed title/end background image ----
def _make_screen_generator():
gen = ScreenVideoGenerator.__new__(ScreenVideoGenerator)
gen.logger = MagicMock()
return gen
def test_create_background_raises_when_configured_image_missing():
"""A background image that's set but missing must raise, not silently use a flat color."""
gen = _make_screen_generator()
fmt = {"background_image": "/nonexistent/bg.png", "background_color": "black"}
with pytest.raises(FileNotFoundError, match="Background image not found"):
gen._create_background(fmt, (100, 100))
def test_create_background_uses_color_when_no_image_configured():
"""No background image configured is legitimate — flat color, no raise."""
gen = _make_screen_generator()
fmt = {"background_image": None, "background_color": "#000000"}
bg = gen._create_background(fmt, (10, 10))
assert bg.size == (10, 10)
@@ -138,11 +138,11 @@ def test_convert_mov_to_mp4_aac(mock_execute_fallback, finaliser_with_aac):
expected_gpu_cmd = (
f'{finaliser_with_aac.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -preset p4 -tune hq -cq 18 -c:a aac -ar 48000 {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -preset p4 -tune hq -cq 18 -c:a aac -ar 48000 -b:a 320k {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
expected_cpu_cmd = (
f'{finaliser_with_aac.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -c:a aac -ar 48000 {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -preset veryfast -c:a aac -ar 48000 -b:a 320k {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
mock_execute_fallback.assert_called_once_with(expected_gpu_cmd, expected_cpu_cmd, "Converting MOV video to MP4")
@@ -153,11 +153,11 @@ def test_convert_mov_to_mp4_aac_at(mock_execute_fallback, finaliser_with_aac_at)
expected_gpu_cmd = (
f'{finaliser_with_aac_at.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -preset p4 -tune hq -cq 18 -c:a aac_at -ar 48000 {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -preset p4 -tune hq -cq 18 -c:a aac_at -ar 48000 -b:a 320k {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
expected_cpu_cmd = (
f'{finaliser_with_aac_at.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -c:a aac_at -ar 48000 {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -preset veryfast -c:a aac_at -ar 48000 -b:a 320k {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
mock_execute_fallback.assert_called_once_with(expected_gpu_cmd, expected_cpu_cmd, "Converting MOV video to MP4")
@@ -398,11 +398,11 @@ def test_convert_mov_to_mp4_aac_nvenc(mock_execute_fallback, finaliser_with_nven
expected_gpu_cmd = (
f'{finaliser_with_nvenc_aac.ffmpeg_base_command} {finaliser_with_nvenc_aac.hwaccel_decode_flags} -i "{WITH_VOCALS_MOV}" '
f'-c:v h264_nvenc -preset p4 -tune hq -cq 18 -c:a aac {finaliser_with_nvenc_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v h264_nvenc -preset p4 -tune hq -cq 18 -c:a aac -ar 48000 -b:a 320k {finaliser_with_nvenc_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
expected_cpu_cmd = (
f'{finaliser_with_nvenc_aac.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -c:a aac {finaliser_with_nvenc_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -preset veryfast -c:a aac -ar 48000 -b:a 320k {finaliser_with_nvenc_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
mock_execute_fallback.assert_called_once_with(expected_gpu_cmd, expected_cpu_cmd, "Converting MOV video to MP4")
@@ -414,11 +414,11 @@ def test_convert_mov_to_mp4_aac_at_nvenc(mock_execute_fallback, finaliser_with_n
expected_gpu_cmd = (
f'{finaliser_with_nvenc_aac_at.ffmpeg_base_command} {finaliser_with_nvenc_aac_at.hwaccel_decode_flags} -i "{WITH_VOCALS_MOV}" '
f'-c:v h264_nvenc -preset p4 -tune hq -cq 18 -c:a aac_at {finaliser_with_nvenc_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v h264_nvenc -preset p4 -tune hq -cq 18 -c:a aac_at -ar 48000 -b:a 320k {finaliser_with_nvenc_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
expected_cpu_cmd = (
f'{finaliser_with_nvenc_aac_at.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -c:a aac_at {finaliser_with_nvenc_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -preset veryfast -c:a aac_at -ar 48000 -b:a 320k {finaliser_with_nvenc_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
mock_execute_fallback.assert_called_once_with(expected_gpu_cmd, expected_cpu_cmd, "Converting MOV video to MP4")