mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 01:31:32 +09:00
36b331f3d7411ecf97c05bf15146e83161ab94de
169
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
3cdb62a058 |
fix: run render-video worker as Cloud Run Job to survive backend deploys (#994)
## Summary Tenant E2E run #107 (`singa`) failed with job `41e06b90` frozen at `rendering_video` — even though the GCE encoder **finished the render and uploaded every output**. Root cause: a backend deploy landed mid-render and killed the render poll, which ran as a FastAPI BackgroundTask on the Cloud Run service. Full investigation: `docs/archive/2026-09-13-render-deploy-survival-investigation.md` ### The failure chain (4 layers, each structurally broken) 1. **BackgroundTask execution** — the render endpoint returns 200 immediately and polls post-response; Cloud Run SIGKILLs old-revision instances ~10s after SIGTERM on every deploy. 2. **Unreachable shutdown parking** — uvicorn waits for background tasks *before* running lifespan shutdown, so `park_active_render_jobs_for_shutdown()` never runs in exactly the scenario it was written for. Its comment claimed a 600s grace period; Cloud Run gives 10s. Verified in logs: the old revision's last lines were uvicorn's `Waiting for background tasks to complete.` — then SIGKILL. 3. **Cloud Tasks retry defeated** — the queue got its 200 at dispatch; `dispatch_deadline=1800s` protects nothing. 4. **45-min stuck sweep** — reachable but slower than the E2E's 30-min budget and a ~50-60 min silent stall + wasted re-render for a real customer, on every deploy that lands mid-render (deploys go out on every merge to main). This is the **identical bug class fixed for the video worker in 2026-03** (`docs/archive/2026-03-08-fix-encoding-deploy-survival.md`, `USE_CLOUD_RUN_JOBS_FOR_VIDEO`) — the render worker was never migrated. ### Changes - **Route `trigger_render_video_worker` through a Cloud Run Job** — reuses `video-encoding-job` with args override `python -m backend.workers.render_video_worker --job-id <id>`, behind `USE_CLOUD_RUN_JOBS_FOR_RENDER` (enabled in deploy env). Job executions run to completion; deploys never touch them. - **New CLI entrypoint** in `render_video_worker.py`. Exit-code contract differs from video_worker deliberately: clean returns (True AND False) exit 0 because `process_render_video` parks/fails/supersedes internally; only an escaped crash exits 1 (job template has `max_retries=2`). - **Worker-side idempotency gate** (review finding): the CRJ path bypasses the HTTP endpoint's `_check_worker_idempotency`, and CRJ retries could re-enter a job in `RENDERING_VIDEO` (hard-failing it via the same-state transition guard) or resurrect a terminal job. The worker now skips terminal + already-rendering jobs cleanly regardless of dispatch path. - **Surface failed video-worker dispatch** (review finding): the ignored `trigger_video_worker` return after render completion now logs at ERROR instead of silently stalling the job at `instrumental_selected`. - **Pulumi**: `video-encoding-job` env gains both `USE_CLOUD_RUN_JOBS_FOR_*` flags so the render execution's in-process video-worker trigger also dispatches a CRJ. **Already applied to prod** (`pulumi up` run locally, verified on the job). - **`main.py`**: corrected the false 600s comment; shrank the unreachable 480s lifespan wait to 5s. Parking hook kept as legacy/flag-off net. ### Rollback Remove `USE_CLOUD_RUN_JOBS_FOR_RENDER=true` from the service env → falls back to the legacy Cloud Tasks path. ## Testing - Backend: 4422 unit + 151 emulator tests pass locally. - New tests: CRJ routing (flag on/off), CLI exit-code contract, worker-side idempotency gate (terminal skip, already-rendering skip). - Post-deploy: will dispatch the Tenant Portals E2E workflow (the failing scenario) against prod. 🤖 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** - Video rendering now runs as durable background jobs, allowing renders to continue through service deployments. - Added safeguards to prevent duplicate processing and safely handle completed or in-progress jobs. - Improved failure reporting when a video-processing job cannot be started. - **Bug Fixes** - Fixed render jobs becoming stuck when deployments interrupted background processing. - **Documentation** - Added troubleshooting guidance and incident lessons for interrupted or stuck renders. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
d93dbddd48 |
ci: reliable R1 canary version-gate + retry (stop false pages) (#988)
Follow-up to the incident-hardening initiative — fixes the false "Post-deploy canary FAILED (v0.222.3)" page from the #987 deploy. **Root cause:** the R1 version-change gate did a single un-retried curl to the raw Cloud Run **origin** `/api/health/detailed`, which came back empty (cold start on the scaled-to-zero prior revision and/or origin edge-auth on the detailed endpoint). It logged `Currently-serving version: <unknown>` and **fail-opened → ran the canary on a no-bump deploy**, which then flake-failed on a review-page timing wait and paged. **Fixes:** 1. **Reliable gate** — read the currently-serving version via the **edge** (`https://api.nomadkaraoke.com/api/health/detailed`, warm + Cloudflare-fronted, verified to return the version) with retries. A no-bump deploy now correctly **skips** the canary. 2. **Retry the canary** — `--retries=2` so a single flaky UI wait doesn't page; only a failure surviving retries is real. (The happy-path's review-page waits are inherently flaky; the identical spec passed on the 0.223.2 deploy.) No app code changed → no version bump. YAML validated. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
5b5264dc54 |
Incident hardening: deploy/CI/runner resilience (R1/R2/R3/R4/C1/C2) (#987)
Part 3 of 3 of the **Incident hardening (post-NOMAD-1632)** initiative (plan: `docs/archive/2026-09-12-incident-hardening-plan.md`). Closes the deploy/CI/runner gaps: no functional gate, no codified rollback, bad revision serves 100% immediately, fire-and-forget runner stranding, and a flaky smoke. **No backend app code changed → no version bump.** ## ⚠️ Reviewer note — read first **R3/R4 rewrites the live `deploy-backend` step.** It's designed to be *auto-revert-safe* (a failed candidate smoke means we simply never migrate traffic, so the prior revision keeps serving 100% — a bad revision serves **0%**, not an outage). But it changes how **every** backend deploy works and **can't be fully exercised in CI**. This is the one to watch on first merge. If you'd rather de-risk, R3/R4 is the only item here that's safe to split out — the rest (R1/R2/C1/C2) are independent and lower-risk. ## R2 — codified fast rollback (`scripts/rollback.sh` + runbook) Dry-run-able, explicit-target-required rollback for the Cloud Run **service** (traffic-shift to a prior revision — instant, no rebuild) and the three **jobs** (image re-pin, correct per-job region/repo — verified against ci.yml). `--list` shows available revisions/tags; `--dry-run` prints every gcloud command. `docs/TROUBLESHOOTING.md` "Fast rollback" runbook added as the first section. ## R3/R4 — service traffic-canary `deploy-backend` now deploys `--no-traffic --tag candidate`, smokes the tagged candidate URL (health + expected version, with retries), then `update-traffic --to-latest` **only on pass**. Cloud Run Jobs can't traffic-split (noted inline) → they rely on R1 + R2. ## R1 — post-deploy functional canary, version-change-gated New `deploy-verify` job runs the real production happy-path (`happy-path-real-user.spec.ts`, admin-credit variant — reuses e2e-daily's impersonate token refresh, secret names verified identical) after a backend deploy, **only when the backend version actually changed** (new "Detect backend version change" step compares `poetry version` to the currently-served `/api/health/detailed`). Frontend/docs/infra-only merges short-circuit. On failure → Discord alert + loud fail printing the exact `scripts/rollback.sh` invocation. Per the plan's caveat, a fresh happy-path won't reproduce every incident class (e.g. Failure B's stale-cache) — an admin reset+retry variant is a noted follow-up. ## C1 — ephemeral-runner stranding fix `infrastructure/functions/runner_manager/ephemeral.py` now confirms the VM insert **operation** succeeded instead of fire-and-forget: a late stockout/quota/transient error raises → existing zone-fallback / webhook redelivery kicks in instead of silently stranding a queued job for ~15 min. An insert-confirm *timeout* is treated as "still provisioning" (not a failure); guarded for older clients. **+4 tests (46 pass).** ## C2 — de-flake the E2E smoke `networkidle` → `domcontentloaded` + explicit element waits (the marketing page's background requests made `networkidle` time out and redden real deploys). ## Validation (local only — no deploy) - `ci.yml` + `e2e-daily.yml` parse; **actionlint clean** on new code. - `rollback.sh`: `bash -n` + `shellcheck` clean; constants cross-checked against ci.yml. - `test_ephemeral.py`: **46 passed**. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
05f024bdd4 |
Requests voting board Phase 2: daily free-community-track automation (#977)
## Summary
Phase 2 of the requests voting board (`requests.nomadkaraoke.com`) — the
daily automation that turns the top-voted request into a free,
auto-generated, published karaoke video. **Deploys dark** behind a
kill-switch (`COMMUNITY_DAILY_PICK_ENABLED`, default off); the daily
Scheduler only shadow-logs until it's flipped on.
Picks up
`docs/archive/2026-09-03-requests-voting-board-phase2-handoff.md`.
Design + Andrew's decisions:
`docs/archive/2026-09-03-requests-board-phase2-plan.md`.
## What's included
- **Daily picker** (`community_daily_pick.py`, Scheduler noon US
Eastern, DST-aware): claims the UTC day with a create-only lock
(`daily_community_pick/{YYYY-MM-DD}` → **one free track/day, total**),
picks the top open request with net votes ≥ 0 (source-agnostic; skips
community-rejected), grants the requester a free credit, and submits the
job **as that user** (owned by them, credit consumed) via the same
search → auto-select → download path the web flow uses. Fully idempotent
(resumable per-day lock phase + per-request guard flags).
Shadow/`?dry_run=true` mode.
- **24h ownership handoff** (`community_handoff.py`, hourly): reassigns
a stale review to the next up-voter (compare-and-set guarded), up to **5
voters**, then parks the track (`stalled`). Community jobs excluded from
the normal stale-review auto-cancel.
- **Voter publish fan-out**: YouTube upload-queue hook marks the request
`published` and emails every up-voter (except the owner) a new "track
you voted for is live" email (33 locales). Retry-safe (per-voter success
tracking).
- **Two internal endpoints** + two Cloud Scheduler jobs (Pulumi).
## Andrew's decisions (via AskUserQuestion)
- Trigger: **noon US Eastern**. Trending-agent fallback source:
**deferred** to a follow-up. Net-negative requests: **skipped**. Handoff
cap: **5 voters then park**.
## Deferred / follow-ups (not in this PR)
- **Trending-agent fallback source** (auto-submit a candidate when the
board is empty) — deliberately deferred; must generate candidates the
careful way (karaoke-decide `candidates` + KaraokeNerds).
- **YouTube description board link** — left untouched to avoid
clobbering Andrew's parallel descriptions work; add
`requests.nomadkaraoke.com` to `default_youtube_description` once that
lands.
## Testing
- Worker unit tests (kill-switch shadow, empty board, day-lock
idempotency, credit-grant/job-create guards, handoff cap/stale/CAS,
voter fan-out retry-safety) + emulator tests for the new service methods
against real Firestore transactions.
- All touched existing suites (youtube queue, stale-review,
requests-board routes/logic) pass. 79 passed locally.
## Review
CodeRabbit reviewed locally (2 cycles completed; 2 major + 1 minor
findings all addressed — retry-safe fan-out, CAS owner assignment,
up-voter ordering). 3rd cycle hit the free-OSS rate limit; it would only
re-verify the applied fixes.
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
3c58143f75 |
fix(review): re-sign instrumental preview URLs on expiry (refresh-on-error) (#973)
## Problem
Completing a combined review failed to play the instrumental in the
preview modal — toggling to **Instrumental** loaded nothing, with
`NS_ERROR_DOM_NETWORK_ERR` in DevTools (Firefox) on the
`review-audio/instrumental_with_backing.ogg` GCS request.
**Root cause:** the overlaid instrumental `<audio>` uses the signed GCS
URL baked into the review payload at page load, which has a **120-minute
expiry**. A long review session outlives it, so the stem fetch returns
`400 ExpiredToken` and playback silently fails. Confirmed by fetching
the exact URL from the report: `ExpiredToken — Request signature expired
at 2026-09-01T20:16:26Z` (page had been open ~2h11m).
Reloading didn't help because the review UI persists the full
`CorrectionData` — including `instrumental_options[].audio_url` — to
`localStorage` (`lyrics_analyzer_data`) and rehydrates it when the user
has unsaved edits, so the *same* expired URL came back.
The `[SW] Service worker registered` log is a red herring:
`frontend/public/sw.js` has no `fetch` handler.
## Fix (refresh-on-error)
- **Backend:** extract a shared `_build_instrumental_options` helper and
add `GET /api/review/{job_id}/instrumental-urls` returning
freshly-signed stem URLs.
- **Frontend:** on the stem `<audio>` `error` event, re-fetch fresh URLs
via the new endpoint and swap them in. The existing video↔audio sync
effect (keyed on the URL) resumes playback in place. Capped at 3
refreshes per modal open so a genuinely-broken stem (404) can't loop.
No new user-facing strings (the recovery is silent) → no i18n changes.
## Testing
- Backend: 3 new tests for the endpoint (both stems / single stem / 404)
— `TestInstrumentalUrlsRefresh`. Full `test_routes_review.py` +
`test_combined_review_flow.py` + `test_audio_transcoding_service.py` =
111 passed.
- Frontend: 3 new `PreviewVideoSection` tests (swap on error / cap at 3
/ no-op without refresh fn). Full unit suite = 1248 passed.
- CodeRabbit local review: no findings.
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
37b9e6088b |
ci(pypi): recurring storage-cap prune reminder (fix failing PyPI publish) (#960)
## Problem The `Deploy - Publish to PyPI` step on `main` has been failing: ``` HTTP Error 400: Project size too large. Limit for project 'karaoke-gen' total size is 10 GB. ``` This is a recurrence of the known 10 GB PyPI project cap. The project is at **10.71 GB / 479 releases**; each release is a ~62 MiB universal wheel (bundled 33-locale frontend) auto-published on every merge (~3 GB/month), so it refills the cap every few months. **Only the public `pip install` publish step fails** — Cloud Run and the GCE encoding worker (pulls the wheel from GCS) are unaffected. The prior fix (v0.187.5) was wheel-only publishing + a one-time manual deletion, which only bought ~2 months. This makes the cleanup **recurring and durable**. ## Why not just automate deletion in CI? PyPI has **no deletion API** (upload tokens / Trusted Publishing are upload-only, and 2FA is mandatory). Deletion is only possible from a logged-in browser session, which can't be safely/durably stored in CI. So we automate the *decision + reminder* and keep the *deletion* a ~1-minute human step. ## What this adds - **`scripts/prune_pypi_releases.py`** (stdlib-only) — reads the public JSON API and computes a retention plan: **keep last 60 days + newest release per older calendar month + latest overall**. Renders a table / JSON / Markdown report and a **paste-into-browser-console** deletion snippet. Never deletes anything itself. Today's plan: keep 82, delete 397, **10.71 GB → 4.17 GB**. - **`.github/workflows/pypi-prune-reminder.yml`** — monthly cron (+ manual dispatch) that runs the planner and, once the project crosses a 7 GB watermark, opens/updates a single tracking issue with the plan + snippet. No secrets. - **`docs/PYPI-STORAGE-PRUNE.md`** runbook + a `TROUBLESHOOTING.md` entry. - **`tests/unit/test_prune_pypi_releases.py`** — 13 tests covering the policy (recency window, per-month keeper, latest-overall, same-day timestamp ranking, empty/undated releases, sizes, rendering). ## Testing - `pytest tests/unit/test_prune_pypi_releases.py` → 13 passed. - Ran the planner against live PyPI data; generated JS validated with `node --check`. - `black` clean; workflow YAML validated; `should_nag` gate verified. ## Notes - **No version bump** — tooling/CI/docs only, nothing in the wheel changes. Merging therefore **skips** the publish step (tag `v0.209.1` already exists), so this PR does not itself add another fat wheel while we're over the cap. - **To unblock publishing now:** after merge, run the prune (locally via the script or trigger the workflow with `workflow_dispatch`), paste the snippet on the logged-in PyPI releases page, then re-run the publish. The monthly cron keeps it under the cap going forward. - Related: filed [pypi/support#12050](https://github.com/pypi/support/issues/12050) requesting a 50 GB limit as a one-off buffer; the recurring prune is the durable fix. @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
b45efbdbc5 |
feat: enable confident backing-keep enforcement in prod (#953)
## Summary One-line deploy-env change: `AUTO_APPROVAL_BACKING_KEEP_ENABLED=true` on the backend service. A confident WITH_BACKING verdict from the 3-stem backing decider (#950) now auto-selects the with-backing instrumental, letting jobs with confident lyrics AND clear backing vocals complete fully automatically. ## Shadow validation evidence (why now) - **20-job replay corpus**: 13/14 true keeps confidently retained (incl. both jobs the human under-kept); catastrophic backing-is-lead case gated; zero unsafe outcomes. - **Live prod battery**: 7/7 keep verdicts on harmony tracks with consistent signal profiles; the misclassified-lead gate fired correctly on an adversarial shoegaze track; one job completed fully zero-touch end to end. - **Human review pass on 11 fresh jobs (2026-08-29)**: 10/11 instrumental picks matched the shadow verdict. The single lyrics-auto-eligible job was shipped by the human with **zero manual edits and the identical instrumental selection** full-auto would have made. Every job needing real lyric work was correctly gated (up to 127 manual edits on gated jobs; zero false-autos). Kill switch: set the var to false (or remove it — code default is false). Per-job opt-out: `review_mode="always_review"`. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
8457a3bfca |
fix(ci): pin google-cloud-firestore in backend deploy (2.29.0 breaks deploys) (#941)
## Problem — backend deploys are broken The **Deploy - Backend (Cloud Run)** job's *Read Firestore config* step crashes: ``` google.api_core.exceptions.InvalidArgument: 400 Invalid database id %28default%29 ``` `%28default%29` is URL-encoded `(default)`. **`google-cloud-firestore` 2.29.0** (published 2026-08-24T21:55Z) percent-encodes the default database id in the resource path. The deploy step ran an **unpinned** `pip install google-cloud-firestore`, so it started pulling 2.29.0 and failing. **Impact:** every backend deploy since 2.29.0 shipped has failed (post-merge runs for `c36bcb08` and `7a3c1d66`). #939 (worker-trigger retry) and #940 (job-list summary field) merged but **never reached Cloud Run** — the active revision is still `00913` from #937. ## Fix Pin the deploy step to `google-cloud-firestore==2.26.0` — the version `pyproject.toml` and prod already run (the running backend reads Firestore fine on 2.26.0). One line + a comment explaining why. ## Testing - PR CI runs unit tests (deploy jobs are push-to-main only); the pin doesn't affect them. - On merge, the backend deploy will run with 2.26.0 and should succeed, deploying main (0.199.3 = retry fix + summary field). - Verified 2.29.0 is the regression via PyPI upload timestamps vs the last good deploy (21:06, used 2.28.1). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Updated the backend deployment to use a fixed Firestore library version, improving deployment consistency and reliability. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
7729d30937 |
build: build frontend into the wheel in CI instead of committing out/ to git (supersedes #892) (#926)
Build the Next.js frontend into the wheel in CI instead of committing the generated out/ to git (fixes #876; supersedes #892). Validated: package-build-test green (npm ci → make build-frontend → poetry build → verify_wheel_frontend guard → install). Thanks @netux for surfacing it. |
||
|
|
6fa4400d3d |
feat(dr): back up all GitHub repos to S3 (survive a GitHub ban) (#929)
## Summary
Extends the nightly DR backup Cloud Function (`backup-to-aws`) to bundle
**every git repo under `github.com/nomadkaraoke` and
`github.com/beveradb`** into a per-repo `git bundle` on S3, so code +
full history survive a complete loss of GitHub access (e.g. an automated
copyright-strike account ban). Each bundle is directly cloneable —
restore is `git clone --mirror <bundle>` → `git push --mirror
<new-remote>`.
## Changes
- **`git_repos_export.py`** (new): enumerate repos via GitHub
`/user/repos` (includes private), mirror-clone + `git bundle create
--all`, upload to `git-repos/{owner}/{repo}.bundle` in staging, plus a
`manifest.json` inventory. Forks excluded, oversized/empty repos
skipped, per-repo errors non-fatal, org backed up **before** the
personal account for deadline resilience. PAT is read from Secret
Manager at **runtime** (not a deploy-time secret env var) so the
function deploys before the secret has a value and skips gracefully if
absent.
- **`main.py`**: new nightly Step 4b (between secrets export and S3
upload).
- **`infrastructure/modules/backup.py`**: bump function to 4Gi/2CPU
(mirror-clone uses in-memory `/tmp`); add `GIT_BACKUP_OWNERS` env.
- **`infrastructure/modules/secrets.py`**: new `github-backup-token`
secret (value added manually).
- **`.github/workflows/dr-backup-freshness.yml`**: monitor `git-repos/`
at 36h, counting only `.bundle` objects.
- **`docs/DISASTER-RECOVERY.md`**: new "Scenario 3: Loss of GitHub
access" + restore steps + token setup.
## Security
- The GitHub PAT is injected via a `GIT_CONFIG_*` `Authorization` header
(like `actions/checkout`), never in the clone URL/argv — so it can't
leak via `ps`, `TimeoutExpired`, or captured stderr. Token is also
redacted from any error text persisted into `manifest.json`.
## Testing
- 14 new unit tests for the module
(enumerate/filter/bundle/skip/error/security paths); full
`backup_to_aws` suite: **27 passing**.
- CodeRabbit local review (cycle 1) completed; all 4 findings (1
critical PAT leak, 2 major, 1 minor) addressed. Cycle-2 verification was
rate-limited (free-tier), so **left for the GitHub bot to review the
final diff**.
## Deploy notes
- **Pulumi already applied locally** (`github-backup-token` secret
created + function on 4Gi/2CPU) — CI re-run is a no-op.
- After merge, run `infrastructure/functions/backup_to_aws/deploy.sh` to
ship the new function source, then set the PAT:
`printf %s '<PAT>' | gcloud secrets versions add github-backup-token
--data-file=- --project=nomadkaraoke`
- Requires a classic GitHub PAT (owner: beveradb, member of nomadkaraoke
org) with `repo` + `read:org`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
c7959ea2d5 |
feat(encoding): mature multi-instance-type pool with availability-aware selection (#911)
## Summary - Replaces "c4d primary + single n2 fallback family" with a **ranked pool of 6 x86_64 / 32-vCPU / ≥32 GB highcpu types** across 4 silicon lineages (c4d, c4, n4d, c2d, n2d, n2), selected **fastest-first** but **availability-aware** — a type that stocks out is demoted for a 15-min cooldown then re-probed. c4d stays the top pick whenever it can start; a render no longer stalls even if 2+ types are fully stocked out in us-central1. - One **pure preference module** (`encoding_worker_preference.ordered_candidates`) is now the single source of truth for candidate ranking, driving **both** runtime selection and deploy green selection so they can't drift. - Keeps the per-VM start/stop model (MIG deferred with documented triggers; no reservation). Full plan + rollout in `docs/archive/2026-08-15-encoding-instance-type-diversity-plan.md`. ## Changes - **New** `backend/services/encoding_worker_preference.py` — speed-rank + Firestore `capacity_state` cooldown; stdlib-only so `deploy_promote` imports it (with a shadow-proof by-path fallback). - **Runtime** (`encoding_service`, `encoding_worker_manager`): builder ranks primary + fallbacks; manager records/clears per-(type,zone) stockout; override routing now keys off an explicit `is_primary` flag instead of list position. - **Deploy** (`deploy_promote`, `ci.yml`): green selection uses the shared ranker + threads `capacity_state`. - **IaC** (`config.py`, tests): `FALLBACKS` broadened to 6 types (additive-only) with family-correct disk types (Titanium c4/c4d/n4/n4d = hyperdisk-balanced; c2d/n2/n2d = pd-balanced); secret schema gains optional `machine_type`. - **Packer** (`provision.sh`, `startup.sh`): bake full dep tree with **CPU-only torch** so fresh type VMs boot self-sufficient; build-time import verify. - **New** `benchmark_types.py` to measure per-type encode wall-time and refine the seeded `SPEED_RANK`. ## Testing - [x] Full backend unit suite: **3871 passed, 36 skipped** (emulator tests need external services) - [x] New/updated tests: preference module (16), capacity_state + `is_primary` manager tests, builder-ordering + non-list-JSON service tests, deploy ranking tests, infra disk-capability + pool-breadth invariants - [ ] Operator rollout (needs write creds): `pulumi up` (verify +8 create, 0 replace) → rebuild image (dep-bake) → grow fallback secret with `machine_type` → run `benchmark_types.py` ## Review - [x] Local CodeRabbit review completed (4 major findings fixed; cycle 2 clean) - [x] Review feedback addressed @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
9a752ab3eb |
fix(deploy): capacity-aware encoding-worker deploy (reach serving fallback in c4d stockout) (#910)
## Problem Follow-up to #908/#909. The CI encoding-worker deploy is a blue-green over the **c4d primary/secondary** VMs. us-central1 is in a persistent **c4d Spot stockout**, so both are down and all traffic runs on an n2 fallback recorded as `active_override_vm`. The deploy can't start the c4d secondary → rolls back → **never refreshes the serving fallback**, so worker-side `main.py` changes (the #908/#909 fixes) never reach prod until a manual restart. Evidence: the config doc's `primary_version` was stuck at `0.192.9`, and I had to hand-start the n2f fallback to get 0.194.0 live. ## Fix — validate on a fresh green, then promote it (zero-downtime, stockout-proof) Decision logic is a pure, unit-tested module (`infrastructure/encoding-worker/deploy_promote.py`) since the branching can't be exercised in CI: - **`select_green_candidates`** — try the c4d `secondary` first, else a fresh n2 fallback (n2 before c4d), **excluding the current override** so it keeps serving while we validate a *different* fresh worker. - **`promote_plan`** — for a c4d green, the classic primary/secondary swap **and clear any stale override**; for a fallback green, set it as `active_override`. Returns the exact Firestore update + which retired VM(s) to drain/stop (**never the just-promoted green**). Workflow (`.github/workflows/ci.yml`): - "Select & start green target" (capacity-aware, `continue-on-error`, emits `green_ok`), health + real-encode-test on the green IP, then "Promote green to serving" (apply plan + drained stop of retired VMs, non-RUNNING skipped, one shared 20-min drain budget). - Rollback uses `always()` so `deploy_in_progress` is always cleared; only stops a green we started fresh, and **recovers the serving override** (starts it back up) if a last-resort in-place restart left it down. ## Testing - `backend/tests/test_deploy_promote.py` — 10 cases: candidate ordering (secondary-first, n2-before-c4d, override excluded), both promote branches, and never-drain-the-green guard. - `actionlint` clean on the new steps; YAML validated. - Two full local CodeRabbit cycles; all 7 findings addressed (self-drain guard, stuck `deploy_in_progress`, None-IP guard, drain time-bound, override recovery). ## Deploy note This PR's own merge is the first live run of the new logic (deploy runs on every push to main). Expected: it selects an n2 fallback as green (c4d won't start), validates it, sets `active_override` to the fresh one, and drains the old override. Will be watched closely. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Improved encoding-worker deployments with capacity-aware green worker selection and fallback support. * Added safer blue-green promotion, health validation, job draining, and rollback handling. * Prevented active jobs from being interrupted during worker replacement. * **Bug Fixes** * Added recovery for capacity shortages, including validated in-place restarts as a last resort. * Automatically clears stale deployment overrides and deployment locks. * **Documentation** * Updated troubleshooting guidance for worker restarts and capacity-related recovery. * **Tests** * Added coverage for worker selection, promotion, fallback handling, and draining behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> @coderabbitai ignore |
||
|
|
d9ecc0d0d0 |
Edge cutover complete: api.nomadkaraoke.com behind Cloudflare (WAF + origin lock enforced) (#888)
Completes the edge-security rollout started in #886. **The prod cutover is done and validated** — `api.nomadkaraoke.com` now serves all traffic through Cloudflare with WAF + rate-limiting, and the origin lock is enforced. ## Cutover (applied via targeted `pulumi up`, validated live) 1. Imported the existing prod `api` DNS record (adopt, not duplicate) 2. Provisioned prod WAF/rate-limit/header rules while `api` stayed DNS-only 3. Flipped `api` to proxied (the one reversible change) 4. `EDGE_AUTH_MODE` off → warn → **enforce** (validated safe via prod E2E) ## Validation results (2026-07-20) - `api.nomadkaraoke.com` → **200 + cf-ray**, exploit paths → **403** (WAF), `/api/health` → 200, **CORS ok**, frontend loads, **0 backend errors** - **Daily prod E2E PASSED** (real Stripe payment + karaoke generation through the edge) - **0 edge-auth warnings** during the full E2E → enforce enabled - Origin lock verified: direct-to-`*.run.app` non-exempt → **403**; health/root exempt → 200 ## Key finding: SSL "full" mode resolves the cert dragon The Cloud Run managed cert can't provision behind Cloudflare (ACME challenge not visible), **but the zone SSL mode is "full" (not strict)** so Cloudflare doesn't validate the origin cert — the edge works and is **renewal-safe** with no run.app Origin Rule / LB / cert wait. Rule: keep zone SSL on "full", never "full (strict)". ## Free-plan constraints handled (in #886) WAF `contains` not regex; rate-limit `period=10`+`cf.colo.id`; managed OWASP off. ## Changes - `config.py`: SSL-"full" note (replaces the reverted run.app-origin config) - `Pulumi.prod.yaml`: cutover config (`rolloutStage=prod`, `proxyProdApi=true`, `proxyStaging=true`) - `ci.yml`: `EDGE_AUTH_MODE=enforce` (persist the origin lock across deploys) - Plan §4 + runbook Phase B: the resolution + actual results ## Rollback `pulumi config set edge:proxyProdApi false && pulumi up --target …api-dns` (DNS-only within a TTL); `EDGE_AUTH_MODE=off` disables the lock. @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
fb2bd6b108 |
Cloudflare edge security (WAF + rate limit + origin lock) for karaoke-backend (#886)
## Summary Puts `api.nomadkaraoke.com` behind the Cloudflare edge that already fronts the rest of the domain, after a vuln-scanner hammered the directly-exposed Cloud Run origin on 2026-07-20 (`/.env`, `/.ssh/id_rsa`, `wp-config.php`… — all 404'd, but the burst of 404s tripped the "High Error Rate" alert). The API was the one internet-facing surface with **no WAF, no rate limiting** — DNS-only CNAME straight to `ghs.googlehosted.com`, Cloud Run ingress `all`. **Zero-downtime by construction:** everything is gated behind `edge:enabled` (default off) and staged via two independent switches (`edge:rolloutStage` for rule scope, `edge:proxyProdApi` for the DNS flip). The whole Cloud-Run×Cloudflare interaction is validated on a throwaway staging host first; the only prod-affecting action is a single, instantly-reversible DNS proxy flip. Full sequence in `docs/archive/2026-07-20-edge-security-cutover-runbook.md`. ## Changes - **`infrastructure/modules/edge_security.py`** (new) — `pulumi_cloudflare` WAF (exploit-path block), per-IP rate limiting (excludes `/api/internal/*`), origin-lock header transform, zone security; staging + prod DNS records. Managed OWASP ruleset gated off (zone is Free plan). - **`backend/middleware/edge_auth.py`** (new) — off/warn/enforce origin lock via a secret header Cloudflare injects; **fails closed (503) in enforce** when the secret is missing; health/root exempt. +13 unit tests. - **`monitoring.py`** — retune the high-error-rate alert to **5xx-only** (+ fix the rate-vs-ratio naming) so client/bot 404 bursts no longer page. - Wiring: `secrets.py` (edge-origin-secret container), `config.py`, `__main__.py`, pinned `pulumi-cloudflare==6.18.0`, `ci.yml` (`EDGE_AUTH_MODE=off` + secret ref), `Pulumi.prod.yaml` (encrypted `edge:originSecret`). - Docs: hardening plan + cutover runbook in `docs/archive/`. ## Already applied to prod (targeted `pulumi up`) - ✅ `edge-origin-secret` Secret Manager container + v1 value - ✅ 5xx error-rate alert retune (fixes the original paging issue immediately) - Everything else stays dormant: `edge:enabled=false`, backend `EDGE_AUTH_MODE=off`. ## Testing - [x] `make test` — full backend + frontend suite green (1085 frontend tests; backend incl. 13 new edge-auth tests) - [x] Cloudflare token verified against live API (DNS create+delete, rulesets, zone settings) - [x] `pulumi preview` clean (targeted apply of only the 2 additive resources) - [ ] Staging validation + prod cutover — follow the runbook (separate, gated) ## Review - [x] CodeRabbit CLI review completed locally; findings addressed (fail-closed enforce, decoupled cutover, fixed origin-lock test, threshold wording). One pre-existing PR_TITLE shell-interp finding in the deploy step left out of scope. ## Notes for reviewer - Nothing here touches prod behavior until someone sets `edge:enabled true` and walks the runbook. The prod `api` DNS record must be `pulumi import`ed (already exists) — documented in runbook step 4a. - Pre-existing cross-worktree Cloud Function source drift is visible in a full `pulumi preview`; not introduced here (applied via `--target` to avoid it). @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
ac4d7f7b3d |
feat(runner-manager): Windows GPU ephemeral runner family (gpu-windows) (#881)
## Summary Adds a Windows Server + T4 family to the ephemeral GHA runner fleet, following the existing pattern exactly (JIT-config single-use VMs from pre-baked image families). Built for python-audio-separator's upcoming `windows-directml` integration tests — part 2 of the RoFormer-on-Windows plan (nomadkaraoke/python-audio-separator#292; see plan in nomadkaraoke/python-audio-separator#294). ### Dispatcher (`ephemeral.py`) - `FamilySpec.os_label` (default `linux`) replaces the hardcoded `linux` advertised label - New `gpu-windows` family: n1-standard-4 + T4, `gha-runner-gpu-windows` image family, 100GB disk - `resolve_family` precedence: windows → gpu → build → general - Windows VMs get the JIT startup script via the `windows-startup-script-ps1` metadata key (`run.cmd --jitconfig` + guaranteed shutdown in `finally`); Linux families unchanged - +8 unit tests (41 pass): family routing, advertised labels, per-family startup metadata key, TERMINATE scheduling ### Image bake - `runner-image-provision.ps1`: NVIDIA **GRID** driver (WDDM mode — the datacenter driver runs T4 in TCC mode with no DirectX, which breaks DirectML), with TCC→WDDM switch + bounded reboot retries; Python 3.12 (torch-directml has no 3.13 wheels); Git, FFmpeg, system-wide Poetry, actions-runner win-x64; lean DirectML model set at `C:\audio-separator-models`. Idempotent via phase markers (startup scripts re-run every boot); emits the same READY/FAILED serial-console markers as the Linux provisioner so the existing wait step works unchanged. - `build-runner-images.yml`: `gpu-windows` variant (windows-cloud/`windows-2022` base, per-variant image + startup-metadata flags), included in monthly "all" builds - `docs/EPHEMERAL-GHA-RUNNERS.md`: fourth image family + label-routing rules ## Deploy sequence (operator) 1. **Before merge: `pulumi up` locally** (runner-manager function redeploys with the new family — my ADC is read-only so I could not run it) 2. Merge, then bake the first image: `gh workflow run build-runner-images.yml -f variants=gpu-windows` 3. First consumer job (`windows-directml`, `runs-on: [self-hosted, windows, gpu]`) lands in python-audio-separator next — it doubles as the verification job The companion label fix (`runs-on: [self-hosted, linux, gpu]` on existing jobs, so Windows runners can't steal Linux jobs) is already in nomadkaraoke/python-audio-separator#294. ## Testing - `test_ephemeral.py`: 41/41 pass - Workflow YAML validated; CodeRabbit local review run, findings applied (windows-2022 family name, bounded WDDM retry, reboot on installer exit 1, atomic downloads) - Real-world validation happens at first bake + first `windows-directml` job (next PR) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
6f86b3d901 |
test(e2e): rewrite tenant daily E2E as a faithful frontend journey (#873)
## Why The daily tenant E2E (`scripts/e2e/tenant_e2e.py`) drove the whole flow via **direct backend API calls**, bypassing the frontend. Two problems: 1. **Not representative** — it never exercised the tenant portal UI a real operator uses. 2. **Intermittent stuck-render orphans** (Run #31 vocalstar, #32 singa) — because it never loaded the lyrics-review page, it never fired `encoding-worker/warmup`, so the encoder was cold when the render started and the job orphaned in `rendering_video` (no recovery). Root-caused this session; the fix is to make the test faithful, which fires the warmup a real user fires. ## What Replaces `tenant_e2e.py` with **`frontend/e2e/production/tenant-happy-path.spec.ts`** — a Playwright journey mirroring `happy-path-real-user.spec.ts`, run per-tenant via the existing `e2e-tenant-daily.yml` matrix (vocalstar, singa; `max-parallel: 1`): login (real magic-link UI) → submit track (tenant form + real audio upload) → wait for transcription → **open review UI (fires warmup)** → approve → wait for render → assert tenant distribution (Dropbox present, no YouTube, downloads, `is_private`) → cleanup. - **Tenant auth**: added `inbox.testmail.app` to both tenants' `allowed_email_domains` (setup scripts + live GCS config via `scripts/e2e/update_tenant_allowlist.py`) so the test signs in through the real magic-link UI. - **Test audio**: short 60s clips fetched from private GCS in CI (`scripts/e2e/fetch_test_audio.sh`) — fast, reliable uploads and quick renders. - Workflow reworked to Node/Playwright; `tenant_e2e.py` deleted; version `0.190.3 → 0.190.4`. ## Findings surfaced (validating the exercise) - **Browser upload was CORS-blocked in Playwright** by the shared config's global `x-playwright-test` header (it made the GCS signed-URL PUT preflight request a header the bucket's CORS doesn't allow). Verified the same PUT succeeds in a real browser — a **test-harness artifact, not a product bug**. Worked around by stripping the header for `storage.googleapis.com` requests. (Note: any prod E2E doing a browser signed-URL upload is affected by this global header.) ## Verification Both tenants run **green end-to-end against prod** locally (login → submit → review → render → distribution; render completed without orphaning). Reworked workflow dispatched on this branch to confirm CI wiring (Node setup + private-audio fetch + secrets). Test-only + CI + tenant-config change. No product code. 🤖 Generated with [Claude Code](https://claude.com/claude-code) @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
bfa375639b |
ci: publish wheel-only to PyPI (fix 10 GB storage cap) (#851)
## Problem Every `poetry publish` on merge to `main` was failing with: ``` HTTP Error 400: Project size too large. Limit project 'karaoke-gen' total size 10 GB. ``` The PyPI project had grown to **10.711 GB across 444 releases**, over the 10 GB cap. ## Root cause Since the i18n initiative (**v0.172.1, 2026-04-23**), `next build` pre-renders the app into **33 locale directories** (~112 MB uncompressed), and both the wheel **and** the sdist bundle this static export. Per-release cost jumped from ~18 MB to ~104 MB (53.7 MB wheel + 50.2 MB sdist). 57 fat releases = >5.8 GB of the 10.7 GB total. ## Fix (this PR): publish wheel-only The sdist is dead weight — we ship a universal `py3-none-any` wheel, pip always installs from it, and nothing builds karaoke-gen from source (the GCE encoding worker pulls the wheel from GCS, not PyPI). - `poetry build --format wheel` in both the package-test and package-publish jobs (no sdist built) - drop `dist/*.tar.gz` from the GitHub release attachments - bump `0.187.4 → 0.187.5` **Per-release PyPI cost: 104 MB → 54 MB.** The wheel is unchanged — it still bundles the frontend the CLI local-review server reads at runtime (verified: built wheel contains all 3575 `out/` entries + entry points). ## Companion one-time cleanup (already done, not in this diff) Deleted **42 old fat releases** (`0.172.1`–`0.182.2`, ~4.35 GB) via the PyPI web UI, keeping the 15 most recent fat releases (`0.183.0`–`0.187.2`) and all 387 small historical releases (`≤0.171.x`). Project is now **~6.36 GB** (3.64 GB headroom). Nothing internal pins old PyPI versions, so blast radius was zero. ## Testing - `poetry build --format wheel` → `dist/` contains only the 53.7 MB wheel (no tar.gz), wheel has all `out/` assets + 3 console entry points. - `ci.yml` validated (parses, no remaining sdist/tar.gz dependencies). - No application code changed; full suite runs in CI on this PR. - The merge itself is the live verification that `poetry publish` succeeds (publishes 0.187.5 wheel-only). @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
715c796bfb |
fix(dr): correct backup freshness monitor limit + scheduler deadline (weekly-S3 Firestore regressions) (#844)
## Summary Fixes two DR-backup alerting regressions introduced by PR #823 (Jun-14 cost reduction), which switched the Firestore S3 upload from **nightly → weekly (Sundays)** to cut cross-cloud egress. Both surfaced as Discord alerts on 2026-06-17/18; backups themselves were never actually broken. ### 1. False "🚨 DR backup is stale" alert (fires every Tue–Sat) The off-platform freshness monitor (`dr-backup-freshness.yml`) checks the **S3** copy of `firestore/` against a **36h** limit — set back when Firestore uploaded to S3 nightly. Since #823, Firestore ships to S3 only weekly (like BigQuery, which correctly uses 192h), so the S3 copy is >36h old from Tuesday onward **by design**. Monitor run history confirms: 06-14 Sun ✅ → 06-15 Mon ✅ (~34h) → 06-16 Tue ❌ → 06-17 Wed ❌, repeating weekly. **Fix:** Firestore limit `36h → 192h` (≈8 days), matching its actual weekly off-site cadence. The nightly GCS-staging export (1-day local restore point) is unaffected. ### 2. Spurious "Path already exists" FAILED backup report Cloud Scheduler had no `attempt_deadline` (default **180s**), but the Firestore export runs for minutes. Scheduler timed out the HTTP call and retried (`retry_count=2`) while the original invocation kept running to success; the retry then collided on the already-created `firestore/<date>/` export path → `400 Path already exists`. **Fix:** set `attempt_deadline="1800s"` (Cloud Scheduler max) and align the Cloud **Function** `timeout_seconds` 3600 → 1800, so the function can't outrun the scheduler's wait and reopen the same collision window (per CodeRabbit). Also refreshes `docs/DISASTER-RECOVERY.md`: Firestore off-site RPO is 7 days (S3) / 24h local (GCS), and the freshness-monitor section now documents the per-prefix S3 cadence so this can't regress again. ## Changes - `.github/workflows/dr-backup-freshness.yml` — Firestore freshness limit 36h → 192h + explanatory comment - `infrastructure/modules/backup.py` — scheduler `attempt_deadline="1800s"`; function `timeout_seconds` 3600 → 1800 - `docs/DISASTER-RECOVERY.md` — RPO table + freshness-monitor cadence docs ## Testing - Backup function unit tests: 13 passed (no function code changed) - YAML + embedded-Python + Pulumi module all validate/compile - CodeRabbit: 0 findings (1 major fixed: function/scheduler timeout mismatch) - **`pulumi up` applied to prod** (clean diff: 2 updated, 265 unchanged). Verified live: scheduler `attemptDeadline=1800s`, function `timeoutSeconds=1800`. Merging keeps IaC in sync (CI re-applies as no-op). Infra/CI + docs only; no application code (no version bump). @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
2002b5eddf |
ci(tenant-e2e): move daily run to ~8pm US Eastern (#837)
## Summary - Moves the tenant-portal daily E2E from **07:37 UTC** (~3:37am ET) to **00:07 UTC** (~8pm US Eastern — 8:07pm EDT / 7:07pm EST), so the soak runs land in the evening when they can be watched / manually tested alongside. - Cron is fixed-UTC, so the local time shifts 1h across DST (noted in the comment). Minute kept off the :00 mark. CI-config only (one-line cron change). @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
814ac50aca |
fix(encoder): fail-safe the active-jobs guards so a busy VM isn't stopped mid-render (#835)
## Summary
- The GCE encoder VMs have two stop paths that guard against killing a
busy worker by checking `/health`'s `active_jobs` — but **both fail
OPEN**, treating an unreachable/slow `/health` as "0 active jobs" and
stopping the VM anyway.
- Under load a busy encoder runs a 4K ffmpeg on all 32 cores and shares
uvicorn with the encode, so `/health` can miss its window *while the VM
is hard at work*. Combined with blue/green deploy churn (every merge
cycles the VMs) + the 5-min idle check, this stopped VMs **mid-render**,
orphaning the in-memory job → backend polls got 404 → "lost contact with
worker ... not found".
- **Incident 2026-06-15:** 12 occurrences, all self-inflicted by rapid
PR merges (#831–#834) during the tenant E2E retries; **0 in the prior
48h**. Not tenant-specific; affects consumer renders too in the same
deploy/idle-during-render window.
## Changes
- **`infrastructure/functions/encoding_worker_idle/main.py`** —
`check_active_jobs()` now returns `None` (not `0`) on any failure, with
3 retries. The idle loop keeps a VM alive for the cycle when the count
is unconfirmed or the VM has no reachable IP; it only stops on a
**confirmed** `active_jobs == 0`. A genuinely idle VM answers `/health`
fast and is still reclaimed next run.
- **`.github/workflows/ci.yml`** ("Drain and stop old primary") — new
`probe_active_jobs` helper distinguishes a real integer from
`"unknown"`; the drain loop only stops on a definitive `0`, or after a
bounded **20-min** timeout (was 10) so a render finishes comfortably
while a wedged worker still can't block the deploy forever. Dropped an
unused `API_KEY` fetch.
- **`docs/LESSONS-LEARNED.md`** — "Is It Busy?" guards must fail safe,
not fail open.
## Testing
- [x] Idle-shutdown unit tests pass (24, incl. new fail-safe cases +
direct `check_active_jobs` contract tests)
- [x] Bash `probe_active_jobs` classification unit-checked (curl-fail /
missing-field / garbage → `unknown`; only real int → number)
- [x] `ci.yml` YAML + actionlint clean (no new findings in the changed
step)
- [x] CodeRabbit CLI review: 0 findings
- No backend/frontend wheel code changed → no version bump (avoids an
unnecessary encoder redeploy)
## Review
- [x] Local CodeRabbit review completed (0 findings)
## Deploy note
The idle Cloud Function deploys via Pulumi (`infrastructure/`); the
`ci.yml` change takes effect on the next workflow run. Per repo
convention, run `pulumi up` locally before merging.
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
460f18d47d |
fix(ci): run tenant E2E matrix sequentially (#833)
@coderabbitai ignore
The daily tenant E2E ran both tenants concurrently and overwhelmed the
single shared GCE encoder ("Encoding job lost contact with worker... not
found"). Both tenants pass individually (verified). Serialize the matrix
(`max-parallel: 1`) so the daily run doesn't self-inflict encoder
contention. CI-config only.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
defaf85230 |
fix(ci): tenant E2E workflow — drop invalid matrix-context job 'if' (#832)
@coderabbitai ignore
The daily tenant E2E workflow used the `matrix` context in a job-level
`if`, which GitHub Actions rejects ("Unrecognized named-value:
'matrix'") — so the workflow (incl. the scheduled run) failed to parse.
Removed the per-tenant dispatch filter; the workflow always runs both
tenants (the intended daily behavior). `workflow_dispatch` takes no
inputs.
CI/workflow-config only.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
40c7960854 |
fix(tenant): stage instrumental for the GCE encoder + daily tenant E2E (#828)
@coderabbitai ignore ## Final render blocker (bug #8) With #824/#825/#826/#827, tenant jobs now render the karaoke video — but the GCE encoder failed with **"No instrumental audio found"**. **Root cause:** the user-supplied instrumental lives under `uploads/{job}/audio/`, but the encoder only pulls input from `jobs/{job}/` (`input_gcs_path`) and locates the instrumental via `find_file("*existing_instrumental*", "*Instrumental User*")`. On top of that, the running encoder VM (`encoding-worker-b`) boots a **2026-01-23 image** that predates the encoder's own `existing_instrumental` config-download path (added 2026-03-04), so it could never fetch it from `uploads/` either. **Fix (image-agnostic — no risky shared-VM recreation, no consumer impact):** `_encode_via_gce` server-side copies the instrumental into `jobs/{job_id}/existing_instrumental.<ext>` before submitting. The encoder downloads `jobs/{job}/` and its **recursive** `find_file` then locates it on any image version. Added `StorageService.copy_blob` + unit test. > Note: the stale encoder VM image is a separate infra item — the `encoding-worker` VMs should be recreated from the image family's newest image (which has 3 months of encoder fixes). Tracked for a Pulumi pass; not required for this fix. ## Daily tenant E2E (second ask) - `scripts/e2e/tenant_e2e.py` — full per-tenant prod health check: submit → approve review → render → assert (completes, Dropbox link present, no YouTube, downloads available) → clean up job + uploads. - `.github/workflows/e2e-tenant-daily.yml` — daily matrix (vocalstar, singa), WIF auth, Discord + email on failure. - `docs/archive/2026-06-15-tenant-portals-e2e.md` — the full story (8 bugs, all fixed). ## Testing - `copy_blob` unit test; storage suite green (20). - Full tenant E2E re-run to completion after deploy. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
39fb93653f |
fix(auto-correct): switch active model from Fable 5 to Opus 4.8 (#822)
## Summary Claude **Fable 5** (`claude-fable-5`) is no longer available on the Anthropic API. Verified live against `api.anthropic.com`: ``` 404 not_found_error: "Claude Fable 5 is not available. Please use Opus 4.8. Learn more: https://www.anthropic.com/news/fable-mythos-access" ``` `claude-opus-4-8` responds normally and is the API's own prescribed replacement. Opus 4.8 was also ≈ Gemini 3.1 Pro in our 30-job offline eval, so switching to it preserves the two-model compare quality. ## Changes - **`.github/workflows/ci.yml`** (load-bearing): `AUTO_CORRECT_MODEL=claude-opus-4-8` and `AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview`. Compare mode now runs **Opus 4.8 + Gemini 3.1 Pro** instead of Fable + Gemini. - **`scripts/measure_autocorrect_cost.py`**: default models + docstring example → Opus, so the cost tool measures what prod runs. - **`docs/API.md`**: example auto-correct response reflects Opus. - **`pyproject.toml`**: `0.182.1` → `0.182.2`. ## Re-enable path Fable is **disabled, not deleted** — its pricing entry in `pricing.py` and all Fable unit tests are intentionally left intact. If access returns, flip it back by reverting the two env-var values in `ci.yml`. ## Testing - Auto-correct suite: 73 passed (`backend/tests/services/auto_correct/` + `test_proactive_auto_correct.py`). - Live API probe confirmed Fable 404s and Opus 4.8 works. - CodeRabbit (uncommitted): 0 findings. @coderabbitai ignore Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
a7bb338703 |
feat(auto-correct): enable proactive pre-generation (runs on API service) (#818)
## Summary Enables the proactive pre-generation that PR #816 intended but couldn't deploy (the lyrics-job `--update-secrets` crashed on Cloud Run secret aliases). Per the chosen approach, the work now runs **on the API service** — which already has a working `ANTHROPIC_API_KEY` + `AUTO_CORRECT_COMPARE_MODELS` — instead of the lyrics job, sidestepping the secret-alias problem entirely. ## How it works 1. Lyrics worker finishes transcription → after `mark_lyrics_complete`, fires `WorkerService.trigger_auto_correct(job_id)` — a direct, awaited HTTP call (no Cloud Tasks / new queue). Best-effort: never blocks or fails the job. 2. New internal endpoint `POST /api/internal/workers/auto-correct` (admin auth) runs `process_proactive_auto_correct(job_id)` synchronously on the service: loads `corrections.json`, runs the multi-model `suggest()` with default settings (cache-aligned with the UI), caches it. Gated by `AUTO_CORRECT_PROACTIVE_ENABLED`, 180s timeout, swallows all errors. 3. `ci.yml`: `AUTO_CORRECT_PROACTIVE_ENABLED=true` added to the **service** env (deploys cleanly — the broken lyrics-job secret path is gone). Result: when a reviewer opens the lyrics UI, the auto-run-on-load request is an instant cache hit. ## Testing - Backend: **3462 passing** (emulator excluded), incl. rewritten `test_proactive_auto_correct.py` covering the service worker (flag gating, no-references skip, happy path multi-model, error-swallow) and the lyrics-worker trigger (fires / swallows errors). - CodeRabbit: trace-context propagation + defensive endpoint guard applied. ## Notes - Failure modes unchanged & graceful: flaky AI / out of credits / timeout → endpoint returns a status, job proceeds; UI falls back to on-demand generation. - Version bumped 0.180.0 → 0.181.0. @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
32dfd9fbdc |
fix(ci): revert lyrics-transcription-job to image-only deploy (#817)
## Why PR #816's deploy **failed** at the "Update Cloud Run Jobs" step: ``` ERROR: gcloud crashed (ValueError): Invalid secret path 'projects/nomadkaraoke/secrets/audioshake-api-key' in annotation ``` The `--update-secrets ANTHROPIC_API_KEY=…` I added to `lyrics-transcription-job` made gcloud re-validate the job's *existing* secrets, which are stored via Cloud Run **secret aliases** (`secret-alias-N`) in a format `--update-secrets` rejects. That crash stranded **lyrics + audio jobs on the previous image** (the API service deployed fine and is healthy; the video-encoding-job updated fine). ## Fix Revert the lyrics-job step to **image-only** (proven to work — same form the video/audio job steps use). This makes deploys succeed and brings lyrics + audio jobs onto the current image, so prod is consistent again. Proactive auto-correct ships dormant: the worker's `_run_proactive_auto_correct()` is gated by `AUTO_CORRECT_PROACTIVE_ENABLED`, which is unset, so it returns early (no-op, zero risk). Wiring that env + the Anthropic secret onto the job via an alias-safe method is a tracked follow-up. ## Testing - No code change; CI-only. The reverted step matches the working video-encoding-job step exactly. @coderabbitai ignore Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
364e4ebd5f |
feat(auto-correct): proactive multi-model suggestions + cost logging + de-AI-ified review UI (#816)
## Summary Makes AI lyrics auto-correction run **automatically on every job** (multi-model), so suggestions are cached and ready the moment the reviewer opens the lyrics UI — plus token/cost instrumentation and a UI cleanup that removes all "AI"/"model" wording. Measured cost first (`scripts/measure_autocorrect_cost.py`): **~$0.13/track** multi-model on normal songs — cheap enough to run proactively. ## Changes **Cost instrumentation** - Capture per-model `usage` from Anthropic + Gemini; log greppable `auto-correct usage` / `auto-correct cost … total_est_cost_usd=…` lines from `suggest()`. - `backend/services/auto_correct/pricing.py` (Anthropic rates authoritative; Gemini estimated) + `scripts/measure_autocorrect_cost.py` offline harness. **Proactive generation (every job)** - `lyrics_worker._run_proactive_auto_correct()` runs the multi-model path after `mark_lyrics_complete` (downstream already triggered → non-blocking), gated by `AUTO_CORRECT_PROACTIVE_ENABLED`, bounded by a 180s timeout, and **swallows every error** — it never blocks or fails the karaoke job (flaky AI / out of credits / timeout all degrade gracefully). - Cache-key aligned with the UI request, so the review page's on-load call is an instant cache hit (no double spend). - `ci.yml`: wires `AUTO_CORRECT_*` env + the `anthropic-api-key` secret onto `lyrics-transcription-job` (same SA as the API service — no IAM change). **Review UI** - Always multi-model (removed the model-selection toggle); button renamed **"Auto-correct"**; stripped model/consensus/cached attribution badges; reworded strings to drop "AI"/"model" (translated to all 32 locales). - Auto-runs once on review load so suggestions are ready without a click; the button stays for the paste-references-later flow. ## Testing - Backend: **3460 passed** (`backend/tests/`, emulator excluded) — incl. new `test_pricing.py` + `test_proactive_auto_correct.py` (gating, graceful failure, cache alignment). - Frontend: **1006 jest tests pass**; type-clean; 33-locale key parity verified. ## Notes / follow-ups - Proactive activates on the **next deploy** (the lyrics-job env/secret apply via this PR's ci.yml on merge). - Left "AI" wording in two *separate* features untouched (different subsystems): `lyricsReview.agenticMetrics` and `lyricsReview.modals.correctionAnnotation` — flagged for a separate decision. - The production E2E spec's click-to-open flow may want a tweak now that suggestions auto-run on load. @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
e4aad66a06 |
feat: Fable 5 default + multi-model compare for AI auto-correct (v0.178.0) (#811)
@coderabbitai ignore ## Summary Follow-up to #809, per Andrew's direction: switch the auto-correct default to the eval's best model, and add an opt-in **multi-model compare mode** that queries several models in parallel, dedupes identical suggestions with consensus counts, and lets the reviewer pick between conflicting variants. ## Changes **Fable 5 as production default** - New Anthropic provider path in `AutoCorrectService` (structured outputs + adaptive thinking — the exact configuration the 30-job eval used). Eval rationale: strict precision 0.62 vs 0.56, strict recall 0.51 vs 0.46, 27s vs 35s median latency vs Gemini 3.1 Pro. - `anthropic-api-key` secret: container added to Pulumi (`infrastructure/modules/secrets.py`, **already applied** — preview was exactly +1 create after pinning pulumi-gcp to 9.22.0 to avoid provider-upgrade VM replaces), value added and verified against the live API. - Cloud Run deploy: `AUTO_CORRECT_MODEL=claude-fable-5`, `AUTO_CORRECT_COMPARE_MODELS=claude-fable-5;gemini-3.1-pro-preview`, `ANTHROPIC_API_KEY` secret mapping. - No silent provider fallback: missing key → clear 502. - `anthropic >=0.109` added as a direct dependency (lock updated). **Multi-model compare mode** - `compare_models` setting → all configured models queried in parallel; identical suggestions deduped with `consensus`/`total_models` + `models` attribution; overlapping disagreements share a `conflict_group`. - UI: "Compare multiple AI models" toggle in the run modal; consensus badges ("2/2 models") and variant badges in the panel; accepting one variant of a conflict group auto-rejects its siblings; accept-all picks the highest-consensus winner per group. - Partial model failure (call error or malformed output) degrades to a response warning; only all-fail returns 502. - EditLog decisions now record models/consensus/conflict_group — per-model accept-rate data accrues in prod. **Cross-provider bug fixed**: google-genai mutates `response_schema` dicts in place (injects `property_ordering`), which the Anthropic API rejects — found via real-call smoke test of compare mode; schemas now deep-copied per call, with a regression test. ## Testing - 55 backend auto-correct tests (incl. 10 new multi-model merge/conflict/degradation tests + schema-pollution regression) and frontend conflict-util tests; full suite green (3,426 backend unit + 103 emulator + 1,004 frontend) - Real-call smoke tests: single-model Fable (glory→chlorine, 0.98, 5.6s) and compare mode (Fable + Gemini parallel, merged to one 2/2-consensus suggestion, 5.8s) - Secret value verified end-to-end against the Anthropic API - CodeRabbit CLI: 12 findings — 5 fixed, 5 skipped with reasons, 2 in files from another merged PR 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
eb1cc7b94f |
fix(encoding,ci): silence self-healing warmup 503 alert + robust E2E result check (#790)
## Summary
Two unrelated production alert-noise fixes, prompted by two false-alarm
Discord alerts on 2026-05-24:
- **Encoding worker 503 → WARNING.** A primary-VM warmup hitting `503
SERVICE_UNAVAILABLE` (or capacity exhaustion) is self-healing — the
encoding flow's `ensure_any_running()` falls back to an alternate-zone
worker and the job completes (verified live on job `a40f3024`). It no
longer logs at ERROR, so it stays below the error monitor's
`severity>=ERROR` filter and stops paging Discord for a non-incident.
- **E2E daily test result check.** Both stages now derive pass/fail from
Playwright's real exit code instead of grepping the log for `"failed"`.
The old check matched the word "failed" inside a benign retry warning
(`goto attempt 1/3 failed`) and reported failure on a run where the job
completed and Playwright printed `1 passed`.
## Changes
- `backend/api/routes/encoding_worker.py` — catch
`EncodingWorkerStartError` in `/warmup` and log at WARNING with a clear
fallback message; genuine unexpected errors still log at ERROR.
- `.github/workflows/e2e-daily.yml` — capture `${PIPESTATUS[0]}` (the
pipe to `tee` was masking Playwright's exit code as 0) and gate the
result on it, for both Stage 1 and Stage 2.
- `backend/tests/test_encoding_worker_routes.py` — 3 regression tests:
503 start failure → WARNING, capacity error → WARNING, unexpected error
→ still ERROR.
- `docs/TROUBLESHOOTING.md` — note that a WARNING-level warmup 503 is
benign/self-healing.
- `pyproject.toml` — bump 0.174.11 → 0.174.12.
## Testing
- [x] `pytest backend/tests/test_encoding_worker_routes.py
backend/tests/test_encoding_worker_manager.py` — 46 passed
- [x] YAML validated
- [x] CodeRabbit CLI review — 0 findings
## Review
- [x] Local CodeRabbit review completed
- [x] Issues addressed
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
a45798bb4d |
fix: remove SendGrid leftovers; consolidate on Postmark (#779)
## Summary - Fixes the failing e2e-daily notification job ([run #25983930960](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/25983930960/job/76378786060)) which still used \`smtp.sendgrid.net\` — SendGrid was cancelled ~3 weeks ago - Drops the \`sendgrid\` Python dep, removes \`SendGridEmailProvider\`, simplifies provider selection in \`email_service.py\` - Removes \`SENDGRID_API_KEY\` env bindings from Pulumi (gdrive-validator Cloud Function + video Cloud Run Job) and from ci.yml's Cloud Run \`--set-secrets\` - \`sendgrid-api-key\` Secret resource intentionally kept in \`infrastructure/modules/secrets.py\` with a "delete manually" marker so an unrelated \`pulumi up\` doesn't destroy the live secret + versions - Version bumped 0.174.10 → 0.174.11 ## Pulumi applied \`pulumi up --target\` already run locally with the two affected resources (video-encoding-job + gdrive-validator-function). PR #776's runner-manager state intentionally untouched. @coderabbitai ignore ## Test plan - [x] Full backend test suite (3178 tests) passes locally - [x] CodeRabbit local review: no findings - [x] Pulumi up applied locally (clean) - [ ] CI green on this PR - [ ] After merge: e2e-daily.yml notification job should pass on next scheduled run - [ ] Verify gdrive-validator function still emails on next post-job trigger 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
659ba1ef7b |
fix(runner-images): image-create disk name + GPU python 3.13.2 (#770)
## Summary Two follow-up fixes after PR #769's visibility update made it possible to see exactly what was failing. ## What broke 1. **general/build PROVISIONED successfully** (READY marker written at 01:04 and 01:02), then the workflow's \`Create image\` step died with: \`\`\` ERROR: (gcloud.compute.images.create) Invalid value for [--source-disk-zone]: You cannot specify [--source-disk-zone] unless you are specifying [--source-disk]. \`\`\` The disk-name extraction format string returned empty. I'm using auto-named boot disks (same as VM name), so just use \`\$VM\` directly. 2. **GPU got further than before** — phase: python 3.13 — but \`get-pip.py | python3.13\` exited non-zero at line 197. PR #768's workaround for the 3.13.0 install-time ensurepip bug introduced a new failure on the bootstrap. Switch to **3.13.2** which fixes the underlying bug, restore \`--with-ensurepip=install\`, drop the bootstrap. Also drop \`--enable-optimizations\` (PGO runs full test suite, can produce half-broken binaries on transient test failures). ## Plus Wait step's failure-context dump now captures **40 lines BEFORE** the FAILED marker (not just 5 after) so the actual error output is in the GHA log. ## Test plan - [x] bash + yaml syntax clean - [ ] Re-trigger build after merge. Expected outcome: all 3 variants build successfully end-to-end and produce images in the \`gha-runner-{general,build,gpu}\` families. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
ce270052ff |
fix(runner-images): stream provisioner log to GCE serial console (eliminate SSH dependency) (#769)
## Problem
Three previous iterations of the image-build workflow failed silently.
Every diagnostic channel depended on \`gcloud compute ssh
--tunnel-through-iap\` and IAP tunneling was unreliable enough that:
- The wait step both false-positived ("Image ready" at 4 min on a 25-min
provisioner) AND false-timed-out (no output for 75 min)
- Manual SSH for debugging was equally broken — \`Connection closed by
UNKNOWN port 65535\` repeatedly
Net effect: 25–60 minute iteration loops with no actual visibility into
the provisioner's state.
## Fix
Eliminate SSH from the diagnostic path entirely:
1. **Provisioner streams to /dev/ttyS0** (GCE serial console). Readable
via \`gcloud compute instances get-serial-port-output --port=1\` with
zero SSH/IAP dependency.
2. **ERR trap + phase checkpoints.** Any non-zero exit prints \`###
runner-image-provision FAILED rc=N line=L cmd=...\` to the console. A
\`ck()\` helper marks each major phase (apt base, docker, python,
node+java, ffmpeg, poetry+gcloud, runner user, runner binary, build
pre-pull, gpu models, tool cache, cleanup, READY).
3. **Workflow wait step polls serial console.** Looks for
\`runner-image: READY:\` for success and \`runner-image-provision
FAILED\` for fast-fail. Also streams new console lines into the GHA log
on every poll so the operator sees live progress.
## Test plan
- [x] \`bash -n\` + yaml lint clean
- [ ] Re-trigger \`build-runner-images.yml\` after merge. When a variant
dies, we'll see exactly which phase failed.
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
7f46bbc0af |
fix(runner-images): trust file content not IAP-tunnel ssh exit codes (#767)
## Summary Hotfix for the build-runner-images workflow, observed failing on the first real run after PR #766's variant-resolution fix. ## Root cause Two related defects in the **Wait for provisioning to complete** step: 1. **False-positive readiness.** The general-image job detected `test -f /opt/runner-image-ready` at attempt 8 (~4 min in) on a provisioner that takes 25+ min. \`gcloud compute ssh --command='test -f ...'\` returned exit 0 even though the remote test had nothing to test against. Most likely an IAP-tunnel race where the SSH session closes before the remote command completes, and the local exit code defaults to 0. 2. **Diagnostic SSH allowed to fail the step.** After "marker detected," a second SSH was run to `cat` the file. That one hit a real IAP error (`destination read failed`) and `set -e` killed the step. So even if the first marker check were trustworthy, this second hop would still flake the build out. ## Fix - Use `cat` instead of `test -f` for readiness check; require the output to start with a 4-digit year (the provisioner writes an ISO-8601 timestamp). Empty stdout from a flaky SSH = "not ready, retry." - Drop the second SSH — fold its diagnostic value into the cat above. - Belt-and-suspenders `2>&1 || true` on the timeout-path diagnostic. ## Test plan - [x] YAML lint clean - [ ] Re-trigger \`build-runner-images.yml\` after merge @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
bf5c9abdd7 |
feat(runners): ephemeral GHA runner dispatcher behind RUNNER_MODE flag (#765)
## Summary
- Implements Phases 1, 2, and 5 of the ephemeral GHA runner plan
([`docs/archive/2026-05-16-ephemeral-gha-runners-plan.md`](docs/archive/2026-05-16-ephemeral-gha-runners-plan.md)
at the workspace root). Target saving when fully cut over: **~\$220/mo**
(eliminates 7×200GB always-billed pd-ssd boot disks).
- **Default behaviour unchanged** — code lands with
`RUNNER_MODE=legacy`. Flipping to `ephemeral` is a Pulumi config +
targeted update, reversible in ~2 minutes.
- Operator runbook for the cutover at
[`docs/EPHEMERAL-GHA-RUNNERS.md`](docs/EPHEMERAL-GHA-RUNNERS.md)
including verification steps, rollback, and known gotchas.
## What's in this PR
**Phase 1 — image build infrastructure**
- `infrastructure/scripts/runner-image-provision.sh` — unified
provisioner with `general` / `build` / `gpu` variants (extracts the
existing `github_runner.sh` and `github_runner_gpu.sh` logic so it runs
at image-build time, not per-VM boot).
- `.github/workflows/build-runner-images.yml` — monthly cron + manual
trigger. Builds via temporary GCE VMs, snapshots to GCE image families
`gha-runner-{general,build,gpu}`, deprecates all but the newest 3 per
family.
**Phase 2 — dispatcher rewrite (behind a flag)**
- `infrastructure/functions/runner_manager/ephemeral.py` — picks image
family from job labels, mints a GitHub JIT runner config,
`compute.instances.insert` with auto-delete boot disk, falls back to
`us-east4-c` on `ZONE_RESOURCE_POOL_EXHAUSTED`. Orphan-cleanup deletes
VMs whose runner registration is gone or whose uptime exceeded 2h, and
de-registers zombie runners.
- `infrastructure/functions/runner_manager/main.py` — routes on
`RUNNER_MODE`. Legacy path untouched.
- `infrastructure/modules/runner_manager.py` — exposes `RUNNER_MODE` via
Pulumi config (`karaoke-gen-infrastructure:runnerMode`).
- 20 new unit tests in `test_ephemeral.py` (label resolution, JIT mint,
zone fallback, orphan reconciliation, zombie cleanup).
**Phase 5 — observability**
- 2 log-based metrics (`runner_dispatcher/create_failures`,
`runner_dispatcher/orphan_kills`).
- 2 alert policies: any create failure in 10 min; any ephemeral VM
uptime > 2h (orphan cleanup escape).
## Not in this PR (handed off)
- Triggering the image-build workflow for the first time (needs branch
merged first).
- `pulumi up` — `GOOGLE_APPLICATION_CREDENTIALS` points at
`claude-readonly@` per the workspace's operational guardrail; couldn't
apply from this session. Targeted apply commands are in the runbook.
Note that this repo's CI doesn't auto-apply Pulumi (see comment in
`ci.yml`).
- Phase 3 cutover (`pulumi config set runnerMode ephemeral` + test PR +
1-week soak).
- Phase 4 destructive decommission of the 7 legacy VMs (requires soak
first).
## Test plan
- [ ] `cd infrastructure/functions/runner_manager && pytest -v` — 20/20
new tests pass; 25/26 legacy tests pass (1 pre-existing failure
documented in the runbook).
- [ ] `cd infrastructure && pulumi preview --diff` — expect 4 resource
changes from this PR + 5 creates (log metrics + alerts).
- [ ] `pulumi up --target ...:runner-manager-source --target
...:runner-manager-function --target ...:runner-dispatcher-failures
--target ...:runner-dispatcher-orphan-kills --target
...:runner-dispatcher-failures-alert --target
...:runner-dispatcher-long-lived-vm-alert` — applies dispatcher +
monitoring.
- [ ] `gh workflow run build-runner-images.yml -f variants=general` —
produces first image, ~25 min.
- [ ] Smoke test launching a one-off VM from
`image-family=gha-runner-general` (runbook step).
- [ ] Repeat image build for `build` and `gpu` variants.
- [ ] Phase 3 cutover when ready (see runbook).
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
4d489c18f7 |
fix(iac): switch encoding-worker fallback us-central1-f → -b (capacity) (#749)
## Summary Two related fixes wrapped into one PR: ### 1. Switch fallback zone us-central1-f → -b The fallback VMs from #748 originally targeted `us-central1-a` and `us-central1-f`. `pulumi up` provisioned the -a VM cleanly but **failed in -f** with `ZONE_RESOURCE_POOL_EXHAUSTED` on multiple retries — the same capacity exhaustion the fallback is meant to mitigate. -b has consistent capacity for the `c4d-highcpu-32` family. ### 2. Mount ENCODING_WORKER_FALLBACK_VMS in Cloud Run Phase 3 of #748 needs an env var on the `karaoke-backend` Cloud Run service to enable multi-zone failover. The value is JSON which contains commas, so gcloud's comma-delimited `--set-env-vars` flag won't work. Stored as a Secret Manager secret instead and wired through `--set-secrets`. ## Already applied (out-of-band) | Resource | Action | Result | |---|---|---| | `encoding-worker-fallback-b` (VM, us-central1-b) | created via pulumi up | TERMINATED, IP `35.193.127.24` | | `encoding-worker-fallback-ip-b` | created via pulumi up | static IP | | `encoding-worker-fallback-ip-f` | deleted via pulumi up | orphan from earlier failed up | | `encoding-worker-fallback-vms` (secret) | created via REST API + Pulumi-imported | version 1 holds the JSON config | | `karaoke-backend` Cloud Run service | PATCHed | revision `00765-jcc` mounts the secret as env var, 100% traffic | This commit syncs the IaC source + CI workflow to match deployed reality so future `pulumi up` and CI deploys are no-ops / durable respectively. ## Current encoding-worker topology ``` encoding-worker-a us-central1-c 34.57.78.246 (TERMINATED, primary blue) encoding-worker-b us-central1-c 34.10.189.118 (TERMINATED, primary green) encoding-worker-fallback-a us-central1-a 34.55.231.54 (TERMINATED, capacity fallback) encoding-worker-fallback-b us-central1-b 35.193.127.24 (TERMINATED, capacity fallback) ``` Multi-zone failover is **live in prod right now** via the patched Cloud Run revision; merging this PR makes it durable across future CI deploys. ## Test plan - [x] `pulumi preview` shows clean diff (only reflects deployed reality) - [x] `pulumi up` succeeded; fallback VMs verified `TERMINATED` in -a and -b - [x] Secret Manager: `encoding-worker-fallback-vms/versions/latest` returns the expected JSON - [x] Cloud Run: revision 00765-jcc has `ENCODING_WORKER_FALLBACK_VMS` mounted from the secret - [ ] After merge: confirm CI's `pulumi up` is a no-op (Pulumi state already imported) - [ ] After merge: confirm CI deploy retains the env var (it will, since it's now in `--set-secrets`) - [ ] First real capacity event in -c will validate end-to-end fallback (will know via logs / Discord alert when next outage hits) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
8c530f5ade |
feat: syllable-aware custom lyrics with validate-and-repair loop (#741)
## Summary Enhances the Custom Lyrics LLM mode with syllable-count validation and per-line repair, plus user-facing settings (`allow_reword`, `allow_omit`, `fixed_line_count`, `strictness`) and a per-line preview UI showing target/actual syllables and severity badges. - **Backend**: New `GenerationSettings` model, validator computing per-line `min_delta` against the existing `SyllablesMatchHandler` engine, repair loop (max 3 iterations, plateau-aware on the full `(violations, total_delta)` score tuple), proportional timing redistribution for variable-line-count outputs, structured per-iteration logging with worst-3-line breadcrumbs. - **Frontend**: Collapsible `CustomLyricsSettings` panel (3 toggles + 5-button strictness segmented control with ARIA group semantics + contradiction warning), `CustomLyricsPreview` with severity badges + iterations badge + stop-reason banner, wired into existing `CustomLyricsMode` modal. Snake-case API response shape (`line_metadata`, `iterations_used`, `stop_reason`, `settings_applied`, `new_segment_timing`). - **i18n**: 33 new keys across 33 locales (auto-translated via Gemini pipeline). - **Eval harness**: `backend/eval/custom_lyrics/` with disk-backed Gemini cache (record-and-replay), per-line + per-fixture + corpus scorers, CLI runner (`make eval-custom-lyrics`), and 4 fixtures (Year 5 Stars from production + 3 handcrafted public-domain). - **Production E2E**: Updated existing test for the new preview UI + 3 new tests for settings panel toggles. ## Risk / Deferred Validation The eval harness is built and ready, but **Phase 8 baseline capture (v1-ships criteria validation) was deferred** — we ship and test in prod. If the Year-5-Stars fixture doesn't hit `pct_pass_at_2 >= 75%` post-merge, the spec lists fallback paths (chunked generation, per-line repair); the eval can be run anytime via `make eval-custom-lyrics`. Repair-loop logging is structured and rich so any prod failure is diagnosable from Cloud Logging without re-running locally — log breadcrumbs include per-iteration violation count, score deltas, and the worst 3 failing lines with their target/candidate text + syllable arrays. ## Test plan - [x] Backend unit tests: 77 passing - [x] Frontend unit tests: 32 passing across CustomLyricsSettings, CustomLyricsPreview, CustomLyricsMode, customLyrics API client, segmentsFromLines - [x] TypeScript compiles cleanly for the touched files - [x] CodeRabbit local review run; real bugs in timing.py (median + zero-syllable) and validator.py (segment-duration hardening) fixed inline - [ ] **Post-merge**: real Gemini run against Year-5-Stars production job, check Cloud Logging for `custom_lyrics_repair_iter_complete` events, verify `pct_pass_at_2` matches expectations - [ ] **Post-merge**: run prod E2E suite once admin token is plumbed in CI (or manually) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
2b4ef257b7 |
ci: flip default EMAIL_PROVIDER to postmark on backend deploy (#740)
## Summary One-line change: `EMAIL_PROVIDER=sendgrid` → `EMAIL_PROVIDER=postmark` in the backend's \`gcloud run deploy --set-env-vars\` flag. ## Why Postmark cutover was completed today via direct Cloud Run env update. Backend, video-encoding-job, and gdrive-validator are all verified to be routing transactional email through Postmark (confirmed end-to-end with test sign-in and validator emails landing in the Postmark Activity feed). The CI workflow still set \`EMAIL_PROVIDER=sendgrid\` on every backend deploy, which would silently revert the cutover on the next merge to main. This locks the cutover in. The \`SendGridEmailProvider\` class and \`sendgrid-api-key\` secret are intentionally left in place as a fallback — to roll back, set \`EMAIL_PROVIDER=sendgrid\` on the Cloud Run service via gcloud. ## Test plan - [x] No code changed; only the CI deploy command's env var - [ ] After merge: confirm new revision still has \`EMAIL_PROVIDER=postmark\` and continues to route through Postmark @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
48e24f4e83 |
feat(email): migrate to Postmark with feature-flag cutover (#735)
## Summary
Replace SendGrid with Postmark as the transactional email provider,
behind an `EMAIL_PROVIDER` feature flag for safe cutover.
## Why
SendGrid's shared IPs have been throttled by Yahoo since ~Apr 22 (`421
4.7.0 [TSS04]`), causing 6-28h delivery delays and breaking magic-link
sign-in for Yahoo users. Postmark has a much stronger transactional
reputation with Yahoo/AOL and is cheaper ($16/mo vs SendGrid Pro at
$90/mo for a dedicated IP). Domain verification is already complete in
Postmark (SPF, DKIM, return-path all green for `nomadkaraoke.com`).
## Approach
- New `PostmarkEmailProvider` in \`backend/services/email_service.py\` —
uses the Postmark REST API directly (no new SDK dependency, reuses
\`requests\`).
- \`_get_provider()\` honors \`EMAIL_PROVIDER\` env var
(\`postmark\`|\`sendgrid\`). Code default is \`postmark\`. CI/Cloud Run
defaults to \`sendgrid\` so this PR is a no-op in prod on merge.
- gdrive-validator Cloud Function swapped to Postmark (drops the
\`sendgrid\` Python dep).
- Pulumi adds \`postmark-server-token\` Secret Manager resource + wires
\`POSTMARK_SERVER_TOKEN\` into encoding job and gdrive-validator. Keeps
\`SENDGRID_API_KEY\` wired in parallel during cutover.
## Cutover plan
1. \`pulumi up --stack prod\` locally **before merging** (creates the
new secret resource — needs admin GCP creds, my readonly SA can't do
it).
2. After \`pulumi up\` succeeds, populate the secret value:
\`\`\`
gcloud secrets versions add postmark-server-token \\
--data-file=- --project=nomadkaraoke <<<"\$POSTMARK_SERVER_KEY"
\`\`\`
3. Merge this PR → \`gcloud run deploy\` runs in CI with
\`EMAIL_PROVIDER=sendgrid\` (zero behavior change). New env vars wired
but inert.
4. Once Postmark account is staff-approved (tomorrow), flip the env var:
\`\`\`
gcloud run services update karaoke-backend --region=us-central1 \\
--update-env-vars=EMAIL_PROVIDER=postmark --project=nomadkaraoke
\`\`\`
5. Test sign-in to a Yahoo address. Confirm the customer
(\`hojob2002@yahoo.com\`) can sign in.
6. Follow-up PR: delete \`SendGridEmailProvider\` class,
\`sendgrid-api-key\` secret, \`sendgrid\` Python dep, and
\`SENDGRID_API_KEY\` env bindings.
## Files
- \`backend/services/email_service.py\` — new \`PostmarkEmailProvider\`,
updated \`_get_provider()\`, shared \`_dedupe_emails()\` helper
- \`backend/tests/test_email_service.py\` — Postmark provider +
provider-selection tests (22 new)
- \`infrastructure/modules/secrets.py\` — adds \`postmark-server-token\`
- \`infrastructure/__main__.py\` — gdrive-validator function gets
\`POSTMARK_SERVER_TOKEN\` (keeps \`SENDGRID_API_KEY\`)
- \`infrastructure/modules/cloud_run.py\` — video-encoding-job gets
\`POSTMARK_SERVER_TOKEN\` (keeps \`SENDGRID_API_KEY\`)
-
\`infrastructure/functions/gdrive_validator/{main.py,deploy.sh,requirements.txt}\`
— swap SendGrid for Postmark; drop \`sendgrid\` Python dep
- \`.github/workflows/ci.yml\` — adds \`POSTMARK_SERVER_TOKEN\` secret +
\`EMAIL_PROVIDER=sendgrid\` env to backend deploy
- \`pyproject.toml\` — 0.172.3 → 0.172.4
## Test plan
- [x] \`pytest backend/tests/ -k "magic_link or anti_abuse or
user_service or auth or email"\` — 377 passed
- [x] \`pulumi preview\` — clean diff (1 create, 2 update with both
providers wired)
- [ ] **Run \`pulumi up --stack prod\` locally before merging**
(requires admin GCP creds)
- [ ] Populate \`postmark-server-token\` secret value via gcloud
- [ ] Verify deploy succeeds with \`EMAIL_PROVIDER=sendgrid\` (no
behavior change)
- [ ] Tomorrow: flip env to \`postmark\`, sign in to a Yahoo address,
observe Postmark Activity feed for instant delivery
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
47df812a26 |
ci: harden deploy curls with --max-time to prevent wedged runs (#733)
## Summary
- Adds `--connect-timeout` and `--max-time` to all outbound `curl` calls
in the CI deploy path and the E2E token-refresh step
- Addresses a follow-up note from a prior session: **"harden CI Wait for
service health step with --max-time on curl (caused two near-wedged
deploys this session)"**
- Prevents a wedged upstream from turning a 3-minute health-check budget
into the 6-hour GH Actions job ceiling
## Context
Without `--max-time`, `curl` waits indefinitely for bytes once a TCP
connection is established. When the encoding-worker's gunicorn worker
wedges (accepts connections but doesn't respond), the poll loop's `for i
in $(seq 1 18); do curl ...; sleep 10; done` blocks on iteration 1
forever instead of failing after 3 minutes.
Root cause applies to 7 `curl` calls across `ci.yml`; this PR hardens
all of them for consistency, not just the one literally named in the
note.
### Scale-up/down interaction
Confirmed the fix is compatible with the blue/green + idle-shutdown
architecture:
- Cold-start of a stopped VM produces **ECONNREFUSED** (fast), not a
hang — `--max-time` is never engaged during boot
- Existing `sleep` windows between poll attempts already cover VM
cold-start time
- `config.deploy_in_progress` flag already blocks the idle-shutdown
Cloud Function during deploys, so no new races introduced
- `--max-time` only engages when the remote wedges post-accept — the
exact failure mode we want to bound
## Changes
| Line | Context | Connect / Max time |
|------|---------|--------------------|
| 271 | E2E impersonation token (Cloud Run) | 5s / 30s |
| 1231 | Wait for service health (**reported bug**) | 3s / 5s |
| 1267 | Deploy health check: submit encode | 5s / 30s |
| 1297 | Deploy health check: status poll | 3s / 10s |
| 1386 / 1396 | Drain old primary | 3s / 5s |
| 1690 | Backend basic health (Cloud Run) | 5s / 30s |
| 1698 | Backend version verify (Cloud Run) | 5s / 30s |
## Test plan
- [ ] YAML validity: `python3 -c "import yaml;
yaml.safe_load(open('.github/workflows/ci.yml'))"` — passed locally
- [ ] CI runs against this PR succeed
- [ ] Post-merge: the deploy job itself is the real validation — the
hardened curls run against real infrastructure. Merge should produce a
normal-duration (~5-10 min) deploy with no hangs
- [ ] No behavioral change on the happy path — all previously-successful
deploys behave identically
No backend/frontend code touched; no version bump needed.
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
7890440a2d |
feat(dr): close gaps from DR drill — secrets backup, freshness monitor, drill reminder (#729)
## Summary Closes the four real gaps identified in a soft DR drill against the cross-cloud backup pipeline (`karaoke-gen/docs/DISASTER-RECOVERY.md`): - **Secrets bucket in S3 was empty.** Secrets are now backed up nightly, encrypted with PyNaCl sealed box (asymmetric Curve25519). The private key lives only in the operator's password manager; the function holds no decryption capability, so a full GCP+AWS compromise still cannot read the bundle. - **No off-platform monitor.** New GitHub Actions cron checks S3 LastModified daily across all critical prefixes; alerts Discord if anything stale or missing. Runs in GitHub, not GCP — survives a complete GCP project loss. - **No quarterly drill cadence.** New Cloud Scheduler job posts a Discord nudge on Jan/Apr/Jul/Oct 1st with a link to the drill procedure. - **`nomadkaraoke-kn-data` bucket wasn't backed up.** Now synced nightly (irreplaceable, not publicly regenerable; MusicBrainz/MLHD raw datasets are public so they're documented as regenerable instead). The DR runbook and external-services-config docs are rewritten to match: prerequisites checklist, three-option GCS recovery, decryption procedure, freshness monitor setup, drill procedure, regenerable-datasets table, expanded service inventory (9 → 25 services with explicit DR actions per service). ## Test plan - [x] Unit tests for secrets export (round-trip decryption, binary payload base64 handling, empty pubkey refusal, per-secret failure tolerance) — 4/4 pass alongside existing 5 - [x] `pulumi up` applied: new IAM grant + drill scheduler + env var - [x] Function rebuilt via REST API after Pulumi (gsutil hit reauth wall, used Python+ADC fallback) - [x] Triggered nightly schedule manually; `secrets/2026-04-20.bin` landed in S3 at 19,851 bytes (consistent with 50 sealed-box-encrypted secrets) - [ ] Decrypt round-trip from S3 to plaintext (pending — `backup-writer` IAM is intentionally write-only; needs admin AWS creds to verify, but private key + ciphertext have been confirmed compatible via local test) ## Follow-up (requires AWS Console — out of scope for this PR) - Create `nomadkaraoke-backup-monitor` IAM user with `s3:ListBucket` + `s3:GetObject` scoped to the backup bucket - Set GitHub repo secrets `AWS_BACKUP_READONLY_ACCESS_KEY_ID`, `AWS_BACKUP_READONLY_SECRET_ACCESS_KEY`, `DR_MONITOR_DISCORD_WEBHOOK` to activate the freshness workflow - Rotate `aws-backup-credentials` (the active access key was in conversation context during the drill) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
321750a8e7 |
security: add gitleaks pre-commit hook and CI scan (#724)
## Summary Adds org-wide gitleaks secret-scanning in two layers: 1. **Local pre-commit hook** (`.githooks/pre-commit`) — blocks commits containing potential secrets before they're even created. Enable with `git config core.hooksPath .githooks`. 2. **CI backstop** (`.github/workflows/security.yml`) — calls the reusable gitleaks workflow in `nomadkaraoke/.github`, scans every PR and push to `main`. Config: `.gitleaks.toml` extends the default gitleaks rules with a dedicated Discord-webhook rule and an allowlist for known false-positive paths (lockfiles, vendor/, node_modules/, Flutter `.dart_tool/`, WordPress `wp-content/`, Python test fixtures, Firebase/GCP client API keys). ## Why Following the 2026-04-17 Discord webhook URL leak — a real webhook URL sat in `nomadkaraoke/karaoke-gen`'s archived setup docs for ~9 months, was scraped, and was used to push malware into the `#releases` channel. Existing defenses: GitHub push protection (enabled on all public repos). This PR adds the two missing layers (local pre-commit, CI). ## Test plan - [ ] After merge, create a test commit with a fake Discord webhook URL — the CI job should fail. - [ ] Run `brew install gitleaks && git config core.hooksPath .githooks` locally, then attempt the same commit — the pre-commit hook should block it. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) |
||
|
|
d4242c78a8 |
feat(e2e): daily payment + happy path production test (#715)
@coderabbitai ignore ## Summary - **New daily E2E test** that purchases credits via **real Stripe Checkout** ($3/day with 70% referral discount), then uses the credit for the existing happy path karaoke generation test - Motivated by the April 10 payment webhook outage — the existing simulated-webhook test would never have caught the Stripe SDK v14 bug - Adds Discord + email alerts for both stages ## Changes - **New:** `frontend/e2e/helpers/stripe-checkout.ts` — Playwright helper for Stripe's hosted checkout page - **New:** `frontend/e2e/production/credit-purchase-real.spec.ts` — Real Stripe payment test - **New:** `.github/workflows/e2e-daily.yml` — Two-stage daily workflow: credit purchase → happy path - **Deleted:** `.github/workflows/e2e-happy-path.yml` — Replaced by combined workflow - **Docs:** Design spec + implementation plan ## Verified - Tested locally 15 iterations to get Stripe Checkout selectors right - Full payment flow works end-to-end: signup → referral discount → Stripe → credits → email - $3 real charge processed successfully each test run ## Test plan - [x] Local test passes (real $3 Stripe payment) - [ ] Merge and trigger e2e-daily workflow manually - [ ] Verify Discord notification - [ ] Monitor first automated daily run (6 AM UTC) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
04c7197445 |
feat(i18n): add translation cache, CI validation, and enforcement (#693)
## Summary @coderabbitai ignore - Add GCS translation cache (`translation_cache.py`) to `translate.py` for instant repeated translations - Add `--no-cache`, `--dry-run`, `--cache-bucket` CLI flags to translation script - Add `translation-check` CI job that validates all 33 locale files have matching keys - Add `.githooks/pre-commit` hook for auto-translation when `en.json` changes - Add i18n section to CLAUDE.md documenting 33-locale support and enforcement rules ## Test plan - [ ] `python frontend/scripts/translate.py --messages-dir frontend/messages --target es --dry-run` shows cache stats - [ ] `python frontend/scripts/validate-translations.py --messages-dir frontend/messages` passes - [ ] CI `translation-check` job runs on PR 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
9ccad7c6d3 |
feat: service health status modal with blue-green deploy details (#645)
## Summary - Clickable footer opens a modal showing all service health, versions, deploy times, and PR links - Progressive disclosure: basic info for everyone, blue-green encoder details for admins - New aggregated `/api/health/system-status` endpoint (single fetch instead of 4 separate calls) - CI captures git SHA and PR info, passes to frontend and backend builds ## Changes - **Backend**: New `/api/health/system-status` endpoint with optional admin auth for blue-green Firestore config - **Backend**: Build metadata env vars (COMMIT_SHA, PR_NUMBER, PR_TITLE, STARTUP_TIME) in version module - **Frontend**: New `SystemStatusModal` component with service cards and expandable blue-green section - **Frontend**: Footer version line is now clickable to open the modal - **Frontend**: Build metadata env vars passed through next.config.mjs - **CI**: Both frontend and backend deploy jobs capture and pass git SHA + PR info ## Testing - [x] 3 unit tests for system-status endpoint (public, offline, admin blue-green) - [x] TypeScript compilation clean (no new errors) - [x] CodeRabbit CLI reviewed @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
8e2a949a29 |
fix: complete blue-green deploy test payload and status check (#644)
## Summary - Fix the deploy health check test payload and status value mismatches that prevented blue-green swaps from ever completing - Follow-up to #642 which fixed the error handling / rollback conditions ## Changes - **Missing required fields**: `encode-preview` requires `audio_gcs_path` and `output_gcs_path` but the health check only sent `job_id`, `ass_gcs_path`, and `duration_seconds` (caused HTTP 422). Added a 3-second test audio file and proper output path. - **Status polling mismatch**: Polling checked for `"completed"` but the GCE worker returns `"complete"` — would always time out even on success. - **Submit response mismatch**: Validated against `"completed"` which is never returned — endpoint returns `"accepted"`, `"cached"`, or `"in_progress"`. ## Root Cause The test payload was written based on the plan doc which had an incomplete request schema. The `audio_gcs_path` and `output_gcs_path` fields have been required since the endpoint was first created (PR #200, Jan 2026). The status string mismatch (`"completed"` vs `"complete"`) was likely a typo that was never caught because the request always failed before reaching the polling stage. ## Testing - Previous deploy (#642) confirmed the 422 error and verified rollback now triggers correctly - This fix addresses the payload so the encode test can actually succeed and the swap can complete - Real validation: next deploy after merge @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
5dfaa3f73f |
fix: blue-green deploy health check and rollback conditions (#642)
## Summary
- Fix blue-green deploy workflow that has been silently failing since
v0.151.0 (March 25)
- Every deploy has fallen through to `ensure_latest_wheel()` hot-update
instead of tested blue-green swap
## Changes
- **Health check curl**: Replace `curl -sf` (which exits immediately on
HTTP errors before setting output) with `curl -s -o file -w
'%{http_code}'` to capture HTTP status without early exit
- **Status polling curl**: Remove `-f` flag and add fallback for failed
status checks
- **Rollback condition**: Change `passed == 'false'` to `passed !=
'true'` to catch unset/skipped cases (defense in depth)
## Root Cause
`curl -sf` with `-f` (fail silently) exits non-zero on HTTP errors.
Combined with GitHub Actions' `set -e`, the script exits before writing
`passed=false` to `$GITHUB_OUTPUT`. Both the rollback (`== 'false'`) and
swap (`== 'true'`) conditions evaluate false against the unset output,
creating a silent no-op.
## Testing
- [x] CI workflow syntax validated
- [x] CodeRabbit CLI review completed locally (no issues in changed
file)
- Real validation: next deploy will exercise the fixed workflow
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
||
|
|
82e9becc7c |
chore: right-size Cloud Run + fix divebar-sync auto-shutdown (#640)
## Summary - Right-size karaoke-backend Cloud Run: concurrency 1→80, minScale 4→1, CPU 8→2, memory 16Gi→2Gi, enable cpu-throttling, maxScale 50→20 - Fix divebar-sync VM: add missing `shutdown -h now` after file sync completes (VM was staying on 24/7) ## Cost Impact - Backend right-sizing: ~$1,800/mo savings - Divebar-sync fix: ~$32/mo savings - Part of broader GCP cost reduction (docs/2026-03-31-cost-reduction-design.md) ## Context The backend is an I/O-bound API orchestrator (Firestore queries + Cloud Run job dispatch). Heavy processing was moved to Cloud Run Jobs and a dedicated GCE encoding worker months ago, but the Cloud Run config was never updated. Concurrency=1 forced one-request-per-instance, and minScale=4 kept 4 instances of 8CPU/16Gi running 24/7. Changes have already been applied live via `gcloud run services update` and verified with health checks. ## Test plan - [x] All 6 Cloud Run settings updated incrementally with health checks between each - [x] `curl https://api.nomadkaraoke.com/api/health` returns 200 after all changes - [x] Divebar-sync VM stopped and metadata updated with new startup script - [ ] Monitor billing data over next 24-48h to confirm cost reduction @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
257315d632 |
ci: use poetry.lock for GPU base image hash to avoid needless rebuilds (#627)
## Summary - Use `poetry.lock` instead of `pyproject.toml` when computing the GPU base image content hash - Prevents expensive 15-20 min GPU base image rebuilds on version-only bumps ## Problem The GPU base image hash was computed from `cat Dockerfile.gpu-base pyproject.toml | sha256sum`. Any change to `pyproject.toml` — including version bumps that don't change dependencies — triggered a full GPU base image rebuild. This adds ~15-20 min to every deploy that follows a version bump. ## Fix `poetry.lock` is the authoritative record of resolved dependencies. It only changes when actual dependencies are added/removed/updated, not on version bumps. The GPU base image installs deps via `pip install -e .` which reads `pyproject.toml` at build time, but the Docker layer cache handles that separately — the CI hash check just needs to know if deps changed. @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
92d1c9729d |
ci: auto-update lyrics-transcription-job on deploy (#626)
## Summary - Add `lyrics-transcription-job` to the CI deploy step that updates Cloud Run Jobs - Previously only `video-encoding-job` and `audio-separation-job` were updated, requiring manual `gcloud run jobs update` for lyrics ## Context Discovered during the anchor IndexError fix (#623) — the fix was deployed to the Cloud Run Service automatically but the Cloud Run Job (where lyrics transcription actually runs) had to be updated manually. ## Changes - `.github/workflows/ci.yml`: Add `gcloud run jobs update lyrics-transcription-job` alongside the existing job updates @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
cd3076fc58 |
fix: allowlisted domains bypassed by external disposable email APIs (#625)
## Summary - The disposable email detection had a bug where the Firestore `allowlisted_domains` only protected against the Tier 1 static blocklist check. External API checks (DeBounce, verifymail.io) at Tiers 3-4 ran regardless and could override admin allowlist decisions. - This broke the E2E happy path test starting March 21 when `inbox.testmail.app` got flagged by DeBounce as disposable — the signup step failed because "Check Your Email" never appeared. - Adds a "Tier 1.5" check so allowlisted domains skip external API calls entirely, plus a CI setup step to ensure the domain stays allowlisted. ## Changes - `backend/services/email_validation_service.py`: Add allowlist check before external API calls; include `allowlisted_domains` in cached config - `backend/tests/test_email_validation_service.py`: Regression test for allowlisted domain bypass - `.github/workflows/e2e-happy-path.yml`: CI setup step to ensure `inbox.testmail.app` is allowlisted before test runs ## Test plan - [x] All 53 email validation tests pass (52 existing + 1 new regression test) - [x] `inbox.testmail.app` added to production Firestore allowlist - [ ] E2E happy path test passes after deployment <!-- @coderabbitai ignore --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |