Compare commits

..
2 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 5.5 49464e8fcc chore(cost): GCP cost cuts round 2 (v0.261.4) (#1107)
Round 2 of the GCP cost cuts, approved by Andrew. Target: the whole
project under $300/mo; the current run-rate is about $400.

## Changes
- **karaoke-backend min-instances 1 → 0** (`ci.yml`), about $24/mo. The
backend Cloud Run service isn't defined in Pulumi, so the CI flag is the
only place this is set. Andrew accepts a ~15s cold start. The 60s
`/api/health` uptime check and the `*/10` schedulers keep an instance
warm most of the time. With `--cpu-throttling` (request-based billing),
a warm instance above the minimum costs nothing while idle.
- **audio-separator Cloud Run GPU service shut down** (us-east4), about
$22/mo. It is now behind the Pulumi flag `audioSeparatorServiceEnabled`,
off by default. The service, SA, IAM bindings, output bucket and AR repo
were already removed with a targeted `pulumi up`; the bucket needed the
break-glass SA. `audio-separation-job` is untouched; it uses
`karaoke-backend-gpu/karaoke-backend`. The separator health check no
longer depends on `AUDIO_SEPARATOR_API_URL`, which also fixes a status
card that always showed "offline". The CLI now logs a clear hint when
the remote API fails. Companion PR:
nomadkaraoke/python-audio-separator#309 makes its Cloud Run deploy
manual-only.
- **backup-to-aws no longer copies job files to S3**, about $15/mo
egress. Job files now rely on GCS versioning plus soft-delete.
Firestore, secrets, BigQuery, kn-data and git-bundle backups are
unchanged. The freshness monitor no longer checks `gcs/job-files/`, and
DISASTER-RECOVERY.md is updated.
- **Artifact Registry cleanup policies**, about $8–10/mo. Per package:
keep the 10 most recent versions plus anything tagged `latest`,
`content-` or `cache`; delete all other versions older than 7d. Until
now, tagged per-commit images were never deleted. Dropped the CI
fallback that copied the GPU base once from us-east4, and deleted the
legacy 13 GB us-east4 GPU base package.
- Docs: GCP-COST-OPTIMIZATION.md (new section, including how to redeploy
the separator on demand), ARCHITECTURE.md, DISASTER-RECOVERY.md.

Changes made outside Pulumi (gcf-artifacts cleanup policy, destroying
superseded secret versions) are recorded in GCP-COST-OPTIMIZATION.md.

## Tests
- `backend/tests/test_system_status_endpoint.py` (new separator status
tests)
- `infrastructure/functions/backup_to_aws` (49 tests, including a new
one that checks job files aren't synced)
- `tests/unit/test_audio_remote.py`, `test_audio_processor_local_gpu.py`

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

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

## Summary by CodeRabbit

* **Service Availability**
* The hosted audio-separation service is no longer available. Audio
separation can run locally; users relying on the hosted service will
need another deployment.
* **Backup and Recovery**
* New job files are no longer copied to off-site S3 backups. S3 recovery
is limited to files backed up through September 30, 2026; newer outputs
may need to be regenerated.
* **System Status**
* Audio-separator health status now reports the locally installed
package version without checking a remote service.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 21:22:49 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 e4dc50d9e3 fix(ci): sanitize PR title in deploy env vars (v0.261.3) (#1109)
The v0.261.2 main deploy (run 36945703908) failed at **Deploy to Cloud
Run (candidate revision)** with:

`argument --set-env-vars: Bad syntax for dict arg`

The #1106 PR title contained a comma, and `PR_TITLE` is spliced into the
comma-delimited `--set-env-vars`. The bug was already there and that
title was the first to trigger it. Its Cloud Build step succeeded.

Fix: in both build-meta steps, commas become `;`, and newlines and
shell-active characters (`\" \` $ \\`) are removed. Version bumped to
0.261.3.

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

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 20:50:43 -04:00
16 changed files with 294 additions and 130 deletions

No files matched your search

+18 -4
View File
@@ -1033,6 +1033,11 @@ jobs:
PR_NUM=""
PR_TITLE=""
fi
# The backend deploy splices PR_TITLE into the comma-delimited
# `gcloud run deploy --set-env-vars "...,PR_TITLE=..."` (inside a
# double-quoted shell string): a comma in a PR title broke the v0.261.2
# deploy. Commas → ';', drop newlines and shell-active chars.
PR_TITLE=$(printf '%s' "$PR_TITLE" | tr ',' ';' | tr -d '\n\r"`$\\')
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
@@ -1153,6 +1158,11 @@ jobs:
PR_NUM=""
PR_TITLE=""
fi
# The backend deploy splices PR_TITLE into the comma-delimited
# `gcloud run deploy --set-env-vars "...,PR_TITLE=..."` (inside a
# double-quoted shell string): a comma in a PR title broke the v0.261.2
# deploy. Commas → ';', drop newlines and shell-active chars.
PR_TITLE=$(printf '%s' "$PR_TITLE" | tr ',' ';' | tr -d '\n\r"`$\\')
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
@@ -1986,9 +1996,13 @@ jobs:
# forced scale-out, and each overflow request waited out a ~16s app
# cold start (2026-09-22 16-tab test: warm instance served in 1.2s,
# freshly-spawned ones in 16-19s). 32 + --min-instances 2 gave 64
# warm slots; min-instances was cut to 1 on 2026-09-26 (GCP cost cut,
# accepted perf trade-off: big bursts may hit a ~15s cold start) while
# staying far below the wedge-era 80. --clear-vpc-connector: the
# warm slots; min-instances was cut to 1 on 2026-09-26 and to 0 on
# 2026-10-01 (GCP cost cuts, ~$24/mo idle min-instance charge; Andrew
# accepts a ~15s cold start on the first request after idle). In
# practice the 60s /api/health uptime check and the */10 Cloud
# Scheduler jobs keep an instance warm most of the time — with
# --cpu-throttling (request-based billing) a warm-but-idle non-min
# instance costs nothing. Concurrency stays far below the wedge-era 80. --clear-vpc-connector: the
# serverless VPC connector was deleted (flacfetch is public now).
gcloud run deploy karaoke-backend \
--image $IMAGE \
@@ -2005,7 +2019,7 @@ jobs:
--timeout 1800 \
--concurrency 32 \
--max-instances 20 \
--min-instances 1 \
--min-instances 0 \
--clear-vpc-connector \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
+4 -3
View File
@@ -60,8 +60,10 @@ jobs:
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
# sees the S3 (off-site) copy, so their limits must allow a full week
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
# files and secrets DO upload to S3 nightly, so they stay at 36h.
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. Secrets DO
# upload to S3 nightly, so they stay at 36h. GCS job files are NOT
# tracked: their off-site copy was stopped 2026-10-01 (egress cost
# cut) — they rely on GCS versioning + soft-delete only.
# Git repos are also weekly (Sundays) AND incremental since
# 2026-09-26 — only repos pushed that week get a fresh bundle, so a
# quiet week legitimately leaves every .bundle older than 8 days.
@@ -70,7 +72,6 @@ jobs:
# a run where every repo failed still reads as stale.
TARGETS = [
("Firestore", "firestore/", 192, None),
("GCS job files", "gcs/job-files/", 36, None),
("Encrypted secrets", "secrets/", 36, None),
("BigQuery weekly", "bigquery/daily-refresh/", 192, None),
("Git repos", "git-repos/manifest.json", 192, None),
+12 -35
View File
@@ -312,16 +312,14 @@ async def flacfetch_health() -> Dict[str, Any]:
def check_audio_separator_status() -> Dict[str, Any]:
"""Check audio separator availability without calling the remote GPU service."""
from backend.config import get_settings
settings = get_settings()
if not settings.audio_separator_api_url:
return {
"available": False,
"status": "not_configured",
}
"""Report audio separation availability.
Separation runs in the ``audio-separation-job`` GPU Cloud Run Job (local
GPU mode, models baked into the image). The standalone ``audio-separator``
Cloud Run GPU service was shut down on 2026-10-01 (cost cut), so there is
no remote service to probe — this reports the installed package version
only and never calls out to anything.
"""
try:
from importlib.metadata import version
pkg_version = version("audio-separator")
@@ -331,6 +329,7 @@ def check_audio_separator_status() -> Dict[str, Any]:
return {
"available": True,
"status": "ok",
"mode": "gpu_job",
"version": pkg_version,
}
@@ -338,34 +337,12 @@ def check_audio_separator_status() -> Dict[str, Any]:
@router.get("/health/audio-separator")
async def audio_separator_health() -> Dict[str, Any]:
"""
Return the installed audio-separator package version.
Return audio separation status (installed audio-separator package version).
Does NOT call the remote GPU service — that would cold-start an expensive
Cloud Run GPU instance (~$0.07 per wake). Instead reports the locally
installed package version, which matches what the audio worker uses.
No authentication required.
Does NOT call any remote service — separation runs in the
audio-separation-job GPU Cloud Run Job. No authentication required.
"""
from backend.config import get_settings
settings = get_settings()
if not settings.audio_separator_api_url:
return {
"available": False,
"status": "not_configured",
}
try:
from importlib.metadata import version
pkg_version = version("audio-separator")
except Exception:
pkg_version = None
return {
"available": True,
"status": "ok",
"version": pkg_version,
}
return check_audio_separator_status()
def _get_encoding_worker_manager():
+4 -4
View File
@@ -15,9 +15,9 @@ steps:
- '-f'
- 'backend/Dockerfile.gpu-base'
- '-t'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:latest'
- '-t'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:$BUILD_ID'
- '--build-arg'
- 'BUILD_DATE=$_BUILD_DATE'
- '--build-arg'
@@ -25,8 +25,8 @@ steps:
- '.'
images:
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:latest'
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:$BUILD_ID'
timeout: '3600s'
@@ -205,3 +205,27 @@ class TestSystemStatusAdmin:
assert admin["active_zone"] == "us-central1-a"
# "n2c" family token → n2-highcpu-16 (inferred from the VM name).
assert admin["active_machine_type"] == "n2-highcpu-16"
class TestAudioSeparatorStatus:
"""Separation runs in the audio-separation-job GPU Cloud Run Job; the
standalone audio-separator service was shut down (2026-10-01), so the
status must not depend on AUDIO_SEPARATOR_API_URL or call anything."""
def test_reports_ok_without_api_url(self, monkeypatch):
from backend.api.routes.health import check_audio_separator_status
monkeypatch.delenv("AUDIO_SEPARATOR_API_URL", raising=False)
status = check_audio_separator_status()
assert status["available"] is True
assert status["status"] == "ok"
assert status["mode"] == "gpu_job"
assert "version" in status
@pytest.mark.asyncio
async def test_endpoint_matches_status_helper(self):
from backend.api.routes.health import audio_separator_health
from backend.api.routes.health import check_audio_separator_status
assert await audio_separator_health() == check_audio_separator_status()
+7 -4
View File
@@ -605,10 +605,13 @@ Audio stem separation runs **directly inside the audio worker Cloud Run Job**
- **Two-stage ensemble preset** — `instrumental_clean` (stage 1) + `karaoke` (stage 2).
- **Model cache** — Models are downloaded to `model_file_dir` (GCS-backed or local) and reused across executions.
**The `audio-separator` Cloud Run GPU service** (us-east4, scale-to-zero) is no longer used by
prod gen jobs, but it still serves external remote-separation clients (`audio-separator-remote` /
local `karaoke-gen` CLI with `AUDIO_SEPARATOR_API_URL`; ~40 `/separate` calls/month as of
2026-09). Keep it at min-instances 0; don't remove it without checking its request logs first.
**The `audio-separator` Cloud Run GPU service** (us-east4) was **shut down on 2026-10-01**
(GCP cost cut, ~$22/mo). Prod gen jobs never used it; its only callers were Andrew's own
remote-separation clients (`audio-separator-remote` / local `karaoke-gen` CLI with
`AUDIO_SEPARATOR_API_URL`). Leave `AUDIO_SEPARATOR_API_URL` unset to separate locally. It
is still defined in Pulumi behind the `audioSeparatorServiceEnabled` flag — see
[GCP-COST-OPTIMIZATION.md](GCP-COST-OPTIMIZATION.md#audio-separator-service-shut-down-on-demand-redeploy)
to bring it back on demand.
### Quick version (kjbox make-it jobs)
+25 -6
View File
@@ -1,6 +1,6 @@
# Disaster Recovery Runbook
**Last updated:** 2026-06-18
**Last updated:** 2026-10-01
**Design doc:** `docs/archive/2026-03-27-business-continuity-design.md`
**Implementation plan:** `docs/archive/2026-03-29-business-continuity-plan.md`
**External services reference:** `docs/archive/2026-03-29-external-services-config.md`
@@ -13,7 +13,7 @@
| BigQuery (weekly) | S3 `bigquery/daily-refresh/` | Load Parquet files | 7 days |
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
| GCS job files | S3 `gcs/job-files/` | Sync to new bucket | 24h |
| GCS job files | **GCS only** — object versioning (non-current kept 30d) + soft-delete (7d). Off-site S3 copy **stopped 2026-10-01**; S3 `gcs/job-files/` is a frozen snapshot up to 2026-09-30 | Restore non-current/soft-deleted generation in GCS | N/A off-site (frozen); in-GCS recovery window 7–30d |
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 7 days (weekly, Sundays; incremental) |
| Secret Manager | S3 `secrets/YYYY-MM-DD.bin` (sealed-box encrypted) | Decrypt with private key from KeepassXC | 24h |
| AWS credentials (function) | GCP Secret Manager `aws-backup-credentials` | Read directly | On-change |
@@ -109,7 +109,7 @@ gcloud storage cp gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/file.flac#GE
gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/file.flac
```
**Option C — Restore from S3 (if A and B both miss the window):**
**Option C — Restore from S3 (if A and B both miss the window; only works for files that existed by 2026-09-30 — the nightly S3 copy of job files was stopped 2026-10-01, see § "Job files: off-site copy stopped"):**
```bash
aws s3 sync s3://nomadkaraoke-backup/gcs/job-files/jobs/JOB_ID/ /tmp/gcs-restore/
@@ -209,7 +209,9 @@ aws s3api restore-object --bucket nomadkaraoke-backup \
# Create new bucket
gsutil mb -l US-CENTRAL1 gs://karaoke-gen-storage-nomadkaraoke-v2/
# Sync from S3 (146 GB last we measured — needs a host with comparable disk + bandwidth)
# Sync from S3 (146 GB last we measured — needs a host with comparable disk + bandwidth).
# NOTE: frozen snapshot — job files created/changed after 2026-09-30 are NOT in S3
# (off-site copy stopped 2026-10-01). Newer outputs must be regenerated.
aws s3 sync s3://nomadkaraoke-backup/gcs/job-files/ /tmp/gcs-restore/
gsutil -m cp -r /tmp/gcs-restore/ gs://karaoke-gen-storage-nomadkaraoke-v2/
```
@@ -462,13 +464,13 @@ export AWS_DEFAULT_REGION=us-east-1
## Backup freshness monitor
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/manifest.json` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/manifest.json` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
Per-prefix limits reflect each prefix's **S3 (off-site)** cadence, which is not the same as its GCS-staging cadence:
| Prefix | S3 upload cadence | Monitor limit |
|--------|-------------------|---------------|
| `gcs/job-files/`, `secrets/` | nightly | 36h |
| `secrets/` | nightly | 36h |
| `firestore/`, `bigquery/daily-refresh/` | weekly (Sundays) | 192h (≈8 days) |
| `git-repos/manifest.json` | weekly (Sundays), incremental | 192h (≈8 days) + manifest must show 0 bundle errors |
@@ -549,6 +551,23 @@ re-import). The raw source files are not.
| Full Spotify dataset retrieval + transfer (~100 GB) | ~$25 total |
| Full GCS job-files egress (~150 GB) | ~$14 |
## Job files: off-site copy stopped (2026-10-01)
The nightly `backup-to-aws` step that delta-synced `karaoke-gen-storage-nomadkaraoke`
(`jobs/`, `tenants/`, `themes/`) → staging `gcs/job-files/` → S3 was removed on
2026-10-01 as a GCP cost cut (~$15/mo cross-cloud egress; business cash constraint).
Job outputs are regenerable from their inputs, and the primary bucket keeps
**object versioning** (non-current versions deleted 30 days after being superseded)
plus **7-day soft-delete**, which covers accidental overwrite/delete. What is
*not* covered any more: loss of the whole GCP project/bucket for files created after
2026-09-30. The existing S3 `gcs/job-files/` objects were deliberately left in place
(frozen snapshot). Firestore (weekly), secrets (nightly), BigQuery, kn-data and git
bundle backups are unchanged. The freshness monitor no longer checks `gcs/job-files/`.
To re-enable: restore the Step 3 `sync_gcs_to_staging(source_bucket="karaoke-gen-storage-nomadkaraoke", staging_prefix="gcs/job-files/")`
call in `infrastructure/functions/backup_to_aws/main.py` (see git history) and
re-add the `gcs/job-files/` row to `.github/workflows/dr-backup-freshness.yml`.
## Incident: S3 overwrites silently failing 2026-09-14 → 2026-09-26
The incremental S3 upload (#997) checked "already in S3?" with `HeadObject`,
+50 -2
View File
@@ -186,5 +186,53 @@ If all optimizations implemented:
| Firestore PITR disabled (nightly export remains) | `database.py` | PITR storage |
| `recover-stuck-downloads` / `retry-pending-render-jobs` every 5 → 10 min | `__main__.py` | ~half their Firestore reads |
Kept: the `audio-separator` Cloud Run GPU service (still used by external remote-CLI
clients; already scale-to-zero).
Kept (at the time): the `audio-separator` Cloud Run GPU service — shut down in round 2 below.
## 2026-10-01 cuts, round 2 (run-rate ~$400 → target < $300/mo)
| Change | Where | Est. saving |
|--------|-------|-------------|
| `karaoke-backend` min-instances 1 → 0 (Andrew accepts a ~15s cold start on the first request after idle). With `--cpu-throttling` (request-based billing), idle non-min instances are free, so the 60s `/api/health` uptime check and the `*/10` schedulers keeping it warm don't cost idle charges | `ci.yml` | ~$24/mo |
| `audio-separator` Cloud Run GPU service (us-east4) + its SA, IAM, output bucket and `audio-separator` AR repo (~42 GB) **deleted**; python-audio-separator's `deploy-to-cloudrun.yml` made manual-only | `__main__.py` (flag `audioSeparatorServiceEnabled`, default off) | ~$22/mo |
| `backup-to-aws` no longer copies job files to S3 (they rely on GCS versioning + soft-delete); freshness monitor no longer checks `gcs/job-files/` | `functions/backup_to_aws/main.py`, `dr-backup-freshness.yml`, `DISASTER-RECOVERY.md` | ~$15/mo egress |
| Artifact Registry cleanup: per package keep the 20 most recent versions (≈10 tagged deploy images; each build also leaves a cache manifest) + tags `latest`/`content-`/`cache`, delete everything else (tagged *or* untagged) older than 7 days. **Applied in DRY-RUN mode** (`CLEANUP_POLICY_DRY_RUN = True` in `artifact_registry.py`) — flip to `False` + targeted `pulumi up` on `karaoke-artifact-repo` / `karaoke-backend-gpu-artifact-repo` after reviewing the dry-run audit logs. After the next GPU base rebuild, delete the superseded `karaoke-backend-gpu-base:content-daa414741653` tag by hand (the `content-` KEEP rule would otherwise keep it forever). Before, tagged per-commit images were never deleted (~265 + ~244 tagged backend versions had piled up). Legacy 13 GB `karaoke-backend-gpu-base` package in us-east4 deleted (gcloud). `gcf-artifacts` (Google-managed, not in Pulumi) got a gcloud policy (also dry-run for now; enable with `gcloud artifacts repositories set-cleanup-policies gcf-artifacts --location=us-central1 --policy=<file> --no-dry-run`): keep 3 most recent + all tagged, delete untagged > 7d | `artifact_registry.py`, `gpu_artifact_registry.py` | ~$8–10/mo |
| Secret Manager: 12 superseded versions disabled → destroyed (none pinned; all consumers use `:latest`) | gcloud (out of Pulumi) | < $1/mo |
### Audio separator service (shut down, on-demand redeploy)
The standalone `audio-separator` API (L4 GPU Cloud Run service, us-east4) is still
defined in `infrastructure/modules/audio_separator_service.py`, gated behind a Pulumi
config flag. To bring it back:
```bash
cd infrastructure
STACK=nomadkaraoke/karaoke-gen-infrastructure/prod
PULUMI="env -u GOOGLE_APPLICATION_CREDENTIALS GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token --account=admin@nomadkaraoke.com) pulumi"
pulumi config set audioSeparatorServiceEnabled true --stack $STACK
# 1) Create ONLY the (empty) Artifact Registry repo first — the service references
# api:latest, which must exist before Cloud Run will accept the service.
$PULUMI up --stack $STACK --target 'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:artifactregistry/repository:Repository::audio-separator-artifact-repo'
# 2) Build + push api:<sha> and api:latest (from a python-audio-separator checkout)
gcloud builds submit --config cloudbuild.yaml --region=us-east4 --project=nomadkaraoke --substitutions=SHORT_SHA=$(git rev-parse --short=8 HEAD)
# 3) Create the service, SA, IAM and output bucket
$PULUMI up --stack $STACK
# Later image updates: gh workflow run deploy-to-cloudrun.yml --repo nomadkaraoke/python-audio-separator
export AUDIO_SEPARATOR_API_URL=$(gcloud run services describe audio-separator --region us-east4 --project nomadkaraoke --format='value(status.url)')
```
The output bucket is protected by the project's `deny-destructive-operations` IAM deny
policy. When you shut the service down again (`pulumi config rm audioSeparatorServiceEnabled`
+ `pulumi up`), delete the bucket first with
`gcloud storage rm -r gs://nomadkaraoke-audio-separator-outputs --impersonate-service-account=break-glass@nomadkaraoke.iam.gserviceaccount.com`,
then `pulumi refresh --target <bucket urn>`.
### Out-of-Pulumi changes (2026-10-01)
- `gcloud artifacts packages delete karaoke-backend-gpu-base --repository=karaoke-backend-gpu --location=us-east4`
(13 GB legacy base; the base has lived in us-central1 `karaoke-repo` since 2026-09-27; the CI one-time-copy fallback that read it was removed).
- `gcloud artifacts repositories set-cleanup-policies gcf-artifacts --location=us-central1` (policy above).
- Secret versions disabled, then destroyed: `encoding-worker-fallback-vms` v1–4, `flacfetch-api-url` v1,
`github-runner-pat` v1, `pushbullet-api-key` v1–2, `rapidapi-key` v1, `spotify-cookie` v1,
`discord-releases-webhook` v1–2. App-rotated secrets (`dropbox-oauth-credentials`, `spotify-oauth-token`,
`youtube-cookies`) keep their own retention and were left alone, as was `gemini-api-key`.
- `gs://nomadkaraoke-audio-separator-outputs` deleted via break-glass SA (IAM deny policy blocks Pulumi).
+26 -14
View File
@@ -655,18 +655,29 @@ divebar_sync_compute_admin = gcp.projects.IAMMember(
backup_resources = backup.create_backup_resources(all_secrets)
# ==================== Audio Separator GPU Service ====================
# Cloud Run GPU (L4) service for audio stem separation — replaces Modal
audio_separator_resources = audio_separator_service.create_all_resources()
# Grant audio separator read access to main storage bucket (for GCS URI passthrough)
gcp.storage.BucketIAMMember(
"audio-separator-storage-reader",
bucket=bucket.name,
role="roles/storage.objectViewer",
member=audio_separator_resources["service_account"].email.apply(
lambda email: f"serviceAccount:{email}"
),
# Standalone Cloud Run GPU (L4, us-east4) audio-separator API service.
# SHUT DOWN 2026-10-01 (GCP cost cut, ~$22/mo): prod jobs never used it —
# separation runs in the `audio-separation-job` GPU Cloud Run Job (local GPU
# mode). Its only callers were Andrew's own tools (kjbox original-vocals
# scripts, kjbox/fastgen). To bring it back on demand, see
# docs/GCP-COST-OPTIMIZATION.md § "Audio separator service (shut down, on-demand redeploy)":
# pulumi config set audioSeparatorServiceEnabled true && pulumi up --target ...
AUDIO_SEPARATOR_SERVICE_ENABLED = (
pulumi.Config().get_bool("audioSeparatorServiceEnabled") or False
)
audio_separator_resources = None
if AUDIO_SEPARATOR_SERVICE_ENABLED:
audio_separator_resources = audio_separator_service.create_all_resources()
# Grant audio separator read access to main storage bucket (for GCS URI passthrough)
gcp.storage.BucketIAMMember(
"audio-separator-storage-reader",
bucket=bucket.name,
role="roles/storage.objectViewer",
member=audio_separator_resources["service_account"].email.apply(
lambda email: f"serviceAccount:{email}"
),
)
# ==================== Compute VMs ====================
@@ -837,9 +848,10 @@ pulumi.export("divebar_lookup_function_url", divebar_lookup_resources["function"
pulumi.export("divebar_sync_vm_name", divebar_sync_instance.name)
pulumi.export("divebar_sync_scheduler_name", divebar_sync_scheduler.name)
# Audio separator GPU service
pulumi.export("audio_separator_service_url", audio_separator_resources["service"].uri)
pulumi.export("audio_separator_service_account", audio_separator_resources["service_account"].email)
# Audio separator GPU service (only when re-enabled on demand)
if audio_separator_resources is not None:
pulumi.export("audio_separator_service_url", audio_separator_resources["service"].uri)
pulumi.export("audio_separator_service_account", audio_separator_resources["service_account"].email)
# Encoding worker idle shutdown
pulumi.export("encoding_worker_idle_function_url", encoding_worker_idle_resources["function"].url)
+13 -12
View File
@@ -4,7 +4,10 @@ Backup to AWS Cloud Function.
Nightly backup pipeline:
1. Firestore export to GCS staging (nightly; uploaded to S3 weekly on Sundays)
2. BigQuery export to GCS staging (weekly/monthly schedule)
3. GCS job files delta sync to staging
3. GCS delta sync of nomadkaraoke-kn-data to staging. (Job files from the
karaoke-gen-storage bucket are NOT copied off-site any more — stopped
2026-10-01 to save ~$15/mo egress; they rely on GCS object versioning
+ soft-delete only. See docs/DISASTER-RECOVERY.md.)
4. Secret Manager export (encrypted with sealed-box public key) to staging
4b. Git repos backup — bundle repos under the configured GitHub owners to
staging (weekly on Sundays, incremental: only repos pushed since their
@@ -50,6 +53,7 @@ GIT_BACKUP_OWNERS = os.environ.get("GIT_BACKUP_OWNERS", "")
GIT_REPOS_PREFIX = "git-repos/"
JOB_FILES_PREFIX = "gcs/job-files/"
def _run_git_repos_backup(full_refresh: bool) -> str:
@@ -152,16 +156,11 @@ def backup_to_aws(request):
logger.error(f"BigQuery export failed: {e}")
errors.append(f"BigQuery: {e}")
# Step 3: GCS delta sync (nightly) — primary job-files bucket
try:
results["gcs_sync"] = sync_gcs_to_staging(
source_bucket="karaoke-gen-storage-nomadkaraoke",
staging_bucket=STAGING_BUCKET,
staging_prefix="gcs/job-files/",
)
except Exception as e:
logger.error(f"GCS sync failed: {e}")
errors.append(f"GCS sync: {e}")
# Step 3 (removed 2026-10-01): the nightly delta sync of job files
# (karaoke-gen-storage-nomadkaraoke -> gcs/job-files/) was the bulk of the
# remaining cross-cloud egress (~$15/mo) for regenerable outputs. Job files
# now rely on GCS object versioning + soft-delete only; existing S3 copies
# under gcs/job-files/ are left in place. See docs/DISASTER-RECOVERY.md.
# Step 3b: GCS delta sync — nomadkaraoke-kn-data (small, irreplaceable
# internal sync data from KaraokeNerds API; not publicly regenerable).
@@ -211,7 +210,9 @@ def backup_to_aws(request):
# _UPLOAD_LAG of its clone. A bundle left in staging by a failed upload
# must not ship on a later night (a push in between would then look backed
# up); next Sunday's git step re-bundles it fresh instead.
exclude = []
# gcs/job-files/ is never shipped any more (off-site job-file copy stopped
# 2026-10-01) — also skip anything a pre-change run left in staging.
exclude = [JOB_FILES_PREFIX]
if not firestore_to_s3_today:
exclude.append("firestore/")
if not git_repos_today:
@@ -33,13 +33,13 @@ def _run(today):
def test_weekday_skips_git_and_holds_back_firestore_and_git_repos():
git, upload = _run(datetime.date(2026, 9, 29)) # Tuesday
git.assert_not_called()
assert set(upload.call_args.kwargs["exclude_prefixes"]) == {"firestore/", "git-repos/"}
assert set(upload.call_args.kwargs["exclude_prefixes"]) == {"gcs/job-files/", "firestore/", "git-repos/"}
def test_sunday_runs_incremental_git_and_uploads_everything():
git, upload = _run(datetime.date(2026, 9, 27)) # Sunday, day 27
git.assert_called_once_with(full_refresh=False)
assert upload.call_args.kwargs["exclude_prefixes"] == []
assert upload.call_args.kwargs["exclude_prefixes"] == ["gcs/job-files/"]
def test_first_sunday_of_month_is_full_refresh():
@@ -58,3 +58,24 @@ def test_manual_git_mode_only_uploads_git_prefix():
git.assert_called_once_with(full_refresh=True)
assert upload.call_args.kwargs["include_prefixes"] == ["git-repos/"]
fs.assert_not_called()
def test_job_files_bucket_is_not_synced_off_site():
"""Job files stopped going to S3 on 2026-10-01 (egress cost cut); only the
small kn-data bucket is still delta-synced to staging."""
_FakeDate.today_value = datetime.date(2026, 9, 29)
request = MagicMock()
request.args = {}
with patch("main.datetime.date", _FakeDate), \
patch("main.export_firestore", return_value="fs"), \
patch("main.export_bigquery_tables", return_value={}), \
patch("main.sync_gcs_to_staging", return_value="gcs") as sync, \
patch("main.export_secrets", return_value="sec") as secrets, \
patch("main._run_git_repos_backup", return_value="git"), \
patch("main.upload_staging_to_s3", return_value="s3"), \
patch("main.send_alert"):
main.backup_to_aws(request)
sources = [c.kwargs["source_bucket"] for c in sync.call_args_list]
assert sources == ["nomadkaraoke-kn-data"]
assert all(c.kwargs["staging_prefix"] != "gcs/job-files/" for c in sync.call_args_list)
secrets.assert_called_once()
+66 -21
View File
@@ -10,6 +10,70 @@ from pulumi_gcp import artifactregistry
from config import PROJECT_ID, REGION
# True = AR only *logs* what the cleanup policies would delete (Cloud Audit
# Logs) instead of deleting. Applied in dry-run first on 2026-10-01; flip to
# False (+ targeted pulumi up on both repos) once the dry-run logs are reviewed.
CLEANUP_POLICY_DRY_RUN = True
# Tags that must never be auto-deleted regardless of age:
# latest — what jobs/services pinned to :latest pull
# content- — the GPU base image child manifest (content-<hash>), deliberately
# tagged so the untagged-delete rule can't orphan it
# cache — BuildKit registry cache manifests (cache-from/cache-to)
PROTECTED_TAG_PREFIXES = ["latest", "content-", "cache"]
def standard_cleanup_policies() -> list:
"""Shared cleanup policy set for the Docker repos (GCP cost cut 2026-10-01).
KEEP rules always win over DELETE rules in Artifact Registry, so a version
survives if it is among the 20 most recent versions of its package (≈10
tagged deploy images, since each build also leaves a cache manifest) OR
carries a protected tag. Everything else is deleted once older than 7 days
(untagged digests AND old per-commit ``<sha>``/``v<version>`` tags — before
this, tagged images were never deleted and every CI deploy accumulated).
The currently deployed image of every Cloud Run service/job is always among
the most recent (or is pinned to :latest), so rollback to recent revisions
keeps working. NOTE: ``content-`` keeps a superseded GPU base child forever
(~13 GB); after the next GPU base rebuild, delete the old
``karaoke-backend-gpu-base:content-daa414741653`` tag by hand.
"""
return [
artifactregistry.RepositoryCleanupPolicyArgs(
id="keep-recent-20",
action="KEEP",
most_recent_versions=artifactregistry.RepositoryCleanupPolicyMostRecentVersionsArgs(
# 20 versions ≈ 10 tagged deploy images: every build also leaves
# an untagged BuildKit cache manifest in the same package.
keep_count=20,
),
),
artifactregistry.RepositoryCleanupPolicyArgs(
id="keep-protected-tags",
action="KEEP",
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
tag_state="TAGGED",
tag_prefixes=PROTECTED_TAG_PREFIXES,
),
),
artifactregistry.RepositoryCleanupPolicyArgs(
id="delete-untagged-after-7d",
action="DELETE",
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
tag_state="UNTAGGED",
older_than="604800s", # 7 days
),
),
artifactregistry.RepositoryCleanupPolicyArgs(
id="delete-tagged-after-7d",
action="DELETE",
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
tag_state="TAGGED",
older_than="604800s", # 7 days
),
),
]
def create_repository() -> artifactregistry.Repository:
"""
@@ -24,27 +88,8 @@ def create_repository() -> artifactregistry.Repository:
location=REGION,
format="DOCKER",
description="Docker repository for karaoke backend images",
# Cost control: keep the 10 most recent versions for rollback, and
# delete untagged digests older than 7 days (orphaned layers left by
# repeated :latest pushes). Tagged images are never auto-deleted.
cleanup_policies=[
artifactregistry.RepositoryCleanupPolicyArgs(
id="keep-recent-10",
action="KEEP",
most_recent_versions=artifactregistry.RepositoryCleanupPolicyMostRecentVersionsArgs(
keep_count=10,
),
),
artifactregistry.RepositoryCleanupPolicyArgs(
id="delete-untagged-after-7d",
action="DELETE",
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
tag_state="UNTAGGED",
older_than="604800s", # 7 days
),
),
],
cleanup_policy_dry_run=False,
cleanup_policies=standard_cleanup_policies(),
cleanup_policy_dry_run=CLEANUP_POLICY_DRY_RUN,
)
return artifact_repo
@@ -2,7 +2,12 @@
Audio Separator Cloud Run GPU Service.
Deploys the audio-separator API as a Cloud Run service with L4 GPU acceleration.
Replaces the Modal deployment for audio stem separation.
Replaced the Modal deployment for audio stem separation.
DISABLED BY DEFAULT since 2026-10-01 (GCP cost cut): only created when the
Pulumi config flag ``audioSeparatorServiceEnabled`` is true. Prod jobs never
call it (they use the audio-separation-job GPU Cloud Run Job). See
docs/GCP-COST-OPTIMIZATION.md for the on-demand redeploy steps.
Resources created:
- Artifact Registry repository for audio-separator Docker images
@@ -139,6 +144,9 @@ def create_service(
"audio-separator-service",
name="audio-separator",
location=AUDIO_SEPARATOR_REGION,
# Off by default and only brought up on demand (see __main__.py), so
# it must be destroyable by flipping audioSeparatorServiceEnabled off.
deletion_protection=False,
ingress="INGRESS_TRAFFIC_ALL",
template=cloudrunv2.ServiceTemplateArgs(
scaling=cloudrunv2.ServiceTemplateScalingArgs(
@@ -2,13 +2,16 @@
Artifact Registry for GPU Docker images.
Located in us-east4 (co-located with L4 GPU instances).
Stores the karaoke-backend-gpu base image used by the audio worker.
Stores the final GPU app image (karaoke-backend) pulled by the audio-separation
job and the CPU job image (karaoke-backend-cpu). The ~13 GB GPU *base* image
moved to us-central1 karaoke-repo on 2026-09-27.
"""
import pulumi_gcp as gcp
from pulumi_gcp import artifactregistry
from config import PROJECT_ID
from modules.artifact_registry import CLEANUP_POLICY_DRY_RUN, standard_cleanup_policies
GPU_REGION = "us-east4"
@@ -21,24 +24,7 @@ def create_gpu_artifact_repo() -> artifactregistry.Repository:
location=GPU_REGION,
format="DOCKER",
description="Docker repository for GPU-enabled karaoke-backend images (audio worker)",
# Cost control: GPU images are multi-GB. Keep 10 most recent versions
# for rollback; delete untagged digests older than 7 days.
cleanup_policies=[
artifactregistry.RepositoryCleanupPolicyArgs(
id="keep-recent-10",
action="KEEP",
most_recent_versions=artifactregistry.RepositoryCleanupPolicyMostRecentVersionsArgs(
keep_count=10,
),
),
artifactregistry.RepositoryCleanupPolicyArgs(
id="delete-untagged-after-7d",
action="DELETE",
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
tag_state="UNTAGGED",
older_than="604800s", # 7 days
),
),
],
cleanup_policy_dry_run=False,
# Cost control: GPU images are multi-GB. See standard_cleanup_policies().
cleanup_policies=standard_cleanup_policies(),
cleanup_policy_dry_run=CLEANUP_POLICY_DRY_RUN,
)
+5
View File
@@ -240,6 +240,11 @@ class AudioProcessor:
except Exception as e:
error_str = str(e)
self.logger.error(f"Remote API processing failed: {error_str}")
self.logger.error(
"Note: Nomad Karaoke's hosted audio-separator API (Cloud Run, us-east4) "
"was shut down on 2026-10-01 to cut costs. Unset AUDIO_SEPARATOR_API_URL "
"to separate locally on this machine, or point it at your own deployment."
)
# Never fall back for API processing errors (download failures,
# missing files, etc.) — retrying locally won't help.
# Only fall back for transient network errors AND only when
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.261.2"
version = "0.261.4"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"