Compare commits

...
16 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 5.5 2b8439a0ae fix(auth): own domain never disposable; tenant-allowlisted emails skip disposable check (#1075)
## Problem
Signing in as `randy@nomadkaraoke.com` on the Randy Vild portal showed
"We don't support disposable email addresses". `nomadkaraoke.com` had
been **auto-learned into the disposable-domain blocklist**
(`blocklists/config.manual_domains`). Its `verified_clean_domains` entry
dated from 2026-07-04 and has a 7-day TTL. After it expired, an external
API (DeBounce/verifymail) flagged the domain. The result: **every
`@nomadkaraoke.com` magic-link sign-in was rejected.**

## Fix
- **Prod data (already done through the admin API):** removed
`nomadkaraoke.com` from `manual_domains` and added it to
`allowlisted_domains`.
- **Code:**
- New `NEVER_DISPOSABLE_DOMAINS = {"nomadkaraoke.com"}`: a tier-0
short-circuit before any list or API check, and `_auto_learn_domain`
refuses it (and well-known providers).
- On tenant portals, an email the tenant explicitly allowlisted
(`allowed_emails` or an allowed domain) skips the disposable checks,
because an admin vouched for it. Everyone else is still checked.

## Tests
- Regression tests: our domain isn't flagged even when it's blocklisted
and the API says it's disposable; auto-learn refuses it; a
tenant-vouched email skips the check while other emails on the same
portal still get 422.
- `pytest backend/tests --ignore=backend/tests/emulator`: 4940 passed.

No local CodeRabbit review was run, so this PR is left open for the
GitHub bot.

🤖 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**
- Explicitly allowlisted email addresses can now request magic links
even if their domain is flagged as disposable. Other addresses on the
same tenant portal remain subject to the existing check.
- `nomadkaraoke.com` is no longer treated as a disposable domain or
automatically recorded as one.

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

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 02:08:24 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 fe217fda1f kjbox singer search: Gemini fallback with the job flow's catalog tidy + descriptive queries (v0.246.2) (#1065)
## Summary
The Gemini fallback for kjbox's singer song identification (kjbox
`docs/SONG-IDENTIFICATION.md`). kjbox's on-device matcher answers most
searches; this endpoint handles what it can't.

- `POST /api/kjbox/catalog/resolve` now runs `resolve_and_tidy`:
1. One Gemini call (`gemini-3.8-flash`) splits the singer's one-line
query into artist/title and fixes typos.
2. It now also resolves **descriptions**: "that song from titanic" →
Céline Dion — My Heart Will Go On; "is this the real life" → Queen —
Bohemian Rhapsody; "song from top gun" → ambiguous: Danger Zone / Take
My Breath Away / Hold My Hand (live-checked).
3. The chosen song goes through the job flow's own
`judge_match(stage="fast")` catalogue tidy, so formatting matches gen's
job form.
- AI kind `none` keeps its typed split, so kjbox can pre-fill its
make-it form. A failed catalogue pass is returned uncached.
- kjbox calls it only when on-device identification and karaoke search
both found nothing, or when the singer uses "Describe it". It's cached
and rate-limited as before.
- Docs: `docs/API.md` notes that the match judge's corrections are
Gemini in practice (its catalogue pass is exact-match only and decide's
catalogue is prefix-only).

## Tests
- `test_match_judge_free_text.py`: resolve_and_tidy cases, descriptive
prompt coverage
- `TestCatalogResolve`
- Local CodeRabbit: findings fixed, re-review clean.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 06:07:13 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 5a9d0024a5 fix(quick-version): ffmpeg 4.4 never-ending render + fast ONNX model (v0.246.1) (#1074)
## Summary
First production make-it quick version (job `405eed71`, Rihanna "Push Up
On Me") failed with `render timed out`:
- **Render never ended**: the GPU image ships ffmpeg **4.4** (Ubuntu
22.04). With the guide-vocals `amix` in the filtergraph plus the
infinite lavfi colour + looped PNG inputs, it ignores `-shortest` —
reproduced in `ubuntu:22.04`: a 20 s song produced 540 s+ of video until
killed. ffmpeg 8 (local dev) stops fine, which is why local tests
passed. Fix: every input and the output are bounded with `-t <duration>`
(colour source `d=`). Verified in `ubuntu:22.04`: 3.7 s render, exactly
20.0 s audio+video.
- **Quick separation too slow**: the baked roformer took 14 s load + 124
s for a 3:15 song on the L4. Switched to fastgen's
`UVR-MDX-NET-Inst_HQ_4.onnx`. It's downloaded on load until the next GPU
base rebuild bakes it (`download_models.py` `EXTRA_MODELS`), with a
fallback to the baked roformer if the load fails.

Prod timeline observed for that job (for the <4 min goal): job created
05:22:12 → **audio-download-job container took 3m46s to start**
(existing issue, 1m40–4m across recent executions; separate follow-up) →
audio in GCS 05:26:46 → GPU worker started 05:27:10 → quick separation
done 05:29:49 → render hung.

## Testing
- `backend/tests/test_quick_version.py`: 40 pass (new: every stream
bounded to the duration; model fallback; both-fail raises).
- Docker `ubuntu:22.04` ffmpeg 4.4.2 reproduction before/after (see
above).

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

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

## Summary by CodeRabbit

* **New Features**
* Quick audio separation now uses a faster model by default, with an
alternate model available if the primary model cannot be loaded.
* **Bug Fixes**
* Quick video rendering is now limited to the song’s duration, helping
prevent renders from continuing beyond the audio or failing to finish.
* Model loading failures are handled more reliably: if both the primary
and alternate models fail to load, the error is reported.

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

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 01:51:13 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 37f7d578ee kn-data-sync: daily export of the kjbox song-identification index (#1066)
## Summary
After the daily KN `full` refresh, `kn-data-sync` now also exports the
**kjbox song-identification index**: every song a singer might mean.
- **Contents:** `spotify_tracks_normalized` (popularity ≥ 30) FULL OUTER
JOIN `karaokenerds_raw`, deduped on normalised artist+title. About 2.0M
rows: artist, title, popularity (blank = KN-only), karaoke (0/1).
- **Export:** `EXPORT DATA` to
`gs://nomadkaraoke-kn-data/song-id/<run>/songs-*.tsv.gz`, then a
manifest at `song-id/latest.json` naming that run's shards, so a device
never mixes runs. The last 3 runs are kept.
- **Cost and safety:** it's a server-side export; no rows pass through
the function (512M memory is fine). The dry run scans about 160 MB
(~$0.001/day). A failed export is reported in the response and doesn't
fail the KN sync.
- No IAM change: the SA already has project `bigquery.dataEditor` +
`jobUser` and write access to the bucket.

Design and reasoning: kjbox `docs/SONG-IDENTIFICATION.md` (on-device
matcher first, Gemini fallback). The NomadPC side (download → build
`song_id.db`) is in the kjbox PR.

## ⚠️ Deploy (manual, needs GCP write)
1. `infrastructure/functions/kn_data_sync/deploy.sh` (uploads the source
zip)
2. `pulumi up`, or redeploy the function. The source object name doesn't
change, so force the function to pick up the new zip.
3. Optionally trigger it once: `gcloud scheduler jobs run
kn-data-sync-full-daily --location us-central1`, then check
`gs://nomadkaraoke-kn-data/song-id/latest.json`.

## Tests
- `infrastructure/functions/kn_data_sync/test_main.py` (5): manifest
names only this run's shards, prune keeps 3 runs, empty export raises,
full sync survives an export failure, community mode doesn't export. Run
manually (function tests aren't in the repo testpaths).
- The rendered SQL passes a BigQuery dry run.

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

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

## Summary by CodeRabbit

* **New Features**
* Full catalog syncs now generate a song-identification index covering
popular Spotify tracks and KaraokeNerds entries. The index is exported
to cloud storage, with a manifest pointing to the latest run and the
three most recent runs retained.
* **Bug Fixes**
* If index export fails, the catalog sync still completes and reports
the export failure. Community syncs do not generate an index.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 01:48:50 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 3a6e175fbf feat(tenant): fully automatic tenant lifecycle — subdomain provisioning, delete, per-email access (#1072)
## Summary
The admin tenant console now creates and deletes **fully working**
tenants.

- **Create:**
- Provisions `{id}.nomadkaraoke.com` through the Cloudflare API: a Pages
custom domain on `karaoke-gen-tenant` plus a proxied CNAME.
- If a non-tenant DNS record already owns the hostname, create returns
`409` before anything is written.
- If Cloudflare fails, the GCS tenant is rolled back and create returns
`502`.
- The subdomain must be `{id}.nomadkaraoke.com`, because the edge
function and middleware derive the tenant from the first hostname label.
- **Delete:** new `DELETE /api/admin/tenants/{id}` removes the subdomain
(only records that point at the tenant Pages project), the theme (unless
it's the default or shared), the registry entry and the config. Jobs are
kept.
- **Retry/backfill:** new `POST /api/admin/tenants/{id}/domain` is
idempotent.
- **Per-email access:** new `auth.allowed_emails`, alongside domains. If
either list has entries, only listed emails/domains can sign in; both
empty = open. `@nomadkaraoke.com` admins can always sign in; the
docstring already claimed this but the code didn't do it.
- **Admin UI:**
  - domain status badge with set-up/retry
  - access editor with an "anyone can sign in" warning
  - delete that requires typing the tenant id
  - after create, polls until the certificate is live
- **Infra:** secret `cloudflare-tenant-domains-token`. The Pulumi
container is already applied; the value is an account-owned Cloudflare
token scoped to Pages R/W on the account plus DNS R/W on the
nomadkaraoke.com zone only.

## Testing
- New `test_tenant_domain_service.py` runs against a stateful fake
Cloudflare (httpx MockTransport). It covers provisioning, idempotency,
foreign-record conflicts, deprovisioning only our records, API errors
and a missing token.
- Service tests cover:
  - create provisions the domain
  - a DNS conflict or unusable Cloudflare means no writes
  - a provisioning failure means a full rollback
- delete removes everything, aborts if Cloudflare fails, and keeps a
shared theme
  - access-list normalisation and enforcement
- Route tests cover delete (204/404/502), the domain endpoint (200/409),
502 on create, allowed_emails passthrough, and admin-only access.
- Model tests cover individual emails, combined lists, the legacy flag,
and the admin bypass.
- Frontend (Jest) covers access editing, the open-portal warning, domain
set-up, and type-to-confirm delete.
- Results: `pytest backend/tests --ignore=backend/tests/emulator` gives
4927 passed; `jest` gives 1421 passed.

No local CodeRabbit review was run, so this PR is left open for the
GitHub bot. A separate agent review was done before merge.

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

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

* **New Features**
* Tenant creation provisions a portal subdomain, with its setup status
shown in tenant management.
* Admins can retry domain setup and delete tenants after confirming the
tenant ID.
* Tenant access can be restricted to specific email addresses, allowed
email domains, or both. Addresses are normalized, and admin access is
retained.
* **Bug Fixes**
* Email restrictions are enforced for magic-link sign-in even when no
domain allowlist is configured.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 01:26:32 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 13ecce4f79 feat: monitor karaoke-decide lb-refresh job errors (v0.245.4) (#1073)
## Summary
Adds `lb-refresh` (karaoke-decide's new ListenBrainz statistics →
BigQuery Cloud Run Job) to `MONITORED_CLOUD_RUN_JOBS`, so a failed run
or its stale-data ERROR reaches the error monitor and Discord. This
matches what #1067 did for `mb-refresh`.

## Changes
- `backend/services/error_monitor/config.py`: add `lb-refresh`
- `tests/unit/services/error_monitor/test_config.py`: expect 6 jobs and
include `lb-refresh`
- Version 0.245.4

## Testing
- `pytest tests/unit/services/error_monitor/`: 361 passed

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

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 00:54:15 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 849167603a fix(ci-runners): re-dispatch self-hosted jobs stranded in queued (v0.245.4) (#1071)
## Summary
Three merge-to-main runs left `Deploy - Backend` stuck `queued`, and
twice prod was left half-deployed. The dispatcher launches **one** VM
per `workflow_job.queued` webhook and never retries. GitHub never
redelivers a failed webhook.

Root causes found in the dispatcher logs:
- **2026-09-27:** the deploy job's webhook got a **Cloud Run 429 "no
available instance"**. `max_instance_count=5`, and each webhook holds an
instance for up to 90s while it confirms the VM insert, so a CI burst
drops webhooks. 429s went 1/day (9/15) → 7 (9/23) → 15 (9/27).
- **2026-08-08 / 09-25:** the dispatched GPU-family VM was preempted
before it registered, and nothing replaced it.

## Changes
- **Stalled-job re-dispatch** in the scheduled pass, which now runs
every 5 min instead of 15:
- Scans org repos for self-hosted jobs that have been `queued` for 5–60
min.
- Per family, compares queued jobs against spare runners (booting VMs,
including JIT-registered-but-offline ones, plus idle online runners).
  - Launches the shortfall, at most 5 per pass, in parallel.
- Gives up after 60 min, so fleet-wide runner breakage can't turn into a
VM-launch loop.
- `max_instance_count` 5 → 20.
- Scheduler `attempt_deadline` = function timeout (300s), so a slow pass
isn't retried while it is still running.
- Env knobs, including a kill switch: `REDISPATCH_ENABLED`,
`REDISPATCH_AFTER_MINUTES`, `REDISPATCH_GIVE_UP_MINUTES`,
`MAX_REDISPATCH_PER_TICK`.
- Docs: `docs/EPHEMERAL-GHA-RUNNERS.md` § Stalled-job re-dispatch.

## Testing
- `infrastructure/functions/runner_manager/test_ephemeral.py`: 65 pass
(16 new). The new tests cover the dropped-webhook case, the preempted-VM
case, spare capacity per family, booting VMs registered as offline, the
give-up limit, the per-pass cap, the kill switch and error isolation. CI
doesn't run these; they were run locally.
- Ran the real repo scan against GitHub read-only: 28 repos in about
20s.
- `/code-review` (the CodeRabbit CLI has no seat): all 3 findings fixed
in the second commit. The CodeRabbit bot reviews this PR as well.
- `pulumi preview`: the targeted diff is the runner-manager source
object replace, a function update (code + maxInstanceCount) and a
scheduler update (schedule + attempt deadline).

## Deploy (infra deploys are local, not CI)
Run a **targeted** `pulumi up` before merging. The untargeted preview
also includes unrelated pending drift from other work (the
`karaoke-storage` CORS update and the `cloudflare-tenant-domains-token`
secret delete):
```
cd infrastructure && pulumi up --stack prod \
  --target 'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:storage/bucketObject:BucketObject::runner-manager-source' \
  --target 'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:cloudfunctionsv2/function:Function::runner-manager-function' \
  --target 'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:cloudscheduler/job:Job::runner-manager-idle-check'
```


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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 00:43:46 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 cada71a0f2 fix(infra): make karaoke-gen storage bucket private; CORS any origin (#1070)
## Summary
- `public_access_prevention = "enforced"` on
`karaoke-gen-storage-nomadkaraoke`. The out-of-band `allUsers`
objectViewer binding was also removed with `gcloud storage buckets
remove-iam-policy-binding`.
- CORS origins changed to `*`, so tenant subdomains created at runtime
work without a per-tenant list. This is safe now that the bucket is
private: a signed URL or origin-bound resumable session is the auth.
- Docs: ARCHITECTURE tenant runbook, plus a LESSONS-LEARNED entry.

## Audit (why it was public)
- Added by hand on **2025-12-22 06:37 UTC** by admin@ via `gsutil iam
ch`. That's the same minute as commit `92affebd` (Job Inspector HTML
page, `public/job-inspector.html`, the only object under `public/`). It
was never in Pulumi and isn't mentioned in any doc.
- No consumer relied on it. The backend and all Cloud Run jobs, the
encoding VMs, flacfetch, audio-separator, backup-to-aws, decide and CI
all use service accounts with their own grants. Browsers only get V4
signed URLs. kjbox goes through the gen API. No code builds unsigned
bucket URLs, and the last 14 days of logs show no unsigned bucket URLs.
- Known casualties: `public/job-inspector.html` is no longer public, and
the `remote_cli.download_file_via_gsutil` anonymous fallback now returns
False; the primary path is the API download.

## Verification (prod, after local `pulumi up`)
- Anonymous list: **401**; anonymous object GET: **403**
- Signed preview URL from `/api/themes`: **200**; with `Origin:
https://randy-vild.nomadkaraoke.com` it returns
`access-control-allow-origin: *`

No local CodeRabbit review was run, so this PR is left open for the
GitHub bot.

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

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

## Summary by CodeRabbit

* **Security**
* Storage buckets now prevent public access, helping keep customer files
private. Signed URLs continue to provide authorized access.
* **Bug Fixes**
* Mutable JSON uploads avoid stale caching, and reads use the latest
stored version.
* **Documentation**
* Updated setup guidance to reflect current bucket access, CORS, and
caching behavior.

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

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 00:19:18 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 3607ccf745 fix(tenant): theme/tenant edits take effect immediately; no orphan jobs on bad theme (#1069)
## Problem
Creating the `randy-vild` tenant via `/admin/tenants` and
bulk-submitting 2 minutes later failed every row with **"Theme not
found: randy-vild"**, and left 10 orphaned "Waiting for upload" jobs.

Root cause: `karaoke-gen-storage-nomadkaraoke` grants `allUsers`
objectViewer, so GCS serves objects with no explicit Cache-Control as
`public, max-age=3600`. The backend's own reads of
`themes/_metadata.json` returned the **pre-tenant** registry (logged
`Loaded theme metadata: 4 themes` at 03:32:38, although the 5-theme
generation was written at 03:30:40). Theme edits (`style_params.json`,
assets) had the same problem: new jobs could pick up the old style for
up to an hour.

## Fix
- `StorageService.upload_json` writes `Cache-Control: no-store`
- `StorageService.download_json` resolves the live generation
(`get_blob`) and downloads that exact generation, which skips any cached
copy (including objects written before this change)
- tenant theme asset and logo uploads pass `cache_control=no-store`
- `ThemeService.theme_exists` force-refreshes the per-instance 5-min
registry cache on a miss
- all 4 job-creation endpoints validate the theme **before**
`create_job` (no more orphan jobs)
- GCS CORS: add `https://randy-vild.nomadkaraoke.com` (**needs local
`pulumi up` before merge**)
- docs: tenant subdomain runbook + caching note in ARCHITECTURE.md

## Testing
- New/updated unit tests: fresh `download_json` + NotFound, `no-store`
on JSON/asset writes, theme_exists refresh-on-miss, unknown theme
rejected before `create_job`
- `pytest backend/tests --ignore=backend/tests/emulator`: 4888 passed,
36 skipped (emulator tests need a local Firestore emulator, unrelated)

No local CodeRabbit review was run, so this PR is left open for the
GitHub bot.

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

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 00:15:17 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 8a5f754efd ci: remove post-deploy canary + never email test accounts on stale review (v0.245.2) (#1068)
## Summary
- Removes the `deploy-verify` job ("Deploy - Post-Deploy Canary (Happy
Path)") from `ci.yml`, plus the `Detect backend version change` step /
`version_changed` output that only gated it.
- `stale_review_processor`: jobs owned by automated-test accounts
(`is_test_email` — `e2e-test-runner@nomadkaraoke.com`,
`@inbox.testmail.app`) no longer get the 24h reminder, review-expired,
or duration-confirm-expired emails. They are still auto-expired at 48h
so stranded test jobs don't linger.
- Updates comments + `docs/TROUBLESHOOTING.md` / `docs/TESTING.md` that
referenced the canary. Version → 0.245.2.

## Why
The canary created a real production job (piri – dog, as
`e2e-test-runner@nomadkaraoke.com`) on every backend version bump.
`ci.yml` uses `cancel-in-progress: true`, so back-to-back merges
cancelled it mid-run — the process is killed before Playwright's
`afterEach` cleanup runs, stranding the job in `awaiting_review`. The
stale-review processor then emailed the test account (which forwards to
Andrew's inbox) at 24h/48h (e.g. job `adb8f393` from cancelled run
36288893657; earlier `a5f84cc3`, `10b532e2`). The canary was overkill;
the daily E2E and the traffic-gated candidate-revision smoke remain, and
the email guard backstops the daily E2E if it ever strands a job.

## Test plan
- [x] New unit tests: test-account reminder is silent (+ still flagged),
review expiry + duration-confirm expiry cancel without email
- [x] `pytest backend/tests --ignore=backend/tests/emulator` — 4883
passed
- [x] `actionlint` — no new findings

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

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

## Summary by CodeRabbit

* **Chores**
* CI no longer runs a post-deployment production canary or sends its
test results and failure notifications. Candidate-revision smoke testing
remains in place.
* Production real-job verification is handled manually or by the daily
E2E run.
* **Documentation**
* Testing and rollback guidance now reflects the updated verification
and recovery steps. Daily E2E failures are identified as a reason to
roll back.
* **Bug Fixes**
* Automated test accounts no longer receive stale-review reminder or
expiry emails; existing expiry and cancellation handling remains in
place.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 23:37:45 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 5b2a0f8c3e feat(error-monitor): watch decide's mb-refresh job (#1067)
## Summary
- Adds `mb-refresh` (karaoke-decide's new weekly MusicBrainz → BigQuery
Cloud Run Job, nomadkaraoke/karaoke-decide PR to follow) to
`MONITORED_CLOUD_RUN_JOBS`, so failed refreshes and staleness warnings
raise error-monitor patterns / Discord alerts.
- Version bump 0.245.0 → 0.245.1.

## Testing
- `pytest tests/unit/services/error_monitor` — 361 passed (count +
membership assertions updated).

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

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

## Summary by CodeRabbit

* **Reliability**
* The weekly MusicBrainz data refresh is now included in service
monitoring. Issues with the refresh can be detected alongside problems
with other monitored services, improving visibility into the
availability of refreshed music data.
* **Release**
  * This update is version 0.245.1.

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

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 23:07:47 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 87a36bd2a5 feat(encoding): GCP cost cuts — Spot 16-vCPU workers, 3-VM fleet, 5-min idle, gated worker deploys (v0.245.0) (#1061)
## Summary
Approved GCP cost cuts for the encoding pipeline (target: whole project
< $300/mo; encoding VMs were ~$300/mo for ~5-20 jobs/day). Details +
before/after table: `docs/archive/2026-09-26-encoding-cost-cuts.md`.

| | Before | After |
|---|---|---|
| Primary pair a/b | c4d-highcpu-32 on-demand | **c4d-highcpu-16 Spot**
(STOP on preemption) |
| Fallbacks | 8 VMs / 6 families | **1 on-demand**
`encoding-worker-fallback-c2df` (c2d-highcpu-16, us-central1-f) |
| Idle shutdown | 15 min / check every 5 | **5 min / check every 2** |
| CI worker blue-green | every push to main | only when
`infrastructure/encoding-worker/worker_code_paths.txt` paths changed
since the serving version (+ `workflow_dispatch`
`force_encoding_worker_deploy`) |
| Nomad Dropbox upload | whole folder | minus lossless 4K **MP4**
(tenant folders unchanged) |

**Infra already applied locally (targeted Pulumi):** 7 fallback VMs +
disks + 7 static IPs deleted; a/b + c2df resized in place; idle function
env + scheduler updated. The Spot switch was done in place with `gcloud
compute instances set-scheduling` on the stopped VMs + `pulumi refresh`
(pulumi-gcp treats a `scheduling` diff as *replace*, and recreating a
c4d VM risks a stockout). `encoding-worker-fallback-vms` secret → v6
(c2df only). CI's pulumi run should be a no-op for these resources.

### Scope change (per Andrew)
**Task 5 dropped:** review previews stay on the encoding VM
(`USE_GCE_PREVIEW_ENCODING=true` unchanged) and the review-page warmup
is kept, since it deliberately warms the VM for the preview and the
final render. To make sure the new 5-min idle timeout doesn't undermine
that, the review page now also heartbeats **every 2 min** while the tab
is visible and was used in the last 15 min, and re-warms on tab refocus
(`useEncodingWorkerKeepAlive`). Before this, the heartbeat only fired on
lyric edits. The idle checker keeps the routed VM alive while
`last_activity_at` < 5 min, and both warmup and heartbeat write it.
Tests cover both sides.

### Code changes
- **Spot preemption mid-encode**: when a poll fails,
`wait_for_completion` checks the pinned worker VM. If it is
STOPPING/TERMINATED it raises `EncodingJobLostError`, so
`run_with_lost_job_resubmit` resubmits the encode, and that resubmit
restarts the Spot VM or falls back to c2df. Before, the failure showed
up after ~7 min as a "lost contact" error that was not resubmitted.
- **Stale fallback lists**: a candidate VM that no longer exists
(`NotFound`) is skipped instead of aborting the whole failover. This
protects the window before running instances pick up the new secret.
- `SPEED_RANK` is now keyed by machine family, so the ranking is
independent of VM size.
- **Idle-stop vs. in-flight encode** (review follow-up): the idle
function's `/health active_jobs` only counts RUNNING jobs, and
`last_activity_at` was only written when a VM was started. With a 5-min
window, a long encode's VM could be stopped in the seconds between the
job finishing and the next poll. The poll loop now refreshes
`last_activity_at` at most once a minute. A VM seen in
STAGING/PROVISIONING after it accepted a job also counts as lost. CI
`Read Firestore config` now writes empty values instead of "None".
- **Worker deploy gate**:
`backend/tests/test_encoding_worker_code_paths.py` derives the worker's
transitive `backend.*` import set and fails if `worker_code_paths.txt`
doesn't cover it. Every deploy still uploads the wheel and `startup.sh`,
so a cold-booted VM always runs the latest code.
- **Dropbox**: nothing automated reads lossless files from Dropbox. The
lossless **MKV** is still uploaded because the completion email and the
live Fiverr auto-reply bot both tell customers it is in the Dropbox
folder, and the VocalStar tenant expects lossless files. To drop the MKV
as well, update those two texts first, then add the MKV suffix to
`DROPBOX_SKIP_OUTPUT_SUFFIXES`.

## Testing
- New/updated unit tests: preemption → lost job → resubmit, NotFound
candidate skip, family ranking, idle 5-min/heartbeat window, fleet-shape
invariants, worker-path coverage, Dropbox exclusion, keep-alive hook
(Jest, fake timers).
- `pytest backend/tests --ignore=backend/tests/emulator`: 4802 passed.
The only failures are 6 tests that need the spaCy `en_core_web_sm`
model, which isn't installed in my local venv; unrelated to this PR.
- Jest lyrics-review + lib/lyrics-review: 423 passed. Infra tests
(`test_encoding_worker_config.py`, idle function): all pass.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 23:20:54 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 c138c9d1ac feat(review): vocal waveforms for own-instrumental jobs (v0.244.1) (#1062)
## Summary
Jobs with a user-supplied instrumental (`existing_instrumental`) skip
GPU separation. That left the lyrics review **Waveforms** mode with no
vocals stem, so `/vocals-peaks` returned 404 and no strips were drawn.
The waveform only needs a peak envelope, so a CPU approximation is
enough.

- **`backend/services/derived_vocals.py`**: decodes the mix and the
instrumental to mono at 22.05 kHz (ffmpeg). It aligns them by FFT
cross-correlation (numpy, ±2s search), fits a least-squares gain, and
subtracts, leaving roughly the vocals. It writes a FLAC and logs offset,
gain and residual ratio. A few seconds of CPU.
- **Lyrics worker**: for existing-instrumental jobs, runs this in a
thread alongside transcription. It uploads
`jobs/{id}/stems/vocals_derived.flac` and registers
`stems.vocals_derived`, and it's awaited before advancing to screens so
the screens step pre-computes peaks as usual. Best-effort: failures log
and the job continues.
- **`vocals_stem_path`**: adds `vocals_derived` as the last-resort key.
It's waveform-only: deliverable stems, the original-vocals guide and the
auto-approval timing gate don't read it.

## Testing
`backend/tests/test_derived_vocals.py` covers:
- offset recovery for positive, negative and large lags
- gain and vocals recovery on synthetic signals
- an unrelated instrumental leaving the mix intact
- a real ffmpeg round trip (24-bit stereo WAVs → mono 22.05 kHz FLAC)
- stem precedence (never overrides real separated vocals)
- worker upload and registration, plus the non-fatal failure path

The full backend unit suite passes in an isolated venv (4812 passed).
The only exceptions are 6 tests needing the spaCy `en_core_web_sm`
model, which isn't installed in that venv; CI has it.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 23:04:15 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 8cbcc03099 infra: GCP cost cuts (VPC connector, min-instances, Autoclass, weekly incremental git backup, hourly error monitor, PITR off) (#1063)
## Summary
These are the cost cuts Andrew approved to get the whole GCP project
under $300/mo. Performance compromises were accepted.

- **VPC connector removed.** `cloud-run-connector` only existed to reach
the old flacfetch GCE VM's private IP. flacfetch now runs on Netcup
behind a public HTTPS URL. I checked every URL secret the backend uses
and none are private IPs. The backend is detached with
`--clear-vpc-connector`: just dropping the `--vpc-connector` flag from
`gcloud run deploy` would keep the old setting. `audio-download-job` and
`bulk-search-job` no longer set `vpc_access`. Saves ~$12/mo plus the
Network Intelligence resource-hours.
- **`karaoke-backend` min-instances 2 → 1** (ci.yml).
- **Autoclass** on `karaoke-gen-storage-nomadkaraoke` (terminal
NEARLINE, because customers re-download old jobs) and on
`nomadkaraoke-divebar-files` (terminal ARCHIVE). Autoclass charges no
retrieval or early-deletion fees.
- **backup-to-aws**
- **Git bundles:** now weekly (Sundays) and incremental. A repo is
re-bundled only when its GitHub `pushed_at` is newer than its bundle's
S3 `LastModified` minus a 1h lag, so S3 itself is the state store. Every
repo is re-bundled on the first Sunday of each month.
`?mode=git_repos[&full=1]` runs the git step alone.
- **Bug fix:** since #997 every S3 **overwrite** has failed. The
`backup-writer` IAM user has no `s3:GetObject`, so HEAD on an existing
key returns 403. Git bundles and the manifest were stuck at 09-15, and
the DR freshness monitor has been red every day. The existence check now
uses `ListObjectsV2`.
- **`gcs_sync`:** detects changes by `time_created` instead of
`updated`. Autoclass transitions bump `updated`, which would have made
the sync re-copy every object and pull it back to Standard.
- **DR freshness monitor:** `git-repos/` is now judged on
`manifest.json` (192h) plus a check of the manifest's contents.
- **Error monitor:** runs hourly instead of every 15 min. Lookback is 60
min, equal to the interval, so there are no gaps or double counts.
`MAX_LOG_ENTRIES` goes from 500 to 2000.
- **Firestore PITR disabled.** The nightly export to GCS staging
remains, plus the weekly copy to S3.
- **`recover-stuck-downloads` / `retry-pending-render-jobs`:** every 5 →
10 min. Both are recovery sweeps with ~10-min stall thresholds.
- Docs updated: DISASTER-RECOVERY (PITR restore replaced, git RPO,
incident write-up), ARCHITECTURE, LESSONS-LEARNED,
GCP-COST-OPTIMIZATION, TROUBLESHOOTING.

**Kept:** the `audio-separator` GPU service. Its request logs show ~40
external `/separate` calls/month from remote-CLI users. It's already
min-instances 0.

## Already applied to prod (before merge)
- `gcloud run services update karaoke-backend --clear-vpc-connector
--min-instances 1`, same image. Health is OK, and
`/api/health/flacfetch` and `/api/health/encoding-worker` are both OK
without the connector.
- Targeted `pulumi up` on the Firestore DB, both buckets, both jobs and
both 5-min schedulers.
- backup-to-aws redeployed with `deploy.sh`. A manual `?mode=git_repos`
run bundled 13 of 121 repos (106 unchanged, 2 skipped) and uploaded 120
files with 0 errors.
- Deleted `gs://…/backups/flacfetch-torrent-backup-20260122-1931.tar.gz`
(1 GB).

## After merge
Targeted `pulumi up` for `error-monitor-scheduler`, which must wait for
the image with LOOKBACK=60, then delete the connector and drop the
`vpcaccess` API service from state (`disable_on_destroy=False`, so the
API itself stays enabled).

## Tests
`make test` passes locally. The backup_to_aws function tests (43,
including new incremental, list-based-existence and gcs_sync tests) were
run separately because CI doesn't run them.

Related: nomadkaraoke/karaoke-decide#140 (ARCHIVE lifecycle on
`nomadkaraoke-data`, already applied).

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

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

## Summary by CodeRabbit

* **Updates**
* Pending-render retries and stuck-download recovery now run every 10
minutes instead of every 5 minutes.
  * Error monitoring now runs hourly and checks a 60-minute window.
* Cloud Run candidate deployments use one minimum instance instead of
two and no longer use a VPC connector.

* **Backups and Recovery**
* Git repository backups now run weekly, with monthly full refreshes and
incremental updates between them.
* Firestore point-in-time recovery is disabled; recovery uses nightly
exports.
  * Storage buckets now use automatic storage-class management.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 22:59:06 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 7179e2863f ci: move test/package jobs to GitHub-hosted runners; GPU base image same-region (cost) (#1059)
## Summary
GCP cost cuts in CI (approved):

1. **GitHub-hosted runners for test/package jobs** (~\$28/mo of
`gha-general-*` VMs, ~390 VMs/30d). Moved to `ubuntu-latest` (free,
public repo): `package-unit-tests`, `package-integration-tests`,
`package-build-test`, `backend-unit-tests`, `backend-emulator-tests`,
`package-build` (main), `frontend-e2e-full` (label-gated). None used GCP
auth. Self-hosted disk checks replaced by a free-disk-space step (drop
dotnet/android/ghc/CodeQL); venv cache keys renamed so self-hosted venvs
aren't restored onto a different interpreter path.
2. **Removed `propagate-base-image`** — pre-pulled the base image onto
"the 3 runners"; runners are now single-use ephemeral VMs so this just
spawned 3 VMs per base rebuild for nothing.
3. **AR inter-region egress** (~\$12-16/mo): the GPU app image was built
on a us-central1 runner `FROM` the ~13 GB GPU base in **us-east4**,
pulling it cross-region on every deploy. The GPU base + all BuildKit
caches now live in us-central1 `karaoke-repo`; only the final app image
is pushed to us-east4 (`karaoke-backend-gpu`) where
`audio-separation-job` pulls it same-region. Push uploads only the small
changed app layers (base layer digests are identical). First deploy
copies the current base from us-east4 via `buildx imagetools create`
(byte-identical, no from-scratch rebuild); falls back to a rebuild only
if that fails.
4. `build-runner-images.yml`: `KEEP_IMAGES_PER_FAMILY` 2 → 1
(GPU/windows images are 15-21 GiB).
5. `ci.yml` changes now trigger the package/backend test jobs (so this
PR exercises the moved jobs).

`deploy-backend` stays on the `docker-build` GCE runner (Docker builds,
WIF, same-region AR). GPU runners untouched.

## Testing
- This PR's CI runs the moved jobs on hosted runners.
- `image_hash` helper + `imagetools create` cross-registry copy verified
locally against two `registry:2` instances (copy wraps in a single-entry
index; helper follows it).
- actionlint: no new findings (fewer than before).

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

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

* **Chores**
* CI test, package, and frontend end-to-end jobs now run on
GitHub-hosted runners. GPU image builds use a centralized base-image
cache, while application images continue to be published in their
existing region.
* Runner image cleanup retains the newest image per family; images
backing existing disks remain protected.
* **Documentation**
* Updated the runner guide to describe which jobs use hosted or
self-hosted runners and how image retention works.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 22:34:09 -04:00
Andrew Beveridge ☄️ 7ebe929d71 feat: quick scrolling-lyrics version for kjbox make-it jobs (v0.244.0) (#1064)
## Summary
kjbox singer "make it" jobs take ~30 min. For kjbox jobs (`X-Client-Id:
kjbox*`) the audio worker now also produces a rough **scrolling-lyrics
draft video** within a few minutes of the audio landing, so the singer
can choose to sing right away (kjbox side: nomadkaraoke/kjbox PR to
follow).

- **Quick separation** — one fast single-model pass
(`mel_band_roformer_instrumental_fv7z_gabox.ckpt`, already baked in the
GPU image, MDXC overlap 2; `QUICK_VERSION_MODEL` override) on the warm
L4 **before** the ensemble.
- **Background render** (`backend/services/quick_version/`, ported from
kjbox `fastgen/`) while the ensemble runs: LRCLIB lyrics (synced →
time-anchored scroll; plain → constant crawl; none → title card), PIL
crawl PNG + one ffmpeg overlay pass, 854×480, vocals mixed back at 30%
as a guide.
- Uploads `jobs/{id}/quick/quick.mp4` → `file_urls.quick.video_mp4`;
`state_data.quick_version = {status, lyrics_tier, ready_at, timings…}`.
- The worker joins the render (≤300 s) before temp-dir cleanup, even if
the ensemble fails. Quick-version failures never fail the job. Skipped
on retries once `ready`, in remote-API mode, or with
`KJBOX_QUICK_VERSION_ENABLED=false`.
- No new endpoint: kjbox polls `GET /api/jobs/{id}` and downloads
`/api/jobs/{id}/download/quick/video_mp4`.

Plan: workspace
`docs/archive/2026-09-26-make-it-quick-fastgen-version-plan.md`.

## Testing
- `backend/tests/test_quick_version.py` (37): lyrics parsing/LRCLIB
fallbacks, layout + scroll expression, ffmpeg cmd, real PIL+ffmpeg
render (skips without ffmpeg), gating, separator params/output
detection, render thread success/failure, audio-worker wiring (join on
ensemble failure, timeout → failed, remote mode skips).
- Full backend suite: 4831 passed.
- Local real runs: Fv7z single-model separation produced both stems with
the custom names; ABBA "Waterloo" rendered in ~9 s (LRCLIB synced).
- Not yet measured in prod: GPU job cold start + L4 quick-separation
time — first thing to check after deploy.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-09-26 22:24:03 -04:00
116 changed files with 6550 additions and 1072 deletions

No files matched your search

+3 -2
View File
@@ -14,7 +14,8 @@ name: Build GHA Runner Images
# 3. Stop the VM, snapshot its boot disk to a new image in the `gha-runner-<variant>`
# image family with name gha-runner-<variant>-<timestamp>.
# 4. Delete the build VM (boot disk auto-deletes).
# 5. Delete older images in the family, keeping the newest 2 (rollback = previous month).
# 5. Delete older images in the family, keeping only the newest (GPU/windows images
# are 15-21 GiB each; roll back by re-running this workflow at an older ref).
on:
workflow_dispatch:
@@ -41,7 +42,7 @@ env:
BUILD_REGION: us-central1
BUILD_ZONE: us-central1-a
BASE_IMAGE: projects/debian-cloud/global/images/family/debian-12
KEEP_IMAGES_PER_FAMILY: 2
KEEP_IMAGES_PER_FAMILY: 1
jobs:
resolve-matrix:
+247 -389
View File
@@ -7,6 +7,15 @@ on:
branches: [main]
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
inputs:
force_encoding_worker_deploy:
# Manual override for the encoding-worker deploy gate (see "Decide
# encoding-worker deploy" in deploy-backend). Dispatch on main re-runs
# package-build + deploy-backend; with this ticked the GCE worker is
# blue-green redeployed even if no worker code changed.
description: "Force a blue-green redeploy of the GCE encoding worker"
type: boolean
default: false
permissions:
contents: write
@@ -51,6 +60,9 @@ jobs:
- 'infrastructure/**'
deps:
- 'poetry.lock'
# CI config changes (runners, setup steps) must exercise the
# package/backend test jobs they affect.
- '.github/workflows/ci.yml'
- name: Summary
run: |
@@ -179,7 +191,7 @@ jobs:
frontend-e2e-full:
name: "Frontend - E2E Full"
runs-on: [self-hosted, linux, gcp]
runs-on: ubuntu-latest
needs: changes
# Full E2E suite only runs when PR has 'e2e' label (on-demand)
if: >-
@@ -187,23 +199,6 @@ jobs:
needs.changes.outputs.frontend == 'true' &&
contains(github.event.pull_request.labels.*.name, 'e2e')
steps:
- name: Check disk space
run: |
echo "Checking disk space..."
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "Current disk usage: ${USAGE}%"
if [ "$USAGE" -gt 70 ]; then
echo "Disk usage high, running cleanup..."
docker system prune -af || true
docker builder prune -af || true
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "After cleanup: ${USAGE}%"
fi
if [ "$USAGE" -gt 85 ]; then
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
exit 1
fi
- uses: actions/checkout@v4
- name: Setup Node.js with caching
@@ -334,25 +329,23 @@ jobs:
package-unit-tests:
name: "Package - Unit Tests (70% coverage)"
runs-on: [self-hosted, linux, gcp]
runs-on: ubuntu-latest
needs: changes
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
steps:
- name: Check disk space
- name: Free disk space (only if low)
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
# the rm takes ~1 min.
run: |
echo "Checking disk space..."
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "Current disk usage: ${USAGE}%"
if [ "$USAGE" -gt 70 ]; then
echo "Disk usage high, running cleanup..."
docker system prune -af || true
docker builder prune -af || true
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "After cleanup: ${USAGE}%"
fi
if [ "$USAGE" -gt 85 ]; then
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
exit 1
df -h /
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
if [ "$AVAIL_GB" -lt 30 ]; then
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
df -h /
fi
- uses: actions/checkout@v4
@@ -374,9 +367,9 @@ jobs:
uses: actions/cache@v4
with:
path: .venv
key: venv-package-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
key: venv-package-hosted-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
restore-keys: |
venv-package-${{ runner.os }}-py3.13-
venv-package-hosted-${{ runner.os }}-py3.13-
- name: Install dependencies
run: poetry install --with dev
@@ -420,25 +413,23 @@ jobs:
package-integration-tests:
name: "Package - Integration Tests"
runs-on: [self-hosted, linux, gcp]
runs-on: ubuntu-latest
needs: changes
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
steps:
- name: Check disk space
- name: Free disk space (only if low)
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
# the rm takes ~1 min.
run: |
echo "Checking disk space..."
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "Current disk usage: ${USAGE}%"
if [ "$USAGE" -gt 70 ]; then
echo "Disk usage high, running cleanup..."
docker system prune -af || true
docker builder prune -af || true
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "After cleanup: ${USAGE}%"
fi
if [ "$USAGE" -gt 85 ]; then
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
exit 1
df -h /
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
if [ "$AVAIL_GB" -lt 30 ]; then
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
df -h /
fi
- uses: actions/checkout@v4
@@ -460,9 +451,9 @@ jobs:
uses: actions/cache@v4
with:
path: .venv
key: venv-package-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
key: venv-package-hosted-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
restore-keys: |
venv-package-${{ runner.os }}-py3.13-
venv-package-hosted-${{ runner.os }}-py3.13-
- name: Install dependencies
run: poetry install --with dev
@@ -497,7 +488,7 @@ jobs:
package-build-test:
name: "Package - Build & Install (Test)"
runs-on: [self-hosted, linux, gcp]
runs-on: ubuntu-latest
needs: [changes, package-unit-tests, package-integration-tests]
if: >-
github.ref != 'refs/heads/main' && always() &&
@@ -505,21 +496,19 @@ jobs:
(needs.package-integration-tests.result == 'success' || needs.package-integration-tests.result == 'skipped') &&
(needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
steps:
- name: Check disk space
- name: Free disk space (only if low)
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
# the rm takes ~1 min.
run: |
echo "Checking disk space..."
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "Current disk usage: ${USAGE}%"
if [ "$USAGE" -gt 70 ]; then
echo "Disk usage high, running cleanup..."
docker system prune -af || true
docker builder prune -af || true
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "After cleanup: ${USAGE}%"
fi
if [ "$USAGE" -gt 85 ]; then
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
exit 1
df -h /
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
if [ "$AVAIL_GB" -lt 30 ]; then
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
df -h /
fi
- uses: actions/checkout@v4
@@ -577,25 +566,23 @@ jobs:
backend-unit-tests:
name: "Backend - Unit Tests"
runs-on: [self-hosted, linux, gcp]
runs-on: ubuntu-latest
needs: changes
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
steps:
- name: Check disk space
- name: Free disk space (only if low)
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
# the rm takes ~1 min.
run: |
echo "Checking disk space..."
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "Current disk usage: ${USAGE}%"
if [ "$USAGE" -gt 70 ]; then
echo "Disk usage high, running cleanup..."
docker system prune -af || true
docker builder prune -af || true
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "After cleanup: ${USAGE}%"
fi
if [ "$USAGE" -gt 85 ]; then
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
exit 1
df -h /
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
if [ "$AVAIL_GB" -lt 30 ]; then
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
df -h /
fi
- name: Checkout code
@@ -618,9 +605,9 @@ jobs:
uses: actions/cache@v4
with:
path: .venv
key: venv-backend-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
key: venv-backend-hosted-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
restore-keys: |
venv-backend-${{ runner.os }}-py3.13-
venv-backend-hosted-${{ runner.os }}-py3.13-
- name: Install dependencies
run: poetry install
@@ -648,25 +635,23 @@ jobs:
backend-emulator-tests:
name: "Backend - Emulator Integration Tests"
runs-on: [self-hosted, linux, gcp]
runs-on: ubuntu-latest
needs: changes
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
steps:
- name: Check disk space
- name: Free disk space (only if low)
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
# the rm takes ~1 min.
run: |
echo "Checking disk space..."
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "Current disk usage: ${USAGE}%"
if [ "$USAGE" -gt 70 ]; then
echo "Disk usage high, running cleanup..."
docker system prune -af || true
docker builder prune -af || true
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "After cleanup: ${USAGE}%"
fi
if [ "$USAGE" -gt 85 ]; then
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
exit 1
df -h /
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
if [ "$AVAIL_GB" -lt 30 ]; then
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
df -h /
fi
- name: Checkout code
@@ -689,9 +674,9 @@ jobs:
uses: actions/cache@v4
with:
path: .venv
key: venv-backend-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
key: venv-backend-hosted-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
restore-keys: |
venv-backend-${{ runner.os }}-py3.13-
venv-backend-hosted-${{ runner.os }}-py3.13-
- name: Set up Java 21 (required by Firestore emulator)
uses: actions/setup-java@v4
@@ -847,24 +832,22 @@ jobs:
package-build:
name: "Package - Build"
runs-on: [self-hosted, linux, gcp]
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
steps:
- name: Check disk space
- name: Free disk space (only if low)
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
# the rm takes ~1 min.
run: |
echo "Checking disk space..."
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "Current disk usage: ${USAGE}%"
if [ "$USAGE" -gt 70 ]; then
echo "Disk usage high, running cleanup..."
docker system prune -af || true
docker builder prune -af || true
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "After cleanup: ${USAGE}%"
fi
if [ "$USAGE" -gt 85 ]; then
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
exit 1
df -h /
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
if [ "$AVAIL_GB" -lt 30 ]; then
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
df -h /
fi
- uses: actions/checkout@v4
@@ -886,9 +869,9 @@ jobs:
uses: actions/cache@v4
with:
path: .venv
key: venv-package-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
key: venv-package-hosted-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
restore-keys: |
venv-package-${{ runner.os }}-py3.13-
venv-package-hosted-${{ runner.os }}-py3.13-
- name: Set up Node.js
uses: actions/setup-node@v4
@@ -1105,16 +1088,13 @@ jobs:
name: "Deploy - Backend (Cloud Run)"
needs: [package-build]
runs-on: [self-hosted, linux, gcp, docker-build]
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
permissions:
contents: read
id-token: write
outputs:
base_rebuilt: ${{ steps.check-base.outputs.needs_rebuild }}
version: ${{ steps.version_check.outputs.version }}
# R1: gates the post-deploy canary — "true" only when the backend version
# actually changed (see "Detect backend version change" step).
version_changed: ${{ steps.version_changed.outputs.changed }}
env:
REGISTRY: us-central1-docker.pkg.dev
PROJECT_ID: nomadkaraoke
@@ -1170,43 +1150,6 @@ jobs:
echo "📋 Current version: $VERSION"
echo "🚀 Deploying on every push to main"
# R1 gate — only run the post-deploy functional canary when the BACKEND
# version actually changed. A frontend-/docs-/infra-only merge still runs
# deploy-backend (image rebuild) but ships an identical version; a real
# karaoke generation is slow + resource-heavy, so we short-circuit the
# canary in that case. We compare the version we're about to ship against
# the version currently served by production.
- name: Detect backend version change
id: version_changed
run: |
NEW_VERSION="${{ steps.version_check.outputs.version }}"
# Read the currently-serving version via the EDGE (api.nomadkaraoke.com),
# NOT the raw Cloud Run origin URL, and retry. The single un-retried
# origin probe returned empty on #987 (cold start on the scaled-to-zero
# prior revision and/or origin edge-auth on the detailed endpoint), so
# the gate fail-opened and ran the canary on a no-bump deploy — which
# then flake-failed and paged. The edge URL is warm (real traffic) and
# Cloudflare-fronted, so it returns the version reliably.
CURRENT_VERSION=""
for attempt in 1 2 3 4; do
CURRENT_VERSION=$(curl -sf --connect-timeout 5 --max-time 25 \
"https://api.nomadkaraoke.com/api/health/detailed" | jq -r '.version // empty' 2>/dev/null || echo "")
[ -n "$CURRENT_VERSION" ] && break
echo " version probe attempt $attempt/4 empty; retrying…"
sleep 5
done
echo "Currently-serving version: ${CURRENT_VERSION:-<unknown>}"
echo "New version: $NEW_VERSION"
if [ -n "$CURRENT_VERSION" ] && [ "$CURRENT_VERSION" = "$NEW_VERSION" ]; then
echo "changed=false" >> "$GITHUB_OUTPUT"
echo "↩️ Backend version unchanged — post-deploy canary will be SKIPPED."
else
# Unknown current version (first deploy / unreachable after retries) →
# run the canary to be safe rather than skip a potentially real change.
echo "changed=true" >> "$GITHUB_OUTPUT"
echo "✅ Backend version changed (or current unknown) — post-deploy canary will RUN."
fi
- name: Capture build metadata
id: build-meta
run: |
@@ -1315,7 +1258,9 @@ jobs:
for key in ["primary_vm", "primary_ip", "primary_version",
"secondary_vm", "secondary_ip",
"active_override_vm", "active_override_ip", "active_override_zone"]:
f.write(f"{key}={data.get(key, '')}\n")
# `or ''`: a key stored as null must be empty, not the string
# "None" (which later steps would treat as a real VM name).
f.write(f"{key}={data.get(key) or ''}\n")
f.write(f"deploy_in_progress={str(data.get('deploy_in_progress', False)).lower()}\n")
# capacity_state is a map — emit as single-line JSON so the green
# selection step can demote recently-stocked-out machine types.
@@ -1324,8 +1269,47 @@ jobs:
f"active_override={data.get('active_override_vm')}")
PYEOF
# Gate the blue-green worker deploy on worker-affecting changes. It boots a
# fresh green VM + runs a real test encode, which used to happen on EVERY
# push to main (~5x/day) even for frontend/backend-only changes. The wheel,
# startup.sh and version.txt above are still uploaded every time, so any
# worker that cold-boots (they idle-stop after 5 min) runs the latest code.
# Diff base = the version the serving worker was last validated at (not
# github.event.before), so a cancelled/skipped deploy can never lose a
# worker change. Any doubt → deploy (fail open).
- name: Decide encoding-worker deploy
id: worker_gate
env:
FORCE: ${{ github.event_name == 'workflow_dispatch' && inputs.force_encoding_worker_deploy == true }}
SERVING_VERSION: ${{ steps.config.outputs.primary_version }}
OVERRIDE_VM: ${{ steps.config.outputs.active_override_vm }}
run: |
mapfile -t PATHS < <(grep -v '^\s*#' infrastructure/encoding-worker/worker_code_paths.txt | grep -v '^\s*$')
DEPLOY=true
if [ "$FORCE" = "true" ]; then
REASON="manual override (workflow_dispatch force_encoding_worker_deploy)"
elif [ -n "$OVERRIDE_VM" ] && [ "$OVERRIDE_VM" != "None" ]; then
REASON="capacity override $OVERRIDE_VM is serving — refresh it"
elif [ -z "$SERVING_VERSION" ] || [ "$SERVING_VERSION" = "None" ]; then
REASON="serving worker version unknown"
elif ! git fetch --no-tags --depth=1 origin "refs/tags/v${SERVING_VERSION}:refs/tags/v${SERVING_VERSION}"; then
REASON="tag v${SERVING_VERSION} not fetchable"
elif ! CHANGED=$(git diff --name-only "v${SERVING_VERSION}" HEAD -- "${PATHS[@]}"); then
REASON="git diff against v${SERVING_VERSION} failed"
elif [ -z "$CHANGED" ]; then
DEPLOY=false
REASON="no worker-affecting changes since serving v${SERVING_VERSION}"
else
REASON="worker-affecting changes since v${SERVING_VERSION}"
echo "Changed worker paths:"; echo "$CHANGED" | head -50
fi
echo "deploy=${DEPLOY}" >> "$GITHUB_OUTPUT"
echo "Encoding-worker blue-green deploy: ${DEPLOY} (${REASON})"
echo "### Encoding worker deploy: ${DEPLOY}" >> "$GITHUB_STEP_SUMMARY"
echo "${REASON}" >> "$GITHUB_STEP_SUMMARY"
- name: Wait for concurrent deploy
if: steps.config.outputs.deploy_in_progress == 'true'
if: steps.worker_gate.outputs.deploy == 'true' && steps.config.outputs.deploy_in_progress == 'true'
run: |
echo "Another deploy is in progress, waiting..."
python3 << 'PYEOF'
@@ -1344,6 +1328,7 @@ jobs:
PYEOF
- name: Set deploy in progress
if: steps.worker_gate.outputs.deploy == 'true'
run: |
python3 << 'PYEOF'
from datetime import datetime, timezone
@@ -1364,6 +1349,7 @@ jobs:
# infrastructure/encoding-worker/deploy_promote.py.
- name: Select & start green target
id: green
if: steps.worker_gate.outputs.deploy == 'true'
# Never hard-fail the whole backend deploy just because no encoding
# worker could be validated — emit green_ok=false and let the gated
# health/encode/promote steps skip while the Cloud Run deploy proceeds.
@@ -1604,7 +1590,7 @@ jobs:
# always() so the deploy_in_progress flag is ALWAYS cleared, even when the
# green step found no worker (its downstream steps skip, but the flag was
# already set). Skips only on a fully successful promote (passed == true).
if: always() && steps.encode-test.outputs.passed != 'true'
if: always() && steps.worker_gate.outputs.deploy == 'true' && steps.encode-test.outputs.passed != 'true'
run: |
GREEN_VM="${{ steps.green.outputs.green_vm }}"
GREEN_ZONE="${{ steps.green.outputs.green_zone }}"
@@ -1745,7 +1731,7 @@ jobs:
# step guarantees the lock is released so the next deploy doesn't stall 10 min
# in "Wait for concurrent deploy". Idempotent with the other clears.
- name: Clear encoding-worker deploy lock
if: always()
if: always() && steps.worker_gate.outputs.deploy == 'true'
run: |
python3 -c "
from google.cloud import firestore
@@ -1881,8 +1867,16 @@ jobs:
# ============================================
# GPU Image Build (for audio worker with L4 GPU)
# Same pattern as base image: hash check → rebuild if needed
# GPU image lives in us-east4 (co-located with GPU instances)
# Same pattern as base image: hash check → rebuild if needed.
#
# Region layout (cost): the ~13 GB GPU base image and all BuildKit
# caches live in us-central1 (karaoke-repo), next to this runner, so
# building the app layer on top of the base is same-region (free). Only
# the FINAL app image is pushed to us-east4 (karaoke-backend-gpu), where
# the audio-separation Cloud Run job pulls it same-region. That push only
# uploads the small changed app layers — the base layers already exist
# there. Previously the base lived in us-east4 and every deploy pulled
# ~13 GB across regions (~$12-16/mo AR inter-region egress).
# ============================================
- name: Calculate GPU base image hash
@@ -1898,33 +1892,74 @@ jobs:
- name: Check if GPU base image exists and is current
id: check-gpu-base
run: |
GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
EXISTING_HASH=""
WANT_HASH="${{ steps.gpu-base-hash.outputs.hash }}"
GPU_BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
# Legacy location (pre cost-fix). Only used to seed us-central1 once.
LEGACY_GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
MANIFEST=$(docker manifest inspect $GPU_BASE_IMAGE 2>/dev/null || echo "")
CONFIG_DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
# Read the base.content.hash label of an image without pulling it
# (manifest ~1KB + config blob ~10KB).
image_hash() {
local image="$1" host path manifest digest
host="${image%%/*}"
path="${image#*/}"
path="${path%:*}"
manifest=$(docker manifest inspect "$image" 2>/dev/null || echo "")
# `buildx imagetools create` (the one-time copy below) wraps the
# image in a single-entry index — follow it to the image manifest.
local child
child=$(echo "$manifest" | jq -r '.manifests[0].digest // ""' 2>/dev/null || echo "")
if [ -n "$child" ] && [ "$child" != "null" ]; then
manifest=$(docker manifest inspect "${image%:*}@${child}" 2>/dev/null || echo "")
fi
digest=$(echo "$manifest" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
if [ -z "$digest" ] || [ "$digest" = "null" ]; then
echo ""
return
fi
curl -sL -H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://${host}/v2/${path}/blobs/${digest}" 2>/dev/null \
| jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo ""
}
if [ -n "$CONFIG_DIGEST" ] && [ "$CONFIG_DIGEST" != "null" ] && [ "$CONFIG_DIGEST" != "" ]; then
echo "📋 Found GPU manifest, config digest: $CONFIG_DIGEST"
TOKEN=$(gcloud auth print-access-token)
CONFIG_JSON=$(curl -sL -H "Authorization: Bearer $TOKEN" \
"https://${{ env.GPU_REGISTRY }}/v2/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}/blobs/$CONFIG_DIGEST" 2>/dev/null)
EXISTING_HASH=$(echo "$CONFIG_JSON" | jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo "")
echo "📋 Registry GPU base image hash: $EXISTING_HASH"
else
echo "⚠️ No existing GPU base image found in registry - will build"
fi
EXISTING_HASH=$(image_hash "$GPU_BASE_IMAGE")
echo "📋 Registry GPU base image hash (us-central1): ${EXISTING_HASH:-<none>}"
if [ "${{ steps.gpu-base-hash.outputs.hash }}" != "$EXISTING_HASH" ]; then
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or pyproject.toml changed)"
echo " Current: ${{ steps.gpu-base-hash.outputs.hash }}"
echo " Registry: $EXISTING_HASH"
echo "needs_rebuild=true" >> $GITHUB_OUTPUT
else
if [ -n "$EXISTING_HASH" ] && [ "$EXISTING_HASH" = "$WANT_HASH" ]; then
echo "✅ GPU base image is up to date"
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# One-time migration: if the legacy us-east4 base is already current,
# copy it byte-for-byte (same digests) instead of rebuilding from
# scratch, so the image content is unchanged by the move.
LEGACY_HASH=$(image_hash "$LEGACY_GPU_BASE_IMAGE")
echo "📋 Legacy GPU base image hash (us-east4): ${LEGACY_HASH:-<none>}"
if [ -n "$LEGACY_HASH" ] && [ "$LEGACY_HASH" = "$WANT_HASH" ]; then
echo "📦 Copying current GPU base from us-east4 to us-central1 (one-time)..."
if timeout 30m docker buildx imagetools create --tag "$GPU_BASE_IMAGE" "$LEGACY_GPU_BASE_IMAGE"; then
echo "✅ GPU base copied to us-central1"
# imagetools wraps the image in a single-entry index; tag the
# child manifest too so AR's delete-untagged cleanup policy can
# never treat it as an orphan.
CHILD=$(docker manifest inspect "$GPU_BASE_IMAGE" | jq -r '.manifests[0].digest // ""' || echo "")
if [ -n "$CHILD" ]; then
gcloud artifacts docker tags add "${GPU_BASE_IMAGE%:*}@${CHILD}" \
"${GPU_BASE_IMAGE%:*}:content-${WANT_HASH:0:12}" --quiet \
|| echo "⚠️ Could not tag child manifest (non-fatal)"
fi
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
exit 0
fi
echo "⚠️ Copy failed — falling back to a rebuild"
fi
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or poetry.lock changed)"
echo " Current: $WANT_HASH"
echo " Registry: $EXISTING_HASH"
echo "needs_rebuild=true" >> "$GITHUB_OUTPUT"
- name: Build and push GPU base image (if needed)
if: steps.check-gpu-base.outputs.needs_rebuild == 'true'
timeout-minutes: 45
@@ -1934,10 +1969,10 @@ jobs:
file: backend/Dockerfile.gpu-base
push: true
tags: |
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
build-args: |
BUILD_DATE=${{ github.run_id }}
BUILD_ID=${{ github.sha }}
@@ -1945,20 +1980,25 @@ jobs:
provenance: false
- name: Build and push GPU app image
timeout-minutes: 10
# Normally ~2 min (only app layers are new). After a GPU base rebuild
# this push also uploads the ~13 GB base layers to us-east4 (they can't
# be cross-mounted from the us-central1 registry), hence the headroom.
timeout-minutes: 40
uses: docker/build-push-action@v6
with:
context: .
file: backend/Dockerfile
push: true
# Final image → us-east4 (same region as the audio-separation job).
tags: |
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:latest
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
# Base + cache → us-central1 (same region as this runner).
build-args: |
BASE_IMAGE=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
BASE_IMAGE=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/karaoke-backend-gpu:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/karaoke-backend-gpu:cache,mode=max,ignore-error=true
provenance: false
# ============================================
@@ -1977,8 +2017,8 @@ jobs:
# smoke fails we simply don't migrate: traffic stays on the prior revision,
# so a bad revision serves 0% instead of 100% (auto-revert by default).
# NOTE: this protects only the Cloud Run *service*. The Cloud Run *jobs*
# updated below cannot traffic-split, so they still rely on R1's real-job
# post-deploy canary + the codified `scripts/rollback.sh` (R2).
# updated below cannot traffic-split, so they rely on the daily E2E run +
# the codified `scripts/rollback.sh` (R2).
- name: Deploy to Cloud Run (candidate revision, no traffic)
id: deploy_candidate
run: |
@@ -2004,9 +2044,11 @@ jobs:
# that but overshot once the loop was made non-blocking: every burst
# forced scale-out, and each overflow request waited out a ~16s app
# cold start (2026-09-22 16-tab test: warm instance served in 1.2s,
# freshly-spawned ones in 16-19s). 32 + --min-instances 2 gives 64
# warm slots so a 16-tab reload is absorbed without cold starts,
# while staying far below the wedge-era 80.
# freshly-spawned ones in 16-19s). 32 + --min-instances 2 gave 64
# warm slots; min-instances was cut to 1 on 2026-09-26 (GCP cost cut,
# accepted perf trade-off: big bursts may hit a ~15s cold start) while
# staying far below the wedge-era 80. --clear-vpc-connector: the
# serverless VPC connector was deleted (flacfetch is public now).
gcloud run deploy karaoke-backend \
--image $IMAGE \
--no-traffic \
@@ -2022,9 +2064,8 @@ jobs:
--timeout 1800 \
--concurrency 32 \
--max-instances 20 \
--min-instances 2 \
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--min-instances 1 \
--clear-vpc-connector \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
@@ -2080,9 +2121,9 @@ jobs:
- name: Update Cloud Run Jobs with new image
# NOTE: Cloud Run *Jobs* cannot traffic-split or canary — this is an
# image-only, all-or-nothing update picked up on each job's next
# invocation. There is no per-revision smoke here; the jobs rely on R1's
# post-deploy real-job canary and the codified `scripts/rollback.sh` (R2)
# for recovery if a bad image reaches them.
# invocation. There is no per-revision smoke here; the jobs rely on the
# daily E2E run and the codified `scripts/rollback.sh` (R2) for recovery
# if a bad image reaches them.
run: |
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
GPU_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}"
@@ -2172,189 +2213,6 @@ jobs:
echo "📊 Built on self-hosted GCP runner (200GB SSD, no disk space issues)"
echo " Runner: gcp-runner with 4 vCPU, 16GB RAM"
# ============================================
# R1 — POST-DEPLOY FUNCTIONAL CANARY (version-change-gated)
# Runs the real production happy-path (admin-credit variant, no Stripe) after
# a backend deploy — but ONLY when the backend version actually changed
# (deploy-backend.outputs.version_changed == 'true'). A frontend-/docs-/
# infra-only merge ships an identical backend version and short-circuits here,
# so we don't burn encode-VM time + a real Drive/YouTube publish on a no-op.
# On failure: the workflow fails loudly (Discord) — this is where an operator
# invokes `scripts/rollback.sh` (R2) to revert the service + jobs.
# ============================================
deploy-verify:
name: "Deploy - Post-Deploy Canary (Happy Path)"
needs: [deploy-backend]
runs-on: ubuntu-latest
timeout-minutes: 90
if: >-
github.ref == 'refs/heads/main' && github.event_name == 'push' &&
needs.deploy-backend.result == 'success' &&
needs.deploy-backend.outputs.version_changed == 'true'
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Install Playwright browsers
working-directory: frontend
run: npx playwright install --with-deps chromium
- name: Create test-results directory
working-directory: frontend
run: mkdir -p test-results
- name: Ensure testmail.app domain is allowlisted
run: |
curl -sf -X POST \
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
-H "Content-Type: application/json" \
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
# Admin-credit variant: impersonate the E2E test runner (which holds
# admin-granted credits) instead of going through Stripe. Same token-refresh
# pattern as e2e-daily.yml's use_test_token path.
- name: Refresh E2E session token
id: refresh_token
run: |
RESPONSE=$(curl -sf --connect-timeout 5 --max-time 30 -X POST \
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
-H "Content-Type: application/json")
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
echo "::add-mask::$TOKEN"
echo "token=$TOKEN" >> $GITHUB_OUTPUT
- name: Run post-deploy happy-path canary
id: run_test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token }}
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
run: |
echo "=== Post-deploy canary: happy path against production ==="
echo "Deployed version: ${{ needs.deploy-backend.outputs.version }}"
echo "Time: $(date)"
# --retries=2: the happy-path has inherently flaky UI waits (e.g. the
# review page's "proceed to instrumental" enable), and this canary
# PAGES on failure — a single flaky attempt must not cry wolf. Only a
# failure that survives 2 retries is treated as real.
npx playwright test happy-path-real-user.spec.ts \
--config=playwright.production.config.ts \
--project=chromium \
--reporter=list \
--retries=2 \
--timeout=3600000 \
2>&1 | tee test-output-canary.log
# Capture Playwright's real exit code, not tee's (0). Matches
# e2e-daily.yml's rationale (grepping the log is fragile).
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Check canary result
id: test_result
run: |
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
echo "result=success" >> "$GITHUB_OUTPUT"
else
echo "result=failure" >> "$GITHUB_OUTPUT"
fi
- name: Upload canary artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: deploy-verify-canary-${{ github.run_number }}
path: |
frontend/test-results/
frontend/playwright-report/
frontend/test-output-canary.log
retention-days: 30
- name: Discord notification (canary failed)
if: steps.test_result.outputs.result == 'failure'
run: |
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"🚨 Post-deploy canary FAILED (v${{ needs.deploy-backend.outputs.version }})\", \"description\": \"The production happy-path failed AFTER deploying v${{ needs.deploy-backend.outputs.version }}. The service already migrated 100% traffic to the new revision — consider rolling back with scripts/rollback.sh.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}" || echo "Discord notify failed (non-fatal)"
- name: Fail if canary failed
if: steps.test_result.outputs.result == 'failure'
run: |
echo "::error::Post-deploy canary failed for v${{ needs.deploy-backend.outputs.version }}."
echo "Roll back now with:"
echo " scripts/rollback.sh --list # find the previous good revision + version"
echo " scripts/rollback.sh --to-revision <PREV_REV> --image-version <PREV_VERSION>"
exit 1
# ============================================
# PROPAGATE BASE IMAGE TO ALL RUNNERS
# When base image is rebuilt, pull it to all 3 runners
# so subsequent app builds don't wait 8 min for the pull
#
# NOTE: This is best-effort distribution. GitHub Actions doesn't
# support targeting specific runners by name, so we spawn 3 jobs
# and rely on the scheduler to distribute them across idle runners.
# In practice, with all runners idle after deploy-backend, distribution
# is good. Runners that miss this pull will get the image on their
# next app build (with the 8 min delay).
# ============================================
propagate-base-image:
name: "Propagate Base Image (${{ matrix.runner_index }})"
needs: deploy-backend
if: github.ref == 'refs/heads/main' && github.event_name == 'push' && needs.deploy-backend.outputs.base_rebuilt == 'true'
runs-on: [self-hosted, linux, gcp]
permissions:
contents: read
id-token: write
strategy:
matrix:
# 3 parallel jobs - one per self-hosted runner
runner_index: [1, 2, 3]
max-parallel: 3
fail-fast: false # Don't cancel other runners if one fails
env:
REGISTRY: us-central1-docker.pkg.dev
PROJECT_ID: nomadkaraoke
REPOSITORY: karaoke-repo
BASE_IMAGE_NAME: karaoke-backend-base
steps:
- name: Authenticate to Google Cloud (Workload Identity)
uses: google-github-actions/auth@v2
with:
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- name: Set up Cloud SDK
uses: google-github-actions/setup-gcloud@v2
with:
version: "latest"
- name: Configure Docker for Artifact Registry
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
- name: Pull latest base image
run: |
BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest"
RUNNER_NAME=$(hostname)
echo "📥 Pulling latest base image on runner $RUNNER_NAME..."
docker pull $BASE_IMAGE
echo "✅ Base image cached on $RUNNER_NAME"
# NOTE: Pulumi infrastructure deploys are done locally, not in CI.
# CI runners run on the infrastructure Pulumi manages, creating a circular
# dependency. Always run `pulumi up` locally before merging infra PRs.
+21 -4
View File
@@ -55,21 +55,25 @@ jobs:
BUCKET = os.environ["BUCKET"]
# (label, prefix, max_age_hours, require_suffix)
# require_suffix: only objects with this key suffix count toward
# freshness (None = any object). git-repos/ requires ".bundle" so the
# always-written manifest.json can't mark the prefix fresh when every
# bundle failed / nothing was bundled — 0 bundles then reads as stale.
# freshness (None = any object).
# NOTE: Firestore and BigQuery export to GCS staging nightly but are
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
# sees the S3 (off-site) copy, so their limits must allow a full week
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
# files and secrets DO upload to S3 nightly, so they stay at 36h.
# Git repos are also weekly (Sundays) AND incremental since
# 2026-09-26 — only repos pushed that week get a fresh bundle, so a
# quiet week legitimately leaves every .bundle older than 8 days.
# Freshness is judged on git-repos/manifest.json instead (rewritten
# every weekly run), and the manifest's contents are checked below so
# a run where every repo failed still reads as stale.
TARGETS = [
("Firestore", "firestore/", 192, None),
("GCS job files", "gcs/job-files/", 36, None),
("Encrypted secrets", "secrets/", 36, None),
("BigQuery weekly", "bigquery/daily-refresh/", 192, None),
("Git repos", "git-repos/", 36, ".bundle"),
("Git repos", "git-repos/manifest.json", 192, None),
]
s3 = boto3.client("s3")
@@ -97,6 +101,19 @@ jobs:
line = f"{label}: {age_h}h old (limit {max_hours}h) — last {latest.isoformat()}"
(stale if age > max_hours * 3600 else ok).append(line)
# Git manifest contents: ANY bundle error alerts, even though the
# manifest itself is fresh. The git step is weekly + incremental, so
# a repo that failed keeps an ever-older S3 bundle until the next
# Sunday — silence here would let it drift past the 7-day RPO.
try:
import json as _json
m = _json.loads(s3.get_object(Bucket=BUCKET, Key="git-repos/manifest.json")["Body"].read())
if int(m.get("errors", 0)) > 0:
failed = [r.get("full_name") for r in m.get("repos", []) if r.get("status") == "error"]
stale.append(f"Git repos: last run had {m.get('errors')} bundle errors: {', '.join(failed[:10])}")
except Exception as e: # noqa: BLE001
stale.append(f"Git repos: could not read manifest.json ({e})")
summary = ["## DR backup freshness", ""]
if stale:
summary.append("### Stale")
+6 -3
View File
@@ -149,9 +149,12 @@ 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
The worker is a **Spot** c4d-highcpu-16 blue-green primary pair (`encoding-worker-a`/`-b`,
us-central1-c) plus ONE stopped on-demand fallback (`encoding-worker-fallback-c2df`,
c2d-highcpu-16, us-central1-f) — 3 VMs since 2026-09-26. Idle VMs stop after 5 min.
CI blue-green redeploys the worker only when worker code changed
(`infrastructure/encoding-worker/worker_code_paths.txt`); force it via Actions → CI →
Run workflow → "Force a blue-green redeploy of the GCE encoding worker". 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
+18
View File
@@ -376,6 +376,20 @@ ALLOWED_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}
ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
def _require_theme_exists(theme_id: Optional[str], locale: str) -> None:
"""Reject an unknown theme BEFORE the job document is created.
``_prepare_theme_for_job`` runs after ``create_job``; if the theme lookup
failed there, the request 400'd but left an orphaned PENDING job behind
(e.g. a tenant bulk submit right after the tenant was created).
"""
if theme_id and not get_theme_service().theme_exists(theme_id):
raise HTTPException(
status_code=400,
detail=t(locale, "fileUpload.invalidTheme", theme_id=theme_id)
)
def _prepare_theme_for_job(
job_id: str,
theme_id: str,
@@ -714,6 +728,7 @@ async def upload_and_create_job(
# UI language the job was submitted in (admin-only signal)
locale=get_full_locale_from_request(request),
)
_require_theme_exists(effective_theme_id, locale)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
@@ -1304,6 +1319,7 @@ async def create_job_with_upload_urls(
# UI language the job was submitted in (admin-only signal)
locale=get_full_locale_from_request(request),
)
_require_theme_exists(effective_theme_id, locale)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
@@ -1997,6 +2013,7 @@ async def create_job_from_url(
# UI language the job was submitted in (admin-only signal)
locale=get_full_locale_from_request(request),
)
_require_theme_exists(effective_theme_id, locale)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
@@ -2304,6 +2321,7 @@ async def create_finalise_only_job(
# UI language the job was submitted in (admin-only signal)
locale=get_full_locale_from_request(request),
)
_require_theme_exists(effective_theme_id, locale)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
+1 -1
View File
@@ -450,7 +450,7 @@ async def system_status(
# 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
# (…-fallback-c2df), 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
+2 -2
View File
@@ -797,7 +797,7 @@ async def retry_pending_render_jobs(
"""
Auto-retry jobs parked in RENDER_PENDING_CAPACITY.
Called every 5 minutes by Cloud Scheduler. When the GCE encoding worker
Called every 10 minutes by Cloud Scheduler. When the GCE encoding worker
can't be started because the zone is exhausted, the render worker parks
the job in this state instead of failing it. This endpoint re-attempts
the render — when GCE has capacity, the start succeeds and the job
@@ -954,7 +954,7 @@ async def recover_stuck_jobs(
"""
Detect and recover jobs stuck in a processing status.
Called by Cloud Scheduler (every 5 minutes) or manually from admin.
Called by Cloud Scheduler (every 10 minutes) or manually from admin.
- DOWNLOADING_AUDIO stuck >10 min:
* torrent sources (RED/OPS) → park into DOWNLOAD_PENDING_RETRY and keep
auto-retrying for up to 24h (handles rare tracks with intermittent
+1
View File
@@ -1839,6 +1839,7 @@ DOWNLOAD_FILENAME_SUFFIXES = {
"txt_zip": " (Final Karaoke TXT).zip",
"with_vocals_mp4": " (With Vocals).mp4",
"with_vocals": " (With Vocals).mkv", # legacy: raw MKV from render step
"video_mp4": " (Quick Version).mp4", # file_urls.quick — kjbox make-it draft
}
+8 -6
View File
@@ -443,12 +443,14 @@ async def catalog_resolve(body: ResolveRequest, _secret: str = Depends(require_k
"""Split + auto-correct a singer's free-text song search.
kjbox calls this only when its own catalogue search found nothing, then
re-searches with the canonical artist/title and shows "Corrected to … —
you typed … Undo" (gen's AudioSourceStep correction, for the singer
search box). Response = the match judge verdict shape + typed_artist /
typed_title. Never 5xx on model trouble: kind "none".
shows gen's AudioSourceStep "Tidied to … / keep what I typed" (re-searching
when the song changed, and pre-filling its generate form). The AI splits the
one-line query; the job flow's judge_match catalog pass then tidies it, so
the canonical artist/title match what gen's own job form would use.
Response = the match judge verdict shape + typed_artist / typed_title.
Never 5xx on model trouble: kind "none".
"""
from backend.services.match_judge.free_text import _none, resolve_free_text
from backend.services.match_judge.free_text import _none, resolve_and_tidy
query = " ".join(body.query.split())
if not query:
@@ -464,7 +466,7 @@ async def catalog_resolve(body: ResolveRequest, _secret: str = Depends(require_k
return hit
if not _resolve_budget_ok():
raise HTTPException(status_code=429, detail="rate_limited")
verdict = await resolve_free_text(query)
verdict = await resolve_and_tidy(query)
if verdict.get("reason") != "unavailable": # don't cache transient failures
with _resolve_lock:
if len(_resolve_cache) >= _RESOLVE_CACHE_MAX:
+58 -4
View File
@@ -13,6 +13,7 @@ import logging
from typing import Any, Dict, List, Optional, Tuple
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
from fastapi.concurrency import run_in_threadpool
from pydantic import BaseModel, ValidationError
from backend.api.dependencies import require_admin
@@ -23,11 +24,15 @@ from backend.services.tenant_admin_service import (
IMAGE_CONTENT_TYPES,
TenantConflictError,
TenantNotFoundError,
TenantProvisioningError,
TenantValidationError,
create_tenant,
delete_tenant,
get_default_style_params,
get_tenant_detail,
get_tenant_domain_status,
list_tenants,
provision_tenant_domain,
update_tenant,
)
@@ -48,6 +53,7 @@ class TenantSummary(BaseModel):
subdomain: Optional[str] = None
is_active: bool = True
locked_theme: Optional[str] = None
theme_id: Optional[str] = None
dropbox_path: Optional[str] = None
created_at: Optional[str] = None
@@ -60,6 +66,9 @@ class TenantCreateResponse(BaseModel):
tenant: TenantPublicConfig
preview_url: str
subdomain_url: str
# Cloudflare state of the portal subdomain: {hostname, state, dns_ok, pages_status}.
# state is "active" once the certificate is issued (usually within ~1 min).
domain: Optional[Dict[str, Any]] = None
class TenantDetailResponse(BaseModel):
@@ -68,6 +77,11 @@ class TenantDetailResponse(BaseModel):
style_params: Dict[str, Any]
assets: List[str]
preview_url: str
domain: Optional[Dict[str, Any]] = None
class TenantDomainResponse(BaseModel):
domain: Dict[str, Any]
class TenantTemplateResponse(BaseModel):
@@ -168,14 +182,47 @@ async def admin_tenant_theme_template(auth_data: AuthResult = Depends(require_ad
raise HTTPException(status_code=500, detail=str(exc))
# Sync handlers: FastAPI runs them in its threadpool, so the blocking GCS and
# Cloudflare calls don't stall the event loop (the admin UI polls this).
@router.get("/{tenant_id}", response_model=TenantDetailResponse)
async def admin_get_tenant(tenant_id: str, auth_data: AuthResult = Depends(require_admin)):
def admin_get_tenant(tenant_id: str, auth_data: AuthResult = Depends(require_admin)):
"""Return a tenant's full config, theme style_params, and asset list for editing."""
try:
detail = get_tenant_detail(tenant_id)
except TenantNotFoundError as exc:
raise HTTPException(status_code=404, detail=str(exc))
return TenantDetailResponse(preview_url=_preview_url(tenant_id), **detail)
return TenantDetailResponse(
preview_url=_preview_url(tenant_id),
domain=get_tenant_domain_status(tenant_id),
**detail,
)
@router.post("/{tenant_id}/domain", response_model=TenantDomainResponse)
def admin_provision_tenant_domain(tenant_id: str, auth_data: AuthResult = Depends(require_admin)):
"""(Re)provision the tenant's {id}.nomadkaraoke.com subdomain (idempotent)."""
try:
domain = provision_tenant_domain(tenant_id)
except TenantNotFoundError as exc:
raise HTTPException(status_code=404, detail=str(exc))
except TenantConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc))
except TenantProvisioningError as exc:
raise HTTPException(status_code=502, detail=str(exc))
logger.info(f"Admin {auth_data.user_email or 'admin:unknown'} provisioned domain for tenant '{tenant_id}'")
return TenantDomainResponse(domain=domain)
@router.delete("/{tenant_id}", status_code=204)
def admin_delete_tenant(tenant_id: str, auth_data: AuthResult = Depends(require_admin)):
"""Delete a tenant: subdomain (Cloudflare), theme, and config. Jobs are kept."""
try:
delete_tenant(tenant_id)
except TenantNotFoundError as exc:
raise HTTPException(status_code=404, detail=str(exc))
except TenantProvisioningError as exc:
raise HTTPException(status_code=502, detail=str(exc))
logger.info(f"Admin {auth_data.user_email or 'admin:unknown'} deleted tenant '{tenant_id}'")
@router.put("/{tenant_id}", response_model=TenantUpdateResponse)
@@ -205,7 +252,8 @@ async def admin_update_tenant(
logo_image = await _read_image(logo, "logo")
try:
updated = update_tenant(
updated = await run_in_threadpool(
update_tenant,
tenant_id,
config_updates=config_updates,
style_params=style,
@@ -236,6 +284,7 @@ async def admin_create_tenant(
tenant_id: Optional[str] = Form(None),
subdomain: Optional[str] = Form(None),
allowed_email_domains: Optional[str] = Form(None),
allowed_emails: Optional[str] = Form(None),
artist_color: Optional[str] = Form(None),
title_color: Optional[str] = Form(None),
sung_lyrics_color: Optional[str] = Form(None),
@@ -282,11 +331,13 @@ async def admin_create_tenant(
raise HTTPException(status_code=400, detail="style_params must be a JSON object.")
try:
config = create_tenant(
config = await run_in_threadpool(
create_tenant,
name=name,
tenant_id=_clean(tenant_id),
subdomain=_clean(subdomain),
allowed_email_domains=_parse_domains(allowed_email_domains),
allowed_emails=_parse_domains(allowed_emails),
colors=colors,
style_params_override=style_override,
tagline=_clean(tagline),
@@ -300,6 +351,8 @@ async def admin_create_tenant(
raise HTTPException(status_code=409, detail=str(exc))
except TenantValidationError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except TenantProvisioningError as exc:
raise HTTPException(status_code=502, detail=str(exc))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc: # pragma: no cover - defensive
@@ -313,4 +366,5 @@ async def admin_create_tenant(
tenant=TenantPublicConfig.from_config(config),
preview_url=_preview_url(config.id),
subdomain_url=config.get_frontend_url(),
domain=await run_in_threadpool(get_tenant_domain_status, config.id),
)
+11 -3
View File
@@ -239,7 +239,15 @@ async def send_magic_link(
locale = get_locale_from_request(http_request)
if email_validation.is_disposable_domain(email):
# On a tenant portal, an address the tenant explicitly allowlisted (by email
# or domain) was vouched for by an admin — don't second-guess it with the
# disposable-domain heuristics (external APIs have false positives).
request_tenant_config = get_tenant_config_from_request(http_request)
tenant_vouched = bool(
request_tenant_config and request_tenant_config.is_explicitly_allowlisted(email)
)
if not tenant_vouched and email_validation.is_disposable_domain(email):
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
raise HTTPException(
status_code=422,
@@ -298,9 +306,9 @@ async def send_magic_link(
tenant_config = get_tenant_config_from_request(http_request)
# Validate email domain for tenant if configured
if tenant_config and tenant_config.auth.allowed_email_domains:
if tenant_config:
if not tenant_config.is_email_allowed(email):
logger.warning(f"Email domain not allowed for tenant {tenant_id}: {_mask_email(email)}")
logger.warning(f"Email not allowed for tenant {tenant_id}: {_mask_email(email)}")
# Return success anyway to prevent email enumeration
return SendMagicLinkResponse(
status="success",
+13
View File
@@ -326,6 +326,19 @@ class Settings(BaseSettings):
default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")
default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")
# Output files NOT uploaded to Nomad's own Dropbox folders (DEFAULT_DROPBOX_PATH /
# DEFAULT_PRIVATE_DROPBOX_PATH), as "|"-separated filename suffixes. They stay in
# GCS (job-page downloads, YouTube upload, AWS backup) — this only saves the
# multi-GB internet egress + upload time. Tenant Dropbox folders are exempt
# (B2B tenants expect the full set). Default skips only the lossless 4K MP4,
# which no customer-facing text promises in Dropbox. The lossless MKV IS promised
# there (completion email + the Fiverr bot), so add
# " (Final Karaoke Lossless 4k).mkv" only after updating those.
# See docs/archive/2026-09-26-encoding-cost-cuts.md.
dropbox_skip_output_suffixes: str = os.getenv(
"DROPBOX_SKIP_OUTPUT_SUFFIXES", " (Final Karaoke Lossless 4k).mp4"
)
# YouTube Data API v3 Quota Configuration
# Daily quota limit (YouTube grants 10,000 units/day by default)
youtube_quota_daily_limit: int = int(os.getenv("YOUTUBE_QUOTA_DAILY_LIMIT", "10000"))
+32 -6
View File
@@ -117,6 +117,10 @@ class TenantAuth(BaseModel):
default_factory=list,
description="Email domains allowed for magic link auth (e.g., ['vocal-star.com'])"
)
allowed_emails: List[str] = Field(
default_factory=list,
description="Individual email addresses allowed for magic link auth (e.g. a client's gmail)"
)
require_email_domain: bool = Field(
True,
description="If true, only allowed domains can sign up. If false, domains get auto-approved."
@@ -160,18 +164,40 @@ class TenantConfig(BaseModel):
# Default pattern: {tenant_id}@nomadkaraoke.com
return f"{self.id}@nomadkaraoke.com"
def is_explicitly_allowlisted(self, email: str) -> bool:
"""True if the email is named in allowed_emails or matches an allowed domain."""
email_lower = (email or "").strip().lower()
if email_lower in [e.strip().lower() for e in self.auth.allowed_emails]:
return True
return any(email_lower.endswith(f"@{d.lower()}") for d in self.auth.allowed_email_domains)
def is_email_allowed(self, email: str) -> bool:
"""Check if an email address is allowed for this tenant."""
if not self.auth.allowed_email_domains:
# No domain restrictions
"""Check if an email address may sign in to this tenant's portal.
- Nomad Karaoke admins (admin email domain) can always sign in.
- No allowlist at all (no domains, no emails) = open portal.
- Otherwise only an ``allowed_emails`` entry or a matching domain is
allowed. (``require_email_domain`` is vestigial: any non-empty
allowlist is always enforced.)
"""
from backend.services.auth_service import is_admin_email # avoid import cycle
email_lower = (email or "").strip().lower()
if is_admin_email(email_lower):
return True
email_lower = email.lower()
for domain in self.auth.allowed_email_domains:
allowed_emails = [e.strip().lower() for e in self.auth.allowed_emails]
domains = self.auth.allowed_email_domains
if not allowed_emails and not domains:
return True
if email_lower in allowed_emails:
return True
for domain in domains:
if email_lower.endswith(f"@{domain.lower()}"):
return True
return not self.auth.require_email_domain
return False
class TenantPublicConfig(BaseModel):
+7 -1
View File
@@ -18,6 +18,10 @@ logger = logging.getLogger(__name__)
# Presets to bake into the GPU image
PRESETS_TO_DOWNLOAD = ["instrumental_clean", "karaoke"]
# Individual models baked in addition to the presets.
# UVR-MDX-NET-Inst_HQ_4.onnx: the kjbox make-it "quick version" separation
# (backend/services/quick_version/service.py).
EXTRA_MODELS = ["UVR-MDX-NET-Inst_HQ_4.onnx"]
def download_preset_models(model_dir: str) -> None:
@@ -34,7 +38,9 @@ def download_preset_models(model_dir: str) -> None:
for preset_name in PRESETS_TO_DOWNLOAD:
models_to_download.update(presets[preset_name]["models"])
logger.info(f"Downloading {len(models_to_download)} models for presets: {PRESETS_TO_DOWNLOAD}")
models_to_download.update(EXTRA_MODELS)
logger.info(f"Downloading {len(models_to_download)} models for presets {PRESETS_TO_DOWNLOAD} + {EXTRA_MODELS}")
for model in sorted(models_to_download):
logger.info(f" Downloading: {model}")
sep = Separator(model_file_dir=model_dir)
+159
View File
@@ -0,0 +1,159 @@
"""
Approximate vocals for jobs where the user supplied their own instrumental.
Those jobs skip GPU separation, so there is no vocals stem and the lyrics review
"Waveforms" mode had nothing to draw. The waveform only needs a peak envelope,
so a cheap CPU estimate is enough: vocals ≈ mix − gain × instrumental, after
aligning the instrumental to the mix by cross-correlation.
The result is registered as ``stems.vocals_derived`` — used ONLY for the review
waveform (see backend/utils/stems.py). It is never shipped as a deliverable stem
or used for the original-vocals guide, since it can contain residue when the
instrumental isn't from the same master as the mix.
Runs inside the lyrics worker (4Gi, shared with transcription), so memory is
bounded: alignment correlates a fixed-length excerpt, not the whole track, and
very long inputs are skipped.
"""
import logging
import subprocess
from dataclasses import dataclass
from typing import Optional
import numpy as np
logger = logging.getLogger(__name__)
# Waveform-only use: mono at 22.05 kHz keeps a 5-minute song ~26 MB as float32.
SAMPLE_RATE = 22050
# Encoder delay / leading silence differences are small; search ±2s.
MAX_LAG_SECONDS = 2.0
# Alignment excerpt length — plenty to lock onto, and keeps the FFT tiny.
ALIGN_WINDOW_SECONDS = 60.0
# Bound memory on the shared worker: skip absurdly long inputs (mashups, DJ sets).
MAX_DURATION_SECONDS = 20 * 60
# Minimum usable decode.
MIN_DURATION_SECONDS = 1.0
# residual energy / mix energy above this = the instrumental didn't cancel
# (different master, big offset, edited mix). Showing that as "vocals" would
# just be the full-mix envelope and mislead timing edits, so don't register it.
MAX_USEFUL_RESIDUAL_RATIO = 0.85
FFMPEG_TIMEOUT_SECONDS = 120
class DerivedVocalsError(RuntimeError):
pass
@dataclass
class DerivationResult:
offset_samples: int
gain: float
# residual energy / mix energy. With a same-master instrumental this is
# roughly the vocals' share of the mix; near 1.0 means the subtraction
# removed little (the waveform is then ≈ the mix).
residual_ratio: float
@property
def useful(self) -> bool:
return self.residual_ratio <= MAX_USEFUL_RESIDUAL_RATIO
def _run_ffmpeg(args: list, input_bytes: Optional[bytes] = None) -> bytes:
try:
proc = subprocess.run(
["ffmpeg", "-nostdin", "-v", "error", *args],
input=input_bytes, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
timeout=FFMPEG_TIMEOUT_SECONDS, check=True,
)
except subprocess.CalledProcessError as e:
stderr = (e.stderr or b"").decode(errors="replace").strip()[-500:]
raise DerivedVocalsError(f"ffmpeg failed (exit {e.returncode}): {stderr}") from e
except subprocess.TimeoutExpired as e:
raise DerivedVocalsError(f"ffmpeg timed out after {FFMPEG_TIMEOUT_SECONDS}s") from e
return proc.stdout
def _decode_mono(path: str, sample_rate: int = SAMPLE_RATE) -> np.ndarray:
"""Decode any audio file to mono float32 at sample_rate via ffmpeg."""
raw = _run_ffmpeg(["-i", path, "-t", str(MAX_DURATION_SECONDS + 1), "-ac", "1",
"-ar", str(sample_rate), "-f", "f32le", "-"])
samples = np.frombuffer(raw, dtype=np.float32).copy()
seconds = len(samples) / sample_rate
if seconds < MIN_DURATION_SECONDS:
raise DerivedVocalsError(f"decoded only {seconds:.2f}s of audio from {path}")
if seconds > MAX_DURATION_SECONDS:
raise DerivedVocalsError(f"audio longer than {MAX_DURATION_SECONDS // 60} min; skipping")
return samples
def _encode_flac(samples: np.ndarray, out_path: str, sample_rate: int = SAMPLE_RATE) -> None:
peak = float(np.max(np.abs(samples))) if samples.size else 0.0
if peak > 1.0:
samples = samples / peak
_run_ffmpeg(["-y", "-f", "f32le", "-ar", str(sample_rate), "-ac", "1", "-i", "-",
"-c:a", "flac", out_path], input_bytes=samples.astype(np.float32).tobytes())
def find_offset(mix: np.ndarray, inst: np.ndarray, max_lag: int,
window: int = int(ALIGN_WINDOW_SECONDS * SAMPLE_RATE)) -> int:
"""Lag (samples) that best aligns inst to mix: mix[n] ≈ inst[n - lag].
Correlates a `window`-sample excerpt of the mix (from a quarter of the way
in, past intros) against the matching instrumental span ±max_lag, so memory
and time are independent of track length.
"""
window = max(1, min(window, len(mix)))
start = min(len(mix) // 4, len(mix) - window)
excerpt = mix[start: start + window].astype(np.float64)
# Instrumental span covering every candidate lag, zero-padded where it runs
# off either end: seg[j] = inst[start - max_lag + j].
seg = np.zeros(window + 2 * max_lag, dtype=np.float64)
lo = start - max_lag
src_lo, src_hi = max(0, lo), min(len(inst), lo + len(seg))
if src_hi > src_lo:
seg[src_lo - lo: src_hi - lo] = inst[src_lo:src_hi]
# c[k] = Σ_j excerpt[j] · seg[j + k] for k in [0, 2·max_lag] ⇒ lag = max_lag − k
size = 1 << (len(seg) + window - 1).bit_length()
corr = np.fft.irfft(np.conj(np.fft.rfft(excerpt, size)) * np.fft.rfft(seg, size), size)
k = int(np.argmax(corr[: 2 * max_lag + 1]))
return max_lag - k
def subtract_instrumental(mix: np.ndarray, inst: np.ndarray, sample_rate: int = SAMPLE_RATE):
"""Return (residual, DerivationResult) with inst aligned + gain-matched to mix."""
lag = find_offset(mix, inst, int(MAX_LAG_SECONDS * sample_rate), int(ALIGN_WINDOW_SECONDS * sample_rate))
aligned = np.zeros_like(mix)
if lag >= 0:
src = inst[: max(0, len(mix) - lag)]
aligned[lag: lag + len(src)] = src
else:
src = inst[-lag: -lag + len(mix)]
aligned[: len(src)] = src
denom = float(np.dot(aligned, aligned))
gain = float(np.dot(mix, aligned) / denom) if denom > 0 else 0.0
residual = mix - gain * aligned
mix_energy = float(np.dot(mix, mix))
ratio = float(np.dot(residual, residual) / mix_energy) if mix_energy > 0 else 1.0
return residual, DerivationResult(offset_samples=lag, gain=gain, residual_ratio=ratio)
def derive_vocals_file(mix_path: str, instrumental_path: str, out_path: str) -> DerivationResult:
"""Compute approximate vocals; write a FLAC (mono, 22.05 kHz) only if useful.
Raises DerivedVocalsError on decode/encode problems. Check ``result.useful``
before registering the output — nothing is written when it's False.
"""
mix = _decode_mono(mix_path)
inst = _decode_mono(instrumental_path)
residual, result = subtract_instrumental(mix, inst)
logger.info(
"Derived vocals: offset=%d samples (%.1f ms) gain=%.3f residual_ratio=%.3f useful=%s",
result.offset_samples, 1000 * result.offset_samples / SAMPLE_RATE, result.gain,
result.residual_ratio, result.useful,
)
if result.useful:
_encode_flac(residual, out_path)
return result
+42 -3
View File
@@ -12,7 +12,7 @@ import json
import logging
import os
import re
from typing import Optional
from typing import Optional, Sequence, Tuple
from google.cloud import secretmanager
@@ -249,13 +249,20 @@ class DropboxService:
)
cursor.offset = file_obj.tell()
def upload_folder(self, local_dir: str, remote_path: str) -> None:
def upload_folder(
self,
local_dir: str,
remote_path: str,
exclude_suffixes: Sequence[str] = (),
) -> None:
"""
Recursively upload all files and subdirectories to Dropbox folder.
Args:
local_dir: Local directory to upload
remote_path: Dropbox destination folder path
exclude_suffixes: Filename suffixes to skip (see
dropbox_skip_suffixes_for). Skipped files stay on local disk / GCS.
"""
# Ensure remote path starts with /
if not remote_path.startswith("/"):
@@ -264,6 +271,7 @@ class DropboxService:
logger.info(f"Uploading folder {local_dir} to {remote_path}")
uploaded_count = 0
skipped_count = 0
for root, _dirs, files in os.walk(local_dir):
# Calculate the relative path from local_dir to current root
rel_root = os.path.relpath(root, local_dir)
@@ -273,12 +281,19 @@ class DropboxService:
current_remote = f"{remote_path}/{rel_root}"
for filename in files:
if exclude_suffixes and filename.endswith(tuple(exclude_suffixes)):
logger.info(f"Skipping {filename} (excluded from Dropbox upload)")
skipped_count += 1
continue
local_file = os.path.join(root, filename)
remote_file = f"{current_remote}/{filename}"
self.upload_file(local_file, remote_file)
uploaded_count += 1
logger.info(f"Uploaded {uploaded_count} files to {remote_path}")
logger.info(
f"Uploaded {uploaded_count} files to {remote_path}"
+ (f" (skipped {skipped_count} excluded)" if skipped_count else "")
)
def create_shared_link(self, path: str) -> str:
"""
@@ -351,3 +366,27 @@ class DropboxService:
def get_dropbox_service() -> DropboxService:
"""Factory function to get a DropboxService instance."""
return DropboxService()
def dropbox_skip_suffixes_for(dropbox_path: Optional[str]) -> Tuple[str, ...]:
"""Filename suffixes to leave out of a Dropbox upload to ``dropbox_path``.
Only Nomad's own folders (DEFAULT_DROPBOX_PATH / DEFAULT_PRIVATE_DROPBOX_PATH)
skip anything — tenant folders get the full output set. The suffix list comes
from settings.dropbox_skip_output_suffixes ("|"-separated). Skipped files are
still in GCS, so job-page downloads and YouTube uploads are unaffected.
"""
from backend.config import get_settings
settings = get_settings()
if not dropbox_path:
return ()
own_paths = {
p.rstrip("/")
for p in (settings.default_dropbox_path, settings.default_private_dropbox_path)
if p
}
if dropbox_path.rstrip("/") not in own_paths:
return ()
raw = settings.dropbox_skip_output_suffixes or ""
return tuple(s for s in raw.split("|") if s.strip())
+10 -2
View File
@@ -71,6 +71,11 @@ GMAIL_LIKE_DOMAINS = {
# Well-known email providers that are never disposable.
# These skip all external API checks for zero-latency validation.
# Our own domains are never disposable. External disposable-email APIs have
# flagged nomadkaraoke.com (auto-learned into manual_domains), which blocked
# every admin magic-link sign-in.
NEVER_DISPOSABLE_DOMAINS = {"nomadkaraoke.com"}
WELL_KNOWN_PROVIDERS = {
"gmail.com",
"googlemail.com",
@@ -261,8 +266,8 @@ class EmailValidationService:
domain = email.lower().split("@")[-1]
# Tier 0: Well-known providers — skip everything
if domain in WELL_KNOWN_PROVIDERS:
# Tier 0: Well-known providers and our own domains — skip everything
if domain in WELL_KNOWN_PROVIDERS or domain in NEVER_DISPOSABLE_DOMAINS:
return False
# Tier 1: Static blocklist (instant, always available)
@@ -394,6 +399,9 @@ class EmailValidationService:
This persists the result so future checks don't need the API call.
Fire-and-forget: errors are logged but don't affect the caller.
"""
if domain in NEVER_DISPOSABLE_DOMAINS or domain in WELL_KNOWN_PROVIDERS:
logger.warning(f"Refusing to auto-learn protected domain as disposable: {domain}")
return
try:
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(
BLOCKLIST_CONFIG_DOC
+147 -31
View File
@@ -116,6 +116,26 @@ def _parse_resubmit_max() -> int:
return 2
# GCE statuses meaning the worker VM is not running (idle-stop, deploy stop, or —
# since the a/b pair moved to Spot on 2026-09-26 — a Spot preemption, which STOPs
# the VM). A job submitted to a VM in one of these states can never complete:
# its in-memory job registry and ffmpeg process are gone.
# PROVISIONING/STAGING/REPAIRING are included too: the job was accepted by a
# RUNNING VM, so seeing the VM in a (re)start state means it went down and came
# back (e.g. another request restarted a preempted worker) — the job is gone.
_STOPPED_VM_STATUSES = frozenset({
"STOPPING", "STOPPED", "TERMINATED", "SUSPENDING", "SUSPENDED",
"PROVISIONING", "STAGING", "REPAIRING",
})
# While polling a job, refresh config/encoding-worker.last_activity_at at most
# this often. The idle-shutdown function keeps the routed VM alive only while
# last_activity_at is < IDLE_TIMEOUT_MINUTES (5) old, and its /health
# active_jobs counts only RUNNING jobs — so without this, a VM whose encode ran
# longer than the idle window could be stopped in the seconds between the job
# finishing and our next poll collecting the result.
ACTIVITY_TOUCH_INTERVAL_SECONDS = 60.0
QUEUE_TIMEOUT_SECONDS = _parse_queue_timeout()
ENCODING_RESUBMIT_MAX = _parse_resubmit_max()
@@ -272,6 +292,104 @@ class EncodingService:
async with sem:
yield
def _fallback_entries(self) -> list:
"""Parse ENCODING_WORKER_FALLBACK_VMS into candidate dicts.
Schema: '[{"vm":"encoding-worker-fallback-c2df","zone":"us-central1-f",
"ip":"34.x.x.x","machine_type":"c2d-highcpu-16"}, ...]'. machine_type is
optional (inferred from the VM name for legacy entries). Malformed input
degrades to fewer/no fallbacks — this runs during connection recovery and
must never raise.
"""
import json as _json
raw = self.settings.encoding_worker_fallback_vms
if not raw:
return []
try:
parsed = _json.loads(raw)
except (ValueError, TypeError) as e:
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
return []
# A non-list root (null, dict, scalar) parses fine but would blow up
# `for item in parsed` and escape during connection recovery — degrade
# to no fallbacks instead.
if not isinstance(parsed, list):
logger.warning("ENCODING_WORKER_FALLBACK_VMS must be a JSON list; ignoring")
return []
entries = []
for item in parsed:
try:
entries.append({
"vm": item["vm"],
"zone": item["zone"],
"ip": item["ip"],
"machine_type": item.get("machine_type"),
"kind": "fallback",
})
except (KeyError, TypeError) as e:
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
continue
return entries
def _vm_for_worker_url(self, worker_url: Optional[str]) -> Optional[tuple]:
"""Map a worker base URL (http://<ip>:8080) back to its (vm_name, zone).
Looks at the blue-green primary/secondary, the active override, and the
configured fallbacks. Returns None when unknown (no manager, unparseable
URL, or an IP no longer in the fleet). BLOCKING (Firestore read).
"""
if not self._worker_manager or not worker_url:
return None
from urllib.parse import urlparse
host = urlparse(worker_url).hostname
if not host:
return None
config = self._worker_manager.get_config()
default_zone = self._worker_manager._zone
known = [
(config.primary_ip, config.primary_vm, default_zone),
(config.secondary_ip, config.secondary_vm, default_zone),
(config.active_override_ip, config.active_override_vm,
config.active_override_zone or default_zone),
]
known.extend((fb["ip"], fb["vm"], fb["zone"]) for fb in self._fallback_entries())
for ip, vm, zone in known:
if ip and vm and ip == host:
return vm, zone
return None
async def _touch_worker_activity(self, job_id: str) -> None:
"""Best-effort refresh of last_activity_at (keeps the VM from idle-stop)."""
try:
await asyncio.to_thread(self._worker_manager.update_activity)
except Exception as e: # noqa: BLE001 — keep-alive only, never fail the poll
logger.debug(f"[job:{job_id}] Could not refresh worker activity: {_format_exception(e)}")
async def _stopped_worker_status(self, worker_url: Optional[str]) -> Optional[str]:
"""If the VM behind ``worker_url`` is stopped/preempted, return its GCE status.
Returns None when the VM is running, unknown, or the lookup fails — the
caller then falls back to the ordinary poll-failure tolerance. Blocking
Firestore/Compute calls run off the event loop.
"""
if not self._worker_manager:
return None
try:
# Unpinned (legacy) polls target the current active URL.
url = worker_url or await asyncio.to_thread(self._get_worker_url)
found = await asyncio.to_thread(self._vm_for_worker_url, url)
if not found:
return None
vm_name, zone = found
status = await asyncio.to_thread(self._worker_manager.get_vm_status, vm_name, zone)
except Exception as e: # noqa: BLE001 — best-effort diagnosis only
logger.debug(f"Could not check worker VM status for {worker_url}: {_format_exception(e)}")
return None
if status in _STOPPED_VM_STATUSES:
return f"{vm_name} is {status}"
return None
def _build_worker_candidates(self) -> list:
"""Build the ranked candidate list for ensure_any_running.
@@ -310,37 +428,9 @@ class EncodingService:
"is_primary": True,
}]
# Optional capacity-fallback VMs in alternate zones/families, configured via
# env var. Schema: '[{"vm":"encoding-worker-fallback-c4a","zone":"us-central1-a",
# "ip":"34.x.x.x","machine_type":"c4-highcpu-32"}, ...]'. machine_type is
# optional (inferred from the VM name for legacy entries). Empty by default;
# populated after `pulumi up` provisions the fallback VMs.
import json as _json
raw = self.settings.encoding_worker_fallback_vms
if raw:
try:
parsed = _json.loads(raw)
except (ValueError, TypeError) as e:
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
parsed = []
# A non-list root (null, dict, scalar) parses fine but would blow up
# `for item in parsed` and escape this method during connection
# recovery — degrade to no fallbacks instead.
if not isinstance(parsed, list):
logger.warning("ENCODING_WORKER_FALLBACK_VMS must be a JSON list; ignoring")
parsed = []
for item in parsed:
try:
pool.append({
"vm": item["vm"],
"zone": item["zone"],
"ip": item["ip"],
"machine_type": item.get("machine_type"),
"kind": "fallback",
})
except (KeyError, TypeError) as e:
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
continue
# Optional capacity-fallback VMs in alternate zones/families (see
# _fallback_entries). Empty when unconfigured.
pool.extend(self._fallback_entries())
# Rank fastest-first, demoting types that recently stocked out. Keeps the
# primary (c4d) at the top whenever it has capacity.
@@ -778,6 +868,7 @@ class EncodingService:
# counts from here; time spent "pending" in the worker's serialized
# heavy queue counts against `queue_timeout` instead.
run_started_at: Optional[float] = None
last_activity_touch: Optional[float] = None
while True:
now = asyncio.get_event_loop().time()
@@ -809,6 +900,25 @@ class EncodingService:
f"Encoding job {job_id} was lost by the worker (restarted mid-run)",
job_id=job_id,
) from e
# The worker VM itself went away (Spot preemption, idle/deploy
# stop). Nothing on that VM can finish this job, so waiting out the
# remaining poll tolerance (several minutes of retries) only delays
# recovery — and "lost contact" is NOT resubmitted. Surface it as a
# lost job so run_with_lost_job_resubmit re-submits it; the
# resubmit's connection failure then restarts a worker (the Spot
# VM, or the on-demand fallback if Spot capacity is gone).
stopped = await self._stopped_worker_status(worker_url)
if stopped:
logger.warning(
f"[job:{job_id}] Encoding worker VM stopped mid-job ({stopped}) — "
f"likely Spot preemption; treating job as lost for resubmission"
)
self._invalidate_cached_url()
raise EncodingJobLostError(
f"Encoding job {job_id} was lost: worker VM {stopped} "
f"(Spot preemption or stop)",
job_id=job_id,
) from e
consecutive_failures += 1
if consecutive_failures >= MAX_CONSECUTIVE_POLL_FAILURES:
logger.error(
@@ -834,6 +944,12 @@ class EncodingService:
status = {}
job_seen = True
if self._worker_manager and (
last_activity_touch is None
or now - last_activity_touch >= ACTIVITY_TOUCH_INTERVAL_SECONDS
):
last_activity_touch = now
await self._touch_worker_activity(job_id)
job_status = status.get("status", "unknown")
progress = status.get("progress", 0)
if run_started_at is None and (job_status == "running" or progress):
+17 -3
View File
@@ -34,6 +34,7 @@ from typing import Any, Optional
import aiohttp
from google.api_core import exceptions as gcp_exceptions
from google.cloud import firestore
from backend.services.encoding_errors import (
@@ -126,7 +127,7 @@ class EncodingWorkerConfig:
Returns the capacity-fallback override if set, otherwise the primary
URL. The override mechanism lets us route around a zone that's
temporarily out of c4d-highcpu-32 capacity without rewriting the
temporarily out of c4d (Spot) capacity without rewriting the
blue-green primary/secondary tracking.
"""
if self.active_override_ip:
@@ -141,7 +142,7 @@ class EncodingWorkerCandidate:
Carries everything needed to talk to the worker: VM name + zone (so the
GCE compute client targets the right zone) and external IP (so successful
starts can be persisted as the active URL override). ``machine_type`` (e.g.
"c4d-highcpu-32") lets the manager record/clear per-(type,zone) capacity
"c4d-highcpu-16") lets the manager record/clear per-(type,zone) capacity
state so the shared preference logic can demote a stocked-out type.
"""
@@ -444,7 +445,20 @@ class EncodingWorkerManager:
has_explicit_primary = any(getattr(c, "is_primary", False) for c in candidates)
for index, candidate in enumerate(candidates):
try:
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
try:
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
except gcp_exceptions.NotFound as nf:
# A candidate that no longer exists (e.g. a fallback VM removed
# from the fleet while an instance still holds the old
# ENCODING_WORKER_FALLBACK_VMS list) must be SKIPPED, not
# abort the whole failover — otherwise one stale entry blocks
# every later (real) candidate.
raise EncodingWorkerStartError(
f"VM {candidate.vm_name} not found in {candidate.zone}: {nf}",
vm_name=candidate.vm_name,
zone=candidate.zone,
code="NOT_FOUND",
) from nf
started = False
if status not in ("RUNNING", "STAGING"):
logger.info(
+41 -31
View File
@@ -33,21 +33,24 @@ from __future__ import annotations
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
# Lower rank = faster = preferred. Seeded from CPU architecture; refine with the
# measured medians from infrastructure/encoding-worker/benchmark_types.py.
# c4d AMD EPYC Turin (Zen5) — current primary, fastest
# Lower rank = faster = preferred. Keyed by machine FAMILY (the prefix before the
# first "-"), so the ranking is independent of the vCPU size — the fleet moved
# from *-highcpu-32 to *-highcpu-16 on 2026-09-26 and could move again. Seeded
# from CPU architecture; refine with the measured medians from
# infrastructure/encoding-worker/benchmark_types.py.
# c4d AMD EPYC Turin (Zen5) — Spot blue-green primary pair, fastest
# c4 Intel Emerald Rapids — newest Intel perf tier
# n4d AMD (Titanium) — flexible/deep AMD
# c2d AMD Milan (Zen3) — mature, deep pool
# n2d AMD Rome/Milan — deep pool (32 GB floor)
# n2 Intel Cascade/Ice Lake — current fallback (32 GB floor)
# c2d AMD Milan (Zen3) — mature, deep pool (current on-demand fallback)
# n2d AMD Rome/Milan — deep pool
# n2 Intel Cascade/Ice Lake — deep pool
SPEED_RANK: Dict[str, int] = {
"c4d-highcpu-32": 10,
"c4-highcpu-32": 20,
"n4d-highcpu-32": 30,
"c2d-highcpu-32": 50,
"n2d-highcpu-32": 60,
"n2-highcpu-32": 70,
"c4d": 10,
"c4": 20,
"n4d": 30,
"c2d": 50,
"n2d": 60,
"n2": 70,
}
# Rank for a candidate whose machine type is unknown and cannot be inferred:
@@ -58,20 +61,26 @@ UNKNOWN_RANK = 1000
COOLDOWN_SECONDS = 900 # 15 minutes
# Machine type of the blue-green primary/secondary pair (encoding-worker-a/-b).
# They are always c4d; used when a candidate carries no explicit machine_type.
PRIMARY_MACHINE_TYPE = "c4d-highcpu-32"
# They are always c4d (Spot); used when a candidate carries no explicit
# machine_type. Keep in sync with infrastructure/config.py MachineTypes.ENCODING_WORKER.
PRIMARY_MACHINE_TYPE = "c4d-highcpu-16"
# vm-name substring → machine type, for backward-compat inference when a fallback
# entry predates the machine_type field. Checked in order — longer / more-specific
# family tokens FIRST so "n2d" is not shadowed by "n2", nor "c4d" by "c4".
_NAME_TOKEN_TO_TYPE = (
("c4d", "c4d-highcpu-32"),
("n4d", "n4d-highcpu-32"),
("n2d", "n2d-highcpu-32"),
("c2d", "c2d-highcpu-32"),
("c4", "c4-highcpu-32"),
("n2", "n2-highcpu-32"),
)
# Current vCPU size of the fleet — used only to turn a family inferred from a VM
# name into a full machine type (for display + cooldown keys).
_FLEET_SIZE_SUFFIX = "-highcpu-16"
# vm-name substring → machine family, for backward-compat inference when a
# fallback entry predates the machine_type field. Checked in order — longer /
# more-specific family tokens FIRST so "n2d" is not shadowed by "n2", nor "c4d"
# by "c4".
_NAME_TOKEN_TO_FAMILY = ("c4d", "n4d", "n2d", "c2d", "c4", "n2")
def machine_family(machine_type: Optional[str]) -> Optional[str]:
"""``"c4d-highcpu-16"`` → ``"c4d"``; None/empty → None."""
if not machine_type:
return None
return machine_type.split("-", 1)[0].lower()
def _candidate_name(candidate: Dict[str, Any]) -> str:
@@ -83,21 +92,22 @@ def infer_machine_type(candidate: Dict[str, Any]) -> Optional[str]:
"""Best-effort machine type: explicit ``machine_type`` field, else vm-name token.
Fallback secret entries created before the ``machine_type`` field carry only
vm/zone/ip; the VM-name family token (…-fallback-n2c, …-fallback-c4a) is the
only hint. Returns None when nothing matches (caller treats as UNKNOWN_RANK).
vm/zone/ip; the VM-name family token (…-fallback-c2df) is the only hint and
is expanded to the current fleet size. Returns None when nothing matches
(caller treats as UNKNOWN_RANK).
"""
explicit = candidate.get("machine_type")
if explicit:
return explicit
name = _candidate_name(candidate).lower()
for token, mtype in _NAME_TOKEN_TO_TYPE:
if token in name:
return mtype
for family in _NAME_TOKEN_TO_FAMILY:
if family in name:
return f"{family}{_FLEET_SIZE_SUFFIX}"
return None
def _speed_rank(candidate: Dict[str, Any]) -> int:
return SPEED_RANK.get(infer_machine_type(candidate), UNKNOWN_RANK)
return SPEED_RANK.get(machine_family(infer_machine_type(candidate)), UNKNOWN_RANK)
def cooldown_key(candidate: Dict[str, Any]) -> Optional[str]:
+15 -4
View File
@@ -17,11 +17,18 @@ GCP_REGION: str = os.environ.get("GCP_REGION", "us-central1")
# Log querying settings
# ---------------------------------------------------------------------------
#: How far back to look for errors on each run (minutes).
LOOKBACK_MINUTES: int = 15
#: How far back to look for errors on each run (minutes). Must equal the
#: scheduler interval (ErrorMonitorConfig.MONITOR_SCHEDULE, hourly since
#: 2026-09-26) so consecutive windows tile without gaps or double counting.
LOOKBACK_MINUTES: int = 60
#: Maximum number of log entries to fetch per service per run.
MAX_LOG_ENTRIES: int = 500
#: Window (minutes) assumed for ``rolling_counts`` entries written before
#: entries recorded their own ``window_minutes`` (i.e. the 15-min era).
LEGACY_ROLLING_WINDOW_MINUTES: int = 15
#: Maximum number of log entries to fetch per resource type per run (scaled
#: 4x with the 15 -> 60 min window to keep the same per-minute capacity).
MAX_LOG_ENTRIES: int = 2000
# ---------------------------------------------------------------------------
# Monitored services
@@ -46,6 +53,10 @@ MONITORED_CLOUD_RUN_JOBS: list[str] = [
"lyrics-transcription-job",
"audio-separation-job",
"audio-download-job",
# karaoke-decide weekly MusicBrainz dump -> BigQuery refresh
"mb-refresh",
# karaoke-decide ListenBrainz statistics dump -> BigQuery refresh
"lb-refresh",
]
# Gen2 Cloud Functions log as cloud_run_revision, not cloud_function.
@@ -19,6 +19,7 @@ from backend.services.error_monitor.config import (
AUTO_RESOLVE_MIN_HOURS,
AUTO_RESOLVE_MULTIPLIER,
ROLLING_WINDOW_DAYS,
LOOKBACK_MINUTES,
)
# ---------------------------------------------------------------------------
@@ -174,7 +175,9 @@ class ErrorPatternsAdapter:
snap = doc_ref.get()
ts_iso = _iso(data.timestamp)
new_rolling_entry = {"ts": ts_iso, "count": data.count}
# window_minutes lets spike detection normalise counts across a change
# of monitor cadence (15 -> 60 min on 2026-09-26).
new_rolling_entry = {"ts": ts_iso, "count": data.count, "window_minutes": LOOKBACK_MINUTES}
if not snap.exists:
# ── brand new pattern ──────────────────────────────────────────
+11 -3
View File
@@ -23,6 +23,7 @@ from google.cloud import secretmanager
from backend.services.error_monitor.config import (
GCP_PROJECT,
LEGACY_ROLLING_WINDOW_MINUTES,
LOOKBACK_MINUTES,
MAX_LOG_ENTRIES,
MONITORED_CLOUD_FUNCTIONS,
@@ -214,15 +215,22 @@ def _group_by_pattern(entries: list[dict]) -> dict[str, dict]:
def _rolling_average(rolling_counts: list[dict]) -> float:
"""Compute the mean count from a list of rolling_count dicts.
Each entry's count is scaled to the current ``LOOKBACK_MINUTES`` window
(entries without ``window_minutes`` predate it and were 15-minute counts),
so a change of monitor cadence doesn't read as a spike.
Args:
rolling_counts: List of ``{"count": int, ...}`` dicts.
rolling_counts: List of ``{"count": int, "window_minutes"?: int, ...}`` dicts.
Returns:
The arithmetic mean as a float, or ``0.0`` for an empty list.
"""
if not rolling_counts:
return 0.0
total = sum(entry.get("count", 0) for entry in rolling_counts)
total = 0.0
for entry in rolling_counts:
window = entry.get("window_minutes") or LEGACY_ROLLING_WINDOW_MINUTES
total += entry.get("count", 0) * LOOKBACK_MINUTES / window
return total / len(rolling_counts)
@@ -258,7 +266,7 @@ def _is_spike(current_count: int, rolling_counts: list[dict]) -> bool:
class ErrorMonitor:
"""Orchestrates the full production error monitoring pipeline.
On each run (typically every 15 minutes via Cloud Scheduler), it:
On each run (hourly via Cloud Scheduler), it:
1. Queries Cloud Logging for recent errors across all monitored services.
2. Groups errors into patterns using normalisation + hashing.
+72 -4
View File
@@ -3,8 +3,12 @@
gen's match judge takes a separate artist + title; a karaoke singer types one
line ("the strokes max picu"). One small Gemini call splits the query into
artist/title AND corrects typos in the same step, returning the match judge's
verdict shape (kind cosmetic/content/ambiguous/none) plus the typed split, so
kjbox can show gen's "Corrected to X — you typed Y. Undo".
verdict shape (kind cosmetic/content/ambiguous/none) plus the typed split.
:func:`resolve_and_tidy` then runs that split through the job flow's own
:func:`judge_match` catalog pass, so the singer gets exactly the canonical
artist/title gen's AudioSourceStep would "tidy" to (the catalog can't parse a
one-line query itself — the AI only does the split + typo fix).
"""
from __future__ import annotations
@@ -15,18 +19,24 @@ import logging
from typing import Awaitable, Callable, Optional
from backend.services.match_judge.ai import _model
from backend.services.match_judge.verdict import KIND_NONE
from backend.services.match_judge.classifier import normalize_for_match
from backend.services.match_judge.verdict import KIND_COSMETIC, KIND_NONE, MatchVerdict
logger = logging.getLogger(__name__)
Generate = Callable[[str, str, str], Awaitable[dict]]
Judge = Callable[[str, str], Awaitable[MatchVerdict]]
_VALID_KINDS = {"cosmetic", "content", "ambiguous"}
_SYSTEM_PROMPT = (
"You resolve a karaoke singer's free-text song search. The query is one line "
"holding an artist and/or a song title in any order, often lazily typed or "
"misspelled (e.g. 'the strokes max picu' = The Strokes — Machu Picchu).\n"
"misspelled (e.g. 'the strokes max picu' = The Strokes — Machu Picchu). It may "
"instead DESCRIBE the song — where it's from, a line of its lyrics, what it's "
"about (e.g. 'that song from titanic' = Céline Dion — My Heart Will Go On; "
"'is this the real life' = Queen — Bohemian Rhapsody). Then name the song meant "
"(kind 'content'), or use 'ambiguous' with the likely songs when several fit.\n"
"Return JSON with: kind, confident, typed_artist, typed_title, canonical_artist, "
"canonical_title, alternatives, reason.\n"
"typed_artist/typed_title: how the query splits as typed (either may be empty).\n"
@@ -82,6 +92,15 @@ def verdict_from_response(data: object, query: str) -> dict:
def _verdict_from_response(data: object, query: str) -> dict:
if isinstance(data, dict) and data.get("kind") == KIND_NONE:
# Not a song the model recognises — keep its split so the catalog can
# still find it (resolve_and_tidy).
typed_artist, typed_title = data.get("typed_artist"), data.get("typed_title")
if (isinstance(typed_artist, str) and isinstance(typed_title, str)
and typed_artist.strip() and typed_title.strip()):
return {**_none(query, str(data.get("reason") or "no suggestion")),
"typed_artist": typed_artist.strip(), "typed_title": typed_title.strip()}
return _none(query)
if not isinstance(data, dict) or data.get("kind") not in _VALID_KINDS:
return _none(query)
for key in ("typed_artist", "typed_title", "canonical_artist", "canonical_title", "reason"):
@@ -127,6 +146,55 @@ async def resolve_free_text(query: str, *, generate: Optional[Generate] = None,
return verdict_from_response(data, query)
async def resolve_and_tidy(query: str, *, generate: Optional[Generate] = None,
judge: Optional[Judge] = None, model: Optional[str] = None) -> dict:
"""Free-text split/correct, then gen's catalog tidy (the job flow's fast pass).
The AI verdict's song — its canonical pick when confident, else the typed
split — is checked against the catalog with :func:`judge_match` (stage
"fast": catalog only, no second AI call). A confident catalog match wins:
its formatting becomes the canonical artist/title, kind "cosmetic" when the
query already named that song (only casing/punctuation/word order differ),
else "content". No catalog match → the AI verdict unchanged. Never raises.
"""
verdict = await resolve_free_text(query, generate=generate, model=model)
kind = verdict.get("kind")
if kind in ("cosmetic", "content") and verdict.get("confident"):
artist, title = verdict["canonical_artist"], verdict["canonical_title"]
elif kind == KIND_NONE and verdict.get("typed_artist") and verdict.get("typed_title"):
artist, title = verdict["typed_artist"], verdict["typed_title"]
else:
return verdict
try:
cat = await (judge or _default_judge)(artist, title)
except Exception as e:
logger.warning(f"resolve_and_tidy catalog pass failed: {e}")
# Still answer with the AI verdict, but as a transient result: the
# resolve route doesn't cache "unavailable", so the tidy retries later.
return {**verdict, "reason": "unavailable"}
if not (cat.confident and cat.engine == "catalog" and cat.kind in (KIND_COSMETIC, KIND_NONE)
and cat.canonical_artist and cat.canonical_title):
return verdict
ca, ct = cat.canonical_artist, cat.canonical_title
typed = normalize_for_match(query)
same_song = typed in (normalize_for_match(f"{ca} {ct}"), normalize_for_match(f"{ct} {ca}"))
return {
**verdict,
"kind": KIND_COSMETIC if same_song else "content",
"confident": True,
"canonical_artist": ca,
"canonical_title": ct,
"alternatives": [],
"engine": "catalog",
"reason": "catalog match",
}
async def _default_judge(artist: str, title: str) -> MatchVerdict:
from backend.services.match_judge.service import judge_match
return await judge_match(artist, title, stage="fast")
async def _default_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
return await asyncio.to_thread(_blocking_generate, model, system_prompt, user_prompt)
@@ -0,0 +1 @@
"""Quick (fastgen-style) draft video for kjbox make-it jobs."""
+361
View File
@@ -0,0 +1,361 @@
"""Quick-version renderer — a scrolling-lyrics 480p karaoke video in seconds.
Ported from kjbox ``fastgen/fastgen.py`` (the local POC Andrew uses at shows).
Given an instrumental (+ optional vocals guide), artist and title, it:
1. fetches lyrics from LRCLIB (line-synced preferred, plain as fallback);
2. lays the lines out as one tall PIL-rendered PNG;
3. scrolls that PNG upward with an ffmpeg ``overlay`` whose y expression is a
piecewise-linear "sum of ramps" anchored so each synced line reaches the
reading row at its sung time (constant crawl when there is no timing);
4. muxes it with the instrumental (and the vocals quietly mixed back in as a
singer guide) in a single ffmpeg pass.
Deliberately primitive: no word-level highlighting and no review — it exists
so a kjbox singer can sing a song minutes after asking, while the full gen job
keeps working toward the proper NOMAD version.
PIL rather than ffmpeg ``drawtext``: ffmpeg 8's always-on harfbuzz shaping
renders a ``.notdef`` box for every newline in a multi-line textfile.
"""
from __future__ import annotations
import logging
import os
import re
import subprocess
import textwrap
from dataclasses import dataclass, field
from typing import List, Optional, Tuple
import requests
logger = logging.getLogger(__name__)
LRCLIB_BASE = "https://lrclib.net/api"
USER_AGENT = "nomadkaraoke-quick-version/1.0 (https://nomadkaraoke.com)"
_FONT_PATH = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))),
"karaoke_gen", "resources", "Montserrat-Bold.ttf",
)
# (text, anchor_seconds | None). Only the first visual row of a lyric line
# carries its anchor.
TimedLine = Tuple[str, Optional[float]]
_LRC_RE = re.compile(r"\[(\d+):(\d+(?:\.\d+)?)\]")
@dataclass
class Lyrics:
kind: str # "synced" | "plain"
plain: str
timed: Optional[List[Tuple[float, str]]] = None
@dataclass
class RenderSettings:
height: int = 480
fps: int = 24
wrap: int = 34
reading_frac: float = 0.42
vocals_level: float = 0.3
gap_threshold: float = 5.0
gap_lines: int = 1
font_path: str = _FONT_PATH
@dataclass
class RenderResult:
output_path: str
lyrics_tier: str # "synced" | "constant" | "none"
line_count: int
duration_seconds: float
extra: dict = field(default_factory=dict)
# --------------------------------------------------------------------------- #
# Lyrics
# --------------------------------------------------------------------------- #
def _strip_lrc_timestamps(synced: str) -> str:
return "\n".join(_LRC_RE.sub("", raw).strip() for raw in synced.splitlines()).strip()
def parse_synced(synced: str) -> List[Tuple[float, str]]:
"""Parse ``[mm:ss.xx] line`` LRC into sorted (start_seconds, text) pairs.
A line may carry several timestamps (``[00:10.00][01:10.00] chorus``); each
becomes its own entry.
"""
out: List[Tuple[float, str]] = []
for raw in synced.splitlines():
stamps = _LRC_RE.findall(raw)
if not stamps:
continue
text = _LRC_RE.sub("", raw).strip()
for mins, secs in stamps:
out.append((int(mins) * 60 + float(secs), text))
out.sort(key=lambda p: p[0])
return out
def lyrics_from_lrclib_payload(data: dict) -> Optional[Lyrics]:
synced = data.get("syncedLyrics")
if synced and synced.strip():
timed = parse_synced(synced)
if timed:
return Lyrics("synced", _strip_lrc_timestamps(synced), timed)
plain = data.get("plainLyrics")
if plain and plain.strip():
return Lyrics("plain", plain)
return None
def fetch_lrclib_lyrics(
artist: str, title: str, duration: Optional[float], timeout: float = 10.0
) -> Optional[Lyrics]:
"""Exact ``/get`` (with duration when known), then ``/search`` preferring synced."""
session = requests.Session()
session.headers["User-Agent"] = USER_AGENT
params = {"artist_name": artist, "track_name": title}
if duration:
params["duration"] = int(round(duration))
try:
r = session.get(f"{LRCLIB_BASE}/get", params=params, timeout=timeout)
if r.status_code == 200:
got = lyrics_from_lrclib_payload(r.json())
if got and got.kind == "synced":
return got
exact_plain = got
else:
exact_plain = None
except (requests.RequestException, ValueError) as exc:
logger.warning(f"LRCLIB get failed: {exc}")
exact_plain = None
try:
r = session.get(f"{LRCLIB_BASE}/search", params={"q": f"{artist} {title}"}, timeout=timeout)
if r.status_code == 200:
hits = r.json() or []
for hit in sorted(hits, key=lambda h: 0 if h.get("syncedLyrics") else 1):
got = lyrics_from_lrclib_payload(hit)
if got and got.kind == "synced":
return got
if got and exact_plain is None:
exact_plain = got
except (requests.RequestException, ValueError) as exc:
logger.warning(f"LRCLIB search failed: {exc}")
return exact_plain
def resolve_timed_lines(lyrics: Optional[Lyrics]) -> Tuple[List[TimedLine], str]:
"""Lyrics → (line, anchor|None) pairs + tier label (synced / constant / none)."""
if lyrics is None:
return [], "none"
if lyrics.kind == "synced" and lyrics.timed:
return [(text, t) for t, text in lyrics.timed if text.strip()], "synced"
return [(raw.strip(), None) for raw in lyrics.plain.splitlines()], "constant"
# --------------------------------------------------------------------------- #
# Layout
# --------------------------------------------------------------------------- #
def insert_instrumental_gaps(timed_lines: List[TimedLine], threshold: float, gap_lines: int = 1) -> List[TimedLine]:
"""Blank spacer rows where consecutive anchored lines are > threshold apart,
so the crawl visibly opens up during an instrumental break."""
if threshold <= 0:
return list(timed_lines)
out: List[TimedLine] = []
last_t: Optional[float] = None
for text, anchor in timed_lines:
if anchor is not None:
if last_t is not None and anchor - last_t > threshold:
out.extend([("", None)] * gap_lines)
last_t = anchor
out.append((text, anchor))
return out
def build_visual_lines(artist: str, title: str, timed_lines: List[TimedLine], wrap: int) -> List[TimedLine]:
header: List[TimedLine] = [("", None), ("", None), (artist.upper(), None), (title.upper(), None),
("", None), ("", None)]
body: List[TimedLine] = []
for text, anchor in timed_lines:
text = text.strip()
if not text:
body.append(("", None))
continue
for i, row in enumerate(textwrap.wrap(text, width=wrap) or [""]):
body.append((row, anchor if i == 0 else None))
return header + body + [("", None)] * 3
def render_crawl_png(
lines: List[TimedLine], width: int, fontsize: int, font_path: str, workdir: str
) -> Tuple[str, int, List[float]]:
"""Rasterise the whole crawl to one tall PNG → (path, height, row centres)."""
from PIL import Image, ImageDraw, ImageFont
font = ImageFont.truetype(font_path, fontsize)
ascent, descent = font.getmetrics()
line_advance = ascent + descent + round(fontsize * 0.35)
stroke = max(2, fontsize // 16)
pad = fontsize
height = pad * 2 + line_advance * len(lines)
img = Image.new("RGB", (width, height), (0, 0, 0))
draw = ImageDraw.Draw(img)
centers: List[float] = []
y = pad
for text, _anchor in lines:
if text:
line_w = draw.textlength(text, font=font)
draw.text(((width - line_w) / 2, y), text, font=font, fill=(255, 232, 31),
stroke_width=stroke, stroke_fill=(0, 0, 0))
centers.append(y + line_advance / 2)
y += line_advance
png_path = os.path.join(workdir, "crawl.png")
img.save(png_path)
return png_path, height, centers
def build_scroll_y_expr(
lines: List[TimedLine], centers: List[float], duration: float,
frame_h: int, img_h: int, reading_frac: float,
) -> Tuple[str, bool]:
"""ffmpeg ``overlay`` y expression → (expr, is_time_anchored).
y is the PNG's top edge relative to the frame top; each anchored line's
centre ``c_i`` should sit on the reading row ``R`` at ``t_i`` (y = R - c_i).
Piecewise-linear between anchors, written as a flat sum of ramps
``Y0 + M0*(t-T0) + Σ (Mk-M[k-1])*max(0,t-Tk)`` with commas escaped for the
filtergraph parser.
"""
reading_row = reading_frac * frame_h
pts = [(0.0, float(frame_h))]
for (_text, anchor), c in zip(lines, centers):
if anchor is not None and 0.0 < anchor < duration:
pts.append((float(anchor), reading_row - c))
timed = len(pts) > 1
if timed:
pts.append((duration, pts[-1][1]))
else:
pts.append((duration, -float(img_h)))
clean = [pts[0]]
for t, y in pts[1:]:
if t > clean[-1][0] + 1e-3:
clean.append((t, y))
pts = clean
if len(pts) < 2: # degenerate (zero-length audio) — park the crawl off-screen
return f"{float(frame_h):.2f}", False
slopes = [(pts[i + 1][1] - pts[i][1]) / (pts[i + 1][0] - pts[i][0]) for i in range(len(pts) - 1)]
terms = [f"{pts[0][1]:.2f}", f"({slopes[0]:.5f})*(t-{pts[0][0]:.3f})"]
for k in range(1, len(slopes)):
dm = slopes[k] - slopes[k - 1]
if abs(dm) < 1e-6:
continue
terms.append(f"({dm:.5f})*max(0\\,t-{pts[k][0]:.3f})")
return "+".join(terms), timed
def build_ffmpeg_cmd(
instrumental: str, vocals: Optional[str], vocals_level: float,
crawl_png: str, y_expr: str, out_path: str, width: int, height: int, fps: int,
duration: float,
) -> List[str]:
"""Every input and the output are explicitly bounded to ``duration``.
``-shortest`` alone is NOT enough: ffmpeg 4.4 (the GPU image's Ubuntu 22.04
package) never ends when an ``amix`` output is paired with the infinite
lavfi colour + looped PNG video — a 20 s song rendered 540 s+ of video until
the timeout (prod job 405eed71, 2026-09-28). ffmpeg 8 happens to stop."""
dur = f"{max(duration, 0.1):.3f}"
overlay = f"[0:v][1:v]overlay=x=(W-w)/2:y={y_expr}[v]"
inputs = [
"-f", "lavfi", "-i", f"color=c=black:s={width}x{height}:r={fps}:d={dur}",
"-loop", "1", "-framerate", str(fps), "-t", dur, "-i", crawl_png,
"-i", instrumental,
]
if vocals and vocals_level > 0:
# Faint lead vocal as a singer guide (there is no word highlighting).
inputs += ["-i", vocals]
audio = (f"[2:a]volume=1[gi];[3:a]volume={vocals_level:.3f}[gv];"
f"[gi][gv]amix=inputs=2:normalize=0:duration=first[a]")
filt, amap = overlay + ";" + audio, ["-map", "[a]"]
else:
filt, amap = overlay, ["-map", "2:a"]
return [
"ffmpeg", "-y", "-hide_banner", "-loglevel", "error", *inputs,
"-filter_complex", filt,
"-map", "[v]", *amap,
"-c:v", "libx264", "-preset", "veryfast", "-crf", "26", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "192k",
"-movflags", "+faststart",
"-t", dur,
"-shortest",
out_path,
]
def probe_duration(audio_path: str) -> float:
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=nk=1:nw=1", audio_path],
capture_output=True, text=True, check=True, timeout=60,
)
return float(out.stdout.strip())
def render_quick_video(
*,
instrumental_path: str,
vocals_path: Optional[str],
artist: str,
title: str,
out_path: str,
workdir: str,
lyrics: Optional[Lyrics] = None,
fetch_lyrics: bool = True,
settings: Optional[RenderSettings] = None,
ffmpeg_timeout: float = 600.0,
) -> RenderResult:
"""Render the quick video. ``lyrics`` overrides the LRCLIB fetch."""
s = settings or RenderSettings()
duration = probe_duration(instrumental_path)
if lyrics is None and fetch_lyrics:
lyrics = fetch_lrclib_lyrics(artist, title, duration)
timed_lines, tier = resolve_timed_lines(lyrics)
if tier == "synced":
timed_lines = insert_instrumental_gaps(timed_lines, s.gap_threshold, s.gap_lines)
if tier == "none":
timed_lines = [("(lyrics unavailable)", None)]
width = round(s.height * 16 / 9)
width += width % 2
fontsize = max(18, round(s.height * 0.07))
lines = build_visual_lines(artist, title, timed_lines, s.wrap)
crawl_png, img_h, centers = render_crawl_png(lines, width, fontsize, s.font_path, workdir)
y_expr, _ = build_scroll_y_expr(lines, centers, duration, s.height, img_h, s.reading_frac)
cmd = build_ffmpeg_cmd(instrumental_path, vocals_path, s.vocals_level, crawl_png, y_expr,
out_path, width, s.height, s.fps, duration)
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=ffmpeg_timeout)
if proc.returncode != 0:
raise RuntimeError(f"ffmpeg failed ({proc.returncode}): {proc.stderr[-2000:]}")
return RenderResult(
output_path=out_path,
lyrics_tier=tier,
line_count=sum(1 for t, _ in timed_lines if t.strip()),
duration_seconds=duration,
)
+271
View File
@@ -0,0 +1,271 @@
"""Quick version for kjbox make-it jobs — orchestration inside the audio worker.
The kjbox singer "make it" flow creates a normal gen job, which takes ~30 min
(ensemble separation, transcription, lyrics review, render). For those jobs we
*also* produce a rough scrolling-lyrics video within a few minutes of the audio
landing, so the singer can choose to sing it right away:
1. ``separate_quick`` — one fast single-model pass on the (already warm) L4,
run by the audio worker BEFORE the ensemble.
2. ``QuickVersionRender`` — a background thread renders the video (CPU: PIL +
ffmpeg) while the GPU runs the ensemble, then uploads it and records
``file_urls.quick.video_mp4`` + ``state_data.quick_version``.
kjbox's GenPoller already reads the job doc and downloads ``file_urls`` entries
through ``/api/jobs/{id}/download/{category}/{key}``, so nothing else is needed
to deliver it. Every failure here is non-fatal to the full job.
"""
from __future__ import annotations
import gc
import glob
import logging
import os
import threading
import time
from datetime import datetime, timezone
from typing import Any, Callable, Dict, Optional, Tuple
from backend.services.job_notification_service import is_kjbox_job
from backend.services.quick_version.renderer import render_quick_video
logger = logging.getLogger(__name__)
STATE_KEY = "quick_version"
FILE_CATEGORY = "quick"
FILE_KEY = "video_mp4"
# fastgen's model: a light MDX-Net ONNX (~60 MB), ~10x less compute than a
# roformer. The baked roformer (instrumental_clean preset's first model) took
# 14 s to load + 124 s to separate a 3:15 song on the L4 (prod, 2026-09-28).
# If the ONNX isn't in /models yet, audio-separator downloads it on load
# (baked by download_models.py on the next GPU base rebuild). Override with
# QUICK_VERSION_MODEL.
DEFAULT_QUICK_MODEL = "UVR-MDX-NET-Inst_HQ_4.onnx"
# Always baked into the GPU image — used if the default can't be loaded
# (e.g. the model download fails).
FALLBACK_QUICK_MODEL = "mel_band_roformer_instrumental_fv7z_gabox.ckpt"
# Roformer (MDXC) overlap: the library default is 8; 2 is ~4x less compute and
# plenty for a draft.
QUICK_MDXC_OVERLAP = 2
STATUS_SEPARATING = "separating"
STATUS_RENDERING = "rendering"
STATUS_READY = "ready"
STATUS_FAILED = "failed"
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def quick_version_enabled() -> bool:
return os.environ.get("KJBOX_QUICK_VERSION_ENABLED", "true").strip().lower() not in ("0", "false", "no", "off")
def should_build_quick_version(job: Any) -> bool:
"""Only for kjbox jobs, when enabled, and not already delivered (job retries)."""
if not quick_version_enabled():
return False
if not is_kjbox_job(getattr(job, "request_metadata", None)):
return False
existing = (getattr(job, "state_data", None) or {}).get(STATE_KEY) or {}
return existing.get("status") != STATUS_READY
def _classify_output(path: str) -> Optional[str]:
"""Map a separator output filename to 'instrumental' / 'vocals' / None."""
base = os.path.basename(path).lower()
if "quick_instrumental" in base:
return "instrumental"
if "quick_vocals" in base:
return "vocals"
tag_start = base.rfind("_(")
tag_end = base.find(")", tag_start) if tag_start >= 0 else -1
tag = base[tag_start + 2:tag_end] if tag_start >= 0 and tag_end > tag_start else ""
if tag in ("instrumental", "no vocal", "no_vocal", "no vocals"):
return "instrumental"
if tag in ("vocals", "vocal"):
return "vocals"
return None
def separate_quick(
audio_path: str,
workdir: str,
model_dir: Optional[str],
model: Optional[str] = None,
separator_factory: Optional[Callable[..., Any]] = None,
) -> Tuple[str, Optional[str]]:
"""Single-model separation → (instrumental_path, vocals_path|None)."""
model = model or os.environ.get("QUICK_VERSION_MODEL") or DEFAULT_QUICK_MODEL
if separator_factory is None:
from audio_separator.separator import Separator as separator_factory # heavy; lazy
out_dir = os.path.join(workdir, "quick_stems")
os.makedirs(out_dir, exist_ok=True)
kwargs: Dict[str, Any] = {
"output_dir": out_dir,
"output_format": "FLAC",
"mdxc_params": {"segment_size": 256, "override_model_segment_size": False,
"batch_size": 1, "overlap": QUICK_MDXC_OVERLAP, "pitch_shift": 0},
}
if model_dir:
kwargs["model_file_dir"] = model_dir
candidates = [model] + ([FALLBACK_QUICK_MODEL] if model != FALLBACK_QUICK_MODEL else [])
sep = None
for i, name in enumerate(candidates):
try:
sep = separator_factory(**kwargs)
sep.load_model(model_filename=name)
break
except Exception as exc:
if i == len(candidates) - 1:
raise
logger.warning(f"Quick model {name} failed to load ({exc}); falling back to {candidates[i + 1]}")
outputs = sep.separate(audio_path, {
"Instrumental": "quick_instrumental", "Vocals": "quick_vocals",
"instrumental": "quick_instrumental", "vocals": "quick_vocals",
}) or []
produced = [o if os.path.isabs(o) else os.path.join(out_dir, o) for o in outputs]
produced += glob.glob(os.path.join(out_dir, "*"))
inst = vocals = None
for p in produced:
if not os.path.exists(p):
continue
kind = _classify_output(p)
if kind == "instrumental" and inst is None:
inst = p
elif kind == "vocals" and vocals is None:
vocals = p
# Free GPU memory before the ensemble loads its models.
del sep
gc.collect()
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
except Exception: # pragma: no cover - torch optional in tests
pass
if inst is None:
raise RuntimeError(f"Quick separation produced no instrumental (outputs: {outputs!r})")
return inst, vocals
class QuickVersionRender:
"""Renders + uploads the quick video on a background thread."""
def __init__(self, job_id: str, artist: str, title: str, instrumental: str, vocals: Optional[str],
workdir: str, job_manager: Any, storage: Any, job_log: Any = None,
started_monotonic: Optional[float] = None, separation_seconds: Optional[float] = None):
self.job_id = job_id
self.artist = artist or "Unknown"
self.title = title or "Unknown"
self.instrumental = instrumental
self.vocals = vocals
self.workdir = workdir
self.job_manager = job_manager
self.storage = storage
self.job_log = job_log or logger
self.started = started_monotonic or time.monotonic()
self.separation_seconds = separation_seconds
self.ok: Optional[bool] = None
self._thread = threading.Thread(target=self._run, name=f"quick-version-{job_id}", daemon=True)
def start(self) -> "QuickVersionRender":
self._thread.start()
return self
def join(self, timeout: float) -> bool:
"""Wait for the render; True if it finished (ok or failed) in time."""
self._thread.join(timeout)
return not self._thread.is_alive()
def _run(self) -> None:
try:
set_quick_state(self.job_manager, self.job_id, STATUS_RENDERING)
render_dir = os.path.join(self.workdir, "quick_render")
os.makedirs(render_dir, exist_ok=True)
out_path = os.path.join(render_dir, "quick.mp4")
t0 = time.monotonic()
result = render_quick_video(
instrumental_path=self.instrumental, vocals_path=self.vocals,
artist=self.artist, title=self.title, out_path=out_path, workdir=render_dir,
)
render_seconds = time.monotonic() - t0
gcs_path = f"jobs/{self.job_id}/quick/quick.mp4"
self.storage.upload_file(out_path, gcs_path)
self.job_manager.update_file_url(self.job_id, FILE_CATEGORY, FILE_KEY, gcs_path)
set_quick_state(
self.job_manager, self.job_id, STATUS_READY,
lyrics_tier=result.lyrics_tier,
line_count=result.line_count,
duration_seconds=round(result.duration_seconds, 1),
size_bytes=os.path.getsize(out_path),
separation_seconds=round(self.separation_seconds, 1) if self.separation_seconds else None,
render_seconds=round(render_seconds, 1),
worker_seconds=round(time.monotonic() - self.started, 1),
ready_at=_now_iso(),
)
self.ok = True
self.job_log.info(
f"Quick version ready: tier={result.lyrics_tier} lines={result.line_count} "
f"render={render_seconds:.1f}s total={time.monotonic() - self.started:.1f}s"
)
except Exception as exc:
self.ok = False
logger.warning(f"[job:{self.job_id}] Quick version render failed (non-fatal): {exc}", exc_info=True)
try:
self.job_log.warning(f"Quick version render failed (non-fatal): {exc}")
except Exception:
pass
set_quick_state(self.job_manager, self.job_id, STATUS_FAILED, error=str(exc)[:500])
def set_quick_state(job_manager: Any, job_id: str, status: str, **extra: Any) -> None:
"""Write ``state_data.quick_version`` (never raises)."""
value: Dict[str, Any] = {"status": status, "updated_at": _now_iso()}
value.update({k: v for k, v in extra.items() if v is not None})
try:
job_manager.update_state_data(job_id, STATE_KEY, value)
except Exception as exc: # pragma: no cover - defensive
logger.warning(f"[job:{job_id}] Could not record quick_version state: {exc}")
def start_quick_version(
job: Any, audio_path: str, workdir: str, model_dir: Optional[str],
job_manager: Any, storage: Any, job_log: Any = None,
separator_factory: Optional[Callable[..., Any]] = None,
) -> Optional[QuickVersionRender]:
"""Run the quick separation (blocking, GPU) and start the render thread.
Returns the running render (join it before the worker exits) or None when
skipped/failed. Never raises.
"""
job_id = job.job_id
try:
if not should_build_quick_version(job):
return None
started = time.monotonic()
set_quick_state(job_manager, job_id, STATUS_SEPARATING, started_at=_now_iso())
inst, vocals = separate_quick(audio_path, workdir, model_dir, separator_factory=separator_factory)
sep_seconds = time.monotonic() - started
if job_log:
job_log.info(f"Quick separation done in {sep_seconds:.1f}s")
return QuickVersionRender(
job_id, job.artist, job.title, inst, vocals, workdir, job_manager, storage, job_log,
started_monotonic=started, separation_seconds=sep_seconds,
).start()
except Exception as exc:
logger.warning(f"[job:{job_id}] Quick version skipped after error (non-fatal): {exc}", exc_info=True)
if job_log:
try:
job_log.warning(f"Quick version failed (non-fatal): {exc}")
except Exception:
pass
set_quick_state(job_manager, job_id, STATUS_FAILED, error=str(exc)[:500])
return None
+34 -4
View File
@@ -14,6 +14,13 @@ from datetime import timedelta
from backend.config import settings
# The bucket is publicly readable, and GCS serves publicly readable objects that
# lack an explicit Cache-Control with ``public, max-age=3600`` — reads (including
# the backend's own authenticated API reads) can then be answered from an edge
# cache for up to an hour after the object is overwritten. Mutable state written
# by the backend must never be cached.
NO_STORE_CACHE_CONTROL = "no-store"
logger = logging.getLogger(__name__)
@@ -70,12 +77,24 @@ class StorageService:
logger.error(f"Error uploading file {local_path}: {e}")
raise
def upload_fileobj(self, file_obj: BinaryIO, destination_path: str, content_type: Optional[str] = None) -> str:
"""Upload a file object to GCS."""
def upload_fileobj(
self,
file_obj: BinaryIO,
destination_path: str,
content_type: Optional[str] = None,
cache_control: Optional[str] = None,
) -> str:
"""Upload a file object to GCS.
Pass ``cache_control=NO_STORE_CACHE_CONTROL`` for objects that may be
overwritten in place and must be visible immediately (e.g. theme assets).
"""
try:
blob = self.bucket.blob(destination_path)
if content_type:
blob.content_type = content_type
if cache_control:
blob.cache_control = cache_control
blob.upload_from_file(file_obj, rewind=True)
logger.info(f"Uploaded file object to gs://{settings.gcs_bucket_name}/{destination_path}")
return destination_path
@@ -376,6 +395,9 @@ class StorageService:
try:
blob = self.bucket.blob(destination_path)
blob.content_type = "application/json"
# JSON objects are mutable state (configs, registries, corrections) —
# never let GCS edge-cache them, or overwrites stay invisible for ~1h.
blob.cache_control = NO_STORE_CACHE_CONTROL
upload_kwargs = {"content_type": "application/json"}
if if_generation_match is not None:
upload_kwargs["if_generation_match"] = if_generation_match
@@ -390,9 +412,17 @@ class StorageService:
raise
def download_json(self, source_path: str) -> Dict[str, Any]:
"""Download and parse a JSON file from GCS."""
"""Download and parse a JSON file from GCS, always reading the latest version.
Objects written before ``upload_json`` set ``no-store`` carry GCS's default
public cache policy, so a plain download can return a stale cached copy.
Resolving the live generation first (metadata request, not cached) and
downloading that exact generation bypasses any cached copy.
"""
try:
blob = self.bucket.blob(source_path)
blob = self.bucket.get_blob(source_path)
if blob is None:
raise NotFound(f"gs://{settings.gcs_bucket_name}/{source_path} not found")
content = blob.download_as_text()
data = json.loads(content)
logger.info(f"Downloaded JSON from gs://{settings.gcs_bucket_name}/{source_path}")
+226 -12
View File
@@ -39,8 +39,14 @@ from backend.models.tenant import (
TenantFeatures,
)
from backend.models.theme import ColorOverrides
from backend.services.storage_service import StorageService
from backend.services.storage_service import NO_STORE_CACHE_CONTROL, StorageService
from backend.services.theme_service import METADATA_FILE, THEMES_PREFIX, get_theme_service
from backend.services.tenant_domain_service import (
TenantDomainConflictError,
TenantDomainError,
TenantDomainService,
get_tenant_domain_service,
)
from backend.services.tenant_service import (
DEFAULT_SENDER_EMAIL,
TENANTS_PREFIX,
@@ -72,6 +78,8 @@ IMAGE_CONTENT_TYPES = {
}
_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$")
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
_DOMAIN_RE = re.compile(r"^(?!-)[a-z0-9-]+(\.[a-z0-9-]+)+$")
class TenantValidationError(ValueError):
@@ -86,6 +94,10 @@ class TenantNotFoundError(ValueError):
"""Raised when the requested tenant does not exist."""
class TenantProvisioningError(RuntimeError):
"""Raised when the tenant's subdomain (Cloudflare) could not be set up/removed."""
# Top-level sections a valid theme style_params document may contain.
STYLE_PARAM_SECTIONS = {"intro", "karaoke", "end", "cdg"}
@@ -106,6 +118,24 @@ def _validate_tenant_id(tenant_id: str) -> None:
raise TenantValidationError(f"'{tenant_id}' is a reserved subdomain and cannot be used.")
def _normalize_emails(emails: Optional[List[str]]) -> List[str]:
cleaned = sorted({(e or "").strip().lower() for e in (emails or []) if (e or "").strip()})
bad = [e for e in cleaned if not _EMAIL_RE.match(e)]
if bad:
raise TenantValidationError(f"Invalid email address(es): {', '.join(bad)}")
return cleaned
def _normalize_domains(domains: Optional[List[str]]) -> List[str]:
cleaned = sorted(
{(d or "").strip().lower().lstrip("@") for d in (domains or []) if (d or "").strip()}
)
bad = [d for d in cleaned if not _DOMAIN_RE.match(d)]
if bad:
raise TenantValidationError(f"Invalid email domain(s): {', '.join(bad)}")
return cleaned
def _content_type_for(ext: str) -> str:
return IMAGE_CONTENT_TYPES.get(ext.lower(), "application/octet-stream")
@@ -173,6 +203,7 @@ def create_tenant(
tenant_id: Optional[str] = None,
subdomain: Optional[str] = None,
allowed_email_domains: Optional[List[str]] = None,
allowed_emails: Optional[List[str]] = None,
colors: Optional[ColorOverrides] = None,
style_params_override: Optional[Dict] = None,
tagline: Optional[str] = None,
@@ -182,16 +213,23 @@ def create_tenant(
backgrounds: Optional[Dict[str, Tuple[bytes, str]]] = None,
logo: Optional[Tuple[bytes, str]] = None,
storage: Optional[StorageService] = None,
domain_service: Optional[TenantDomainService] = None,
) -> TenantConfig:
"""
Provision a new white-label tenant (theme + config) in GCS.
Provision a new white-label tenant: theme + config in GCS, then its
``{id}.nomadkaraoke.com`` subdomain in Cloudflare. If the subdomain can't be
provisioned the GCS side is rolled back, so a tenant either works end-to-end
or doesn't exist.
Args:
name: Display name (e.g. "Randy Vild").
tenant_id: Slug id; derived from name if omitted.
subdomain: Full subdomain; defaults to ``{id}.nomadkaraoke.com``.
allowed_email_domains: Domains permitted to log in (empty = no restriction;
admins can always sign in).
subdomain: Full subdomain; must be ``{id}.nomadkaraoke.com`` (the portal
edge function and backend middleware derive the tenant id from the
first hostname label). Defaults to that.
allowed_email_domains: Domains permitted to log in.
allowed_emails: Individual addresses permitted to log in (e.g. a client's
gmail). Both lists empty = open portal; admins can always sign in.
colors: Lyric/title/artist colour overrides applied to the theme.
tagline: Optional portal tagline.
distribution_mode: "download_only" (default), "all", or "cloud_only".
@@ -200,12 +238,13 @@ def create_tenant(
backgrounds: {field -> (bytes, ext)} for karaoke/intro/end backgrounds.
logo: (bytes, ext) for the portal logo.
storage: Injected StorageService (for tests).
domain_service: Injected TenantDomainService (for tests).
Returns:
The persisted TenantConfig.
Raises:
TenantValidationError, TenantConflictError, ValueError.
TenantValidationError, TenantConflictError, TenantProvisioningError, ValueError.
"""
name = (name or "").strip()
if not name:
@@ -214,9 +253,16 @@ def create_tenant(
tenant_id = (tenant_id or slugify_tenant_id(name)).strip().lower()
_validate_tenant_id(tenant_id)
subdomain = (subdomain or f"{tenant_id}.{BASE_DOMAIN}").strip().lower()
expected_subdomain = f"{tenant_id}.{BASE_DOMAIN}"
subdomain = (subdomain or expected_subdomain).strip().lower()
if subdomain != expected_subdomain:
raise TenantValidationError(
f"Subdomain must be '{expected_subdomain}' — the portal derives the tenant "
"id from the first label of the hostname."
)
storage = storage or StorageService()
domain_service = domain_service or get_tenant_domain_service()
tenant_service = get_tenant_service()
theme_service = get_theme_service()
@@ -234,6 +280,15 @@ def create_tenant(
f"A theme named '{theme_id}' already exists; choose a different tenant id."
)
# Fail fast (before any write) if the hostname is owned by a non-tenant
# DNS record (e.g. an existing product subdomain) or Cloudflare is unusable.
try:
domain_service.check_available(subdomain)
except TenantDomainConflictError as exc:
raise TenantConflictError(str(exc)) from exc
except TenantDomainError as exc:
raise TenantProvisioningError(str(exc)) from exc
# --- Derive theme from the default Nomad theme ---------------------------
base_theme_id = theme_service.get_default_theme_id()
if not base_theme_id:
@@ -243,7 +298,8 @@ def create_tenant(
raise ValueError(f"Default theme '{base_theme_id}' style params could not be loaded.")
# --- Build the tenant config (logo_url filled in after reservation) -------
domains = sorted({d.strip().lower() for d in (allowed_email_domains or []) if d.strip()})
domains = _normalize_domains(allowed_email_domains)
emails = _normalize_emails(allowed_emails)
now = datetime.now(timezone.utc)
branding = TenantBranding(
@@ -289,7 +345,8 @@ def create_tenant(
),
auth=TenantAuth(
allowed_email_domains=domains,
require_email_domain=bool(domains),
allowed_emails=emails,
require_email_domain=bool(domains or emails),
fixed_token_ids=[],
sender_email=DEFAULT_SENDER_EMAIL,
),
@@ -330,6 +387,7 @@ def create_tenant(
io.BytesIO(data),
f"{THEMES_PREFIX}/{theme_id}/assets/{filename}",
content_type=_content_type_for(ext),
cache_control=NO_STORE_CACHE_CONTROL,
)
style_params.setdefault(section, {})["background_image"] = filename
@@ -341,7 +399,10 @@ def create_tenant(
logo_ext = logo_ext.lower().lstrip(".")
logo_path = f"{TENANTS_PREFIX}/{tenant_id}/logo.{logo_ext}"
storage.upload_fileobj(
io.BytesIO(logo_data), logo_path, content_type=_content_type_for(logo_ext)
io.BytesIO(logo_data),
logo_path,
content_type=_content_type_for(logo_ext),
cache_control=NO_STORE_CACHE_CONTROL,
)
config.branding.logo_url = f"gs://{settings.gcs_bucket_name}/{logo_path}"
config.updated_at = datetime.now(timezone.utc)
@@ -358,6 +419,23 @@ def create_tenant(
tenant_service.invalidate_cache(tenant_id)
theme_service.invalidate_cache()
# --- Subdomain (Cloudflare Pages custom domain + CNAME) ------------------
try:
domain_service.provision(subdomain)
except Exception as exc:
logger.error(f"Provisioning subdomain {subdomain} failed; rolling back tenant '{tenant_id}': {exc}")
try:
_delete_tenant_storage(storage, tenant_id, theme_id)
except Exception: # pragma: no cover - best effort
logger.exception(f"Rollback of tenant '{tenant_id}' storage failed")
try: # a half-provisioned Pages domain (CNAME failed) must not linger
domain_service.deprovision(subdomain)
except Exception: # pragma: no cover - best effort
logger.exception(f"Rollback of subdomain {subdomain} failed")
tenant_service.invalidate_cache(tenant_id)
theme_service.invalidate_cache()
raise TenantProvisioningError(f"Could not set up {subdomain}: {exc}") from exc
logger.info(f"Created tenant '{tenant_id}' (theme '{theme_id}', subdomain '{subdomain}')")
return config
@@ -455,6 +533,13 @@ def update_tenant(
theme_id = _theme_id_for(config)
config_updates = dict(config_updates or {})
new_subdomain = config_updates.pop("subdomain", None) # never persisted as sent
if new_subdomain is not None and str(new_subdomain).strip().lower() != config.subdomain:
raise TenantValidationError(
"The portal subdomain can't be changed (it is derived from the tenant id)."
)
# 1. Assets (uploaded files -> theme assets, keyed by their target basename)
for name, (data, ext) in (assets or {}).items():
safe = _safe_asset_name(name)
@@ -462,6 +547,7 @@ def update_tenant(
io.BytesIO(data),
f"{THEMES_PREFIX}/{theme_id}/assets/{safe}",
content_type=_content_type_for(ext),
cache_control=NO_STORE_CACHE_CONTROL,
)
# 2. Full theme style_params replace
@@ -476,15 +562,32 @@ def update_tenant(
logo_ext = logo_ext.lower().lstrip(".")
logo_path = f"{TENANTS_PREFIX}/{tenant_id}/logo.{logo_ext}"
storage.upload_fileobj(
io.BytesIO(logo_data), logo_path, content_type=_content_type_for(logo_ext)
io.BytesIO(logo_data),
logo_path,
content_type=_content_type_for(logo_ext),
cache_control=NO_STORE_CACHE_CONTROL,
)
branding = dict(merged_updates.get("branding") or {})
branding["logo_url"] = f"gs://{settings.gcs_bucket_name}/{logo_path}"
merged_updates["branding"] = branding
# 4. Config merge
# 4. Config merge (access lists normalized; any allowlist => enforced)
auth_updates = merged_updates.get("auth")
if isinstance(auth_updates, dict):
auth_updates = dict(auth_updates)
if "allowed_emails" in auth_updates:
auth_updates["allowed_emails"] = _normalize_emails(auth_updates["allowed_emails"])
if "allowed_email_domains" in auth_updates:
auth_updates["allowed_email_domains"] = _normalize_domains(
auth_updates["allowed_email_domains"]
)
merged_updates["auth"] = auth_updates
if merged_updates:
config = _merge_config(config, merged_updates)
if isinstance(auth_updates, dict) and "require_email_domain" not in auth_updates:
config.auth.require_email_domain = bool(
config.auth.allowed_email_domains or config.auth.allowed_emails
)
config.updated_at = datetime.now(timezone.utc)
storage.upload_json(f"{TENANTS_PREFIX}/{tenant_id}/config.json", config.model_dump(mode="json"))
@@ -521,9 +624,120 @@ def list_tenants(storage: Optional[StorageService] = None) -> List[Dict[str, obj
"subdomain": data.get("subdomain"),
"is_active": data.get("is_active", True),
"locked_theme": defaults.get("locked_theme"),
"theme_id": defaults.get("theme_id"),
"dropbox_path": defaults.get("dropbox_path"),
"created_at": data.get("created_at"),
}
)
summaries.sort(key=lambda t: str(t.get("name") or t.get("id") or "").lower())
return summaries
def _unregister_theme_metadata(storage: StorageService, theme_id: str) -> None:
"""Remove a theme from themes/_metadata.json (read-modify-write, idempotent)."""
try:
registry = storage.download_json(METADATA_FILE)
except Exception:
return
themes = registry.get("themes") or []
kept = [t for t in themes if t.get("id") != theme_id]
if len(kept) != len(themes):
registry["themes"] = kept
storage.upload_json(METADATA_FILE, registry)
def _delete_tenant_storage(storage: StorageService, tenant_id: str, theme_id: Optional[str]) -> None:
"""Delete a tenant's theme (files + registry entry) and config/logo from GCS."""
if theme_id:
_unregister_theme_metadata(storage, theme_id)
storage.delete_folder(f"{THEMES_PREFIX}/{theme_id}/")
# Config last: while it exists the tenant is still addressable for a retry.
storage.delete_folder(f"{TENANTS_PREFIX}/{tenant_id}/")
def delete_tenant(
tenant_id: str,
*,
storage: Optional[StorageService] = None,
domain_service: Optional[TenantDomainService] = None,
) -> None:
"""
Delete a tenant completely: its subdomain (Cloudflare Pages domain + CNAME),
its theme (assets, style_params, registry entry) and its config/logo.
Jobs already created for the tenant are kept (finished outputs stay
downloadable) but can no longer be re-rendered with the deleted theme.
The theme is kept if it is the default theme or another tenant still uses it.
Raises:
TenantNotFoundError, TenantProvisioningError (nothing in GCS is deleted
if the subdomain can't be removed, so the delete can simply be retried).
"""
storage = storage or StorageService()
domain_service = domain_service or get_tenant_domain_service()
tenant_service = get_tenant_service()
theme_service = get_theme_service()
config = tenant_service.get_tenant_config(tenant_id, force_refresh=True)
if not config:
raise TenantNotFoundError(f"Tenant '{tenant_id}' not found.")
# Always the canonical host (subdomain changes are rejected, but legacy
# configs could differ) — deprovision only ever touches OUR records.
hostname = TenantDomainService.hostname_for(tenant_id)
try:
domain_service.deprovision(hostname)
except TenantDomainError as exc:
raise TenantProvisioningError(f"Could not remove {hostname}: {exc}") from exc
# Delete the tenant's own 1:1 theme (named after the tenant — the one
# create_tenant made) even if the tenant has since switched to another
# theme; never delete a theme another tenant uses or the default theme.
theme_id: Optional[str] = tenant_id
shared = any(
t.get("id") != tenant_id and theme_id in (t.get("locked_theme"), t.get("theme_id"))
for t in list_tenants(storage)
)
if shared or theme_id == theme_service.get_default_theme_id():
logger.info(f"Keeping theme '{theme_id}' while deleting tenant '{tenant_id}'")
theme_id = None
_delete_tenant_storage(storage, tenant_id, theme_id)
# delete_folder swallows errors — verify, so a failed delete isn't a 204.
if storage.file_exists(f"{TENANTS_PREFIX}/{tenant_id}/config.json"):
raise TenantProvisioningError(
f"Subdomain removed but tenant '{tenant_id}' storage could not be deleted; retry the delete."
)
tenant_service.invalidate_cache(tenant_id)
theme_service.invalidate_cache()
logger.info(f"Deleted tenant '{tenant_id}' (subdomain '{hostname}', theme '{theme_id}')")
def get_tenant_domain_status(
tenant_id: str, *, domain_service: Optional[TenantDomainService] = None
) -> Optional[Dict[str, object]]:
"""Cloudflare provisioning state of the tenant's subdomain (None if unavailable)."""
domain_service = domain_service or get_tenant_domain_service()
try:
return domain_service.status(TenantDomainService.hostname_for(tenant_id)).to_dict()
except TenantDomainError as exc:
logger.warning(f"Could not read domain status for tenant '{tenant_id}': {exc}")
return None
def provision_tenant_domain(
tenant_id: str, *, domain_service: Optional[TenantDomainService] = None
) -> Dict[str, object]:
"""(Re)provision an existing tenant's subdomain — for tenants created before
automation, or to retry after a transient Cloudflare failure."""
domain_service = domain_service or get_tenant_domain_service()
if not get_tenant_service().tenant_exists(tenant_id):
raise TenantNotFoundError(f"Tenant '{tenant_id}' not found.")
hostname = TenantDomainService.hostname_for(tenant_id)
try:
return domain_service.provision(hostname).to_dict()
except TenantDomainConflictError as exc:
raise TenantConflictError(str(exc)) from exc
except TenantDomainError as exc:
raise TenantProvisioningError(str(exc)) from exc
+219
View File
@@ -0,0 +1,219 @@
"""
Cloudflare provisioning for tenant portal subdomains.
Every white-label tenant is served at ``{tenant_id}.nomadkaraoke.com`` by the
shared ``karaoke-gen-tenant`` Cloudflare Pages project (its edge function reads
the tenant id from the first hostname label). Cloudflare Pages has no wildcard
custom domains, so each tenant needs two Cloudflare objects:
1. a Pages custom domain on ``karaoke-gen-tenant`` (Cloudflare issues the cert), and
2. a proxied ``CNAME {tenant_id} -> karaoke-gen-tenant.pages.dev`` in the
``nomadkaraoke.com`` zone.
Both operations are idempotent. We never take over or delete a DNS record that
points anywhere other than the tenant Pages project, so a tenant id can't hijack
a real subdomain (e.g. ``decide``) and deleting a tenant can't remove one.
Auth: ``cloudflare-tenant-domains-token`` secret (account-owned token scoped to
Pages Read/Write on the account + DNS Read/Write on the nomadkaraoke.com zone).
"""
import logging
import os
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
import httpx
from backend.config import get_settings
logger = logging.getLogger(__name__)
CF_API = "https://api.cloudflare.com/client/v4"
CF_TOKEN_SECRET = "cloudflare-tenant-domains-token"
# Non-secret identifiers (overridable for tests / other environments).
CF_ACCOUNT_ID = os.getenv("CLOUDFLARE_ACCOUNT_ID", "a7dd2a2bee7151ef4dc7a9f53d99b520")
CF_ZONE_ID = os.getenv("CLOUDFLARE_NOMADKARAOKE_ZONE_ID", "807f07f458f9cd38251f3b7948d55172")
PAGES_PROJECT = os.getenv("TENANT_PAGES_PROJECT", "karaoke-gen-tenant")
PAGES_TARGET = f"{PAGES_PROJECT}.pages.dev"
BASE_DOMAIN = "nomadkaraoke.com"
class TenantDomainError(RuntimeError):
"""Cloudflare provisioning failed (API error, missing token, ...)."""
class TenantDomainConflictError(TenantDomainError):
"""The hostname already has a DNS record we don't own."""
@dataclass
class DomainStatus:
"""Provisioning state of one tenant hostname."""
hostname: str
dns_ok: bool
pages_status: Optional[str] # "active", "initializing", "pending", ... or None if absent
@property
def active(self) -> bool:
return self.dns_ok and self.pages_status == "active"
def to_dict(self) -> Dict[str, Any]:
if self.active:
state = "active"
elif self.dns_ok or self.pages_status:
state = "provisioning"
else:
state = "missing"
return {
"hostname": self.hostname,
"state": state,
"dns_ok": self.dns_ok,
"pages_status": self.pages_status,
}
class TenantDomainService:
def __init__(
self,
api_token: Optional[str] = None,
client: Optional[httpx.Client] = None,
account_id: str = CF_ACCOUNT_ID,
zone_id: str = CF_ZONE_ID,
pages_project: str = PAGES_PROJECT,
):
self._api_token = api_token
self._client = client
self.account_id = account_id
self.zone_id = zone_id
self.pages_project = pages_project
self.pages_target = f"{pages_project}.pages.dev"
# --- HTTP plumbing -------------------------------------------------------
def _token(self) -> str:
if not self._api_token:
self._api_token = get_settings().get_secret(CF_TOKEN_SECRET)
if not self._api_token:
raise TenantDomainError(
f"Cloudflare token secret '{CF_TOKEN_SECRET}' is not configured; "
"tenant subdomains can't be provisioned."
)
return self._api_token
def _http(self) -> httpx.Client:
if self._client is None:
self._client = httpx.Client(base_url=CF_API, timeout=20.0)
return self._client
def _request(self, method: str, path: str, *, allow_404: bool = False, **kwargs) -> Optional[Dict]:
headers = {"Authorization": f"Bearer {self._token()}"}
try:
resp = self._http().request(method, path, headers=headers, **kwargs)
except httpx.HTTPError as exc:
raise TenantDomainError(f"Cloudflare API {method} {path} failed: {exc}") from exc
if resp.status_code == 404 and allow_404:
return None
try:
body = resp.json()
except ValueError:
body = {}
if resp.status_code >= 400 or not body.get("success", False):
errors = body.get("errors") or resp.text[:300]
raise TenantDomainError(f"Cloudflare API {method} {path} -> {resp.status_code}: {errors}")
return body
# --- Pages custom domain -------------------------------------------------
def _pages_domains_path(self) -> str:
return f"/accounts/{self.account_id}/pages/projects/{self.pages_project}/domains"
def _get_pages_domain(self, hostname: str) -> Optional[Dict]:
body = self._request("GET", f"{self._pages_domains_path()}/{hostname}", allow_404=True)
return body.get("result") if body else None
# --- DNS -------------------------------------------------------------------
def _dns_records(self, hostname: str) -> List[Dict]:
body = self._request(
"GET", f"/zones/{self.zone_id}/dns_records", params={"name": hostname}
)
return body.get("result") or []
def _is_ours(self, record: Dict) -> bool:
return (
record.get("type") == "CNAME"
and (record.get("content") or "").rstrip(".").lower() == self.pages_target
)
# --- Public API ------------------------------------------------------------
@staticmethod
def hostname_for(tenant_id: str) -> str:
return f"{tenant_id}.{BASE_DOMAIN}"
def check_available(self, hostname: str) -> None:
"""Raise TenantDomainConflictError if a foreign DNS record owns ``hostname``."""
foreign = [r for r in self._dns_records(hostname) if not self._is_ours(r)]
if foreign:
kinds = ", ".join(f"{r.get('type')} -> {r.get('content')}" for r in foreign)
raise TenantDomainConflictError(
f"{hostname} already has DNS records not managed by the tenant portal ({kinds})."
)
def provision(self, hostname: str) -> DomainStatus:
"""Idempotently attach ``hostname`` to the tenant Pages project + create its CNAME."""
self.check_available(hostname)
pages = self._get_pages_domain(hostname)
if pages is None:
body = self._request("POST", self._pages_domains_path(), json={"name": hostname})
pages = body.get("result") or {}
logger.info(f"Added Pages custom domain {hostname} to {self.pages_project}")
if not any(self._is_ours(r) for r in self._dns_records(hostname)):
label = hostname[: -len(BASE_DOMAIN) - 1]
self._request(
"POST",
f"/zones/{self.zone_id}/dns_records",
json={
"type": "CNAME",
"name": label,
"content": self.pages_target,
"proxied": True,
"comment": "karaoke-gen tenant portal (managed by admin tenant console)",
},
)
logger.info(f"Created DNS CNAME {hostname} -> {self.pages_target}")
return DomainStatus(hostname=hostname, dns_ok=True, pages_status=pages.get("status"))
def status(self, hostname: str) -> DomainStatus:
pages = self._get_pages_domain(hostname)
dns_ok = any(self._is_ours(r) for r in self._dns_records(hostname))
return DomainStatus(
hostname=hostname, dns_ok=dns_ok, pages_status=(pages or {}).get("status")
)
def deprovision(self, hostname: str) -> None:
"""Remove the Pages custom domain and OUR CNAME (foreign records are left alone)."""
if self._get_pages_domain(hostname) is not None:
self._request("DELETE", f"{self._pages_domains_path()}/{hostname}", allow_404=True)
logger.info(f"Removed Pages custom domain {hostname}")
for record in self._dns_records(hostname):
if self._is_ours(record):
self._request(
"DELETE", f"/zones/{self.zone_id}/dns_records/{record['id']}", allow_404=True
)
logger.info(f"Deleted DNS CNAME {hostname}")
_service: Optional[TenantDomainService] = None
def get_tenant_domain_service() -> TenantDomainService:
global _service
if _service is None:
_service = TenantDomainService()
return _service
+6
View File
@@ -434,6 +434,12 @@ class ThemeService:
True if theme exists, False otherwise
"""
metadata = self._load_metadata()
if any(t.id == theme_id for t in metadata.themes):
return True
# The registry cache is per-instance: a theme just created (e.g. by the
# admin tenant console on another instance) won't be in it yet. Re-read
# before rejecting.
metadata = self._load_metadata(force_refresh=True)
return any(t.id == theme_id for t in metadata.themes)
def get_default_theme_id(self) -> Optional[str]:
@@ -71,7 +71,7 @@ def endpoint_mocks():
job_manager.create_job.return_value = Mock(job_id="job-123")
storage.generate_signed_upload_url.return_value = "https://signed-put"
storage.create_resumable_upload_session.return_value = "https://session-uri"
yield {"storage": storage, "job_manager": job_manager}
yield {"storage": storage, "job_manager": job_manager, "theme_svc": theme_svc}
@pytest.mark.asyncio
@@ -125,3 +125,17 @@ async def test_requires_audio_edit_not_set_by_default(endpoint_mocks, auth):
await create_job_with_upload_urls(_request(), _body(), auth)
keys = [c.args[1] for c in endpoint_mocks["job_manager"].update_state_data.call_args_list]
assert "requires_audio_edit" not in keys
@pytest.mark.asyncio
async def test_unknown_theme_rejected_before_job_is_created(endpoint_mocks, auth):
"""Regression: theme validation ran after create_job, so a 400 "Theme not found"
(e.g. tenant bulk submit right after tenant creation) left orphaned
"Waiting for upload" jobs behind."""
from fastapi import HTTPException
endpoint_mocks["theme_svc"].return_value.theme_exists.return_value = False
with pytest.raises(HTTPException) as exc:
await create_job_with_upload_urls(_request(), _body(theme_id="missing-theme"), auth)
assert exc.value.status_code == 400
endpoint_mocks["job_manager"].create_job.assert_not_called()
+4 -2
View File
@@ -28,8 +28,10 @@ def _cloud_run_task_timeout_seconds() -> int:
pathlib.Path(__file__).resolve().parents[2]
/ "infrastructure" / "modules" / "cloud_run.py"
).read_text()
# The audio-download job block sets timeout="NNNNs" right before max_retries.
m = re.search(r'timeout="(\d+)s",\s*\n\s*max_retries=2,\s*\n\s*vpc_access=', src)
# Scope to the create_audio_download_job() body, then take its task timeout.
start = src.index("def create_audio_download_job(")
end = src.index("\ndef ", start + 1)
m = re.search(r'timeout="(\d+)s",\s*\n\s*max_retries=2,', src[start:end])
assert m, "could not locate audio-download-job timeout in cloud_run.py"
return int(m.group(1))
+7 -7
View File
@@ -176,15 +176,15 @@ class TestSelectGreenRankingSharedWithRuntime:
# 6-type pool with explicit machine_type (mirrors the post-rollout secret).
POOL = [
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.1",
"machine_type": "c4-highcpu-32"},
"machine_type": "c4-highcpu-16"},
{"vm": "encoding-worker-fallback-n4db", "zone": "us-central1-b", "ip": "10.0.0.2",
"machine_type": "n4d-highcpu-32"},
"machine_type": "n4d-highcpu-16"},
{"vm": "encoding-worker-fallback-c2df", "zone": "us-central1-f", "ip": "10.0.0.3",
"machine_type": "c2d-highcpu-32"},
"machine_type": "c2d-highcpu-16"},
{"vm": "encoding-worker-fallback-n2da", "zone": "us-central1-a", "ip": "10.0.0.4",
"machine_type": "n2d-highcpu-32"},
"machine_type": "n2d-highcpu-16"},
{"vm": "encoding-worker-fallback-n2c", "zone": "us-central1-c", "ip": "10.0.0.5",
"machine_type": "n2-highcpu-32"},
"machine_type": "n2-highcpu-16"},
]
def test_secondary_c4d_leads_then_fastest_fallbacks(self):
@@ -205,7 +205,7 @@ class TestSelectGreenRankingSharedWithRuntime:
from datetime import datetime, timezone
cfg = _config(
active_override_vm=None,
capacity_state={"c4d-highcpu-32@us-central1-c": datetime.now(timezone.utc).isoformat()},
capacity_state={"c4d-highcpu-16@us-central1-c": datetime.now(timezone.utc).isoformat()},
)
cands = select_green_candidates(cfg, self.POOL)
vms = [c["vm"] for c in cands]
@@ -218,4 +218,4 @@ class TestSelectGreenRankingSharedWithRuntime:
def test_machine_type_carried_through(self):
cands = select_green_candidates(_config(active_override_vm=None), self.POOL)
c4 = next(c for c in cands if c["vm"] == "encoding-worker-fallback-c4a")
assert c4["machine_type"] == "c4-highcpu-32"
assert c4["machine_type"] == "c4-highcpu-16"
+177
View File
@@ -0,0 +1,177 @@
"""Approximate vocals (mix − aligned user instrumental) for the review waveform."""
import os
import shutil
import subprocess
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import numpy as np
import pytest
from backend.services.derived_vocals import (
SAMPLE_RATE,
DerivedVocalsError,
derive_vocals_file,
find_offset,
subtract_instrumental,
)
from backend.utils.stems import vocals_stem_path
requires_ffmpeg = pytest.mark.skipif(
shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None, reason="ffmpeg not installed"
)
def _signals(lag, gain=0.8, seconds=6):
rng = np.random.default_rng(1)
n = SAMPLE_RATE * seconds
inst = rng.normal(0, 0.2, n).astype(np.float32)
t = np.arange(n) / SAMPLE_RATE
# "vocals": 440 Hz bursts every other second
vocals = (0.3 * np.sin(2 * np.pi * 440 * t) * ((t.astype(int) % 2) == 0)).astype(np.float32)
shifted = np.zeros(n, dtype=np.float32)
if lag >= 0:
shifted[lag:] = inst[: n - lag]
else:
shifted[: n + lag] = inst[-lag:]
return vocals + gain * shifted, inst, vocals
@pytest.mark.parametrize("lag", [0, 300, -1200, 20000, -44000])
def test_find_offset_recovers_known_lag(lag):
mix, inst, _ = _signals(lag)
assert find_offset(mix, inst, int(2 * SAMPLE_RATE)) == lag
@pytest.mark.parametrize("lag", [-100, 100])
def test_find_offset_on_very_short_input_is_not_ambiguous(lag):
"""Regression: with inputs shorter than the lag window, positive/negative lag
slices used to overlap and a negative lag came back as a large positive one."""
mix, inst, _ = _signals(lag, seconds=1)
assert find_offset(mix, inst, int(2 * SAMPLE_RATE)) == lag
def test_find_offset_uses_bounded_window_on_long_tracks():
"""Alignment correlates a fixed excerpt, so a long track costs the same
memory/time as a short one (a whole-track FFT could OOM the lyrics worker)."""
mix, inst, _ = _signals(lag=777, seconds=240)
with patch("backend.services.derived_vocals.np.fft.rfft", wraps=np.fft.rfft) as rfft:
assert find_offset(mix, inst, int(2 * SAMPLE_RATE), window=int(10 * SAMPLE_RATE)) == 777
assert max(call.args[1] for call in rfft.call_args_list) <= 1 << 20
def test_subtraction_recovers_vocals_and_gain():
mix, inst, vocals = _signals(lag=300, gain=0.8)
residual, result = subtract_instrumental(mix, inst)
assert result.offset_samples == 300
assert result.gain == pytest.approx(0.8, abs=0.02)
assert result.residual_ratio == pytest.approx(float(np.dot(vocals, vocals) / np.dot(mix, mix)), abs=0.02)
assert np.corrcoef(residual, vocals)[0, 1] > 0.98
def test_unrelated_instrumental_leaves_the_mix_mostly_intact():
mix, _, _ = _signals(lag=0)
other = np.random.default_rng(7).normal(0, 0.2, len(mix)).astype(np.float32)
residual, result = subtract_instrumental(mix, other)
assert result.residual_ratio > 0.9
assert np.corrcoef(residual, mix)[0, 1] > 0.95
def _write_wav(path, samples, sr=44100):
# Write at 44.1 kHz stereo like a real upload; the module resamples to mono 22.05 kHz.
up = np.repeat(samples, 2).astype(np.float32)
subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "f32le", "-ar", str(sr), "-ac", "1", "-i", "-",
"-ac", "2", "-c:a", "pcm_s24le", path], input=up.tobytes(), check=True)
@requires_ffmpeg
def test_derive_vocals_file_end_to_end(tmp_path):
mix, inst, vocals = _signals(lag=150)
mix_path, inst_path, out_path = (str(tmp_path / n) for n in ("mix.wav", "inst.wav", "out.flac"))
_write_wav(mix_path, mix)
_write_wav(inst_path, inst)
result = derive_vocals_file(mix_path, inst_path, out_path)
assert result.useful
assert os.path.getsize(out_path) > 0
assert abs(result.offset_samples - 150) <= 1
assert result.gain == pytest.approx(0.8, abs=0.02)
# ≈ the vocals' share of the mix energy (~0.47 here) — i.e. the instrumental cancelled
ideal = float(np.dot(vocals, vocals) / np.dot(mix, mix))
assert result.residual_ratio == pytest.approx(ideal, abs=0.1)
probe = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "stream=codec_name,channels,sample_rate",
"-of", "csv=p=0", out_path], capture_output=True, text=True, check=True).stdout.strip()
assert probe == f"flac,{SAMPLE_RATE},1"
def test_vocals_stem_path_uses_derived_only_as_last_resort():
derived = SimpleNamespace(file_urls={"stems": {"vocals_derived": "d.flac"}})
both = SimpleNamespace(file_urls={"stems": {"vocals_derived": "d.flac", "vocals_clean": "v.flac"}})
assert vocals_stem_path(derived) == "d.flac"
assert vocals_stem_path(both) == "v.flac"
class TestStoreDerivedVocals:
def _call(self, tmp_path, derive):
from backend.workers.lyrics_worker import _store_derived_vocals
storage, job_manager, job_log = MagicMock(), MagicMock(), MagicMock()
with patch("backend.services.derived_vocals.derive_vocals_file", derive):
_store_derived_vocals("j1", "uploads/j1/audio/existing_instrumental.wav", "/tmp/mix.wav",
storage, job_manager, job_log)
return storage, job_manager, job_log
def test_uploads_and_registers_waveform_stem(self, tmp_path):
derive = MagicMock(return_value=SimpleNamespace(offset_samples=0, gain=1.0, residual_ratio=0.1, useful=True))
storage, job_manager, _ = self._call(tmp_path, derive)
assert storage.download_file.call_args[0][0] == "uploads/j1/audio/existing_instrumental.wav"
local_out, remote = storage.upload_file.call_args[0]
assert local_out.endswith("vocals_derived.flac") and remote == "jobs/j1/stems/vocals_derived.flac"
# own temp dir, cleaned up afterwards
assert not os.path.exists(os.path.dirname(local_out))
job_manager.update_file_url.assert_called_once_with("j1", "stems", "vocals_derived", "jobs/j1/stems/vocals_derived.flac")
def test_useless_subtraction_is_not_registered(self, tmp_path):
derive = MagicMock(return_value=SimpleNamespace(offset_samples=0, gain=0.0, residual_ratio=0.99, useful=False))
storage, job_manager, job_log = self._call(tmp_path, derive)
storage.upload_file.assert_not_called()
job_manager.update_file_url.assert_not_called()
assert "no vocal waveform" in job_log.info.call_args[0][0]
def test_failure_is_non_fatal(self, tmp_path):
derive = MagicMock(side_effect=RuntimeError("ffmpeg exploded"))
_, job_manager, job_log = self._call(tmp_path, derive)
job_manager.update_file_url.assert_not_called()
assert "non-fatal" in job_log.warning.call_args[0][0]
@requires_ffmpeg
def test_unrelated_instrumental_is_not_written(tmp_path):
"""A subtraction that removed nothing would just show the full-mix envelope."""
mix, _, _ = _signals(lag=0)
other = np.random.default_rng(9).normal(0, 0.2, len(mix)).astype(np.float32)
mix_path, inst_path, out_path = (str(tmp_path / n) for n in ("mix.wav", "inst.wav", "out.flac"))
_write_wav(mix_path, mix)
_write_wav(inst_path, other)
result = derive_vocals_file(mix_path, inst_path, out_path)
assert not result.useful
assert not os.path.exists(out_path)
@requires_ffmpeg
def test_empty_or_undecodable_input_raises_with_ffmpeg_detail(tmp_path):
bad = tmp_path / "bad.wav"
bad.write_bytes(b"not audio at all")
with pytest.raises(DerivedVocalsError, match="ffmpeg failed"):
derive_vocals_file(str(bad), str(bad), str(tmp_path / "o.flac"))
silent = str(tmp_path / "tiny.wav")
_write_wav(silent, np.zeros(1000, dtype=np.float32)) # ~0.05s
with pytest.raises(DerivedVocalsError, match="decoded only"):
derive_vocals_file(silent, silent, str(tmp_path / "o.flac"))
+66
View File
@@ -531,3 +531,69 @@ class TestFileExists:
service.file_exists("Karaoke/x.flac")
mock_client.files_get_metadata.assert_called_once_with("/Karaoke/x.flac")
class TestDropboxLosslessExclusion:
"""2026-09-26 cost cut: Nomad's own Dropbox folders skip the lossless 4K MP4
(it stays in GCS); tenant folders still get everything."""
@patch("backend.services.dropbox_service.secretmanager.SecretManagerServiceClient")
def test_upload_folder_skips_excluded_suffixes(self, mock_sm_client_class, tmp_path):
from backend.services.dropbox_service import DropboxService
mock_response = Mock()
mock_response.payload.data = json.dumps({"access_token": "token"}).encode()
mock_sm_client_class.return_value.access_secret_version.return_value = mock_response
(tmp_path / "A - B (Final Karaoke Lossless 4k).mp4").write_text("x")
(tmp_path / "A - B (Final Karaoke Lossless 4k).mkv").write_text("x")
(tmp_path / "A - B (Final Karaoke Lossy 4k).mp4").write_text("x")
service = DropboxService()
with patch.object(service, "upload_file") as mock_upload:
service.upload_folder(
str(tmp_path), "/Uploads/folder",
exclude_suffixes=(" (Final Karaoke Lossless 4k).mp4",),
)
uploaded = sorted(c.args[1].rsplit("/", 1)[1] for c in mock_upload.call_args_list)
assert uploaded == [
"A - B (Final Karaoke Lossless 4k).mkv",
"A - B (Final Karaoke Lossy 4k).mp4",
]
def _settings(self, suffixes=" (Final Karaoke Lossless 4k).mp4"):
s = Mock()
s.default_dropbox_path = "/MediaUnsynced/Karaoke/Tracks-Organized"
s.default_private_dropbox_path = "/MediaUnsynced/Karaoke/Tracks-NonPublished"
s.dropbox_skip_output_suffixes = suffixes
return s
def test_own_folders_skip_lossless_mp4_only_by_default(self):
from backend.config import Settings
from backend.services.dropbox_service import dropbox_skip_suffixes_for
default = Settings().dropbox_skip_output_suffixes
with patch("backend.config.get_settings", return_value=self._settings(default)):
for path in ("/MediaUnsynced/Karaoke/Tracks-Organized",
"/MediaUnsynced/Karaoke/Tracks-NonPublished/"):
skip = dropbox_skip_suffixes_for(path)
assert skip == (" (Final Karaoke Lossless 4k).mp4",)
# The MKV is promised in the Dropbox folder (completion email, Fiverr bot).
assert not any(s.endswith(".mkv") for s in skip)
def test_tenant_folder_gets_everything(self):
from backend.services.dropbox_service import dropbox_skip_suffixes_for
with patch("backend.config.get_settings", return_value=self._settings()):
assert dropbox_skip_suffixes_for("/MediaUnsynced/Karaoke/Tracks-VocalStar") == ()
assert dropbox_skip_suffixes_for(None) == ()
def test_multiple_suffixes_and_empty_config(self):
from backend.services.dropbox_service import dropbox_skip_suffixes_for
both = " (Final Karaoke Lossless 4k).mp4| (Final Karaoke Lossless 4k).mkv"
with patch("backend.config.get_settings", return_value=self._settings(both)):
assert len(dropbox_skip_suffixes_for("/MediaUnsynced/Karaoke/Tracks-Organized")) == 2
with patch("backend.config.get_settings", return_value=self._settings("")):
assert dropbox_skip_suffixes_for("/MediaUnsynced/Karaoke/Tracks-Organized") == ()
@@ -105,3 +105,31 @@ class TestDisposableDomainList:
def test_gmail_not_in_defaults(self):
from backend.services.email_validation_service import DEFAULT_DISPOSABLE_DOMAINS
assert "gmail.com" not in DEFAULT_DISPOSABLE_DOMAINS
class TestTenantVouchedEmails:
"""A tenant portal's explicitly allowlisted addresses skip the disposable
heuristics (an admin vouched for them); everyone else is still checked."""
def _tenant(self):
from backend.models.tenant import TenantAuth, TenantConfig
return TenantConfig(
id="randy-vild",
name="Randy Vild",
subdomain="randy-vild.nomadkaraoke.com",
auth=TenantAuth(allowed_emails=["randy@weird-domain.example"], require_email_domain=True),
)
def test_explicitly_allowlisted_email_skips_disposable_check(self, client, mock_validation_svc):
mock_validation_svc.is_disposable_domain.return_value = True
with patch("backend.middleware.tenant.get_tenant_config_from_request", return_value=self._tenant()):
response = client.post("/api/users/auth/magic-link", json={"email": "randy@weird-domain.example"})
assert response.status_code != 422
mock_validation_svc.is_disposable_domain.assert_not_called()
def test_other_emails_on_tenant_portal_still_checked(self, client, mock_validation_svc):
mock_validation_svc.is_disposable_domain.return_value = True
with patch("backend.middleware.tenant.get_tenant_config_from_request", return_value=self._tenant()):
response = client.post("/api/users/auth/magic-link", json={"email": "abuse@tempmail.com"})
assert response.status_code == 422
@@ -178,6 +178,23 @@ class TestDisposableDomainDetection:
def test_detect_invalid_email_returns_false(self, email_service):
"""Test invalid email returns False."""
assert email_service.is_disposable_domain("notanemail") is False
def test_own_domain_never_disposable_even_if_blocklisted(self, email_service, mock_db, mock_external_apis):
"""Regression: nomadkaraoke.com got auto-learned as disposable (external API
false positive), blocking every admin magic-link sign-in."""
mock_db.collection.return_value.document.return_value.get.return_value.to_dict.return_value[
"manual_domains"
] = ["nomadkaraoke.com"]
type(email_service)._blocklist_cache = None
mock_external_apis.return_value.get.return_value.json.return_value = {"disposable": "true"}
assert email_service.is_disposable_domain("randy@nomadkaraoke.com") is False
assert email_service.is_disposable_domain("Admin@NomadKaraoke.com") is False
mock_external_apis.return_value.get.assert_not_called()
def test_auto_learn_refuses_own_domain(self, email_service, mock_db):
mock_db.reset_mock()
email_service._auto_learn_domain("nomadkaraoke.com")
mock_db.collection.return_value.document.return_value.set.assert_not_called()
assert email_service.is_disposable_domain("") is False
+193 -5
View File
@@ -869,6 +869,194 @@ class TestWaitForCompletionLostJob:
assert result["status"] == "complete"
class TestWaitForCompletionWorkerStopped:
"""The a/b workers run on Spot (2026-09-26). A preempted (STOPPED) worker VM
must surface as a lost job immediately so run_with_lost_job_resubmit re-submits
it, instead of burning the poll tolerance and failing with "lost contact"."""
def _with_manager(self, encoding_service, vm_status, fallbacks_json=None):
cfg = MagicMock()
cfg.primary_vm, cfg.primary_ip = "encoding-worker-a", "10.0.0.1"
cfg.secondary_vm, cfg.secondary_ip = "encoding-worker-b", "10.0.0.2"
cfg.active_override_vm = cfg.active_override_ip = cfg.active_override_zone = None
mgr = MagicMock()
mgr._zone = "us-central1-c"
mgr.get_config.return_value = cfg
mgr.get_vm_status.return_value = vm_status
encoding_service._worker_manager = mgr
encoding_service.settings.encoding_worker_fallback_vms = fallbacks_json
return mgr
@staticmethod
async def _conn_refused(job_id, worker_url=None):
raise aiohttp.ClientConnectorError(
connection_key=MagicMock(), os_error=OSError("Connection refused")
)
@pytest.mark.asyncio
async def test_preempted_worker_raises_lost_error_on_first_failure(self, encoding_service):
mgr = self._with_manager(encoding_service, "TERMINATED")
calls = 0
async def status(job_id, worker_url=None):
nonlocal calls
calls += 1
if calls == 1:
return {"status": "running", "progress": 40}
return await self._conn_refused(job_id, worker_url)
with patch.object(encoding_service, "get_job_status", side_effect=status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
with pytest.raises(EncodingJobLostError, match="encoding-worker-a is TERMINATED"):
await encoding_service.wait_for_completion(
"j1", worker_url="http://10.0.0.1:8080"
)
assert calls == 2 # bailed on the first failed poll
mgr.get_vm_status.assert_called_with("encoding-worker-a", "us-central1-c")
@pytest.mark.asyncio
async def test_stopped_fallback_worker_resolved_via_fallback_list(self, encoding_service):
import json
mgr = self._with_manager(
encoding_service, "STOPPING",
fallbacks_json=json.dumps([{"vm": "encoding-worker-fallback-c2df",
"zone": "us-central1-f", "ip": "10.0.0.9"}]),
)
with patch.object(encoding_service, "get_job_status", side_effect=self._conn_refused), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
with pytest.raises(EncodingJobLostError):
await encoding_service.wait_for_completion(
"j1", worker_url="http://10.0.0.9:8080"
)
mgr.get_vm_status.assert_called_with("encoding-worker-fallback-c2df", "us-central1-f")
@pytest.mark.asyncio
async def test_running_worker_keeps_normal_poll_tolerance(self, encoding_service):
"""A RUNNING VM that's just slow/unreachable is NOT a lost job."""
self._with_manager(encoding_service, "RUNNING")
with patch.object(encoding_service, "get_job_status", side_effect=self._conn_refused), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
with pytest.raises(RuntimeError, match="consecutive poll failures"):
await encoding_service.wait_for_completion(
"j1", worker_url="http://10.0.0.1:8080"
)
@pytest.mark.asyncio
async def test_unknown_worker_ip_keeps_normal_poll_tolerance(self, encoding_service):
mgr = self._with_manager(encoding_service, "TERMINATED")
with patch.object(encoding_service, "get_job_status", side_effect=self._conn_refused), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
with pytest.raises(RuntimeError, match="consecutive poll failures"):
await encoding_service.wait_for_completion(
"j1", worker_url="http://10.9.9.9:8080"
)
mgr.get_vm_status.assert_not_called()
@pytest.mark.asyncio
async def test_status_lookup_failure_is_non_fatal(self, encoding_service):
mgr = self._with_manager(encoding_service, "TERMINATED")
mgr.get_vm_status.side_effect = Exception("compute API down")
with patch.object(encoding_service, "get_job_status", side_effect=self._conn_refused), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
with pytest.raises(RuntimeError, match="consecutive poll failures"):
await encoding_service.wait_for_completion(
"j1", worker_url="http://10.0.0.1:8080"
)
@pytest.mark.asyncio
async def test_restarted_worker_mid_boot_counts_as_lost(self, encoding_service):
"""Another request restarted the preempted VM before our poll — STAGING
means it went down, so the job (accepted while RUNNING) is gone."""
self._with_manager(encoding_service, "STAGING")
with patch.object(encoding_service, "get_job_status", side_effect=self._conn_refused), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
with pytest.raises(EncodingJobLostError):
await encoding_service.wait_for_completion(
"j1", worker_url="http://10.0.0.1:8080"
)
@pytest.mark.asyncio
async def test_polling_refreshes_worker_activity_at_most_once_a_minute(self, encoding_service):
"""Keeps the routed VM inside the 5-min idle window for the whole encode,
so it isn't stopped between the job finishing and us collecting it."""
mgr = self._with_manager(encoding_service, "RUNNING")
# First call is wait_for_completion's start_time, then one per poll.
clock = iter([0, 0, 10, 20, 70, 80, 150])
statuses = iter([
{"status": "running", "progress": 10},
{"status": "running", "progress": 20},
{"status": "running", "progress": 30},
{"status": "running", "progress": 40},
{"status": "running", "progress": 50},
{"status": "complete", "output_files": ["a.mp4"]},
])
async def status(job_id, worker_url=None):
return next(statuses)
with patch.object(encoding_service, "get_job_status", side_effect=status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.side_effect = lambda: next(clock)
result = await encoding_service.wait_for_completion(
"j1", worker_url="http://10.0.0.1:8080"
)
assert result["status"] == "complete"
# Touched at t=0, t=70, t=150 (>= 60s apart), not on every poll.
assert mgr.update_activity.call_count == 3
@pytest.mark.asyncio
async def test_activity_refresh_failure_does_not_fail_the_poll(self, encoding_service):
mgr = self._with_manager(encoding_service, "RUNNING")
mgr.update_activity.side_effect = Exception("firestore down")
async def status(job_id, worker_url=None):
return {"status": "complete", "output_files": ["a.mp4"]}
with patch.object(encoding_service, "get_job_status", side_effect=status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
result = await encoding_service.wait_for_completion("j1")
assert result["status"] == "complete"
@pytest.mark.asyncio
async def test_preemption_is_resubmitted_by_run_with_lost_job_resubmit(self, encoding_service):
"""End-to-end: a preempted first attempt is resubmitted under a fresh id."""
self._with_manager(encoding_service, "TERMINATED")
attempts = []
async def operation(job_id):
attempts.append(job_id)
if len(attempts) == 1:
with patch.object(encoding_service, "get_job_status",
side_effect=self._conn_refused), \
patch("asyncio.sleep", new_callable=AsyncMock):
return await encoding_service.wait_for_completion(
job_id, worker_url="http://10.0.0.1:8080"
)
return {"status": "complete"}
result = await run_with_lost_job_resubmit(operation, "job123")
assert result == {"status": "complete"}
assert attempts[0] == "job123"
assert attempts[1].startswith("job123_retry_")
class TestPreviewQueueTimeout:
"""A queued preview must not wait the long default queue_timeout — an
interactive user is waiting, so total wait is capped at the short timeout."""
@@ -1178,15 +1366,15 @@ class TestBuildWorkerCandidates:
cands = svc._build_worker_candidates()
assert cands[0].vm_name == "encoding-worker-a"
assert cands[0].is_primary is True
assert cands[0].machine_type == "c4d-highcpu-32"
assert cands[0].machine_type == "c4d-highcpu-16"
def test_fallbacks_ranked_fastest_first(self, encoding_service):
import json
fallbacks = json.dumps([
{"vm": "encoding-worker-fallback-n2f", "zone": "us-central1-f", "ip": "10.0.0.5",
"machine_type": "n2-highcpu-32"},
"machine_type": "n2-highcpu-16"},
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.6",
"machine_type": "c4-highcpu-32"},
"machine_type": "c4-highcpu-16"},
])
svc = self._service_with_fallbacks(encoding_service, fallbacks)
order = [c.vm_name for c in svc._build_worker_candidates()]
@@ -1199,10 +1387,10 @@ class TestBuildWorkerCandidates:
from datetime import datetime, timezone
fallbacks = json.dumps([
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.6",
"machine_type": "c4-highcpu-32"},
"machine_type": "c4-highcpu-16"},
])
# c4d@us-central1-c stocked out "now" → demoted below c4.
cap = {"c4d-highcpu-32@us-central1-c": datetime.now(timezone.utc).isoformat()}
cap = {"c4d-highcpu-16@us-central1-c": datetime.now(timezone.utc).isoformat()}
svc = self._service_with_fallbacks(encoding_service, fallbacks, capacity_state=cap)
cands = svc._build_worker_candidates()
order = [c.vm_name for c in cands]
@@ -0,0 +1,105 @@
"""Guard for the CI encoding-worker deploy gate.
CI only blue-green redeploys the GCE encoding worker when a path listed in
infrastructure/encoding-worker/worker_code_paths.txt changed since the serving
worker's version. If the worker starts importing a backend module that is NOT
listed, changes to it would ship to the worker only on its next cold boot and
without the pre-promote test encode. This test derives the worker's import
closure (every ``backend.*`` module reachable from the worker entrypoint and the
karaoke_gen package) and asserts each one is covered by the path list.
"""
import ast
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATHS_FILE = REPO / "infrastructure" / "encoding-worker" / "worker_code_paths.txt"
def _pathspecs():
specs = []
for line in PATHS_FILE.read_text().splitlines():
line = line.strip()
if line and not line.startswith("#"):
specs.append(line)
return specs
def _covered(rel_path: str, specs) -> bool:
return any(rel_path == s or (s.endswith("/") and rel_path.startswith(s)) for s in specs)
def _backend_imports(py_file: Path):
"""All ``backend.*`` module names imported anywhere in the file (incl. lazily)."""
tree = ast.parse(py_file.read_text(), filename=str(py_file))
mods = set()
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
if node.module == "backend" or node.module.startswith("backend."):
mods.add(node.module)
for alias in node.names: # `from backend.services import x` → module x
mods.add(f"{node.module}.{alias.name}")
elif isinstance(node, ast.Import):
for alias in node.names:
if alias.name.startswith("backend."):
mods.add(alias.name)
return mods
def _module_file(mod: str):
base = REPO / Path(*mod.split("."))
for candidate in (base.with_suffix(".py"), base / "__init__.py"):
if candidate.is_file():
return candidate
return None # a name imported from a module, not a module itself
def _worker_closure():
roots = list((REPO / "karaoke_gen").rglob("*.py"))
roots += list((REPO / "backend" / "services" / "gce_encoding").rglob("*.py"))
seen_files = set()
queue = list(roots)
backend_files = set()
while queue:
f = queue.pop()
if f in seen_files:
continue
seen_files.add(f)
for mod in _backend_imports(f):
mf = _module_file(mod)
if not mf:
continue
# Importing backend.a.b also executes backend/__init__.py and
# backend/a/__init__.py — they're part of the worker's code too.
parts = mod.split(".")
pkg_inits = [_module_file(".".join(parts[:i])) for i in range(1, len(parts))]
for dep in [mf, *pkg_inits]:
if dep and dep not in seen_files:
backend_files.add(dep)
queue.append(dep)
return backend_files
def test_worker_code_paths_file_is_well_formed():
specs = _pathspecs()
assert "karaoke_gen/" in specs
assert "backend/services/gce_encoding/" in specs
# pyproject.toml changes on EVERY PR (version bump) — listing it would make
# the gate fire on every push, defeating it. Dependency changes are caught
# via poetry.lock.
assert "pyproject.toml" not in specs
assert "poetry.lock" in specs
for s in specs:
assert (REPO / s.rstrip("/")).exists(), f"stale path in {PATHS_FILE.name}: {s}"
def test_every_backend_module_the_worker_imports_is_gated():
specs = _pathspecs()
missing = sorted(
str(f.relative_to(REPO)) for f in _worker_closure()
if not _covered(str(f.relative_to(REPO)), specs)
)
assert not missing, (
"The encoding worker imports backend modules not listed in "
f"{PATHS_FILE.relative_to(REPO)} — add them so CI redeploys the worker "
f"when they change: {missing}"
)
+60 -10
View File
@@ -494,6 +494,56 @@ class TestEnsureAnyRunning:
# Only the first candidate's start was attempted.
mock_compute.start.assert_called_once()
def test_skips_deleted_candidate_and_starts_next(self, manager, mock_db, mock_compute):
"""A candidate VM that no longer exists (removed from the fleet while an
instance still holds a stale fallback list) is skipped, not fatal."""
from google.api_core import exceptions as gcp_exceptions
stopped = MagicMock()
stopped.status = "TERMINATED"
def _get(project, zone, instance):
if instance == "encoding-worker-fallback-gone":
raise gcp_exceptions.NotFound("instance not found")
return stopped
mock_compute.get.side_effect = _get
# Primary: Spot capacity exhausted. Deleted fallback: NotFound. Live fallback: ok.
mock_compute.start.side_effect = [_capacity_op(), _ok_op()]
candidates = [
EncodingWorkerCandidate(vm_name="encoding-worker-blue", zone="us-central1-c",
ip="10.0.0.1", is_primary=True),
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-gone", zone="us-central1-a",
ip="10.0.0.2"),
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-c2df", zone="us-central1-f",
ip="10.0.0.3"),
]
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 9, 26, 9, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
result = manager.ensure_any_running(candidates)
assert result["vm_name"] == "encoding-worker-fallback-c2df"
assert result["fell_back"] is True
# The deleted VM was never asked to start.
started = [c.kwargs["instance"] for c in mock_compute.start.call_args_list]
assert started == ["encoding-worker-blue", "encoding-worker-fallback-c2df"]
def test_all_candidates_missing_raises_start_error(self, manager, mock_compute):
"""If every candidate is gone, surface a typed start error (not a bare NotFound)."""
from google.api_core import exceptions as gcp_exceptions
mock_compute.get.side_effect = gcp_exceptions.NotFound("gone")
candidates = [
EncodingWorkerCandidate(vm_name="vm-x", zone="us-central1-a", ip="10.0.0.9"),
]
with pytest.raises(EncodingWorkerStartError) as exc_info:
manager.ensure_any_running(candidates)
assert exc_info.value.code == "NOT_FOUND"
mock_compute.start.assert_not_called()
def test_falls_through_to_next_zone_on_capacity_error(self, manager, mock_db, mock_compute):
"""Capacity error on candidate 1 triggers a try of candidate 2."""
mock_instance = MagicMock()
@@ -953,9 +1003,9 @@ class TestCapacityStateFeedback:
candidates = [
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
ip="10.0.0.1", machine_type="c4d-highcpu-16", is_primary=True),
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-n2f", zone="us-central1-f",
ip="10.0.0.2", machine_type="n2-highcpu-32"),
ip="10.0.0.2", machine_type="n2-highcpu-16"),
]
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
@@ -970,7 +1020,7 @@ class TestCapacityStateFeedback:
recorded = {}
for c in set_calls:
recorded.update(c.args[0]["capacity_state"])
assert recorded.get("c4d-highcpu-32@us-central1-c") == "2026-05-05T09:00:00+00:00"
assert recorded.get("c4d-highcpu-16@us-central1-c") == "2026-05-05T09:00:00+00:00"
def test_clears_stockout_for_type_on_clean_start(self, manager, mock_db, mock_compute):
mock_instance = MagicMock()
@@ -980,7 +1030,7 @@ class TestCapacityStateFeedback:
candidates = [
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
ip="10.0.0.1", machine_type="c4d-highcpu-16", is_primary=True),
]
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
@@ -994,7 +1044,7 @@ class TestCapacityStateFeedback:
payload = c.args[0] if c.args else {}
if "capacity_state" in payload:
cleared.update(payload["capacity_state"])
assert cleared.get("c4d-highcpu-32@us-central1-c") is None
assert cleared.get("c4d-highcpu-16@us-central1-c") is None
def test_stockout_write_failure_does_not_break_start(self, manager, mock_db, mock_compute):
"""A Firestore error while recording a stockout must not abort failover."""
@@ -1008,9 +1058,9 @@ class TestCapacityStateFeedback:
candidates = [
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
ip="10.0.0.1", machine_type="c4d-highcpu-16", is_primary=True),
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-n2f", zone="us-central1-f",
ip="10.0.0.2", machine_type="n2-highcpu-32"),
ip="10.0.0.2", machine_type="n2-highcpu-16"),
]
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
@@ -1035,9 +1085,9 @@ class TestCapacityStateFeedback:
# Fallback is first (primary demoted), primary flagged but ranked second.
candidates = [
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-c2df", zone="us-central1-f",
ip="10.0.0.9", machine_type="c2d-highcpu-32", is_primary=False),
ip="10.0.0.9", machine_type="c2d-highcpu-16", is_primary=False),
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
ip="10.0.0.1", machine_type="c4d-highcpu-16", is_primary=True),
]
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
@@ -1101,7 +1151,7 @@ class TestDemoteActiveWorker:
assert doc_ref.set.called
set_args, set_kwargs = doc_ref.set.call_args
assert "capacity_state" in set_args[0]
assert "c4-highcpu-32@us-central1-c" in set_args[0]["capacity_state"]
assert "c4-highcpu-16@us-central1-c" in set_args[0]["capacity_state"]
assert set_kwargs.get("merge") is True
# Cleared the active_override so the retry starts from the primary.
@@ -31,14 +31,14 @@ def _c(vm, zone, machine_type=None, **extra):
# ---------------------------------------------------------------------------
def test_explicit_machine_type_wins():
assert infer_machine_type(_c("whatever", "z", "c2d-highcpu-32")) == "c2d-highcpu-32"
assert infer_machine_type(_c("whatever", "z", "c2d-highcpu-16")) == "c2d-highcpu-16"
def test_infer_from_vm_name_specific_before_generic():
# "n2d"/"c4d" must not be shadowed by "n2"/"c4".
assert infer_machine_type(_c("encoding-worker-fallback-n2da", "z")) == "n2d-highcpu-32"
assert infer_machine_type(_c("encoding-worker-fallback-n2f", "z")) == "n2-highcpu-32"
assert infer_machine_type(_c("encoding-worker-fallback-c4x", "z")) == "c4-highcpu-32"
assert infer_machine_type(_c("encoding-worker-fallback-n2da", "z")) == "n2d-highcpu-16"
assert infer_machine_type(_c("encoding-worker-fallback-n2f", "z")) == "n2-highcpu-16"
assert infer_machine_type(_c("encoding-worker-fallback-c4x", "z")) == "c4-highcpu-16"
def test_infer_unknown_returns_none():
@@ -47,7 +47,7 @@ def test_infer_unknown_returns_none():
def test_runtime_dict_shape_uses_vm_name_key():
assert infer_machine_type({"vm_name": "x-n2d-y", "zone": "z"}) == "n2d-highcpu-32"
assert infer_machine_type({"vm_name": "x-n2d-y", "zone": "z"}) == "n2d-highcpu-16"
# ---------------------------------------------------------------------------
@@ -56,10 +56,10 @@ def test_runtime_dict_shape_uses_vm_name_key():
def test_orders_fastest_first():
pool = [
_c("n2", "us-central1-c", "n2-highcpu-32"),
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
_c("c2d", "us-central1-f", "c2d-highcpu-32"),
_c("c4", "us-central1-a", "c4-highcpu-32"),
_c("n2", "us-central1-c", "n2-highcpu-16"),
_c("c4d", "us-central1-c", "c4d-highcpu-16"),
_c("c2d", "us-central1-f", "c2d-highcpu-16"),
_c("c4", "us-central1-a", "c4-highcpu-16"),
]
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
assert got == ["c4d", "c4", "c2d", "n2"]
@@ -68,18 +68,18 @@ def test_orders_fastest_first():
def test_unknown_type_sorts_last_but_kept():
pool = [
_c("mystery", "z"), # no machine_type, unknown name
_c("c4d", "z", "c4d-highcpu-32"),
_c("c4d", "z", "c4d-highcpu-16"),
]
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
assert got == ["c4d", "mystery"]
assert SPEED_RANK["c4d-highcpu-32"] < UNKNOWN_RANK
assert SPEED_RANK["c4d"] < UNKNOWN_RANK
def test_stable_within_equal_rank_preserves_zone_spread():
# Two n2 in different zones keep input order (caller's secondary preference).
pool = [
_c("n2f", "us-central1-f", "n2-highcpu-32"),
_c("n2c", "us-central1-c", "n2-highcpu-32"),
_c("n2f", "us-central1-f", "n2-highcpu-16"),
_c("n2c", "us-central1-c", "n2-highcpu-16"),
]
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
assert got == ["n2f", "n2c"]
@@ -91,24 +91,24 @@ def test_stable_within_equal_rank_preserves_zone_spread():
def test_recent_stockout_demotes_type_to_back():
pool = [
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
_c("c4", "us-central1-a", "c4-highcpu-32"),
_c("n2", "us-central1-c", "n2-highcpu-32"),
_c("c4d", "us-central1-c", "c4d-highcpu-16"),
_c("c4", "us-central1-a", "c4-highcpu-16"),
_c("n2", "us-central1-c", "n2-highcpu-16"),
]
# c4d stocked out 1 minute ago → demoted behind the still-healthy types.
capacity_state = {"c4d-highcpu-32@us-central1-c": (NOW - timedelta(minutes=1)).isoformat()}
capacity_state = {"c4d-highcpu-16@us-central1-c": (NOW - timedelta(minutes=1)).isoformat()}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
assert got == ["c4", "n2", "c4d"]
def test_cooldown_expires_and_snaps_back_to_fastest():
pool = [
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
_c("c4", "us-central1-a", "c4-highcpu-32"),
_c("c4d", "us-central1-c", "c4d-highcpu-16"),
_c("c4", "us-central1-a", "c4-highcpu-16"),
]
# Stockout older than COOLDOWN → c4d is hot again and returns to the top.
old = (NOW - timedelta(seconds=COOLDOWN_SECONDS + 60)).isoformat()
capacity_state = {"c4d-highcpu-32@us-central1-c": old}
capacity_state = {"c4d-highcpu-16@us-central1-c": old}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
assert got == ["c4d", "c4"]
@@ -116,15 +116,15 @@ def test_cooldown_expires_and_snaps_back_to_fastest():
def test_two_types_stocked_out_still_serves_from_deep_pool():
# Both newest-gen types (c4d, c4) exhausted; deep pools keep serving in order.
pool = [
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
_c("c4", "us-central1-a", "c4-highcpu-32"),
_c("c2d", "us-central1-f", "c2d-highcpu-32"),
_c("n2d", "us-central1-a", "n2d-highcpu-32"),
_c("c4d", "us-central1-c", "c4d-highcpu-16"),
_c("c4", "us-central1-a", "c4-highcpu-16"),
_c("c2d", "us-central1-f", "c2d-highcpu-16"),
_c("n2d", "us-central1-a", "n2d-highcpu-16"),
]
recent = (NOW - timedelta(minutes=2)).isoformat()
capacity_state = {
"c4d-highcpu-32@us-central1-c": recent,
"c4-highcpu-32@us-central1-a": recent,
"c4d-highcpu-16@us-central1-c": recent,
"c4-highcpu-16@us-central1-a": recent,
}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
# Hot deep pools first (fastest-first among them), then the two cold types.
@@ -133,31 +133,31 @@ def test_two_types_stocked_out_still_serves_from_deep_pool():
def test_type_only_capacity_key_demotes_all_zones():
pool = [
_c("c4d-c", "us-central1-c", "c4d-highcpu-32"),
_c("n2", "us-central1-c", "n2-highcpu-32"),
_c("c4d-c", "us-central1-c", "c4d-highcpu-16"),
_c("n2", "us-central1-c", "n2-highcpu-16"),
]
capacity_state = {"c4d-highcpu-32": (NOW - timedelta(minutes=1)).isoformat()}
capacity_state = {"c4d-highcpu-16": (NOW - timedelta(minutes=1)).isoformat()}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
assert got == ["n2", "c4d-c"]
def test_empty_capacity_state_is_pure_speed_order():
pool = [_c("n2", "z", "n2-highcpu-32"), _c("c4d", "z", "c4d-highcpu-32")]
pool = [_c("n2", "z", "n2-highcpu-16"), _c("c4d", "z", "c4d-highcpu-16")]
assert [c["vm"] for c in ordered_candidates(pool, {}, now=NOW)] == ["c4d", "n2"]
assert [c["vm"] for c in ordered_candidates(pool, None, now=NOW)] == ["c4d", "n2"]
def test_naive_timestamp_tolerated():
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-32"), _c("n2", "z", "n2-highcpu-32")]
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-16"), _c("n2", "z", "n2-highcpu-16")]
naive = (NOW - timedelta(minutes=1)).replace(tzinfo=None).isoformat()
capacity_state = {"c4d-highcpu-32@us-central1-c": naive}
capacity_state = {"c4d-highcpu-16@us-central1-c": naive}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
assert got == ["n2", "c4d"]
def test_malformed_timestamp_ignored():
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-32"), _c("n2", "z", "n2-highcpu-32")]
capacity_state = {"c4d-highcpu-32@us-central1-c": "not-a-date"}
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-16"), _c("n2", "z", "n2-highcpu-16")]
capacity_state = {"c4d-highcpu-16@us-central1-c": "not-a-date"}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
assert got == ["c4d", "n2"] # unparseable → not in cooldown
@@ -167,6 +167,6 @@ def test_empty_pool():
def test_cooldown_key_shape():
assert cooldown_key(_c("x", "us-central1-c", "c4d-highcpu-32")) == "c4d-highcpu-32@us-central1-c"
assert cooldown_key(_c("x", None, "n2-highcpu-32")) == "n2-highcpu-32"
assert cooldown_key(_c("x", "us-central1-c", "c4d-highcpu-16")) == "c4d-highcpu-16@us-central1-c"
assert cooldown_key(_c("x", None, "n2-highcpu-16")) == "n2-highcpu-16"
assert cooldown_key(_c("no-token", "z")) is None
+1 -1
View File
@@ -746,7 +746,7 @@ class TestCatalogResolve:
"typed_title": "max picu", "alternatives": [], "engine": "ai", "reason": ""}
from backend.services.match_judge import free_text
monkeypatch.setattr(free_text, "resolve_free_text", fake_resolve)
monkeypatch.setattr(free_text, "resolve_and_tidy", fake_resolve)
return calls
def _post(self, client, q):
+102 -1
View File
@@ -3,7 +3,12 @@ import asyncio
import pytest
from backend.services.match_judge.free_text import resolve_free_text, verdict_from_response
from backend.services.match_judge.free_text import (
resolve_and_tidy,
resolve_free_text,
verdict_from_response,
)
from backend.services.match_judge.verdict import MatchVerdict
def _run(data=None, exc=None):
@@ -46,3 +51,99 @@ def test_ambiguous_keeps_up_to_four_alternatives():
alts = [{"artist": f"A{i}", "title": f"T{i}"} for i in range(6)] + [{"artist": "x"}]
v = verdict_from_response({"kind": "ambiguous", "confident": False, "alternatives": alts}, "q")
assert v["kind"] == "ambiguous" and len(v["alternatives"]) == 4
# ---- resolve_and_tidy: AI split → the job flow's judge_match catalog pass
def _tidy(query, ai, judge_result=None, judge_exc=None):
seen = []
async def gen(model, system_prompt, user_prompt):
return ai
async def judge(artist, title):
seen.append((artist, title))
if judge_exc:
raise judge_exc
return judge_result
v = asyncio.run(resolve_and_tidy(query, generate=gen, judge=judge, model="m"))
return v, seen
_CATALOG_HIT = MatchVerdict("cosmetic", True, "Rihanna", "Push Up On Me", engine="catalog")
def test_lowercase_query_is_tidied_to_catalog_formatting():
ai = {"kind": "cosmetic", "confident": True, "typed_artist": "rihanna",
"typed_title": "push up on me", "canonical_artist": "Rihanna",
"canonical_title": "Push Up on Me"}
v, seen = _tidy("rihanna push up on me", ai, _CATALOG_HIT)
assert seen == [("Rihanna", "Push Up on Me")] # AI's pick goes to the catalog
assert (v["canonical_artist"], v["canonical_title"]) == ("Rihanna", "Push Up On Me")
assert v["kind"] == "cosmetic" and v["confident"] is True and v["engine"] == "catalog"
assert (v["typed_artist"], v["typed_title"]) == ("rihanna", "push up on me")
def test_title_first_word_order_is_still_cosmetic():
ai = {"kind": "cosmetic", "confident": True, "typed_artist": "rihanna",
"typed_title": "push up on me", "canonical_artist": "Rihanna",
"canonical_title": "Push Up On Me"}
v, _ = _tidy("push up on me rihanna", ai, _CATALOG_HIT)
assert v["kind"] == "cosmetic"
def test_typo_fix_confirmed_by_catalog_is_content():
ai = {"kind": "content", "confident": True, "typed_artist": "the strokes",
"typed_title": "max picu", "canonical_artist": "the Strokes",
"canonical_title": "Machu picchu"}
hit = MatchVerdict("cosmetic", True, "The Strokes", "Machu Picchu", engine="catalog")
v, _ = _tidy("the strokes max picu", ai, hit)
assert v["kind"] == "content" and v["engine"] == "catalog"
assert (v["canonical_artist"], v["canonical_title"]) == ("The Strokes", "Machu Picchu")
def test_unrecognised_by_ai_but_split_is_checked_against_catalog():
ai = {"kind": "none", "confident": False, "typed_artist": "some band",
"typed_title": "deep cut"}
hit = MatchVerdict("none", True, "some band", "deep cut", engine="catalog",
reason="already canonical")
v, seen = _tidy("some band deep cut", ai, hit)
assert seen == [("some band", "deep cut")]
assert v["kind"] == "cosmetic" and v["canonical_title"] == "deep cut"
@pytest.mark.parametrize("judge_result,judge_exc", [
(MatchVerdict("none", False, "Rihanna", "Push Up on Me", engine="catalog",
needs_ai=True), None), # catalog inconclusive
(None, RuntimeError("decide down")),
])
def test_no_catalog_match_keeps_ai_verdict(judge_result, judge_exc):
ai = {"kind": "cosmetic", "confident": True, "typed_artist": "rihanna",
"typed_title": "push up on me", "canonical_artist": "Rihanna",
"canonical_title": "Push Up on Me"}
v, _ = _tidy("rihanna push up on me", ai, judge_result, judge_exc)
assert v["engine"] == "ai" and v["canonical_title"] == "Push Up on Me"
# A failed catalog pass is transient — the route must not cache it.
assert (v["reason"] == "unavailable") is (judge_exc is not None)
def test_ambiguous_and_failures_skip_the_catalog():
alts = [{"artist": "A", "title": "T"}, {"artist": "B", "title": "T"}]
v, seen = _tidy("t", {"kind": "ambiguous", "confident": False, "alternatives": alts})
assert v["kind"] == "ambiguous" and seen == []
v, seen = _tidy("t", None)
assert v["kind"] == "none" and seen == []
def test_prompt_covers_descriptive_queries():
from backend.services.match_judge.free_text import _SYSTEM_PROMPT
assert "DESCRIBE" in _SYSTEM_PROMPT and "titanic" in _SYSTEM_PROMPT
def test_description_resolved_to_a_song_is_content():
ai = {"kind": "content", "confident": True, "typed_artist": "", "typed_title": "that song from titanic",
"canonical_artist": "Céline Dion", "canonical_title": "My Heart Will Go On"}
hit = MatchVerdict("cosmetic", True, "Céline Dion", "My Heart Will Go On", engine="catalog")
v, seen = _tidy("that song from titanic", ai, hit)
assert seen == [("Céline Dion", "My Heart Will Go On")]
assert v["kind"] == "content" and v["canonical_title"] == "My Heart Will Go On"
+387
View File
@@ -0,0 +1,387 @@
"""Quick version (fastgen-style draft video) for kjbox make-it jobs."""
import os
import shutil
import subprocess
from datetime import datetime, UTC
from types import SimpleNamespace
from unittest.mock import MagicMock, Mock, patch
import pytest
from backend.services.quick_version import renderer as r
from backend.services.quick_version import service as qs
# --------------------------------------------------------------------------- #
# Lyrics parsing / tiers
# --------------------------------------------------------------------------- #
class TestLyrics:
def test_parse_synced_sorts_and_expands_multi_stamps(self):
lrc = "[00:12.50]second\n[00:05.00][01:00.00]chorus\nno stamp line\n"
assert r.parse_synced(lrc) == [(5.0, "chorus"), (12.5, "second"), (60.0, "chorus")]
def test_payload_prefers_synced(self):
got = r.lyrics_from_lrclib_payload({"syncedLyrics": "[00:01.00]hi", "plainLyrics": "hi"})
assert got.kind == "synced" and got.timed == [(1.0, "hi")] and got.plain == "hi"
def test_payload_plain_and_empty(self):
assert r.lyrics_from_lrclib_payload({"syncedLyrics": " ", "plainLyrics": "a\nb"}).kind == "plain"
assert r.lyrics_from_lrclib_payload({"syncedLyrics": None, "plainLyrics": ""}) is None
def test_resolve_tiers(self):
synced = r.Lyrics("synced", "a", [(1.0, "a"), (2.0, " ")])
assert r.resolve_timed_lines(synced) == ([("a", 1.0)], "synced")
plain = r.Lyrics("plain", "a\n\nb")
assert r.resolve_timed_lines(plain) == ([("a", None), ("", None), ("b", None)], "constant")
assert r.resolve_timed_lines(None) == ([], "none")
def _resp(status, payload):
return SimpleNamespace(status_code=status, json=lambda: payload)
class TestFetchLrclib:
def _session(self, get_side_effect):
sess = MagicMock()
sess.headers = {}
sess.get.side_effect = get_side_effect
return sess
def test_exact_synced_hit_skips_search(self):
sess = self._session([_resp(200, {"syncedLyrics": "[00:01.00]x"})])
with patch.object(r.requests, "Session", return_value=sess):
got = r.fetch_lrclib_lyrics("A", "T", 180.4)
assert got.kind == "synced"
assert sess.get.call_count == 1
assert sess.get.call_args.kwargs["params"]["duration"] == 180
def test_exact_plain_then_search_synced_wins(self):
sess = self._session([
_resp(200, {"plainLyrics": "plain words"}),
_resp(200, [{"plainLyrics": "p"}, {"syncedLyrics": "[00:02.00]s"}]),
])
with patch.object(r.requests, "Session", return_value=sess):
got = r.fetch_lrclib_lyrics("A", "T", None)
assert got.kind == "synced" and got.timed == [(2.0, "s")]
def test_falls_back_to_exact_plain(self):
sess = self._session([_resp(200, {"plainLyrics": "plain words"}), _resp(200, [])])
with patch.object(r.requests, "Session", return_value=sess):
got = r.fetch_lrclib_lyrics("A", "T", None)
assert got.kind == "plain" and got.plain == "plain words"
def test_network_errors_return_none(self):
err = r.requests.RequestException("down")
sess = self._session([err, err])
with patch.object(r.requests, "Session", return_value=sess):
assert r.fetch_lrclib_lyrics("A", "T", 100) is None
# --------------------------------------------------------------------------- #
# Layout + scroll expression + ffmpeg command
# --------------------------------------------------------------------------- #
class TestLayout:
def test_gaps_inserted_only_for_long_breaks(self):
lines = [("a", 1.0), ("b", 3.0), ("c", 20.0)]
assert r.insert_instrumental_gaps(lines, 5.0) == [("a", 1.0), ("b", 3.0), ("", None), ("c", 20.0)]
assert r.insert_instrumental_gaps(lines, 0) == lines
def test_visual_lines_wrap_keeps_anchor_on_first_row(self):
vis = r.build_visual_lines("abba", "waterloo", [("one two three four", 7.0), ("", None)], wrap=8)
assert vis[2:4] == [("ABBA", None), ("WATERLOO", None)]
body = vis[6:-3]
assert body[0] == ("one two", 7.0)
assert all(a is None for _, a in body[1:])
assert body[-1] == ("", None)
def test_scroll_expr_time_anchored(self):
lines = [("", None), ("a", 10.0), ("b", 20.0)]
expr, timed = r.build_scroll_y_expr(lines, [0, 100, 150], 60.0, 480, 400, 0.5)
assert timed
assert expr.startswith("480.00+")
assert "max(0\\,t-10.000)" in expr # commas escaped for the filtergraph
def test_scroll_expr_constant_crawl_without_anchors(self):
expr, timed = r.build_scroll_y_expr([("a", None)], [50], 100.0, 480, 1000, 0.42)
assert not timed
assert expr == "480.00+(-14.80000)*(t-0.000)"
def test_scroll_expr_degenerate_duration(self):
expr, timed = r.build_scroll_y_expr([("a", None)], [50], 0.0, 480, 1000, 0.42)
assert (expr, timed) == ("480.00", False)
def test_ffmpeg_cmd_mixes_guide_vocals(self):
cmd = r.build_ffmpeg_cmd("i.flac", "v.flac", 0.3, "c.png", "Y", "o.mp4", 854, 480, 24, 180.0)
filt = cmd[cmd.index("-filter_complex") + 1]
assert "amix=inputs=2:normalize=0" in filt and "volume=0.300" in filt
assert cmd[-1] == "o.mp4" and "+faststart" in cmd
def test_ffmpeg_cmd_without_vocals_maps_instrumental(self):
cmd = r.build_ffmpeg_cmd("i.flac", None, 0.3, "c.png", "Y", "o.mp4", 854, 480, 24, 180.0)
assert "2:a" in cmd and "v.flac" not in cmd
def test_ffmpeg_cmd_bounds_every_stream_to_duration(self):
"""ffmpeg 4.4 + amix never ends on -shortest alone (prod 2026-09-28)."""
cmd = r.build_ffmpeg_cmd("i.flac", "v.flac", 0.3, "c.png", "Y", "o.mp4", 854, 480, 24, 195.04)
assert "color=c=black:s=854x480:r=24:d=195.040" in cmd
png = cmd.index("c.png")
assert cmd[png - 3:png - 1] == ["-t", "195.040"]
assert cmd[-4:-2] == ["-t", "195.040"]
def test_font_is_bundled(self):
assert os.path.exists(r._FONT_PATH)
@pytest.mark.skipif(not shutil.which("ffmpeg"), reason="ffmpeg not installed")
def test_render_quick_video_end_to_end(tmp_path):
"""Real PIL + ffmpeg render from a generated tone with supplied synced lyrics."""
audio = tmp_path / "tone.wav"
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "sine=frequency=440:duration=6",
str(audio)], check=True)
lyrics = r.Lyrics("synced", "hello\nworld", [(1.0, "hello"), (3.0, "world")])
out = tmp_path / "quick.mp4"
res = r.render_quick_video(instrumental_path=str(audio), vocals_path=None, artist="A", title="T",
out_path=str(out), workdir=str(tmp_path), lyrics=lyrics)
assert out.exists() and out.stat().st_size > 1000
assert res.lyrics_tier == "synced" and res.line_count == 2
assert 5.5 < res.duration_seconds < 6.5
@pytest.mark.skipif(not shutil.which("ffmpeg"), reason="ffmpeg not installed")
def test_render_without_lyrics_still_produces_video(tmp_path):
audio = tmp_path / "tone.wav"
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "sine=duration=3", str(audio)],
check=True)
out = tmp_path / "q.mp4"
res = r.render_quick_video(instrumental_path=str(audio), vocals_path=None, artist="A", title="T",
out_path=str(out), workdir=str(tmp_path), fetch_lyrics=False)
assert res.lyrics_tier == "none" and out.exists()
# --------------------------------------------------------------------------- #
# Service: gating, separation, render thread
# --------------------------------------------------------------------------- #
def _job(client_id="kjbox", quick=None):
return SimpleNamespace(
job_id="j1", artist="ABBA", title="Waterloo",
request_metadata={"client_id": client_id} if client_id else {},
state_data={"quick_version": quick} if quick else {},
)
class TestGating:
def test_kjbox_jobs_only(self):
assert qs.should_build_quick_version(_job("kjbox"))
assert qs.should_build_quick_version(_job("kjbox-nomadpc"))
assert not qs.should_build_quick_version(_job("web"))
assert not qs.should_build_quick_version(_job(None))
def test_skips_when_already_ready(self):
assert not qs.should_build_quick_version(_job(quick={"status": "ready"}))
assert qs.should_build_quick_version(_job(quick={"status": "failed"}))
def test_env_kill_switch(self, monkeypatch):
monkeypatch.setenv("KJBOX_QUICK_VERSION_ENABLED", "false")
assert not qs.should_build_quick_version(_job())
class TestClassify:
@pytest.mark.parametrize("name,kind", [
("quick_instrumental.flac", "instrumental"),
("quick_vocals.flac", "vocals"),
("song_(Instrumental)_model.flac", "instrumental"),
("song_(No Vocal)_model.flac", "instrumental"),
("vocals song_(Vocals)_model.flac", "vocals"),
("random.flac", None),
])
def test_classify(self, name, kind):
assert qs._classify_output(name) == kind
class _FakeSeparator:
instances = []
def __init__(self, **kwargs):
self.kwargs = kwargs
_FakeSeparator.instances.append(self)
def load_model(self, model_filename):
self.model = model_filename
def separate(self, path, custom_output_names=None):
self.custom = custom_output_names
out = self.kwargs["output_dir"]
for n in ("quick_instrumental.flac", "quick_vocals.flac"):
open(os.path.join(out, n), "w").close()
return ["quick_instrumental.flac", "quick_vocals.flac"]
class TestSeparateQuick:
def test_single_model_fast_params(self, tmp_path):
_FakeSeparator.instances.clear()
inst, voc = qs.separate_quick("in.flac", str(tmp_path), "/models", separator_factory=_FakeSeparator)
sep = _FakeSeparator.instances[0]
assert sep.model == qs.DEFAULT_QUICK_MODEL
assert sep.kwargs["model_file_dir"] == "/models"
assert sep.kwargs["mdxc_params"]["overlap"] == qs.QUICK_MDXC_OVERLAP
assert sep.custom["Instrumental"] == "quick_instrumental"
assert inst.endswith("quick_instrumental.flac") and voc.endswith("quick_vocals.flac")
def test_model_override_env(self, tmp_path, monkeypatch):
monkeypatch.setenv("QUICK_VERSION_MODEL", "other.onnx")
_FakeSeparator.instances.clear()
qs.separate_quick("in.flac", str(tmp_path), None, separator_factory=_FakeSeparator)
assert _FakeSeparator.instances[0].model == "other.onnx"
assert "model_file_dir" not in _FakeSeparator.instances[0].kwargs
def test_falls_back_to_baked_model_when_default_fails(self, tmp_path):
class FirstFails(_FakeSeparator):
def load_model(self, model_filename):
if model_filename == qs.DEFAULT_QUICK_MODEL:
raise RuntimeError("download failed")
self.model = model_filename
_FakeSeparator.instances.clear()
inst, _ = qs.separate_quick("in.flac", str(tmp_path), "/models", separator_factory=FirstFails)
assert _FakeSeparator.instances[-1].model == qs.FALLBACK_QUICK_MODEL
assert inst.endswith("quick_instrumental.flac")
def test_both_models_failing_raises(self, tmp_path):
class AllFail(_FakeSeparator):
def load_model(self, model_filename):
raise RuntimeError("nope")
with pytest.raises(RuntimeError):
qs.separate_quick("in.flac", str(tmp_path), "/models", separator_factory=AllFail)
def test_no_instrumental_raises(self, tmp_path):
class Empty(_FakeSeparator):
def separate(self, path, custom_output_names=None):
return []
with pytest.raises(RuntimeError):
qs.separate_quick("in.flac", str(tmp_path), None, separator_factory=Empty)
def _states(job_manager):
return [c.args[2]["status"] for c in job_manager.update_state_data.call_args_list if c.args[1] == "quick_version"]
class TestStartQuickVersion:
def test_non_kjbox_job_is_skipped(self, tmp_path):
jm = Mock()
assert qs.start_quick_version(_job("web"), "a.flac", str(tmp_path), "/models", jm, Mock()) is None
jm.update_state_data.assert_not_called()
def test_success_uploads_and_marks_ready(self, tmp_path):
jm, storage = Mock(), Mock()
def fake_render(**kw):
open(kw["out_path"], "wb").write(b"x" * 10)
return r.RenderResult(kw["out_path"], "synced", 42, 165.7)
with patch.object(qs, "render_quick_video", side_effect=fake_render):
job = qs.start_quick_version(_job(), "a.flac", str(tmp_path), "/models", jm, storage,
separator_factory=_FakeSeparator)
assert job is not None and job.join(10)
assert job.ok is True
storage.upload_file.assert_called_once()
assert storage.upload_file.call_args.args[1] == "jobs/j1/quick/quick.mp4"
jm.update_file_url.assert_called_once_with("j1", "quick", "video_mp4", "jobs/j1/quick/quick.mp4")
assert _states(jm) == ["separating", "rendering", "ready"]
ready = jm.update_state_data.call_args_list[-1].args[2]
assert ready["lyrics_tier"] == "synced" and ready["line_count"] == 42 and "ready_at" in ready
def test_separation_failure_is_non_fatal(self, tmp_path):
jm = Mock()
class Boom(_FakeSeparator):
def load_model(self, model_filename):
raise RuntimeError("cuda oom")
assert qs.start_quick_version(_job(), "a.flac", str(tmp_path), "/m", jm, Mock(),
separator_factory=Boom) is None
assert _states(jm) == ["separating", "failed"]
assert "cuda oom" in jm.update_state_data.call_args_list[-1].args[2]["error"]
def test_render_failure_marks_failed(self, tmp_path):
jm, storage = Mock(), Mock()
with patch.object(qs, "render_quick_video", side_effect=RuntimeError("ffmpeg died")):
job = qs.start_quick_version(_job(), "a.flac", str(tmp_path), "/m", jm, storage,
separator_factory=_FakeSeparator)
assert job.join(10)
assert job.ok is False
storage.upload_file.assert_not_called()
assert _states(jm)[-1] == "failed"
# --------------------------------------------------------------------------- #
# Audio worker wiring
# --------------------------------------------------------------------------- #
class TestAudioWorkerWiring:
def _job(self):
from backend.models.job import Job, JobStatus
return Job(job_id="j1", status=JobStatus.DOWNLOADING, created_at=datetime.now(UTC),
updated_at=datetime.now(UTC), artist="A", title="T",
request_metadata={"client_id": "kjbox"})
@pytest.mark.asyncio
async def test_quick_render_joined_even_when_ensemble_fails(self, monkeypatch, tmp_path):
monkeypatch.delenv("AUDIO_SEPARATOR_API_URL", raising=False)
monkeypatch.setenv("MODEL_DIR", "/models")
jm = MagicMock()
jm.get_job.return_value = self._job()
render = Mock()
render.join.return_value = True
audio = tmp_path / "a.flac"
audio.write_bytes(b"x")
with patch("backend.workers.audio_worker.JobManager", return_value=jm), \
patch("backend.workers.audio_worker.StorageService"), \
patch("backend.workers.audio_worker.download_audio", return_value=str(audio)), \
patch("backend.workers.audio_worker._store_audio_source_metadata"), \
patch("backend.workers.audio_worker.start_quick_version", return_value=render) as start, \
patch("backend.workers.audio_worker.create_audio_processor", side_effect=RuntimeError("ensemble")):
from backend.workers.audio_worker import process_audio_separation
assert await process_audio_separation("j1") is False
start.assert_called_once()
assert start.call_args.args[3] == "/models"
render.join.assert_called_once()
jm.mark_job_failed.assert_called_once()
@pytest.mark.asyncio
async def test_render_timeout_marks_failed(self, monkeypatch, tmp_path):
monkeypatch.delenv("AUDIO_SEPARATOR_API_URL", raising=False)
monkeypatch.setenv("MODEL_DIR", "/models")
jm = MagicMock()
jm.get_job.return_value = self._job()
render = Mock()
render.join.return_value = False
audio = tmp_path / "a.flac"
audio.write_bytes(b"x")
with patch("backend.workers.audio_worker.JobManager", return_value=jm), \
patch("backend.workers.audio_worker.StorageService"), \
patch("backend.workers.audio_worker.download_audio", return_value=str(audio)), \
patch("backend.workers.audio_worker._store_audio_source_metadata"), \
patch("backend.workers.audio_worker.start_quick_version", return_value=render), \
patch("backend.workers.audio_worker.create_audio_processor", side_effect=RuntimeError("x")):
from backend.workers.audio_worker import process_audio_separation
await process_audio_separation("j1")
quick_calls = [c.args[2] for c in jm.update_state_data.call_args_list if c.args[1] == "quick_version"]
assert quick_calls and quick_calls[-1]["status"] == "failed"
@pytest.mark.asyncio
async def test_remote_api_mode_skips_quick_version(self, monkeypatch, tmp_path):
monkeypatch.setenv("AUDIO_SEPARATOR_API_URL", "https://sep")
monkeypatch.delenv("MODEL_DIR", raising=False)
jm = MagicMock()
jm.get_job.return_value = self._job()
audio = tmp_path / "a.flac"
audio.write_bytes(b"x")
with patch("backend.workers.audio_worker.JobManager", return_value=jm), \
patch("backend.workers.audio_worker.StorageService"), \
patch("backend.workers.audio_worker.download_audio", return_value=str(audio)), \
patch("backend.workers.audio_worker._store_audio_source_metadata"), \
patch("backend.workers.audio_worker.start_quick_version") as start, \
patch("backend.workers.audio_worker.create_audio_processor", side_effect=RuntimeError("x")):
from backend.workers.audio_worker import process_audio_separation
await process_audio_separation("j1")
start.assert_not_called()
@@ -166,6 +166,52 @@ class TestProcessStaleReviews:
assert call_args[0][1]['state_data.expiry_reminder_sent'] is True
assert 'state_data.expiry_reminder_sent_at' in call_args[0][1]
@pytest.mark.parametrize("email", [
"e2e-test-runner@nomadkaraoke.com",
"abc.xyz@inbox.testmail.app",
])
async def test_test_account_reminder_is_silent(self, email, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""A stranded E2E job hits the 24h window: no email, but still marked so it isn't retried."""
job = _make_job(hours_ago=30, user_email=email)
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["reminders_sent"] == 1
mock_email_service.send_review_reminder.assert_not_called()
assert mock_firestore.update_job.call_args[0][1]['state_data.expiry_reminder_sent'] is True
async def test_test_account_review_expiry_cancels_without_email(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""A stranded E2E job past 48h is still expired (not left forever), just silently."""
job = _make_job(hours_ago=50, user_email="e2e-test-runner@nomadkaraoke.com")
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1
mock_job_manager.cancel_job.assert_called_once()
mock_email_service.send_review_expired.assert_not_called()
async def test_test_account_duration_confirm_expiry_cancels_without_email(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
job = _make_job(
hours_ago=50,
status=JobStatus.AWAITING_DURATION_CONFIRM,
user_email="e2e-test-runner@nomadkaraoke.com",
)
mock_firestore.list_jobs.side_effect = [[], [], [job]]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1
mock_job_manager.cancel_job.assert_called_once()
mock_email_service.send_duration_confirm_expired.assert_not_called()
async def test_kjbox_job_reminder_uses_one_click_login_link(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""kjbox singers never signed in on gen → the 24h reminder links via a sign-in token."""
job = _make_job(hours_ago=30)
+51 -1
View File
@@ -9,6 +9,7 @@ These tests mock the GCS client to verify:
"""
import json
import pytest
from google.cloud.exceptions import NotFound
from unittest.mock import Mock, MagicMock, patch
from io import BytesIO
@@ -161,6 +162,8 @@ class TestStorageServiceUpload:
uploaded_content = call_args[0][0]
assert json.loads(uploaded_content) == data
assert result == "data/config.json"
# Mutable JSON must never be edge-cached (bucket is publicly readable)
assert mock_blob.cache_control == "no-store"
class TestStorageServiceDownload:
@@ -244,7 +247,7 @@ class TestStorageServiceDownload:
mock_blob = Mock()
mock_blob.download_as_text.return_value = '{"key": "value", "count": 42}'
mock_bucket = Mock()
mock_bucket.blob.return_value = mock_blob
mock_bucket.get_blob.return_value = mock_blob
mock_client = Mock()
mock_client.bucket.return_value = mock_bucket
mock_client_class.return_value = mock_client
@@ -253,6 +256,53 @@ class TestStorageServiceDownload:
result = service.download_json("data/config.json")
assert result == {"key": "value", "count": 42}
# Resolves the live generation (metadata GET) and downloads that blob,
# so a stale edge-cached copy of an overwritten object can't be served.
mock_bucket.get_blob.assert_called_once_with("data/config.json")
mock_bucket.blob.assert_not_called()
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_download_json_missing_raises_not_found(self, mock_settings, mock_client_class):
"""A missing object raises NotFound (get_blob returns None)."""
mock_settings.google_cloud_project = "test-project"
mock_settings.gcs_bucket_name = "test-bucket"
mock_bucket = Mock()
mock_bucket.get_blob.return_value = None
mock_client = Mock()
mock_client.bucket.return_value = mock_bucket
mock_client_class.return_value = mock_client
service = StorageService()
with pytest.raises(NotFound):
service.download_json("data/missing.json")
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_upload_fileobj_sets_cache_control_when_given(self, mock_settings, mock_client_class):
"""upload_fileobj applies an explicit Cache-Control (used for theme assets)."""
mock_settings.google_cloud_project = "test-project"
mock_settings.gcs_bucket_name = "test-bucket"
mock_blob = Mock()
mock_blob.cache_control = None
mock_bucket = Mock()
mock_bucket.blob.return_value = mock_blob
mock_client = Mock()
mock_client.bucket.return_value = mock_bucket
mock_client_class.return_value = mock_client
service = StorageService()
service.upload_fileobj(BytesIO(b"img"), "themes/t/assets/bg.png", content_type="image/png",
cache_control="no-store")
assert mock_blob.cache_control == "no-store"
other_blob = Mock()
other_blob.cache_control = None
mock_bucket.blob.return_value = other_blob
service.upload_fileobj(BytesIO(b"x"), "jobs/j/file.bin")
assert other_blob.cache_control is None
class TestStorageServiceDelete:
+3 -3
View File
@@ -167,7 +167,7 @@ class TestSystemStatusAdmin:
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"
assert admin["active_machine_type"] == "c4d-highcpu-16"
@pytest.mark.asyncio
async def test_admin_sees_capacity_fallback_worker(
@@ -203,5 +203,5 @@ class TestSystemStatusAdmin:
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"
# "n2c" family token → n2-highcpu-16 (inferred from the VM name).
assert admin["active_machine_type"] == "n2-highcpu-16"
+92
View File
@@ -16,6 +16,7 @@ from backend.services.auth_service import AuthResult, UserType
from backend.services.tenant_admin_service import (
TenantConflictError,
TenantNotFoundError,
TenantProvisioningError,
TenantValidationError,
)
from backend.models.tenant import TenantConfig, TenantDefaults, TenantFeatures
@@ -36,6 +37,15 @@ def get_mock_admin():
)
DOMAIN = {"hostname": "randy-vild.nomadkaraoke.com", "state": "active", "dns_ok": True, "pages_status": "active"}
@pytest.fixture(autouse=True)
def stub_domain_status(monkeypatch):
"""Never reach Cloudflare from route tests."""
monkeypatch.setattr(tenant_admin, "get_tenant_domain_status", lambda tid: DOMAIN)
@pytest.fixture
def client():
app.dependency_overrides[require_admin] = get_mock_admin
@@ -239,3 +249,85 @@ def test_list_tenants(client, monkeypatch):
resp = client.get("/api/admin/tenants")
assert resp.status_code == 200
assert resp.json()["tenants"][0]["id"] == "a"
def test_get_tenant_detail_includes_domain_status(client, monkeypatch):
monkeypatch.setattr(
tenant_admin,
"get_tenant_detail",
lambda tid: {"tenant": {"id": tid}, "theme_id": tid, "style_params": {}, "assets": []},
)
body = client.get("/api/admin/tenants/randy-vild").json()
assert body["domain"] == DOMAIN
def test_create_tenant_provisioning_failure_maps_to_502(client, monkeypatch):
def fail(**kwargs):
raise TenantProvisioningError("Could not set up randy-vild.nomadkaraoke.com: cloudflare 500")
monkeypatch.setattr(tenant_admin, "create_tenant", fail)
resp = client.post("/api/admin/tenants", data={"name": "Randy Vild"})
assert resp.status_code == 502
assert "cloudflare" in resp.json()["detail"]
def test_create_tenant_passes_allowed_emails(client, monkeypatch):
captured = {}
def fake_create(**kwargs):
captured.update(kwargs)
return _sample_config()
monkeypatch.setattr(tenant_admin, "create_tenant", fake_create)
resp = client.post(
"/api/admin/tenants", data={"name": "Randy Vild", "allowed_emails": "randy@gmail.com, me@x.com"}
)
assert resp.status_code == 201
assert captured["allowed_emails"] == ["randy@gmail.com", "me@x.com"]
assert resp.json()["domain"] == DOMAIN
def test_delete_tenant(client, monkeypatch):
deleted = []
monkeypatch.setattr(tenant_admin, "delete_tenant", lambda tid: deleted.append(tid))
resp = client.delete("/api/admin/tenants/randy-vild")
assert resp.status_code == 204
assert deleted == ["randy-vild"]
def test_delete_tenant_404(client, monkeypatch):
def raise_nf(tid):
raise TenantNotFoundError("nope")
monkeypatch.setattr(tenant_admin, "delete_tenant", raise_nf)
assert client.delete("/api/admin/tenants/ghost").status_code == 404
def test_delete_tenant_cloudflare_failure_502(client, monkeypatch):
def fail(tid):
raise TenantProvisioningError("Could not remove host")
monkeypatch.setattr(tenant_admin, "delete_tenant", fail)
assert client.delete("/api/admin/tenants/randy-vild").status_code == 502
def test_provision_domain_endpoint(client, monkeypatch):
monkeypatch.setattr(tenant_admin, "provision_tenant_domain", lambda tid: DOMAIN)
resp = client.post("/api/admin/tenants/randy-vild/domain")
assert resp.status_code == 200
assert resp.json()["domain"] == DOMAIN
def test_provision_domain_conflict_409(client, monkeypatch):
def conflict(tid):
raise TenantConflictError("has foreign DNS records")
monkeypatch.setattr(tenant_admin, "provision_tenant_domain", conflict)
assert client.post("/api/admin/tenants/decide/domain").status_code == 409
def test_admin_endpoints_require_admin():
app.dependency_overrides.clear()
c = TestClient(app)
assert c.delete("/api/admin/tenants/randy-vild").status_code in (401, 403)
assert c.post("/api/admin/tenants/randy-vild/domain").status_code in (401, 403)
+266 -2
View File
@@ -16,6 +16,11 @@ from google.api_core.exceptions import PreconditionFailed
from backend.models.theme import ColorOverrides, hex_to_rgba
from backend.services import tenant_admin_service as tas
from backend.services.theme_service import ThemeService
from backend.services.tenant_domain_service import (
DomainStatus,
TenantDomainConflictError,
TenantDomainError,
)
from backend.services.tenant_service import TenantService
@@ -24,6 +29,7 @@ class FakeStorage:
def __init__(self):
self.blobs: dict[str, bytes] = {}
self.cache_control: dict[str, str | None] = {}
def upload_json(self, path, data, if_generation_match=None):
if if_generation_match == 0 and path in self.blobs:
@@ -46,10 +52,17 @@ class FakeStorage:
self.blobs[dst] = self.blobs.get(src, b"")
return dst
def upload_fileobj(self, fileobj, path, content_type=None):
def upload_fileobj(self, fileobj, path, content_type=None, cache_control=None):
self.blobs[path] = fileobj.read()
self.cache_control[path] = cache_control
return path
def delete_folder(self, prefix):
doomed = [p for p in self.blobs if p.startswith(prefix)]
for p in doomed:
del self.blobs[p]
return len(doomed)
def delete_file(self, path, ignore_missing=False):
existed = path in self.blobs
self.blobs.pop(path, None)
@@ -82,8 +95,46 @@ def fake_storage():
return s
class FakeDomains:
"""Stand-in for TenantDomainService recording Cloudflare calls."""
def __init__(self):
self.provisioned = []
self.deprovisioned = []
self.checked = []
self.fail_check = None
self.fail_provision = None
self.fail_deprovision = None
def check_available(self, hostname):
self.checked.append(hostname)
if self.fail_check:
raise self.fail_check
def provision(self, hostname):
if self.fail_provision:
raise self.fail_provision
self.provisioned.append(hostname)
return DomainStatus(hostname=hostname, dns_ok=True, pages_status="initializing")
def deprovision(self, hostname):
if self.fail_deprovision:
raise self.fail_deprovision
self.deprovisioned.append(hostname)
def status(self, hostname):
return DomainStatus(hostname=hostname, dns_ok=hostname in self.provisioned, pages_status="active")
@pytest.fixture
def fake_domains(monkeypatch):
d = FakeDomains()
monkeypatch.setattr(tas, "get_tenant_domain_service", lambda: d)
return d
@pytest.fixture(autouse=True)
def patch_singletons(fake_storage, monkeypatch):
def patch_singletons(fake_storage, fake_domains, monkeypatch):
"""Point the service's tenant/theme singletons at the fake storage."""
monkeypatch.setattr(tas, "get_tenant_service", lambda: TenantService(storage=fake_storage))
monkeypatch.setattr(tas, "get_theme_service", lambda: ThemeService(storage=fake_storage))
@@ -130,6 +181,8 @@ def test_create_tenant_happy_path(fake_storage):
assert "themes/randy-vild/assets/intro_bg.png" in fake_storage.blobs
# Admin-provided background uploaded + referenced by BARE basename
assert fake_storage.blobs["themes/randy-vild/assets/karaoke_background.png"] == b"newbg"
# Uploaded theme assets may later be overwritten in place — never edge-cache them
assert fake_storage.cache_control["themes/randy-vild/assets/karaoke_background.png"] == "no-store"
style = json.loads(fake_storage.blobs["themes/randy-vild/style_params.json"].decode())
assert style["karaoke"]["background_image"] == "karaoke_background.png"
@@ -291,6 +344,8 @@ def test_update_tenant_full_theme_and_config(fake_storage):
assert style["intro"]["title_color"] == "#123456"
# asset replaced
assert fake_storage.blobs["themes/randy-vild/assets/kbg.jpg"] == b"replacement"
# Overwritten in place, so it must be written no-store to be visible immediately
assert fake_storage.cache_control["themes/randy-vild/assets/kbg.jpg"] == "no-store"
def test_update_tenant_rejects_bad_style_params(fake_storage):
@@ -316,3 +371,212 @@ def test_list_tenants(fake_storage):
names = [t["name"] for t in listed]
assert names == ["Alpha", "Bravo"] # sorted by name
assert all("id" in t and "subdomain" in t for t in listed)
# --- Subdomain provisioning (Cloudflare) + delete + access lists -------------
def test_create_provisions_subdomain(fake_storage, fake_domains):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
assert fake_domains.checked == ["randy-vild.nomadkaraoke.com"]
assert fake_domains.provisioned == ["randy-vild.nomadkaraoke.com"]
def test_create_rejects_subdomain_not_matching_id(fake_storage, fake_domains):
with pytest.raises(tas.TenantValidationError, match="randy-vild.nomadkaraoke.com"):
tas.create_tenant(name="Randy Vild", subdomain="other.nomadkaraoke.com", storage=fake_storage)
assert "tenants/randy-vild/config.json" not in fake_storage.blobs
def test_create_dns_conflict_fails_before_any_write(fake_storage, fake_domains):
fake_domains.fail_check = TenantDomainConflictError("decide.nomadkaraoke.com already has DNS records")
before = dict(fake_storage.blobs)
with pytest.raises(tas.TenantConflictError):
tas.create_tenant(name="Decide", storage=fake_storage)
assert fake_storage.blobs == before
assert fake_domains.provisioned == []
def test_create_cloudflare_unusable_fails_before_any_write(fake_storage, fake_domains):
fake_domains.fail_check = TenantDomainError("token not configured")
before = dict(fake_storage.blobs)
with pytest.raises(tas.TenantProvisioningError):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
assert fake_storage.blobs == before
def test_create_rolls_back_everything_when_provisioning_fails(fake_storage, fake_domains):
fake_domains.fail_provision = TenantDomainError("cloudflare 500")
before = dict(fake_storage.blobs)
with pytest.raises(tas.TenantProvisioningError):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
# No config, no theme files, registry back to the original themes
assert not any(p.startswith("tenants/randy-vild/") for p in fake_storage.blobs)
assert not any(p.startswith("themes/randy-vild/") for p in fake_storage.blobs)
registry = json.loads(fake_storage.blobs["themes/_metadata.json"].decode())
assert [t["id"] for t in registry["themes"]] == ["nomad"]
assert set(fake_storage.blobs) == set(before)
# A half-provisioned Pages domain is cleaned up too
assert fake_domains.deprovisioned == ["randy-vild.nomadkaraoke.com"]
def test_delete_tenant_removes_domain_theme_and_config(fake_storage, fake_domains):
tas.create_tenant(name="Randy Vild", logo=(b"logo", "png"), storage=fake_storage)
tas.delete_tenant("randy-vild", storage=fake_storage)
assert fake_domains.deprovisioned == ["randy-vild.nomadkaraoke.com"]
assert not any(p.startswith("tenants/randy-vild/") for p in fake_storage.blobs)
assert not any(p.startswith("themes/randy-vild/") for p in fake_storage.blobs)
registry = json.loads(fake_storage.blobs["themes/_metadata.json"].decode())
assert [t["id"] for t in registry["themes"]] == ["nomad"]
# Default theme untouched
assert "themes/nomad/style_params.json" in fake_storage.blobs
# Id is reusable afterwards
tas.create_tenant(name="Randy Vild", storage=fake_storage)
def test_delete_tenant_missing_raises(fake_storage):
with pytest.raises(tas.TenantNotFoundError):
tas.delete_tenant("nope", storage=fake_storage)
def test_delete_aborts_without_touching_gcs_if_domain_removal_fails(fake_storage, fake_domains):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
fake_domains.fail_deprovision = TenantDomainError("cloudflare down")
with pytest.raises(tas.TenantProvisioningError):
tas.delete_tenant("randy-vild", storage=fake_storage)
assert "tenants/randy-vild/config.json" in fake_storage.blobs
assert "themes/randy-vild/style_params.json" in fake_storage.blobs
def test_delete_keeps_theme_shared_with_another_tenant(fake_storage):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
tas.create_tenant(name="Randy Two", tenant_id="randy-two", storage=fake_storage)
tas.update_tenant(
"randy-two", config_updates={"defaults": {"locked_theme": "randy-vild"}}, storage=fake_storage
)
tas.delete_tenant("randy-vild", storage=fake_storage)
assert "tenants/randy-vild/config.json" not in fake_storage.blobs
assert "themes/randy-vild/style_params.json" in fake_storage.blobs
def test_provision_tenant_domain_backfill(fake_storage, fake_domains):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
fake_domains.provisioned.clear()
status = tas.provision_tenant_domain("randy-vild")
assert status["hostname"] == "randy-vild.nomadkaraoke.com"
assert fake_domains.provisioned == ["randy-vild.nomadkaraoke.com"]
def test_provision_tenant_domain_missing_tenant(fake_storage):
with pytest.raises(tas.TenantNotFoundError):
tas.provision_tenant_domain("nope")
def test_get_tenant_domain_status_swallows_cloudflare_errors(fake_domains, monkeypatch):
def boom(hostname):
raise TenantDomainError("down")
monkeypatch.setattr(fake_domains, "status", boom)
assert tas.get_tenant_domain_status("randy-vild") is None
def test_create_with_allowed_emails_restricts_access(fake_storage):
config = tas.create_tenant(
name="Randy Vild", allowed_emails=[" Randy@Gmail.com ", "randy@gmail.com"], storage=fake_storage
)
assert config.auth.allowed_emails == ["randy@gmail.com"]
assert config.auth.require_email_domain is True
assert config.is_email_allowed("RANDY@gmail.com")
assert not config.is_email_allowed("someone@gmail.com")
assert config.is_email_allowed("andrew@nomadkaraoke.com") # admins always
def test_create_rejects_invalid_email(fake_storage):
with pytest.raises(tas.TenantValidationError, match="not-an-email"):
tas.create_tenant(name="Randy Vild", allowed_emails=["not-an-email"], storage=fake_storage)
def test_update_access_lists_normalized_and_enforced(fake_storage):
tas.create_tenant(name="Randy Vild", storage=fake_storage) # open portal
updated = tas.update_tenant(
"randy-vild",
config_updates={"auth": {"allowed_emails": ["Randy@Gmail.com"], "allowed_email_domains": ["@Label.com"]}},
storage=fake_storage,
)
assert updated.auth.allowed_emails == ["randy@gmail.com"]
assert updated.auth.allowed_email_domains == ["label.com"]
assert updated.auth.require_email_domain is True
assert updated.is_email_allowed("exec@label.com")
assert not updated.is_email_allowed("random@gmail.com")
reopened = tas.update_tenant(
"randy-vild", config_updates={"auth": {"allowed_emails": [], "allowed_email_domains": []}},
storage=fake_storage,
)
assert reopened.auth.require_email_domain is False
assert reopened.is_email_allowed("random@gmail.com")
def test_update_rejects_invalid_domain(fake_storage):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
with pytest.raises(tas.TenantValidationError):
tas.update_tenant(
"randy-vild", config_updates={"auth": {"allowed_email_domains": ["not a domain"]}},
storage=fake_storage,
)
def test_update_rejects_subdomain_change(fake_storage):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
with pytest.raises(tas.TenantValidationError, match="can't be changed"):
tas.update_tenant("randy-vild", config_updates={"subdomain": "other.nomadkaraoke.com"}, storage=fake_storage)
# Same value is fine (the UI may echo it back)
tas.update_tenant("randy-vild", config_updates={"subdomain": "randy-vild.nomadkaraoke.com"}, storage=fake_storage)
def test_delete_always_deprovisions_canonical_host(fake_storage, fake_domains):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
cfg_path = "tenants/randy-vild/config.json"
cfg = json.loads(fake_storage.blobs[cfg_path].decode())
cfg["subdomain"] = "legacy.example.com" # legacy/odd config
fake_storage.blobs[cfg_path] = json.dumps(cfg).encode()
tas.delete_tenant("randy-vild", storage=fake_storage)
assert fake_domains.deprovisioned == ["randy-vild.nomadkaraoke.com"]
def test_delete_keeps_theme_not_owned_by_tenant(fake_storage):
"""A tenant pointing at some other theme (not its 1:1 theme) never deletes it."""
tas.create_tenant(name="Randy Vild", storage=fake_storage)
fake_storage.blobs["themes/foo/style_params.json"] = b"{}"
tas.update_tenant(
"randy-vild", config_updates={"defaults": {"locked_theme": "foo", "theme_id": "foo"}}, storage=fake_storage
)
tas.delete_tenant("randy-vild", storage=fake_storage)
assert "themes/foo/style_params.json" in fake_storage.blobs
def test_update_does_not_persist_subdomain_echo(fake_storage):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
updated = tas.update_tenant(
"randy-vild", config_updates={"subdomain": " Randy-Vild.nomadkaraoke.com "}, storage=fake_storage
)
assert updated.subdomain == "randy-vild.nomadkaraoke.com"
def test_delete_removes_own_theme_even_after_switching_themes(fake_storage):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
fake_storage.blobs["themes/foo/style_params.json"] = b"{}"
tas.update_tenant("randy-vild", config_updates={"defaults": {"locked_theme": "foo"}}, storage=fake_storage)
tas.delete_tenant("randy-vild", storage=fake_storage)
assert not any(p.startswith("themes/randy-vild/") for p in fake_storage.blobs)
assert "themes/foo/style_params.json" in fake_storage.blobs
# id reusable
tas.create_tenant(name="Randy Vild", storage=fake_storage)
def test_delete_reports_storage_failure(fake_storage, monkeypatch):
tas.create_tenant(name="Randy Vild", storage=fake_storage)
monkeypatch.setattr(fake_storage, "delete_folder", lambda prefix: 0) # GCS failure swallowed
with pytest.raises(tas.TenantProvisioningError, match="retry"):
tas.delete_tenant("randy-vild", storage=fake_storage)
+171
View File
@@ -0,0 +1,171 @@
"""
Unit tests for TenantDomainService (Cloudflare Pages custom domain + DNS CNAME
for tenant portal subdomains). Cloudflare is faked with an in-memory
httpx.MockTransport so every request/response is exercised without network.
"""
import json
import httpx
import pytest
from backend.services.tenant_domain_service import (
TenantDomainConflictError,
TenantDomainError,
TenantDomainService,
)
ACCOUNT = "acct"
ZONE = "zone"
PROJECT = "karaoke-gen-tenant"
TARGET = f"{PROJECT}.pages.dev"
HOST = "randy-vild.nomadkaraoke.com"
class FakeCloudflare:
"""Minimal stateful model of the Pages domains + DNS records endpoints."""
def __init__(self):
self.pages: dict[str, dict] = {}
self.dns: list[dict] = []
self.calls: list[tuple[str, str]] = []
self.fail_all = False
self._next_id = 1
def handler(self, request: httpx.Request) -> httpx.Response:
path = request.url.path.removeprefix("/client/v4")
self.calls.append((request.method, path))
assert request.headers["Authorization"] == "Bearer tok"
if self.fail_all:
return httpx.Response(500, json={"success": False, "errors": [{"message": "boom"}]})
pages_prefix = f"/accounts/{ACCOUNT}/pages/projects/{PROJECT}/domains"
dns_prefix = f"/zones/{ZONE}/dns_records"
if path == pages_prefix and request.method == "POST":
name = json.loads(request.content)["name"]
self.pages[name] = {"name": name, "status": "initializing"}
return httpx.Response(200, json={"success": True, "result": self.pages[name]})
if path.startswith(pages_prefix + "/"):
name = path.rsplit("/", 1)[-1]
if name not in self.pages:
return httpx.Response(404, json={"success": False, "errors": [{"code": 8000007}]})
if request.method == "DELETE":
del self.pages[name]
return httpx.Response(200, json={"success": True, "result": None})
return httpx.Response(200, json={"success": True, "result": self.pages[name]})
if path == dns_prefix and request.method == "GET":
name = request.url.params.get("name")
return httpx.Response(
200, json={"success": True, "result": [r for r in self.dns if r["name"] == name]}
)
if path == dns_prefix and request.method == "POST":
body = json.loads(request.content)
record = {
"id": f"r{self._next_id}",
"type": body["type"],
"name": f"{body['name']}.nomadkaraoke.com",
"content": body["content"],
"proxied": body["proxied"],
}
self._next_id += 1
self.dns.append(record)
return httpx.Response(200, json={"success": True, "result": record})
if path.startswith(dns_prefix + "/") and request.method == "DELETE":
rid = path.rsplit("/", 1)[-1]
self.dns = [r for r in self.dns if r["id"] != rid]
return httpx.Response(200, json={"success": True, "result": {"id": rid}})
return httpx.Response(404, json={"success": False, "errors": [{"message": f"unhandled {path}"}]})
@pytest.fixture
def cf():
return FakeCloudflare()
@pytest.fixture
def svc(cf):
client = httpx.Client(
base_url="https://api.cloudflare.com/client/v4", transport=httpx.MockTransport(cf.handler)
)
return TenantDomainService(
api_token="tok", client=client, account_id=ACCOUNT, zone_id=ZONE, pages_project=PROJECT
)
def test_provision_creates_pages_domain_and_proxied_cname(svc, cf):
status = svc.provision(HOST)
assert HOST in cf.pages
assert cf.dns == [
{"id": "r1", "type": "CNAME", "name": HOST, "content": TARGET, "proxied": True}
]
assert status.dns_ok is True
assert status.pages_status == "initializing"
assert status.to_dict()["state"] == "provisioning"
def test_provision_is_idempotent(svc, cf):
svc.provision(HOST)
svc.provision(HOST)
assert len(cf.dns) == 1
assert [c for c in cf.calls if c[0] == "POST"] == [
("POST", f"/accounts/{ACCOUNT}/pages/projects/{PROJECT}/domains"),
("POST", f"/zones/{ZONE}/dns_records"),
]
def test_status_active_once_cert_issued(svc, cf):
svc.provision(HOST)
cf.pages[HOST]["status"] = "active"
assert svc.status(HOST).to_dict()["state"] == "active"
def test_status_missing(svc):
assert svc.status(HOST).to_dict() == {
"hostname": HOST, "state": "missing", "dns_ok": False, "pages_status": None,
}
def test_foreign_dns_record_blocks_provisioning(svc, cf):
cf.dns.append({"id": "x", "type": "A", "name": "decide.nomadkaraoke.com", "content": "1.2.3.4"})
with pytest.raises(TenantDomainConflictError, match="decide.nomadkaraoke.com"):
svc.provision("decide.nomadkaraoke.com")
assert cf.pages == {} # nothing created
def test_foreign_cname_blocks_provisioning(svc, cf):
cf.dns.append({"id": "x", "type": "CNAME", "name": HOST, "content": "elsewhere.example.com"})
with pytest.raises(TenantDomainConflictError):
svc.check_available(HOST)
def test_deprovision_removes_only_our_records(svc, cf):
svc.provision(HOST)
cf.dns.append({"id": "keep", "type": "TXT", "name": HOST, "content": "verification"})
svc.deprovision(HOST)
assert HOST not in cf.pages
assert [r["id"] for r in cf.dns] == ["keep"]
def test_deprovision_when_nothing_exists_is_noop(svc, cf):
svc.deprovision(HOST)
assert not [c for c in cf.calls if c[0] == "DELETE"]
def test_api_errors_raise_tenant_domain_error(svc, cf):
cf.fail_all = True
with pytest.raises(TenantDomainError, match="500"):
svc.provision(HOST)
def test_missing_token_raises(monkeypatch):
from backend.services import tenant_domain_service as tds
class NoSecrets:
def get_secret(self, _):
return None
monkeypatch.setattr(tds, "get_settings", lambda: NoSecrets())
with pytest.raises(TenantDomainError, match="not configured"):
TenantDomainService().status(HOST)
+41 -4
View File
@@ -264,8 +264,9 @@ class TestTenantConfig:
assert basic_config.is_email_allowed("anyone@gmail.com") is True
assert basic_config.is_email_allowed("user@anything.com") is True
def test_is_email_allowed_require_domain_false(self):
"""Test non-matching emails allowed when require_email_domain=False."""
def test_is_email_allowed_require_domain_false_still_enforced(self):
"""A non-empty allowlist is always enforced — the legacy
require_email_domain=False loophole no longer lets other emails in."""
config = TenantConfig(
id="flexible",
name="Flexible Tenant",
@@ -278,8 +279,8 @@ class TestTenantConfig:
# Matching domain still works
assert config.is_email_allowed("user@preferred.com") is True
# Non-matching also allowed since require_email_domain=False
assert config.is_email_allowed("user@other.com") is True
# Non-matching is rejected despite require_email_domain=False
assert config.is_email_allowed("user@other.com") is False
def test_is_email_allowed_partial_domain_no_match(self, full_config):
"""Test partial domain matches don't work (must be exact suffix)."""
@@ -288,6 +289,42 @@ class TestTenantConfig:
# Subdomain of allowed domain should work
assert full_config.is_email_allowed("user@sub.vocal-star.com") is False
def test_is_email_allowed_individual_emails(self):
"""Individual addresses (e.g. a client's gmail) can be allowlisted."""
config = TenantConfig(
id="randy-vild",
name="Randy Vild",
subdomain="randy-vild.nomadkaraoke.com",
auth=TenantAuth(allowed_emails=["randy@gmail.com"], require_email_domain=True),
)
assert config.is_email_allowed("randy@gmail.com") is True
assert config.is_email_allowed(" Randy@GMAIL.com ") is True
assert config.is_email_allowed("other@gmail.com") is False
def test_is_email_allowed_emails_enforced_even_if_require_flag_false(self):
"""Listing individual emails always restricts access (legacy flag ignored)."""
config = TenantConfig(
id="t",
name="T",
subdomain="t.nomadkaraoke.com",
auth=TenantAuth(allowed_emails=["a@gmail.com"], require_email_domain=False),
)
assert config.is_email_allowed("b@gmail.com") is False
def test_is_email_allowed_emails_and_domains_combined(self):
config = TenantConfig(
id="t",
name="T",
subdomain="t.nomadkaraoke.com",
auth=TenantAuth(allowed_emails=["a@gmail.com"], allowed_email_domains=["label.com"]),
)
assert config.is_email_allowed("a@gmail.com") is True
assert config.is_email_allowed("exec@label.com") is True
assert config.is_email_allowed("b@gmail.com") is False
def test_admins_can_always_sign_in(self, full_config):
assert full_config.is_email_allowed("andrew@nomadkaraoke.com") is True
class TestTenantPublicConfig:
"""Tests for TenantPublicConfig model."""
+23
View File
@@ -233,6 +233,29 @@ class TestThemeService:
service = ThemeService(storage=mock_storage)
assert service.theme_exists("unknown") is False
def test_theme_exists_refreshes_stale_cache_on_miss(self, mock_storage, sample_metadata):
"""A theme created after this instance cached the registry is still found."""
mock_storage.download_json.return_value = sample_metadata
service = ThemeService(storage=mock_storage)
service.list_themes() # warm the per-instance cache without the new theme
updated = {
**sample_metadata,
"themes": sample_metadata["themes"]
+ [{"id": "new-tenant", "name": "New", "description": "New", "is_default": False}],
}
mock_storage.download_json.return_value = updated
assert service.theme_exists("new-tenant") is True
def test_theme_exists_hit_uses_cache(self, mock_storage, sample_metadata):
"""A cache hit does not re-download the registry."""
mock_storage.download_json.return_value = sample_metadata
service = ThemeService(storage=mock_storage)
service.theme_exists("nomad")
service.theme_exists("nomad")
assert mock_storage.download_json.call_count == 1
def test_get_default_theme_id(self, mock_storage, sample_metadata):
"""Test get_default_theme_id returns the default theme."""
mock_storage.download_json.return_value = sample_metadata
+5 -2
View File
@@ -11,10 +11,13 @@ def vocals_stem_path(job) -> Optional[str]:
- "vocals" : full vocal from a 2-stem split (rare)
- "vocals_clean" : full vocal from the primary vocal/instrumental
split (present on essentially all cloud jobs)
- "lead_vocals" : last-resort fallback (misses backing lines)
- "lead_vocals" : fallback (misses backing lines)
- "vocals_derived": mix minus the user's own instrumental, for jobs that
skipped separation (backend/services/derived_vocals.py).
Waveform-only — never a deliverable stem.
"""
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
for key in ("vocals", "vocals_clean", "lead_vocals"):
for key in ("vocals", "vocals_clean", "lead_vocals", "vocals_derived"):
if stems.get(key):
return stems[key]
return None
+3 -3
View File
@@ -17,9 +17,9 @@ TEST_EMAIL_DOMAINS = [
# These live on the internal nomadkaraoke.com domain (so they'd otherwise pass
# is_internal_email, not is_test_email), but every job they create is E2E test
# data. Listed here so admin dashboards' exclude_test filter hides their jobs.
# e2e-test-runner is the persistent account the CI post-deploy canary and daily
# E2E workflows impersonate; without this entry its piri/dog jobs leak into the
# admin "My Jobs" view.
# e2e-test-runner is the persistent account the daily E2E workflow
# impersonates; without this entry its piri/dog jobs leak into the admin
# "My Jobs" view.
TEST_EMAIL_ADDRESSES = [
"e2e-test-runner@nomadkaraoke.com",
]
+27
View File
@@ -33,6 +33,15 @@ from backend.workers.worker_logging import create_job_logger, setup_job_logging,
from backend.workers.registry import worker_registry
from backend.services.tracing import job_span, add_span_event, add_span_attribute
from backend.services.metrics import metrics
from backend.services.quick_version.service import (
STATUS_FAILED as QUICK_STATUS_FAILED,
set_quick_state,
start_quick_version,
)
# Upper bound on how long the audio worker waits (at exit) for the quick-version
# render thread. The render normally finishes long before the ensemble does.
QUICK_VERSION_JOIN_TIMEOUT_SECONDS = 300
# Import from karaoke_gen package
from karaoke_gen.audio_processor import AudioProcessor
@@ -182,6 +191,8 @@ async def process_audio_separation(job_id: str) -> bool:
job_log.warning(status_error)
# Continue anyway - this is a safety net warning, not a hard failure
quick_render = None
# Create temporary working directory
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_{job_id}_")
job_log.info(f"Created temp directory: {temp_dir}")
@@ -226,6 +237,14 @@ async def process_audio_separation(job_id: str) -> bool:
# Capture input audio properties via ffprobe (before any processing)
_store_audio_source_metadata(job_manager, job_id, audio_path, job_log)
# kjbox make-it jobs: a quick single-model separation on the warm
# GPU, then a background render of a scrolling-lyrics draft video
# while the ensemble below runs. Never raises; joined in `finally`.
if model_dir:
quick_render = start_quick_version(
job, audio_path, temp_dir, model_dir, job_manager, storage, job_log
)
# Update progress using state_data (don't change status during parallel processing)
# The status is managed at a higher level - workers just track their progress
job_manager.update_state_data(job_id, 'audio_progress', {
@@ -412,6 +431,14 @@ async def process_audio_separation(job_id: str) -> bool:
return False
finally:
# Let the quick-version render (reads files in temp_dir) finish before
# cleanup — even when the full separation failed.
if quick_render is not None:
finished = await asyncio.to_thread(quick_render.join, QUICK_VERSION_JOIN_TIMEOUT_SECONDS)
if not finished:
logger.warning(f"[job:{job_id}] Quick version render still running at worker exit; abandoning")
set_quick_state(job_manager, job_id, QUICK_STATUS_FAILED, error="render timed out")
# Unregister from worker registry to signal completion
await worker_registry.unregister(job_id, "audio")
+63
View File
@@ -310,6 +310,16 @@ async def process_lyrics_transcription(job_id: str) -> bool:
job_log.info(f"Audio downloaded: {os.path.basename(audio_path)}")
download_span.set_attribute("audio_file", os.path.basename(audio_path))
# Jobs with the user's own instrumental skip separation, so there's
# no vocals stem for the review waveform. Derive an approximation
# (mix − instrumental) on CPU alongside transcription.
derived_vocals_task = None
if getattr(job, 'existing_instrumental_gcs_path', None):
derived_vocals_task = asyncio.create_task(asyncio.to_thread(
_store_derived_vocals, job_id, job.existing_instrumental_gcs_path,
audio_path, storage, job_manager, job_log,
))
# Set up LyricsTranscriber cache directory and sync from GCS
# This allows reusing cached AudioShake/lyrics API responses across Cloud Run instances
cache_dir = os.path.join(temp_dir, "lyrics-cache")
@@ -539,6 +549,21 @@ async def process_lyrics_transcription(job_id: str) -> bool:
# cancelled on Cloud Run Job event-loop teardown, orphaning jobs at
# `downloading`; awaiting guarantees the screens Cloud Task is
# enqueued before this worker returns.
# Screens pre-computes the vocals peaks, so the derived stem must be
# registered before we advance. Never fails the job.
if derived_vocals_task is not None:
try:
# shield: on timeout stop waiting but let the thread finish
# on its own (threads can't be cancelled; it cleans up after itself)
await asyncio.wait_for(asyncio.shield(derived_vocals_task), DERIVED_VOCALS_TIMEOUT_SECONDS)
except asyncio.TimeoutError:
job_log.warning(
f"Derived vocals still running after {DERIVED_VOCALS_TIMEOUT_SECONDS}s; "
"continuing without waiting (non-fatal)"
)
except Exception as e:
job_log.warning(f"Derived vocals task failed (non-fatal): {e}")
job_log.info("Lyrics worker complete, advancing to screen generation...")
job_manager.mark_lyrics_complete(job_id)
await job_manager.advance_to_screens_if_ready(job_id)
@@ -597,6 +622,44 @@ async def process_lyrics_transcription(job_id: str) -> bool:
logger.debug(f"[job:{job_id}] Cleaned up temp directory: {temp_dir}")
# Waveform-only nicety: never let it hold up the lyrics -> screens handoff for long.
DERIVED_VOCALS_TIMEOUT_SECONDS = 180
def _store_derived_vocals(job_id, instrumental_gcs_path, mix_path, storage, job_manager, job_log) -> None:
"""Derive approximate vocals (mix − user instrumental) for the review waveform
and register them as stems.vocals_derived. Best-effort: logs and returns on failure.
Uses its own temp dir (the worker's temp_dir may be removed on failure paths
while this thread is still running); only reads mix_path.
"""
import shutil
import tempfile
from backend.services.derived_vocals import derive_vocals_file
work_dir = tempfile.mkdtemp(prefix="derived-vocals-")
try:
ext = os.path.splitext(instrumental_gcs_path)[1] or ".audio"
inst_path = os.path.join(work_dir, f"user_instrumental{ext}")
storage.download_file(instrumental_gcs_path, inst_path)
out_path = os.path.join(work_dir, "vocals_derived.flac")
result = derive_vocals_file(mix_path, inst_path, out_path)
summary = (f"offset {result.offset_samples} samples, gain {result.gain:.3f}, "
f"residual {result.residual_ratio:.2f}")
if not result.useful:
job_log.info(f"Instrumental didn't cancel against the mix ({summary}); no vocal waveform")
return
gcs_path = f"jobs/{job_id}/stems/vocals_derived.flac"
storage.upload_file(out_path, gcs_path)
job_manager.update_file_url(job_id, 'stems', 'vocals_derived', gcs_path)
job_log.info(f"Derived vocals for review waveform ({summary})")
except Exception as e:
job_log.warning(f"Could not derive vocals for review waveform (non-fatal): {e}")
finally:
shutil.rmtree(work_dir, ignore_errors=True)
async def download_audio(
job_id: str,
temp_dir: str,
+2 -2
View File
@@ -790,7 +790,7 @@ def _park_job_for_capacity_retry(
The user-facing message tells the user this is temporary and will retry
automatically — no action needed. Auto-retry is driven by the
/api/internal/retry-pending-render-jobs endpoint, fired every 5 min by
/api/internal/retry-pending-render-jobs endpoint, fired every 10 min by
Cloud Scheduler.
"""
now = datetime.now(UTC).isoformat()
@@ -850,7 +850,7 @@ def park_active_render_jobs_for_shutdown() -> int:
Parking transitions the job to RENDER_PENDING_CAPACITY, which the
`/api/internal/retry-pending-render-jobs` Cloud Scheduler job picks up
every 5 minutes.
every 10 minutes.
Only jobs currently in the RENDERING_VIDEO state are parked — if the
worker completed concurrently (or the job was already moved past this
+10 -4
View File
@@ -16,6 +16,7 @@ from backend.models.job import JobStatus
from backend.services.email_service import get_email_service
from backend.services.firestore_service import FirestoreService
from backend.services.job_manager import JobManager
from backend.utils.test_data import is_test_email
logger = logging.getLogger(__name__)
@@ -47,7 +48,8 @@ async def process_stale_reviews() -> Dict[str, Any]:
- 48h expiry: add_credits(credits_charged) + cancel_job + send_duration_confirm_expired
The full credits_charged amount (not flat 1) is refunded.
Excludes made-for-you and tenant jobs.
Excludes made-for-you and tenant jobs. Jobs owned by automated-test accounts
(e.g. a stranded E2E job) are still expired, but never emailed.
Returns:
Summary dict with counts and any errors encountered.
@@ -121,6 +123,10 @@ async def process_stale_reviews() -> Dict[str, Any]:
is_duration_confirm = job.status in _DURATION_CONFIRM_STATUSES
# A stranded E2E job must not email the test account (it forwards to
# a real inbox) — still expire it, just silently.
send_emails = bool(job.user_email) and not is_test_email(job.user_email)
if hours_elapsed >= REVIEW_EXPIRY_HOURS:
if is_duration_confirm:
# Duration-confirm expiry: refund full credits_charged, then cancel.
@@ -179,7 +185,7 @@ async def process_stale_reviews() -> Dict[str, Any]:
f"Job {job.job_id}: failed to set duration_confirm_expiry_processed: {flag_err}"
)
if job.user_email:
if send_emails:
try:
email_service.send_duration_confirm_expired(
to_email=job.user_email,
@@ -209,7 +215,7 @@ async def process_stale_reviews() -> Dict[str, Any]:
jobs_expired += 1
# Send expiry notification email
if job.user_email:
if send_emails:
try:
from backend.services.user_service import get_user_service
user_service = get_user_service()
@@ -249,7 +255,7 @@ async def process_stale_reviews() -> Dict[str, Any]:
)
# Send reminder email (different email per status)
if job.user_email:
if send_emails:
try:
# Look up user locale for email
user_locale = "en"
+6 -1
View File
@@ -1180,7 +1180,12 @@ async def _handle_native_distribution(
remote_folder = f"{dropbox_path}/{folder_name}"
job_log.info(f"Uploading to Dropbox folder: {remote_folder}")
dropbox.upload_folder(temp_dir, remote_folder)
from backend.services.dropbox_service import dropbox_skip_suffixes_for
dropbox.upload_folder(
temp_dir, remote_folder,
exclude_suffixes=dropbox_skip_suffixes_for(dropbox_path),
)
# Create sharing link
try:
+9 -2
View File
@@ -931,8 +931,15 @@ class VideoWorkerOrchestrator:
folder_name = f"{self.result.brand_code or 'TRACK-0000'} - {base_name}"
remote_folder = f"{self.config.dropbox_path}/{folder_name}"
# Upload entire output directory
dropbox.upload_folder(self.config.output_dir, remote_folder)
# Upload the output directory, minus files Nomad's own Dropbox archive
# doesn't need (lossless 4K MP4 by default — it stays in GCS). Tenant
# folders get everything. See dropbox_skip_suffixes_for.
from backend.services.dropbox_service import dropbox_skip_suffixes_for
skip = dropbox_skip_suffixes_for(self.config.dropbox_path)
if skip:
self.job_log.info(f"Excluding from Dropbox upload (kept in GCS): {list(skip)}")
dropbox.upload_folder(self.config.output_dir, remote_folder, exclude_suffixes=skip)
# Create sharing link
try:
+56 -10
View File
@@ -971,6 +971,14 @@ optional) lets the judge tell whether weak audio results hint at a typo. The cal
never blocks job creation — on timeout/error it returns a `none` verdict. Disable
the AI layer with `MATCH_JUDGE_ENABLED=false` (deterministic+catalog still run).
> **In practice the correction comes from Gemini.** The catalog pass is only confident when the
> typed text *equals* a catalog entry after case, punctuation and accent folding. The catalog it
> queries (decide `/api/catalog/tracks`) is BigQuery prefix-only `LIKE 'q%'`, so any typo
> ("the stokes" / "max picu") gets zero candidates. Most job submissions therefore go
> `fast … needs_ai=True` then `full … engine=ai`, which prod logs confirm. kjbox's singer search
> is designing an on-device typo-tolerant matcher that uses Gemini only as a fallback. Read
> `kjbox/docs/SONG-IDENTIFICATION.md` before reusing this judge for free-text search.
`stage` (optional, `"fast"` | `"full"`, default `"full"`) supports a two-call
pattern the frontend uses to keep the tidy off the critical path:
@@ -1284,9 +1292,29 @@ GET /api/admin/tenants/_template
GET /api/admin/tenants/{id}
POST /api/admin/tenants (multipart/form-data)
PUT /api/admin/tenants/{id} (multipart/form-data)
DELETE /api/admin/tenants/{id}
POST /api/admin/tenants/{id}/domain
Authorization: Bearer <admin token>
```
**Lifecycle (v0.246.0):** creating a tenant also provisions its portal at `{id}.nomadkaraoke.com`
(Cloudflare Pages custom domain on `karaoke-gen-tenant` + proxied CNAME, via
`services/tenant_domain_service.py` and the `cloudflare-tenant-domains-token` secret). If the
hostname already has a non-tenant DNS record → `409` before anything is written; if Cloudflare
fails → the GCS side is rolled back and `502` is returned. `subdomain` must equal
`{id}.nomadkaraoke.com`. Create and `GET /{id}` responses include
`domain: {hostname, state: active|provisioning|missing, dns_ok, pages_status}` (certificate issuance
usually takes ~1 min). `POST /{id}/domain` idempotently (re)provisions (backfill/retry).
`DELETE /{id}` → `204`: removes the subdomain (only records pointing at the tenant Pages project),
theme (assets, style_params, registry entry — kept if default or shared) and config/logo; jobs are
kept. `502` if Cloudflare removal fails (nothing in GCS is deleted, so it can be retried).
**Portal access:** `allowed_emails` (individual addresses, e.g. a client's gmail) and
`allowed_email_domains` (form fields on create; `config.auth.*` on `PUT`). Either non-empty → only
listed emails/domains receive magic links (always — the legacy `require_email_domain` flag no
longer loosens a non-empty allowlist); both empty → open portal. `@nomadkaraoke.com` admins can
always sign in.
Admin-only endpoints (`require_admin`) that mint and manage white-label tenants from the admin panel
(`/admin/tenants`), replacing the hand-run `scripts/setup-*-tenant.py` recipe.
@@ -2788,6 +2816,11 @@ env `KJBOX_PARTNER_SECRET`, Secret Manager `kjbox-partner-secret`):
`503 {"detail": "not configured"}` while unset (deploys dark), `403` if wrong.
Code: `backend/api/routes/kjbox.py` + `backend/services/kjbox_partner_service.py`.
**Quick version:** kjbox jobs also get a draft scrolling-lyrics video a few minutes after the audio
downloads (see ARCHITECTURE.md § "Quick version"). No new endpoint: poll `GET /api/jobs/{job_id}`
for `state_data.quick_version.status == "ready"`, then download
`GET /api/jobs/{job_id}/download/quick/video_mp4` (`… (Quick Version).mp4`).
### Send code
```http
@@ -2868,18 +2901,31 @@ by Nomad.
```http
POST /api/kjbox/catalog/resolve
X-Kjbox-Secret: <partner secret>
{"query": "the strokes max picu"}
→ {"kind": "content", "confident": true, "typed_artist": "the strokes", "typed_title": "max picu",
"canonical_artist": "The Strokes", "canonical_title": "Machu Picchu", "alternatives": [],
"engine": "ai", "reason": "…"}
{"query": "rihanna push up on me"}
→ {"kind": "cosmetic", "confident": true, "typed_artist": "rihanna", "typed_title": "push up on me",
"canonical_artist": "Rihanna", "canonical_title": "Push Up On Me", "alternatives": [],
"engine": "catalog", "reason": "catalog match"}
```
Splits a singer's one-line search into artist/title and corrects typos in one
small Gemini call (`backend/services/match_judge/free_text.py`, the match
judge's model + kinds). kjbox calls it only when its own catalogue search is
empty. Model trouble → `kind: "none"` (never 5xx). Results are cached per
case-folded query (in-process, 2000 entries); AI calls are capped partner-wide
at 120/min per instance (`429 rate_limited`; cache hits are free).
Gives a singer's one-line search the same tidy as the job form's
AudioSourceStep ("Tidied to …" / "Corrected to …"). Two steps
(`backend/services/match_judge/free_text.py`, `resolve_and_tidy`):
1. **Split + typo fix** — one small Gemini call splits the free text into
artist/title and corrects typos (the catalog can't parse a one-line query:
decide's track search finds nothing for "rihanna push up on me").
2. **Catalog tidy** — the chosen song (the AI's canonical pick, or its typed
split when it didn't recognise the song) goes through the job flow's own
`judge_match(stage="fast")`. A confident catalog match wins: its formatting
becomes `canonical_*`, `engine: "catalog"`, kind `cosmetic` when the query
already named that song (only casing/punctuation/word order differ), else
`content`. No catalog match → the AI verdict unchanged.
kind `none` keeps the AI's `typed_artist`/`typed_title` split when it has one
(kjbox pre-fills its make-it form with it). kjbox calls this only when its own
catalogue search is empty. Model trouble → `kind: "none"` (never 5xx). Results
are cached per case-folded query (in-process, 2000 entries); calls are capped
partner-wide at 120/min per instance (`429 rate_limited`; cache hits are free).
### Review emails for kjbox jobs
+67 -18
View File
@@ -38,10 +38,11 @@
│ (jobs) │ │ (files) │ │ (API keys) │ │ Worker (*) │
└──────────┘ └──────────┘ └──────────────┘ └──────────────┘
(*) 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.
(*) GCE Encoding Worker: a Spot c4d-highcpu-16 blue-green pair (AMD EPYC
Turin, the preferred pick) plus ONE on-demand c2d-highcpu-16 fallback in a
different zone for Spot/c4d stockouts (3 VMs since 2026-09-26 — see
docs/archive/2026-09-26-encoding-cost-cuts.md). Candidates are 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
and the "Encoding Worker" section below.
@@ -50,7 +51,7 @@
### Error Monitor
```text
Cloud Logging (all services) ──→ Error Monitor (Cloud Run Job, */15 min)
Cloud Logging (all services) ──→ Error Monitor (Cloud Run Job, hourly)
Frontend clients ───────────────→ POST /api/client-errors ──→ Firestore
│
├─ Normalize & deduplicate
@@ -262,7 +263,7 @@ LyricsTranscriber LyricsTranscriber
| karaoke-decide | Song catalog (MusicBrainz + Spotify) for autocomplete | Optional |
| KaraokeNerds | Community karaoke version detection | Optional |
*Flacfetch runs on a dedicated GCE VM with YouTube cookies and tracker access. Without it, YouTube downloads will fail due to bot detection on Cloud Run IPs.
*Flacfetch runs on a dedicated server (Netcup VPS, reached over public HTTPS) with YouTube cookies and tracker access. Without it, YouTube downloads will fail due to bot detection on Cloud Run IPs.
### Data Pipeline Cloud Functions
@@ -271,7 +272,7 @@ Three Cloud Functions manage the community karaoke data pipeline, running daily
| Function | Schedule | Purpose |
|----------|----------|---------|
| `divebar-mirror` | Daily 2:00 AM ET | Indexes 48K+ files from [diveBar Karaoke Google Drive](https://drive.google.com/drive/folders/1zxnSZcE03gzy0YVGOdnTrEIi8It_3Wu8) into BigQuery `divebar_catalog` |
| `kn-data-sync` | Daily 3:05 AM + 4:30 AM ET | Fetches KaraokeNerds catalog (281K songs) and community tracks (58K with YouTube URLs) to BigQuery + GCS |
| `kn-data-sync` | Daily 3:05 AM + 4:30 AM ET | Fetches KaraokeNerds catalog (281K songs) and community tracks (58K with YouTube URLs) to BigQuery + GCS. `full` mode then exports the **kjbox song-identification index** (≈2M songs: Spotify popularity ≥ 30 + all KN; `EXPORT DATA` → `gs://nomadkaraoke-kn-data/song-id/<run>/songs-*.tsv.gz`, manifest `song-id/latest.json`, last 3 runs kept), which the NomadPC downloads. Design: kjbox `docs/SONG-IDENTIFICATION.md` |
| `divebar-lookup` | Daily 6:00 AM ET + on-demand API | Public search/lookup API for KJ Controller; rebuilds KN↔Divebar cross-reference index |
**Infrastructure** (Pulumi-managed in `infrastructure/`):
@@ -305,16 +306,25 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
## Encoding Worker: blue-green primary pair + multi-family fallback pool
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.
both **Spot** c4d-highcpu-16 in us-central1-c) plus **one on-demand fallback**
(`encoding-worker-fallback-c2df`, c2d-highcpu-16, us-central1-f). **3 VMs total**
(cut from 10 on 2026-09-26 — docs/archive/2026-09-26-encoding-cost-cuts.md), all
TERMINATED by default, started on demand, and idle-stopped after 5 min.
**Spot preemption:** the pair uses `instance_termination_action=STOP`, so a
preempted worker is just a TERMINATED VM that the next request restarts. An
encode in flight when the VM is preempted is detected by
`EncodingService.wait_for_completion` (the pinned worker VM is no longer RUNNING)
and raised as `EncodingJobLostError`, which `run_with_lost_job_resubmit` resubmits
— the resubmit's connection failure then starts the Spot VM again, or the
on-demand fallback if Spot capacity is gone.
### Architecture
```text
Frontend → Backend (Cloud Run) → Firestore config → active worker (primary, or a
↑ capacity-fallback "override")
Cloud Scheduler (5 min) → Cloud Function → checks idle + stops VMs
Cloud Scheduler (2 min) → Cloud Function → checks idle (5 min) + stops VMs
↑
CI (GitHub Actions) → selects a fresh "green" (ranked pool) → health + encode test
→ promote (swap primary OR set active_override) → stop old
@@ -323,10 +333,13 @@ CI (GitHub Actions) → selects a fresh "green" (ranked pool) → health + encod
### 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).
stockout across every zone at once. To survive that, the fallback lives in a
different family AND zone from the c4d pair: `encoding-worker-fallback-c2df`
(c2d-highcpu-16, on-demand, us-central1-f). The pool was 8 fallbacks across 6
families (v0.195.0) until the 2026-09-26 cost cut; the selection machinery below
still handles any number of fallbacks — re-add entries to
`EncodingWorkerConfig.FALLBACKS` + the `encoding-worker-fallback-vms` secret if
stockouts become a problem again.
**Candidate ordering is one shared pure module**,
`backend/services/encoding_worker_preference.py::ordered_candidates(pool, capacity_state)`,
@@ -494,7 +507,7 @@ Audio can come from file upload or remote search (YouTube, torrents). All YouTub
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ Flacfetch VM (GCE) │
│ Flacfetch server (Netcup VPS, off-GCP) │
│ │
│ • Has YouTube cookies (avoids bot detection) │
│ • Has tracker credentials (RED, OPS private trackers) │
@@ -504,7 +517,10 @@ Audio can come from file upload or remote search (YouTube, torrents). All YouTub
```
**Key environment variables**:
- `FLACFETCH_API_URL` - URL of flacfetch VM (e.g., `http://10.x.x.x:8080`)
- `FLACFETCH_API_URL` - public HTTPS URL of the flacfetch server (secret `flacfetch-api-url`). The
serverless VPC connector that once let Cloud Run reach the old GCE VM's private IP was deleted
2026-09-26; the backend and `audio-download-job` / `bulk-search-job` have no VPC egress, so every
dependency they call must be reachable on a public address.
- `FLACFETCH_API_KEY` - API key for authentication
## Worker Execution
@@ -582,7 +598,36 @@ Audio stem separation runs **directly inside the audio worker Cloud Run Job**
- **Two-stage ensemble preset** — `instrumental_clean` (stage 1) + `karaoke` (stage 2).
- **Model cache** — Models are downloaded to `model_file_dir` (GCS-backed or local) and reused across executions.
**Rollback**: The old audio-separator Cloud Run Service (HTTP endpoint) is kept for rollback but no longer receives traffic. It will be removed in a future phase.
**The `audio-separator` Cloud Run GPU service** (us-east4, scale-to-zero) is no longer used by
prod gen jobs, but it still serves external remote-separation clients (`audio-separator-remote` /
local `karaoke-gen` CLI with `AUDIO_SEPARATOR_API_URL`; ~40 `/separate` calls/month as of
2026-09). Keep it at min-instances 0; don't remove it without checking its request logs first.
### Quick version (kjbox make-it jobs)
For jobs created by kjbox on behalf of a singer (`request_metadata.client_id` starts with
`kjbox`), the audio worker also produces a rough **scrolling-lyrics draft video** within a few
minutes of the audio landing, so the singer can sing now instead of waiting ~30 min for the
full NOMAD version. Code: `backend/services/quick_version/` (a port of kjbox `fastgen/`).
1. **Before the ensemble**, one fast single-model pass (`UVR-MDX-NET-Inst_HQ_4.onnx`, fastgen's model;
baked by `download_models.py` `EXTRA_MODELS`, downloaded on load until the next GPU base rebuild;
falls back to the always-baked `mel_band_roformer_instrumental_fv7z_gabox.ckpt`, which took
14 s load + 124 s for a 3:15 song on the L4; override with `QUICK_VERSION_MODEL`) → quick
instrumental + vocals.
2. A **background thread** renders the video while the GPU runs the ensemble: LRCLIB lyrics
(line-synced → time-anchored scroll; plain → constant crawl; none → title card), PIL-rasterised
crawl PNG + one ffmpeg `overlay` pass, 854×480, vocals mixed back in at 30% as a guide. Every
ffmpeg input and the output are bounded with `-t <duration>`: the GPU image's ffmpeg 4.4 never
ends on `-shortest` alone once `amix` is involved (first prod job ran into the 300 s join timeout).
3. Uploads `jobs/{id}/quick/quick.mp4` → `file_urls.quick.video_mp4`, and records
`state_data.quick_version = {status: separating|rendering|ready|failed, lyrics_tier, ready_at, …}`.
4. The worker joins the render (≤300 s) before cleaning up its temp dir — even when the ensemble
fails. Quick-version failures never fail the job. Skipped when `quick_version.status == ready`
(job retries), in remote-API separation mode, or with `KJBOX_QUICK_VERSION_ENABLED=false`.
kjbox's GenPoller reads `state_data.quick_version` from `GET /api/jobs/{id}` and downloads the file
via `/api/jobs/{id}/download/quick/video_mp4`.
## Multitenancy
@@ -732,6 +777,10 @@ The frontend's `TenantProvider` reads `window.__TENANT_CONFIG__` on startup (no
**Admin preview**: Admins can preview any tenant's branding in the main app by appending `?preview_tenant=<tenant_id>` to any URL. This bypasses subdomain detection and loads the specified tenant config, useful for verifying branding before DNS cutover.
**Tenant subdomains are automatic** (v0.246.0): `/admin/tenants` create provisions `{id}.nomadkaraoke.com` via the Cloudflare API (`services/tenant_domain_service.py`, secret `cloudflare-tenant-domains-token` = account-owned token scoped to Pages Read/Write + DNS Read/Write on the nomadkaraoke.com zone only), and delete removes it. Cloudflare Pages has no wildcard custom domains, so each tenant gets: (1) a Pages custom domain on `karaoke-gen-tenant`, (2) a proxied `CNAME <id>` → `karaoke-gen-tenant.pages.dev`. Existing non-tenant DNS records are never taken over or deleted. **Token blast radius (accepted risk):** Cloudflare can't scope Pages permissions to one project, so this token can modify any Pages project in the account (incl. the consumer `karaoke-gen` site) — it lives only in Secret Manager, readable by the backend SA; rotate it if the backend is ever compromised. DNS access is limited to the nomadkaraoke.com zone. No GCS CORS change is needed (bucket CORS allows any origin — safe because the bucket is private and signed URLs are the auth). Tenants created before this can be backfilled with **Manage → Set up domain** (`POST /api/admin/tenants/{id}/domain`). The subdomain is immutable (derived from the id). After a delete, other backend instances may still serve the tenant's cached config for up to 5 minutes (per-instance `TenantService` TTL).
**Theme/tenant edits take effect immediately**: while the storage bucket was publicly readable (until 2026-09-28), GCS served objects with the default `Cache-Control: public, max-age=3600` and even the backend's own reads could return a stale copy for up to an hour after an overwrite. The bucket is now private (`public_access_prevention=enforced`), and as defence in depth `StorageService.upload_json` writes `no-store`, theme asset/logo uploads pass `cache_control=no-store`, and `download_json` resolves the live generation before downloading (bypassing any cached copy of objects written before this).
## Tech Stack
- **Backend**: FastAPI, Python 3.12, Cloud Run
+1 -1
View File
@@ -221,7 +221,7 @@ TESTMAIL_NAMESPACE=... # testmail.app namespace
## Encoding Worker Operations
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.
The encoding worker is a Spot blue-green primary pair (`encoding-worker-a`/`-b`, c4d-highcpu-16) plus one stopped on-demand fallback (`encoding-worker-fallback-c2df`, c2d-highcpu-16, us-central1-f) — 3 VMs total since 2026-09-26. CI only blue-green redeploys the worker when a path in `infrastructure/encoding-worker/worker_code_paths.txt` changed since the serving version (or via Actions → CI → Run workflow with "Force a blue-green redeploy of the GCE encoding worker"). 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)
+48 -16
View File
@@ -14,7 +14,7 @@
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
| GCS job files | S3 `gcs/job-files/` | Sync to new bucket | 24h |
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 24h |
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 7 days (weekly, Sundays; incremental) |
| Secret Manager | S3 `secrets/YYYY-MM-DD.bin` (sealed-box encrypted) | Decrypt with private key from KeepassXC | 24h |
| AWS credentials (function) | GCP Secret Manager `aws-backup-credentials` | Read directly | On-change |
| AWS credentials (offline) | KeepassXC — "Nomad Karaoke — DR backup AWS access" | Manual lookup | On-change |
@@ -25,7 +25,7 @@
- [ ] KeepassXC contains "Nomad Karaoke — DR backup AWS access" (access key, secret key, region, S3 bucket name)
- [ ] KeepassXC contains "Nomad Karaoke — DR backup decryption key" (Curve25519 private key, 64 hex chars)
- [ ] GitHub repo `nomadkaraoke/karaoke-gen` has the secrets `AWS_BACKUP_READONLY_ACCESS_KEY_ID`, `AWS_BACKUP_READONLY_SECRET_ACCESS_KEY`, `DR_MONITOR_DISCORD_WEBHOOK` configured (powers the freshness monitor)
- [ ] GCP Secret Manager `github-backup-token` holds a valid GitHub PAT (`repo` + `read:org`) so the nightly job can bundle every repo — without it the git-repo backup silently skips (see § "Git repo backup setup")
- [ ] GCP Secret Manager `github-backup-token` holds a valid GitHub PAT (`repo` + `read:org`) so the weekly git step can bundle every repo — without it the git-repo backup silently skips (see § "Git repo backup setup")
- [ ] You can decrypt yesterday's secrets backup locally (run the drill in § "Quarterly restore drill")
- [ ] Your KeepassXC database itself is backed up off-machine (cloud sync, second device, or printed paper recovery)
@@ -35,13 +35,15 @@ If any of these fail, fix them now — not during an incident.
### Firestore Recovery
**Option A — PITR (fastest, within 7 days):**
**Option A — last night's local export (fastest, within 24h):**
Point-in-time recovery was **disabled on 2026-09-26** (GCP cost cut), so there
is no PITR restore any more. The backup function exports Firestore nightly to
`gs://nomadkaraoke-backup-staging/firestore/<YYYY-MM-DD>/` (only the latest
night is kept):
```bash
gcloud firestore databases restore \
--source-database="(default)" \
--destination-database="(default)-restored" \
--snapshot-time="2026-03-28T12:00:00Z" \
--project=nomadkaraoke
LATEST=$(gcloud storage ls gs://nomadkaraoke-backup-staging/firestore/ | sort | tail -1)
gcloud firestore import "$LATEST" --project=nomadkaraoke
```
**Option B — Import from S3 backup:**
@@ -307,7 +309,7 @@ Some external services lock to redirect URIs or treat the old GCP project ID as
If the GitHub account is suspended (e.g. an automated copyright false-positive)
or repos are taken down, **the code and its full history are still in S3**. The
nightly backup bundles every repo under `github.com/nomadkaraoke` and
weekly backup bundles every repo under `github.com/nomadkaraoke` and
`github.com/beveradb` into a single `git bundle` per repo — a self-contained
file you can clone from directly, no GitHub required. GCP is unaffected, so
production keeps running; this is purely about recovering the source of truth to
@@ -322,8 +324,18 @@ a new home.
flags, and per-repo backup status. Use it to know exactly what existed and to
recreate repo settings on the new host.
Forks are excluded by default (recoverable from upstream). Repos are only as
fresh as the last nightly run (24h RPO).
Forks are excluded by default (recoverable from upstream). The git step runs
**weekly (Sundays)** and is **incremental** (since 2026-09-26, to cut
cross-cloud egress): a repo is only re-cloned and re-uploaded when its GitHub
`pushed_at` is newer than its bundle's S3 upload time (minus a 1h safety lag);
unchanged repos show `"status": "unchanged"` in the manifest and keep their
existing S3 bundle. `git-repos/` only uploads to S3 in the same invocation as
the git step (a bundle stranded in staging by a failed upload is re-bundled next
Sunday rather than shipped late, which would break the lag assumption). The
first Sunday of each month re-bundles everything. So a
bundle is at most ~7 days behind (7-day RPO). To force a run now:
`?mode=git_repos` (incremental) or `?mode=git_repos&full=1` (all repos) — see
§ "Git repo backup setup".
### Restore
@@ -399,15 +411,16 @@ One-time setup so the nightly job can bundle private repos:
3. The owners backed up are set by the `GIT_BACKUP_OWNERS` env var on the
`backup-to-aws` function (default `nomadkaraoke,beveradb`), wired in
`infrastructure/modules/backup.py`.
4. Trigger a run and confirm bundles appear:
4. Trigger a git-only run (skips Firestore/BigQuery/GCS/secrets, so it is
safe to run any time) and confirm bundles appear:
```bash
curl -X POST -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
https://us-central1-nomadkaraoke.cloudfunctions.net/backup-to-aws
"https://us-central1-nomadkaraoke.cloudfunctions.net/backup-to-aws?mode=git_repos"
aws s3 ls s3://nomadkaraoke-backup/git-repos/ --recursive | head
```
If the PAT is missing/expired the git-repo step logs a warning and skips; the
freshness monitor then flags `git-repos/` as stale within ~36h.
freshness monitor then flags `git-repos/manifest.json` as stale within ~8 days.
## Decrypting the secrets backup
@@ -449,14 +462,15 @@ export AWS_DEFAULT_REGION=us-east-1
## Backup freshness monitor
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/manifest.json` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
Per-prefix limits reflect each prefix's **S3 (off-site)** cadence, which is not the same as its GCS-staging cadence:
| Prefix | S3 upload cadence | Monitor limit |
|--------|-------------------|---------------|
| `gcs/job-files/`, `secrets/`, `git-repos/` | nightly | 36h |
| `gcs/job-files/`, `secrets/` | nightly | 36h |
| `firestore/`, `bigquery/daily-refresh/` | weekly (Sundays) | 192h (≈8 days) |
| `git-repos/manifest.json` | weekly (Sundays), incremental | 192h (≈8 days) + manifest must show 0 bundle errors |
Firestore exports to GCS staging nightly (24h local restore point) but only ships to S3 weekly to cut cross-cloud egress (see `backup_to_aws/main.py` → `firestore_to_s3_today`). The monitor only sees the S3 copy, so its Firestore limit must allow a full week — using the 36h nightly figure caused a false "DR backup is stale" alert every Tue–Sat (fixed 2026-06-18).
@@ -534,3 +548,21 @@ re-import). The raw source files are not.
| S3 data transfer out to GCP | ~$0.09/GB |
| Full Spotify dataset retrieval + transfer (~100 GB) | ~$25 total |
| Full GCS job-files egress (~150 GB) | ~$14 |
## Incident: S3 overwrites silently failing 2026-09-14 → 2026-09-26
The incremental S3 upload (#997) checked "already in S3?" with `HeadObject`,
but the `backup-writer` IAM user only has `s3:ListBucket` + `s3:PutObject`
(no `s3:GetObject`). S3 answers HEAD on a *missing* key with 404 (fine — the
file uploaded) but on an *existing* key with **403**, so every **overwrite**
errored: git bundles + `manifest.json` stopped updating after 09-15 (the
freshness monitor failed daily on `git-repos/`), and re-written job files
(e.g. `lyrics/corrections_updated.json`, `karaoke.lrc`, re-rendered screens)
kept their older S3 copy. New keys (dated secrets/Firestore exports, new job
files) were unaffected. Fixed 2026-09-26 by switching the existence check to
`ListObjectsV2` (`s3_upload._list_s3_sizes`); a manual `?mode=git_repos` run
refreshed all changed bundles the same day. Re-written job files from
09-14..09-19 aged out of the 7-day staging lifecycle before the fix, so S3
holds their previous version (primary copies in GCS are intact; not
backfilled). Lesson: the IAM user is intentionally write+list only — test new
S3 calls against it, not an admin credential.
+41 -2
View File
@@ -164,6 +164,17 @@ Hard-won insights for the next person debugging GCE image builds:
./run.sh ...`, so the smoke test must verify tools-as-runner. The v2 smoke
test uses startup-script + `sudo -iu runner` for this.
## Which jobs use self-hosted runners (2026-09-26)
karaoke-gen's test/package jobs (package/backend unit + integration + emulator
tests, package builds, full frontend E2E) moved to **GitHub-hosted
`ubuntu-latest`** runners — free for this public repo, and they never needed GCP
credentials. That removed ~390 `gha-general-*` VMs/month. Only jobs that need
the GCE runners still request them: `deploy-backend` (`docker-build` label —
Docker image builds, same-region Artifact Registry) and the GPU integration
tests in python-audio-separator (`gpu`). No workflow currently requests the
plain general label; the `gha-runner-general` family is kept as a fallback.
## High-level architecture
```
@@ -183,14 +194,41 @@ Fresh GCE VM boots from custom image
▼
Boot disk auto-deletes; VM is gone
Every 15 min: orphan cleanup pass
Every 5 min: orphan cleanup + stalled-job re-dispatch pass
│ ─ list VMs labelled purpose=gha-ephemeral-runner
│ ─ cross-reference with org runners list
│ ─ delete VMs older than 30 min with no registration
│ ─ delete VMs older than 2 h regardless (hung job protection)
│ ─ de-register zombie GHA runners with no live VM
│ ─ scan every org repo for self-hosted jobs still `queued`
│ ─ per family: if a job is queued 5–60 min and queued jobs outnumber
│ spare runners (booting VMs + idle online runners), launch the
│ shortfall (max 5 per pass)
```
### Stalled-job re-dispatch (2026-09-28)
GitHub sends `workflow_job.queued` **once** and never redelivers a failed
webhook, and the webhook path launches exactly one VM. Three incidents left a
deploy job `queued` indefinitely (prod half-deployed each time):
* 2026-08-08 / 2026-09-25 — the dispatched GPU-family VM was preempted before it
registered; nothing replaced it.
* 2026-09-27 — the `deploy-backend` webhook got a **Cloud Run 429** ("no
available instance"): a CI burst had all 5 function instances busy, each
blocked up to 90s confirming its VM insert. No VM was ever created.
Fixes: `max_instance_count` 5 → 20 (`RunnerManagerConfig.FUNCTION_MAX_INSTANCES`),
and the scheduled pass (now every 5 min) re-dispatches stranded jobs regardless
of cause. JIT runners aren't bound to a job, so it compares per-family demand
with spare supply rather than tracking individual jobs. It stops retrying a job
after 60 min so fleet-wide runner breakage (see "stale baked runner version"
below) can't become a VM-launch loop. Env knobs on the function:
`REDISPATCH_ENABLED` (kill switch), `REDISPATCH_AFTER_MINUTES` (5),
`REDISPATCH_GIVE_UP_MINUTES` (60), `MAX_REDISPATCH_PER_TICK` (5). The scheduler
response JSON includes a `redispatch` object (`stalled_jobs`, `given_up`,
`dispatched`, `dispatch_failed`); log lines start `Re-dispatch`.
## Modes
Controlled by Pulumi config `karaoke-gen-infrastructure:runnerMode`:
@@ -242,7 +280,8 @@ GitHub schedules onto any runner whose labels are a superset of the job's.
Each image is tagged `gha-runner-<variant>-<YYYYMMDD-HHMMSS>` and joined to the
matching image family. The dispatcher always selects from the family, so the
newest non-deprecated image wins automatically. The build workflow keeps the
newest 2 images per family and **deletes** the rest (deprecated images still bill
newest image per family (`KEEP_IMAGES_PER_FAMILY: 1` since 2026-09-26 — GPU/windows
images are 15-21 GiB each) and **deletes** the rest (deprecated images still bill
for storage; images that an existing disk was created from are never deleted).
Until 2026-09-26 this step used an invalid gcloud filter and silently pruned
nothing — 31 runner images (~360 GB archived, ~$18/mo) had accumulated; they were pruned by hand to
+21 -5
View File
@@ -80,11 +80,11 @@ The `concurrency=1` setting may have been added deliberately for performance rea
### 🔍 GCE Encoding Worker
**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
- No longer a single 24/7 VM. Since 2026-09-26 it is 3 VMs: a **Spot**
c4d-highcpu-16 blue-green pair + 1 stopped on-demand c2d-highcpu-16 fallback
(was 10 × 32-vCPU on-demand VMs — see docs/archive/2026-09-26-encoding-cost-cuts.md).
- **Idle auto-shutdown is live** (JIT start + heartbeat on the lyrics-review page;
a Cloud Function checks every 2 min and stops idle VMs after 5 min). When idle, cost is just boot disks
(50 GB since 2026-09-26, ~$4-5/VM/mo; was 100 GB / ~$10 — see
docs/archive/2026-09-26-encoding-worker-disk-cost.md); compute is billed only while encoding — so the historical
"~$700/mo running 24/7" no longer applies.
@@ -171,3 +171,19 @@ If all optimizations implemented:
- **2026-02-10:** Initial analysis and GitHub runner optimization implemented
- **2026-02-10:** Runners reduced from 20 → 3 with auto-scaling, saving $1,390/month
- **2026-03-03:** Added dedicated on-demand build runner (`e2-standard-8`) for Docker deploys to prevent spot preemption during builds (~$0.27/hr only when deploying)
## 2026-09-26 cuts (post-credit-expiry, target: whole project < $300/mo)
| Change | Where | Est. saving |
|--------|-------|-------------|
| Deleted serverless VPC connector `cloud-run-connector` (flacfetch is off-GCP on a public URL) | `__main__.py`, `cloud_run.py`, `ci.yml` (`--clear-vpc-connector`) | ~$12/mo + Network Intelligence resource-hours |
| `karaoke-backend` min-instances 2 → 1 (accepted: big bursts may hit a ~15s cold start) | `ci.yml` | ~$25/mo |
| Autoclass on `karaoke-gen-storage-nomadkaraoke` (terminal NEARLINE) and `nomadkaraoke-divebar-files` (terminal ARCHIVE) | `storage.py`, `divebar_mirror.py` | ~$9–17/mo once objects cool (30d+) |
| `nomadkaraoke-data` (raw Spotify ETL, 158 GiB) → ARCHIVE after 30d | karaoke-decide `infrastructure/__main__.py` | ~$3/mo |
| DR git bundles weekly + incremental (only repos pushed since last S3 upload) | `functions/backup_to_aws/` | cross-cloud egress |
| Error monitor every 15 min → hourly (lookback 60 min) | `config.py`, `backend/services/error_monitor/config.py` | Cloud Run Job + Logging API |
| Firestore PITR disabled (nightly export remains) | `database.py` | PITR storage |
| `recover-stuck-downloads` / `retry-pending-render-jobs` every 5 → 10 min | `__main__.py` | ~half their Firestore reads |
Kept: the `audio-separator` Cloud Run GPU service (still used by external remote-CLI
clients; already scale-to-zero).
+35 -1
View File
@@ -645,7 +645,7 @@ When two sequential human review steps can be combined into one, do it. We origi
- 6 GCE encoding workers: 2 primaries in `us-central1-c` (blue-green, `c4d-highcpu-32`) + 2 `c4d` capacity fallbacks in `us-central1-a`/`-b` + 2 `n2-highcpu-32` fallbacks in `us-central1-c`/`-f`. All idle by default; started on demand.
- `EncodingWorkerCandidate` list iterated in `ensure_any_running` — primary first, fallbacks in declared order. Capacity errors fall through to next candidate; non-capacity start errors also fall through (broadened in PR #750).
- New `RENDER_PENDING_CAPACITY` job state for transient infra failures — different from `FAILED` (which is for unrecoverable bugs).
- Cloud Scheduler fires `/api/internal/retry-pending-render-jobs` every 5 min; 24h hard timeout per job.
- Cloud Scheduler fires `/api/internal/retry-pending-render-jobs` every 10 min; 24h hard timeout per job.
- `EncodingWorkerConfig.active_url` returns the override URL when set, else primary. `_get_worker_url()` consults this with a 30s TTL cache.
- Both Cloud Run service AND Cloud Run Job (video-encoding-job) need `ENCODING_WORKER_FALLBACK_VMS` env — they each instantiate their own `EncodingService`.
@@ -2077,3 +2077,37 @@ fallbacks — go through `JobManager.start_job_processing`, which ignored it, so
users never saw the audio editor. `start_job_processing` now parks such jobs via the
shared `enter_audio_edit` helper. Any new "audio just arrived" path must go through one
of these two gates.
## GCS Autoclass bumps `updated`; S3 HEAD needs GetObject (2026-09-26 cost cuts)
- **Autoclass / lifecycle storage-class transitions change an object's `updated`
timestamp** (it tracks any metadata change). Anything that detects "changed since
last run" via `blob.updated` will treat every cooled object as new — and reading it
pulls it straight back to Standard, defeating Autoclass. Use `time_created` (the
current generation's creation time) for content-change detection. The DR
`gcs_sync.py` was switched before Autoclass was enabled on the job-files bucket.
- **S3 HEAD on an existing key returns 403 without `s3:GetObject`** (404 only for
missing keys when you have `s3:ListBucket`). The write-only `backup-writer` IAM user
therefore failed every *overwrite* for 12 days after #997 added a HEAD-based
"already uploaded?" check. Use `ListObjectsV2` for existence/size checks with that
user, and test new S3 calls against the real least-privilege credential.
- **Removing a serverless VPC connector from a gcloud-deployed Cloud Run service needs
`--clear-vpc-connector`**: just dropping `--vpc-connector` from `gcloud run deploy`
keeps the existing setting. Detach every service/job before deleting the connector.
## A public GCS bucket makes the backend read its own stale writes (2026-09-28, v0.245.3)
`karaoke-gen-storage-nomadkaraoke` had an out-of-band `allUsers` objectViewer grant
(added by hand 2025-12-22 to host a one-off `public/job-inspector.html`; never in Pulumi).
Besides exposing every customer file to anonymous listing, it changed caching: GCS serves
publicly readable objects without an explicit Cache-Control as `public, max-age=3600`,
and **authenticated API reads can be answered from that edge cache too**. A tenant created
in the admin console was "Theme not found" for new jobs because the backend downloaded the
pre-tenant `themes/_metadata.json` two minutes after it was rewritten.
- Never make the main bucket public for convenience — host debug pages elsewhere or sign a URL.
`public_access_prevention="enforced"` is now set in Pulumi so a stray grant can't take effect.
- Mutable JSON is written `no-store` and `download_json` reads the live generation
(`bucket.get_blob` → generation-pinned download), so this class of staleness can't recur.
- Removing an IAM member that Pulumi doesn't manage needs an explicit
`gcloud storage buckets remove-iam-policy-binding`; PAP=enforced blocks it meanwhile.
+2 -1
View File
@@ -44,7 +44,7 @@
| **Review reminder & auto-expiry** | Working (24h reminder, 48h cancel + refund) |
| **i18n / Multilingual (frontend)** | Working (next-intl, en/es/de, 1062 strings, [locale] routing) |
| **Referral system** | Working (referral links with configurable discounts, 20% cash kickback via Stripe Connect, auto-payout at $20) |
| **Error monitor** | New (Cloud Run Job every 15 min — log collection, normalization, LLM dedup/grouping, Discord alerts, auto-resolution, daily digest) |
| **Error monitor** | New (Cloud Run Job hourly — log collection, normalization, LLM dedup/grouping, Discord alerts, auto-resolution, daily digest) |
| **Edge security (Cloudflare)** | Working (api.nomadkaraoke.com proxied — WAF + rate limit + origin lock enforced; 2026-07-20) |
## Known Issues
@@ -57,6 +57,7 @@
## Recent Changes
- **Vocal waveforms for own-instrumental jobs** (2026-09-26, v0.244.1): jobs with a user-supplied instrumental skip GPU separation, so the lyrics review Waveforms mode had no vocals stem (`/vocals-peaks` 404). The lyrics worker now derives approximate vocals on CPU, alongside transcription: it aligns the instrumental to the mix by FFT cross-correlation (±2s), fits a gain by least squares, and subtracts (`backend/services/derived_vocals.py`, numpy + ffmpeg, a few seconds). The result is stored as `stems.vocals_derived` (mono 22.05 kHz FLAC), which `vocals_stem_path` uses only as a last resort, so screens pre-computes the peaks as usual. It's waveform-only: never shipped as a deliverable stem, never downloaded by the remote CLI, and never used for the original-vocals guide. Safeguards: alignment correlates a fixed 60s excerpt (memory doesn't scale with track length); inputs over 20 min are skipped; ffmpeg calls time out; the handoff waits at most 3 min; nothing is registered when the instrumental didn't cancel (residual > 85% of the mix), since a full-mix envelope would mislead timing edits. Best-effort: any failure logs and the job proceeds.
- **User-instrumental renders: WAV/M4A/OGG/AAC no longer fail** (2026-09-26, v0.243.1): the orchestrator render path sent only `instrumental_selection="custom"` to the GCE encoder, whose custom lookup accepted just `*custom_instrumental*.{flac,mp3}`. Tenant MP3s worked, but a `.wav` user instrumental failed with "No instrumental audio found" (job 3ea34552). The orchestrator now passes `existing_instrumental` (the encoder downloads it and matches any extension), and the custom lookup (`resolve_instrumental` in `gce_encoding/main.py`) accepts any audio extension.
- **Crash reports carry diagnostics + breadcrumbs** (2026-09-26, v0.243.1): A Firefox "Uncaught out of memory" froze a tab mid-upload, and the alert was useless. The browser gave no Error object, so the reporter's own stack became the pattern, and that stack pushed URL/UA/build out of Discord's view (`extra` was never kept). Now `lib/diagnostics.ts` keeps a 30-entry breadcrumb trail (navigation, clicks, upload phases, errors) and snapshots page age, DOM/canvas/audio counts, live blob URLs and the JS heap (Chromium) into every report. Errors without an Error object are flagged `synthetic` (stack dropped, location kept) and group by message. One page load can send at most 20 reports. The alert sample now lists message → location → URL/UA/build → Diag → Trail → trimmed stack, and the full `extra` is logged as `client_extra` on `frontend_crash_reported`.
- **Unified browser upload flow + bring-your-own instrumental** (2026-09-26, v0.243.0): Two invisible upload failures on the same song. Job 8729f19a: the job was created and charged, then the browser upload was abandoned; the only UI hint was the "Creating..." button text and the card already said "Setting up", so it sat `pending` forever. Job 2d0c1ae0: a 44 MB instrumental upload on the review screen was a multipart POST through Cloud Run (32 MiB cap) and failed silently. Now every user upload (guided job creation, tenant single job, instrumental review) goes through one shared layer: `lib/upload.ts` (signed-URL PUT with progress, multi-file aggregate progress, client-side duration pre-check), `hooks/useUploadTask.ts` (progress state + `beforeunload` guard; tenant bulk uses the guard) and `components/upload/UploadProgressModal.tsx` (a modal that can't be dismissed, showing progress, speed and ETA). The guided flow always uses the signed-URL path, which fixed `requires_audio_edit` being silently dropped for 25MB+ uploads. Private upload jobs can attach the user's own instrumental (`existing_instrumental`), which skips separation and instrumental review. Instrumental review uploads go direct to GCS (`instrumental-upload-url` / `instrumental-upload-complete`), and the review now plays the upload via the returned signed `audio_url` (the old `/audio-stream` URL had no route). Backend: `state_data.awaiting_upload` → "Waiting for upload" label; the hourly stale-review run cancels + refunds jobs still awaiting upload after 6h (24h if some files landed; tenant bulk exempt); a failed browser upload cancels its own job immediately; `uploads-complete` checks ownership and cancels + refunds on an instrumental duration mismatch. See [archive/2026-09-26-unified-upload-flow-plan.md](archive/2026-09-26-unified-upload-flow-plan.md).
+1 -1
View File
@@ -34,7 +34,7 @@ GitHub-hosted runners work but are slower (2 vCPU, 7GB RAM) and costs scale line
| Build runner | 1x `github-build-runner`, `e2-standard-8`, 200GB SSD | Docker image builds (needs more CPU/RAM) |
| GPU runners | 3x `github-gpu-runner-{1..3}`, `n1-standard-4` + T4 GPU, 200GB SSD | Audio separation model testing |
| Cloud Function | `github-runner-manager`, Gen2, Python 3.12, 5min timeout | Start/stop VMs based on webhooks and idle checks |
| Cloud Scheduler | `runner-manager-idle-check`, every 15 min | Trigger idle runner checks |
| Cloud Scheduler | `runner-manager-idle-check`, every 5 min | Orphan cleanup + stalled-job re-dispatch (see EPHEMERAL-GHA-RUNNERS.md) |
| Cloud NAT | `github-runners-nat` + `github-runners-router` | Outbound internet for VMs (no external IPs) |
All runner VMs are in `us-central1-a`.
+1 -1
View File
@@ -818,7 +818,7 @@ A change tagged critical-path requires, before it enforces new behavior:
- A **composed integration test** of the affected seam (producer + consumer, real, with
only the external boundary mocked) — see the New Guard checklist item 5.
- **Shadow-first** rollout for any new enforcement (checklist item 4).
- A **post-deploy canary / real-job verification** before the change is trusted at 100%
- A **real-job verification in production** (manual, or the daily E2E) before the change is trusted at 100%
(a fresh happy-path job plus, where relevant, an admin-reset + retry to exercise the
recovery path).
+14 -17
View File
@@ -63,7 +63,7 @@ defense-in-depth beneath the signing-free review path.
## Fast rollback (bad backend deploy)
**When to use:** a merge-to-main deploy shipped a bad backend revision — the
post-deploy canary failed, the error monitor/Discord is alerting, or you can see
daily E2E failed, the error monitor/Discord is alerting, or you can see
failing jobs/5xx in production — and you want to get back to the last known-good
state *now* rather than wait for a forward fix to build and deploy.
@@ -104,7 +104,7 @@ scripts/rollback.sh --image-version v0.222.2 --jobs-only
- After rollback, confirm the serving version:
`curl -s https://api.nomadkaraoke.com/api/health/detailed | jq .version`.
- This is the manual counterpart to CI's automatic service canary: a failed
post-deploy canary leaves the *service* on the prior revision automatically
candidate-revision smoke leaves the *service* on the prior revision automatically
(the new revision is deployed `--no-traffic`), but the **jobs** have no
auto-rollback — if a bad deploy reached the jobs, re-pin them with this script.
@@ -127,9 +127,9 @@ runbook: **[docs/PYPI-STORAGE-PRUNE.md](PYPI-STORAGE-PRUNE.md)**.
## Job stuck at `downloading_audio` status
**Cause:** Before v0.130.0, audio downloads ran as FastAPI BackgroundTasks. Cloud Run would terminate "idle" instances mid-download. Since v0.130.0, downloads use a Cloud Run Job (`audio-download-job`) and a Cloud Scheduler recovery job runs every 5 minutes to fail stuck downloads automatically.
**Cause:** Before v0.130.0, audio downloads ran as FastAPI BackgroundTasks. Cloud Run would terminate "idle" instances mid-download. Since v0.130.0, downloads use a Cloud Run Job (`audio-download-job`) and a Cloud Scheduler recovery job runs every 10 minutes (5 before 2026-09-26) to fail stuck downloads automatically.
**Auto-recovery:** The `recover-stuck-downloads` scheduler (`/api/internal/recover-stuck-jobs`, every 5 min) detects jobs stuck in `downloading_audio` for >10 minutes and, since v0.192.3:
**Auto-recovery:** The `recover-stuck-downloads` scheduler (`/api/internal/recover-stuck-jobs`, every 10 min) detects jobs stuck in `downloading_audio` for >10 minutes and, since v0.192.3:
- **Torrent sources (RED/OPS)** → parks the job in `download_pending_retry` and keeps re-attempting the download for up to **24 hours** (handles rare tracks with few/intermittent seeders and transient tracker outages), then fails permanently with a clear message. No manual action needed. See `download_pending_retry` below.
- **Other sources (YouTube/Spotify/URL)** → fails the job (deterministic); use the admin retry button to re-attempt.
@@ -404,7 +404,7 @@ gcloud compute instances describe encoding-worker-a \
**Cause:** The render worker started (VM up, rendering underway) then died mid-render — Cloud Run instance recycle / SIGKILL / OOM / lost GCE VM — without unregistering. `updated_at` stops advancing. Before v0.192.3 nothing recovered this: the capacity-retry cron only looks at `render_pending_capacity`, `recover-stuck-jobs` only looked at `downloading_audio`, and the render Cloud Task has finite attempts.
**Auto-recovery (v0.192.3+):** `recover-stuck-jobs` (every 5 min) now flags a job in `rendering_video` with no progress for **>45 min** (`rendering_video_stuck`) and re-parks it into `render_pending_capacity`, so the existing `retry-pending-render-jobs` cron resets it to `review_complete` and re-renders (same 24h ceiling). No manual action needed.
**Auto-recovery (v0.192.3+):** `recover-stuck-jobs` (every 10 min) now flags a job in `rendering_video` with no progress for **>45 min** (`rendering_video_stuck`) and re-parks it into `render_pending_capacity`, so the existing `retry-pending-render-jobs` cron resets it to `review_complete` and re-renders (same 24h ceiling). No manual action needed.
**Root-cause fix (v0.224.0+):** the dominant cause of this state was **backend deploys**: the render worker ran as a FastAPI BackgroundTask on the Cloud Run *service*, and every deploy rollout that landed mid-render SIGKILLed it ~10s after SIGTERM (the lifespan "park on shutdown" hook never runs in that scenario — uvicorn waits for background tasks *before* running lifespan shutdown, so it dies waiting; incident 2026-09-13, job `41e06b90`, tenant-E2E run #107). Since v0.224.0 the render worker runs as a **Cloud Run Job** (`video-encoding-job` with a `render_video_worker` args override, flag `USE_CLOUD_RUN_JOBS_FOR_RENDER`), which runs to completion regardless of service deploys — same fix the video worker got in 2026-03 (`USE_CLOUD_RUN_JOBS_FOR_VIDEO`). The 45-min sweep remains as the safety net for the remaining causes (job execution crash/OOM/timeout, lost GCE VM). Rollback: remove `USE_CLOUD_RUN_JOBS_FOR_RENDER=true` from the service env to fall back to the legacy Cloud Tasks path.
@@ -436,9 +436,11 @@ gcloud compute instances describe encoding-worker-a \
**Symptoms:** Job status is `render_pending_capacity` (introduced 2026-05-05). User-facing message says *"Encoding capacity is temporarily unavailable. Your job will retry automatically — no action needed."* (As of v0.192.3 a mid-render stall can also land here — see "orphaned render" above.)
**Background — what this state means:** GCE returned `ZONE_RESOURCE_POOL_EXHAUSTED` or transient `503 SERVICE_UNAVAILABLE` from `compute.instances.start` on every encoding-worker VM. The render worker parks the job in `RENDER_PENDING_CAPACITY` instead of failing it; Cloud Scheduler retries it every 5 min via `/api/internal/retry-pending-render-jobs`. Hard timeout is 24 hours (then transitions to `failed` with a clear permanent-failure message).
**Background — what this state means:** GCE returned `ZONE_RESOURCE_POOL_EXHAUSTED` or transient `503 SERVICE_UNAVAILABLE` from `compute.instances.start` on every encoding-worker VM. The render worker parks the job in `RENDER_PENDING_CAPACITY` instead of failing it; Cloud Scheduler retries it every 10 min via `/api/internal/retry-pending-render-jobs`. Hard timeout is 24 hours (then transitions to `failed` with a clear permanent-failure message).
The fallback fleet is diversified across **6 machine families** (broadened to the full pool in v0.195.0): `c4d-highcpu-32` primaries (`encoding-worker-a`/`-b`) in `us-central1-c`, plus 8 stopped fallbacks — `c4d` (`-fallback-a`/`-b`, zones a/b), `n2` (`-n2c`/`-n2f`, zones c/f), `c4` (`-c4a`, zone a), `n4d` (`-n4db`, zone b), `c2d` (`-c2df`, zone f), `n2d` (`-n2da`, zone a). Candidates are tried **fastest-first with a 15-min capacity cooldown** (a family that stocks out is demoted, then re-probed) — see `backend/services/encoding_worker_preference.py`. A single-family region-wide stockout (which took out c4d a/b/c at once on 2026-08-12) now still finds capacity in the 5 other families. If you see EVERY family return stockout, that's a genuinely severe regional event — wait, or add a cross-region fallback. NOTE: creating a *new* fallback VM (or re-creating a deleted one) still needs a one-time boot allocation, so a deep enough crunch can even block provisioning — a `pulumi up` may show the missing VM as "to create / errored" until capacity returns.
Since 2026-09-26 the fleet is 3 VMs: **Spot** `c4d-highcpu-16` primaries (`encoding-worker-a`/`-b`) in `us-central1-c`, plus ONE stopped on-demand fallback `encoding-worker-fallback-c2df` (`c2d-highcpu-16`, `us-central1-f`). Candidates are tried **fastest-first with a 15-min capacity cooldown** — see `backend/services/encoding_worker_preference.py`. If both the Spot pair and the c2d fallback return stockout, that's a genuinely severe regional event — wait, or (re-)add a fallback in another family/zone to `EncodingWorkerConfig.FALLBACKS` **and** the `encoding-worker-fallback-vms` secret (the 2026-08-15 pool had 8 fallbacks across 6 families). NOTE: creating a *new* fallback VM needs a one-time boot allocation, so a deep enough crunch can even block provisioning.
**Spot preemption mid-encode** is expected occasionally: the backend sees the pinned worker VM is TERMINATED/STOPPING, logs `Encoding worker VM stopped mid-job (... ) — likely Spot preemption`, and resubmits the encode as `<job>_retry_<hex>` (up to `ENCODING_RESUBMIT_MAX`, default 2). Repeated preemptions → the job fails with the lost-job error; check `gcloud compute operations list --filter="operationType=compute.instances.preempted"`.
**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.
@@ -452,7 +454,7 @@ print((d.get('state_data') or {}).get('render_pending_capacity'))
"
```
**Force an immediate retry** (Cloud Scheduler runs every 5 min, but you can poke it manually):
**Force an immediate retry** (Cloud Scheduler runs every 10 min, but you can poke it manually):
```bash
ADMIN_TOKEN=$(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1)
curl -X POST https://api.nomadkaraoke.com/api/internal/retry-pending-render-jobs \
@@ -466,18 +468,13 @@ 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 of the 6 families; if ALL refuse, it's severe — wait.
# Try starting each worker; if ALL refuse, it's severe — wait.
# Synchronous (no --async) so the start op surfaces stockout inline, and we capture
# gcloud's own exit status rather than piping (a pipe would return sed's status).
for VM_ZONE in \
"encoding-worker-fallback-a:us-central1-a" \
"encoding-worker-fallback-b:us-central1-b" \
"encoding-worker-fallback-n2c:us-central1-c" \
"encoding-worker-fallback-n2f:us-central1-f" \
"encoding-worker-fallback-c4a:us-central1-a" \
"encoding-worker-fallback-n4db:us-central1-b" \
"encoding-worker-fallback-c2df:us-central1-f" \
"encoding-worker-fallback-n2da:us-central1-a"; do
"encoding-worker-a:us-central1-c" \
"encoding-worker-b:us-central1-c" \
"encoding-worker-fallback-c2df:us-central1-f"; 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,86 @@
# Encoding-worker cost cuts (2026-09-26)
Part of the "whole GCP project under $300/mo" push (workspace plan:
`docs/archive/2026-09-26-gcp-under-300-plan.md`). The encoding VMs were costing
~$300/mo for ~5-20 jobs/day. Andrew approved all of these, including the speed
trade-offs.
## What changed
| | Before | After |
|---|---|---|
| Primary pair `encoding-worker-a`/`-b` | c4d-highcpu-32, on-demand | **c4d-highcpu-16, Spot** (STOP on preemption) |
| Fallbacks | 8 stopped VMs across 6 families (+8 static IPs, 8 boot disks) | **1**: `encoding-worker-fallback-c2df`, c2d-highcpu-16, **on-demand**, us-central1-f |
| Fleet | 10 VMs | 3 VMs |
| Idle shutdown | 15 min, checked every 5 min | **5 min, checked every 2 min** |
| CI worker blue-green deploy | every push to main (~5x/day, boots a green + test encode) | only when `infrastructure/encoding-worker/worker_code_paths.txt` paths changed since the serving version; manual override via workflow_dispatch input `force_encoding_worker_deploy` |
| Nomad Dropbox upload | whole output folder | minus the lossless 4K **MP4** (`DROPBOX_SKIP_OUTPUT_SUFFIXES`); tenant folders unchanged |
Dropped from scope by Andrew mid-task: moving review previews off the VMs
(`USE_GCE_PREVIEW_ENCODING` stays `true`) and removing the review-page warmup. The
warmup is deliberate (VM warm for preview + final render), so instead the review
page now heartbeats every 2 min while the tab is visible and was used in the last
15 min (`frontend/lib/lyrics-review/hooks/useEncodingWorkerKeepAlive.ts`), keeping
the VM inside the new 5-min idle window during a review. Previously the heartbeat
only fired on lyric edits.
## How it was applied (infra)
- **Spot conversion without recreating the VMs.** Pulumi (pulumi-gcp 9.22.0)
treats a `scheduling` change as *replace*; recreating a c4d VM risks a stockout
at create time (and the VM would be gone). Instead each VM was converted in
place while STOPPED:
`gcloud compute instances set-scheduling <vm> --zone us-central1-c --preemptible --provisioning-model=SPOT --instance-termination-action=STOP --no-restart-on-failure --maintenance-policy=TERMINATE`,
then `pulumi refresh --target <vm>` (state now matches the code) and a targeted
`pulumi up` for the in-place machine-type change (`allow_stopping_for_update`).
Note `--preemptible` is required alongside `--provisioning-model=SPOT`.
- Fallback removal: targeted `pulumi up` deleted 7 VMs (+ their auto-delete boot
disks) and 7 static IPs; c2df resized in place to c2d-highcpu-16.
- `encoding-worker-fallback-vms` secret → version 6 (only c2df). The value is
managed manually (Pulumi only creates the secret).
- Idle function env + scheduler updated by Pulumi; `main.py` default also 5.
## Behaviour notes
- **Spot preemption mid-encode**: `EncodingService.wait_for_completion` now checks
the pinned worker VM's status on a failed poll; if it's STOPPING/TERMINATED/etc.
it raises `EncodingJobLostError`, so `run_with_lost_job_resubmit` resubmits the
encode (fresh `_retry_` id; outputs overwrite the same GCS paths). Before, a
vanished VM surfaced after ~7 min as a non-resubmitted "lost contact" failure.
- **Idle-stop vs. an encode in flight**: the idle function's `/health active_jobs`
counts only RUNNING jobs and `last_activity_at` used to be written only when a
VM was started, so with a 5-min window a long encode's VM could be stopped in
the seconds between the job finishing and the backend's next poll. The poll
loop now refreshes `last_activity_at` at most once a minute while waiting.
(A VM seen in STAGING/PROVISIONING after accepting a job also counts as lost.)
- **Stale fallback entries** (a removed VM still listed in an instance's cached
`ENCODING_WORKER_FALLBACK_VMS`) are now skipped (`NOT_FOUND` start error)
instead of aborting the whole failover.
- `SPEED_RANK` is keyed by machine *family* now, so the ranking survives vCPU
resizes.
- 16 vCPU: final encodes/renders will be slower (x264 kept ~66-78% of 32 vCPUs
busy). RAM is ~30-32 GB — one 4K encode peaks ~18 GB and heavy jobs are
serialized (`ENCODING_HEAVY_CONCURRENCY=1`), so no OOM risk.
## Dropbox lossless (item 7) — why only the MP4
No automated consumer reads lossless files from Dropbox (YouTube reads the local /
GCS MKV; GDrive, the NOMAD master mirror, kjbox and the AWS backup use GCS or
lossy files). But the lossless **MKV** is promised *in the Dropbox folder* by the
customer completion email (`backend/services/template_service.py`,
`backend/translations/*.json` `fileList`) and by the live Fiverr auto-reply bot
(`fiverrbot/fiverrbot/triage/prompts.py` "What's delivered"), and B2B tenant
VocalStar expects lossless. So the default skips only the lossless 4K MP4 (not
promised anywhere in Dropbox) and only for Nomad's own folders. To also skip the
MKV: update those two texts, then set
`DROPBOX_SKIP_OUTPUT_SUFFIXES=" (Final Karaoke Lossless 4k).mp4| (Final Karaoke Lossless 4k).mkv"`
on the `video-encoding-job` (Pulumi `infrastructure/modules/cloud_run.py`) or
change the default in `backend/config.py`.
## Open risks
- Spot capacity for c4d in us-central1-c can disappear; then all work lands on
the single on-demand c2d fallback (slower, and a single lane).
- Two consecutive preemptions of the same encode exhaust `ENCODING_RESUBMIT_MAX=2`.
- Skipped CI worker deploys mean `config/encoding-worker.primary_version` can lag
the backend version; VMs still boot the latest wheel from GCS.
+78 -1
View File
@@ -13,6 +13,8 @@ const createTenant = jest.fn()
const getTenant = jest.fn()
const updateTenant = jest.fn()
const getThemeTemplate = jest.fn()
const deleteTenant = jest.fn()
const provisionTenantDomain = jest.fn()
jest.mock('@/lib/api', () => ({
adminApi: {
@@ -21,6 +23,8 @@ jest.mock('@/lib/api', () => ({
getTenant: (...args: unknown[]) => getTenant(...args),
updateTenant: (...args: unknown[]) => updateTenant(...args),
getThemeTemplate: (...args: unknown[]) => getThemeTemplate(...args),
deleteTenant: (...args: unknown[]) => deleteTenant(...args),
provisionTenantDomain: (...args: unknown[]) => provisionTenantDomain(...args),
},
}))
@@ -43,6 +47,7 @@ beforeEach(() => {
tenant: { id: 'randy-vild', name: 'Randy Vild', subdomain: 'randy-vild.nomadkaraoke.com', is_active: true },
preview_url: 'https://gen.nomadkaraoke.com/en/app?preview_tenant=randy-vild',
subdomain_url: 'https://randy-vild.nomadkaraoke.com',
domain: { hostname: 'randy-vild.nomadkaraoke.com', state: 'active', dns_ok: true, pages_status: 'active' },
})
getTenant.mockResolvedValue({
tenant: {
@@ -52,12 +57,17 @@ beforeEach(() => {
is_active: true,
branding: { tagline: 'Be a Vocal Star' },
defaults: { dropbox_path: '/Karaoke/Tracks-VocalStar', brand_prefix: 'VSTAR', distribution_mode: 'download_only' },
auth: { allowed_email_domains: ['vocal-star.com'] },
auth: { allowed_email_domains: ['vocal-star.com'], allowed_emails: ['boss@gmail.com'] },
},
theme_id: 'vocalstar',
style_params: { intro: { title_color: '#ffff00' }, karaoke: {}, end: {}, cdg: {} },
assets: ['karaoke_background.jpg', 'Oswald-SemiBold.ttf'],
preview_url: 'https://gen.nomadkaraoke.com/en/app?preview_tenant=vocalstar',
domain: { hostname: 'vocalstar.nomadkaraoke.com', state: 'missing', dns_ok: false, pages_status: null },
})
deleteTenant.mockResolvedValue(undefined)
provisionTenantDomain.mockResolvedValue({
domain: { hostname: 'vocalstar.nomadkaraoke.com', state: 'provisioning', dns_ok: true, pages_status: 'initializing' },
})
updateTenant.mockResolvedValue({ tenant: { id: 'vocalstar', name: 'Vocal Star', subdomain: 'vocalstar.nomadkaraoke.com', is_active: true } })
getThemeTemplate.mockResolvedValue({ style_params: { intro: {}, karaoke: {}, end: {}, cdg: {} } })
@@ -91,6 +101,8 @@ describe('Admin Tenants page', () => {
const fd = createTenant.mock.calls[0][0] as FormData
expect(fd.get('name')).toBe('Randy Vild')
expect(fd.get('tenant_id')).toBe('randy-vild')
// Subdomain is derived server-side, never sent
expect(fd.get('subdomain')).toBeNull()
// Success view shows the preview link
expect(
@@ -123,6 +135,59 @@ describe('Admin Tenants page', () => {
expect(config.name).toBe('Vocal Star')
expect(config.defaults.dropbox_path).toBe('/Karaoke/Tracks-VocalStar')
expect(JSON.parse(fd.get('style_params') as string).intro.title_color).toBe('#ffff00')
expect(config.auth).toEqual({ allowed_email_domains: ['vocal-star.com'], allowed_emails: ['boss@gmail.com'] })
expect(config.subdomain).toBeUndefined()
})
it('edits individual allowed emails', async () => {
render(<AdminTenantsPage />)
await screen.findByText('Vocal Star')
fireEvent.click(screen.getByRole('button', { name: /manage/i }))
const emails = await screen.findByLabelText(/allowed emails/i)
expect(emails).toHaveValue('boss@gmail.com')
fireEvent.change(emails, { target: { value: 'Randy@Gmail.com, andrew@example.com' } })
fireEvent.click(screen.getByRole('button', { name: /save changes/i }))
await waitFor(() => expect(updateTenant).toHaveBeenCalledTimes(1))
const config = JSON.parse((updateTenant.mock.calls[0][1] as FormData).get('config') as string)
expect(config.auth.allowed_emails).toEqual(['randy@gmail.com', 'andrew@example.com'])
})
it('warns when the portal is open to anyone', async () => {
render(<AdminTenantsPage />)
await screen.findByText('Vocal Star')
fireEvent.click(screen.getByRole('button', { name: /manage/i }))
fireEvent.change(await screen.findByLabelText(/allowed emails/i), { target: { value: '' } })
fireEvent.change(screen.getByLabelText(/allowed email domains/i), { target: { value: '' } })
expect(screen.getByText(/anyone can sign in/i)).toBeInTheDocument()
})
it('shows domain status and can set up a missing domain', async () => {
render(<AdminTenantsPage />)
await screen.findByText('Vocal Star')
fireEvent.click(screen.getByRole('button', { name: /manage/i }))
expect(await screen.findByText('not set up')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: /set up domain/i }))
await waitFor(() => expect(provisionTenantDomain).toHaveBeenCalledWith('vocalstar'))
expect(await screen.findByText(/provisioning \(initializing\)/)).toBeInTheDocument()
})
it('deletes a tenant only after typing its id', async () => {
render(<AdminTenantsPage />)
await screen.findByText('Vocal Star')
fireEvent.click(screen.getByRole('button', { name: /manage/i }))
await screen.findByLabelText(/allowed emails/i)
fireEvent.click(screen.getByRole('button', { name: /delete tenant/i }))
const confirmBtn = () => screen.getAllByRole('button', { name: /^delete tenant$/i }).slice(-1)[0]
const input = await screen.findByLabelText(/to confirm/i)
expect(confirmBtn()).toBeDisabled()
fireEvent.change(input, { target: { value: 'vocal' } })
expect(confirmBtn()).toBeDisabled()
fireEvent.change(input, { target: { value: 'vocalstar' } })
fireEvent.click(confirmBtn())
await waitFor(() => expect(deleteTenant).toHaveBeenCalledWith('vocalstar'))
await waitFor(() => expect(listTenants).toHaveBeenCalledTimes(2))
})
it('blocks save when the theme JSON is invalid', async () => {
@@ -134,3 +199,15 @@ describe('Admin Tenants page', () => {
expect(screen.getByRole('button', { name: /save changes/i })).toBeDisabled()
})
})
describe('Admin Tenants page — access warning edge cases', () => {
it('treats separator-only input as an open portal (matches what Save sends)', async () => {
render(<AdminTenantsPage />)
await screen.findByText('Vocal Star')
fireEvent.click(screen.getByRole('button', { name: /manage/i }))
fireEvent.change(await screen.findByLabelText(/allowed emails/i), { target: { value: ' , ' } })
fireEvent.change(screen.getByLabelText(/allowed email domains/i), { target: { value: ',' } })
expect(screen.getByText(/anyone can sign in/i)).toBeInTheDocument()
})
})
+211 -28
View File
@@ -1,7 +1,7 @@
"use client"
import { useEffect, useState, useCallback } from "react"
import { adminApi, TenantSummary, TenantCreateResult, TenantDetail } from "@/lib/api"
import { adminApi, TenantSummary, TenantCreateResult, TenantDetail, TenantDomainStatus } from "@/lib/api"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
@@ -17,6 +17,7 @@ import {
} from "@/components/ui/dialog"
import {
Building2, Plus, RefreshCw, Loader2, Copy, Check, ExternalLink, Settings2, Code2, WandSparkles,
Trash2, Globe, AlertTriangle,
} from "lucide-react"
import { useToast } from "@/hooks/use-toast"
@@ -84,11 +85,24 @@ function ThemeJsonEditor({
)
}
// --- Portal subdomain status ------------------------------------------------
function DomainBadge({ domain }: { domain?: TenantDomainStatus | null }) {
if (!domain) return <Badge variant="outline">unknown</Badge>
if (domain.state === "active") return <Badge>live</Badge>
if (domain.state === "provisioning") return <Badge variant="secondary">provisioning ({domain.pages_status || "dns"})</Badge>
return <Badge variant="destructive">not set up</Badge>
}
function splitList(text: string): string[] {
return text.split(/[\s,;]+/).map((s) => s.trim().toLowerCase()).filter(Boolean)
}
const EMPTY_FORM = {
name: "",
tenant_id: "",
subdomain: "",
allowed_email_domains: "",
allowed_emails: "",
artist_color: "",
title_color: "",
sung_lyrics_color: "",
@@ -132,9 +146,15 @@ export default function AdminTenantsPage() {
const [manageLoading, setManageLoading] = useState(false)
const [detail, setDetail] = useState<TenantDetail | null>(null)
const [mCfg, setMCfg] = useState({
name: "", subdomain: "", tagline: "", allowed_email_domains: "",
name: "", subdomain: "", tagline: "", allowed_email_domains: "", allowed_emails: "",
dropbox_path: "", brand_prefix: "", distribution_mode: "download_only", is_active: true,
})
const [domainBusy, setDomainBusy] = useState(false)
// --- Delete state -----------------------------------------------------------
const [deleteOpen, setDeleteOpen] = useState(false)
const [deleteConfirm, setDeleteConfirm] = useState("")
const [deleting, setDeleting] = useState(false)
const [styleText, setStyleText] = useState("")
const [newAssets, setNewAssets] = useState<File[]>([])
const [saving, setSaving] = useState(false)
@@ -208,7 +228,7 @@ export default function AdminTenantsPage() {
try {
const fd = new FormData()
const fields: (keyof typeof EMPTY_FORM)[] = [
"name", "tenant_id", "subdomain", "allowed_email_domains",
"name", "tenant_id", "allowed_email_domains", "allowed_emails",
"artist_color", "title_color", "sung_lyrics_color", "unsung_lyrics_color",
"tagline", "distribution_mode", "dropbox_path", "brand_prefix",
]
@@ -232,6 +252,40 @@ export default function AdminTenantsPage() {
}
}
// After create, poll the portal subdomain until Cloudflare has issued its cert.
const createdId = created?.tenant.id
const createdActive = created?.domain?.state === "active"
const [pollRound, setPollRound] = useState(0)
const [pollExhausted, setPollExhausted] = useState(false)
useEffect(() => {
// Keyed on the tenant id (+ manual "check again"), so status flapping can't
// reset the try cap. One request at a time, so a slow older response can't
// overwrite a newer status.
if (!createdId || createdActive) return
setPollExhausted(false)
let tries = 0
let inFlight = false
let stopped = false
const stop = () => { stopped = true; clearInterval(timer) }
const timer = setInterval(async () => {
if (inFlight || stopped) return
inFlight = true
tries += 1
try {
const d = await adminApi.getTenant(createdId)
if (stopped) return
setCreated((c) => (c ? { ...c, domain: d.domain } : c))
if (d.domain?.state === "active") stop()
} catch {
// keep polling until the cap
} finally {
inFlight = false
}
if (!stopped && tries >= 40) { stop(); setPollExhausted(true) }
}, 5000)
return stop
}, [createdId, pollRound]) // eslint-disable-line react-hooks/exhaustive-deps
const copyPreview = async () => {
if (!created) return
await navigator.clipboard.writeText(created.preview_url)
@@ -254,6 +308,7 @@ export default function AdminTenantsPage() {
subdomain: t.subdomain || "",
tagline: t.branding?.tagline || "",
allowed_email_domains: (t.auth?.allowed_email_domains || []).join(", "),
allowed_emails: (t.auth?.allowed_emails || []).join(", "),
dropbox_path: t.defaults?.dropbox_path || "",
brand_prefix: t.defaults?.brand_prefix || "",
distribution_mode: t.defaults?.distribution_mode || "download_only",
@@ -276,10 +331,8 @@ export default function AdminTenantsPage() {
}
setSaving(true)
try {
const domains = mCfg.allowed_email_domains.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)
const configUpdate: Record<string, any> = {
name: mCfg.name.trim(),
subdomain: mCfg.subdomain.trim(),
is_active: mCfg.is_active,
branding: { tagline: mCfg.tagline.trim() || null },
defaults: {
@@ -288,7 +341,11 @@ export default function AdminTenantsPage() {
distribution_mode: mCfg.distribution_mode,
},
features: { dropbox_upload: !!mCfg.dropbox_path.trim() },
auth: { allowed_email_domains: domains, require_email_domain: domains.length > 0 },
// Backend normalizes these and enforces the allowlist whenever either is non-empty.
auth: {
allowed_email_domains: splitList(mCfg.allowed_email_domains),
allowed_emails: splitList(mCfg.allowed_emails),
},
}
const fd = new FormData()
fd.append("config", JSON.stringify(configUpdate))
@@ -306,6 +363,52 @@ export default function AdminTenantsPage() {
}
}
const setUpDomain = async () => {
if (!manageId) return
setDomainBusy(true)
try {
const { domain } = await adminApi.provisionTenantDomain(manageId)
setDetail((d) => (d ? { ...d, domain } : d))
toast({ title: "Domain set up", description: `${domain.hostname}: ${domain.state}` })
} catch (err: any) {
toast({ title: "Domain setup failed", description: err.message || "Unknown error", variant: "destructive" })
} finally {
setDomainBusy(false)
}
}
const refreshDomain = async () => {
if (!manageId) return
setDomainBusy(true)
try {
const d = await adminApi.getTenant(manageId)
setDetail((cur) => (cur ? { ...cur, domain: d.domain } : cur))
} catch (err: any) {
toast({ title: "Couldn't refresh domain status", description: err.message || "Unknown error", variant: "destructive" })
} finally {
setDomainBusy(false)
}
}
const handleDelete = async () => {
if (!manageId || deleteConfirm !== manageId) return
setDeleting(true)
try {
await adminApi.deleteTenant(manageId)
toast({ title: "Tenant deleted", description: `${manageId} and its portal subdomain were removed.` })
setDeleteOpen(false)
setManageOpen(false)
loadTenants()
} catch (err: any) {
toast({ title: "Failed to delete tenant", description: err.message || "Unknown error", variant: "destructive" })
} finally {
setDeleting(false)
}
}
// Computed from exactly what Save submits (e.g. "," alone = no entries = open).
const accessOpen = splitList(mCfg.allowed_emails).length === 0 && splitList(mCfg.allowed_email_domains).length === 0
return (
<div className="p-6 space-y-6">
<div className="flex items-center justify-between">
@@ -351,7 +454,9 @@ export default function AdminTenantsPage() {
<TableRow key={t.id}>
<TableCell className="font-medium">{t.name}</TableCell>
<TableCell className="font-mono text-xs">{t.id}</TableCell>
<TableCell className="text-xs">{t.subdomain}</TableCell>
<TableCell className="text-xs">
<a href={`https://${t.subdomain}`} target="_blank" rel="noreferrer" className="hover:underline">{t.subdomain}</a>
</TableCell>
<TableCell className="text-xs">{t.dropbox_path || "download only"}</TableCell>
<TableCell>
<Badge variant={t.is_active ? "default" : "secondary"}>{t.is_active ? "active" : "inactive"}</Badge>
@@ -380,8 +485,8 @@ export default function AdminTenantsPage() {
<DialogHeader>
<DialogTitle>Create tenant</DialogTitle>
<DialogDescription>
Provisions a branded portal with a locked theme. Jobs are private and delivered to
Dropbox (or download only). Drive it immediately via the preview link — no DNS.
Provisions a branded portal with a locked theme at its own subdomain (DNS + certificate
are set up automatically). Jobs are private and delivered to Dropbox (or download only).
</DialogDescription>
</DialogHeader>
@@ -393,6 +498,18 @@ export default function AdminTenantsPage() {
<CardDescription>Open the preview link, switch to <strong>Bulk</strong>, and drop the album folder.</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-center gap-2 text-sm">
<Globe className="h-4 w-4 text-muted-foreground" />
<a href={created.subdomain_url} target="_blank" rel="noreferrer" className="font-mono hover:underline">{created.subdomain_url}</a>
<DomainBadge domain={created.domain} />
{created.domain?.state !== "active" && !pollExhausted && <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />}
{created.domain?.state !== "active" && pollExhausted && (
<>
<span className="text-xs text-muted-foreground">still pending — the certificate can take a few minutes</span>
<Button variant="outline" size="sm" onClick={() => setPollRound((n) => n + 1)}>Check again</Button>
</>
)}
</div>
<div className="flex items-center gap-2">
<Input readOnly value={created.preview_url} className="font-mono text-xs" />
<Button variant="outline" size="icon" onClick={copyPreview}>
@@ -422,15 +539,23 @@ export default function AdminTenantsPage() {
</div>
</div>
<div className="space-y-1">
<Label htmlFor="create-subdomain">Subdomain</Label>
<Input id="create-subdomain" value={form.subdomain} onChange={(e) => setForm((f) => ({ ...f, subdomain: e.target.value }))} placeholder="randy-vild.nomadkaraoke.com" className="font-mono text-sm" />
<p className="text-xs text-muted-foreground">Only needed for a real client portal (DNS + Cloudflare). The preview link works without it.</p>
<Label htmlFor="create-subdomain">Portal subdomain</Label>
<Input id="create-subdomain" value={form.subdomain} readOnly placeholder="randy-vild.nomadkaraoke.com" className="font-mono text-sm" />
<p className="text-xs text-muted-foreground">Derived from the tenant ID; DNS and the certificate are provisioned automatically.</p>
</div>
<div className="space-y-1">
<Label htmlFor="create-domains">Allowed email domains <span className="text-muted-foreground">(optional)</span></Label>
<Input id="create-domains" value={form.allowed_email_domains} onChange={(e) => set("allowed_email_domains", e.target.value)} placeholder="client.com, label.com" />
<p className="text-xs text-muted-foreground">Comma-separated. Blank = no restriction (you can always log in as admin).</p>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label htmlFor="create-emails">Allowed emails</Label>
<Input id="create-emails" value={form.allowed_emails} onChange={(e) => set("allowed_emails", e.target.value)} placeholder="client@gmail.com" />
</div>
<div className="space-y-1">
<Label htmlFor="create-domains">Allowed email domains</Label>
<Input id="create-domains" value={form.allowed_email_domains} onChange={(e) => set("allowed_email_domains", e.target.value)} placeholder="client.com, label.com" />
</div>
</div>
<p className="text-xs text-muted-foreground -mt-2">
Comma-separated. Who can sign in to the portal. Both blank = anyone. Nomad Karaoke admins can always sign in.
</p>
<div>
<Label className="mb-2 block">Theme colours <span className="text-muted-foreground">(blank = Nomad default)</span></Label>
@@ -523,8 +648,8 @@ export default function AdminTenantsPage() {
<Input id="manage-name" value={mCfg.name} onChange={(e) => setMCfg((c) => ({ ...c, name: e.target.value }))} />
</div>
<div className="space-y-1">
<Label htmlFor="manage-subdomain">Subdomain</Label>
<Input id="manage-subdomain" value={mCfg.subdomain} onChange={(e) => setMCfg((c) => ({ ...c, subdomain: e.target.value }))} className="font-mono text-sm" />
<Label htmlFor="manage-subdomain">Portal subdomain</Label>
<Input id="manage-subdomain" value={mCfg.subdomain} readOnly className="font-mono text-sm" />
</div>
</div>
<div className="grid grid-cols-2 gap-3">
@@ -537,15 +662,44 @@ export default function AdminTenantsPage() {
<Input id="manage-brand-prefix" value={mCfg.brand_prefix} onChange={(e) => setMCfg((c) => ({ ...c, brand_prefix: e.target.value }))} />
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label htmlFor="manage-domains">Allowed email domains</Label>
<Input id="manage-domains" value={mCfg.allowed_email_domains} onChange={(e) => setMCfg((c) => ({ ...c, allowed_email_domains: e.target.value }))} placeholder="client.com, label.com" />
<div className="flex items-center gap-2 rounded-md border p-3 text-sm">
<Globe className="h-4 w-4 text-muted-foreground" />
<a href={`https://${mCfg.subdomain}`} target="_blank" rel="noreferrer" className="font-mono hover:underline">{mCfg.subdomain}</a>
<DomainBadge domain={detail.domain} />
<div className="ml-auto flex gap-2">
<Button variant="ghost" size="sm" onClick={refreshDomain} disabled={domainBusy}>
<RefreshCw className={`h-3.5 w-3.5 ${domainBusy ? "animate-spin" : ""}`} />
</Button>
{detail.domain?.state !== "active" && (
<Button variant="outline" size="sm" onClick={setUpDomain} disabled={domainBusy}>
{detail.domain?.state === "missing" ? "Set up domain" : "Retry setup"}
</Button>
)}
</div>
<div className="space-y-1">
<Label htmlFor="manage-tagline">Tagline</Label>
<Input id="manage-tagline" value={mCfg.tagline} onChange={(e) => setMCfg((c) => ({ ...c, tagline: e.target.value }))} />
</div>
<div className="space-y-2 rounded-md border p-3">
<Label>Portal access</Label>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label htmlFor="manage-emails" className="text-xs text-muted-foreground">Allowed emails</Label>
<Input id="manage-emails" value={mCfg.allowed_emails} onChange={(e) => setMCfg((c) => ({ ...c, allowed_emails: e.target.value }))} placeholder="client@gmail.com, manager@gmail.com" />
</div>
<div className="space-y-1">
<Label htmlFor="manage-domains" className="text-xs text-muted-foreground">Allowed email domains</Label>
<Input id="manage-domains" value={mCfg.allowed_email_domains} onChange={(e) => setMCfg((c) => ({ ...c, allowed_email_domains: e.target.value }))} placeholder="client.com, label.com" />
</div>
</div>
{accessOpen ? (
<p className="flex items-center gap-1.5 text-xs text-amber-500">
<AlertTriangle className="h-3.5 w-3.5" /> Open portal: anyone can sign in. Add emails or domains to restrict it.
</p>
) : (
<p className="text-xs text-muted-foreground">Only these can sign in (plus Nomad Karaoke admins).</p>
)}
</div>
<div className="space-y-1">
<Label htmlFor="manage-tagline">Tagline</Label>
<Input id="manage-tagline" value={mCfg.tagline} onChange={(e) => setMCfg((c) => ({ ...c, tagline: e.target.value }))} />
</div>
<div className="flex items-center gap-2">
<Switch checked={mCfg.is_active} onCheckedChange={(v) => setMCfg((c) => ({ ...c, is_active: v }))} id="active-switch" />
@@ -571,9 +725,14 @@ export default function AdminTenantsPage() {
</div>
<DialogFooter className="flex items-center justify-between sm:justify-between">
<Button asChild variant="ghost">
<a href={detail.preview_url} target="_blank" rel="noreferrer">Open preview <ExternalLink className="h-4 w-4 ml-2" /></a>
</Button>
<div className="flex gap-2">
<Button asChild variant="ghost">
<a href={detail.preview_url} target="_blank" rel="noreferrer">Open preview <ExternalLink className="h-4 w-4 ml-2" /></a>
</Button>
<Button variant="ghost" className="text-destructive hover:text-destructive" onClick={() => { setDeleteConfirm(""); setDeleteOpen(true) }} disabled={saving}>
<Trash2 className="h-4 w-4 mr-2" /> Delete tenant
</Button>
</div>
<div className="flex gap-2">
<Button variant="ghost" onClick={() => setManageOpen(false)} disabled={saving}>Close</Button>
<Button onClick={handleSave} disabled={saving || !!styleError}>
@@ -585,6 +744,30 @@ export default function AdminTenantsPage() {
)}
</DialogContent>
</Dialog>
{/* Delete confirmation */}
<Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Delete {manageId}?</DialogTitle>
<DialogDescription>
Removes the portal subdomain ({mCfg.subdomain}), the tenant&apos;s theme and assets, and its
config. Existing jobs and their finished files are kept, but can&apos;t be re-rendered with
this theme afterwards.
</DialogDescription>
</DialogHeader>
<div className="space-y-1">
<Label htmlFor="delete-confirm">Type <span className="font-mono">{manageId}</span> to confirm</Label>
<Input id="delete-confirm" value={deleteConfirm} onChange={(e) => setDeleteConfirm(e.target.value)} className="font-mono" autoComplete="off" />
</div>
<DialogFooter>
<Button variant="ghost" onClick={() => setDeleteOpen(false)} disabled={deleting}>Cancel</Button>
<Button variant="destructive" onClick={handleDelete} disabled={deleting || deleteConfirm !== manageId}>
{deleting ? <><Loader2 className="h-4 w-4 mr-2 animate-spin" /> Deleting…</> : "Delete tenant"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
@@ -27,7 +27,8 @@ import {
} from '@/lib/lyrics-review/types'
import type { EditLog, EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
import type { InstrumentalSelectionType, LyricsReviewApiClient } from '@/lib/api'
import { lyricsReviewApi, warmupEncodingWorker, heartbeatEncodingWorker, getAccessToken } from '@/lib/api'
import { lyricsReviewApi, getAccessToken } from '@/lib/api'
import { useEncodingWorkerKeepAlive } from '@/lib/lyrics-review/hooks/useEncodingWorkerKeepAlive'
import { cn } from '@/lib/utils'
import ReferenceView from './ReferenceView'
import TranscriptionView from './TranscriptionView'
@@ -492,25 +493,12 @@ export default function LyricsAnalyzer({
setSessionRestoreOpen(true)
}, [sessionClient])
// Warm up encoding worker VM when lyrics review page loads.
// Only in cloud mode (jobId present) — the endpoint is review-auth scoped to
// the job, and there's no cloud encoding VM to warm in local mode.
useEffect(() => {
if (!isReadOnly && jobId) {
warmupEncodingWorker(jobId)
}
}, []) // eslint-disable-line react-hooks/exhaustive-deps
// Debounced heartbeat — keeps VM alive during active editing
const lastHeartbeat = useRef(0)
const sendHeartbeat = useCallback(() => {
if (!jobId) return
const now = Date.now()
if (now - lastHeartbeat.current > 60_000) {
lastHeartbeat.current = now
heartbeatEncodingWorker(jobId)
}
}, [jobId])
// Keep the encoding worker VM warm while reviewing: warmup on load, heartbeat
// on edits AND periodically while the tab is visible and in use, so the 5-min
// backend idle shutdown doesn't stop it under an active reviewer. Only in cloud
// mode (jobId present) — the endpoints are review-auth scoped to the job, and
// there's no cloud encoding VM to warm in local mode.
const { sendHeartbeat } = useEncodingWorkerKeepAlive(jobId, !isReadOnly)
// Heartbeat the encoding worker as the reviewer works. Crash recovery /
// restore now flows entirely through review sessions (server in cloud mode,
@@ -216,10 +216,10 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
// Allow ONE retry. Each retry creates a fresh ~15-20 min karaoke job, so we
// don't want the prod config's default of 2 — but prod smoke tests can hit
// genuinely transient infra (encoder cold-start, network blips), and with
// retries:0 a single flake hard-fails and PAGES (daily E2E + the post-deploy
// canary). One retry lets a genuine flake self-heal on a clean run while
// capping the wasted time at a single extra attempt — a passing run never
// retries, so there's no steady-state cost.
// retries:0 a single flake hard-fails and PAGES (daily E2E). One retry lets
// a genuine flake self-heal on a clean run while capping the wasted time at a
// single extra attempt — a passing run never retries, so there's no
// steady-state cost.
test.describe.configure({ retries: 1 });
// Safety-net job tracker. The in-flow cleanup (Step 12) only runs on a fully
+32
View File
@@ -2600,6 +2600,14 @@ export interface TenantSummary {
created_at?: string | null;
}
/** Cloudflare state of a tenant's {id}.nomadkaraoke.com portal subdomain. */
export interface TenantDomainStatus {
hostname: string;
state: 'active' | 'provisioning' | 'missing';
dns_ok: boolean;
pages_status?: string | null;
}
export interface TenantCreateResult {
tenant: {
id: string;
@@ -2609,6 +2617,7 @@ export interface TenantCreateResult {
};
preview_url: string;
subdomain_url: string;
domain?: TenantDomainStatus | null;
}
export interface TenantDetail {
@@ -2617,6 +2626,7 @@ export interface TenantDetail {
style_params: Record<string, any>;
assets: string[];
preview_url: string;
domain?: TenantDomainStatus | null;
}
export interface CommunityReviewItem {
@@ -2732,6 +2742,28 @@ export const adminApi = {
return handleResponse(response);
},
/**
* Delete a tenant: portal subdomain (Cloudflare), theme, and config. Jobs are kept.
*/
async deleteTenant(tenantId: string): Promise<void> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/tenants/${encodeURIComponent(tenantId)}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
if (!response.ok) await handleResponse(response);
},
/**
* (Re)provision a tenant's {id}.nomadkaraoke.com subdomain (idempotent).
*/
async provisionTenantDomain(tenantId: string): Promise<{ domain: TenantDomainStatus }> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/tenants/${encodeURIComponent(tenantId)}/domain`, {
method: 'POST',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Get the default Nomad theme's full style_params — a starting template for a new theme.
*/
@@ -0,0 +1,114 @@
import { renderHook, act } from '@testing-library/react'
import {
useEncodingWorkerKeepAlive,
REVIEW_HEARTBEAT_INTERVAL_MS,
REVIEW_ACTIVE_WINDOW_MS,
HEARTBEAT_MIN_GAP_MS,
} from '../useEncodingWorkerKeepAlive'
import { warmupEncodingWorker, heartbeatEncodingWorker } from '@/lib/api'
jest.mock('@/lib/api', () => ({
warmupEncodingWorker: jest.fn(),
heartbeatEncodingWorker: jest.fn(),
}))
const warmup = warmupEncodingWorker as jest.Mock
const heartbeat = heartbeatEncodingWorker as jest.Mock
function setVisibility(state: 'visible' | 'hidden') {
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state })
document.dispatchEvent(new Event('visibilitychange'))
}
describe('useEncodingWorkerKeepAlive', () => {
beforeEach(() => {
jest.useFakeTimers()
warmup.mockClear()
heartbeat.mockClear()
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' })
})
afterEach(() => {
jest.useRealTimers()
})
it('heartbeat interval stays well under the 5-minute backend idle timeout', () => {
expect(REVIEW_HEARTBEAT_INTERVAL_MS * 2).toBeLessThanOrEqual(5 * 60_000)
})
it('warms up once on mount', () => {
renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
expect(warmup).toHaveBeenCalledTimes(1)
expect(warmup).toHaveBeenCalledWith('job-1')
})
it('does nothing when disabled (read-only) or without a job id', () => {
renderHook(() => useEncodingWorkerKeepAlive('job-1', false))
renderHook(() => useEncodingWorkerKeepAlive(undefined, true))
act(() => {
jest.advanceTimersByTime(REVIEW_HEARTBEAT_INTERVAL_MS * 3)
})
expect(warmup).not.toHaveBeenCalled()
expect(heartbeat).not.toHaveBeenCalled()
})
it('heartbeats periodically while visible even without edits', () => {
renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
act(() => {
jest.advanceTimersByTime(REVIEW_HEARTBEAT_INTERVAL_MS * 3)
})
expect(heartbeat).toHaveBeenCalledTimes(3)
})
it('skips periodic heartbeats while the tab is hidden', () => {
renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
act(() => {
setVisibility('hidden')
jest.advanceTimersByTime(REVIEW_HEARTBEAT_INTERVAL_MS * 3)
})
expect(heartbeat).not.toHaveBeenCalled()
})
it('re-warms the worker when the tab becomes visible again', () => {
renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
expect(warmup).toHaveBeenCalledTimes(1)
act(() => {
setVisibility('hidden')
setVisibility('visible')
})
expect(warmup).toHaveBeenCalledTimes(2)
})
it('stops keeping the VM alive after the reviewer goes inactive', () => {
renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
act(() => {
jest.advanceTimersByTime(REVIEW_ACTIVE_WINDOW_MS + REVIEW_HEARTBEAT_INTERVAL_MS * 3)
})
const callsWhileIdle = heartbeat.mock.calls.length
act(() => {
jest.advanceTimersByTime(REVIEW_HEARTBEAT_INTERVAL_MS * 3)
})
expect(heartbeat.mock.calls.length).toBe(callsWhileIdle)
// Any interaction resumes the keep-alive.
act(() => {
window.dispatchEvent(new Event('pointerdown'))
jest.advanceTimersByTime(REVIEW_HEARTBEAT_INTERVAL_MS)
})
expect(heartbeat.mock.calls.length).toBe(callsWhileIdle + 1)
})
it('debounces edit-triggered heartbeats', () => {
const { result } = renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
act(() => {
result.current.sendHeartbeat()
result.current.sendHeartbeat()
})
expect(heartbeat).toHaveBeenCalledTimes(1)
act(() => {
jest.advanceTimersByTime(HEARTBEAT_MIN_GAP_MS + 1)
result.current.sendHeartbeat()
})
expect(heartbeat).toHaveBeenCalledTimes(2)
})
})
@@ -0,0 +1,85 @@
import { useCallback, useEffect, useRef } from 'react'
import { warmupEncodingWorker, heartbeatEncodingWorker } from '@/lib/api'
/**
* Keeps the encoding worker VM warm while a reviewer is on the lyrics-review page,
* so the preview video and the final render don't pay a VM cold start.
*
* The backend idle-shutdown stops the serving VM once `last_activity_at` is older
* than IDLE_TIMEOUT_MINUTES (5 min since 2026-09-26, checked every 2 min — see
* infrastructure/config.py EncodingWorkerConfig). Previously the only heartbeat
* fired on lyric *edits*, so a reviewer reading or listening without editing would
* let the VM stop. Now:
* - warmup once on mount (starts the VM if stopped),
* - heartbeat on edits (debounced to one per HEARTBEAT_MIN_GAP_MS),
* - heartbeat every REVIEW_HEARTBEAT_INTERVAL_MS while the tab is visible AND
* the reviewer interacted within REVIEW_ACTIVE_WINDOW_MS (an abandoned tab
* stops keeping the VM alive),
* - warmup again when the tab becomes visible after being hidden (the VM may
* have idled out meanwhile).
*/
// Must stay comfortably below the backend idle timeout (5 min) — asserted by
// infrastructure/test_encoding_worker_config.py::test_idle_shutdown_is_fast_but_outlives_review_heartbeat.
export const REVIEW_HEARTBEAT_INTERVAL_MS = 2 * 60_000
export const HEARTBEAT_MIN_GAP_MS = 60_000
// Keep-alive stops this long after the last interaction (≈ the old 15-min idle window).
export const REVIEW_ACTIVE_WINDOW_MS = 15 * 60_000
const INTERACTION_EVENTS = ['pointerdown', 'keydown', 'wheel', 'touchstart'] as const
export function useEncodingWorkerKeepAlive(jobId: string | null | undefined, enabled: boolean) {
const lastHeartbeat = useRef(0)
const lastInteraction = useRef(Date.now())
const active = enabled && !!jobId
const sendHeartbeat = useCallback(() => {
if (!active || !jobId) return
lastInteraction.current = Date.now()
const now = Date.now()
if (now - lastHeartbeat.current > HEARTBEAT_MIN_GAP_MS) {
lastHeartbeat.current = now
heartbeatEncodingWorker(jobId)
}
}, [active, jobId])
// Warm up once when the review page loads (cloud mode only).
useEffect(() => {
if (active && jobId) warmupEncodingWorker(jobId)
}, []) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!active || !jobId) return
const markInteraction = () => {
lastInteraction.current = Date.now()
}
INTERACTION_EVENTS.forEach((evt) => window.addEventListener(evt, markInteraction, { passive: true }))
const tick = () => {
if (document.visibilityState !== 'visible') return
if (Date.now() - lastInteraction.current > REVIEW_ACTIVE_WINDOW_MS) return
lastHeartbeat.current = Date.now()
heartbeatEncodingWorker(jobId)
}
const intervalId = setInterval(tick, REVIEW_HEARTBEAT_INTERVAL_MS)
const onVisibilityChange = () => {
if (document.visibilityState !== 'visible') return
lastInteraction.current = Date.now()
lastHeartbeat.current = Date.now()
// Starts the VM if it idled out while the tab was hidden; otherwise just
// refreshes last_activity_at.
warmupEncodingWorker(jobId)
}
document.addEventListener('visibilitychange', onVisibilityChange)
return () => {
INTERACTION_EVENTS.forEach((evt) => window.removeEventListener(evt, markInteraction))
clearInterval(intervalId)
document.removeEventListener('visibilitychange', onVisibilityChange)
}
}, [active, jobId])
return { sendHeartbeat }
}
+28 -29
View File
@@ -35,9 +35,10 @@ from config import (
NUM_GITHUB_RUNNERS,
MachineTypes,
DiskSizes,
EncodingWorkerConfig,
)
from modules import database, storage as storage_module, artifact_registry, secrets
from modules import cloud_tasks, cloud_run, monitoring, networking, runner_manager
from modules import cloud_tasks, cloud_run, monitoring, runner_manager
from modules import divebar_mirror, kn_data_sync, divebar_lookup, backup
from modules import audio_separator_service
from modules import edge_security
@@ -68,9 +69,9 @@ all_secrets = secrets.create_secrets()
queues = cloud_tasks.create_queues()
# ==================== Networking ====================
# VPC connector for Cloud Run to access internal resources (e.g., flacfetch VM)
vpc_access_api = networking.enable_vpc_access_api()
vpc_connector = networking.create_vpc_connector(vpc_access_api)
# The serverless VPC connector (cloud-run-connector) was removed 2026-09-26:
# it only existed to reach the old flacfetch GCE VM's internal IP, and flacfetch
# now runs off-GCP behind a public HTTPS URL. All backend egress is public.
# ==================== Cloud Build IAM ====================
# These bindings allow Cloud Build to access Artifact Registry and deploy as the backend SA
@@ -188,8 +189,8 @@ edge_resources = edge_security.configure_edge_security()
video_encoding_job = cloud_run.create_video_encoding_job(bucket, backend_service_account)
lyrics_transcription_job = cloud_run.create_lyrics_transcription_job(bucket, backend_service_account)
audio_separation_job = cloud_run.create_audio_separation_job(bucket, backend_service_account)
audio_download_job = cloud_run.create_audio_download_job(bucket, backend_service_account, vpc_connector)
bulk_search_job = cloud_run.create_bulk_search_job(bucket, backend_service_account, vpc_connector)
audio_download_job = cloud_run.create_audio_download_job(bucket, backend_service_account)
bulk_search_job = cloud_run.create_bulk_search_job(bucket, backend_service_account)
# ==================== Error Monitor ====================
@@ -495,7 +496,10 @@ recover_stuck_downloads_scheduler = cloudscheduler.Job(
name="recover-stuck-downloads",
description="Detect and recover jobs stuck in downloading_audio status",
region=REGION,
schedule="*/5 * * * *", # Every 5 minutes
# Every 10 min (was 5; 2026-09-26 cost cut — each tick streams the
# processing-status job docs from Firestore). Recovery sweeps only, with
# ~10-min stall thresholds, so worst-case detection moves from ~15 to ~20 min.
schedule="*/10 * * * *",
time_zone="America/Los_Angeles",
http_target=cloudscheduler.JobHttpTargetArgs(
uri="https://api.nomadkaraoke.com/api/internal/recover-stuck-jobs",
@@ -521,7 +525,10 @@ retry_pending_render_jobs_scheduler = cloudscheduler.Job(
name="retry-pending-render-jobs",
description="Auto-retry render jobs parked on GCE encoding capacity exhaustion",
region=REGION,
schedule="*/5 * * * *", # Every 5 minutes
# Every 10 min (was 5; 2026-09-26 cost cut — each tick streams the
# processing-status job docs from Firestore). Recovery sweeps only, with
# ~10-min stall thresholds, so worst-case detection moves from ~15 to ~20 min.
schedule="*/10 * * * *",
time_zone="America/Los_Angeles",
http_target=cloudscheduler.JobHttpTargetArgs(
uri="https://api.nomadkaraoke.com/api/internal/retry-pending-render-jobs",
@@ -657,11 +664,10 @@ encoding_worker_instances = encoding_worker_vm.create_encoding_worker_vms(
encoding_worker_ips, encoding_worker_sa
)
# Capacity-fallback Encoding Worker VMs — diversified across alternate zones
# AND an alternate machine family (c4d in us-central1-a/-b + n2 in -c/-f) so a
# region-wide c4d-highcpu-32 ZONE_RESOURCE_POOL_EXHAUSTED can't take out every
# lane (incident 2026-08-12). Provisioned stopped; only started by the
# application when the primary rejects a start. Cost when idle: ~$10/mo each.
# Capacity-fallback Encoding Worker VM — one ON-DEMAND VM in a different zone AND
# machine family from the c4d Spot pair, so a Spot/c4d stockout can't take out
# every lane (incident 2026-08-12). Provisioned stopped; only started by the
# application when the primary rejects a start. Cost when idle: the boot disk.
# See EncodingWorkerConfig.FALLBACKS for the fleet definition.
encoding_worker_fallback_ips = encoding_worker_vm.create_encoding_worker_fallback_ips()
encoding_worker_fallback_instances = encoding_worker_vm.create_encoding_worker_fallback_vms(
@@ -673,7 +679,7 @@ encoding_worker_firewall = encoding_worker_vm.create_encoding_worker_firewall()
# Grant backend SA permission to start encoding worker VMs
backend_compute_perms = worker_sas.grant_backend_compute_permissions(backend_service_account)
# Encoding Worker Idle Shutdown (auto-stop after 15 min idle)
# Encoding Worker Idle Shutdown (auto-stop after 5 min idle, checked every 2 min)
encoding_worker_idle_resources = encoding_worker_manager.create_idle_shutdown_resources()
# GitHub Runners (CI/CD self-hosted runners)
@@ -777,27 +783,20 @@ pulumi.export("recover_stuck_downloads_scheduler_name", recover_stuck_downloads_
pulumi.export("disposable_domains_sync_scheduler_name", disposable_domains_sync_scheduler.name)
pulumi.export("gdrive_validator_service_account", gdrive_validator_sa.email)
# VPC networking
pulumi.export("vpc_connector_name", vpc_connector.name)
pulumi.export("vpc_connector_self_link", vpc_connector.self_link)
# Encoding workers (blue-green pair)
pulumi.export("encoding_worker_a_ip", encoding_worker_ips[0].address)
pulumi.export("encoding_worker_b_ip", encoding_worker_ips[1].address)
pulumi.export("encoding_worker_a_url", encoding_worker_ips[0].address.apply(lambda ip: f"http://{ip}:8080"))
pulumi.export("encoding_worker_b_url", encoding_worker_ips[1].address.apply(lambda ip: f"http://{ip}:8080"))
# Capacity-fallback VM exports (us-central1-a, -b)
pulumi.export("encoding_worker_fallback_a_ip", encoding_worker_fallback_ips[0].address)
pulumi.export("encoding_worker_fallback_b_ip", encoding_worker_fallback_ips[1].address)
pulumi.export(
"encoding_worker_fallback_a_url",
encoding_worker_fallback_ips[0].address.apply(lambda ip: f"http://{ip}:8080"),
)
pulumi.export(
"encoding_worker_fallback_b_url",
encoding_worker_fallback_ips[1].address.apply(lambda ip: f"http://{ip}:8080"),
)
# Capacity-fallback VM exports (one per EncodingWorkerConfig.FALLBACKS entry,
# keyed by suffix, e.g. encoding_worker_fallback_c2df_ip).
for _fb, _fb_ip in zip(EncodingWorkerConfig.FALLBACKS, encoding_worker_fallback_ips):
pulumi.export(f"encoding_worker_fallback_{_fb['suffix']}_ip", _fb_ip.address)
pulumi.export(
f"encoding_worker_fallback_{_fb['suffix']}_url",
_fb_ip.address.apply(lambda ip: f"http://{ip}:8080"),
)
pulumi.export("encoding_worker_service_account", encoding_worker_sa.email)
pulumi.export("encoding_worker_a_name", encoding_worker_instances[0].name)
pulumi.export("encoding_worker_b_name", encoding_worker_instances[1].name)
+38 -13
View File
@@ -3,7 +3,9 @@ Encoding Worker VM resources — blue-green deployment pair.
Manages two identical VMs (a/b) for zero-downtime deployments.
Only one is active (primary) at a time; the other is stopped (secondary).
Both auto-shutdown when idle to minimize cost.
Both auto-shutdown when idle to minimize cost, and both run on SPOT capacity
(preempted → STOPPED, restarted on demand; lost encodes are resubmitted). One
on-demand fallback VM in a different family/zone absorbs Spot stockouts.
See docs/superpowers/specs/2026-03-24-blue-green-encoding-worker-design.md
"""
@@ -80,18 +82,42 @@ def create_encoding_worker_vms(
advanced_machine_features=compute.InstanceAdvancedMachineFeaturesArgs(
threads_per_core=2,
),
scheduling=_primary_pair_scheduling(),
)
vms.append(vm)
return vms
def _primary_pair_scheduling() -> compute.InstanceSchedulingArgs:
"""Scheduling for the a/b pair: Spot with STOP-on-preemption.
STOP (not DELETE) keeps the VM, its disk and static IP, so a preempted
worker is just a TERMINATED instance that the backend's ensure-running path
restarts like any idle-stopped worker. automatic_restart must be False and
on_host_maintenance TERMINATE for Spot.
"""
if not EncodingWorkerConfig.PRIMARY_PAIR_SPOT:
return compute.InstanceSchedulingArgs(
provisioning_model="STANDARD",
preemptible=False,
automatic_restart=True,
on_host_maintenance="MIGRATE",
)
return compute.InstanceSchedulingArgs(
provisioning_model="SPOT",
preemptible=True,
automatic_restart=False,
on_host_maintenance="TERMINATE",
instance_termination_action="STOP",
)
def create_encoding_worker_fallback_ips() -> list[compute.Address]:
"""Create static IPs for the capacity-fallback VMs.
These IPs back the fallback fleet that absorbs a primary-family stockout —
both alternate zones AND an alternate machine family (n2-highcpu-32) so a
region-wide c4d-highcpu-32 ZONE_RESOURCE_POOL_EXHAUSTED can't take out every
lane. One IP per entry in EncodingWorkerConfig.FALLBACKS (order-aligned).
These IPs back the on-demand fallback that absorbs a Spot/c4d stockout of
the primary pair (alternate zone AND machine family). One IP per entry in
EncodingWorkerConfig.FALLBACKS (order-aligned).
"""
ips = []
for fb in EncodingWorkerConfig.FALLBACKS:
@@ -115,14 +141,13 @@ def create_encoding_worker_fallback_vms(
) -> list[compute.Instance]:
"""Create capacity-fallback encoding worker VMs.
Provisioned stopped — only started by the application when the primary zone
rejects starts with ZONE_RESOURCE_POOL_EXHAUSTED. The fleet diversifies
across both alternate zones AND an alternate machine family
(n2-highcpu-32) so a region-wide c4d-highcpu-32 stockout cannot exhaust
every lane at once (incident 2026-08-12). Each entry's machine_type and
disk_type come from EncodingWorkerConfig.FALLBACKS — n2 uses pd-balanced
because it does not support hyperdisk-balanced. Cost when stopped is just
the 50 GB boot disk (~$4-5/mo each).
Provisioned stopped — only started by the application when the Spot primary
pair can't start (ZONE_RESOURCE_POOL_EXHAUSTED / Spot stockout). On-demand
(default STANDARD scheduling — never preempted), in a different machine
family and zone from the c4d pair (incident 2026-08-12). Each entry's
machine_type and disk_type come from EncodingWorkerConfig.FALLBACKS — c2d/n2
use pd-balanced because they don't support hyperdisk-balanced. Cost when
stopped is just the 50 GB boot disk.
"""
startup_script = read_script("encoding_worker.sh")
custom_image = f"projects/{PROJECT_ID}/global/images/family/encoding-worker"
+47 -61
View File
@@ -33,7 +33,7 @@ def get_project_number() -> str:
REGION = "us-central1"
ZONE = f"{REGION}-a"
# Encoding worker zone - uses us-central1-c due to c4d-highcpu-32 availability
# Encoding worker zone - uses us-central1-c due to c4d availability
# (us-central1-a and us-central1-b often lack capacity for high-end C4D instances)
ENCODING_WORKER_ZONE = f"{REGION}-c"
@@ -47,23 +47,19 @@ class MachineTypes:
GITHUB_RUNNER = "e2-standard-4" # 4 vCPU, 16GB RAM
GITHUB_BUILD_RUNNER = "e2-standard-8" # 8 vCPU, 32GB RAM - dedicated Docker build runner
GITHUB_GPU_RUNNER = "n1-standard-4" # 4 vCPU, 15GB RAM - GPU runners need N1 series
ENCODING_WORKER = "c4d-highcpu-32" # 32 vCPU, AMD EPYC 9B45 Turin - 4.92x faster than c4-standard-8
# Capacity-fallback machine family, deliberately DIFFERENT from ENCODING_WORKER.
# c4d-highcpu-32 suffered a region-wide ZONE_RESOURCE_POOL_EXHAUSTED stockout across
# us-central1-a/-b/-c simultaneously (2026-08-12) which took out every same-family lane.
# n2-highcpu-32 (Intel Cascade/Ice Lake) draws from a much deeper, independent pool, so a
# c4d shortage cannot exhaust it. n2 does NOT support hyperdisk-balanced → uses pd-balanced.
ENCODING_WORKER_ALT = "n2-highcpu-32" # 32 vCPU, Intel Cascade/Ice Lake - deep-capacity fallback pool
# Broadened ranked pool (2026-08-15) — ≥5 x86_64, 32-vCPU, ≥32 GB highcpu types
# across 4 distinct silicon lineages, so a stockout of the newest-gen cohort
# (c4d/c4, the crunch) cannot exhaust every lane. Encode-speed ranking lives in
# backend/services/encoding_worker_preference.py::SPEED_RANK. Disk-type rule:
# next-gen Titanium families (c4/c4d/n4/n4d) support hyperdisk-balanced ONLY;
# older families (c2d/n2/n2d) use pd-balanced. Getting this wrong = pulumi error.
ENCODING_WORKER_C4 = "c4-highcpu-32" # 32 vCPU / 64 GB, Intel Emerald Rapids (hyperdisk-only)
ENCODING_WORKER_N4D = "n4d-highcpu-32" # 32 vCPU / 64 GB, AMD Titanium (hyperdisk-only)
ENCODING_WORKER_C2D = "c2d-highcpu-32" # 32 vCPU / 64 GB, AMD Milan (Zen3), deep pool (pd-balanced)
ENCODING_WORKER_N2D = "n2d-highcpu-32" # 32 vCPU / 32 GB, AMD Rome/Milan, deep pool (pd-balanced)
# Encoding workers (2026-09-26 cost cut, docs/archive/2026-09-26-encoding-cost-cuts.md):
# 16 vCPU instead of 32 — an approved speed-for-cost trade (finalization x264
# only kept ~66-78% of 32 vCPUs busy; ffmpeg auto-threads adapt to 16). The
# worker serializes heavy jobs (ENCODING_HEAVY_CONCURRENCY=1), and highcpu-16
# still has ~30-32 GB RAM — enough for one 4K encode (~18 GB peak).
ENCODING_WORKER = "c4d-highcpu-16" # 16 vCPU / 30 GB, AMD EPYC Turin — Spot blue-green pair
# The ONE on-demand capacity fallback. Deliberately a DIFFERENT machine family
# and zone from the c4d Spot pair: c4d suffered a region-wide
# ZONE_RESOURCE_POOL_EXHAUSTED stockout (2026-08-12), and Spot capacity can
# vanish at any time. c2d (AMD Milan) draws from a deep, mature pool and is
# on-demand, so it is not preemptible. c2d does NOT support hyperdisk →
# pd-balanced boot disk.
ENCODING_WORKER_FALLBACK = "c2d-highcpu-16" # 16 vCPU / 32 GB, AMD Milan (Zen3), on-demand
FLACFETCH = "e2-small" # 0.5 vCPU, 2GB RAM
@@ -137,7 +133,13 @@ class RunnerManagerConfig:
FUNCTION_TIMEOUT = 300 # 5 minutes
# Scheduler cadence for the orphan-cleanup pass (reconciles ephemeral VMs
# against org-runner registrations, deletes stragglers).
IDLE_CHECK_SCHEDULE = "*/15 * * * *" # Every 15 minutes
# Also re-dispatches self-hosted jobs stuck `queued` (dropped webhook,
# VM that never registered), so the cadence bounds how long a job strands.
IDLE_CHECK_SCHEDULE = "*/5 * * * *" # Every 5 minutes
# Each webhook holds an instance for up to ~90s confirming the VM insert,
# so a CI burst needs headroom — at 5, bursts got Cloud Run 429s and GitHub
# never redelivers a dropped webhook (2026-09-27 stalled deploy).
FUNCTION_MAX_INSTANCES = 20
class SecretNames:
@@ -308,56 +310,38 @@ class EncodingWorkerConfig:
"""Configuration for blue-green encoding worker VMs."""
VM_NAMES = ["encoding-worker-a", "encoding-worker-b"]
IP_NAMES = ["encoding-worker-ip-a", "encoding-worker-ip-b"]
IDLE_CHECK_SCHEDULE = "*/5 * * * *" # Every 5 minutes
IDLE_TIMEOUT_MINUTES = 15
# Stop idle workers fast: VMs bill per second while RUNNING, and with only
# ~5-20 jobs/day most of the old 15-min tail was paid idle time. The function
# still NEVER stops a VM with active jobs (fail-safe on unconfirmed /health).
IDLE_CHECK_SCHEDULE = "*/2 * * * *" # Every 2 minutes
IDLE_TIMEOUT_MINUTES = 5
FUNCTION_NAME = "encoding-worker-idle-shutdown"
FUNCTION_MEMORY = "512M" # Increased from 256M — OOM with gRPC/Firestore/Compute client libs
FUNCTION_TIMEOUT = 120 # 2 minutes
# Capacity-resilience fallback fleet. Each VM is provisioned STOPPED in an
# alternate zone / machine family and is started on demand only when the
# primary zone rejects a start with ZONE_RESOURCE_POOL_EXHAUSTED. Cost when
# stopped is just the 50 GB boot disk (~$4-5/mo each).
# The a/b blue-green pair runs on SPOT capacity (~60-70% cheaper). A preempted
# Spot VM is STOPPED (not deleted) — the backend restarts it on the next
# request, and an encode lost to preemption is resubmitted automatically
# (encoding_service.wait_for_completion → EncodingJobLostError).
PRIMARY_PAIR_SPOT = True
# Capacity-resilience fallback. Provisioned STOPPED and started on demand only
# when the Spot pair can't start (ZONE_RESOURCE_POOL_EXHAUSTED / Spot
# stockout). ON-DEMAND (never preempted) and a different family + zone from the
# c4d pair so one shortage can't take out both lanes. Cost when stopped is just
# the 50 GB boot disk.
#
# Machine-family diversity is DELIBERATE. The primary pair and the two c4d
# fallbacks are all c4d-highcpu-32, so a region-wide c4d stockout (observed
# 2026-08-12 across us-central1-a/-b/-c at once) exhausts every lane
# simultaneously and forces slow local encoding (→ 524 on preview, parked
# renders). The n2-highcpu-32 fallbacks draw from an independent, much deeper
# pool so a c4d shortage cannot take them out. n2 does not support
# hyperdisk-balanced, hence pd-balanced boot disks on those entries.
# Was 8 fallbacks across 6 families (2026-08-15) — cut to 1 on 2026-09-26
# (fleet 10 → 3 VMs) to save the idle disk/IP spend; c2df was kept because it
# is a deep-pool, pd-balanced (cheaper disk) family in a separate zone.
#
# Each entry: name/IP suffix, zone suffix ({REGION}-{zone_suffix}),
# machine_type, boot disk_type. ORDER MATTERS — IPs and VMs are zipped by
# position. (Candidate PRIORITY is no longer positional: it is decided at
# runtime/deploy by the shared speed-rank + cooldown in
# backend/services/encoding_worker_preference.py.) Keep the existing a/b/n2c/n2f
# entries first and byte-identical so Pulumi does not recreate those VMs; the
# broadened-pool entries are APPENDED so the change is purely additive
# (verify `pulumi preview` shows only new IPs+VMs, zero replace).
#
# Zone spread: one machine type per zone where possible so a single
# (type × zone) stockout can't correlate across the pool. c4d primary lives in
# zone c (the primary pair), so the c4 fallback goes to a, n4d to b, c2d to f,
# n2d to a — 4 lineages across 4 zones.
# machine_type, boot disk_type. IPs and VMs are zipped by position. The
# runtime/deploy candidate PRIORITY is decided by the shared speed-rank +
# cooldown in backend/services/encoding_worker_preference.py.
FALLBACKS = [
{"suffix": "a", "zone_suffix": "a",
"machine_type": MachineTypes.ENCODING_WORKER, "disk_type": "hyperdisk-balanced"},
{"suffix": "b", "zone_suffix": "b",
"machine_type": MachineTypes.ENCODING_WORKER, "disk_type": "hyperdisk-balanced"},
{"suffix": "n2c", "zone_suffix": "c",
"machine_type": MachineTypes.ENCODING_WORKER_ALT, "disk_type": "pd-balanced"},
{"suffix": "n2f", "zone_suffix": "f",
"machine_type": MachineTypes.ENCODING_WORKER_ALT, "disk_type": "pd-balanced"},
# --- Broadened pool (2026-08-15), appended (additive-only) ---
{"suffix": "c4a", "zone_suffix": "a",
"machine_type": MachineTypes.ENCODING_WORKER_C4, "disk_type": "hyperdisk-balanced"},
{"suffix": "n4db", "zone_suffix": "b",
"machine_type": MachineTypes.ENCODING_WORKER_N4D, "disk_type": "hyperdisk-balanced"},
{"suffix": "c2df", "zone_suffix": "f",
"machine_type": MachineTypes.ENCODING_WORKER_C2D, "disk_type": "pd-balanced"},
{"suffix": "n2da", "zone_suffix": "a",
"machine_type": MachineTypes.ENCODING_WORKER_N2D, "disk_type": "pd-balanced"},
"machine_type": MachineTypes.ENCODING_WORKER_FALLBACK, "disk_type": "pd-balanced"},
]
# Derived name lists (kept for readability / any external reference).
@@ -380,6 +364,8 @@ class ErrorMonitorConfig:
CPU = "1"
TIMEOUT = "300s"
MAX_RETRIES = 0
MONITOR_SCHEDULE = "*/15 * * * *" # Every 15 minutes UTC
# Hourly (was every 15 min; 2026-09-26 cost cut). Must match
# backend/services/error_monitor/config.py LOOKBACK_MINUTES (60).
MONITOR_SCHEDULE = "0 * * * *"
DIGEST_SCHEDULE = "0 8 * * *" # 08:00 UTC daily
SCHEDULER_SA_NAME = "error-monitor-scheduler"
@@ -84,7 +84,8 @@ def _inventory(only_types: Optional[set]) -> List[Dict[str, Any]]:
if data.get("primary_vm"):
workers.append({
"vm": data["primary_vm"], "zone": DEFAULT_C4D_ZONE,
"ip": data.get("primary_ip"), "machine_type": "c4d-highcpu-32",
# Keep in sync with encoding_worker_preference.PRIMARY_MACHINE_TYPE.
"ip": data.get("primary_ip"), "machine_type": "c4d-highcpu-16",
})
except Exception as e: # noqa: BLE001
print(f"WARN: could not read primary from Firestore ({e}); benchmarking fallbacks only")
@@ -238,11 +239,19 @@ def benchmark(args) -> Dict[str, float]:
def _suggest_ranks(medians: Dict[str, float]) -> Dict[str, int]:
"""Map medians → SPEED_RANK ints (fastest = smallest), spaced by 10."""
"""Map medians → SPEED_RANK ints (fastest = smallest), spaced by 10.
Keyed by machine FAMILY ("c4d-highcpu-16" → "c4d"), matching
encoding_worker_preference.SPEED_RANK (family-keyed since 2026-09-26).
"""
ordered = sorted(medians.items(), key=lambda kv: kv[1])
return {mt: (idx + 1) * 10 for idx, (mt, _) in enumerate(ordered)}
def _family(machine_type: str) -> str:
return machine_type.split("-", 1)[0].lower()
def main() -> int:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--input-gcs", dest="input_gcs", required=True,
@@ -282,7 +291,10 @@ def main() -> int:
for mt, secs in sorted(medians.items(), key=lambda kv: kv[1]):
print(f" {mt:>16}: {secs:>7.1f}s → suggested SPEED_RANK {ranks[mt]}")
payload = {"medians_seconds": medians, "suggested_speed_rank": ranks}
family_ranks: Dict[str, int] = {}
for mt, rank in sorted(ranks.items(), key=lambda kv: kv[1]):
family_ranks.setdefault(_family(mt), rank) # fastest size wins per family
payload = {"medians_seconds": medians, "suggested_speed_rank": family_ranks}
if args.json_out:
with open(args.json_out, "w") as f:
json.dump(payload, f, indent=2)
@@ -6,13 +6,14 @@ delegates the *decisions* to the pure functions here so the branching — the pa
that's easy to get wrong and impossible to run locally in CI — has real unit
tests (`backend/tests/test_deploy_promote.py`).
Background: us-central1 is in a persistent c4d Spot stockout, so the c4d
primary/secondary are usually down and all traffic runs on an n2 fallback
recorded as `active_override_vm`. A naive "start the c4d secondary and swap"
deploy can't start the secondary and never refreshes the serving fallback, so
worker-side changes never reach production. These helpers make the deploy pick a
*fresh* green target (c4d secondary if it starts, else a different n2 fallback)
and then promote that validated green to serving with zero downtime.
Background: the c4d primary/secondary are Spot VMs (since 2026-09-26) and c4d
capacity in us-central1 can run out, in which case traffic runs on the on-demand
fallback recorded as `active_override_vm`. A naive "start the c4d secondary and
swap" deploy can't start the secondary and never refreshes the serving fallback,
so worker-side changes never reach production. These helpers make the deploy pick
a *fresh* green target (c4d secondary if it starts, else a fallback) and then
promote that validated green to serving with zero downtime. CI only runs this when
worker code changed (infrastructure/encoding-worker/worker_code_paths.txt).
"""
from __future__ import annotations
@@ -0,0 +1,34 @@
# Paths whose changes require a blue-green redeploy of the GCE encoding worker.
#
# CI (.github/workflows/ci.yml, "Decide encoding-worker deploy") diffs these
# paths between the version the serving worker was last validated at
# (config/encoding-worker.primary_version → git tag v<version>) and HEAD. No
# diff → the fresh-green boot + test encode + swap is skipped (it used to run on
# every push to main). The wheel/startup.sh/version.txt are STILL uploaded to
# GCS on every deploy, so any worker that cold-boots picks up the latest wheel.
#
# The worker process runs backend/services/gce_encoding/main.py and imports
# karaoke_gen (render/encode) plus a few backend modules.
# backend/tests/test_encoding_worker_code_paths.py derives that import closure
# and fails if a module the worker imports is not covered here — so adding a new
# worker import can't silently bypass the gate.
#
# One git pathspec per line; blank lines and # comments are ignored.
karaoke_gen/
backend/__init__.py
backend/services/__init__.py
backend/models/__init__.py
backend/services/gce_encoding/
backend/services/local_encoding_service.py
backend/services/local_preview_encoding_service.py
backend/services/theme_service.py
backend/services/storage_service.py
backend/services/langfuse_preloader.py
backend/services/nltk_preloader.py
backend/services/spacy_preloader.py
backend/models/theme.py
backend/utils/
backend/config.py
infrastructure/encoding-worker/
infrastructure/packer/
poetry.lock
@@ -18,8 +18,16 @@ def sync_gcs_to_staging(
) -> str:
"""Copy new/changed objects from source to staging bucket.
Uses object metadata (updated time) to detect changes since last sync.
The staging bucket stores a marker file with the last sync timestamp.
Uses each object's ``time_created`` (the creation time of its current
generation — an overwrite creates a new generation) to detect new/changed
content since the last sync. The staging bucket stores a marker file with
the last sync timestamp.
Deliberately NOT ``updated``: that is bumped by any *metadata* change,
including Autoclass storage-class transitions (enabled on the job-files
bucket 2026-09-26). Keying on it would re-copy every object each time it
cooled to Nearline — and the copy's read would pull it straight back to
Standard, defeating Autoclass.
Args:
source_bucket: Source GCS bucket name.
@@ -48,18 +56,19 @@ def sync_gcs_to_staging(
for prefix in prefixes:
blobs = src.list_blobs(prefix=prefix)
for blob in blobs:
if not blob.updated:
created = blob.time_created
if not created:
continue
if last_sync_dt and blob.updated <= last_sync_dt:
if last_sync_dt and created <= last_sync_dt:
continue
dst_path = f"{staging_prefix}{blob.name}"
src.copy_blob(blob, dst, dst_path)
copied += 1
if latest_updated_dt is None or blob.updated > latest_updated_dt:
latest_updated_dt = blob.updated
if latest_updated_dt is None or created > latest_updated_dt:
latest_updated_dt = created
if copied >= max_objects:
logger.warning(f"Hit max_objects limit ({max_objects})")
@@ -19,9 +19,19 @@ working set, not the sum of all repos.
A ``manifest.json`` alongside the bundles records exactly which repos existed at
backup time (visibility, default branch, description, size, fork/archived flags)
— essential when recreating repos and settings from scratch after a ban.
Incremental (2026-09-26, egress cost cut): the step runs weekly and only
re-bundles repos that changed since their bundle last landed in S3. A repo is
"unchanged" when S3 already holds its bundle and that S3 object was uploaded at
least ``_UPLOAD_LAG`` after the repo's GitHub ``pushed_at``. The lag covers the
clone -> S3-upload gap within one run (bounded by the function's 30-min
deadline): a push that lands after the clone but before the upload is newer
than ``LastModified - _UPLOAD_LAG`` and so is re-bundled next time. S3 itself is
the state store — no separate bookkeeping to drift or expire.
"""
import base64
import datetime
import json
import logging
import os
@@ -53,6 +63,10 @@ _MAX_PAGES = 30
_CLONE_TIMEOUT = 1200
_BUNDLE_TIMEOUT = 600
# Max gap between cloning a repo and its bundle reaching S3 in the same run
# (function deadline is 30 min; doubled for slack). See module docstring.
_UPLOAD_LAG = datetime.timedelta(hours=1)
def get_github_token(project: str, secret_id: str = "github-backup-token") -> str:
"""Fetch the GitHub backup PAT from Secret Manager. Returns "" if unset.
@@ -209,6 +223,24 @@ def _repo_entry(repo: dict) -> dict:
}
def _parse_github_time(value: str | None) -> datetime.datetime | None:
if not value:
return None
try:
return datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
def _is_unchanged(repo: dict, backed_up_at: datetime.datetime | None) -> bool:
"""True if the S3 bundle (uploaded at ``backed_up_at``) already contains the
repo's latest push. Unknown ``pushed_at`` or no S3 copy -> not unchanged."""
pushed_at = _parse_github_time(repo.get("pushed_at"))
if backed_up_at is None or pushed_at is None:
return False
return backed_up_at - _UPLOAD_LAG >= pushed_at
def export_git_repos(
staging_bucket: str,
github_token: str,
@@ -216,13 +248,15 @@ def export_git_repos(
include_forks: bool = False,
max_repo_size_kb: int = DEFAULT_MAX_REPO_SIZE_KB,
staging_prefix: str = "git-repos/",
existing_backups: dict | None = None,
full_refresh: bool = False,
) -> str:
"""Bundle every repo under ``owners`` and write to the GCS staging bucket.
Bundles land at ``{staging_prefix}{owner}/{repo}.bundle`` and a
``{staging_prefix}manifest.json`` records the full repo inventory. The
nightly S3 upload step then ships them off-site (they are small, so unlike
Firestore they upload every night, not weekly).
``{staging_prefix}manifest.json`` records the full repo inventory (including
``unchanged`` repos whose existing S3 bundle is still current). The S3
upload step then ships them off-site.
Per-repo failures are recorded in the manifest and counted in the summary
but do not abort the run (mirrors ``secrets_export`` behaviour). Only a
@@ -238,6 +272,11 @@ def export_git_repos(
recoverable from upstream).
max_repo_size_kb: Skip repos larger than this (GitHub-reported size).
staging_prefix: Prefix under the staging bucket for bundles/manifest.
existing_backups: ``{s3_key: LastModified}`` for bundles already in S3
(``s3_upload.list_s3_objects``). Repos whose bundle is present and
newer than their last push are recorded as ``unchanged`` and not
re-cloned/re-uploaded. ``None`` -> bundle everything.
full_refresh: Ignore ``existing_backups`` and re-bundle every repo.
Returns:
Summary string.
@@ -256,8 +295,15 @@ def export_git_repos(
gcs_client = gcs_storage.Client()
bucket = gcs_client.bucket(staging_bucket)
manifest: dict = {"owners": owners, "repos": []}
bundled = errors = skipped = 0
existing_backups = {} if full_refresh else (existing_backups or {})
manifest: dict = {
"owners": owners,
"repos": [],
"generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"full_refresh": full_refresh,
}
bundled = errors = skipped = unchanged = 0
for repo in repos:
owner = repo["owner"]["login"]
@@ -273,10 +319,18 @@ def export_git_repos(
manifest["repos"].append(entry)
continue
dst = f"{staging_prefix}{owner}/{name}.bundle"
backed_up_at = existing_backups.get(dst)
if _is_unchanged(repo, backed_up_at):
entry["status"] = "unchanged"
entry["backed_up_at"] = backed_up_at.isoformat()
unchanged += 1
manifest["repos"].append(entry)
continue
workdir = tempfile.mkdtemp(prefix="gitbak-")
try:
bundle_path = _bundle_repo(repo, github_token, workdir)
dst = f"{staging_prefix}{owner}/{name}.bundle"
bucket.blob(dst).upload_from_filename(bundle_path)
entry["status"] = "bundled"
entry["bundle_bytes"] = os.path.getsize(bundle_path)
@@ -305,6 +359,7 @@ def export_git_repos(
manifest["bundled"] = bundled
manifest["errors"] = errors
manifest["skipped"] = skipped
manifest["unchanged"] = unchanged
manifest["total"] = len(repos)
# Always write the manifest — even on a bad run it records what we saw.
@@ -315,14 +370,17 @@ def export_git_repos(
summary = (
f"Bundled {bundled}/{len(repos)} repos "
f"({errors} errors, {skipped} skipped) to gs://{staging_bucket}/{staging_prefix}"
f"({unchanged} unchanged, {errors} errors, {skipped} skipped) "
f"to gs://{staging_bucket}/{staging_prefix}"
)
logger.info(summary)
# Systemic failure: nothing bundled successfully yet repos errored → surface
# it as a hard error (bad token, git broken, network down). A run where every
# repo was a *benign* skip (empty/oversized) or where at least one bundled is
# not systemic, so it stays green with the counts noted in the summary.
# Systemic failure: every repo we actually tried to bundle errored (bad
# token, git broken, network down) → surface it as a hard error. Repos
# skipped as unchanged/empty/oversized don't count as successes here: in
# incremental mode almost everything is unchanged, so counting them would
# hide a total failure of the week's changed repos. A run where at least
# one bundle succeeded, or nothing needed bundling, stays green.
if bundled == 0 and errors > 0:
raise RuntimeError(summary)
+77 -23
View File
@@ -6,8 +6,10 @@ Nightly backup pipeline:
2. BigQuery export to GCS staging (weekly/monthly schedule)
3. GCS job files delta sync to staging
4. Secret Manager export (encrypted with sealed-box public key) to staging
4b. Git repos backup — bundle every repo under the configured GitHub owners to
staging (nightly; survives loss of GitHub access, e.g. an account ban)
4b. Git repos backup — bundle repos under the configured GitHub owners to
staging (weekly on Sundays, incremental: only repos pushed since their
bundle last reached S3; full re-bundle on the first Sunday of each month;
survives loss of GitHub access, e.g. an account ban)
5. Upload staging files to S3 (Firestore export held back except Sundays)
6. Discord alert
@@ -31,7 +33,7 @@ from bigquery_export import export_bigquery_tables
from gcs_sync import sync_gcs_to_staging
from git_repos_export import export_git_repos, get_github_token
from secrets_export import export_secrets
from s3_upload import upload_staging_to_s3
from s3_upload import get_s3_client, list_s3_objects, upload_staging_to_s3
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@@ -47,6 +49,34 @@ BACKUP_ENCRYPTION_PUBKEY = os.environ.get("BACKUP_ENCRYPTION_PUBKEY", "")
GIT_BACKUP_OWNERS = os.environ.get("GIT_BACKUP_OWNERS", "")
GIT_REPOS_PREFIX = "git-repos/"
def _run_git_repos_backup(full_refresh: bool) -> str:
"""Stage bundles for repos changed since their S3 copy (or all, if
``full_refresh``). Returns a summary string; raises on systemic failure."""
github_token = get_github_token(GCP_PROJECT)
if not github_token:
logger.warning("github-backup-token has no value — skipping git repo backup")
return "skipped (no token)"
existing = None
if not full_refresh:
try:
existing = list_s3_objects(get_s3_client(GCP_PROJECT), S3_BUCKET, GIT_REPOS_PREFIX)
except Exception as e: # noqa: BLE001 — can't see S3 -> safe fallback is a full bundle
logger.warning(f"Could not list existing git bundles in S3 ({e}); bundling all repos")
owners = [o.strip() for o in GIT_BACKUP_OWNERS.split(",") if o.strip()] or None
return export_git_repos(
staging_bucket=STAGING_BUCKET,
github_token=github_token,
owners=owners,
existing_backups=existing,
full_refresh=full_refresh,
)
@functions_framework.http
def backup_to_aws(request):
"""Main entry point for the backup Cloud Function."""
@@ -65,6 +95,23 @@ def backup_to_aws(request):
)
return json.dumps({"status": "drill_reminder_sent"}), 200
# Manual git-repo-only run (e.g. to verify a change or force a refresh
# without re-running the Firestore export, which collides on same-day paths):
# ?mode=git_repos incremental
# ?mode=git_repos&full=1 re-bundle everything
if request.args.get("mode") == "git_repos":
try:
summary = _run_git_repos_backup(full_refresh=request.args.get("full") == "1")
upload = upload_staging_to_s3(
staging_bucket=STAGING_BUCKET,
s3_bucket=S3_BUCKET,
include_prefixes=[GIT_REPOS_PREFIX],
)
return json.dumps({"status": "ok", "git_repos": summary, "s3_upload": upload}), 200
except Exception as e:
logger.error(f"Manual git repos backup failed: {e}")
return json.dumps({"status": "failed", "errors": [f"Git repos: {e}"]}), 500
today = datetime.date.today()
date_str = today.isoformat()
results = {}
@@ -75,6 +122,8 @@ def backup_to_aws(request):
# weekly cadence. This is the bulk of the cross-cloud egress, so weekly
# off-site keeps a 1-week off-site RPO while a 1-day local RPO is retained.
firestore_to_s3_today = today.weekday() == 6 # Sunday
git_repos_today = today.weekday() == 6 # Sunday
git_full_refresh_today = git_repos_today and today.day <= 7 # first Sunday of the month
logger.info(f"Starting backup for {date_str} (firestore->S3: {firestore_to_s3_today})")
@@ -140,33 +189,38 @@ def backup_to_aws(request):
logger.error(f"Secrets export failed: {e}")
errors.append(f"Secrets: {e}")
# Step 4b: Git repos backup (nightly). Bundle every repo under the
# configured GitHub owners so code + full history survives loss of GitHub
# access (e.g. an account ban). Bundles are small, so they ship to S3 every
# night (not held back like Firestore). Cleanly skipped if no token is set.
try:
github_token = get_github_token(GCP_PROJECT)
if github_token:
owners = [o.strip() for o in GIT_BACKUP_OWNERS.split(",") if o.strip()] or None
results["git_repos"] = export_git_repos(
staging_bucket=STAGING_BUCKET,
github_token=github_token,
owners=owners,
)
else:
logger.warning("github-backup-token has no value — skipping git repo backup")
results["git_repos"] = "skipped (no token)"
except Exception as e:
logger.error(f"Git repos backup failed: {e}")
errors.append(f"Git repos: {e}")
# Step 4b: Git repos backup (weekly, Sundays). Bundles repos so code + full
# history survives loss of GitHub access (e.g. an account ban). Incremental:
# only repos pushed since their bundle last landed in S3 are re-cloned and
# re-uploaded (cross-cloud egress was a nightly full re-upload of ~120
# bundles). The first Sunday of each month re-bundles everything as a
# belt-and-braces refresh. Cleanly skipped if no token is set.
if git_repos_today:
try:
results["git_repos"] = _run_git_repos_backup(full_refresh=git_full_refresh_today)
except Exception as e:
logger.error(f"Git repos backup failed: {e}")
errors.append(f"Git repos: {e}")
else:
results["git_repos"] = "skipped (weekly, runs Sundays)"
# Step 5: Upload to S3. On non-Sundays, hold the Firestore export back
# (it stays in GCS staging as a daily local backup); it ships to S3 weekly.
# git-repos/ uploads only in the same invocation as the git step: the
# incremental check trusts that a bundle's S3 LastModified is within
# _UPLOAD_LAG of its clone. A bundle left in staging by a failed upload
# must not ship on a later night (a push in between would then look backed
# up); next Sunday's git step re-bundles it fresh instead.
exclude = []
if not firestore_to_s3_today:
exclude.append("firestore/")
if not git_repos_today:
exclude.append(GIT_REPOS_PREFIX)
try:
results["s3_upload"] = upload_staging_to_s3(
staging_bucket=STAGING_BUCKET,
s3_bucket=S3_BUCKET,
exclude_prefixes=[] if firestore_to_s3_today else ["firestore/"],
exclude_prefixes=exclude,
)
except Exception as e:
logger.error(f"S3 upload failed: {e}")
@@ -6,7 +6,6 @@ from concurrent.futures import ThreadPoolExecutor
import boto3
from boto3.s3.transfer import TransferConfig
from botocore.exceptions import ClientError
from google.cloud import storage, secretmanager
logger = logging.getLogger(__name__)
@@ -92,27 +91,65 @@ def _dedupe_final_duplicates(blobs: list) -> tuple[list, int]:
return kept, dup_count
def _s3_object_matches(s3_client, s3_bucket: str, key: str, size) -> bool:
# Prefixes that are always overwritten in S3 (no "already present" skip). The
# git-repo step only stages bundles whose repo actually changed, plus the
# manifest, so everything staged under git-repos/ is new content — and a
# changed bundle can coincidentally keep the same byte size, which the
# size-based skip would wrongly treat as "already backed up".
_ALWAYS_OVERWRITE_PREFIXES = ("git-repos/",)
def _dir_prefix(key: str) -> str:
return key.rsplit("/", 1)[0] + "/" if "/" in key else ""
def _list_s3_sizes(s3_client, s3_bucket: str, keys) -> dict:
"""Map ``key -> size`` for the S3 objects that share a directory with any of
``keys``.
Uses ListObjectsV2 (one delimited listing per distinct directory) rather than
a HEAD per object: the ``backup-writer`` IAM user has ``s3:ListBucket`` +
``s3:PutObject`` but NOT ``s3:GetObject``, so S3 answers HEAD on an
*existing* key with 403 — which made every overwrite (git bundles, manifest,
re-written job files) fail from 2026-09-14 (#997) until 2026-09-26. Listing
is also far fewer requests than one HEAD per file.
"""
sizes: dict = {}
paginator = s3_client.get_paginator("list_objects_v2")
for prefix in sorted({_dir_prefix(k) for k in keys}):
for page in paginator.paginate(Bucket=s3_bucket, Prefix=prefix, Delimiter="/"):
for obj in page.get("Contents", []):
sizes[obj["Key"]] = obj["Size"]
return sizes
def list_s3_objects(s3_client, s3_bucket: str, prefix: str) -> dict:
"""Map ``key -> LastModified`` (tz-aware datetime) for every S3 object under
``prefix`` (recursive). Used by the git-repo step to find which bundles are
already off-site and when they were uploaded."""
found: dict = {}
paginator = s3_client.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket=s3_bucket, Prefix=prefix):
for obj in page.get("Contents", []):
found[obj["Key"]] = obj["LastModified"]
return found
def _already_in_s3(existing_sizes: dict, key: str, size) -> bool:
"""True if S3 already holds ``key`` with the same byte size. Lets the nightly
skip anything already backed up — making it genuinely incremental and
self-healing (a file left in staging by a prior timeout/error is not
re-transferred once it lands in S3)."""
if size is None:
if size is None or key.startswith(_ALWAYS_OVERWRITE_PREFIXES):
return False
try:
head = s3_client.head_object(Bucket=s3_bucket, Key=key)
except ClientError as e:
if e.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):
return False
raise
return head.get("ContentLength") == size
return existing_sizes.get(key) == size
def _transfer_blob(blob, s3_client, s3_bucket: str) -> str:
def _transfer_blob(blob, s3_client, s3_bucket: str, existing_sizes: dict) -> str:
"""Idempotently move one staging blob to S3, deleting it from staging on
success. Returns 'uploaded', 'skipped_exists', or 'error'."""
try:
if _s3_object_matches(s3_client, s3_bucket, blob.name, blob.size):
if _already_in_s3(existing_sizes, blob.name, blob.size):
blob.delete()
return "skipped_exists"
with blob.open("rb") as gcs_file:
@@ -129,6 +166,17 @@ def _transfer_blob(blob, s3_client, s3_bucket: str) -> str:
return "error"
def get_s3_client(project: str = "nomadkaraoke"):
"""boto3 S3 client authenticated as the backup-writer IAM user."""
aws_creds = get_aws_credentials(project)
return boto3.client(
"s3",
aws_access_key_id=aws_creds["access_key_id"],
aws_secret_access_key=aws_creds["secret_access_key"],
region_name=aws_creds.get("region", "us-east-1"),
)
def get_aws_credentials(project: str) -> dict:
"""Retrieve AWS credentials from GCP Secret Manager."""
client = secretmanager.SecretManagerServiceClient()
@@ -142,6 +190,7 @@ def upload_staging_to_s3(
s3_bucket: str,
project: str = "nomadkaraoke",
exclude_prefixes: list | None = None,
include_prefixes: list | None = None,
) -> str:
"""Upload staging-bucket objects to S3, incrementally and in parallel.
@@ -150,14 +199,16 @@ def upload_staging_to_s3(
on non-weekly days — it stays in GCS staging as a daily local restore point
and is uploaded only on the weekly run). Excluded objects are left in staging
(not deleted), so they remain a local backup until the GCS lifecycle policy
or the next weekly upload removes them.
or the next weekly upload removes them. ``include_prefixes`` (optional)
restricts the run to objects under those prefixes (used by the manual
``?mode=git_repos`` trigger).
Efficiency:
* **Deduped** — byte-identical duplicate finals are dropped so the largest
data is stored/transferred once (see ``_dedupe_final_duplicates``).
* **Incremental** — objects already in S3 (same key + size) are skipped, so
only genuinely new/changed bytes cross the wire and a prior partial run
self-heals (see ``_s3_object_matches``).
* **Incremental** — objects already in S3 (same key + size, found via
ListObjectsV2) are skipped, so only genuinely new/changed bytes cross
the wire and a prior partial run self-heals (see ``_already_in_s3``).
* **Parallel** — transfers fan out across a thread pool instead of a single
serialized stream.
@@ -166,13 +217,7 @@ def upload_staging_to_s3(
timeout can only cost the replaceable finals.
"""
exclude_prefixes = exclude_prefixes or []
aws_creds = get_aws_credentials(project)
s3_client = boto3.client(
"s3",
aws_access_key_id=aws_creds["access_key_id"],
aws_secret_access_key=aws_creds["secret_access_key"],
region_name=aws_creds.get("region", "us-east-1"),
)
s3_client = get_s3_client(project)
gcs_client = storage.Client()
bucket = gcs_client.bucket(staging_bucket)
@@ -182,6 +227,7 @@ def upload_staging_to_s3(
for blob in bucket.list_blobs()
if not (blob.name.startswith(".") or "/.last_sync" in blob.name)
and not any(blob.name.startswith(p) for p in exclude_prefixes)
and (include_prefixes is None or any(blob.name.startswith(p) for p in include_prefixes))
]
candidates, dup_count = _dedupe_final_duplicates(candidates)
@@ -192,6 +238,12 @@ def upload_staging_to_s3(
critical = [b for b in candidates if not _is_large_last(b.name)]
bulk = [b for b in candidates if _is_large_last(b.name)]
try:
existing_sizes = _list_s3_sizes(s3_client, s3_bucket, [b.name for b in candidates])
except Exception as e: # noqa: BLE001 — degrade to "upload everything", don't abort
logger.warning(f"Could not list existing S3 objects ({e}); uploading all candidates")
existing_sizes = {}
counts = {"uploaded": 0, "skipped_exists": 0, "error": 0}
def run_phase(phase_blobs):
@@ -199,7 +251,7 @@ def upload_staging_to_s3(
return
with ThreadPoolExecutor(max_workers=_MAX_UPLOAD_WORKERS) as pool:
for result in pool.map(
lambda b: _transfer_blob(b, s3_client, s3_bucket), phase_blobs
lambda b: _transfer_blob(b, s3_client, s3_bucket, existing_sizes), phase_blobs
):
counts[result] += 1
@@ -0,0 +1,49 @@
"""Tests for gcs_sync change detection."""
import datetime
from unittest.mock import MagicMock, patch
from gcs_sync import sync_gcs_to_staging
UTC = datetime.timezone.utc
LAST_SYNC = datetime.datetime(2026, 9, 20, tzinfo=UTC)
def _blob(name, created, updated):
b = MagicMock()
b.name = name
b.time_created = created
b.updated = updated
return b
def _run(blobs):
client = MagicMock()
src, dst = MagicMock(), MagicMock()
client.bucket.side_effect = lambda n: src if n == "src" else dst
marker = MagicMock()
marker.exists.return_value = True
marker.download_as_text.return_value = LAST_SYNC.isoformat()
dst.blob.return_value = marker
src.list_blobs.return_value = blobs
with patch("gcs_sync.storage.Client", return_value=client):
summary = sync_gcs_to_staging("src", "dst", "gcs/job-files/", sync_prefixes=["jobs/"])
return summary, src, marker
def test_metadata_only_change_is_not_recopied():
"""An Autoclass storage-class transition bumps `updated` but not
`time_created`; it must not be treated as new content."""
cooled = _blob("jobs/a/old.mp4", LAST_SYNC - datetime.timedelta(days=40), LAST_SYNC + datetime.timedelta(days=1))
summary, src, marker = _run([cooled])
src.copy_blob.assert_not_called()
assert summary == "Synced 0 objects"
def test_new_generation_is_copied_and_marker_advances():
created = LAST_SYNC + datetime.timedelta(hours=3)
new = _blob("jobs/b/final.mp4", created, created)
summary, src, marker = _run([new])
src.copy_blob.assert_called_once()
marker.upload_from_string.assert_called_with(created.isoformat())
assert summary == "Synced 1 objects"
@@ -1,5 +1,6 @@
"""Tests for git_repos_export module."""
import datetime
import json
import subprocess
from unittest.mock import MagicMock, patch
@@ -59,7 +60,13 @@ def _fake_gcs():
return client, uploads
def _run(pages, subprocess_side_effect=None, max_repo_size_kb=git_repos_export.DEFAULT_MAX_REPO_SIZE_KB):
def _run(
pages,
subprocess_side_effect=None,
max_repo_size_kb=git_repos_export.DEFAULT_MAX_REPO_SIZE_KB,
existing_backups=None,
full_refresh=False,
):
client, uploads = _fake_gcs()
run_mock = MagicMock()
if subprocess_side_effect is not None:
@@ -76,6 +83,8 @@ def _run(pages, subprocess_side_effect=None, max_repo_size_kb=git_repos_export.D
github_token="ghp_test",
owners=["nomadkaraoke", "beveradb"],
max_repo_size_kb=max_repo_size_kb,
existing_backups=existing_backups,
full_refresh=full_refresh,
)
return summary, uploads, run_mock
@@ -280,3 +289,103 @@ def test_get_github_token_missing_returns_empty_string():
client.access_secret_version.side_effect = Exception("NOT_FOUND: no versions")
with patch("git_repos_export.secretmanager.SecretManagerServiceClient", return_value=client):
assert get_github_token("nomadkaraoke") == ""
# ---------------------------------------------------------------------------
# Incremental (only re-bundle repos pushed since their bundle reached S3)
# ---------------------------------------------------------------------------
def _utc(s):
return datetime.datetime.fromisoformat(s).replace(tzinfo=datetime.timezone.utc)
def _cloned(run_mock):
return [c.args[0][-2] for c in run_mock.call_args_list if c.args[0][:2] == ["git", "clone"]]
def test_unchanged_repo_is_not_recloned_or_restaged():
pages = [[
_make_repo("nomadkaraoke", "quiet", pushed_at="2026-09-01T00:00:00Z"),
_make_repo("nomadkaraoke", "busy", pushed_at="2026-09-20T00:00:00Z"),
]]
existing = {
"git-repos/nomadkaraoke/quiet.bundle": _utc("2026-09-13T05:00:00"),
"git-repos/nomadkaraoke/busy.bundle": _utc("2026-09-13T05:00:00"),
}
summary, uploads, run_mock = _run(pages, existing_backups=existing)
assert _cloned(run_mock) == ["https://github.com/nomadkaraoke/busy.git"]
assert "git-repos/nomadkaraoke/quiet.bundle" not in uploads
assert "git-repos/nomadkaraoke/busy.bundle" in uploads
manifest = _manifest(uploads)
statuses = {r["full_name"]: r["status"] for r in manifest["repos"]}
assert statuses == {"nomadkaraoke/quiet": "unchanged", "nomadkaraoke/busy": "bundled"}
assert manifest["unchanged"] == 1 and manifest["bundled"] == 1
assert "1 unchanged" in summary
def test_repo_missing_from_s3_is_bundled():
pages = [[_make_repo("nomadkaraoke", "new", pushed_at="2026-01-01T00:00:00Z")]]
_, uploads, _ = _run(pages, existing_backups={})
assert "git-repos/nomadkaraoke/new.bundle" in uploads
def test_push_just_before_upload_is_rebundled():
# Push landed 10 min before the bundle hit S3 — it may have been after the
# clone, so it must NOT be treated as backed up.
pages = [[_make_repo("nomadkaraoke", "racy", pushed_at="2026-09-13T04:50:00Z")]]
existing = {"git-repos/nomadkaraoke/racy.bundle": _utc("2026-09-13T05:00:00")}
_, uploads, _ = _run(pages, existing_backups=existing)
assert "git-repos/nomadkaraoke/racy.bundle" in uploads
def test_missing_pushed_at_is_bundled():
pages = [[_make_repo("nomadkaraoke", "odd", pushed_at=None)]]
existing = {"git-repos/nomadkaraoke/odd.bundle": _utc("2026-09-13T05:00:00")}
_, uploads, _ = _run(pages, existing_backups=existing)
assert "git-repos/nomadkaraoke/odd.bundle" in uploads
def test_full_refresh_ignores_existing_backups():
pages = [[_make_repo("nomadkaraoke", "quiet", pushed_at="2026-09-01T00:00:00Z")]]
existing = {"git-repos/nomadkaraoke/quiet.bundle": _utc("2026-09-13T05:00:00")}
_, uploads, _ = _run(pages, existing_backups=existing, full_refresh=True)
assert "git-repos/nomadkaraoke/quiet.bundle" in uploads
assert _manifest(uploads)["full_refresh"] is True
def test_changed_repos_all_failing_is_systemic_even_with_unchanged():
# In incremental mode nearly every repo is "unchanged"; if every repo that
# actually needed bundling failed, that must still surface as a failure.
def side_effect(cmd, **kw):
raise subprocess.CalledProcessError(128, cmd, output=b"", stderr=b"fatal: not found")
pages = [[
_make_repo("nomadkaraoke", "quiet", pushed_at="2026-09-01T00:00:00Z"),
_make_repo("nomadkaraoke", "broken", pushed_at="2026-09-20T00:00:00Z"),
]]
existing = {"git-repos/nomadkaraoke/quiet.bundle": _utc("2026-09-13T05:00:00")}
client, uploads = _fake_gcs()
with patch("git_repos_export.requests.get", side_effect=_fake_requests_get(pages)), \
patch("git_repos_export.gcs_storage.Client", return_value=client), \
patch("git_repos_export.shutil.which", return_value="/usr/bin/git"), \
patch("git_repos_export.subprocess.run", side_effect=side_effect), \
patch("git_repos_export.tempfile.mkdtemp", return_value="/tmp/gitbak-x"), \
patch("git_repos_export.shutil.rmtree"):
with pytest.raises(RuntimeError, match="1 unchanged, 1 errors"):
export_git_repos(
staging_bucket="staging",
github_token="ghp_test",
owners=["nomadkaraoke"],
existing_backups=existing,
)
manifest = _manifest(uploads)
assert manifest["errors"] == 1 and manifest["unchanged"] == 1
def test_all_unchanged_is_green():
pages = [[_make_repo("nomadkaraoke", "quiet", pushed_at="2026-09-01T00:00:00Z")]]
existing = {"git-repos/nomadkaraoke/quiet.bundle": _utc("2026-09-13T05:00:00")}
summary, uploads, run_mock = _run(pages, existing_backups=existing)
run_mock.assert_not_called()
assert "Bundled 0/1 repos (1 unchanged" in summary
@@ -0,0 +1,60 @@
"""Tests for main.backup_to_aws cadence gating (weekly git step, S3 excludes)."""
import datetime
from unittest.mock import MagicMock, patch
import main
class _FakeDate(datetime.date):
today_value = datetime.date(2026, 9, 28) # a Monday
@classmethod
def today(cls):
return cls.today_value
def _run(today):
_FakeDate.today_value = today
request = MagicMock()
request.args = {}
with patch("main.datetime.date", _FakeDate), \
patch("main.export_firestore", return_value="fs"), \
patch("main.export_bigquery_tables", return_value={}), \
patch("main.sync_gcs_to_staging", return_value="gcs"), \
patch("main.export_secrets", return_value="sec"), \
patch("main._run_git_repos_backup", return_value="git") as git, \
patch("main.upload_staging_to_s3", return_value="s3") as upload, \
patch("main.send_alert"):
main.backup_to_aws(request)
return git, upload
def test_weekday_skips_git_and_holds_back_firestore_and_git_repos():
git, upload = _run(datetime.date(2026, 9, 29)) # Tuesday
git.assert_not_called()
assert set(upload.call_args.kwargs["exclude_prefixes"]) == {"firestore/", "git-repos/"}
def test_sunday_runs_incremental_git_and_uploads_everything():
git, upload = _run(datetime.date(2026, 9, 27)) # Sunday, day 27
git.assert_called_once_with(full_refresh=False)
assert upload.call_args.kwargs["exclude_prefixes"] == []
def test_first_sunday_of_month_is_full_refresh():
git, _ = _run(datetime.date(2026, 10, 4)) # first Sunday of October
git.assert_called_once_with(full_refresh=True)
def test_manual_git_mode_only_uploads_git_prefix():
request = MagicMock()
request.args = {"mode": "git_repos", "full": "1"}
with patch("main._run_git_repos_backup", return_value="git") as git, \
patch("main.upload_staging_to_s3", return_value="s3") as upload, \
patch("main.export_firestore") as fs:
body, status = main.backup_to_aws(request)
assert status == 200
git.assert_called_once_with(full_refresh=True)
assert upload.call_args.kwargs["include_prefixes"] == ["git-repos/"]
fs.assert_not_called()
@@ -3,9 +3,22 @@
import unittest
from unittest.mock import MagicMock, patch
from botocore.exceptions import ClientError
_NOT_FOUND = ClientError({"Error": {"Code": "404"}}, "HeadObject")
def _set_s3_listing(client, objects):
"""Make the S3 client's list_objects_v2 paginator serve ``objects``
({key: size}), filtered by Prefix + Delimiter like real S3."""
def paginate(Bucket, Prefix="", Delimiter=None):
contents = []
for key, size in objects.items():
if not key.startswith(Prefix):
continue
if Delimiter and Delimiter in key[len(Prefix):]:
continue
contents.append({"Key": key, "Size": size})
return [{"Contents": contents}]
client.get_paginator.return_value.paginate.side_effect = paginate
def _blob(name, size=1234, crc32c=None):
@@ -20,9 +33,9 @@ def _blob(name, size=1234, crc32c=None):
def _mock_boto(mock_boto):
"""Default: nothing exists in S3 yet (HEAD -> 404), so everything uploads."""
"""Default: nothing exists in S3 yet, so everything uploads."""
client = mock_boto.return_value
client.head_object.side_effect = _NOT_FOUND
_set_s3_listing(client, {})
return client
@@ -106,12 +119,7 @@ class TestUploadStagingToS3(unittest.TestCase):
present = _blob("gcs/job-files/jobs/abc/finals/portrait_1080x1920.mp4", size=999)
fresh = _blob("secrets/2026-09-15.bin", size=42)
def head(Bucket, Key):
if Key == present.name:
return {"ContentLength": 999}
raise _NOT_FOUND
client.head_object.side_effect = head
_set_s3_listing(client, {present.name: 999})
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [present, fresh]
upload_staging_to_s3("staging", "s3b")
@@ -166,5 +174,79 @@ class TestUploadStagingToS3(unittest.TestCase):
self.assertEqual(bulk_phase, [final.name])
@patch("s3_upload.boto3.client")
@patch("s3_upload.storage.Client")
@patch("s3_upload.get_aws_credentials")
def test_never_uses_head_object(self, mock_creds, mock_storage, mock_boto):
"""Regression (2026-09-14..26 outage): the backup-writer IAM user lacks
s3:GetObject, so HEAD on an existing key returns 403. Existence must come from listing."""
from s3_upload import upload_staging_to_s3
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
client = _mock_boto(mock_boto)
client.head_object.side_effect = AssertionError("HEAD must not be called")
blob = _blob("secrets/2026-09-27.bin")
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [blob]
summary = upload_staging_to_s3("staging", "s3b")
self.assertEqual(client.upload_fileobj.call_count, 1)
self.assertNotIn("errors", summary)
@patch("s3_upload.boto3.client")
@patch("s3_upload.storage.Client")
@patch("s3_upload.get_aws_credentials")
def test_git_repos_always_overwritten_even_if_same_size(self, mock_creds, mock_storage, mock_boto):
"""A changed bundle can keep its byte size; git-repos/ is only staged
when it changed, so it must upload regardless of the size match."""
from s3_upload import upload_staging_to_s3
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
client = mock_boto.return_value
bundle = _blob("git-repos/nomadkaraoke/karaoke-gen.bundle", size=500)
manifest = _blob("git-repos/manifest.json", size=77)
_set_s3_listing(client, {bundle.name: 500, manifest.name: 77})
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [bundle, manifest]
upload_staging_to_s3("staging", "s3b")
uploaded = {c.kwargs["Key"] for c in client.upload_fileobj.call_args_list}
self.assertEqual(uploaded, {bundle.name, manifest.name})
@patch("s3_upload.boto3.client")
@patch("s3_upload.storage.Client")
@patch("s3_upload.get_aws_credentials")
def test_include_prefixes_limits_upload(self, mock_creds, mock_storage, mock_boto):
from s3_upload import upload_staging_to_s3
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
client = _mock_boto(mock_boto)
git = _blob("git-repos/manifest.json")
sec = _blob("secrets/2026-09-27.bin")
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [git, sec]
upload_staging_to_s3("staging", "s3b", include_prefixes=["git-repos/"])
self.assertEqual(client.upload_fileobj.call_count, 1)
self.assertEqual(client.upload_fileobj.call_args.kwargs["Key"], git.name)
sec.delete.assert_not_called()
class TestListS3Objects(unittest.TestCase):
def test_returns_key_to_last_modified(self):
from s3_upload import list_s3_objects
client = MagicMock()
client.get_paginator.return_value.paginate.return_value = [
{"Contents": [{"Key": "git-repos/a/b.bundle", "LastModified": "t1"}]},
{"Contents": [{"Key": "git-repos/a/c.bundle", "LastModified": "t2"}]},
{},
]
self.assertEqual(
list_s3_objects(client, "s3b", "git-repos/"),
{"git-repos/a/b.bundle": "t1", "git-repos/a/c.bundle": "t2"},
)
if __name__ == "__main__":
unittest.main()
@@ -1,7 +1,7 @@
"""
Encoding Worker Idle Shutdown Cloud Function.
Triggered by Cloud Scheduler every 5 minutes. Checks all encoding worker
Triggered by Cloud Scheduler every 2 minutes. Checks all encoding worker
VMs (primary, secondary, AND multi-zone fallbacks) and stops any that
are idle. Without checking the fallbacks, a fallback VM started during a
capacity event could be left running indefinitely after the event clears
@@ -11,7 +11,7 @@ iterated primary/secondary in the default zone.
Idle criteria (all must be true to stop a VM):
- No active encoding jobs (from /health endpoint active_jobs)
- No recent user activity (from Firestore last_activity_at > 15 min)
- No recent user activity (from Firestore last_activity_at > IDLE_TIMEOUT_MINUTES)
- Only applies to the *currently routed* VM: `active_override_vm` if
set, else primary. Secondary and non-active fallbacks always stop on
idle so they don't leak after a capacity event.
@@ -20,7 +20,8 @@ Idle criteria (all must be true to stop a VM):
Environment variables:
- GCP_PROJECT: GCP project ID (default: nomadkaraoke)
- GCP_ZONE: Default zone for primary/secondary (default: us-central1-c)
- IDLE_TIMEOUT_MINUTES: Minutes of inactivity before shutdown (default: 15)
- IDLE_TIMEOUT_MINUTES: Minutes of inactivity before shutdown (default: 5;
Pulumi sets it from EncodingWorkerConfig.IDLE_TIMEOUT_MINUTES)
- ENCODING_WORKER_FALLBACK_VMS: JSON list of {vm, zone, ip} for fallback
VMs in alternate zones. Same secret the backend uses for multi-zone
failover. Empty/missing → no fallbacks checked.
@@ -40,7 +41,7 @@ logger = logging.getLogger(__name__)
PROJECT_ID = os.environ.get("GCP_PROJECT", "nomadkaraoke")
ZONE = os.environ.get("GCP_ZONE", "us-central1-c")
IDLE_TIMEOUT_MINUTES = int(os.environ.get("IDLE_TIMEOUT_MINUTES", "15"))
IDLE_TIMEOUT_MINUTES = int(os.environ.get("IDLE_TIMEOUT_MINUTES", "5"))
DEPLOY_STALE_TIMEOUT_MINUTES = 20
ENCODING_WORKER_PORT = 8080
@@ -218,7 +219,7 @@ def idle_shutdown(request):
# Fail SAFE: never stop a VM unless /health gives us a *confirmed*
# active_jobs == 0. If we can't reach the VM or confirm its job count,
# keep it alive this cycle (the function reruns every 5 min, so a
# keep it alive this cycle (the function reruns every 2 min, so a
# genuinely idle VM is reclaimed once /health responds). This prevents
# stopping a VM mid-render — the cause of "lost contact with worker"
# (incident 2026-06-15).
@@ -107,7 +107,7 @@ class TestIdleShutdown:
def test_skips_deploy_in_progress(self, mock_compute, mock_firestore):
"""Should skip idle check when a deploy is in progress."""
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
recent = (datetime.now(timezone.utc) - timedelta(minutes=2)).isoformat()
config = _make_config(
deploy_in_progress=True,
deploy_in_progress_since=recent,
@@ -147,7 +147,7 @@ class TestIdleShutdown:
def test_recent_activity_keeps_primary_alive(self, mock_compute, mock_firestore):
"""Recent activity should keep the primary VM alive but stop the secondary."""
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
recent = (datetime.now(timezone.utc) - timedelta(minutes=2)).isoformat()
config = _make_config(last_activity_at=recent)
_setup_firestore(mock_firestore, config)
@@ -163,6 +163,33 @@ class TestIdleShutdown:
# Only secondary should be stopped
assert mock_compute.stop.call_count == 1
def test_default_idle_timeout_is_five_minutes(self):
"""2026-09-26 cost cut: idle VMs stop after 5 min (was 15)."""
assert main.IDLE_TIMEOUT_MINUTES == 5
def test_review_heartbeat_within_timeout_keeps_primary_alive(self, mock_compute, mock_firestore):
"""The lyrics-review page heartbeats every ~2 min; a heartbeat 4 min ago is
still inside the 5-min window, so the warm primary must NOT be stopped
while someone is reviewing (it's kept warm for the preview + final render)."""
heartbeat = (datetime.now(timezone.utc) - timedelta(minutes=4)).isoformat()
_setup_firestore(mock_firestore, _make_config(last_activity_at=heartbeat))
mock_compute.get.return_value = _make_instance(status="RUNNING", ip="1.2.3.4")
with patch("main.check_active_jobs", return_value=0):
response, _ = main.idle_shutdown(MagicMock())
assert json.loads(response)["results"]["encoding-worker-a"] == "active_session"
def test_activity_older_than_timeout_stops_idle_primary(self, mock_compute, mock_firestore):
stale = (datetime.now(timezone.utc) - timedelta(minutes=6)).isoformat()
_setup_firestore(mock_firestore, _make_config(last_activity_at=stale))
mock_compute.get.return_value = _make_instance(status="RUNNING", ip="1.2.3.4")
with patch("main.check_active_jobs", return_value=0):
response, _ = main.idle_shutdown(MagicMock())
assert json.loads(response)["results"]["encoding-worker-a"] == "stopped"
def test_skips_terminated_vms(self, mock_compute, mock_firestore):
"""VMs that are already TERMINATED should be skipped."""
config = _make_config()
@@ -299,7 +326,7 @@ class TestFallbackVms:
def test_idle_fallback_gets_stopped(self, mock_compute, mock_firestore, fallback_env):
"""A fallback VM that's RUNNING but idle (no jobs, not active) must be stopped.
This is the bug the fix addresses — previously fallbacks were never checked."""
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
recent = (datetime.now(timezone.utc) - timedelta(minutes=2)).isoformat()
config = _make_config(last_activity_at=recent)
_setup_firestore(mock_firestore, config)
@@ -345,7 +372,7 @@ class TestFallbackVms:
{"vm": "encoding-worker-fallback-n2f", "zone": "us-central1-f", "ip": "4.4.4.4"},
]),
)
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
recent = (datetime.now(timezone.utc) - timedelta(minutes=2)).isoformat()
_setup_firestore(mock_firestore, _make_config(last_activity_at=recent))
# Only the n2-f fallback is RUNNING+idle → it must be stopped in -f.
@@ -376,7 +403,7 @@ class TestFallbackVms:
"""When a capacity-fallback override is set, that fallback is the
currently-routed VM and gets the keep-alive treatment (matching
what primary normally gets). Primary should still stop on idle."""
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
recent = (datetime.now(timezone.utc) - timedelta(minutes=2)).isoformat()
config = {
**_make_config(last_activity_at=recent),
"active_override_vm": "encoding-worker-fallback-a",
+103 -1
View File
@@ -5,7 +5,8 @@ Fetches daily exports from the KaraokeNerds API and loads them into BigQuery
and GCS. Replaces the legacy pipeline in projectbread-karaokay.
Two modes (controlled by request body):
mode=full — Fetch full song catalog, store to GCS + refresh BigQuery
mode=full — Fetch full song catalog, store to GCS + refresh BigQuery, then
export the kjbox song-identification index (see below)
mode=community — Fetch community tracks (with YouTube URLs), store to GCS + refresh BigQuery
Environment variables:
@@ -33,6 +34,59 @@ KARAOKENERDS_API_KEY = os.environ.get("KARAOKENERDS_API_KEY", "")
GCS_BUCKET = os.environ.get("GCS_BUCKET", "nomadkaraoke-kn-data")
DATASET_ID = "karaoke_decide"
# kjbox song-identification index: every song a singer might mean, exported daily
# after the KN refresh and downloaded by the NomadPC's nomad-catalog-sync. Design:
# kjbox docs/SONG-IDENTIFICATION.md. Rows from three sources, merged/deduped on the
# device (scripts/build_song_id_db.py):
# - MusicBrainz recordings (weekly-refreshed by karaoke-decide's mb-refresh — the
# source that keeps NEW songs coming): kept when Spotify track popularity >= 30
# (via ISRC), or 3+ recordings, or the artist's Spotify popularity >= 50; songs
# with no track score get 0.8 x artist popularity, capped at 50 (an
# estimate must not outrank a measured Spotify score)
# - the static July 2025 Spotify snapshot (popularity >= 30)
# - every KaraokeNerds song (daily; karaoke = 1)
# ~6.7 GB scanned per run (~$0.04). Each run writes a dated folder + a manifest
# (song-id/latest.json) naming its shards, so the device never mixes runs.
SONG_ID_PREFIX = "song-id"
SONG_ID_KEEP_RUNS = 3
SONG_ID_SQL = r"""
WITH
art AS (
SELECT name_normalized, MAX(popularity) apop
FROM `{project}.{dataset}.mb_artists_normalized`
WHERE spotify_artist_id IS NOT NULL
GROUP BY name_normalized),
mb AS (
SELECT r.artist_normalized na, r.name_normalized nt,
ARRAY_AGG(STRUCT(r.artist_credit AS a, r.title AS t) ORDER BY r.spotify_popularity DESC LIMIT 1)[OFFSET(0)] best,
COUNT(DISTINCT r.recording_mbid) recs, MAX(r.spotify_popularity) sp
FROM `{project}.{dataset}.mb_recordings_enriched` r
WHERE r.name_normalized IS NOT NULL AND r.artist_normalized IS NOT NULL
AND NOT REGEXP_CONTAINS(LOWER(IFNULL(r.disambiguation, '')), r'\b(live|demo|rehearsal|instrumental|karaoke)\b')
GROUP BY na, nt),
mb_kept AS (
SELECT mb.best.a artist, mb.best.t title,
-- no Spotify track score (e.g. released after the July 2025 snapshot): estimate from the
-- artist's popularity, a little below it and capped at 50, so a known artist's new song still
-- ranks sensibly but never above a measured track score
COALESCE(NULLIF(mb.sp, 0), CAST(LEAST(art.apop * 0.8, 50) AS INT64), mb.sp) popularity, 0 karaoke
FROM mb LEFT JOIN art ON art.name_normalized = mb.na
WHERE mb.sp >= 30 OR mb.recs >= 3 OR art.apop >= 50),
sp AS (
SELECT ARRAY_AGG(STRUCT(artist_name AS a, track_name AS t) ORDER BY popularity DESC LIMIT 1)[OFFSET(0)] best,
MAX(popularity) p
FROM `{project}.{dataset}.spotify_tracks_normalized`
GROUP BY normalized_artist, normalized_title),
kn AS (
SELECT ANY_VALUE(Artist) a, ANY_VALUE(Title) t
FROM `{project}.{dataset}.karaokenerds_raw`
WHERE Artist IS NOT NULL AND Title IS NOT NULL
GROUP BY LOWER(Artist), LOWER(Title))
SELECT artist, title, popularity, karaoke FROM mb_kept
UNION ALL SELECT sp.best.a, sp.best.t, sp.p, 0 FROM sp
UNION ALL SELECT a, t, CAST(NULL AS INT64), 1 FROM kn
"""
# API endpoints
SONGS_URL = "https://karaokenerds.com/Data/Songs"
COMMUNITY_URL = "https://karaokenerds.com/Data/Community"
@@ -170,6 +224,43 @@ def _load_community_to_bigquery(raw_bytes: bytes) -> int:
return load_job.output_rows
def _export_song_id_index() -> dict:
"""EXPORT DATA the song-identification index to GCS + write the manifest.
Server-side export (no rows pass through this function). Columns:
artist, title, popularity (blank = karaoke-only row), karaoke (0/1); TSV,
gzipped, no header, sharded by BigQuery.
"""
run = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
folder = f"{SONG_ID_PREFIX}/{run}"
client = bigquery.Client(project=GCP_PROJECT_ID)
select = SONG_ID_SQL.format(project=GCP_PROJECT_ID, dataset=DATASET_ID)
export = (
f"EXPORT DATA OPTIONS(uri='gs://{GCS_BUCKET}/{folder}/songs-*.tsv.gz', format='CSV', "
"field_delimiter='\t', header=false, compression='GZIP', overwrite=true) AS " + select
)
client.query(export).result()
gcs = storage.Client(project=GCP_PROJECT_ID)
bucket = gcs.bucket(GCS_BUCKET)
shards = sorted(b.name for b in gcs.list_blobs(GCS_BUCKET, prefix=f"{folder}/"))
if not shards:
raise RuntimeError(f"song-id export wrote no files under {folder}/")
manifest = {"run": run, "shards": [f"gs://{GCS_BUCKET}/{name}" for name in shards],
"columns": ["artist", "title", "popularity", "karaoke"]}
bucket.blob(f"{SONG_ID_PREFIX}/latest.json").upload_from_string(
json.dumps(manifest), content_type="application/json")
# Prune old runs (keep a few so a device mid-download never loses its shards).
runs = sorted({b.name.split("/")[1] for b in gcs.list_blobs(GCS_BUCKET, prefix=f"{SONG_ID_PREFIX}/")
if b.name.count("/") >= 2})
for old in runs[:-SONG_ID_KEEP_RUNS]:
for b in gcs.list_blobs(GCS_BUCKET, prefix=f"{SONG_ID_PREFIX}/{old}/"):
b.delete()
logger.info("song-id index exported: %s (%d shards)", folder, len(shards))
return {"run": run, "shards": len(shards)}
@functions_framework.http
def sync_kn_data(request):
"""
@@ -210,6 +301,16 @@ def sync_kn_data(request):
else:
rows_loaded = _load_community_to_bigquery(raw_bytes)
# Step 4 (full mode): refresh the kjbox song-identification index from the
# just-loaded KN table. Its failure must not fail the KN sync itself.
song_id = None
if mode == "full":
try:
song_id = _export_song_id_index()
except Exception as e: # noqa: BLE001
logger.exception("song-id index export failed")
song_id = {"error": str(e)}
duration = time.time() - start
result = {
@@ -218,6 +319,7 @@ def sync_kn_data(request):
"records_fetched": record_count,
"rows_loaded": rows_loaded,
"gcs_path": f"gs://{GCS_BUCKET}/{gcs_path}",
"song_id_index": song_id,
"duration_s": round(duration, 1),
}
@@ -0,0 +1,129 @@
"""
Tests for kn_data_sync/main.py — the kjbox song-identification index export.
Run: cd infrastructure/functions/kn_data_sync && python -m pytest test_main.py
(Cloud Function tests aren't in the repo-wide testpaths.)
"""
import json
import os
import sys
from unittest.mock import MagicMock
import pytest
_functions_framework = MagicMock()
_functions_framework.http = lambda fn: fn
for name, mod in (
("functions_framework", _functions_framework),
("google.cloud.bigquery", MagicMock()),
("google.cloud.storage", MagicMock()),
):
sys.modules.setdefault(name, mod)
sys.path.insert(0, os.path.dirname(__file__))
import main # noqa: E402
class _Blob:
def __init__(self, name, store):
self.name, self._store = name, store
def delete(self):
self._store.pop(self.name, None)
class FakeGCS:
"""In-memory bucket: list_blobs by prefix, upload, delete."""
def __init__(self, names=()):
self.objects = {n: b"" for n in names}
self.uploaded = {}
def list_blobs(self, bucket, prefix=""):
return [_Blob(n, self.objects) for n in sorted(self.objects) if n.startswith(prefix)]
def bucket(self, _name):
gcs = self
class B:
def blob(self, name):
blob = MagicMock()
blob.upload_from_string.side_effect = lambda data, content_type=None: (
gcs.uploaded.__setitem__(name, data), gcs.objects.__setitem__(name, data))
return blob
return B()
@pytest.fixture
def clients(monkeypatch):
bq = MagicMock()
old_runs = [f"song-id/2026010{i}-000000/songs-000000000000.tsv.gz" for i in range(1, 5)]
gcs = FakeGCS(old_runs)
def run_export(sql):
# The export writes shards into the run folder named in the URI.
folder = sql.split(f"gs://{main.GCS_BUCKET}/")[1].split("/songs-")[0]
for k in range(2):
gcs.objects[f"{folder}/songs-00000000000{k}.tsv.gz"] = b""
job = MagicMock()
return job
bq.query.side_effect = run_export
monkeypatch.setattr(main.bigquery, "Client", lambda project=None: bq)
monkeypatch.setattr(main.storage, "Client", lambda project=None: gcs)
return bq, gcs
def test_export_writes_manifest_for_this_run_only(clients):
bq, gcs = clients
out = main._export_song_id_index()
sql = bq.query.call_args[0][0]
assert sql.startswith("EXPORT DATA OPTIONS(uri='gs://nomadkaraoke-kn-data/song-id/")
assert "compression='GZIP'" in sql and "karaokenerds_raw" in sql and "spotify_tracks_normalized" in sql and "mb_recordings_enriched" in sql
manifest = json.loads(gcs.uploaded["song-id/latest.json"])
assert manifest["run"] == out["run"] and out["shards"] == 2
assert all(f"/song-id/{out['run']}/" in s for s in manifest["shards"])
assert manifest["columns"] == ["artist", "title", "popularity", "karaoke"]
def test_export_prunes_all_but_the_newest_runs(clients):
_bq, gcs = clients
main._export_song_id_index()
runs = {n.split("/")[1] for n in gcs.objects if n.count("/") >= 2}
assert len(runs) == main.SONG_ID_KEEP_RUNS
assert "20260101-000000" not in runs
def test_export_with_no_output_raises(clients, monkeypatch):
bq, _gcs = clients
bq.query.side_effect = None
with pytest.raises(RuntimeError, match="no files"):
main._export_song_id_index()
def test_full_sync_survives_export_failure(monkeypatch):
monkeypatch.setattr(main, "KARAOKENERDS_API_KEY", "k")
monkeypatch.setattr(main, "_fetch_kn_data", lambda url: (b"[]", 0))
monkeypatch.setattr(main, "_store_to_gcs", lambda raw, prefix: "full/x.json.gz")
monkeypatch.setattr(main, "_load_songs_to_bigquery", lambda raw: 0)
monkeypatch.setattr(main, "_export_song_id_index", MagicMock(side_effect=RuntimeError("bq down")))
req = MagicMock()
req.get_json.return_value = {"mode": "full"}
body, status, _ = main.sync_kn_data(req)
data = json.loads(body)
assert status == 200 and data["status"] == "ok"
assert data["song_id_index"] == {"error": "bq down"}
def test_community_sync_does_not_export(monkeypatch):
monkeypatch.setattr(main, "KARAOKENERDS_API_KEY", "k")
monkeypatch.setattr(main, "_fetch_kn_data", lambda url: (b"[]", 0))
monkeypatch.setattr(main, "_store_to_gcs", lambda raw, prefix: "community/x.json.gz")
monkeypatch.setattr(main, "_load_community_to_bigquery", lambda raw: 0)
export = MagicMock()
monkeypatch.setattr(main, "_export_song_id_index", export)
req = MagicMock()
req.get_json.return_value = {"mode": "community"}
body, status, _ = main.sync_kn_data(req)
assert status == 200 and json.loads(body)["song_id_index"] is None
export.assert_not_called()
@@ -3,8 +3,10 @@ Ephemeral GitHub Actions runner dispatcher.
Creates a single-use GCE VM per `workflow_job.queued` webhook, registers it as
a JIT-config ephemeral runner with the nomadkaraoke org, and lets the VM
self-destruct after the job runs. An orphan-cleanup pass runs every 15 min to
catch VMs whose job died before the runner could de-register itself.
self-destruct after the job runs. A scheduled pass (every 5 min) catches VMs
whose job died before the runner could de-register itself, and re-dispatches
self-hosted jobs left `queued` with no runner coming (dropped webhook, VM that
never registered or was preempted).
This module is invoked from main.py when RUNNER_MODE=ephemeral.
"""
@@ -38,6 +40,19 @@ RUNNER_SERVICE_ACCOUNT = os.environ.get(
ORPHAN_GRACE_MINUTES = int(os.environ.get("ORPHAN_GRACE_MINUTES", "30"))
MAX_VM_LIFETIME_MINUTES = int(os.environ.get("MAX_VM_LIFETIME_MINUTES", "120"))
# Stalled-job re-dispatch: a self-hosted job still `queued` this long after
# creation, with no spare runner capacity for its family, gets a fresh VM.
# Covers dropped webhooks (Cloud Run 429), VMs that never register, and VMs
# preempted before picking up their job. Kill switch: REDISPATCH_ENABLED=false.
REDISPATCH_ENABLED = os.environ.get("REDISPATCH_ENABLED", "true").lower() != "false"
REDISPATCH_AFTER_MINUTES = int(os.environ.get("REDISPATCH_AFTER_MINUTES", "5"))
MAX_REDISPATCH_PER_TICK = int(os.environ.get("MAX_REDISPATCH_PER_TICK", "5"))
# Stop retrying a job queued this long: if runners are broken fleet-wide (e.g.
# a deprecated baked runner version — every VM registers, gets rejected, halts)
# re-dispatching would launch a doomed VM per job every tick. Past this age a
# human needs to look; the existing dispatcher alerts cover that.
REDISPATCH_GIVE_UP_MINUTES = int(os.environ.get("REDISPATCH_GIVE_UP_MINUTES", "60"))
# Max seconds to block confirming the VM *insert operation* succeeded (NOT VM
# boot — just that the API accepted and fulfilled instance creation). A timeout
# here means "still provisioning" and is treated as success; only an explicit
@@ -659,6 +674,9 @@ def cleanup_orphans(pat: str) -> dict:
else:
result["delete_failed"].append(name)
deleted = set(result["deleted_vms"])
live_vms = [(zone, inst) for zone, inst in vms if inst.name not in deleted]
# Zombie runners: ephemeral-named runners with no live VM.
for runner in runners:
name = runner["name"]
@@ -677,4 +695,178 @@ def cleanup_orphans(pat: str) -> dict:
print(f"Failed to deregister {name}: {exc!r}")
result["deregister_failed"].append(name)
if REDISPATCH_ENABLED:
# Never let a re-dispatch failure mask the cleanup result.
try:
result["redispatch"] = redispatch_stalled_jobs(pat, live_vms, runner_by_name)
except Exception as exc: # noqa: BLE001
print(f"redispatch_stalled_jobs failed: {exc!r}")
result["redispatch"] = {"error": str(exc)}
return result
# ---------------------------------------------------------------------------
# Stalled-job re-dispatch
# ---------------------------------------------------------------------------
def _parse_github_time(value: str) -> datetime:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
def list_org_repos(pat: str) -> list[str]:
"""Names of the org's non-archived repos (paginated, up to 1000)."""
names: list[str] = []
page = 1
while page <= 10:
result = _github_request(
"GET", f"/orgs/{GITHUB_ORG}/repos?type=all&per_page=100&page={page}", pat
)
if not isinstance(result, list):
break
names.extend(r["name"] for r in result if not r.get("archived"))
if len(result) < 100:
break
page += 1
return names
def list_queued_self_hosted_jobs(pat: str) -> list[dict]:
"""Every org job still waiting for a self-hosted runner.
GitHub has no org-wide "queued jobs" endpoint, so walk each repo's queued
and in-progress runs (a deploy job can sit queued inside an in-progress
run) and collect their queued jobs. A failure on one repo (e.g. a PAT
without access) is logged and skipped rather than aborting the pass.
"""
jobs: list[dict] = []
for repo in list_org_repos(pat):
try:
run_ids: set[int] = set()
for status in ("queued", "in_progress"):
runs = _github_request(
"GET",
f"/repos/{GITHUB_ORG}/{repo}/actions/runs?status={status}&per_page=50",
pat,
)
if isinstance(runs, dict):
run_ids.update(r["id"] for r in runs.get("workflow_runs", []))
for run_id in sorted(run_ids):
run_jobs = _github_request(
"GET",
f"/repos/{GITHUB_ORG}/{repo}/actions/runs/{run_id}/jobs?filter=latest&per_page=100",
pat,
)
if not isinstance(run_jobs, dict):
continue
for job in run_jobs.get("jobs", []):
if job.get("status") == "queued" and "self-hosted" in job.get("labels", []):
jobs.append({**job, "repo": repo})
except Exception as exc: # noqa: BLE001
print(f"Skipping {repo} in stalled-job scan: {exc!r}")
return jobs
def _family_of_runner_name(name: str) -> str | None:
"""``gha-gpu-windows-abc123`` → ``gpu-windows``; None if not ours."""
if not name.startswith("gha-") or "-" not in name[len("gha-"):]:
return None
return name[len("gha-"):].rsplit("-", 1)[0]
def _spare_capacity_by_family(
vms: list[tuple[str, compute_v1.Instance]], runner_by_name: dict[str, dict]
) -> dict[str, int]:
"""Count runners that could still pick up a queued job, per family.
A VM counts if it is still booting inside the orphan grace window, or
registered, online and idle. "Booting" includes a registered-but-offline
runner: ``generate-jitconfig`` registers the runner (offline) before the VM
even exists, so a fresh dispatch normally shows up that way. Busy, stopped
and past-grace VMs don't count — they will never take a new job.
"""
spare: dict[str, int] = {}
for _, instance in vms:
family = _family_of_runner_name(instance.name)
if family is None or getattr(instance, "status", "") in ("TERMINATED", "STOPPING", "SUSPENDED"):
continue
runner = runner_by_name.get(instance.name)
if runner is None or runner.get("status") != "online":
available = _vm_age_minutes(instance) < ORPHAN_GRACE_MINUTES
else:
available = not runner.get("busy")
if available:
spare[family] = spare.get(family, 0) + 1
return spare
def redispatch_stalled_jobs(
pat: str,
vms: list[tuple[str, compute_v1.Instance]],
runner_by_name: dict[str, dict],
) -> dict:
"""Launch a fresh runner for each stalled job not covered by spare capacity.
JIT runners aren't bound to a job — any queued job with matching labels
takes the first free runner — so we compare per-family demand (all queued
jobs) against spare supply, and only act when some job has been queued
longer than REDISPATCH_AFTER_MINUTES (and less than
REDISPATCH_GIVE_UP_MINUTES). Launches per family are capped at the number
of stalled jobs, and per tick at MAX_REDISPATCH_PER_TICK.
"""
result: dict = {"stalled_jobs": [], "given_up": [], "dispatched": [], "dispatch_failed": []}
queued = list_queued_self_hosted_jobs(pat)
if not queued:
return result
now = datetime.now(timezone.utc)
demand: dict[str, int] = {}
stalled: dict[str, list[dict]] = {}
for job in queued:
family = resolve_family(job["labels"]).name
created = job.get("created_at")
age = (now - _parse_github_time(created)).total_seconds() / 60 if created else 0
if age >= REDISPATCH_GIVE_UP_MINUTES:
# Excluded from demand too, so a job we've abandoned doesn't make
# every later stalled job in its family look under-supplied.
print(f"Not re-dispatching {job['repo']} job {job.get('id')}: queued {age:.0f}min (> give-up)")
result["given_up"].append(job.get("id"))
continue
demand[family] = demand.get(family, 0) + 1
if age >= REDISPATCH_AFTER_MINUTES:
stalled.setdefault(family, []).append(job)
result["stalled_jobs"].append(
f"{job['repo']}#{job.get('run_id')}/{job.get('name')} ({age:.0f}min, {family})"
)
spare = _spare_capacity_by_family(vms, runner_by_name)
budget = MAX_REDISPATCH_PER_TICK
to_launch: list[dict] = []
for family, jobs in stalled.items():
deficit = demand[family] - spare.get(family, 0)
count = min(max(deficit, 0), len(jobs), budget)
print(
f"Re-dispatch {family}: queued={demand[family]} stalled={len(jobs)} "
f"spare={spare.get(family, 0)} launching={count}"
)
to_launch.extend(jobs[:count])
budget -= count
if budget <= 0:
break
if not to_launch:
return result
# Each launch blocks up to INSERT_CONFIRM_TIMEOUT_SECONDS; run them in
# parallel so a full budget stays well inside the function timeout.
with ThreadPoolExecutor(max_workers=len(to_launch)) as ex:
futures = {ex.submit(create_ephemeral_runner, job["labels"], pat): job for job in to_launch}
for fut in as_completed(futures):
job = futures[fut]
try:
result["dispatched"].append(fut.result()["runner_name"])
except Exception as exc: # noqa: BLE001
print(f"Re-dispatch for {job['repo']} job {job.get('id')} failed: {exc!r}")
result["dispatch_failed"].append(job.get("id"))
return result
@@ -6,9 +6,9 @@ dispatcher. The heavy lifting lives in ``ephemeral.py``:
* ``workflow_job.queued`` webhook → ``create_ephemeral_runner`` (mints a JIT
config, creates a fresh GCE VM, returns).
* Cloud Scheduler tick (every 15 min) → ``cleanup_orphans`` (reconciles GCE
* Cloud Scheduler tick (every 5 min) → ``cleanup_orphans`` (reconciles GCE
VMs against org-runner registrations, deletes stragglers, de-registers
zombies).
zombies, then re-dispatches jobs stuck ``queued`` with no runner coming).
Environment variables: see ``ephemeral.py``.
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more