mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-04 17:16:04 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a5f754efd | ||
|
|
5b2a0f8c3e | ||
|
|
87a36bd2a5 | ||
|
|
c138c9d1ac | ||
|
|
8cbcc03099 | ||
|
|
7179e2863f |
No files matched your search
@@ -14,7 +14,8 @@ name: Build GHA Runner Images
|
||||
# 3. Stop the VM, snapshot its boot disk to a new image in the `gha-runner-<variant>`
|
||||
# image family with name gha-runner-<variant>-<timestamp>.
|
||||
# 4. Delete the build VM (boot disk auto-deletes).
|
||||
# 5. Delete older images in the family, keeping the newest 2 (rollback = previous month).
|
||||
# 5. Delete older images in the family, keeping only the newest (GPU/windows images
|
||||
# are 15-21 GiB each; roll back by re-running this workflow at an older ref).
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -41,7 +42,7 @@ env:
|
||||
BUILD_REGION: us-central1
|
||||
BUILD_ZONE: us-central1-a
|
||||
BASE_IMAGE: projects/debian-cloud/global/images/family/debian-12
|
||||
KEEP_IMAGES_PER_FAMILY: 2
|
||||
KEEP_IMAGES_PER_FAMILY: 1
|
||||
|
||||
jobs:
|
||||
resolve-matrix:
|
||||
|
||||
+247
-389
@@ -7,6 +7,15 @@ on:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force_encoding_worker_deploy:
|
||||
# Manual override for the encoding-worker deploy gate (see "Decide
|
||||
# encoding-worker deploy" in deploy-backend). Dispatch on main re-runs
|
||||
# package-build + deploy-backend; with this ticked the GCE worker is
|
||||
# blue-green redeployed even if no worker code changed.
|
||||
description: "Force a blue-green redeploy of the GCE encoding worker"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -51,6 +60,9 @@ jobs:
|
||||
- 'infrastructure/**'
|
||||
deps:
|
||||
- 'poetry.lock'
|
||||
# CI config changes (runners, setup steps) must exercise the
|
||||
# package/backend test jobs they affect.
|
||||
- '.github/workflows/ci.yml'
|
||||
|
||||
- name: Summary
|
||||
run: |
|
||||
@@ -179,7 +191,7 @@ jobs:
|
||||
|
||||
frontend-e2e-full:
|
||||
name: "Frontend - E2E Full"
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
# Full E2E suite only runs when PR has 'e2e' label (on-demand)
|
||||
if: >-
|
||||
@@ -187,23 +199,6 @@ jobs:
|
||||
needs.changes.outputs.frontend == 'true' &&
|
||||
contains(github.event.pull_request.labels.*.name, 'e2e')
|
||||
steps:
|
||||
- name: Check disk space
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Disk usage high, running cleanup..."
|
||||
docker system prune -af || true
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js with caching
|
||||
@@ -334,25 +329,23 @@ jobs:
|
||||
|
||||
package-unit-tests:
|
||||
name: "Package - Unit Tests (70% coverage)"
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- name: Check disk space
|
||||
- name: Free disk space (only if low)
|
||||
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
|
||||
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
|
||||
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
|
||||
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
|
||||
# the rm takes ~1 min.
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Disk usage high, running cleanup..."
|
||||
docker system prune -af || true
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
exit 1
|
||||
df -h /
|
||||
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
|
||||
if [ "$AVAIL_GB" -lt 30 ]; then
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
|
||||
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
|
||||
df -h /
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
@@ -374,9 +367,9 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-package-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
key: venv-package-hosted-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
venv-package-hosted-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install --with dev
|
||||
@@ -420,25 +413,23 @@ jobs:
|
||||
|
||||
package-integration-tests:
|
||||
name: "Package - Integration Tests"
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- name: Check disk space
|
||||
- name: Free disk space (only if low)
|
||||
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
|
||||
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
|
||||
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
|
||||
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
|
||||
# the rm takes ~1 min.
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Disk usage high, running cleanup..."
|
||||
docker system prune -af || true
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
exit 1
|
||||
df -h /
|
||||
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
|
||||
if [ "$AVAIL_GB" -lt 30 ]; then
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
|
||||
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
|
||||
df -h /
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
@@ -460,9 +451,9 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-package-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
key: venv-package-hosted-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
venv-package-hosted-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install --with dev
|
||||
@@ -497,7 +488,7 @@ jobs:
|
||||
|
||||
package-build-test:
|
||||
name: "Package - Build & Install (Test)"
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
runs-on: ubuntu-latest
|
||||
needs: [changes, package-unit-tests, package-integration-tests]
|
||||
if: >-
|
||||
github.ref != 'refs/heads/main' && always() &&
|
||||
@@ -505,21 +496,19 @@ jobs:
|
||||
(needs.package-integration-tests.result == 'success' || needs.package-integration-tests.result == 'skipped') &&
|
||||
(needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- name: Check disk space
|
||||
- name: Free disk space (only if low)
|
||||
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
|
||||
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
|
||||
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
|
||||
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
|
||||
# the rm takes ~1 min.
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Disk usage high, running cleanup..."
|
||||
docker system prune -af || true
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
exit 1
|
||||
df -h /
|
||||
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
|
||||
if [ "$AVAIL_GB" -lt 30 ]; then
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
|
||||
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
|
||||
df -h /
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
@@ -577,25 +566,23 @@ jobs:
|
||||
|
||||
backend-unit-tests:
|
||||
name: "Backend - Unit Tests"
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- name: Check disk space
|
||||
- name: Free disk space (only if low)
|
||||
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
|
||||
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
|
||||
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
|
||||
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
|
||||
# the rm takes ~1 min.
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Disk usage high, running cleanup..."
|
||||
docker system prune -af || true
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
exit 1
|
||||
df -h /
|
||||
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
|
||||
if [ "$AVAIL_GB" -lt 30 ]; then
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
|
||||
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
|
||||
df -h /
|
||||
fi
|
||||
|
||||
- name: Checkout code
|
||||
@@ -618,9 +605,9 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-backend-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
key: venv-backend-hosted-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-backend-${{ runner.os }}-py3.13-
|
||||
venv-backend-hosted-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
@@ -648,25 +635,23 @@ jobs:
|
||||
|
||||
backend-emulator-tests:
|
||||
name: "Backend - Emulator Integration Tests"
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- name: Check disk space
|
||||
- name: Free disk space (only if low)
|
||||
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
|
||||
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
|
||||
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
|
||||
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
|
||||
# the rm takes ~1 min.
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Disk usage high, running cleanup..."
|
||||
docker system prune -af || true
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
exit 1
|
||||
df -h /
|
||||
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
|
||||
if [ "$AVAIL_GB" -lt 30 ]; then
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
|
||||
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
|
||||
df -h /
|
||||
fi
|
||||
|
||||
- name: Checkout code
|
||||
@@ -689,9 +674,9 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-backend-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
key: venv-backend-hosted-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-backend-${{ runner.os }}-py3.13-
|
||||
venv-backend-hosted-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Set up Java 21 (required by Firestore emulator)
|
||||
uses: actions/setup-java@v4
|
||||
@@ -847,24 +832,22 @@ jobs:
|
||||
|
||||
package-build:
|
||||
name: "Package - Build"
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
|
||||
steps:
|
||||
- name: Check disk space
|
||||
- name: Free disk space (only if low)
|
||||
# GitHub-hosted runners (free for this public repo) currently have ~86 GB
|
||||
# free, but only ~14 GB is documented. The poetry venv (CUDA torch wheels)
|
||||
# plus poetry's download cache need ~20 GB, so if the image ever shrinks,
|
||||
# drop preinstalled SDKs we never use. Skipped (0s) when space is ample;
|
||||
# the rm takes ~1 min.
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Disk usage high, running cleanup..."
|
||||
docker system prune -af || true
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
exit 1
|
||||
df -h /
|
||||
AVAIL_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
|
||||
if [ "$AVAIL_GB" -lt 30 ]; then
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
|
||||
/usr/local/.ghcup /opt/hostedtoolcache/CodeQL
|
||||
df -h /
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
@@ -886,9 +869,9 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-package-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
key: venv-package-hosted-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
venv-package-hosted-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -1105,16 +1088,13 @@ jobs:
|
||||
name: "Deploy - Backend (Cloud Run)"
|
||||
needs: [package-build]
|
||||
runs-on: [self-hosted, linux, gcp, docker-build]
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
outputs:
|
||||
base_rebuilt: ${{ steps.check-base.outputs.needs_rebuild }}
|
||||
version: ${{ steps.version_check.outputs.version }}
|
||||
# R1: gates the post-deploy canary — "true" only when the backend version
|
||||
# actually changed (see "Detect backend version change" step).
|
||||
version_changed: ${{ steps.version_changed.outputs.changed }}
|
||||
env:
|
||||
REGISTRY: us-central1-docker.pkg.dev
|
||||
PROJECT_ID: nomadkaraoke
|
||||
@@ -1170,43 +1150,6 @@ jobs:
|
||||
echo "📋 Current version: $VERSION"
|
||||
echo "🚀 Deploying on every push to main"
|
||||
|
||||
# R1 gate — only run the post-deploy functional canary when the BACKEND
|
||||
# version actually changed. A frontend-/docs-/infra-only merge still runs
|
||||
# deploy-backend (image rebuild) but ships an identical version; a real
|
||||
# karaoke generation is slow + resource-heavy, so we short-circuit the
|
||||
# canary in that case. We compare the version we're about to ship against
|
||||
# the version currently served by production.
|
||||
- name: Detect backend version change
|
||||
id: version_changed
|
||||
run: |
|
||||
NEW_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
# Read the currently-serving version via the EDGE (api.nomadkaraoke.com),
|
||||
# NOT the raw Cloud Run origin URL, and retry. The single un-retried
|
||||
# origin probe returned empty on #987 (cold start on the scaled-to-zero
|
||||
# prior revision and/or origin edge-auth on the detailed endpoint), so
|
||||
# the gate fail-opened and ran the canary on a no-bump deploy — which
|
||||
# then flake-failed and paged. The edge URL is warm (real traffic) and
|
||||
# Cloudflare-fronted, so it returns the version reliably.
|
||||
CURRENT_VERSION=""
|
||||
for attempt in 1 2 3 4; do
|
||||
CURRENT_VERSION=$(curl -sf --connect-timeout 5 --max-time 25 \
|
||||
"https://api.nomadkaraoke.com/api/health/detailed" | jq -r '.version // empty' 2>/dev/null || echo "")
|
||||
[ -n "$CURRENT_VERSION" ] && break
|
||||
echo " version probe attempt $attempt/4 empty; retrying…"
|
||||
sleep 5
|
||||
done
|
||||
echo "Currently-serving version: ${CURRENT_VERSION:-<unknown>}"
|
||||
echo "New version: $NEW_VERSION"
|
||||
if [ -n "$CURRENT_VERSION" ] && [ "$CURRENT_VERSION" = "$NEW_VERSION" ]; then
|
||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "↩️ Backend version unchanged — post-deploy canary will be SKIPPED."
|
||||
else
|
||||
# Unknown current version (first deploy / unreachable after retries) →
|
||||
# run the canary to be safe rather than skip a potentially real change.
|
||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
||||
echo "✅ Backend version changed (or current unknown) — post-deploy canary will RUN."
|
||||
fi
|
||||
|
||||
- name: Capture build metadata
|
||||
id: build-meta
|
||||
run: |
|
||||
@@ -1315,7 +1258,9 @@ jobs:
|
||||
for key in ["primary_vm", "primary_ip", "primary_version",
|
||||
"secondary_vm", "secondary_ip",
|
||||
"active_override_vm", "active_override_ip", "active_override_zone"]:
|
||||
f.write(f"{key}={data.get(key, '')}\n")
|
||||
# `or ''`: a key stored as null must be empty, not the string
|
||||
# "None" (which later steps would treat as a real VM name).
|
||||
f.write(f"{key}={data.get(key) or ''}\n")
|
||||
f.write(f"deploy_in_progress={str(data.get('deploy_in_progress', False)).lower()}\n")
|
||||
# capacity_state is a map — emit as single-line JSON so the green
|
||||
# selection step can demote recently-stocked-out machine types.
|
||||
@@ -1324,8 +1269,47 @@ jobs:
|
||||
f"active_override={data.get('active_override_vm')}")
|
||||
PYEOF
|
||||
|
||||
# Gate the blue-green worker deploy on worker-affecting changes. It boots a
|
||||
# fresh green VM + runs a real test encode, which used to happen on EVERY
|
||||
# push to main (~5x/day) even for frontend/backend-only changes. The wheel,
|
||||
# startup.sh and version.txt above are still uploaded every time, so any
|
||||
# worker that cold-boots (they idle-stop after 5 min) runs the latest code.
|
||||
# Diff base = the version the serving worker was last validated at (not
|
||||
# github.event.before), so a cancelled/skipped deploy can never lose a
|
||||
# worker change. Any doubt → deploy (fail open).
|
||||
- name: Decide encoding-worker deploy
|
||||
id: worker_gate
|
||||
env:
|
||||
FORCE: ${{ github.event_name == 'workflow_dispatch' && inputs.force_encoding_worker_deploy == true }}
|
||||
SERVING_VERSION: ${{ steps.config.outputs.primary_version }}
|
||||
OVERRIDE_VM: ${{ steps.config.outputs.active_override_vm }}
|
||||
run: |
|
||||
mapfile -t PATHS < <(grep -v '^\s*#' infrastructure/encoding-worker/worker_code_paths.txt | grep -v '^\s*$')
|
||||
DEPLOY=true
|
||||
if [ "$FORCE" = "true" ]; then
|
||||
REASON="manual override (workflow_dispatch force_encoding_worker_deploy)"
|
||||
elif [ -n "$OVERRIDE_VM" ] && [ "$OVERRIDE_VM" != "None" ]; then
|
||||
REASON="capacity override $OVERRIDE_VM is serving — refresh it"
|
||||
elif [ -z "$SERVING_VERSION" ] || [ "$SERVING_VERSION" = "None" ]; then
|
||||
REASON="serving worker version unknown"
|
||||
elif ! git fetch --no-tags --depth=1 origin "refs/tags/v${SERVING_VERSION}:refs/tags/v${SERVING_VERSION}"; then
|
||||
REASON="tag v${SERVING_VERSION} not fetchable"
|
||||
elif ! CHANGED=$(git diff --name-only "v${SERVING_VERSION}" HEAD -- "${PATHS[@]}"); then
|
||||
REASON="git diff against v${SERVING_VERSION} failed"
|
||||
elif [ -z "$CHANGED" ]; then
|
||||
DEPLOY=false
|
||||
REASON="no worker-affecting changes since serving v${SERVING_VERSION}"
|
||||
else
|
||||
REASON="worker-affecting changes since v${SERVING_VERSION}"
|
||||
echo "Changed worker paths:"; echo "$CHANGED" | head -50
|
||||
fi
|
||||
echo "deploy=${DEPLOY}" >> "$GITHUB_OUTPUT"
|
||||
echo "Encoding-worker blue-green deploy: ${DEPLOY} (${REASON})"
|
||||
echo "### Encoding worker deploy: ${DEPLOY}" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "${REASON}" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Wait for concurrent deploy
|
||||
if: steps.config.outputs.deploy_in_progress == 'true'
|
||||
if: steps.worker_gate.outputs.deploy == 'true' && steps.config.outputs.deploy_in_progress == 'true'
|
||||
run: |
|
||||
echo "Another deploy is in progress, waiting..."
|
||||
python3 << 'PYEOF'
|
||||
@@ -1344,6 +1328,7 @@ jobs:
|
||||
PYEOF
|
||||
|
||||
- name: Set deploy in progress
|
||||
if: steps.worker_gate.outputs.deploy == 'true'
|
||||
run: |
|
||||
python3 << 'PYEOF'
|
||||
from datetime import datetime, timezone
|
||||
@@ -1364,6 +1349,7 @@ jobs:
|
||||
# infrastructure/encoding-worker/deploy_promote.py.
|
||||
- name: Select & start green target
|
||||
id: green
|
||||
if: steps.worker_gate.outputs.deploy == 'true'
|
||||
# Never hard-fail the whole backend deploy just because no encoding
|
||||
# worker could be validated — emit green_ok=false and let the gated
|
||||
# health/encode/promote steps skip while the Cloud Run deploy proceeds.
|
||||
@@ -1604,7 +1590,7 @@ jobs:
|
||||
# always() so the deploy_in_progress flag is ALWAYS cleared, even when the
|
||||
# green step found no worker (its downstream steps skip, but the flag was
|
||||
# already set). Skips only on a fully successful promote (passed == true).
|
||||
if: always() && steps.encode-test.outputs.passed != 'true'
|
||||
if: always() && steps.worker_gate.outputs.deploy == 'true' && steps.encode-test.outputs.passed != 'true'
|
||||
run: |
|
||||
GREEN_VM="${{ steps.green.outputs.green_vm }}"
|
||||
GREEN_ZONE="${{ steps.green.outputs.green_zone }}"
|
||||
@@ -1745,7 +1731,7 @@ jobs:
|
||||
# step guarantees the lock is released so the next deploy doesn't stall 10 min
|
||||
# in "Wait for concurrent deploy". Idempotent with the other clears.
|
||||
- name: Clear encoding-worker deploy lock
|
||||
if: always()
|
||||
if: always() && steps.worker_gate.outputs.deploy == 'true'
|
||||
run: |
|
||||
python3 -c "
|
||||
from google.cloud import firestore
|
||||
@@ -1881,8 +1867,16 @@ jobs:
|
||||
|
||||
# ============================================
|
||||
# GPU Image Build (for audio worker with L4 GPU)
|
||||
# Same pattern as base image: hash check → rebuild if needed
|
||||
# GPU image lives in us-east4 (co-located with GPU instances)
|
||||
# Same pattern as base image: hash check → rebuild if needed.
|
||||
#
|
||||
# Region layout (cost): the ~13 GB GPU base image and all BuildKit
|
||||
# caches live in us-central1 (karaoke-repo), next to this runner, so
|
||||
# building the app layer on top of the base is same-region (free). Only
|
||||
# the FINAL app image is pushed to us-east4 (karaoke-backend-gpu), where
|
||||
# the audio-separation Cloud Run job pulls it same-region. That push only
|
||||
# uploads the small changed app layers — the base layers already exist
|
||||
# there. Previously the base lived in us-east4 and every deploy pulled
|
||||
# ~13 GB across regions (~$12-16/mo AR inter-region egress).
|
||||
# ============================================
|
||||
|
||||
- name: Calculate GPU base image hash
|
||||
@@ -1898,33 +1892,74 @@ jobs:
|
||||
- name: Check if GPU base image exists and is current
|
||||
id: check-gpu-base
|
||||
run: |
|
||||
GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
|
||||
EXISTING_HASH=""
|
||||
WANT_HASH="${{ steps.gpu-base-hash.outputs.hash }}"
|
||||
GPU_BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
|
||||
# Legacy location (pre cost-fix). Only used to seed us-central1 once.
|
||||
LEGACY_GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
|
||||
|
||||
MANIFEST=$(docker manifest inspect $GPU_BASE_IMAGE 2>/dev/null || echo "")
|
||||
CONFIG_DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
|
||||
# Read the base.content.hash label of an image without pulling it
|
||||
# (manifest ~1KB + config blob ~10KB).
|
||||
image_hash() {
|
||||
local image="$1" host path manifest digest
|
||||
host="${image%%/*}"
|
||||
path="${image#*/}"
|
||||
path="${path%:*}"
|
||||
manifest=$(docker manifest inspect "$image" 2>/dev/null || echo "")
|
||||
# `buildx imagetools create` (the one-time copy below) wraps the
|
||||
# image in a single-entry index — follow it to the image manifest.
|
||||
local child
|
||||
child=$(echo "$manifest" | jq -r '.manifests[0].digest // ""' 2>/dev/null || echo "")
|
||||
if [ -n "$child" ] && [ "$child" != "null" ]; then
|
||||
manifest=$(docker manifest inspect "${image%:*}@${child}" 2>/dev/null || echo "")
|
||||
fi
|
||||
digest=$(echo "$manifest" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
|
||||
if [ -z "$digest" ] || [ "$digest" = "null" ]; then
|
||||
echo ""
|
||||
return
|
||||
fi
|
||||
curl -sL -H "Authorization: Bearer $(gcloud auth print-access-token)" \
|
||||
"https://${host}/v2/${path}/blobs/${digest}" 2>/dev/null \
|
||||
| jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo ""
|
||||
}
|
||||
|
||||
if [ -n "$CONFIG_DIGEST" ] && [ "$CONFIG_DIGEST" != "null" ] && [ "$CONFIG_DIGEST" != "" ]; then
|
||||
echo "📋 Found GPU manifest, config digest: $CONFIG_DIGEST"
|
||||
TOKEN=$(gcloud auth print-access-token)
|
||||
CONFIG_JSON=$(curl -sL -H "Authorization: Bearer $TOKEN" \
|
||||
"https://${{ env.GPU_REGISTRY }}/v2/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}/blobs/$CONFIG_DIGEST" 2>/dev/null)
|
||||
EXISTING_HASH=$(echo "$CONFIG_JSON" | jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo "")
|
||||
echo "📋 Registry GPU base image hash: $EXISTING_HASH"
|
||||
else
|
||||
echo "⚠️ No existing GPU base image found in registry - will build"
|
||||
fi
|
||||
EXISTING_HASH=$(image_hash "$GPU_BASE_IMAGE")
|
||||
echo "📋 Registry GPU base image hash (us-central1): ${EXISTING_HASH:-<none>}"
|
||||
|
||||
if [ "${{ steps.gpu-base-hash.outputs.hash }}" != "$EXISTING_HASH" ]; then
|
||||
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or pyproject.toml changed)"
|
||||
echo " Current: ${{ steps.gpu-base-hash.outputs.hash }}"
|
||||
echo " Registry: $EXISTING_HASH"
|
||||
echo "needs_rebuild=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
if [ -n "$EXISTING_HASH" ] && [ "$EXISTING_HASH" = "$WANT_HASH" ]; then
|
||||
echo "✅ GPU base image is up to date"
|
||||
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
|
||||
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# One-time migration: if the legacy us-east4 base is already current,
|
||||
# copy it byte-for-byte (same digests) instead of rebuilding from
|
||||
# scratch, so the image content is unchanged by the move.
|
||||
LEGACY_HASH=$(image_hash "$LEGACY_GPU_BASE_IMAGE")
|
||||
echo "📋 Legacy GPU base image hash (us-east4): ${LEGACY_HASH:-<none>}"
|
||||
if [ -n "$LEGACY_HASH" ] && [ "$LEGACY_HASH" = "$WANT_HASH" ]; then
|
||||
echo "📦 Copying current GPU base from us-east4 to us-central1 (one-time)..."
|
||||
if timeout 30m docker buildx imagetools create --tag "$GPU_BASE_IMAGE" "$LEGACY_GPU_BASE_IMAGE"; then
|
||||
echo "✅ GPU base copied to us-central1"
|
||||
# imagetools wraps the image in a single-entry index; tag the
|
||||
# child manifest too so AR's delete-untagged cleanup policy can
|
||||
# never treat it as an orphan.
|
||||
CHILD=$(docker manifest inspect "$GPU_BASE_IMAGE" | jq -r '.manifests[0].digest // ""' || echo "")
|
||||
if [ -n "$CHILD" ]; then
|
||||
gcloud artifacts docker tags add "${GPU_BASE_IMAGE%:*}@${CHILD}" \
|
||||
"${GPU_BASE_IMAGE%:*}:content-${WANT_HASH:0:12}" --quiet \
|
||||
|| echo "⚠️ Could not tag child manifest (non-fatal)"
|
||||
fi
|
||||
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
echo "⚠️ Copy failed — falling back to a rebuild"
|
||||
fi
|
||||
|
||||
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or poetry.lock changed)"
|
||||
echo " Current: $WANT_HASH"
|
||||
echo " Registry: $EXISTING_HASH"
|
||||
echo "needs_rebuild=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push GPU base image (if needed)
|
||||
if: steps.check-gpu-base.outputs.needs_rebuild == 'true'
|
||||
timeout-minutes: 45
|
||||
@@ -1934,10 +1969,10 @@ jobs:
|
||||
file: backend/Dockerfile.gpu-base
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
|
||||
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
build-args: |
|
||||
BUILD_DATE=${{ github.run_id }}
|
||||
BUILD_ID=${{ github.sha }}
|
||||
@@ -1945,20 +1980,25 @@ jobs:
|
||||
provenance: false
|
||||
|
||||
- name: Build and push GPU app image
|
||||
timeout-minutes: 10
|
||||
# Normally ~2 min (only app layers are new). After a GPU base rebuild
|
||||
# this push also uploads the ~13 GB base layers to us-east4 (they can't
|
||||
# be cross-mounted from the us-central1 registry), hence the headroom.
|
||||
timeout-minutes: 40
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile
|
||||
push: true
|
||||
# Final image → us-east4 (same region as the audio-separation job).
|
||||
tags: |
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:latest
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
# Base + cache → us-central1 (same region as this runner).
|
||||
build-args: |
|
||||
BASE_IMAGE=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
BASE_IMAGE=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/karaoke-backend-gpu:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/karaoke-backend-gpu:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
|
||||
# ============================================
|
||||
@@ -1977,8 +2017,8 @@ jobs:
|
||||
# smoke fails we simply don't migrate: traffic stays on the prior revision,
|
||||
# so a bad revision serves 0% instead of 100% (auto-revert by default).
|
||||
# NOTE: this protects only the Cloud Run *service*. The Cloud Run *jobs*
|
||||
# updated below cannot traffic-split, so they still rely on R1's real-job
|
||||
# post-deploy canary + the codified `scripts/rollback.sh` (R2).
|
||||
# updated below cannot traffic-split, so they rely on the daily E2E run +
|
||||
# the codified `scripts/rollback.sh` (R2).
|
||||
- name: Deploy to Cloud Run (candidate revision, no traffic)
|
||||
id: deploy_candidate
|
||||
run: |
|
||||
@@ -2004,9 +2044,11 @@ jobs:
|
||||
# that but overshot once the loop was made non-blocking: every burst
|
||||
# forced scale-out, and each overflow request waited out a ~16s app
|
||||
# cold start (2026-09-22 16-tab test: warm instance served in 1.2s,
|
||||
# freshly-spawned ones in 16-19s). 32 + --min-instances 2 gives 64
|
||||
# warm slots so a 16-tab reload is absorbed without cold starts,
|
||||
# while staying far below the wedge-era 80.
|
||||
# freshly-spawned ones in 16-19s). 32 + --min-instances 2 gave 64
|
||||
# warm slots; min-instances was cut to 1 on 2026-09-26 (GCP cost cut,
|
||||
# accepted perf trade-off: big bursts may hit a ~15s cold start) while
|
||||
# staying far below the wedge-era 80. --clear-vpc-connector: the
|
||||
# serverless VPC connector was deleted (flacfetch is public now).
|
||||
gcloud run deploy karaoke-backend \
|
||||
--image $IMAGE \
|
||||
--no-traffic \
|
||||
@@ -2022,9 +2064,8 @@ jobs:
|
||||
--timeout 1800 \
|
||||
--concurrency 32 \
|
||||
--max-instances 20 \
|
||||
--min-instances 2 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--min-instances 1 \
|
||||
--clear-vpc-connector \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
|
||||
|
||||
@@ -2080,9 +2121,9 @@ jobs:
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
# NOTE: Cloud Run *Jobs* cannot traffic-split or canary — this is an
|
||||
# image-only, all-or-nothing update picked up on each job's next
|
||||
# invocation. There is no per-revision smoke here; the jobs rely on R1's
|
||||
# post-deploy real-job canary and the codified `scripts/rollback.sh` (R2)
|
||||
# for recovery if a bad image reaches them.
|
||||
# invocation. There is no per-revision smoke here; the jobs rely on the
|
||||
# daily E2E run and the codified `scripts/rollback.sh` (R2) for recovery
|
||||
# if a bad image reaches them.
|
||||
run: |
|
||||
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
GPU_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
@@ -2172,189 +2213,6 @@ jobs:
|
||||
echo "📊 Built on self-hosted GCP runner (200GB SSD, no disk space issues)"
|
||||
echo " Runner: gcp-runner with 4 vCPU, 16GB RAM"
|
||||
|
||||
# ============================================
|
||||
# R1 — POST-DEPLOY FUNCTIONAL CANARY (version-change-gated)
|
||||
# Runs the real production happy-path (admin-credit variant, no Stripe) after
|
||||
# a backend deploy — but ONLY when the backend version actually changed
|
||||
# (deploy-backend.outputs.version_changed == 'true'). A frontend-/docs-/
|
||||
# infra-only merge ships an identical backend version and short-circuits here,
|
||||
# so we don't burn encode-VM time + a real Drive/YouTube publish on a no-op.
|
||||
# On failure: the workflow fails loudly (Discord) — this is where an operator
|
||||
# invokes `scripts/rollback.sh` (R2) to revert the service + jobs.
|
||||
# ============================================
|
||||
deploy-verify:
|
||||
name: "Deploy - Post-Deploy Canary (Happy Path)"
|
||||
needs: [deploy-backend]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
if: >-
|
||||
github.ref == 'refs/heads/main' && github.event_name == 'push' &&
|
||||
needs.deploy-backend.result == 'success' &&
|
||||
needs.deploy-backend.outputs.version_changed == 'true'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
# Admin-credit variant: impersonate the E2E test runner (which holds
|
||||
# admin-granted credits) instead of going through Stripe. Same token-refresh
|
||||
# pattern as e2e-daily.yml's use_test_token path.
|
||||
- name: Refresh E2E session token
|
||||
id: refresh_token
|
||||
run: |
|
||||
RESPONSE=$(curl -sf --connect-timeout 5 --max-time 30 -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run post-deploy happy-path canary
|
||||
id: run_test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
run: |
|
||||
echo "=== Post-deploy canary: happy path against production ==="
|
||||
echo "Deployed version: ${{ needs.deploy-backend.outputs.version }}"
|
||||
echo "Time: $(date)"
|
||||
# --retries=2: the happy-path has inherently flaky UI waits (e.g. the
|
||||
# review page's "proceed to instrumental" enable), and this canary
|
||||
# PAGES on failure — a single flaky attempt must not cry wolf. Only a
|
||||
# failure that survives 2 retries is treated as real.
|
||||
npx playwright test happy-path-real-user.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=chromium \
|
||||
--reporter=list \
|
||||
--retries=2 \
|
||||
--timeout=3600000 \
|
||||
2>&1 | tee test-output-canary.log
|
||||
# Capture Playwright's real exit code, not tee's (0). Matches
|
||||
# e2e-daily.yml's rationale (grepping the log is fragile).
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check canary result
|
||||
id: test_result
|
||||
run: |
|
||||
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
|
||||
echo "result=success" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "result=failure" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Upload canary artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: deploy-verify-canary-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
frontend/test-output-canary.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Discord notification (canary failed)
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"🚨 Post-deploy canary FAILED (v${{ needs.deploy-backend.outputs.version }})\", \"description\": \"The production happy-path failed AFTER deploying v${{ needs.deploy-backend.outputs.version }}. The service already migrated 100% traffic to the new revision — consider rolling back with scripts/rollback.sh.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}" || echo "Discord notify failed (non-fatal)"
|
||||
|
||||
- name: Fail if canary failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
echo "::error::Post-deploy canary failed for v${{ needs.deploy-backend.outputs.version }}."
|
||||
echo "Roll back now with:"
|
||||
echo " scripts/rollback.sh --list # find the previous good revision + version"
|
||||
echo " scripts/rollback.sh --to-revision <PREV_REV> --image-version <PREV_VERSION>"
|
||||
exit 1
|
||||
|
||||
# ============================================
|
||||
# PROPAGATE BASE IMAGE TO ALL RUNNERS
|
||||
# When base image is rebuilt, pull it to all 3 runners
|
||||
# so subsequent app builds don't wait 8 min for the pull
|
||||
#
|
||||
# NOTE: This is best-effort distribution. GitHub Actions doesn't
|
||||
# support targeting specific runners by name, so we spawn 3 jobs
|
||||
# and rely on the scheduler to distribute them across idle runners.
|
||||
# In practice, with all runners idle after deploy-backend, distribution
|
||||
# is good. Runners that miss this pull will get the image on their
|
||||
# next app build (with the 8 min delay).
|
||||
# ============================================
|
||||
|
||||
propagate-base-image:
|
||||
name: "Propagate Base Image (${{ matrix.runner_index }})"
|
||||
needs: deploy-backend
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push' && needs.deploy-backend.outputs.base_rebuilt == 'true'
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
strategy:
|
||||
matrix:
|
||||
# 3 parallel jobs - one per self-hosted runner
|
||||
runner_index: [1, 2, 3]
|
||||
max-parallel: 3
|
||||
fail-fast: false # Don't cancel other runners if one fails
|
||||
env:
|
||||
REGISTRY: us-central1-docker.pkg.dev
|
||||
PROJECT_ID: nomadkaraoke
|
||||
REPOSITORY: karaoke-repo
|
||||
BASE_IMAGE_NAME: karaoke-backend-base
|
||||
steps:
|
||||
- name: Authenticate to Google Cloud (Workload Identity)
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- name: Set up Cloud SDK
|
||||
uses: google-github-actions/setup-gcloud@v2
|
||||
with:
|
||||
version: "latest"
|
||||
|
||||
- name: Configure Docker for Artifact Registry
|
||||
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
|
||||
|
||||
- name: Pull latest base image
|
||||
run: |
|
||||
BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest"
|
||||
RUNNER_NAME=$(hostname)
|
||||
echo "📥 Pulling latest base image on runner $RUNNER_NAME..."
|
||||
docker pull $BASE_IMAGE
|
||||
echo "✅ Base image cached on $RUNNER_NAME"
|
||||
|
||||
# NOTE: Pulumi infrastructure deploys are done locally, not in CI.
|
||||
# CI runners run on the infrastructure Pulumi manages, creating a circular
|
||||
# dependency. Always run `pulumi up` locally before merging infra PRs.
|
||||
|
||||
@@ -55,21 +55,25 @@ jobs:
|
||||
BUCKET = os.environ["BUCKET"]
|
||||
# (label, prefix, max_age_hours, require_suffix)
|
||||
# require_suffix: only objects with this key suffix count toward
|
||||
# freshness (None = any object). git-repos/ requires ".bundle" so the
|
||||
# always-written manifest.json can't mark the prefix fresh when every
|
||||
# bundle failed / nothing was bundled — 0 bundles then reads as stale.
|
||||
# freshness (None = any object).
|
||||
# NOTE: Firestore and BigQuery export to GCS staging nightly but are
|
||||
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
|
||||
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
|
||||
# sees the S3 (off-site) copy, so their limits must allow a full week
|
||||
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
|
||||
# files and secrets DO upload to S3 nightly, so they stay at 36h.
|
||||
# Git repos are also weekly (Sundays) AND incremental since
|
||||
# 2026-09-26 — only repos pushed that week get a fresh bundle, so a
|
||||
# quiet week legitimately leaves every .bundle older than 8 days.
|
||||
# Freshness is judged on git-repos/manifest.json instead (rewritten
|
||||
# every weekly run), and the manifest's contents are checked below so
|
||||
# a run where every repo failed still reads as stale.
|
||||
TARGETS = [
|
||||
("Firestore", "firestore/", 192, None),
|
||||
("GCS job files", "gcs/job-files/", 36, None),
|
||||
("Encrypted secrets", "secrets/", 36, None),
|
||||
("BigQuery weekly", "bigquery/daily-refresh/", 192, None),
|
||||
("Git repos", "git-repos/", 36, ".bundle"),
|
||||
("Git repos", "git-repos/manifest.json", 192, None),
|
||||
]
|
||||
|
||||
s3 = boto3.client("s3")
|
||||
@@ -97,6 +101,19 @@ jobs:
|
||||
line = f"{label}: {age_h}h old (limit {max_hours}h) — last {latest.isoformat()}"
|
||||
(stale if age > max_hours * 3600 else ok).append(line)
|
||||
|
||||
# Git manifest contents: ANY bundle error alerts, even though the
|
||||
# manifest itself is fresh. The git step is weekly + incremental, so
|
||||
# a repo that failed keeps an ever-older S3 bundle until the next
|
||||
# Sunday — silence here would let it drift past the 7-day RPO.
|
||||
try:
|
||||
import json as _json
|
||||
m = _json.loads(s3.get_object(Bucket=BUCKET, Key="git-repos/manifest.json")["Body"].read())
|
||||
if int(m.get("errors", 0)) > 0:
|
||||
failed = [r.get("full_name") for r in m.get("repos", []) if r.get("status") == "error"]
|
||||
stale.append(f"Git repos: last run had {m.get('errors')} bundle errors: {', '.join(failed[:10])}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
stale.append(f"Git repos: could not read manifest.json ({e})")
|
||||
|
||||
summary = ["## DR backup freshness", ""]
|
||||
if stale:
|
||||
summary.append("### Stale")
|
||||
|
||||
@@ -149,9 +149,12 @@ EOF
|
||||
```
|
||||
|
||||
### GCE Encoding Worker
|
||||
The worker is a c4d blue-green primary pair (`encoding-worker-a`/`-b`, us-central1-c)
|
||||
plus 8 stopped fallback VMs across 6 machine families for stockout resilience
|
||||
(`encoding-worker-fallback-{a,b,n2c,n2f,c4a,n4db,c2df,n2da}`). The currently-serving
|
||||
The worker is a **Spot** c4d-highcpu-16 blue-green primary pair (`encoding-worker-a`/`-b`,
|
||||
us-central1-c) plus ONE stopped on-demand fallback (`encoding-worker-fallback-c2df`,
|
||||
c2d-highcpu-16, us-central1-f) — 3 VMs since 2026-09-26. Idle VMs stop after 5 min.
|
||||
CI blue-green redeploys the worker only when worker code changed
|
||||
(`infrastructure/encoding-worker/worker_code_paths.txt`); force it via Actions → CI →
|
||||
Run workflow → "Force a blue-green redeploy of the GCE encoding worker". The currently-serving
|
||||
VM is `active_override_vm` in `config/encoding-worker` if set, else `primary_vm`.
|
||||
Use that VM name + its zone below (there is no VM literally named `encoding-worker`):
|
||||
```bash
|
||||
|
||||
@@ -450,7 +450,7 @@ async def system_status(
|
||||
# alternate family) the override points at the live VM;
|
||||
# otherwise it's the blue-green primary. The primary pair is
|
||||
# always c4d — fallbacks carry their family in the VM name
|
||||
# (…-fallback-n2c, …-fallback-c4a), which infer_machine_type
|
||||
# (…-fallback-c2df), which infer_machine_type
|
||||
# decodes when no explicit machine_type is stored on the config.
|
||||
on_fallback = bool(config.active_override_vm)
|
||||
active_vm = config.active_override_vm or config.primary_vm
|
||||
|
||||
@@ -797,7 +797,7 @@ async def retry_pending_render_jobs(
|
||||
"""
|
||||
Auto-retry jobs parked in RENDER_PENDING_CAPACITY.
|
||||
|
||||
Called every 5 minutes by Cloud Scheduler. When the GCE encoding worker
|
||||
Called every 10 minutes by Cloud Scheduler. When the GCE encoding worker
|
||||
can't be started because the zone is exhausted, the render worker parks
|
||||
the job in this state instead of failing it. This endpoint re-attempts
|
||||
the render — when GCE has capacity, the start succeeds and the job
|
||||
@@ -954,7 +954,7 @@ async def recover_stuck_jobs(
|
||||
"""
|
||||
Detect and recover jobs stuck in a processing status.
|
||||
|
||||
Called by Cloud Scheduler (every 5 minutes) or manually from admin.
|
||||
Called by Cloud Scheduler (every 10 minutes) or manually from admin.
|
||||
- DOWNLOADING_AUDIO stuck >10 min:
|
||||
* torrent sources (RED/OPS) → park into DOWNLOAD_PENDING_RETRY and keep
|
||||
auto-retrying for up to 24h (handles rare tracks with intermittent
|
||||
|
||||
@@ -326,6 +326,19 @@ class Settings(BaseSettings):
|
||||
default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")
|
||||
default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")
|
||||
|
||||
# Output files NOT uploaded to Nomad's own Dropbox folders (DEFAULT_DROPBOX_PATH /
|
||||
# DEFAULT_PRIVATE_DROPBOX_PATH), as "|"-separated filename suffixes. They stay in
|
||||
# GCS (job-page downloads, YouTube upload, AWS backup) — this only saves the
|
||||
# multi-GB internet egress + upload time. Tenant Dropbox folders are exempt
|
||||
# (B2B tenants expect the full set). Default skips only the lossless 4K MP4,
|
||||
# which no customer-facing text promises in Dropbox. The lossless MKV IS promised
|
||||
# there (completion email + the Fiverr bot), so add
|
||||
# " (Final Karaoke Lossless 4k).mkv" only after updating those.
|
||||
# See docs/archive/2026-09-26-encoding-cost-cuts.md.
|
||||
dropbox_skip_output_suffixes: str = os.getenv(
|
||||
"DROPBOX_SKIP_OUTPUT_SUFFIXES", " (Final Karaoke Lossless 4k).mp4"
|
||||
)
|
||||
|
||||
# YouTube Data API v3 Quota Configuration
|
||||
# Daily quota limit (YouTube grants 10,000 units/day by default)
|
||||
youtube_quota_daily_limit: int = int(os.getenv("YOUTUBE_QUOTA_DAILY_LIMIT", "10000"))
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
Approximate vocals for jobs where the user supplied their own instrumental.
|
||||
|
||||
Those jobs skip GPU separation, so there is no vocals stem and the lyrics review
|
||||
"Waveforms" mode had nothing to draw. The waveform only needs a peak envelope,
|
||||
so a cheap CPU estimate is enough: vocals ≈ mix − gain × instrumental, after
|
||||
aligning the instrumental to the mix by cross-correlation.
|
||||
|
||||
The result is registered as ``stems.vocals_derived`` — used ONLY for the review
|
||||
waveform (see backend/utils/stems.py). It is never shipped as a deliverable stem
|
||||
or used for the original-vocals guide, since it can contain residue when the
|
||||
instrumental isn't from the same master as the mix.
|
||||
|
||||
Runs inside the lyrics worker (4Gi, shared with transcription), so memory is
|
||||
bounded: alignment correlates a fixed-length excerpt, not the whole track, and
|
||||
very long inputs are skipped.
|
||||
"""
|
||||
import logging
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Waveform-only use: mono at 22.05 kHz keeps a 5-minute song ~26 MB as float32.
|
||||
SAMPLE_RATE = 22050
|
||||
# Encoder delay / leading silence differences are small; search ±2s.
|
||||
MAX_LAG_SECONDS = 2.0
|
||||
# Alignment excerpt length — plenty to lock onto, and keeps the FFT tiny.
|
||||
ALIGN_WINDOW_SECONDS = 60.0
|
||||
# Bound memory on the shared worker: skip absurdly long inputs (mashups, DJ sets).
|
||||
MAX_DURATION_SECONDS = 20 * 60
|
||||
# Minimum usable decode.
|
||||
MIN_DURATION_SECONDS = 1.0
|
||||
# residual energy / mix energy above this = the instrumental didn't cancel
|
||||
# (different master, big offset, edited mix). Showing that as "vocals" would
|
||||
# just be the full-mix envelope and mislead timing edits, so don't register it.
|
||||
MAX_USEFUL_RESIDUAL_RATIO = 0.85
|
||||
FFMPEG_TIMEOUT_SECONDS = 120
|
||||
|
||||
|
||||
class DerivedVocalsError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class DerivationResult:
|
||||
offset_samples: int
|
||||
gain: float
|
||||
# residual energy / mix energy. With a same-master instrumental this is
|
||||
# roughly the vocals' share of the mix; near 1.0 means the subtraction
|
||||
# removed little (the waveform is then ≈ the mix).
|
||||
residual_ratio: float
|
||||
|
||||
@property
|
||||
def useful(self) -> bool:
|
||||
return self.residual_ratio <= MAX_USEFUL_RESIDUAL_RATIO
|
||||
|
||||
|
||||
def _run_ffmpeg(args: list, input_bytes: Optional[bytes] = None) -> bytes:
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["ffmpeg", "-nostdin", "-v", "error", *args],
|
||||
input=input_bytes, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
timeout=FFMPEG_TIMEOUT_SECONDS, check=True,
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
stderr = (e.stderr or b"").decode(errors="replace").strip()[-500:]
|
||||
raise DerivedVocalsError(f"ffmpeg failed (exit {e.returncode}): {stderr}") from e
|
||||
except subprocess.TimeoutExpired as e:
|
||||
raise DerivedVocalsError(f"ffmpeg timed out after {FFMPEG_TIMEOUT_SECONDS}s") from e
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def _decode_mono(path: str, sample_rate: int = SAMPLE_RATE) -> np.ndarray:
|
||||
"""Decode any audio file to mono float32 at sample_rate via ffmpeg."""
|
||||
raw = _run_ffmpeg(["-i", path, "-t", str(MAX_DURATION_SECONDS + 1), "-ac", "1",
|
||||
"-ar", str(sample_rate), "-f", "f32le", "-"])
|
||||
samples = np.frombuffer(raw, dtype=np.float32).copy()
|
||||
seconds = len(samples) / sample_rate
|
||||
if seconds < MIN_DURATION_SECONDS:
|
||||
raise DerivedVocalsError(f"decoded only {seconds:.2f}s of audio from {path}")
|
||||
if seconds > MAX_DURATION_SECONDS:
|
||||
raise DerivedVocalsError(f"audio longer than {MAX_DURATION_SECONDS // 60} min; skipping")
|
||||
return samples
|
||||
|
||||
|
||||
def _encode_flac(samples: np.ndarray, out_path: str, sample_rate: int = SAMPLE_RATE) -> None:
|
||||
peak = float(np.max(np.abs(samples))) if samples.size else 0.0
|
||||
if peak > 1.0:
|
||||
samples = samples / peak
|
||||
_run_ffmpeg(["-y", "-f", "f32le", "-ar", str(sample_rate), "-ac", "1", "-i", "-",
|
||||
"-c:a", "flac", out_path], input_bytes=samples.astype(np.float32).tobytes())
|
||||
|
||||
|
||||
def find_offset(mix: np.ndarray, inst: np.ndarray, max_lag: int,
|
||||
window: int = int(ALIGN_WINDOW_SECONDS * SAMPLE_RATE)) -> int:
|
||||
"""Lag (samples) that best aligns inst to mix: mix[n] ≈ inst[n - lag].
|
||||
|
||||
Correlates a `window`-sample excerpt of the mix (from a quarter of the way
|
||||
in, past intros) against the matching instrumental span ±max_lag, so memory
|
||||
and time are independent of track length.
|
||||
"""
|
||||
window = max(1, min(window, len(mix)))
|
||||
start = min(len(mix) // 4, len(mix) - window)
|
||||
excerpt = mix[start: start + window].astype(np.float64)
|
||||
|
||||
# Instrumental span covering every candidate lag, zero-padded where it runs
|
||||
# off either end: seg[j] = inst[start - max_lag + j].
|
||||
seg = np.zeros(window + 2 * max_lag, dtype=np.float64)
|
||||
lo = start - max_lag
|
||||
src_lo, src_hi = max(0, lo), min(len(inst), lo + len(seg))
|
||||
if src_hi > src_lo:
|
||||
seg[src_lo - lo: src_hi - lo] = inst[src_lo:src_hi]
|
||||
|
||||
# c[k] = Σ_j excerpt[j] · seg[j + k] for k in [0, 2·max_lag] ⇒ lag = max_lag − k
|
||||
size = 1 << (len(seg) + window - 1).bit_length()
|
||||
corr = np.fft.irfft(np.conj(np.fft.rfft(excerpt, size)) * np.fft.rfft(seg, size), size)
|
||||
k = int(np.argmax(corr[: 2 * max_lag + 1]))
|
||||
return max_lag - k
|
||||
|
||||
|
||||
def subtract_instrumental(mix: np.ndarray, inst: np.ndarray, sample_rate: int = SAMPLE_RATE):
|
||||
"""Return (residual, DerivationResult) with inst aligned + gain-matched to mix."""
|
||||
lag = find_offset(mix, inst, int(MAX_LAG_SECONDS * sample_rate), int(ALIGN_WINDOW_SECONDS * sample_rate))
|
||||
aligned = np.zeros_like(mix)
|
||||
if lag >= 0:
|
||||
src = inst[: max(0, len(mix) - lag)]
|
||||
aligned[lag: lag + len(src)] = src
|
||||
else:
|
||||
src = inst[-lag: -lag + len(mix)]
|
||||
aligned[: len(src)] = src
|
||||
denom = float(np.dot(aligned, aligned))
|
||||
gain = float(np.dot(mix, aligned) / denom) if denom > 0 else 0.0
|
||||
residual = mix - gain * aligned
|
||||
mix_energy = float(np.dot(mix, mix))
|
||||
ratio = float(np.dot(residual, residual) / mix_energy) if mix_energy > 0 else 1.0
|
||||
return residual, DerivationResult(offset_samples=lag, gain=gain, residual_ratio=ratio)
|
||||
|
||||
|
||||
def derive_vocals_file(mix_path: str, instrumental_path: str, out_path: str) -> DerivationResult:
|
||||
"""Compute approximate vocals; write a FLAC (mono, 22.05 kHz) only if useful.
|
||||
|
||||
Raises DerivedVocalsError on decode/encode problems. Check ``result.useful``
|
||||
before registering the output — nothing is written when it's False.
|
||||
"""
|
||||
mix = _decode_mono(mix_path)
|
||||
inst = _decode_mono(instrumental_path)
|
||||
residual, result = subtract_instrumental(mix, inst)
|
||||
logger.info(
|
||||
"Derived vocals: offset=%d samples (%.1f ms) gain=%.3f residual_ratio=%.3f useful=%s",
|
||||
result.offset_samples, 1000 * result.offset_samples / SAMPLE_RATE, result.gain,
|
||||
result.residual_ratio, result.useful,
|
||||
)
|
||||
if result.useful:
|
||||
_encode_flac(residual, out_path)
|
||||
return result
|
||||
@@ -12,7 +12,7 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from typing import Optional
|
||||
from typing import Optional, Sequence, Tuple
|
||||
|
||||
from google.cloud import secretmanager
|
||||
|
||||
@@ -249,13 +249,20 @@ class DropboxService:
|
||||
)
|
||||
cursor.offset = file_obj.tell()
|
||||
|
||||
def upload_folder(self, local_dir: str, remote_path: str) -> None:
|
||||
def upload_folder(
|
||||
self,
|
||||
local_dir: str,
|
||||
remote_path: str,
|
||||
exclude_suffixes: Sequence[str] = (),
|
||||
) -> None:
|
||||
"""
|
||||
Recursively upload all files and subdirectories to Dropbox folder.
|
||||
|
||||
Args:
|
||||
local_dir: Local directory to upload
|
||||
remote_path: Dropbox destination folder path
|
||||
exclude_suffixes: Filename suffixes to skip (see
|
||||
dropbox_skip_suffixes_for). Skipped files stay on local disk / GCS.
|
||||
"""
|
||||
# Ensure remote path starts with /
|
||||
if not remote_path.startswith("/"):
|
||||
@@ -264,6 +271,7 @@ class DropboxService:
|
||||
logger.info(f"Uploading folder {local_dir} to {remote_path}")
|
||||
|
||||
uploaded_count = 0
|
||||
skipped_count = 0
|
||||
for root, _dirs, files in os.walk(local_dir):
|
||||
# Calculate the relative path from local_dir to current root
|
||||
rel_root = os.path.relpath(root, local_dir)
|
||||
@@ -273,12 +281,19 @@ class DropboxService:
|
||||
current_remote = f"{remote_path}/{rel_root}"
|
||||
|
||||
for filename in files:
|
||||
if exclude_suffixes and filename.endswith(tuple(exclude_suffixes)):
|
||||
logger.info(f"Skipping {filename} (excluded from Dropbox upload)")
|
||||
skipped_count += 1
|
||||
continue
|
||||
local_file = os.path.join(root, filename)
|
||||
remote_file = f"{current_remote}/{filename}"
|
||||
self.upload_file(local_file, remote_file)
|
||||
uploaded_count += 1
|
||||
|
||||
logger.info(f"Uploaded {uploaded_count} files to {remote_path}")
|
||||
logger.info(
|
||||
f"Uploaded {uploaded_count} files to {remote_path}"
|
||||
+ (f" (skipped {skipped_count} excluded)" if skipped_count else "")
|
||||
)
|
||||
|
||||
def create_shared_link(self, path: str) -> str:
|
||||
"""
|
||||
@@ -351,3 +366,27 @@ class DropboxService:
|
||||
def get_dropbox_service() -> DropboxService:
|
||||
"""Factory function to get a DropboxService instance."""
|
||||
return DropboxService()
|
||||
|
||||
|
||||
def dropbox_skip_suffixes_for(dropbox_path: Optional[str]) -> Tuple[str, ...]:
|
||||
"""Filename suffixes to leave out of a Dropbox upload to ``dropbox_path``.
|
||||
|
||||
Only Nomad's own folders (DEFAULT_DROPBOX_PATH / DEFAULT_PRIVATE_DROPBOX_PATH)
|
||||
skip anything — tenant folders get the full output set. The suffix list comes
|
||||
from settings.dropbox_skip_output_suffixes ("|"-separated). Skipped files are
|
||||
still in GCS, so job-page downloads and YouTube uploads are unaffected.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not dropbox_path:
|
||||
return ()
|
||||
own_paths = {
|
||||
p.rstrip("/")
|
||||
for p in (settings.default_dropbox_path, settings.default_private_dropbox_path)
|
||||
if p
|
||||
}
|
||||
if dropbox_path.rstrip("/") not in own_paths:
|
||||
return ()
|
||||
raw = settings.dropbox_skip_output_suffixes or ""
|
||||
return tuple(s for s in raw.split("|") if s.strip())
|
||||
@@ -116,6 +116,26 @@ def _parse_resubmit_max() -> int:
|
||||
return 2
|
||||
|
||||
|
||||
# GCE statuses meaning the worker VM is not running (idle-stop, deploy stop, or —
|
||||
# since the a/b pair moved to Spot on 2026-09-26 — a Spot preemption, which STOPs
|
||||
# the VM). A job submitted to a VM in one of these states can never complete:
|
||||
# its in-memory job registry and ffmpeg process are gone.
|
||||
# PROVISIONING/STAGING/REPAIRING are included too: the job was accepted by a
|
||||
# RUNNING VM, so seeing the VM in a (re)start state means it went down and came
|
||||
# back (e.g. another request restarted a preempted worker) — the job is gone.
|
||||
_STOPPED_VM_STATUSES = frozenset({
|
||||
"STOPPING", "STOPPED", "TERMINATED", "SUSPENDING", "SUSPENDED",
|
||||
"PROVISIONING", "STAGING", "REPAIRING",
|
||||
})
|
||||
|
||||
# While polling a job, refresh config/encoding-worker.last_activity_at at most
|
||||
# this often. The idle-shutdown function keeps the routed VM alive only while
|
||||
# last_activity_at is < IDLE_TIMEOUT_MINUTES (5) old, and its /health
|
||||
# active_jobs counts only RUNNING jobs — so without this, a VM whose encode ran
|
||||
# longer than the idle window could be stopped in the seconds between the job
|
||||
# finishing and our next poll collecting the result.
|
||||
ACTIVITY_TOUCH_INTERVAL_SECONDS = 60.0
|
||||
|
||||
QUEUE_TIMEOUT_SECONDS = _parse_queue_timeout()
|
||||
ENCODING_RESUBMIT_MAX = _parse_resubmit_max()
|
||||
|
||||
@@ -272,6 +292,104 @@ class EncodingService:
|
||||
async with sem:
|
||||
yield
|
||||
|
||||
def _fallback_entries(self) -> list:
|
||||
"""Parse ENCODING_WORKER_FALLBACK_VMS into candidate dicts.
|
||||
|
||||
Schema: '[{"vm":"encoding-worker-fallback-c2df","zone":"us-central1-f",
|
||||
"ip":"34.x.x.x","machine_type":"c2d-highcpu-16"}, ...]'. machine_type is
|
||||
optional (inferred from the VM name for legacy entries). Malformed input
|
||||
degrades to fewer/no fallbacks — this runs during connection recovery and
|
||||
must never raise.
|
||||
"""
|
||||
import json as _json
|
||||
raw = self.settings.encoding_worker_fallback_vms
|
||||
if not raw:
|
||||
return []
|
||||
try:
|
||||
parsed = _json.loads(raw)
|
||||
except (ValueError, TypeError) as e:
|
||||
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
|
||||
return []
|
||||
# A non-list root (null, dict, scalar) parses fine but would blow up
|
||||
# `for item in parsed` and escape during connection recovery — degrade
|
||||
# to no fallbacks instead.
|
||||
if not isinstance(parsed, list):
|
||||
logger.warning("ENCODING_WORKER_FALLBACK_VMS must be a JSON list; ignoring")
|
||||
return []
|
||||
entries = []
|
||||
for item in parsed:
|
||||
try:
|
||||
entries.append({
|
||||
"vm": item["vm"],
|
||||
"zone": item["zone"],
|
||||
"ip": item["ip"],
|
||||
"machine_type": item.get("machine_type"),
|
||||
"kind": "fallback",
|
||||
})
|
||||
except (KeyError, TypeError) as e:
|
||||
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
|
||||
continue
|
||||
return entries
|
||||
|
||||
def _vm_for_worker_url(self, worker_url: Optional[str]) -> Optional[tuple]:
|
||||
"""Map a worker base URL (http://<ip>:8080) back to its (vm_name, zone).
|
||||
|
||||
Looks at the blue-green primary/secondary, the active override, and the
|
||||
configured fallbacks. Returns None when unknown (no manager, unparseable
|
||||
URL, or an IP no longer in the fleet). BLOCKING (Firestore read).
|
||||
"""
|
||||
if not self._worker_manager or not worker_url:
|
||||
return None
|
||||
from urllib.parse import urlparse
|
||||
|
||||
host = urlparse(worker_url).hostname
|
||||
if not host:
|
||||
return None
|
||||
config = self._worker_manager.get_config()
|
||||
default_zone = self._worker_manager._zone
|
||||
known = [
|
||||
(config.primary_ip, config.primary_vm, default_zone),
|
||||
(config.secondary_ip, config.secondary_vm, default_zone),
|
||||
(config.active_override_ip, config.active_override_vm,
|
||||
config.active_override_zone or default_zone),
|
||||
]
|
||||
known.extend((fb["ip"], fb["vm"], fb["zone"]) for fb in self._fallback_entries())
|
||||
for ip, vm, zone in known:
|
||||
if ip and vm and ip == host:
|
||||
return vm, zone
|
||||
return None
|
||||
|
||||
async def _touch_worker_activity(self, job_id: str) -> None:
|
||||
"""Best-effort refresh of last_activity_at (keeps the VM from idle-stop)."""
|
||||
try:
|
||||
await asyncio.to_thread(self._worker_manager.update_activity)
|
||||
except Exception as e: # noqa: BLE001 — keep-alive only, never fail the poll
|
||||
logger.debug(f"[job:{job_id}] Could not refresh worker activity: {_format_exception(e)}")
|
||||
|
||||
async def _stopped_worker_status(self, worker_url: Optional[str]) -> Optional[str]:
|
||||
"""If the VM behind ``worker_url`` is stopped/preempted, return its GCE status.
|
||||
|
||||
Returns None when the VM is running, unknown, or the lookup fails — the
|
||||
caller then falls back to the ordinary poll-failure tolerance. Blocking
|
||||
Firestore/Compute calls run off the event loop.
|
||||
"""
|
||||
if not self._worker_manager:
|
||||
return None
|
||||
try:
|
||||
# Unpinned (legacy) polls target the current active URL.
|
||||
url = worker_url or await asyncio.to_thread(self._get_worker_url)
|
||||
found = await asyncio.to_thread(self._vm_for_worker_url, url)
|
||||
if not found:
|
||||
return None
|
||||
vm_name, zone = found
|
||||
status = await asyncio.to_thread(self._worker_manager.get_vm_status, vm_name, zone)
|
||||
except Exception as e: # noqa: BLE001 — best-effort diagnosis only
|
||||
logger.debug(f"Could not check worker VM status for {worker_url}: {_format_exception(e)}")
|
||||
return None
|
||||
if status in _STOPPED_VM_STATUSES:
|
||||
return f"{vm_name} is {status}"
|
||||
return None
|
||||
|
||||
def _build_worker_candidates(self) -> list:
|
||||
"""Build the ranked candidate list for ensure_any_running.
|
||||
|
||||
@@ -310,37 +428,9 @@ class EncodingService:
|
||||
"is_primary": True,
|
||||
}]
|
||||
|
||||
# Optional capacity-fallback VMs in alternate zones/families, configured via
|
||||
# env var. Schema: '[{"vm":"encoding-worker-fallback-c4a","zone":"us-central1-a",
|
||||
# "ip":"34.x.x.x","machine_type":"c4-highcpu-32"}, ...]'. machine_type is
|
||||
# optional (inferred from the VM name for legacy entries). Empty by default;
|
||||
# populated after `pulumi up` provisions the fallback VMs.
|
||||
import json as _json
|
||||
raw = self.settings.encoding_worker_fallback_vms
|
||||
if raw:
|
||||
try:
|
||||
parsed = _json.loads(raw)
|
||||
except (ValueError, TypeError) as e:
|
||||
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
|
||||
parsed = []
|
||||
# A non-list root (null, dict, scalar) parses fine but would blow up
|
||||
# `for item in parsed` and escape this method during connection
|
||||
# recovery — degrade to no fallbacks instead.
|
||||
if not isinstance(parsed, list):
|
||||
logger.warning("ENCODING_WORKER_FALLBACK_VMS must be a JSON list; ignoring")
|
||||
parsed = []
|
||||
for item in parsed:
|
||||
try:
|
||||
pool.append({
|
||||
"vm": item["vm"],
|
||||
"zone": item["zone"],
|
||||
"ip": item["ip"],
|
||||
"machine_type": item.get("machine_type"),
|
||||
"kind": "fallback",
|
||||
})
|
||||
except (KeyError, TypeError) as e:
|
||||
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
|
||||
continue
|
||||
# Optional capacity-fallback VMs in alternate zones/families (see
|
||||
# _fallback_entries). Empty when unconfigured.
|
||||
pool.extend(self._fallback_entries())
|
||||
|
||||
# Rank fastest-first, demoting types that recently stocked out. Keeps the
|
||||
# primary (c4d) at the top whenever it has capacity.
|
||||
@@ -778,6 +868,7 @@ class EncodingService:
|
||||
# counts from here; time spent "pending" in the worker's serialized
|
||||
# heavy queue counts against `queue_timeout` instead.
|
||||
run_started_at: Optional[float] = None
|
||||
last_activity_touch: Optional[float] = None
|
||||
|
||||
while True:
|
||||
now = asyncio.get_event_loop().time()
|
||||
@@ -809,6 +900,25 @@ class EncodingService:
|
||||
f"Encoding job {job_id} was lost by the worker (restarted mid-run)",
|
||||
job_id=job_id,
|
||||
) from e
|
||||
# The worker VM itself went away (Spot preemption, idle/deploy
|
||||
# stop). Nothing on that VM can finish this job, so waiting out the
|
||||
# remaining poll tolerance (several minutes of retries) only delays
|
||||
# recovery — and "lost contact" is NOT resubmitted. Surface it as a
|
||||
# lost job so run_with_lost_job_resubmit re-submits it; the
|
||||
# resubmit's connection failure then restarts a worker (the Spot
|
||||
# VM, or the on-demand fallback if Spot capacity is gone).
|
||||
stopped = await self._stopped_worker_status(worker_url)
|
||||
if stopped:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Encoding worker VM stopped mid-job ({stopped}) — "
|
||||
f"likely Spot preemption; treating job as lost for resubmission"
|
||||
)
|
||||
self._invalidate_cached_url()
|
||||
raise EncodingJobLostError(
|
||||
f"Encoding job {job_id} was lost: worker VM {stopped} "
|
||||
f"(Spot preemption or stop)",
|
||||
job_id=job_id,
|
||||
) from e
|
||||
consecutive_failures += 1
|
||||
if consecutive_failures >= MAX_CONSECUTIVE_POLL_FAILURES:
|
||||
logger.error(
|
||||
@@ -834,6 +944,12 @@ class EncodingService:
|
||||
status = {}
|
||||
|
||||
job_seen = True
|
||||
if self._worker_manager and (
|
||||
last_activity_touch is None
|
||||
or now - last_activity_touch >= ACTIVITY_TOUCH_INTERVAL_SECONDS
|
||||
):
|
||||
last_activity_touch = now
|
||||
await self._touch_worker_activity(job_id)
|
||||
job_status = status.get("status", "unknown")
|
||||
progress = status.get("progress", 0)
|
||||
if run_started_at is None and (job_status == "running" or progress):
|
||||
|
||||
@@ -34,6 +34,7 @@ from typing import Any, Optional
|
||||
|
||||
import aiohttp
|
||||
|
||||
from google.api_core import exceptions as gcp_exceptions
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.services.encoding_errors import (
|
||||
@@ -126,7 +127,7 @@ class EncodingWorkerConfig:
|
||||
|
||||
Returns the capacity-fallback override if set, otherwise the primary
|
||||
URL. The override mechanism lets us route around a zone that's
|
||||
temporarily out of c4d-highcpu-32 capacity without rewriting the
|
||||
temporarily out of c4d (Spot) capacity without rewriting the
|
||||
blue-green primary/secondary tracking.
|
||||
"""
|
||||
if self.active_override_ip:
|
||||
@@ -141,7 +142,7 @@ class EncodingWorkerCandidate:
|
||||
Carries everything needed to talk to the worker: VM name + zone (so the
|
||||
GCE compute client targets the right zone) and external IP (so successful
|
||||
starts can be persisted as the active URL override). ``machine_type`` (e.g.
|
||||
"c4d-highcpu-32") lets the manager record/clear per-(type,zone) capacity
|
||||
"c4d-highcpu-16") lets the manager record/clear per-(type,zone) capacity
|
||||
state so the shared preference logic can demote a stocked-out type.
|
||||
"""
|
||||
|
||||
@@ -444,7 +445,20 @@ class EncodingWorkerManager:
|
||||
has_explicit_primary = any(getattr(c, "is_primary", False) for c in candidates)
|
||||
for index, candidate in enumerate(candidates):
|
||||
try:
|
||||
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
|
||||
try:
|
||||
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
|
||||
except gcp_exceptions.NotFound as nf:
|
||||
# A candidate that no longer exists (e.g. a fallback VM removed
|
||||
# from the fleet while an instance still holds the old
|
||||
# ENCODING_WORKER_FALLBACK_VMS list) must be SKIPPED, not
|
||||
# abort the whole failover — otherwise one stale entry blocks
|
||||
# every later (real) candidate.
|
||||
raise EncodingWorkerStartError(
|
||||
f"VM {candidate.vm_name} not found in {candidate.zone}: {nf}",
|
||||
vm_name=candidate.vm_name,
|
||||
zone=candidate.zone,
|
||||
code="NOT_FOUND",
|
||||
) from nf
|
||||
started = False
|
||||
if status not in ("RUNNING", "STAGING"):
|
||||
logger.info(
|
||||
|
||||
@@ -33,21 +33,24 @@ from __future__ import annotations
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
# Lower rank = faster = preferred. Seeded from CPU architecture; refine with the
|
||||
# measured medians from infrastructure/encoding-worker/benchmark_types.py.
|
||||
# c4d AMD EPYC Turin (Zen5) — current primary, fastest
|
||||
# Lower rank = faster = preferred. Keyed by machine FAMILY (the prefix before the
|
||||
# first "-"), so the ranking is independent of the vCPU size — the fleet moved
|
||||
# from *-highcpu-32 to *-highcpu-16 on 2026-09-26 and could move again. Seeded
|
||||
# from CPU architecture; refine with the measured medians from
|
||||
# infrastructure/encoding-worker/benchmark_types.py.
|
||||
# c4d AMD EPYC Turin (Zen5) — Spot blue-green primary pair, fastest
|
||||
# c4 Intel Emerald Rapids — newest Intel perf tier
|
||||
# n4d AMD (Titanium) — flexible/deep AMD
|
||||
# c2d AMD Milan (Zen3) — mature, deep pool
|
||||
# n2d AMD Rome/Milan — deep pool (32 GB floor)
|
||||
# n2 Intel Cascade/Ice Lake — current fallback (32 GB floor)
|
||||
# c2d AMD Milan (Zen3) — mature, deep pool (current on-demand fallback)
|
||||
# n2d AMD Rome/Milan — deep pool
|
||||
# n2 Intel Cascade/Ice Lake — deep pool
|
||||
SPEED_RANK: Dict[str, int] = {
|
||||
"c4d-highcpu-32": 10,
|
||||
"c4-highcpu-32": 20,
|
||||
"n4d-highcpu-32": 30,
|
||||
"c2d-highcpu-32": 50,
|
||||
"n2d-highcpu-32": 60,
|
||||
"n2-highcpu-32": 70,
|
||||
"c4d": 10,
|
||||
"c4": 20,
|
||||
"n4d": 30,
|
||||
"c2d": 50,
|
||||
"n2d": 60,
|
||||
"n2": 70,
|
||||
}
|
||||
|
||||
# Rank for a candidate whose machine type is unknown and cannot be inferred:
|
||||
@@ -58,20 +61,26 @@ UNKNOWN_RANK = 1000
|
||||
COOLDOWN_SECONDS = 900 # 15 minutes
|
||||
|
||||
# Machine type of the blue-green primary/secondary pair (encoding-worker-a/-b).
|
||||
# They are always c4d; used when a candidate carries no explicit machine_type.
|
||||
PRIMARY_MACHINE_TYPE = "c4d-highcpu-32"
|
||||
# They are always c4d (Spot); used when a candidate carries no explicit
|
||||
# machine_type. Keep in sync with infrastructure/config.py MachineTypes.ENCODING_WORKER.
|
||||
PRIMARY_MACHINE_TYPE = "c4d-highcpu-16"
|
||||
|
||||
# vm-name substring → machine type, for backward-compat inference when a fallback
|
||||
# entry predates the machine_type field. Checked in order — longer / more-specific
|
||||
# family tokens FIRST so "n2d" is not shadowed by "n2", nor "c4d" by "c4".
|
||||
_NAME_TOKEN_TO_TYPE = (
|
||||
("c4d", "c4d-highcpu-32"),
|
||||
("n4d", "n4d-highcpu-32"),
|
||||
("n2d", "n2d-highcpu-32"),
|
||||
("c2d", "c2d-highcpu-32"),
|
||||
("c4", "c4-highcpu-32"),
|
||||
("n2", "n2-highcpu-32"),
|
||||
)
|
||||
# Current vCPU size of the fleet — used only to turn a family inferred from a VM
|
||||
# name into a full machine type (for display + cooldown keys).
|
||||
_FLEET_SIZE_SUFFIX = "-highcpu-16"
|
||||
|
||||
# vm-name substring → machine family, for backward-compat inference when a
|
||||
# fallback entry predates the machine_type field. Checked in order — longer /
|
||||
# more-specific family tokens FIRST so "n2d" is not shadowed by "n2", nor "c4d"
|
||||
# by "c4".
|
||||
_NAME_TOKEN_TO_FAMILY = ("c4d", "n4d", "n2d", "c2d", "c4", "n2")
|
||||
|
||||
|
||||
def machine_family(machine_type: Optional[str]) -> Optional[str]:
|
||||
"""``"c4d-highcpu-16"`` → ``"c4d"``; None/empty → None."""
|
||||
if not machine_type:
|
||||
return None
|
||||
return machine_type.split("-", 1)[0].lower()
|
||||
|
||||
|
||||
def _candidate_name(candidate: Dict[str, Any]) -> str:
|
||||
@@ -83,21 +92,22 @@ def infer_machine_type(candidate: Dict[str, Any]) -> Optional[str]:
|
||||
"""Best-effort machine type: explicit ``machine_type`` field, else vm-name token.
|
||||
|
||||
Fallback secret entries created before the ``machine_type`` field carry only
|
||||
vm/zone/ip; the VM-name family token (…-fallback-n2c, …-fallback-c4a) is the
|
||||
only hint. Returns None when nothing matches (caller treats as UNKNOWN_RANK).
|
||||
vm/zone/ip; the VM-name family token (…-fallback-c2df) is the only hint and
|
||||
is expanded to the current fleet size. Returns None when nothing matches
|
||||
(caller treats as UNKNOWN_RANK).
|
||||
"""
|
||||
explicit = candidate.get("machine_type")
|
||||
if explicit:
|
||||
return explicit
|
||||
name = _candidate_name(candidate).lower()
|
||||
for token, mtype in _NAME_TOKEN_TO_TYPE:
|
||||
if token in name:
|
||||
return mtype
|
||||
for family in _NAME_TOKEN_TO_FAMILY:
|
||||
if family in name:
|
||||
return f"{family}{_FLEET_SIZE_SUFFIX}"
|
||||
return None
|
||||
|
||||
|
||||
def _speed_rank(candidate: Dict[str, Any]) -> int:
|
||||
return SPEED_RANK.get(infer_machine_type(candidate), UNKNOWN_RANK)
|
||||
return SPEED_RANK.get(machine_family(infer_machine_type(candidate)), UNKNOWN_RANK)
|
||||
|
||||
|
||||
def cooldown_key(candidate: Dict[str, Any]) -> Optional[str]:
|
||||
|
||||
@@ -17,11 +17,18 @@ GCP_REGION: str = os.environ.get("GCP_REGION", "us-central1")
|
||||
# Log querying settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: How far back to look for errors on each run (minutes).
|
||||
LOOKBACK_MINUTES: int = 15
|
||||
#: How far back to look for errors on each run (minutes). Must equal the
|
||||
#: scheduler interval (ErrorMonitorConfig.MONITOR_SCHEDULE, hourly since
|
||||
#: 2026-09-26) so consecutive windows tile without gaps or double counting.
|
||||
LOOKBACK_MINUTES: int = 60
|
||||
|
||||
#: Maximum number of log entries to fetch per service per run.
|
||||
MAX_LOG_ENTRIES: int = 500
|
||||
#: Window (minutes) assumed for ``rolling_counts`` entries written before
|
||||
#: entries recorded their own ``window_minutes`` (i.e. the 15-min era).
|
||||
LEGACY_ROLLING_WINDOW_MINUTES: int = 15
|
||||
|
||||
#: Maximum number of log entries to fetch per resource type per run (scaled
|
||||
#: 4x with the 15 -> 60 min window to keep the same per-minute capacity).
|
||||
MAX_LOG_ENTRIES: int = 2000
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Monitored services
|
||||
@@ -46,6 +53,8 @@ MONITORED_CLOUD_RUN_JOBS: list[str] = [
|
||||
"lyrics-transcription-job",
|
||||
"audio-separation-job",
|
||||
"audio-download-job",
|
||||
# karaoke-decide weekly MusicBrainz dump -> BigQuery refresh
|
||||
"mb-refresh",
|
||||
]
|
||||
|
||||
# Gen2 Cloud Functions log as cloud_run_revision, not cloud_function.
|
||||
|
||||
@@ -19,6 +19,7 @@ from backend.services.error_monitor.config import (
|
||||
AUTO_RESOLVE_MIN_HOURS,
|
||||
AUTO_RESOLVE_MULTIPLIER,
|
||||
ROLLING_WINDOW_DAYS,
|
||||
LOOKBACK_MINUTES,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -174,7 +175,9 @@ class ErrorPatternsAdapter:
|
||||
snap = doc_ref.get()
|
||||
ts_iso = _iso(data.timestamp)
|
||||
|
||||
new_rolling_entry = {"ts": ts_iso, "count": data.count}
|
||||
# window_minutes lets spike detection normalise counts across a change
|
||||
# of monitor cadence (15 -> 60 min on 2026-09-26).
|
||||
new_rolling_entry = {"ts": ts_iso, "count": data.count, "window_minutes": LOOKBACK_MINUTES}
|
||||
|
||||
if not snap.exists:
|
||||
# ── brand new pattern ──────────────────────────────────────────
|
||||
|
||||
@@ -23,6 +23,7 @@ from google.cloud import secretmanager
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
GCP_PROJECT,
|
||||
LEGACY_ROLLING_WINDOW_MINUTES,
|
||||
LOOKBACK_MINUTES,
|
||||
MAX_LOG_ENTRIES,
|
||||
MONITORED_CLOUD_FUNCTIONS,
|
||||
@@ -214,15 +215,22 @@ def _group_by_pattern(entries: list[dict]) -> dict[str, dict]:
|
||||
def _rolling_average(rolling_counts: list[dict]) -> float:
|
||||
"""Compute the mean count from a list of rolling_count dicts.
|
||||
|
||||
Each entry's count is scaled to the current ``LOOKBACK_MINUTES`` window
|
||||
(entries without ``window_minutes`` predate it and were 15-minute counts),
|
||||
so a change of monitor cadence doesn't read as a spike.
|
||||
|
||||
Args:
|
||||
rolling_counts: List of ``{"count": int, ...}`` dicts.
|
||||
rolling_counts: List of ``{"count": int, "window_minutes"?: int, ...}`` dicts.
|
||||
|
||||
Returns:
|
||||
The arithmetic mean as a float, or ``0.0`` for an empty list.
|
||||
"""
|
||||
if not rolling_counts:
|
||||
return 0.0
|
||||
total = sum(entry.get("count", 0) for entry in rolling_counts)
|
||||
total = 0.0
|
||||
for entry in rolling_counts:
|
||||
window = entry.get("window_minutes") or LEGACY_ROLLING_WINDOW_MINUTES
|
||||
total += entry.get("count", 0) * LOOKBACK_MINUTES / window
|
||||
return total / len(rolling_counts)
|
||||
|
||||
|
||||
@@ -258,7 +266,7 @@ def _is_spike(current_count: int, rolling_counts: list[dict]) -> bool:
|
||||
class ErrorMonitor:
|
||||
"""Orchestrates the full production error monitoring pipeline.
|
||||
|
||||
On each run (typically every 15 minutes via Cloud Scheduler), it:
|
||||
On each run (hourly via Cloud Scheduler), it:
|
||||
|
||||
1. Queries Cloud Logging for recent errors across all monitored services.
|
||||
2. Groups errors into patterns using normalisation + hashing.
|
||||
|
||||
@@ -28,8 +28,10 @@ def _cloud_run_task_timeout_seconds() -> int:
|
||||
pathlib.Path(__file__).resolve().parents[2]
|
||||
/ "infrastructure" / "modules" / "cloud_run.py"
|
||||
).read_text()
|
||||
# The audio-download job block sets timeout="NNNNs" right before max_retries.
|
||||
m = re.search(r'timeout="(\d+)s",\s*\n\s*max_retries=2,\s*\n\s*vpc_access=', src)
|
||||
# Scope to the create_audio_download_job() body, then take its task timeout.
|
||||
start = src.index("def create_audio_download_job(")
|
||||
end = src.index("\ndef ", start + 1)
|
||||
m = re.search(r'timeout="(\d+)s",\s*\n\s*max_retries=2,', src[start:end])
|
||||
assert m, "could not locate audio-download-job timeout in cloud_run.py"
|
||||
return int(m.group(1))
|
||||
|
||||
|
||||
@@ -176,15 +176,15 @@ class TestSelectGreenRankingSharedWithRuntime:
|
||||
# 6-type pool with explicit machine_type (mirrors the post-rollout secret).
|
||||
POOL = [
|
||||
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.1",
|
||||
"machine_type": "c4-highcpu-32"},
|
||||
"machine_type": "c4-highcpu-16"},
|
||||
{"vm": "encoding-worker-fallback-n4db", "zone": "us-central1-b", "ip": "10.0.0.2",
|
||||
"machine_type": "n4d-highcpu-32"},
|
||||
"machine_type": "n4d-highcpu-16"},
|
||||
{"vm": "encoding-worker-fallback-c2df", "zone": "us-central1-f", "ip": "10.0.0.3",
|
||||
"machine_type": "c2d-highcpu-32"},
|
||||
"machine_type": "c2d-highcpu-16"},
|
||||
{"vm": "encoding-worker-fallback-n2da", "zone": "us-central1-a", "ip": "10.0.0.4",
|
||||
"machine_type": "n2d-highcpu-32"},
|
||||
"machine_type": "n2d-highcpu-16"},
|
||||
{"vm": "encoding-worker-fallback-n2c", "zone": "us-central1-c", "ip": "10.0.0.5",
|
||||
"machine_type": "n2-highcpu-32"},
|
||||
"machine_type": "n2-highcpu-16"},
|
||||
]
|
||||
|
||||
def test_secondary_c4d_leads_then_fastest_fallbacks(self):
|
||||
@@ -205,7 +205,7 @@ class TestSelectGreenRankingSharedWithRuntime:
|
||||
from datetime import datetime, timezone
|
||||
cfg = _config(
|
||||
active_override_vm=None,
|
||||
capacity_state={"c4d-highcpu-32@us-central1-c": datetime.now(timezone.utc).isoformat()},
|
||||
capacity_state={"c4d-highcpu-16@us-central1-c": datetime.now(timezone.utc).isoformat()},
|
||||
)
|
||||
cands = select_green_candidates(cfg, self.POOL)
|
||||
vms = [c["vm"] for c in cands]
|
||||
@@ -218,4 +218,4 @@ class TestSelectGreenRankingSharedWithRuntime:
|
||||
def test_machine_type_carried_through(self):
|
||||
cands = select_green_candidates(_config(active_override_vm=None), self.POOL)
|
||||
c4 = next(c for c in cands if c["vm"] == "encoding-worker-fallback-c4a")
|
||||
assert c4["machine_type"] == "c4-highcpu-32"
|
||||
assert c4["machine_type"] == "c4-highcpu-16"
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Approximate vocals (mix − aligned user instrumental) for the review waveform."""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from backend.services.derived_vocals import (
|
||||
SAMPLE_RATE,
|
||||
DerivedVocalsError,
|
||||
derive_vocals_file,
|
||||
find_offset,
|
||||
subtract_instrumental,
|
||||
)
|
||||
from backend.utils.stems import vocals_stem_path
|
||||
|
||||
requires_ffmpeg = pytest.mark.skipif(
|
||||
shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None, reason="ffmpeg not installed"
|
||||
)
|
||||
|
||||
|
||||
def _signals(lag, gain=0.8, seconds=6):
|
||||
rng = np.random.default_rng(1)
|
||||
n = SAMPLE_RATE * seconds
|
||||
inst = rng.normal(0, 0.2, n).astype(np.float32)
|
||||
t = np.arange(n) / SAMPLE_RATE
|
||||
# "vocals": 440 Hz bursts every other second
|
||||
vocals = (0.3 * np.sin(2 * np.pi * 440 * t) * ((t.astype(int) % 2) == 0)).astype(np.float32)
|
||||
shifted = np.zeros(n, dtype=np.float32)
|
||||
if lag >= 0:
|
||||
shifted[lag:] = inst[: n - lag]
|
||||
else:
|
||||
shifted[: n + lag] = inst[-lag:]
|
||||
return vocals + gain * shifted, inst, vocals
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lag", [0, 300, -1200, 20000, -44000])
|
||||
def test_find_offset_recovers_known_lag(lag):
|
||||
mix, inst, _ = _signals(lag)
|
||||
assert find_offset(mix, inst, int(2 * SAMPLE_RATE)) == lag
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lag", [-100, 100])
|
||||
def test_find_offset_on_very_short_input_is_not_ambiguous(lag):
|
||||
"""Regression: with inputs shorter than the lag window, positive/negative lag
|
||||
slices used to overlap and a negative lag came back as a large positive one."""
|
||||
mix, inst, _ = _signals(lag, seconds=1)
|
||||
assert find_offset(mix, inst, int(2 * SAMPLE_RATE)) == lag
|
||||
|
||||
|
||||
def test_find_offset_uses_bounded_window_on_long_tracks():
|
||||
"""Alignment correlates a fixed excerpt, so a long track costs the same
|
||||
memory/time as a short one (a whole-track FFT could OOM the lyrics worker)."""
|
||||
mix, inst, _ = _signals(lag=777, seconds=240)
|
||||
with patch("backend.services.derived_vocals.np.fft.rfft", wraps=np.fft.rfft) as rfft:
|
||||
assert find_offset(mix, inst, int(2 * SAMPLE_RATE), window=int(10 * SAMPLE_RATE)) == 777
|
||||
assert max(call.args[1] for call in rfft.call_args_list) <= 1 << 20
|
||||
|
||||
|
||||
def test_subtraction_recovers_vocals_and_gain():
|
||||
mix, inst, vocals = _signals(lag=300, gain=0.8)
|
||||
residual, result = subtract_instrumental(mix, inst)
|
||||
assert result.offset_samples == 300
|
||||
assert result.gain == pytest.approx(0.8, abs=0.02)
|
||||
assert result.residual_ratio == pytest.approx(float(np.dot(vocals, vocals) / np.dot(mix, mix)), abs=0.02)
|
||||
assert np.corrcoef(residual, vocals)[0, 1] > 0.98
|
||||
|
||||
|
||||
def test_unrelated_instrumental_leaves_the_mix_mostly_intact():
|
||||
mix, _, _ = _signals(lag=0)
|
||||
other = np.random.default_rng(7).normal(0, 0.2, len(mix)).astype(np.float32)
|
||||
residual, result = subtract_instrumental(mix, other)
|
||||
assert result.residual_ratio > 0.9
|
||||
assert np.corrcoef(residual, mix)[0, 1] > 0.95
|
||||
|
||||
|
||||
def _write_wav(path, samples, sr=44100):
|
||||
# Write at 44.1 kHz stereo like a real upload; the module resamples to mono 22.05 kHz.
|
||||
up = np.repeat(samples, 2).astype(np.float32)
|
||||
subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "f32le", "-ar", str(sr), "-ac", "1", "-i", "-",
|
||||
"-ac", "2", "-c:a", "pcm_s24le", path], input=up.tobytes(), check=True)
|
||||
|
||||
|
||||
@requires_ffmpeg
|
||||
def test_derive_vocals_file_end_to_end(tmp_path):
|
||||
mix, inst, vocals = _signals(lag=150)
|
||||
mix_path, inst_path, out_path = (str(tmp_path / n) for n in ("mix.wav", "inst.wav", "out.flac"))
|
||||
_write_wav(mix_path, mix)
|
||||
_write_wav(inst_path, inst)
|
||||
|
||||
result = derive_vocals_file(mix_path, inst_path, out_path)
|
||||
|
||||
assert result.useful
|
||||
assert os.path.getsize(out_path) > 0
|
||||
assert abs(result.offset_samples - 150) <= 1
|
||||
assert result.gain == pytest.approx(0.8, abs=0.02)
|
||||
# ≈ the vocals' share of the mix energy (~0.47 here) — i.e. the instrumental cancelled
|
||||
ideal = float(np.dot(vocals, vocals) / np.dot(mix, mix))
|
||||
assert result.residual_ratio == pytest.approx(ideal, abs=0.1)
|
||||
probe = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "stream=codec_name,channels,sample_rate",
|
||||
"-of", "csv=p=0", out_path], capture_output=True, text=True, check=True).stdout.strip()
|
||||
assert probe == f"flac,{SAMPLE_RATE},1"
|
||||
|
||||
|
||||
def test_vocals_stem_path_uses_derived_only_as_last_resort():
|
||||
derived = SimpleNamespace(file_urls={"stems": {"vocals_derived": "d.flac"}})
|
||||
both = SimpleNamespace(file_urls={"stems": {"vocals_derived": "d.flac", "vocals_clean": "v.flac"}})
|
||||
assert vocals_stem_path(derived) == "d.flac"
|
||||
assert vocals_stem_path(both) == "v.flac"
|
||||
|
||||
|
||||
class TestStoreDerivedVocals:
|
||||
def _call(self, tmp_path, derive):
|
||||
from backend.workers.lyrics_worker import _store_derived_vocals
|
||||
|
||||
storage, job_manager, job_log = MagicMock(), MagicMock(), MagicMock()
|
||||
with patch("backend.services.derived_vocals.derive_vocals_file", derive):
|
||||
_store_derived_vocals("j1", "uploads/j1/audio/existing_instrumental.wav", "/tmp/mix.wav",
|
||||
storage, job_manager, job_log)
|
||||
return storage, job_manager, job_log
|
||||
|
||||
def test_uploads_and_registers_waveform_stem(self, tmp_path):
|
||||
derive = MagicMock(return_value=SimpleNamespace(offset_samples=0, gain=1.0, residual_ratio=0.1, useful=True))
|
||||
storage, job_manager, _ = self._call(tmp_path, derive)
|
||||
|
||||
assert storage.download_file.call_args[0][0] == "uploads/j1/audio/existing_instrumental.wav"
|
||||
local_out, remote = storage.upload_file.call_args[0]
|
||||
assert local_out.endswith("vocals_derived.flac") and remote == "jobs/j1/stems/vocals_derived.flac"
|
||||
# own temp dir, cleaned up afterwards
|
||||
assert not os.path.exists(os.path.dirname(local_out))
|
||||
job_manager.update_file_url.assert_called_once_with("j1", "stems", "vocals_derived", "jobs/j1/stems/vocals_derived.flac")
|
||||
|
||||
def test_useless_subtraction_is_not_registered(self, tmp_path):
|
||||
derive = MagicMock(return_value=SimpleNamespace(offset_samples=0, gain=0.0, residual_ratio=0.99, useful=False))
|
||||
storage, job_manager, job_log = self._call(tmp_path, derive)
|
||||
|
||||
storage.upload_file.assert_not_called()
|
||||
job_manager.update_file_url.assert_not_called()
|
||||
assert "no vocal waveform" in job_log.info.call_args[0][0]
|
||||
|
||||
def test_failure_is_non_fatal(self, tmp_path):
|
||||
derive = MagicMock(side_effect=RuntimeError("ffmpeg exploded"))
|
||||
_, job_manager, job_log = self._call(tmp_path, derive)
|
||||
|
||||
job_manager.update_file_url.assert_not_called()
|
||||
assert "non-fatal" in job_log.warning.call_args[0][0]
|
||||
|
||||
|
||||
@requires_ffmpeg
|
||||
def test_unrelated_instrumental_is_not_written(tmp_path):
|
||||
"""A subtraction that removed nothing would just show the full-mix envelope."""
|
||||
mix, _, _ = _signals(lag=0)
|
||||
other = np.random.default_rng(9).normal(0, 0.2, len(mix)).astype(np.float32)
|
||||
mix_path, inst_path, out_path = (str(tmp_path / n) for n in ("mix.wav", "inst.wav", "out.flac"))
|
||||
_write_wav(mix_path, mix)
|
||||
_write_wav(inst_path, other)
|
||||
|
||||
result = derive_vocals_file(mix_path, inst_path, out_path)
|
||||
|
||||
assert not result.useful
|
||||
assert not os.path.exists(out_path)
|
||||
|
||||
|
||||
@requires_ffmpeg
|
||||
def test_empty_or_undecodable_input_raises_with_ffmpeg_detail(tmp_path):
|
||||
bad = tmp_path / "bad.wav"
|
||||
bad.write_bytes(b"not audio at all")
|
||||
with pytest.raises(DerivedVocalsError, match="ffmpeg failed"):
|
||||
derive_vocals_file(str(bad), str(bad), str(tmp_path / "o.flac"))
|
||||
|
||||
silent = str(tmp_path / "tiny.wav")
|
||||
_write_wav(silent, np.zeros(1000, dtype=np.float32)) # ~0.05s
|
||||
with pytest.raises(DerivedVocalsError, match="decoded only"):
|
||||
derive_vocals_file(silent, silent, str(tmp_path / "o.flac"))
|
||||
@@ -531,3 +531,69 @@ class TestFileExists:
|
||||
|
||||
service.file_exists("Karaoke/x.flac")
|
||||
mock_client.files_get_metadata.assert_called_once_with("/Karaoke/x.flac")
|
||||
|
||||
|
||||
class TestDropboxLosslessExclusion:
|
||||
"""2026-09-26 cost cut: Nomad's own Dropbox folders skip the lossless 4K MP4
|
||||
(it stays in GCS); tenant folders still get everything."""
|
||||
|
||||
@patch("backend.services.dropbox_service.secretmanager.SecretManagerServiceClient")
|
||||
def test_upload_folder_skips_excluded_suffixes(self, mock_sm_client_class, tmp_path):
|
||||
from backend.services.dropbox_service import DropboxService
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.payload.data = json.dumps({"access_token": "token"}).encode()
|
||||
mock_sm_client_class.return_value.access_secret_version.return_value = mock_response
|
||||
|
||||
(tmp_path / "A - B (Final Karaoke Lossless 4k).mp4").write_text("x")
|
||||
(tmp_path / "A - B (Final Karaoke Lossless 4k).mkv").write_text("x")
|
||||
(tmp_path / "A - B (Final Karaoke Lossy 4k).mp4").write_text("x")
|
||||
|
||||
service = DropboxService()
|
||||
with patch.object(service, "upload_file") as mock_upload:
|
||||
service.upload_folder(
|
||||
str(tmp_path), "/Uploads/folder",
|
||||
exclude_suffixes=(" (Final Karaoke Lossless 4k).mp4",),
|
||||
)
|
||||
|
||||
uploaded = sorted(c.args[1].rsplit("/", 1)[1] for c in mock_upload.call_args_list)
|
||||
assert uploaded == [
|
||||
"A - B (Final Karaoke Lossless 4k).mkv",
|
||||
"A - B (Final Karaoke Lossy 4k).mp4",
|
||||
]
|
||||
|
||||
def _settings(self, suffixes=" (Final Karaoke Lossless 4k).mp4"):
|
||||
s = Mock()
|
||||
s.default_dropbox_path = "/MediaUnsynced/Karaoke/Tracks-Organized"
|
||||
s.default_private_dropbox_path = "/MediaUnsynced/Karaoke/Tracks-NonPublished"
|
||||
s.dropbox_skip_output_suffixes = suffixes
|
||||
return s
|
||||
|
||||
def test_own_folders_skip_lossless_mp4_only_by_default(self):
|
||||
from backend.config import Settings
|
||||
from backend.services.dropbox_service import dropbox_skip_suffixes_for
|
||||
|
||||
default = Settings().dropbox_skip_output_suffixes
|
||||
with patch("backend.config.get_settings", return_value=self._settings(default)):
|
||||
for path in ("/MediaUnsynced/Karaoke/Tracks-Organized",
|
||||
"/MediaUnsynced/Karaoke/Tracks-NonPublished/"):
|
||||
skip = dropbox_skip_suffixes_for(path)
|
||||
assert skip == (" (Final Karaoke Lossless 4k).mp4",)
|
||||
# The MKV is promised in the Dropbox folder (completion email, Fiverr bot).
|
||||
assert not any(s.endswith(".mkv") for s in skip)
|
||||
|
||||
def test_tenant_folder_gets_everything(self):
|
||||
from backend.services.dropbox_service import dropbox_skip_suffixes_for
|
||||
|
||||
with patch("backend.config.get_settings", return_value=self._settings()):
|
||||
assert dropbox_skip_suffixes_for("/MediaUnsynced/Karaoke/Tracks-VocalStar") == ()
|
||||
assert dropbox_skip_suffixes_for(None) == ()
|
||||
|
||||
def test_multiple_suffixes_and_empty_config(self):
|
||||
from backend.services.dropbox_service import dropbox_skip_suffixes_for
|
||||
|
||||
both = " (Final Karaoke Lossless 4k).mp4| (Final Karaoke Lossless 4k).mkv"
|
||||
with patch("backend.config.get_settings", return_value=self._settings(both)):
|
||||
assert len(dropbox_skip_suffixes_for("/MediaUnsynced/Karaoke/Tracks-Organized")) == 2
|
||||
with patch("backend.config.get_settings", return_value=self._settings("")):
|
||||
assert dropbox_skip_suffixes_for("/MediaUnsynced/Karaoke/Tracks-Organized") == ()
|
||||
@@ -869,6 +869,194 @@ class TestWaitForCompletionLostJob:
|
||||
assert result["status"] == "complete"
|
||||
|
||||
|
||||
class TestWaitForCompletionWorkerStopped:
|
||||
"""The a/b workers run on Spot (2026-09-26). A preempted (STOPPED) worker VM
|
||||
must surface as a lost job immediately so run_with_lost_job_resubmit re-submits
|
||||
it, instead of burning the poll tolerance and failing with "lost contact"."""
|
||||
|
||||
def _with_manager(self, encoding_service, vm_status, fallbacks_json=None):
|
||||
cfg = MagicMock()
|
||||
cfg.primary_vm, cfg.primary_ip = "encoding-worker-a", "10.0.0.1"
|
||||
cfg.secondary_vm, cfg.secondary_ip = "encoding-worker-b", "10.0.0.2"
|
||||
cfg.active_override_vm = cfg.active_override_ip = cfg.active_override_zone = None
|
||||
mgr = MagicMock()
|
||||
mgr._zone = "us-central1-c"
|
||||
mgr.get_config.return_value = cfg
|
||||
mgr.get_vm_status.return_value = vm_status
|
||||
encoding_service._worker_manager = mgr
|
||||
encoding_service.settings.encoding_worker_fallback_vms = fallbacks_json
|
||||
return mgr
|
||||
|
||||
@staticmethod
|
||||
async def _conn_refused(job_id, worker_url=None):
|
||||
raise aiohttp.ClientConnectorError(
|
||||
connection_key=MagicMock(), os_error=OSError("Connection refused")
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preempted_worker_raises_lost_error_on_first_failure(self, encoding_service):
|
||||
mgr = self._with_manager(encoding_service, "TERMINATED")
|
||||
calls = 0
|
||||
|
||||
async def status(job_id, worker_url=None):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
return {"status": "running", "progress": 40}
|
||||
return await self._conn_refused(job_id, worker_url)
|
||||
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
with pytest.raises(EncodingJobLostError, match="encoding-worker-a is TERMINATED"):
|
||||
await encoding_service.wait_for_completion(
|
||||
"j1", worker_url="http://10.0.0.1:8080"
|
||||
)
|
||||
|
||||
assert calls == 2 # bailed on the first failed poll
|
||||
mgr.get_vm_status.assert_called_with("encoding-worker-a", "us-central1-c")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stopped_fallback_worker_resolved_via_fallback_list(self, encoding_service):
|
||||
import json
|
||||
mgr = self._with_manager(
|
||||
encoding_service, "STOPPING",
|
||||
fallbacks_json=json.dumps([{"vm": "encoding-worker-fallback-c2df",
|
||||
"zone": "us-central1-f", "ip": "10.0.0.9"}]),
|
||||
)
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=self._conn_refused), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
with pytest.raises(EncodingJobLostError):
|
||||
await encoding_service.wait_for_completion(
|
||||
"j1", worker_url="http://10.0.0.9:8080"
|
||||
)
|
||||
mgr.get_vm_status.assert_called_with("encoding-worker-fallback-c2df", "us-central1-f")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_running_worker_keeps_normal_poll_tolerance(self, encoding_service):
|
||||
"""A RUNNING VM that's just slow/unreachable is NOT a lost job."""
|
||||
self._with_manager(encoding_service, "RUNNING")
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=self._conn_refused), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
with pytest.raises(RuntimeError, match="consecutive poll failures"):
|
||||
await encoding_service.wait_for_completion(
|
||||
"j1", worker_url="http://10.0.0.1:8080"
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_worker_ip_keeps_normal_poll_tolerance(self, encoding_service):
|
||||
mgr = self._with_manager(encoding_service, "TERMINATED")
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=self._conn_refused), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
with pytest.raises(RuntimeError, match="consecutive poll failures"):
|
||||
await encoding_service.wait_for_completion(
|
||||
"j1", worker_url="http://10.9.9.9:8080"
|
||||
)
|
||||
mgr.get_vm_status.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_status_lookup_failure_is_non_fatal(self, encoding_service):
|
||||
mgr = self._with_manager(encoding_service, "TERMINATED")
|
||||
mgr.get_vm_status.side_effect = Exception("compute API down")
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=self._conn_refused), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
with pytest.raises(RuntimeError, match="consecutive poll failures"):
|
||||
await encoding_service.wait_for_completion(
|
||||
"j1", worker_url="http://10.0.0.1:8080"
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_restarted_worker_mid_boot_counts_as_lost(self, encoding_service):
|
||||
"""Another request restarted the preempted VM before our poll — STAGING
|
||||
means it went down, so the job (accepted while RUNNING) is gone."""
|
||||
self._with_manager(encoding_service, "STAGING")
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=self._conn_refused), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
with pytest.raises(EncodingJobLostError):
|
||||
await encoding_service.wait_for_completion(
|
||||
"j1", worker_url="http://10.0.0.1:8080"
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_polling_refreshes_worker_activity_at_most_once_a_minute(self, encoding_service):
|
||||
"""Keeps the routed VM inside the 5-min idle window for the whole encode,
|
||||
so it isn't stopped between the job finishing and us collecting it."""
|
||||
mgr = self._with_manager(encoding_service, "RUNNING")
|
||||
# First call is wait_for_completion's start_time, then one per poll.
|
||||
clock = iter([0, 0, 10, 20, 70, 80, 150])
|
||||
statuses = iter([
|
||||
{"status": "running", "progress": 10},
|
||||
{"status": "running", "progress": 20},
|
||||
{"status": "running", "progress": 30},
|
||||
{"status": "running", "progress": 40},
|
||||
{"status": "running", "progress": 50},
|
||||
{"status": "complete", "output_files": ["a.mp4"]},
|
||||
])
|
||||
|
||||
async def status(job_id, worker_url=None):
|
||||
return next(statuses)
|
||||
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.side_effect = lambda: next(clock)
|
||||
result = await encoding_service.wait_for_completion(
|
||||
"j1", worker_url="http://10.0.0.1:8080"
|
||||
)
|
||||
|
||||
assert result["status"] == "complete"
|
||||
# Touched at t=0, t=70, t=150 (>= 60s apart), not on every poll.
|
||||
assert mgr.update_activity.call_count == 3
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_activity_refresh_failure_does_not_fail_the_poll(self, encoding_service):
|
||||
mgr = self._with_manager(encoding_service, "RUNNING")
|
||||
mgr.update_activity.side_effect = Exception("firestore down")
|
||||
|
||||
async def status(job_id, worker_url=None):
|
||||
return {"status": "complete", "output_files": ["a.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
result = await encoding_service.wait_for_completion("j1")
|
||||
assert result["status"] == "complete"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preemption_is_resubmitted_by_run_with_lost_job_resubmit(self, encoding_service):
|
||||
"""End-to-end: a preempted first attempt is resubmitted under a fresh id."""
|
||||
self._with_manager(encoding_service, "TERMINATED")
|
||||
attempts = []
|
||||
|
||||
async def operation(job_id):
|
||||
attempts.append(job_id)
|
||||
if len(attempts) == 1:
|
||||
with patch.object(encoding_service, "get_job_status",
|
||||
side_effect=self._conn_refused), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock):
|
||||
return await encoding_service.wait_for_completion(
|
||||
job_id, worker_url="http://10.0.0.1:8080"
|
||||
)
|
||||
return {"status": "complete"}
|
||||
|
||||
result = await run_with_lost_job_resubmit(operation, "job123")
|
||||
assert result == {"status": "complete"}
|
||||
assert attempts[0] == "job123"
|
||||
assert attempts[1].startswith("job123_retry_")
|
||||
|
||||
|
||||
class TestPreviewQueueTimeout:
|
||||
"""A queued preview must not wait the long default queue_timeout — an
|
||||
interactive user is waiting, so total wait is capped at the short timeout."""
|
||||
@@ -1178,15 +1366,15 @@ class TestBuildWorkerCandidates:
|
||||
cands = svc._build_worker_candidates()
|
||||
assert cands[0].vm_name == "encoding-worker-a"
|
||||
assert cands[0].is_primary is True
|
||||
assert cands[0].machine_type == "c4d-highcpu-32"
|
||||
assert cands[0].machine_type == "c4d-highcpu-16"
|
||||
|
||||
def test_fallbacks_ranked_fastest_first(self, encoding_service):
|
||||
import json
|
||||
fallbacks = json.dumps([
|
||||
{"vm": "encoding-worker-fallback-n2f", "zone": "us-central1-f", "ip": "10.0.0.5",
|
||||
"machine_type": "n2-highcpu-32"},
|
||||
"machine_type": "n2-highcpu-16"},
|
||||
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.6",
|
||||
"machine_type": "c4-highcpu-32"},
|
||||
"machine_type": "c4-highcpu-16"},
|
||||
])
|
||||
svc = self._service_with_fallbacks(encoding_service, fallbacks)
|
||||
order = [c.vm_name for c in svc._build_worker_candidates()]
|
||||
@@ -1199,10 +1387,10 @@ class TestBuildWorkerCandidates:
|
||||
from datetime import datetime, timezone
|
||||
fallbacks = json.dumps([
|
||||
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.6",
|
||||
"machine_type": "c4-highcpu-32"},
|
||||
"machine_type": "c4-highcpu-16"},
|
||||
])
|
||||
# c4d@us-central1-c stocked out "now" → demoted below c4.
|
||||
cap = {"c4d-highcpu-32@us-central1-c": datetime.now(timezone.utc).isoformat()}
|
||||
cap = {"c4d-highcpu-16@us-central1-c": datetime.now(timezone.utc).isoformat()}
|
||||
svc = self._service_with_fallbacks(encoding_service, fallbacks, capacity_state=cap)
|
||||
cands = svc._build_worker_candidates()
|
||||
order = [c.vm_name for c in cands]
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Guard for the CI encoding-worker deploy gate.
|
||||
|
||||
CI only blue-green redeploys the GCE encoding worker when a path listed in
|
||||
infrastructure/encoding-worker/worker_code_paths.txt changed since the serving
|
||||
worker's version. If the worker starts importing a backend module that is NOT
|
||||
listed, changes to it would ship to the worker only on its next cold boot and
|
||||
without the pre-promote test encode. This test derives the worker's import
|
||||
closure (every ``backend.*`` module reachable from the worker entrypoint and the
|
||||
karaoke_gen package) and asserts each one is covered by the path list.
|
||||
"""
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
PATHS_FILE = REPO / "infrastructure" / "encoding-worker" / "worker_code_paths.txt"
|
||||
|
||||
|
||||
def _pathspecs():
|
||||
specs = []
|
||||
for line in PATHS_FILE.read_text().splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
specs.append(line)
|
||||
return specs
|
||||
|
||||
|
||||
def _covered(rel_path: str, specs) -> bool:
|
||||
return any(rel_path == s or (s.endswith("/") and rel_path.startswith(s)) for s in specs)
|
||||
|
||||
|
||||
def _backend_imports(py_file: Path):
|
||||
"""All ``backend.*`` module names imported anywhere in the file (incl. lazily)."""
|
||||
tree = ast.parse(py_file.read_text(), filename=str(py_file))
|
||||
mods = set()
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
|
||||
if node.module == "backend" or node.module.startswith("backend."):
|
||||
mods.add(node.module)
|
||||
for alias in node.names: # `from backend.services import x` → module x
|
||||
mods.add(f"{node.module}.{alias.name}")
|
||||
elif isinstance(node, ast.Import):
|
||||
for alias in node.names:
|
||||
if alias.name.startswith("backend."):
|
||||
mods.add(alias.name)
|
||||
return mods
|
||||
|
||||
|
||||
def _module_file(mod: str):
|
||||
base = REPO / Path(*mod.split("."))
|
||||
for candidate in (base.with_suffix(".py"), base / "__init__.py"):
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
return None # a name imported from a module, not a module itself
|
||||
|
||||
|
||||
def _worker_closure():
|
||||
roots = list((REPO / "karaoke_gen").rglob("*.py"))
|
||||
roots += list((REPO / "backend" / "services" / "gce_encoding").rglob("*.py"))
|
||||
seen_files = set()
|
||||
queue = list(roots)
|
||||
backend_files = set()
|
||||
while queue:
|
||||
f = queue.pop()
|
||||
if f in seen_files:
|
||||
continue
|
||||
seen_files.add(f)
|
||||
for mod in _backend_imports(f):
|
||||
mf = _module_file(mod)
|
||||
if not mf:
|
||||
continue
|
||||
# Importing backend.a.b also executes backend/__init__.py and
|
||||
# backend/a/__init__.py — they're part of the worker's code too.
|
||||
parts = mod.split(".")
|
||||
pkg_inits = [_module_file(".".join(parts[:i])) for i in range(1, len(parts))]
|
||||
for dep in [mf, *pkg_inits]:
|
||||
if dep and dep not in seen_files:
|
||||
backend_files.add(dep)
|
||||
queue.append(dep)
|
||||
return backend_files
|
||||
|
||||
|
||||
def test_worker_code_paths_file_is_well_formed():
|
||||
specs = _pathspecs()
|
||||
assert "karaoke_gen/" in specs
|
||||
assert "backend/services/gce_encoding/" in specs
|
||||
# pyproject.toml changes on EVERY PR (version bump) — listing it would make
|
||||
# the gate fire on every push, defeating it. Dependency changes are caught
|
||||
# via poetry.lock.
|
||||
assert "pyproject.toml" not in specs
|
||||
assert "poetry.lock" in specs
|
||||
for s in specs:
|
||||
assert (REPO / s.rstrip("/")).exists(), f"stale path in {PATHS_FILE.name}: {s}"
|
||||
|
||||
|
||||
def test_every_backend_module_the_worker_imports_is_gated():
|
||||
specs = _pathspecs()
|
||||
missing = sorted(
|
||||
str(f.relative_to(REPO)) for f in _worker_closure()
|
||||
if not _covered(str(f.relative_to(REPO)), specs)
|
||||
)
|
||||
assert not missing, (
|
||||
"The encoding worker imports backend modules not listed in "
|
||||
f"{PATHS_FILE.relative_to(REPO)} — add them so CI redeploys the worker "
|
||||
f"when they change: {missing}"
|
||||
)
|
||||
@@ -494,6 +494,56 @@ class TestEnsureAnyRunning:
|
||||
# Only the first candidate's start was attempted.
|
||||
mock_compute.start.assert_called_once()
|
||||
|
||||
def test_skips_deleted_candidate_and_starts_next(self, manager, mock_db, mock_compute):
|
||||
"""A candidate VM that no longer exists (removed from the fleet while an
|
||||
instance still holds a stale fallback list) is skipped, not fatal."""
|
||||
from google.api_core import exceptions as gcp_exceptions
|
||||
|
||||
stopped = MagicMock()
|
||||
stopped.status = "TERMINATED"
|
||||
|
||||
def _get(project, zone, instance):
|
||||
if instance == "encoding-worker-fallback-gone":
|
||||
raise gcp_exceptions.NotFound("instance not found")
|
||||
return stopped
|
||||
|
||||
mock_compute.get.side_effect = _get
|
||||
# Primary: Spot capacity exhausted. Deleted fallback: NotFound. Live fallback: ok.
|
||||
mock_compute.start.side_effect = [_capacity_op(), _ok_op()]
|
||||
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-blue", zone="us-central1-c",
|
||||
ip="10.0.0.1", is_primary=True),
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-gone", zone="us-central1-a",
|
||||
ip="10.0.0.2"),
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-c2df", zone="us-central1-f",
|
||||
ip="10.0.0.3"),
|
||||
]
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 9, 26, 9, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
result = manager.ensure_any_running(candidates)
|
||||
|
||||
assert result["vm_name"] == "encoding-worker-fallback-c2df"
|
||||
assert result["fell_back"] is True
|
||||
# The deleted VM was never asked to start.
|
||||
started = [c.kwargs["instance"] for c in mock_compute.start.call_args_list]
|
||||
assert started == ["encoding-worker-blue", "encoding-worker-fallback-c2df"]
|
||||
|
||||
def test_all_candidates_missing_raises_start_error(self, manager, mock_compute):
|
||||
"""If every candidate is gone, surface a typed start error (not a bare NotFound)."""
|
||||
from google.api_core import exceptions as gcp_exceptions
|
||||
|
||||
mock_compute.get.side_effect = gcp_exceptions.NotFound("gone")
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="vm-x", zone="us-central1-a", ip="10.0.0.9"),
|
||||
]
|
||||
with pytest.raises(EncodingWorkerStartError) as exc_info:
|
||||
manager.ensure_any_running(candidates)
|
||||
assert exc_info.value.code == "NOT_FOUND"
|
||||
mock_compute.start.assert_not_called()
|
||||
|
||||
def test_falls_through_to_next_zone_on_capacity_error(self, manager, mock_db, mock_compute):
|
||||
"""Capacity error on candidate 1 triggers a try of candidate 2."""
|
||||
mock_instance = MagicMock()
|
||||
@@ -953,9 +1003,9 @@ class TestCapacityStateFeedback:
|
||||
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-16", is_primary=True),
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-n2f", zone="us-central1-f",
|
||||
ip="10.0.0.2", machine_type="n2-highcpu-32"),
|
||||
ip="10.0.0.2", machine_type="n2-highcpu-16"),
|
||||
]
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
@@ -970,7 +1020,7 @@ class TestCapacityStateFeedback:
|
||||
recorded = {}
|
||||
for c in set_calls:
|
||||
recorded.update(c.args[0]["capacity_state"])
|
||||
assert recorded.get("c4d-highcpu-32@us-central1-c") == "2026-05-05T09:00:00+00:00"
|
||||
assert recorded.get("c4d-highcpu-16@us-central1-c") == "2026-05-05T09:00:00+00:00"
|
||||
|
||||
def test_clears_stockout_for_type_on_clean_start(self, manager, mock_db, mock_compute):
|
||||
mock_instance = MagicMock()
|
||||
@@ -980,7 +1030,7 @@ class TestCapacityStateFeedback:
|
||||
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-16", is_primary=True),
|
||||
]
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
@@ -994,7 +1044,7 @@ class TestCapacityStateFeedback:
|
||||
payload = c.args[0] if c.args else {}
|
||||
if "capacity_state" in payload:
|
||||
cleared.update(payload["capacity_state"])
|
||||
assert cleared.get("c4d-highcpu-32@us-central1-c") is None
|
||||
assert cleared.get("c4d-highcpu-16@us-central1-c") is None
|
||||
|
||||
def test_stockout_write_failure_does_not_break_start(self, manager, mock_db, mock_compute):
|
||||
"""A Firestore error while recording a stockout must not abort failover."""
|
||||
@@ -1008,9 +1058,9 @@ class TestCapacityStateFeedback:
|
||||
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-16", is_primary=True),
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-n2f", zone="us-central1-f",
|
||||
ip="10.0.0.2", machine_type="n2-highcpu-32"),
|
||||
ip="10.0.0.2", machine_type="n2-highcpu-16"),
|
||||
]
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
@@ -1035,9 +1085,9 @@ class TestCapacityStateFeedback:
|
||||
# Fallback is first (primary demoted), primary flagged but ranked second.
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-c2df", zone="us-central1-f",
|
||||
ip="10.0.0.9", machine_type="c2d-highcpu-32", is_primary=False),
|
||||
ip="10.0.0.9", machine_type="c2d-highcpu-16", is_primary=False),
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-16", is_primary=True),
|
||||
]
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
@@ -1101,7 +1151,7 @@ class TestDemoteActiveWorker:
|
||||
assert doc_ref.set.called
|
||||
set_args, set_kwargs = doc_ref.set.call_args
|
||||
assert "capacity_state" in set_args[0]
|
||||
assert "c4-highcpu-32@us-central1-c" in set_args[0]["capacity_state"]
|
||||
assert "c4-highcpu-16@us-central1-c" in set_args[0]["capacity_state"]
|
||||
assert set_kwargs.get("merge") is True
|
||||
|
||||
# Cleared the active_override so the retry starts from the primary.
|
||||
|
||||
@@ -31,14 +31,14 @@ def _c(vm, zone, machine_type=None, **extra):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_explicit_machine_type_wins():
|
||||
assert infer_machine_type(_c("whatever", "z", "c2d-highcpu-32")) == "c2d-highcpu-32"
|
||||
assert infer_machine_type(_c("whatever", "z", "c2d-highcpu-16")) == "c2d-highcpu-16"
|
||||
|
||||
|
||||
def test_infer_from_vm_name_specific_before_generic():
|
||||
# "n2d"/"c4d" must not be shadowed by "n2"/"c4".
|
||||
assert infer_machine_type(_c("encoding-worker-fallback-n2da", "z")) == "n2d-highcpu-32"
|
||||
assert infer_machine_type(_c("encoding-worker-fallback-n2f", "z")) == "n2-highcpu-32"
|
||||
assert infer_machine_type(_c("encoding-worker-fallback-c4x", "z")) == "c4-highcpu-32"
|
||||
assert infer_machine_type(_c("encoding-worker-fallback-n2da", "z")) == "n2d-highcpu-16"
|
||||
assert infer_machine_type(_c("encoding-worker-fallback-n2f", "z")) == "n2-highcpu-16"
|
||||
assert infer_machine_type(_c("encoding-worker-fallback-c4x", "z")) == "c4-highcpu-16"
|
||||
|
||||
|
||||
def test_infer_unknown_returns_none():
|
||||
@@ -47,7 +47,7 @@ def test_infer_unknown_returns_none():
|
||||
|
||||
|
||||
def test_runtime_dict_shape_uses_vm_name_key():
|
||||
assert infer_machine_type({"vm_name": "x-n2d-y", "zone": "z"}) == "n2d-highcpu-32"
|
||||
assert infer_machine_type({"vm_name": "x-n2d-y", "zone": "z"}) == "n2d-highcpu-16"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -56,10 +56,10 @@ def test_runtime_dict_shape_uses_vm_name_key():
|
||||
|
||||
def test_orders_fastest_first():
|
||||
pool = [
|
||||
_c("n2", "us-central1-c", "n2-highcpu-32"),
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
|
||||
_c("c2d", "us-central1-f", "c2d-highcpu-32"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-32"),
|
||||
_c("n2", "us-central1-c", "n2-highcpu-16"),
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-16"),
|
||||
_c("c2d", "us-central1-f", "c2d-highcpu-16"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-16"),
|
||||
]
|
||||
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
|
||||
assert got == ["c4d", "c4", "c2d", "n2"]
|
||||
@@ -68,18 +68,18 @@ def test_orders_fastest_first():
|
||||
def test_unknown_type_sorts_last_but_kept():
|
||||
pool = [
|
||||
_c("mystery", "z"), # no machine_type, unknown name
|
||||
_c("c4d", "z", "c4d-highcpu-32"),
|
||||
_c("c4d", "z", "c4d-highcpu-16"),
|
||||
]
|
||||
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
|
||||
assert got == ["c4d", "mystery"]
|
||||
assert SPEED_RANK["c4d-highcpu-32"] < UNKNOWN_RANK
|
||||
assert SPEED_RANK["c4d"] < UNKNOWN_RANK
|
||||
|
||||
|
||||
def test_stable_within_equal_rank_preserves_zone_spread():
|
||||
# Two n2 in different zones keep input order (caller's secondary preference).
|
||||
pool = [
|
||||
_c("n2f", "us-central1-f", "n2-highcpu-32"),
|
||||
_c("n2c", "us-central1-c", "n2-highcpu-32"),
|
||||
_c("n2f", "us-central1-f", "n2-highcpu-16"),
|
||||
_c("n2c", "us-central1-c", "n2-highcpu-16"),
|
||||
]
|
||||
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
|
||||
assert got == ["n2f", "n2c"]
|
||||
@@ -91,24 +91,24 @@ def test_stable_within_equal_rank_preserves_zone_spread():
|
||||
|
||||
def test_recent_stockout_demotes_type_to_back():
|
||||
pool = [
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-32"),
|
||||
_c("n2", "us-central1-c", "n2-highcpu-32"),
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-16"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-16"),
|
||||
_c("n2", "us-central1-c", "n2-highcpu-16"),
|
||||
]
|
||||
# c4d stocked out 1 minute ago → demoted behind the still-healthy types.
|
||||
capacity_state = {"c4d-highcpu-32@us-central1-c": (NOW - timedelta(minutes=1)).isoformat()}
|
||||
capacity_state = {"c4d-highcpu-16@us-central1-c": (NOW - timedelta(minutes=1)).isoformat()}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
assert got == ["c4", "n2", "c4d"]
|
||||
|
||||
|
||||
def test_cooldown_expires_and_snaps_back_to_fastest():
|
||||
pool = [
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-32"),
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-16"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-16"),
|
||||
]
|
||||
# Stockout older than COOLDOWN → c4d is hot again and returns to the top.
|
||||
old = (NOW - timedelta(seconds=COOLDOWN_SECONDS + 60)).isoformat()
|
||||
capacity_state = {"c4d-highcpu-32@us-central1-c": old}
|
||||
capacity_state = {"c4d-highcpu-16@us-central1-c": old}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
assert got == ["c4d", "c4"]
|
||||
|
||||
@@ -116,15 +116,15 @@ def test_cooldown_expires_and_snaps_back_to_fastest():
|
||||
def test_two_types_stocked_out_still_serves_from_deep_pool():
|
||||
# Both newest-gen types (c4d, c4) exhausted; deep pools keep serving in order.
|
||||
pool = [
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-32"),
|
||||
_c("c2d", "us-central1-f", "c2d-highcpu-32"),
|
||||
_c("n2d", "us-central1-a", "n2d-highcpu-32"),
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-16"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-16"),
|
||||
_c("c2d", "us-central1-f", "c2d-highcpu-16"),
|
||||
_c("n2d", "us-central1-a", "n2d-highcpu-16"),
|
||||
]
|
||||
recent = (NOW - timedelta(minutes=2)).isoformat()
|
||||
capacity_state = {
|
||||
"c4d-highcpu-32@us-central1-c": recent,
|
||||
"c4-highcpu-32@us-central1-a": recent,
|
||||
"c4d-highcpu-16@us-central1-c": recent,
|
||||
"c4-highcpu-16@us-central1-a": recent,
|
||||
}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
# Hot deep pools first (fastest-first among them), then the two cold types.
|
||||
@@ -133,31 +133,31 @@ def test_two_types_stocked_out_still_serves_from_deep_pool():
|
||||
|
||||
def test_type_only_capacity_key_demotes_all_zones():
|
||||
pool = [
|
||||
_c("c4d-c", "us-central1-c", "c4d-highcpu-32"),
|
||||
_c("n2", "us-central1-c", "n2-highcpu-32"),
|
||||
_c("c4d-c", "us-central1-c", "c4d-highcpu-16"),
|
||||
_c("n2", "us-central1-c", "n2-highcpu-16"),
|
||||
]
|
||||
capacity_state = {"c4d-highcpu-32": (NOW - timedelta(minutes=1)).isoformat()}
|
||||
capacity_state = {"c4d-highcpu-16": (NOW - timedelta(minutes=1)).isoformat()}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
assert got == ["n2", "c4d-c"]
|
||||
|
||||
|
||||
def test_empty_capacity_state_is_pure_speed_order():
|
||||
pool = [_c("n2", "z", "n2-highcpu-32"), _c("c4d", "z", "c4d-highcpu-32")]
|
||||
pool = [_c("n2", "z", "n2-highcpu-16"), _c("c4d", "z", "c4d-highcpu-16")]
|
||||
assert [c["vm"] for c in ordered_candidates(pool, {}, now=NOW)] == ["c4d", "n2"]
|
||||
assert [c["vm"] for c in ordered_candidates(pool, None, now=NOW)] == ["c4d", "n2"]
|
||||
|
||||
|
||||
def test_naive_timestamp_tolerated():
|
||||
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-32"), _c("n2", "z", "n2-highcpu-32")]
|
||||
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-16"), _c("n2", "z", "n2-highcpu-16")]
|
||||
naive = (NOW - timedelta(minutes=1)).replace(tzinfo=None).isoformat()
|
||||
capacity_state = {"c4d-highcpu-32@us-central1-c": naive}
|
||||
capacity_state = {"c4d-highcpu-16@us-central1-c": naive}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
assert got == ["n2", "c4d"]
|
||||
|
||||
|
||||
def test_malformed_timestamp_ignored():
|
||||
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-32"), _c("n2", "z", "n2-highcpu-32")]
|
||||
capacity_state = {"c4d-highcpu-32@us-central1-c": "not-a-date"}
|
||||
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-16"), _c("n2", "z", "n2-highcpu-16")]
|
||||
capacity_state = {"c4d-highcpu-16@us-central1-c": "not-a-date"}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
assert got == ["c4d", "n2"] # unparseable → not in cooldown
|
||||
|
||||
@@ -167,6 +167,6 @@ def test_empty_pool():
|
||||
|
||||
|
||||
def test_cooldown_key_shape():
|
||||
assert cooldown_key(_c("x", "us-central1-c", "c4d-highcpu-32")) == "c4d-highcpu-32@us-central1-c"
|
||||
assert cooldown_key(_c("x", None, "n2-highcpu-32")) == "n2-highcpu-32"
|
||||
assert cooldown_key(_c("x", "us-central1-c", "c4d-highcpu-16")) == "c4d-highcpu-16@us-central1-c"
|
||||
assert cooldown_key(_c("x", None, "n2-highcpu-16")) == "n2-highcpu-16"
|
||||
assert cooldown_key(_c("no-token", "z")) is None
|
||||
@@ -166,6 +166,52 @@ class TestProcessStaleReviews:
|
||||
assert call_args[0][1]['state_data.expiry_reminder_sent'] is True
|
||||
assert 'state_data.expiry_reminder_sent_at' in call_args[0][1]
|
||||
|
||||
@pytest.mark.parametrize("email", [
|
||||
"e2e-test-runner@nomadkaraoke.com",
|
||||
"abc.xyz@inbox.testmail.app",
|
||||
])
|
||||
async def test_test_account_reminder_is_silent(self, email, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""A stranded E2E job hits the 24h window: no email, but still marked so it isn't retried."""
|
||||
job = _make_job(hours_ago=30, user_email=email)
|
||||
mock_firestore.list_jobs.side_effect = [[job], [], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["reminders_sent"] == 1
|
||||
mock_email_service.send_review_reminder.assert_not_called()
|
||||
assert mock_firestore.update_job.call_args[0][1]['state_data.expiry_reminder_sent'] is True
|
||||
|
||||
async def test_test_account_review_expiry_cancels_without_email(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""A stranded E2E job past 48h is still expired (not left forever), just silently."""
|
||||
job = _make_job(hours_ago=50, user_email="e2e-test-runner@nomadkaraoke.com")
|
||||
mock_firestore.list_jobs.side_effect = [[job], [], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 1
|
||||
mock_job_manager.cancel_job.assert_called_once()
|
||||
mock_email_service.send_review_expired.assert_not_called()
|
||||
|
||||
async def test_test_account_duration_confirm_expiry_cancels_without_email(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
job = _make_job(
|
||||
hours_ago=50,
|
||||
status=JobStatus.AWAITING_DURATION_CONFIRM,
|
||||
user_email="e2e-test-runner@nomadkaraoke.com",
|
||||
)
|
||||
mock_firestore.list_jobs.side_effect = [[], [], [job]]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 1
|
||||
mock_job_manager.cancel_job.assert_called_once()
|
||||
mock_email_service.send_duration_confirm_expired.assert_not_called()
|
||||
|
||||
async def test_kjbox_job_reminder_uses_one_click_login_link(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""kjbox singers never signed in on gen → the 24h reminder links via a sign-in token."""
|
||||
job = _make_job(hours_ago=30)
|
||||
|
||||
@@ -167,7 +167,7 @@ class TestSystemStatusAdmin:
|
||||
assert admin["on_fallback"] is False
|
||||
assert admin["active_vm"] == "encoding-worker-b"
|
||||
assert admin["active_zone"] == "us-central1-c"
|
||||
assert admin["active_machine_type"] == "c4d-highcpu-32"
|
||||
assert admin["active_machine_type"] == "c4d-highcpu-16"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_sees_capacity_fallback_worker(
|
||||
@@ -203,5 +203,5 @@ class TestSystemStatusAdmin:
|
||||
assert admin["on_fallback"] is True
|
||||
assert admin["active_vm"] == "encoding-worker-fallback-n2c"
|
||||
assert admin["active_zone"] == "us-central1-a"
|
||||
# "n2c" family token → n2-highcpu-32 (inferred from the VM name).
|
||||
assert admin["active_machine_type"] == "n2-highcpu-32"
|
||||
# "n2c" family token → n2-highcpu-16 (inferred from the VM name).
|
||||
assert admin["active_machine_type"] == "n2-highcpu-16"
|
||||
@@ -11,10 +11,13 @@ def vocals_stem_path(job) -> Optional[str]:
|
||||
- "vocals" : full vocal from a 2-stem split (rare)
|
||||
- "vocals_clean" : full vocal from the primary vocal/instrumental
|
||||
split (present on essentially all cloud jobs)
|
||||
- "lead_vocals" : last-resort fallback (misses backing lines)
|
||||
- "lead_vocals" : fallback (misses backing lines)
|
||||
- "vocals_derived": mix minus the user's own instrumental, for jobs that
|
||||
skipped separation (backend/services/derived_vocals.py).
|
||||
Waveform-only — never a deliverable stem.
|
||||
"""
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
for key in ("vocals", "vocals_clean", "lead_vocals"):
|
||||
for key in ("vocals", "vocals_clean", "lead_vocals", "vocals_derived"):
|
||||
if stems.get(key):
|
||||
return stems[key]
|
||||
return None
|
||||
@@ -17,9 +17,9 @@ TEST_EMAIL_DOMAINS = [
|
||||
# These live on the internal nomadkaraoke.com domain (so they'd otherwise pass
|
||||
# is_internal_email, not is_test_email), but every job they create is E2E test
|
||||
# data. Listed here so admin dashboards' exclude_test filter hides their jobs.
|
||||
# e2e-test-runner is the persistent account the CI post-deploy canary and daily
|
||||
# E2E workflows impersonate; without this entry its piri/dog jobs leak into the
|
||||
# admin "My Jobs" view.
|
||||
# e2e-test-runner is the persistent account the daily E2E workflow
|
||||
# impersonates; without this entry its piri/dog jobs leak into the admin
|
||||
# "My Jobs" view.
|
||||
TEST_EMAIL_ADDRESSES = [
|
||||
"e2e-test-runner@nomadkaraoke.com",
|
||||
]
|
||||
|
||||
@@ -310,6 +310,16 @@ async def process_lyrics_transcription(job_id: str) -> bool:
|
||||
job_log.info(f"Audio downloaded: {os.path.basename(audio_path)}")
|
||||
download_span.set_attribute("audio_file", os.path.basename(audio_path))
|
||||
|
||||
# Jobs with the user's own instrumental skip separation, so there's
|
||||
# no vocals stem for the review waveform. Derive an approximation
|
||||
# (mix − instrumental) on CPU alongside transcription.
|
||||
derived_vocals_task = None
|
||||
if getattr(job, 'existing_instrumental_gcs_path', None):
|
||||
derived_vocals_task = asyncio.create_task(asyncio.to_thread(
|
||||
_store_derived_vocals, job_id, job.existing_instrumental_gcs_path,
|
||||
audio_path, storage, job_manager, job_log,
|
||||
))
|
||||
|
||||
# Set up LyricsTranscriber cache directory and sync from GCS
|
||||
# This allows reusing cached AudioShake/lyrics API responses across Cloud Run instances
|
||||
cache_dir = os.path.join(temp_dir, "lyrics-cache")
|
||||
@@ -539,6 +549,21 @@ async def process_lyrics_transcription(job_id: str) -> bool:
|
||||
# cancelled on Cloud Run Job event-loop teardown, orphaning jobs at
|
||||
# `downloading`; awaiting guarantees the screens Cloud Task is
|
||||
# enqueued before this worker returns.
|
||||
# Screens pre-computes the vocals peaks, so the derived stem must be
|
||||
# registered before we advance. Never fails the job.
|
||||
if derived_vocals_task is not None:
|
||||
try:
|
||||
# shield: on timeout stop waiting but let the thread finish
|
||||
# on its own (threads can't be cancelled; it cleans up after itself)
|
||||
await asyncio.wait_for(asyncio.shield(derived_vocals_task), DERIVED_VOCALS_TIMEOUT_SECONDS)
|
||||
except asyncio.TimeoutError:
|
||||
job_log.warning(
|
||||
f"Derived vocals still running after {DERIVED_VOCALS_TIMEOUT_SECONDS}s; "
|
||||
"continuing without waiting (non-fatal)"
|
||||
)
|
||||
except Exception as e:
|
||||
job_log.warning(f"Derived vocals task failed (non-fatal): {e}")
|
||||
|
||||
job_log.info("Lyrics worker complete, advancing to screen generation...")
|
||||
job_manager.mark_lyrics_complete(job_id)
|
||||
await job_manager.advance_to_screens_if_ready(job_id)
|
||||
@@ -597,6 +622,44 @@ async def process_lyrics_transcription(job_id: str) -> bool:
|
||||
logger.debug(f"[job:{job_id}] Cleaned up temp directory: {temp_dir}")
|
||||
|
||||
|
||||
# Waveform-only nicety: never let it hold up the lyrics -> screens handoff for long.
|
||||
DERIVED_VOCALS_TIMEOUT_SECONDS = 180
|
||||
|
||||
|
||||
def _store_derived_vocals(job_id, instrumental_gcs_path, mix_path, storage, job_manager, job_log) -> None:
|
||||
"""Derive approximate vocals (mix − user instrumental) for the review waveform
|
||||
and register them as stems.vocals_derived. Best-effort: logs and returns on failure.
|
||||
|
||||
Uses its own temp dir (the worker's temp_dir may be removed on failure paths
|
||||
while this thread is still running); only reads mix_path.
|
||||
"""
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
from backend.services.derived_vocals import derive_vocals_file
|
||||
|
||||
work_dir = tempfile.mkdtemp(prefix="derived-vocals-")
|
||||
try:
|
||||
ext = os.path.splitext(instrumental_gcs_path)[1] or ".audio"
|
||||
inst_path = os.path.join(work_dir, f"user_instrumental{ext}")
|
||||
storage.download_file(instrumental_gcs_path, inst_path)
|
||||
out_path = os.path.join(work_dir, "vocals_derived.flac")
|
||||
result = derive_vocals_file(mix_path, inst_path, out_path)
|
||||
summary = (f"offset {result.offset_samples} samples, gain {result.gain:.3f}, "
|
||||
f"residual {result.residual_ratio:.2f}")
|
||||
if not result.useful:
|
||||
job_log.info(f"Instrumental didn't cancel against the mix ({summary}); no vocal waveform")
|
||||
return
|
||||
gcs_path = f"jobs/{job_id}/stems/vocals_derived.flac"
|
||||
storage.upload_file(out_path, gcs_path)
|
||||
job_manager.update_file_url(job_id, 'stems', 'vocals_derived', gcs_path)
|
||||
job_log.info(f"Derived vocals for review waveform ({summary})")
|
||||
except Exception as e:
|
||||
job_log.warning(f"Could not derive vocals for review waveform (non-fatal): {e}")
|
||||
finally:
|
||||
shutil.rmtree(work_dir, ignore_errors=True)
|
||||
|
||||
|
||||
async def download_audio(
|
||||
job_id: str,
|
||||
temp_dir: str,
|
||||
|
||||
@@ -790,7 +790,7 @@ def _park_job_for_capacity_retry(
|
||||
|
||||
The user-facing message tells the user this is temporary and will retry
|
||||
automatically — no action needed. Auto-retry is driven by the
|
||||
/api/internal/retry-pending-render-jobs endpoint, fired every 5 min by
|
||||
/api/internal/retry-pending-render-jobs endpoint, fired every 10 min by
|
||||
Cloud Scheduler.
|
||||
"""
|
||||
now = datetime.now(UTC).isoformat()
|
||||
@@ -850,7 +850,7 @@ def park_active_render_jobs_for_shutdown() -> int:
|
||||
|
||||
Parking transitions the job to RENDER_PENDING_CAPACITY, which the
|
||||
`/api/internal/retry-pending-render-jobs` Cloud Scheduler job picks up
|
||||
every 5 minutes.
|
||||
every 10 minutes.
|
||||
|
||||
Only jobs currently in the RENDERING_VIDEO state are parked — if the
|
||||
worker completed concurrently (or the job was already moved past this
|
||||
|
||||
@@ -16,6 +16,7 @@ from backend.models.job import JobStatus
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.utils.test_data import is_test_email
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -47,7 +48,8 @@ async def process_stale_reviews() -> Dict[str, Any]:
|
||||
- 48h expiry: add_credits(credits_charged) + cancel_job + send_duration_confirm_expired
|
||||
The full credits_charged amount (not flat 1) is refunded.
|
||||
|
||||
Excludes made-for-you and tenant jobs.
|
||||
Excludes made-for-you and tenant jobs. Jobs owned by automated-test accounts
|
||||
(e.g. a stranded E2E job) are still expired, but never emailed.
|
||||
|
||||
Returns:
|
||||
Summary dict with counts and any errors encountered.
|
||||
@@ -121,6 +123,10 @@ async def process_stale_reviews() -> Dict[str, Any]:
|
||||
|
||||
is_duration_confirm = job.status in _DURATION_CONFIRM_STATUSES
|
||||
|
||||
# A stranded E2E job must not email the test account (it forwards to
|
||||
# a real inbox) — still expire it, just silently.
|
||||
send_emails = bool(job.user_email) and not is_test_email(job.user_email)
|
||||
|
||||
if hours_elapsed >= REVIEW_EXPIRY_HOURS:
|
||||
if is_duration_confirm:
|
||||
# Duration-confirm expiry: refund full credits_charged, then cancel.
|
||||
@@ -179,7 +185,7 @@ async def process_stale_reviews() -> Dict[str, Any]:
|
||||
f"Job {job.job_id}: failed to set duration_confirm_expiry_processed: {flag_err}"
|
||||
)
|
||||
|
||||
if job.user_email:
|
||||
if send_emails:
|
||||
try:
|
||||
email_service.send_duration_confirm_expired(
|
||||
to_email=job.user_email,
|
||||
@@ -209,7 +215,7 @@ async def process_stale_reviews() -> Dict[str, Any]:
|
||||
jobs_expired += 1
|
||||
|
||||
# Send expiry notification email
|
||||
if job.user_email:
|
||||
if send_emails:
|
||||
try:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
@@ -249,7 +255,7 @@ async def process_stale_reviews() -> Dict[str, Any]:
|
||||
)
|
||||
|
||||
# Send reminder email (different email per status)
|
||||
if job.user_email:
|
||||
if send_emails:
|
||||
try:
|
||||
# Look up user locale for email
|
||||
user_locale = "en"
|
||||
|
||||
@@ -1180,7 +1180,12 @@ async def _handle_native_distribution(
|
||||
remote_folder = f"{dropbox_path}/{folder_name}"
|
||||
|
||||
job_log.info(f"Uploading to Dropbox folder: {remote_folder}")
|
||||
dropbox.upload_folder(temp_dir, remote_folder)
|
||||
from backend.services.dropbox_service import dropbox_skip_suffixes_for
|
||||
|
||||
dropbox.upload_folder(
|
||||
temp_dir, remote_folder,
|
||||
exclude_suffixes=dropbox_skip_suffixes_for(dropbox_path),
|
||||
)
|
||||
|
||||
# Create sharing link
|
||||
try:
|
||||
|
||||
@@ -931,8 +931,15 @@ class VideoWorkerOrchestrator:
|
||||
folder_name = f"{self.result.brand_code or 'TRACK-0000'} - {base_name}"
|
||||
remote_folder = f"{self.config.dropbox_path}/{folder_name}"
|
||||
|
||||
# Upload entire output directory
|
||||
dropbox.upload_folder(self.config.output_dir, remote_folder)
|
||||
# Upload the output directory, minus files Nomad's own Dropbox archive
|
||||
# doesn't need (lossless 4K MP4 by default — it stays in GCS). Tenant
|
||||
# folders get everything. See dropbox_skip_suffixes_for.
|
||||
from backend.services.dropbox_service import dropbox_skip_suffixes_for
|
||||
|
||||
skip = dropbox_skip_suffixes_for(self.config.dropbox_path)
|
||||
if skip:
|
||||
self.job_log.info(f"Excluding from Dropbox upload (kept in GCS): {list(skip)}")
|
||||
dropbox.upload_folder(self.config.output_dir, remote_folder, exclude_suffixes=skip)
|
||||
|
||||
# Create sharing link
|
||||
try:
|
||||
|
||||
+36
-17
@@ -38,10 +38,11 @@
|
||||
│ (jobs) │ │ (files) │ │ (API keys) │ │ Worker (*) │
|
||||
└──────────┘ └──────────┘ └──────────────┘ └──────────────┘
|
||||
|
||||
(*) GCE Encoding Worker: a ranked pool of 6 x86_64 32-vCPU highcpu machine
|
||||
families (c4d/c4/n4d/c2d/n2d/n2). c4d-highcpu-32 (AMD EPYC Turin) is the
|
||||
fastest and stays the primary/preferred pick; the other families are
|
||||
stockout-resilience fallbacks selected fastest-first with a capacity cooldown.
|
||||
(*) GCE Encoding Worker: a Spot c4d-highcpu-16 blue-green pair (AMD EPYC
|
||||
Turin, the preferred pick) plus ONE on-demand c2d-highcpu-16 fallback in a
|
||||
different zone for Spot/c4d stockouts (3 VMs since 2026-09-26 — see
|
||||
docs/archive/2026-09-26-encoding-cost-cuts.md). Candidates are selected
|
||||
fastest-first with a capacity cooldown.
|
||||
Used for both final video encoding and preview video generation.
|
||||
Uses immutable deployment pattern - see infrastructure/encoding-worker/README.md
|
||||
and the "Encoding Worker" section below.
|
||||
@@ -50,7 +51,7 @@
|
||||
### Error Monitor
|
||||
|
||||
```text
|
||||
Cloud Logging (all services) ──→ Error Monitor (Cloud Run Job, */15 min)
|
||||
Cloud Logging (all services) ──→ Error Monitor (Cloud Run Job, hourly)
|
||||
Frontend clients ───────────────→ POST /api/client-errors ──→ Firestore
|
||||
│
|
||||
├─ Normalize & deduplicate
|
||||
@@ -262,7 +263,7 @@ LyricsTranscriber LyricsTranscriber
|
||||
| karaoke-decide | Song catalog (MusicBrainz + Spotify) for autocomplete | Optional |
|
||||
| KaraokeNerds | Community karaoke version detection | Optional |
|
||||
|
||||
*Flacfetch runs on a dedicated GCE VM with YouTube cookies and tracker access. Without it, YouTube downloads will fail due to bot detection on Cloud Run IPs.
|
||||
*Flacfetch runs on a dedicated server (Netcup VPS, reached over public HTTPS) with YouTube cookies and tracker access. Without it, YouTube downloads will fail due to bot detection on Cloud Run IPs.
|
||||
|
||||
### Data Pipeline Cloud Functions
|
||||
|
||||
@@ -305,16 +306,25 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
|
||||
## Encoding Worker: blue-green primary pair + multi-family fallback pool
|
||||
|
||||
The GCE encoding worker is a **blue-green primary pair** (`encoding-worker-a`/`-b`,
|
||||
both c4d-highcpu-32 in us-central1-c) plus a **ranked pool of stockout-resilience
|
||||
fallback VMs** spanning 6 x86_64 machine families (see "Multi-instance-type pool"
|
||||
below). **10 VMs total**, all TERMINATED by default and started on demand.
|
||||
both **Spot** c4d-highcpu-16 in us-central1-c) plus **one on-demand fallback**
|
||||
(`encoding-worker-fallback-c2df`, c2d-highcpu-16, us-central1-f). **3 VMs total**
|
||||
(cut from 10 on 2026-09-26 — docs/archive/2026-09-26-encoding-cost-cuts.md), all
|
||||
TERMINATED by default, started on demand, and idle-stopped after 5 min.
|
||||
|
||||
**Spot preemption:** the pair uses `instance_termination_action=STOP`, so a
|
||||
preempted worker is just a TERMINATED VM that the next request restarts. An
|
||||
encode in flight when the VM is preempted is detected by
|
||||
`EncodingService.wait_for_completion` (the pinned worker VM is no longer RUNNING)
|
||||
and raised as `EncodingJobLostError`, which `run_with_lost_job_resubmit` resubmits
|
||||
— the resubmit's connection failure then starts the Spot VM again, or the
|
||||
on-demand fallback if Spot capacity is gone.
|
||||
|
||||
### Architecture
|
||||
|
||||
```text
|
||||
Frontend → Backend (Cloud Run) → Firestore config → active worker (primary, or a
|
||||
↑ capacity-fallback "override")
|
||||
Cloud Scheduler (5 min) → Cloud Function → checks idle + stops VMs
|
||||
Cloud Scheduler (2 min) → Cloud Function → checks idle (5 min) + stops VMs
|
||||
↑
|
||||
CI (GitHub Actions) → selects a fresh "green" (ranked pool) → health + encode test
|
||||
→ promote (swap primary OR set active_override) → stop old
|
||||
@@ -323,10 +333,13 @@ CI (GitHub Actions) → selects a fresh "green" (ranked pool) → health + encod
|
||||
### Multi-instance-type pool (stockout resilience, v0.195.0)
|
||||
|
||||
A single machine family can hit a region-wide `ZONE_RESOURCE_POOL_EXHAUSTED`
|
||||
stockout across every zone at once. To survive that, the fallback fleet spans
|
||||
**6 families** (c4d, c4, n4d, c2d, n2d, n2 — all `-highcpu-32`, ≥32 GB) across
|
||||
zones a/b/c/f: `encoding-worker-fallback-a`/`-b` (c4d), `-n2c`/`-n2f` (n2),
|
||||
`-c4a` (c4), `-n4db` (n4d), `-c2df` (c2d), `-n2da` (n2d).
|
||||
stockout across every zone at once. To survive that, the fallback lives in a
|
||||
different family AND zone from the c4d pair: `encoding-worker-fallback-c2df`
|
||||
(c2d-highcpu-16, on-demand, us-central1-f). The pool was 8 fallbacks across 6
|
||||
families (v0.195.0) until the 2026-09-26 cost cut; the selection machinery below
|
||||
still handles any number of fallbacks — re-add entries to
|
||||
`EncodingWorkerConfig.FALLBACKS` + the `encoding-worker-fallback-vms` secret if
|
||||
stockouts become a problem again.
|
||||
|
||||
**Candidate ordering is one shared pure module**,
|
||||
`backend/services/encoding_worker_preference.py::ordered_candidates(pool, capacity_state)`,
|
||||
@@ -494,7 +507,7 @@ Audio can come from file upload or remote search (YouTube, torrents). All YouTub
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────────────────────┐
|
||||
│ Flacfetch VM (GCE) │
|
||||
│ Flacfetch server (Netcup VPS, off-GCP) │
|
||||
│ │
|
||||
│ • Has YouTube cookies (avoids bot detection) │
|
||||
│ • Has tracker credentials (RED, OPS private trackers) │
|
||||
@@ -504,7 +517,10 @@ Audio can come from file upload or remote search (YouTube, torrents). All YouTub
|
||||
```
|
||||
|
||||
**Key environment variables**:
|
||||
- `FLACFETCH_API_URL` - URL of flacfetch VM (e.g., `http://10.x.x.x:8080`)
|
||||
- `FLACFETCH_API_URL` - public HTTPS URL of the flacfetch server (secret `flacfetch-api-url`). The
|
||||
serverless VPC connector that once let Cloud Run reach the old GCE VM's private IP was deleted
|
||||
2026-09-26; the backend and `audio-download-job` / `bulk-search-job` have no VPC egress, so every
|
||||
dependency they call must be reachable on a public address.
|
||||
- `FLACFETCH_API_KEY` - API key for authentication
|
||||
|
||||
## Worker Execution
|
||||
@@ -582,7 +598,10 @@ Audio stem separation runs **directly inside the audio worker Cloud Run Job**
|
||||
- **Two-stage ensemble preset** — `instrumental_clean` (stage 1) + `karaoke` (stage 2).
|
||||
- **Model cache** — Models are downloaded to `model_file_dir` (GCS-backed or local) and reused across executions.
|
||||
|
||||
**Rollback**: The old audio-separator Cloud Run Service (HTTP endpoint) is kept for rollback but no longer receives traffic. It will be removed in a future phase.
|
||||
**The `audio-separator` Cloud Run GPU service** (us-east4, scale-to-zero) is no longer used by
|
||||
prod gen jobs, but it still serves external remote-separation clients (`audio-separator-remote` /
|
||||
local `karaoke-gen` CLI with `AUDIO_SEPARATOR_API_URL`; ~40 `/separate` calls/month as of
|
||||
2026-09). Keep it at min-instances 0; don't remove it without checking its request logs first.
|
||||
|
||||
### Quick version (kjbox make-it jobs)
|
||||
|
||||
|
||||
+1
-1
@@ -221,7 +221,7 @@ TESTMAIL_NAMESPACE=... # testmail.app namespace
|
||||
|
||||
## Encoding Worker Operations
|
||||
|
||||
The encoding worker is a blue-green primary pair (`encoding-worker-a`/`-b`, c4d) plus a ranked pool of 8 stopped fallback VMs spanning 6 machine families (c4d/c4/n4d/c2d/n2d/n2) for stockout resilience — 10 VMs total. Candidate ordering (runtime + deploy) is the shared `backend/services/encoding_worker_preference.py`. See [ARCHITECTURE.md](ARCHITECTURE.md#encoding-worker-blue-green-primary-pair--multi-family-fallback-pool) for the full design.
|
||||
The encoding worker is a Spot blue-green primary pair (`encoding-worker-a`/`-b`, c4d-highcpu-16) plus one stopped on-demand fallback (`encoding-worker-fallback-c2df`, c2d-highcpu-16, us-central1-f) — 3 VMs total since 2026-09-26. CI only blue-green redeploys the worker when a path in `infrastructure/encoding-worker/worker_code_paths.txt` changed since the serving version (or via Actions → CI → Run workflow with "Force a blue-green redeploy of the GCE encoding worker"). Candidate ordering (runtime + deploy) is the shared `backend/services/encoding_worker_preference.py`. See [ARCHITECTURE.md](ARCHITECTURE.md#encoding-worker-blue-green-primary-pair--multi-family-fallback-pool) for the full design.
|
||||
|
||||
### Seed Firestore config (initial setup or reset)
|
||||
|
||||
|
||||
+48
-16
@@ -14,7 +14,7 @@
|
||||
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
|
||||
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
|
||||
| GCS job files | S3 `gcs/job-files/` | Sync to new bucket | 24h |
|
||||
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 24h |
|
||||
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 7 days (weekly, Sundays; incremental) |
|
||||
| Secret Manager | S3 `secrets/YYYY-MM-DD.bin` (sealed-box encrypted) | Decrypt with private key from KeepassXC | 24h |
|
||||
| AWS credentials (function) | GCP Secret Manager `aws-backup-credentials` | Read directly | On-change |
|
||||
| AWS credentials (offline) | KeepassXC — "Nomad Karaoke — DR backup AWS access" | Manual lookup | On-change |
|
||||
@@ -25,7 +25,7 @@
|
||||
- [ ] KeepassXC contains "Nomad Karaoke — DR backup AWS access" (access key, secret key, region, S3 bucket name)
|
||||
- [ ] KeepassXC contains "Nomad Karaoke — DR backup decryption key" (Curve25519 private key, 64 hex chars)
|
||||
- [ ] GitHub repo `nomadkaraoke/karaoke-gen` has the secrets `AWS_BACKUP_READONLY_ACCESS_KEY_ID`, `AWS_BACKUP_READONLY_SECRET_ACCESS_KEY`, `DR_MONITOR_DISCORD_WEBHOOK` configured (powers the freshness monitor)
|
||||
- [ ] GCP Secret Manager `github-backup-token` holds a valid GitHub PAT (`repo` + `read:org`) so the nightly job can bundle every repo — without it the git-repo backup silently skips (see § "Git repo backup setup")
|
||||
- [ ] GCP Secret Manager `github-backup-token` holds a valid GitHub PAT (`repo` + `read:org`) so the weekly git step can bundle every repo — without it the git-repo backup silently skips (see § "Git repo backup setup")
|
||||
- [ ] You can decrypt yesterday's secrets backup locally (run the drill in § "Quarterly restore drill")
|
||||
- [ ] Your KeepassXC database itself is backed up off-machine (cloud sync, second device, or printed paper recovery)
|
||||
|
||||
@@ -35,13 +35,15 @@ If any of these fail, fix them now — not during an incident.
|
||||
|
||||
### Firestore Recovery
|
||||
|
||||
**Option A — PITR (fastest, within 7 days):**
|
||||
**Option A — last night's local export (fastest, within 24h):**
|
||||
|
||||
Point-in-time recovery was **disabled on 2026-09-26** (GCP cost cut), so there
|
||||
is no PITR restore any more. The backup function exports Firestore nightly to
|
||||
`gs://nomadkaraoke-backup-staging/firestore/<YYYY-MM-DD>/` (only the latest
|
||||
night is kept):
|
||||
```bash
|
||||
gcloud firestore databases restore \
|
||||
--source-database="(default)" \
|
||||
--destination-database="(default)-restored" \
|
||||
--snapshot-time="2026-03-28T12:00:00Z" \
|
||||
--project=nomadkaraoke
|
||||
LATEST=$(gcloud storage ls gs://nomadkaraoke-backup-staging/firestore/ | sort | tail -1)
|
||||
gcloud firestore import "$LATEST" --project=nomadkaraoke
|
||||
```
|
||||
|
||||
**Option B — Import from S3 backup:**
|
||||
@@ -307,7 +309,7 @@ Some external services lock to redirect URIs or treat the old GCP project ID as
|
||||
|
||||
If the GitHub account is suspended (e.g. an automated copyright false-positive)
|
||||
or repos are taken down, **the code and its full history are still in S3**. The
|
||||
nightly backup bundles every repo under `github.com/nomadkaraoke` and
|
||||
weekly backup bundles every repo under `github.com/nomadkaraoke` and
|
||||
`github.com/beveradb` into a single `git bundle` per repo — a self-contained
|
||||
file you can clone from directly, no GitHub required. GCP is unaffected, so
|
||||
production keeps running; this is purely about recovering the source of truth to
|
||||
@@ -322,8 +324,18 @@ a new home.
|
||||
flags, and per-repo backup status. Use it to know exactly what existed and to
|
||||
recreate repo settings on the new host.
|
||||
|
||||
Forks are excluded by default (recoverable from upstream). Repos are only as
|
||||
fresh as the last nightly run (24h RPO).
|
||||
Forks are excluded by default (recoverable from upstream). The git step runs
|
||||
**weekly (Sundays)** and is **incremental** (since 2026-09-26, to cut
|
||||
cross-cloud egress): a repo is only re-cloned and re-uploaded when its GitHub
|
||||
`pushed_at` is newer than its bundle's S3 upload time (minus a 1h safety lag);
|
||||
unchanged repos show `"status": "unchanged"` in the manifest and keep their
|
||||
existing S3 bundle. `git-repos/` only uploads to S3 in the same invocation as
|
||||
the git step (a bundle stranded in staging by a failed upload is re-bundled next
|
||||
Sunday rather than shipped late, which would break the lag assumption). The
|
||||
first Sunday of each month re-bundles everything. So a
|
||||
bundle is at most ~7 days behind (7-day RPO). To force a run now:
|
||||
`?mode=git_repos` (incremental) or `?mode=git_repos&full=1` (all repos) — see
|
||||
§ "Git repo backup setup".
|
||||
|
||||
### Restore
|
||||
|
||||
@@ -399,15 +411,16 @@ One-time setup so the nightly job can bundle private repos:
|
||||
3. The owners backed up are set by the `GIT_BACKUP_OWNERS` env var on the
|
||||
`backup-to-aws` function (default `nomadkaraoke,beveradb`), wired in
|
||||
`infrastructure/modules/backup.py`.
|
||||
4. Trigger a run and confirm bundles appear:
|
||||
4. Trigger a git-only run (skips Firestore/BigQuery/GCS/secrets, so it is
|
||||
safe to run any time) and confirm bundles appear:
|
||||
```bash
|
||||
curl -X POST -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
|
||||
https://us-central1-nomadkaraoke.cloudfunctions.net/backup-to-aws
|
||||
"https://us-central1-nomadkaraoke.cloudfunctions.net/backup-to-aws?mode=git_repos"
|
||||
aws s3 ls s3://nomadkaraoke-backup/git-repos/ --recursive | head
|
||||
```
|
||||
|
||||
If the PAT is missing/expired the git-repo step logs a warning and skips; the
|
||||
freshness monitor then flags `git-repos/` as stale within ~36h.
|
||||
freshness monitor then flags `git-repos/manifest.json` as stale within ~8 days.
|
||||
|
||||
## Decrypting the secrets backup
|
||||
|
||||
@@ -449,14 +462,15 @@ export AWS_DEFAULT_REGION=us-east-1
|
||||
|
||||
## Backup freshness monitor
|
||||
|
||||
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
|
||||
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/manifest.json` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
|
||||
|
||||
Per-prefix limits reflect each prefix's **S3 (off-site)** cadence, which is not the same as its GCS-staging cadence:
|
||||
|
||||
| Prefix | S3 upload cadence | Monitor limit |
|
||||
|--------|-------------------|---------------|
|
||||
| `gcs/job-files/`, `secrets/`, `git-repos/` | nightly | 36h |
|
||||
| `gcs/job-files/`, `secrets/` | nightly | 36h |
|
||||
| `firestore/`, `bigquery/daily-refresh/` | weekly (Sundays) | 192h (≈8 days) |
|
||||
| `git-repos/manifest.json` | weekly (Sundays), incremental | 192h (≈8 days) + manifest must show 0 bundle errors |
|
||||
|
||||
Firestore exports to GCS staging nightly (24h local restore point) but only ships to S3 weekly to cut cross-cloud egress (see `backup_to_aws/main.py` → `firestore_to_s3_today`). The monitor only sees the S3 copy, so its Firestore limit must allow a full week — using the 36h nightly figure caused a false "DR backup is stale" alert every Tue–Sat (fixed 2026-06-18).
|
||||
|
||||
@@ -534,3 +548,21 @@ re-import). The raw source files are not.
|
||||
| S3 data transfer out to GCP | ~$0.09/GB |
|
||||
| Full Spotify dataset retrieval + transfer (~100 GB) | ~$25 total |
|
||||
| Full GCS job-files egress (~150 GB) | ~$14 |
|
||||
|
||||
## Incident: S3 overwrites silently failing 2026-09-14 → 2026-09-26
|
||||
|
||||
The incremental S3 upload (#997) checked "already in S3?" with `HeadObject`,
|
||||
but the `backup-writer` IAM user only has `s3:ListBucket` + `s3:PutObject`
|
||||
(no `s3:GetObject`). S3 answers HEAD on a *missing* key with 404 (fine — the
|
||||
file uploaded) but on an *existing* key with **403**, so every **overwrite**
|
||||
errored: git bundles + `manifest.json` stopped updating after 09-15 (the
|
||||
freshness monitor failed daily on `git-repos/`), and re-written job files
|
||||
(e.g. `lyrics/corrections_updated.json`, `karaoke.lrc`, re-rendered screens)
|
||||
kept their older S3 copy. New keys (dated secrets/Firestore exports, new job
|
||||
files) were unaffected. Fixed 2026-09-26 by switching the existence check to
|
||||
`ListObjectsV2` (`s3_upload._list_s3_sizes`); a manual `?mode=git_repos` run
|
||||
refreshed all changed bundles the same day. Re-written job files from
|
||||
09-14..09-19 aged out of the 7-day staging lifecycle before the fix, so S3
|
||||
holds their previous version (primary copies in GCS are intact; not
|
||||
backfilled). Lesson: the IAM user is intentionally write+list only — test new
|
||||
S3 calls against it, not an admin credential.
|
||||
@@ -164,6 +164,17 @@ Hard-won insights for the next person debugging GCE image builds:
|
||||
./run.sh ...`, so the smoke test must verify tools-as-runner. The v2 smoke
|
||||
test uses startup-script + `sudo -iu runner` for this.
|
||||
|
||||
## Which jobs use self-hosted runners (2026-09-26)
|
||||
|
||||
karaoke-gen's test/package jobs (package/backend unit + integration + emulator
|
||||
tests, package builds, full frontend E2E) moved to **GitHub-hosted
|
||||
`ubuntu-latest`** runners — free for this public repo, and they never needed GCP
|
||||
credentials. That removed ~390 `gha-general-*` VMs/month. Only jobs that need
|
||||
the GCE runners still request them: `deploy-backend` (`docker-build` label —
|
||||
Docker image builds, same-region Artifact Registry) and the GPU integration
|
||||
tests in python-audio-separator (`gpu`). No workflow currently requests the
|
||||
plain general label; the `gha-runner-general` family is kept as a fallback.
|
||||
|
||||
## High-level architecture
|
||||
|
||||
```
|
||||
@@ -242,7 +253,8 @@ GitHub schedules onto any runner whose labels are a superset of the job's.
|
||||
Each image is tagged `gha-runner-<variant>-<YYYYMMDD-HHMMSS>` and joined to the
|
||||
matching image family. The dispatcher always selects from the family, so the
|
||||
newest non-deprecated image wins automatically. The build workflow keeps the
|
||||
newest 2 images per family and **deletes** the rest (deprecated images still bill
|
||||
newest image per family (`KEEP_IMAGES_PER_FAMILY: 1` since 2026-09-26 — GPU/windows
|
||||
images are 15-21 GiB each) and **deletes** the rest (deprecated images still bill
|
||||
for storage; images that an existing disk was created from are never deleted).
|
||||
Until 2026-09-26 this step used an invalid gcloud filter and silently pruned
|
||||
nothing — 31 runner images (~360 GB archived, ~$18/mo) had accumulated; they were pruned by hand to
|
||||
|
||||
@@ -80,11 +80,11 @@ The `concurrency=1` setting may have been added deliberately for performance rea
|
||||
### 🔍 GCE Encoding Worker
|
||||
|
||||
**Current State (updated v0.195.0 — the opportunities below are largely SHIPPED):**
|
||||
- No longer a single 24/7 VM. It is a pool of **on-demand** VMs: a c4d-highcpu-32
|
||||
blue-green primary pair + 8 stopped fallbacks across 6 machine families
|
||||
(c4d/c4/n4d/c2d/n2d/n2) for stockout resilience.
|
||||
- **Idle auto-shutdown is live** (JIT start on the lyrics-review page; a Cloud
|
||||
Function stops idle VMs after 15 min). When idle, cost is just boot disks
|
||||
- No longer a single 24/7 VM. Since 2026-09-26 it is 3 VMs: a **Spot**
|
||||
c4d-highcpu-16 blue-green pair + 1 stopped on-demand c2d-highcpu-16 fallback
|
||||
(was 10 × 32-vCPU on-demand VMs — see docs/archive/2026-09-26-encoding-cost-cuts.md).
|
||||
- **Idle auto-shutdown is live** (JIT start + heartbeat on the lyrics-review page;
|
||||
a Cloud Function checks every 2 min and stops idle VMs after 5 min). When idle, cost is just boot disks
|
||||
(50 GB since 2026-09-26, ~$4-5/VM/mo; was 100 GB / ~$10 — see
|
||||
docs/archive/2026-09-26-encoding-worker-disk-cost.md); compute is billed only while encoding — so the historical
|
||||
"~$700/mo running 24/7" no longer applies.
|
||||
@@ -171,3 +171,19 @@ If all optimizations implemented:
|
||||
- **2026-02-10:** Initial analysis and GitHub runner optimization implemented
|
||||
- **2026-02-10:** Runners reduced from 20 → 3 with auto-scaling, saving $1,390/month
|
||||
- **2026-03-03:** Added dedicated on-demand build runner (`e2-standard-8`) for Docker deploys to prevent spot preemption during builds (~$0.27/hr only when deploying)
|
||||
|
||||
## 2026-09-26 cuts (post-credit-expiry, target: whole project < $300/mo)
|
||||
|
||||
| Change | Where | Est. saving |
|
||||
|--------|-------|-------------|
|
||||
| Deleted serverless VPC connector `cloud-run-connector` (flacfetch is off-GCP on a public URL) | `__main__.py`, `cloud_run.py`, `ci.yml` (`--clear-vpc-connector`) | ~$12/mo + Network Intelligence resource-hours |
|
||||
| `karaoke-backend` min-instances 2 → 1 (accepted: big bursts may hit a ~15s cold start) | `ci.yml` | ~$25/mo |
|
||||
| Autoclass on `karaoke-gen-storage-nomadkaraoke` (terminal NEARLINE) and `nomadkaraoke-divebar-files` (terminal ARCHIVE) | `storage.py`, `divebar_mirror.py` | ~$9–17/mo once objects cool (30d+) |
|
||||
| `nomadkaraoke-data` (raw Spotify ETL, 158 GiB) → ARCHIVE after 30d | karaoke-decide `infrastructure/__main__.py` | ~$3/mo |
|
||||
| DR git bundles weekly + incremental (only repos pushed since last S3 upload) | `functions/backup_to_aws/` | cross-cloud egress |
|
||||
| Error monitor every 15 min → hourly (lookback 60 min) | `config.py`, `backend/services/error_monitor/config.py` | Cloud Run Job + Logging API |
|
||||
| Firestore PITR disabled (nightly export remains) | `database.py` | PITR storage |
|
||||
| `recover-stuck-downloads` / `retry-pending-render-jobs` every 5 → 10 min | `__main__.py` | ~half their Firestore reads |
|
||||
|
||||
Kept: the `audio-separator` Cloud Run GPU service (still used by external remote-CLI
|
||||
clients; already scale-to-zero).
|
||||
+18
-1
@@ -645,7 +645,7 @@ When two sequential human review steps can be combined into one, do it. We origi
|
||||
- 6 GCE encoding workers: 2 primaries in `us-central1-c` (blue-green, `c4d-highcpu-32`) + 2 `c4d` capacity fallbacks in `us-central1-a`/`-b` + 2 `n2-highcpu-32` fallbacks in `us-central1-c`/`-f`. All idle by default; started on demand.
|
||||
- `EncodingWorkerCandidate` list iterated in `ensure_any_running` — primary first, fallbacks in declared order. Capacity errors fall through to next candidate; non-capacity start errors also fall through (broadened in PR #750).
|
||||
- New `RENDER_PENDING_CAPACITY` job state for transient infra failures — different from `FAILED` (which is for unrecoverable bugs).
|
||||
- Cloud Scheduler fires `/api/internal/retry-pending-render-jobs` every 5 min; 24h hard timeout per job.
|
||||
- Cloud Scheduler fires `/api/internal/retry-pending-render-jobs` every 10 min; 24h hard timeout per job.
|
||||
- `EncodingWorkerConfig.active_url` returns the override URL when set, else primary. `_get_worker_url()` consults this with a 30s TTL cache.
|
||||
- Both Cloud Run service AND Cloud Run Job (video-encoding-job) need `ENCODING_WORKER_FALLBACK_VMS` env — they each instantiate their own `EncodingService`.
|
||||
|
||||
@@ -2077,3 +2077,20 @@ fallbacks — go through `JobManager.start_job_processing`, which ignored it, so
|
||||
users never saw the audio editor. `start_job_processing` now parks such jobs via the
|
||||
shared `enter_audio_edit` helper. Any new "audio just arrived" path must go through one
|
||||
of these two gates.
|
||||
|
||||
## GCS Autoclass bumps `updated`; S3 HEAD needs GetObject (2026-09-26 cost cuts)
|
||||
|
||||
- **Autoclass / lifecycle storage-class transitions change an object's `updated`
|
||||
timestamp** (it tracks any metadata change). Anything that detects "changed since
|
||||
last run" via `blob.updated` will treat every cooled object as new — and reading it
|
||||
pulls it straight back to Standard, defeating Autoclass. Use `time_created` (the
|
||||
current generation's creation time) for content-change detection. The DR
|
||||
`gcs_sync.py` was switched before Autoclass was enabled on the job-files bucket.
|
||||
- **S3 HEAD on an existing key returns 403 without `s3:GetObject`** (404 only for
|
||||
missing keys when you have `s3:ListBucket`). The write-only `backup-writer` IAM user
|
||||
therefore failed every *overwrite* for 12 days after #997 added a HEAD-based
|
||||
"already uploaded?" check. Use `ListObjectsV2` for existence/size checks with that
|
||||
user, and test new S3 calls against the real least-privilege credential.
|
||||
- **Removing a serverless VPC connector from a gcloud-deployed Cloud Run service needs
|
||||
`--clear-vpc-connector`**: just dropping `--vpc-connector` from `gcloud run deploy`
|
||||
keeps the existing setting. Detach every service/job before deleting the connector.
|
||||
+2
-1
@@ -44,7 +44,7 @@
|
||||
| **Review reminder & auto-expiry** | Working (24h reminder, 48h cancel + refund) |
|
||||
| **i18n / Multilingual (frontend)** | Working (next-intl, en/es/de, 1062 strings, [locale] routing) |
|
||||
| **Referral system** | Working (referral links with configurable discounts, 20% cash kickback via Stripe Connect, auto-payout at $20) |
|
||||
| **Error monitor** | New (Cloud Run Job every 15 min — log collection, normalization, LLM dedup/grouping, Discord alerts, auto-resolution, daily digest) |
|
||||
| **Error monitor** | New (Cloud Run Job hourly — log collection, normalization, LLM dedup/grouping, Discord alerts, auto-resolution, daily digest) |
|
||||
| **Edge security (Cloudflare)** | Working (api.nomadkaraoke.com proxied — WAF + rate limit + origin lock enforced; 2026-07-20) |
|
||||
|
||||
## Known Issues
|
||||
@@ -57,6 +57,7 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Vocal waveforms for own-instrumental jobs** (2026-09-26, v0.244.1): jobs with a user-supplied instrumental skip GPU separation, so the lyrics review Waveforms mode had no vocals stem (`/vocals-peaks` 404). The lyrics worker now derives approximate vocals on CPU, alongside transcription: it aligns the instrumental to the mix by FFT cross-correlation (±2s), fits a gain by least squares, and subtracts (`backend/services/derived_vocals.py`, numpy + ffmpeg, a few seconds). The result is stored as `stems.vocals_derived` (mono 22.05 kHz FLAC), which `vocals_stem_path` uses only as a last resort, so screens pre-computes the peaks as usual. It's waveform-only: never shipped as a deliverable stem, never downloaded by the remote CLI, and never used for the original-vocals guide. Safeguards: alignment correlates a fixed 60s excerpt (memory doesn't scale with track length); inputs over 20 min are skipped; ffmpeg calls time out; the handoff waits at most 3 min; nothing is registered when the instrumental didn't cancel (residual > 85% of the mix), since a full-mix envelope would mislead timing edits. Best-effort: any failure logs and the job proceeds.
|
||||
- **User-instrumental renders: WAV/M4A/OGG/AAC no longer fail** (2026-09-26, v0.243.1): the orchestrator render path sent only `instrumental_selection="custom"` to the GCE encoder, whose custom lookup accepted just `*custom_instrumental*.{flac,mp3}`. Tenant MP3s worked, but a `.wav` user instrumental failed with "No instrumental audio found" (job 3ea34552). The orchestrator now passes `existing_instrumental` (the encoder downloads it and matches any extension), and the custom lookup (`resolve_instrumental` in `gce_encoding/main.py`) accepts any audio extension.
|
||||
- **Crash reports carry diagnostics + breadcrumbs** (2026-09-26, v0.243.1): A Firefox "Uncaught out of memory" froze a tab mid-upload, and the alert was useless. The browser gave no Error object, so the reporter's own stack became the pattern, and that stack pushed URL/UA/build out of Discord's view (`extra` was never kept). Now `lib/diagnostics.ts` keeps a 30-entry breadcrumb trail (navigation, clicks, upload phases, errors) and snapshots page age, DOM/canvas/audio counts, live blob URLs and the JS heap (Chromium) into every report. Errors without an Error object are flagged `synthetic` (stack dropped, location kept) and group by message. One page load can send at most 20 reports. The alert sample now lists message → location → URL/UA/build → Diag → Trail → trimmed stack, and the full `extra` is logged as `client_extra` on `frontend_crash_reported`.
|
||||
- **Unified browser upload flow + bring-your-own instrumental** (2026-09-26, v0.243.0): Two invisible upload failures on the same song. Job 8729f19a: the job was created and charged, then the browser upload was abandoned; the only UI hint was the "Creating..." button text and the card already said "Setting up", so it sat `pending` forever. Job 2d0c1ae0: a 44 MB instrumental upload on the review screen was a multipart POST through Cloud Run (32 MiB cap) and failed silently. Now every user upload (guided job creation, tenant single job, instrumental review) goes through one shared layer: `lib/upload.ts` (signed-URL PUT with progress, multi-file aggregate progress, client-side duration pre-check), `hooks/useUploadTask.ts` (progress state + `beforeunload` guard; tenant bulk uses the guard) and `components/upload/UploadProgressModal.tsx` (a modal that can't be dismissed, showing progress, speed and ETA). The guided flow always uses the signed-URL path, which fixed `requires_audio_edit` being silently dropped for 25MB+ uploads. Private upload jobs can attach the user's own instrumental (`existing_instrumental`), which skips separation and instrumental review. Instrumental review uploads go direct to GCS (`instrumental-upload-url` / `instrumental-upload-complete`), and the review now plays the upload via the returned signed `audio_url` (the old `/audio-stream` URL had no route). Backend: `state_data.awaiting_upload` → "Waiting for upload" label; the hourly stale-review run cancels + refunds jobs still awaiting upload after 6h (24h if some files landed; tenant bulk exempt); a failed browser upload cancels its own job immediately; `uploads-complete` checks ownership and cancels + refunds on an instrumental duration mismatch. See [archive/2026-09-26-unified-upload-flow-plan.md](archive/2026-09-26-unified-upload-flow-plan.md).
|
||||
|
||||
+1
-1
@@ -818,7 +818,7 @@ A change tagged critical-path requires, before it enforces new behavior:
|
||||
- A **composed integration test** of the affected seam (producer + consumer, real, with
|
||||
only the external boundary mocked) — see the New Guard checklist item 5.
|
||||
- **Shadow-first** rollout for any new enforcement (checklist item 4).
|
||||
- A **post-deploy canary / real-job verification** before the change is trusted at 100%
|
||||
- A **real-job verification in production** (manual, or the daily E2E) before the change is trusted at 100%
|
||||
(a fresh happy-path job plus, where relevant, an admin-reset + retry to exercise the
|
||||
recovery path).
|
||||
|
||||
|
||||
+14
-17
@@ -63,7 +63,7 @@ defense-in-depth beneath the signing-free review path.
|
||||
## Fast rollback (bad backend deploy)
|
||||
|
||||
**When to use:** a merge-to-main deploy shipped a bad backend revision — the
|
||||
post-deploy canary failed, the error monitor/Discord is alerting, or you can see
|
||||
daily E2E failed, the error monitor/Discord is alerting, or you can see
|
||||
failing jobs/5xx in production — and you want to get back to the last known-good
|
||||
state *now* rather than wait for a forward fix to build and deploy.
|
||||
|
||||
@@ -104,7 +104,7 @@ scripts/rollback.sh --image-version v0.222.2 --jobs-only
|
||||
- After rollback, confirm the serving version:
|
||||
`curl -s https://api.nomadkaraoke.com/api/health/detailed | jq .version`.
|
||||
- This is the manual counterpart to CI's automatic service canary: a failed
|
||||
post-deploy canary leaves the *service* on the prior revision automatically
|
||||
candidate-revision smoke leaves the *service* on the prior revision automatically
|
||||
(the new revision is deployed `--no-traffic`), but the **jobs** have no
|
||||
auto-rollback — if a bad deploy reached the jobs, re-pin them with this script.
|
||||
|
||||
@@ -127,9 +127,9 @@ runbook: **[docs/PYPI-STORAGE-PRUNE.md](PYPI-STORAGE-PRUNE.md)**.
|
||||
|
||||
## Job stuck at `downloading_audio` status
|
||||
|
||||
**Cause:** Before v0.130.0, audio downloads ran as FastAPI BackgroundTasks. Cloud Run would terminate "idle" instances mid-download. Since v0.130.0, downloads use a Cloud Run Job (`audio-download-job`) and a Cloud Scheduler recovery job runs every 5 minutes to fail stuck downloads automatically.
|
||||
**Cause:** Before v0.130.0, audio downloads ran as FastAPI BackgroundTasks. Cloud Run would terminate "idle" instances mid-download. Since v0.130.0, downloads use a Cloud Run Job (`audio-download-job`) and a Cloud Scheduler recovery job runs every 10 minutes (5 before 2026-09-26) to fail stuck downloads automatically.
|
||||
|
||||
**Auto-recovery:** The `recover-stuck-downloads` scheduler (`/api/internal/recover-stuck-jobs`, every 5 min) detects jobs stuck in `downloading_audio` for >10 minutes and, since v0.192.3:
|
||||
**Auto-recovery:** The `recover-stuck-downloads` scheduler (`/api/internal/recover-stuck-jobs`, every 10 min) detects jobs stuck in `downloading_audio` for >10 minutes and, since v0.192.3:
|
||||
- **Torrent sources (RED/OPS)** → parks the job in `download_pending_retry` and keeps re-attempting the download for up to **24 hours** (handles rare tracks with few/intermittent seeders and transient tracker outages), then fails permanently with a clear message. No manual action needed. See `download_pending_retry` below.
|
||||
- **Other sources (YouTube/Spotify/URL)** → fails the job (deterministic); use the admin retry button to re-attempt.
|
||||
|
||||
@@ -404,7 +404,7 @@ gcloud compute instances describe encoding-worker-a \
|
||||
|
||||
**Cause:** The render worker started (VM up, rendering underway) then died mid-render — Cloud Run instance recycle / SIGKILL / OOM / lost GCE VM — without unregistering. `updated_at` stops advancing. Before v0.192.3 nothing recovered this: the capacity-retry cron only looks at `render_pending_capacity`, `recover-stuck-jobs` only looked at `downloading_audio`, and the render Cloud Task has finite attempts.
|
||||
|
||||
**Auto-recovery (v0.192.3+):** `recover-stuck-jobs` (every 5 min) now flags a job in `rendering_video` with no progress for **>45 min** (`rendering_video_stuck`) and re-parks it into `render_pending_capacity`, so the existing `retry-pending-render-jobs` cron resets it to `review_complete` and re-renders (same 24h ceiling). No manual action needed.
|
||||
**Auto-recovery (v0.192.3+):** `recover-stuck-jobs` (every 10 min) now flags a job in `rendering_video` with no progress for **>45 min** (`rendering_video_stuck`) and re-parks it into `render_pending_capacity`, so the existing `retry-pending-render-jobs` cron resets it to `review_complete` and re-renders (same 24h ceiling). No manual action needed.
|
||||
|
||||
**Root-cause fix (v0.224.0+):** the dominant cause of this state was **backend deploys**: the render worker ran as a FastAPI BackgroundTask on the Cloud Run *service*, and every deploy rollout that landed mid-render SIGKILLed it ~10s after SIGTERM (the lifespan "park on shutdown" hook never runs in that scenario — uvicorn waits for background tasks *before* running lifespan shutdown, so it dies waiting; incident 2026-09-13, job `41e06b90`, tenant-E2E run #107). Since v0.224.0 the render worker runs as a **Cloud Run Job** (`video-encoding-job` with a `render_video_worker` args override, flag `USE_CLOUD_RUN_JOBS_FOR_RENDER`), which runs to completion regardless of service deploys — same fix the video worker got in 2026-03 (`USE_CLOUD_RUN_JOBS_FOR_VIDEO`). The 45-min sweep remains as the safety net for the remaining causes (job execution crash/OOM/timeout, lost GCE VM). Rollback: remove `USE_CLOUD_RUN_JOBS_FOR_RENDER=true` from the service env to fall back to the legacy Cloud Tasks path.
|
||||
|
||||
@@ -436,9 +436,11 @@ gcloud compute instances describe encoding-worker-a \
|
||||
|
||||
**Symptoms:** Job status is `render_pending_capacity` (introduced 2026-05-05). User-facing message says *"Encoding capacity is temporarily unavailable. Your job will retry automatically — no action needed."* (As of v0.192.3 a mid-render stall can also land here — see "orphaned render" above.)
|
||||
|
||||
**Background — what this state means:** GCE returned `ZONE_RESOURCE_POOL_EXHAUSTED` or transient `503 SERVICE_UNAVAILABLE` from `compute.instances.start` on every encoding-worker VM. The render worker parks the job in `RENDER_PENDING_CAPACITY` instead of failing it; Cloud Scheduler retries it every 5 min via `/api/internal/retry-pending-render-jobs`. Hard timeout is 24 hours (then transitions to `failed` with a clear permanent-failure message).
|
||||
**Background — what this state means:** GCE returned `ZONE_RESOURCE_POOL_EXHAUSTED` or transient `503 SERVICE_UNAVAILABLE` from `compute.instances.start` on every encoding-worker VM. The render worker parks the job in `RENDER_PENDING_CAPACITY` instead of failing it; Cloud Scheduler retries it every 10 min via `/api/internal/retry-pending-render-jobs`. Hard timeout is 24 hours (then transitions to `failed` with a clear permanent-failure message).
|
||||
|
||||
The fallback fleet is diversified across **6 machine families** (broadened to the full pool in v0.195.0): `c4d-highcpu-32` primaries (`encoding-worker-a`/`-b`) in `us-central1-c`, plus 8 stopped fallbacks — `c4d` (`-fallback-a`/`-b`, zones a/b), `n2` (`-n2c`/`-n2f`, zones c/f), `c4` (`-c4a`, zone a), `n4d` (`-n4db`, zone b), `c2d` (`-c2df`, zone f), `n2d` (`-n2da`, zone a). Candidates are tried **fastest-first with a 15-min capacity cooldown** (a family that stocks out is demoted, then re-probed) — see `backend/services/encoding_worker_preference.py`. A single-family region-wide stockout (which took out c4d a/b/c at once on 2026-08-12) now still finds capacity in the 5 other families. If you see EVERY family return stockout, that's a genuinely severe regional event — wait, or add a cross-region fallback. NOTE: creating a *new* fallback VM (or re-creating a deleted one) still needs a one-time boot allocation, so a deep enough crunch can even block provisioning — a `pulumi up` may show the missing VM as "to create / errored" until capacity returns.
|
||||
Since 2026-09-26 the fleet is 3 VMs: **Spot** `c4d-highcpu-16` primaries (`encoding-worker-a`/`-b`) in `us-central1-c`, plus ONE stopped on-demand fallback `encoding-worker-fallback-c2df` (`c2d-highcpu-16`, `us-central1-f`). Candidates are tried **fastest-first with a 15-min capacity cooldown** — see `backend/services/encoding_worker_preference.py`. If both the Spot pair and the c2d fallback return stockout, that's a genuinely severe regional event — wait, or (re-)add a fallback in another family/zone to `EncodingWorkerConfig.FALLBACKS` **and** the `encoding-worker-fallback-vms` secret (the 2026-08-15 pool had 8 fallbacks across 6 families). NOTE: creating a *new* fallback VM needs a one-time boot allocation, so a deep enough crunch can even block provisioning.
|
||||
|
||||
**Spot preemption mid-encode** is expected occasionally: the backend sees the pinned worker VM is TERMINATED/STOPPING, logs `Encoding worker VM stopped mid-job (... ) — likely Spot preemption`, and resubmits the encode as `<job>_retry_<hex>` (up to `ENCODING_RESUBMIT_MAX`, default 2). Repeated preemptions → the job fails with the lost-job error; check `gcloud compute operations list --filter="operationType=compute.instances.preempted"`.
|
||||
|
||||
**Related symptom — preview 524 / "NetworkError":** the same capacity exhaustion also makes `POST /api/review/{id}/preview-video` fall back to slow local encoding (~130–160 s), which exceeds Cloudflare's ~100 s edge timeout → the browser shows a **524** or Firefox *"NetworkError when attempting to fetch resource"* even though the backend returns 200. If a user reports the review preview failing, check for a concurrent stockout; the already-rendered preview mp4 (if any) is fetchable via `GET /api/review/{id}/preview-video/{hash}` (302 → signed GCS URL) with a Bearer admin token. Completing the review does **not** require the preview.
|
||||
|
||||
@@ -452,7 +454,7 @@ print((d.get('state_data') or {}).get('render_pending_capacity'))
|
||||
"
|
||||
```
|
||||
|
||||
**Force an immediate retry** (Cloud Scheduler runs every 5 min, but you can poke it manually):
|
||||
**Force an immediate retry** (Cloud Scheduler runs every 10 min, but you can poke it manually):
|
||||
```bash
|
||||
ADMIN_TOKEN=$(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1)
|
||||
curl -X POST https://api.nomadkaraoke.com/api/internal/retry-pending-render-jobs \
|
||||
@@ -466,18 +468,13 @@ gcloud logging read 'protoPayload.methodName:"instances.start" AND "ZONE_RESOURC
|
||||
--project=nomadkaraoke --freshness=30m --limit=5 \
|
||||
--format='value(timestamp, protoPayload.resourceName)'
|
||||
|
||||
# Try starting a fallback in each of the 6 families; if ALL refuse, it's severe — wait.
|
||||
# Try starting each worker; if ALL refuse, it's severe — wait.
|
||||
# Synchronous (no --async) so the start op surfaces stockout inline, and we capture
|
||||
# gcloud's own exit status rather than piping (a pipe would return sed's status).
|
||||
for VM_ZONE in \
|
||||
"encoding-worker-fallback-a:us-central1-a" \
|
||||
"encoding-worker-fallback-b:us-central1-b" \
|
||||
"encoding-worker-fallback-n2c:us-central1-c" \
|
||||
"encoding-worker-fallback-n2f:us-central1-f" \
|
||||
"encoding-worker-fallback-c4a:us-central1-a" \
|
||||
"encoding-worker-fallback-n4db:us-central1-b" \
|
||||
"encoding-worker-fallback-c2df:us-central1-f" \
|
||||
"encoding-worker-fallback-n2da:us-central1-a"; do
|
||||
"encoding-worker-a:us-central1-c" \
|
||||
"encoding-worker-b:us-central1-c" \
|
||||
"encoding-worker-fallback-c2df:us-central1-f"; do
|
||||
VM="${VM_ZONE%%:*}"; ZONE="${VM_ZONE##*:}"
|
||||
if OUT=$(gcloud compute instances start "$VM" --zone="$ZONE" --project=nomadkaraoke 2>&1); then
|
||||
echo "$VM: OK (started — remember to stop it)"
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# Encoding-worker cost cuts (2026-09-26)
|
||||
|
||||
Part of the "whole GCP project under $300/mo" push (workspace plan:
|
||||
`docs/archive/2026-09-26-gcp-under-300-plan.md`). The encoding VMs were costing
|
||||
~$300/mo for ~5-20 jobs/day. Andrew approved all of these, including the speed
|
||||
trade-offs.
|
||||
|
||||
## What changed
|
||||
|
||||
| | Before | After |
|
||||
|---|---|---|
|
||||
| Primary pair `encoding-worker-a`/`-b` | c4d-highcpu-32, on-demand | **c4d-highcpu-16, Spot** (STOP on preemption) |
|
||||
| Fallbacks | 8 stopped VMs across 6 families (+8 static IPs, 8 boot disks) | **1**: `encoding-worker-fallback-c2df`, c2d-highcpu-16, **on-demand**, us-central1-f |
|
||||
| Fleet | 10 VMs | 3 VMs |
|
||||
| Idle shutdown | 15 min, checked every 5 min | **5 min, checked every 2 min** |
|
||||
| CI worker blue-green deploy | every push to main (~5x/day, boots a green + test encode) | only when `infrastructure/encoding-worker/worker_code_paths.txt` paths changed since the serving version; manual override via workflow_dispatch input `force_encoding_worker_deploy` |
|
||||
| Nomad Dropbox upload | whole output folder | minus the lossless 4K **MP4** (`DROPBOX_SKIP_OUTPUT_SUFFIXES`); tenant folders unchanged |
|
||||
|
||||
Dropped from scope by Andrew mid-task: moving review previews off the VMs
|
||||
(`USE_GCE_PREVIEW_ENCODING` stays `true`) and removing the review-page warmup. The
|
||||
warmup is deliberate (VM warm for preview + final render), so instead the review
|
||||
page now heartbeats every 2 min while the tab is visible and was used in the last
|
||||
15 min (`frontend/lib/lyrics-review/hooks/useEncodingWorkerKeepAlive.ts`), keeping
|
||||
the VM inside the new 5-min idle window during a review. Previously the heartbeat
|
||||
only fired on lyric edits.
|
||||
|
||||
## How it was applied (infra)
|
||||
|
||||
- **Spot conversion without recreating the VMs.** Pulumi (pulumi-gcp 9.22.0)
|
||||
treats a `scheduling` change as *replace*; recreating a c4d VM risks a stockout
|
||||
at create time (and the VM would be gone). Instead each VM was converted in
|
||||
place while STOPPED:
|
||||
`gcloud compute instances set-scheduling <vm> --zone us-central1-c --preemptible --provisioning-model=SPOT --instance-termination-action=STOP --no-restart-on-failure --maintenance-policy=TERMINATE`,
|
||||
then `pulumi refresh --target <vm>` (state now matches the code) and a targeted
|
||||
`pulumi up` for the in-place machine-type change (`allow_stopping_for_update`).
|
||||
Note `--preemptible` is required alongside `--provisioning-model=SPOT`.
|
||||
- Fallback removal: targeted `pulumi up` deleted 7 VMs (+ their auto-delete boot
|
||||
disks) and 7 static IPs; c2df resized in place to c2d-highcpu-16.
|
||||
- `encoding-worker-fallback-vms` secret → version 6 (only c2df). The value is
|
||||
managed manually (Pulumi only creates the secret).
|
||||
- Idle function env + scheduler updated by Pulumi; `main.py` default also 5.
|
||||
|
||||
## Behaviour notes
|
||||
|
||||
- **Spot preemption mid-encode**: `EncodingService.wait_for_completion` now checks
|
||||
the pinned worker VM's status on a failed poll; if it's STOPPING/TERMINATED/etc.
|
||||
it raises `EncodingJobLostError`, so `run_with_lost_job_resubmit` resubmits the
|
||||
encode (fresh `_retry_` id; outputs overwrite the same GCS paths). Before, a
|
||||
vanished VM surfaced after ~7 min as a non-resubmitted "lost contact" failure.
|
||||
- **Idle-stop vs. an encode in flight**: the idle function's `/health active_jobs`
|
||||
counts only RUNNING jobs and `last_activity_at` used to be written only when a
|
||||
VM was started, so with a 5-min window a long encode's VM could be stopped in
|
||||
the seconds between the job finishing and the backend's next poll. The poll
|
||||
loop now refreshes `last_activity_at` at most once a minute while waiting.
|
||||
(A VM seen in STAGING/PROVISIONING after accepting a job also counts as lost.)
|
||||
- **Stale fallback entries** (a removed VM still listed in an instance's cached
|
||||
`ENCODING_WORKER_FALLBACK_VMS`) are now skipped (`NOT_FOUND` start error)
|
||||
instead of aborting the whole failover.
|
||||
- `SPEED_RANK` is keyed by machine *family* now, so the ranking survives vCPU
|
||||
resizes.
|
||||
- 16 vCPU: final encodes/renders will be slower (x264 kept ~66-78% of 32 vCPUs
|
||||
busy). RAM is ~30-32 GB — one 4K encode peaks ~18 GB and heavy jobs are
|
||||
serialized (`ENCODING_HEAVY_CONCURRENCY=1`), so no OOM risk.
|
||||
|
||||
## Dropbox lossless (item 7) — why only the MP4
|
||||
|
||||
No automated consumer reads lossless files from Dropbox (YouTube reads the local /
|
||||
GCS MKV; GDrive, the NOMAD master mirror, kjbox and the AWS backup use GCS or
|
||||
lossy files). But the lossless **MKV** is promised *in the Dropbox folder* by the
|
||||
customer completion email (`backend/services/template_service.py`,
|
||||
`backend/translations/*.json` `fileList`) and by the live Fiverr auto-reply bot
|
||||
(`fiverrbot/fiverrbot/triage/prompts.py` "What's delivered"), and B2B tenant
|
||||
VocalStar expects lossless. So the default skips only the lossless 4K MP4 (not
|
||||
promised anywhere in Dropbox) and only for Nomad's own folders. To also skip the
|
||||
MKV: update those two texts, then set
|
||||
`DROPBOX_SKIP_OUTPUT_SUFFIXES=" (Final Karaoke Lossless 4k).mp4| (Final Karaoke Lossless 4k).mkv"`
|
||||
on the `video-encoding-job` (Pulumi `infrastructure/modules/cloud_run.py`) or
|
||||
change the default in `backend/config.py`.
|
||||
|
||||
## Open risks
|
||||
|
||||
- Spot capacity for c4d in us-central1-c can disappear; then all work lands on
|
||||
the single on-demand c2d fallback (slower, and a single lane).
|
||||
- Two consecutive preemptions of the same encode exhaust `ENCODING_RESUBMIT_MAX=2`.
|
||||
- Skipped CI worker deploys mean `config/encoding-worker.primary_version` can lag
|
||||
the backend version; VMs still boot the latest wheel from GCS.
|
||||
@@ -27,7 +27,8 @@ import {
|
||||
} from '@/lib/lyrics-review/types'
|
||||
import type { EditLog, EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
|
||||
import type { InstrumentalSelectionType, LyricsReviewApiClient } from '@/lib/api'
|
||||
import { lyricsReviewApi, warmupEncodingWorker, heartbeatEncodingWorker, getAccessToken } from '@/lib/api'
|
||||
import { lyricsReviewApi, getAccessToken } from '@/lib/api'
|
||||
import { useEncodingWorkerKeepAlive } from '@/lib/lyrics-review/hooks/useEncodingWorkerKeepAlive'
|
||||
import { cn } from '@/lib/utils'
|
||||
import ReferenceView from './ReferenceView'
|
||||
import TranscriptionView from './TranscriptionView'
|
||||
@@ -492,25 +493,12 @@ export default function LyricsAnalyzer({
|
||||
setSessionRestoreOpen(true)
|
||||
}, [sessionClient])
|
||||
|
||||
// Warm up encoding worker VM when lyrics review page loads.
|
||||
// Only in cloud mode (jobId present) — the endpoint is review-auth scoped to
|
||||
// the job, and there's no cloud encoding VM to warm in local mode.
|
||||
useEffect(() => {
|
||||
if (!isReadOnly && jobId) {
|
||||
warmupEncodingWorker(jobId)
|
||||
}
|
||||
}, []) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Debounced heartbeat — keeps VM alive during active editing
|
||||
const lastHeartbeat = useRef(0)
|
||||
const sendHeartbeat = useCallback(() => {
|
||||
if (!jobId) return
|
||||
const now = Date.now()
|
||||
if (now - lastHeartbeat.current > 60_000) {
|
||||
lastHeartbeat.current = now
|
||||
heartbeatEncodingWorker(jobId)
|
||||
}
|
||||
}, [jobId])
|
||||
// Keep the encoding worker VM warm while reviewing: warmup on load, heartbeat
|
||||
// on edits AND periodically while the tab is visible and in use, so the 5-min
|
||||
// backend idle shutdown doesn't stop it under an active reviewer. Only in cloud
|
||||
// mode (jobId present) — the endpoints are review-auth scoped to the job, and
|
||||
// there's no cloud encoding VM to warm in local mode.
|
||||
const { sendHeartbeat } = useEncodingWorkerKeepAlive(jobId, !isReadOnly)
|
||||
|
||||
// Heartbeat the encoding worker as the reviewer works. Crash recovery /
|
||||
// restore now flows entirely through review sessions (server in cloud mode,
|
||||
|
||||
@@ -216,10 +216,10 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
// Allow ONE retry. Each retry creates a fresh ~15-20 min karaoke job, so we
|
||||
// don't want the prod config's default of 2 — but prod smoke tests can hit
|
||||
// genuinely transient infra (encoder cold-start, network blips), and with
|
||||
// retries:0 a single flake hard-fails and PAGES (daily E2E + the post-deploy
|
||||
// canary). One retry lets a genuine flake self-heal on a clean run while
|
||||
// capping the wasted time at a single extra attempt — a passing run never
|
||||
// retries, so there's no steady-state cost.
|
||||
// retries:0 a single flake hard-fails and PAGES (daily E2E). One retry lets
|
||||
// a genuine flake self-heal on a clean run while capping the wasted time at a
|
||||
// single extra attempt — a passing run never retries, so there's no
|
||||
// steady-state cost.
|
||||
test.describe.configure({ retries: 1 });
|
||||
|
||||
// Safety-net job tracker. The in-flow cleanup (Step 12) only runs on a fully
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import {
|
||||
useEncodingWorkerKeepAlive,
|
||||
REVIEW_HEARTBEAT_INTERVAL_MS,
|
||||
REVIEW_ACTIVE_WINDOW_MS,
|
||||
HEARTBEAT_MIN_GAP_MS,
|
||||
} from '../useEncodingWorkerKeepAlive'
|
||||
import { warmupEncodingWorker, heartbeatEncodingWorker } from '@/lib/api'
|
||||
|
||||
jest.mock('@/lib/api', () => ({
|
||||
warmupEncodingWorker: jest.fn(),
|
||||
heartbeatEncodingWorker: jest.fn(),
|
||||
}))
|
||||
|
||||
const warmup = warmupEncodingWorker as jest.Mock
|
||||
const heartbeat = heartbeatEncodingWorker as jest.Mock
|
||||
|
||||
function setVisibility(state: 'visible' | 'hidden') {
|
||||
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state })
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
}
|
||||
|
||||
describe('useEncodingWorkerKeepAlive', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
warmup.mockClear()
|
||||
heartbeat.mockClear()
|
||||
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
it('heartbeat interval stays well under the 5-minute backend idle timeout', () => {
|
||||
expect(REVIEW_HEARTBEAT_INTERVAL_MS * 2).toBeLessThanOrEqual(5 * 60_000)
|
||||
})
|
||||
|
||||
it('warms up once on mount', () => {
|
||||
renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
|
||||
expect(warmup).toHaveBeenCalledTimes(1)
|
||||
expect(warmup).toHaveBeenCalledWith('job-1')
|
||||
})
|
||||
|
||||
it('does nothing when disabled (read-only) or without a job id', () => {
|
||||
renderHook(() => useEncodingWorkerKeepAlive('job-1', false))
|
||||
renderHook(() => useEncodingWorkerKeepAlive(undefined, true))
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(REVIEW_HEARTBEAT_INTERVAL_MS * 3)
|
||||
})
|
||||
expect(warmup).not.toHaveBeenCalled()
|
||||
expect(heartbeat).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('heartbeats periodically while visible even without edits', () => {
|
||||
renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(REVIEW_HEARTBEAT_INTERVAL_MS * 3)
|
||||
})
|
||||
expect(heartbeat).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('skips periodic heartbeats while the tab is hidden', () => {
|
||||
renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
|
||||
act(() => {
|
||||
setVisibility('hidden')
|
||||
jest.advanceTimersByTime(REVIEW_HEARTBEAT_INTERVAL_MS * 3)
|
||||
})
|
||||
expect(heartbeat).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('re-warms the worker when the tab becomes visible again', () => {
|
||||
renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
|
||||
expect(warmup).toHaveBeenCalledTimes(1)
|
||||
act(() => {
|
||||
setVisibility('hidden')
|
||||
setVisibility('visible')
|
||||
})
|
||||
expect(warmup).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('stops keeping the VM alive after the reviewer goes inactive', () => {
|
||||
renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(REVIEW_ACTIVE_WINDOW_MS + REVIEW_HEARTBEAT_INTERVAL_MS * 3)
|
||||
})
|
||||
const callsWhileIdle = heartbeat.mock.calls.length
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(REVIEW_HEARTBEAT_INTERVAL_MS * 3)
|
||||
})
|
||||
expect(heartbeat.mock.calls.length).toBe(callsWhileIdle)
|
||||
|
||||
// Any interaction resumes the keep-alive.
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event('pointerdown'))
|
||||
jest.advanceTimersByTime(REVIEW_HEARTBEAT_INTERVAL_MS)
|
||||
})
|
||||
expect(heartbeat.mock.calls.length).toBe(callsWhileIdle + 1)
|
||||
})
|
||||
|
||||
it('debounces edit-triggered heartbeats', () => {
|
||||
const { result } = renderHook(() => useEncodingWorkerKeepAlive('job-1', true))
|
||||
act(() => {
|
||||
result.current.sendHeartbeat()
|
||||
result.current.sendHeartbeat()
|
||||
})
|
||||
expect(heartbeat).toHaveBeenCalledTimes(1)
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(HEARTBEAT_MIN_GAP_MS + 1)
|
||||
result.current.sendHeartbeat()
|
||||
})
|
||||
expect(heartbeat).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import { warmupEncodingWorker, heartbeatEncodingWorker } from '@/lib/api'
|
||||
|
||||
/**
|
||||
* Keeps the encoding worker VM warm while a reviewer is on the lyrics-review page,
|
||||
* so the preview video and the final render don't pay a VM cold start.
|
||||
*
|
||||
* The backend idle-shutdown stops the serving VM once `last_activity_at` is older
|
||||
* than IDLE_TIMEOUT_MINUTES (5 min since 2026-09-26, checked every 2 min — see
|
||||
* infrastructure/config.py EncodingWorkerConfig). Previously the only heartbeat
|
||||
* fired on lyric *edits*, so a reviewer reading or listening without editing would
|
||||
* let the VM stop. Now:
|
||||
* - warmup once on mount (starts the VM if stopped),
|
||||
* - heartbeat on edits (debounced to one per HEARTBEAT_MIN_GAP_MS),
|
||||
* - heartbeat every REVIEW_HEARTBEAT_INTERVAL_MS while the tab is visible AND
|
||||
* the reviewer interacted within REVIEW_ACTIVE_WINDOW_MS (an abandoned tab
|
||||
* stops keeping the VM alive),
|
||||
* - warmup again when the tab becomes visible after being hidden (the VM may
|
||||
* have idled out meanwhile).
|
||||
*/
|
||||
|
||||
// Must stay comfortably below the backend idle timeout (5 min) — asserted by
|
||||
// infrastructure/test_encoding_worker_config.py::test_idle_shutdown_is_fast_but_outlives_review_heartbeat.
|
||||
export const REVIEW_HEARTBEAT_INTERVAL_MS = 2 * 60_000
|
||||
export const HEARTBEAT_MIN_GAP_MS = 60_000
|
||||
// Keep-alive stops this long after the last interaction (≈ the old 15-min idle window).
|
||||
export const REVIEW_ACTIVE_WINDOW_MS = 15 * 60_000
|
||||
|
||||
const INTERACTION_EVENTS = ['pointerdown', 'keydown', 'wheel', 'touchstart'] as const
|
||||
|
||||
export function useEncodingWorkerKeepAlive(jobId: string | null | undefined, enabled: boolean) {
|
||||
const lastHeartbeat = useRef(0)
|
||||
const lastInteraction = useRef(Date.now())
|
||||
const active = enabled && !!jobId
|
||||
|
||||
const sendHeartbeat = useCallback(() => {
|
||||
if (!active || !jobId) return
|
||||
lastInteraction.current = Date.now()
|
||||
const now = Date.now()
|
||||
if (now - lastHeartbeat.current > HEARTBEAT_MIN_GAP_MS) {
|
||||
lastHeartbeat.current = now
|
||||
heartbeatEncodingWorker(jobId)
|
||||
}
|
||||
}, [active, jobId])
|
||||
|
||||
// Warm up once when the review page loads (cloud mode only).
|
||||
useEffect(() => {
|
||||
if (active && jobId) warmupEncodingWorker(jobId)
|
||||
}, []) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || !jobId) return
|
||||
|
||||
const markInteraction = () => {
|
||||
lastInteraction.current = Date.now()
|
||||
}
|
||||
INTERACTION_EVENTS.forEach((evt) => window.addEventListener(evt, markInteraction, { passive: true }))
|
||||
|
||||
const tick = () => {
|
||||
if (document.visibilityState !== 'visible') return
|
||||
if (Date.now() - lastInteraction.current > REVIEW_ACTIVE_WINDOW_MS) return
|
||||
lastHeartbeat.current = Date.now()
|
||||
heartbeatEncodingWorker(jobId)
|
||||
}
|
||||
const intervalId = setInterval(tick, REVIEW_HEARTBEAT_INTERVAL_MS)
|
||||
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState !== 'visible') return
|
||||
lastInteraction.current = Date.now()
|
||||
lastHeartbeat.current = Date.now()
|
||||
// Starts the VM if it idled out while the tab was hidden; otherwise just
|
||||
// refreshes last_activity_at.
|
||||
warmupEncodingWorker(jobId)
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
|
||||
return () => {
|
||||
INTERACTION_EVENTS.forEach((evt) => window.removeEventListener(evt, markInteraction))
|
||||
clearInterval(intervalId)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
}
|
||||
}, [active, jobId])
|
||||
|
||||
return { sendHeartbeat }
|
||||
}
|
||||
+28
-29
@@ -35,9 +35,10 @@ from config import (
|
||||
NUM_GITHUB_RUNNERS,
|
||||
MachineTypes,
|
||||
DiskSizes,
|
||||
EncodingWorkerConfig,
|
||||
)
|
||||
from modules import database, storage as storage_module, artifact_registry, secrets
|
||||
from modules import cloud_tasks, cloud_run, monitoring, networking, runner_manager
|
||||
from modules import cloud_tasks, cloud_run, monitoring, runner_manager
|
||||
from modules import divebar_mirror, kn_data_sync, divebar_lookup, backup
|
||||
from modules import audio_separator_service
|
||||
from modules import edge_security
|
||||
@@ -68,9 +69,9 @@ all_secrets = secrets.create_secrets()
|
||||
queues = cloud_tasks.create_queues()
|
||||
|
||||
# ==================== Networking ====================
|
||||
# VPC connector for Cloud Run to access internal resources (e.g., flacfetch VM)
|
||||
vpc_access_api = networking.enable_vpc_access_api()
|
||||
vpc_connector = networking.create_vpc_connector(vpc_access_api)
|
||||
# The serverless VPC connector (cloud-run-connector) was removed 2026-09-26:
|
||||
# it only existed to reach the old flacfetch GCE VM's internal IP, and flacfetch
|
||||
# now runs off-GCP behind a public HTTPS URL. All backend egress is public.
|
||||
|
||||
# ==================== Cloud Build IAM ====================
|
||||
# These bindings allow Cloud Build to access Artifact Registry and deploy as the backend SA
|
||||
@@ -188,8 +189,8 @@ edge_resources = edge_security.configure_edge_security()
|
||||
video_encoding_job = cloud_run.create_video_encoding_job(bucket, backend_service_account)
|
||||
lyrics_transcription_job = cloud_run.create_lyrics_transcription_job(bucket, backend_service_account)
|
||||
audio_separation_job = cloud_run.create_audio_separation_job(bucket, backend_service_account)
|
||||
audio_download_job = cloud_run.create_audio_download_job(bucket, backend_service_account, vpc_connector)
|
||||
bulk_search_job = cloud_run.create_bulk_search_job(bucket, backend_service_account, vpc_connector)
|
||||
audio_download_job = cloud_run.create_audio_download_job(bucket, backend_service_account)
|
||||
bulk_search_job = cloud_run.create_bulk_search_job(bucket, backend_service_account)
|
||||
|
||||
# ==================== Error Monitor ====================
|
||||
|
||||
@@ -495,7 +496,10 @@ recover_stuck_downloads_scheduler = cloudscheduler.Job(
|
||||
name="recover-stuck-downloads",
|
||||
description="Detect and recover jobs stuck in downloading_audio status",
|
||||
region=REGION,
|
||||
schedule="*/5 * * * *", # Every 5 minutes
|
||||
# Every 10 min (was 5; 2026-09-26 cost cut — each tick streams the
|
||||
# processing-status job docs from Firestore). Recovery sweeps only, with
|
||||
# ~10-min stall thresholds, so worst-case detection moves from ~15 to ~20 min.
|
||||
schedule="*/10 * * * *",
|
||||
time_zone="America/Los_Angeles",
|
||||
http_target=cloudscheduler.JobHttpTargetArgs(
|
||||
uri="https://api.nomadkaraoke.com/api/internal/recover-stuck-jobs",
|
||||
@@ -521,7 +525,10 @@ retry_pending_render_jobs_scheduler = cloudscheduler.Job(
|
||||
name="retry-pending-render-jobs",
|
||||
description="Auto-retry render jobs parked on GCE encoding capacity exhaustion",
|
||||
region=REGION,
|
||||
schedule="*/5 * * * *", # Every 5 minutes
|
||||
# Every 10 min (was 5; 2026-09-26 cost cut — each tick streams the
|
||||
# processing-status job docs from Firestore). Recovery sweeps only, with
|
||||
# ~10-min stall thresholds, so worst-case detection moves from ~15 to ~20 min.
|
||||
schedule="*/10 * * * *",
|
||||
time_zone="America/Los_Angeles",
|
||||
http_target=cloudscheduler.JobHttpTargetArgs(
|
||||
uri="https://api.nomadkaraoke.com/api/internal/retry-pending-render-jobs",
|
||||
@@ -657,11 +664,10 @@ encoding_worker_instances = encoding_worker_vm.create_encoding_worker_vms(
|
||||
encoding_worker_ips, encoding_worker_sa
|
||||
)
|
||||
|
||||
# Capacity-fallback Encoding Worker VMs — diversified across alternate zones
|
||||
# AND an alternate machine family (c4d in us-central1-a/-b + n2 in -c/-f) so a
|
||||
# region-wide c4d-highcpu-32 ZONE_RESOURCE_POOL_EXHAUSTED can't take out every
|
||||
# lane (incident 2026-08-12). Provisioned stopped; only started by the
|
||||
# application when the primary rejects a start. Cost when idle: ~$10/mo each.
|
||||
# Capacity-fallback Encoding Worker VM — one ON-DEMAND VM in a different zone AND
|
||||
# machine family from the c4d Spot pair, so a Spot/c4d stockout can't take out
|
||||
# every lane (incident 2026-08-12). Provisioned stopped; only started by the
|
||||
# application when the primary rejects a start. Cost when idle: the boot disk.
|
||||
# See EncodingWorkerConfig.FALLBACKS for the fleet definition.
|
||||
encoding_worker_fallback_ips = encoding_worker_vm.create_encoding_worker_fallback_ips()
|
||||
encoding_worker_fallback_instances = encoding_worker_vm.create_encoding_worker_fallback_vms(
|
||||
@@ -673,7 +679,7 @@ encoding_worker_firewall = encoding_worker_vm.create_encoding_worker_firewall()
|
||||
# Grant backend SA permission to start encoding worker VMs
|
||||
backend_compute_perms = worker_sas.grant_backend_compute_permissions(backend_service_account)
|
||||
|
||||
# Encoding Worker Idle Shutdown (auto-stop after 15 min idle)
|
||||
# Encoding Worker Idle Shutdown (auto-stop after 5 min idle, checked every 2 min)
|
||||
encoding_worker_idle_resources = encoding_worker_manager.create_idle_shutdown_resources()
|
||||
|
||||
# GitHub Runners (CI/CD self-hosted runners)
|
||||
@@ -777,27 +783,20 @@ pulumi.export("recover_stuck_downloads_scheduler_name", recover_stuck_downloads_
|
||||
pulumi.export("disposable_domains_sync_scheduler_name", disposable_domains_sync_scheduler.name)
|
||||
pulumi.export("gdrive_validator_service_account", gdrive_validator_sa.email)
|
||||
|
||||
# VPC networking
|
||||
pulumi.export("vpc_connector_name", vpc_connector.name)
|
||||
pulumi.export("vpc_connector_self_link", vpc_connector.self_link)
|
||||
|
||||
# Encoding workers (blue-green pair)
|
||||
pulumi.export("encoding_worker_a_ip", encoding_worker_ips[0].address)
|
||||
pulumi.export("encoding_worker_b_ip", encoding_worker_ips[1].address)
|
||||
pulumi.export("encoding_worker_a_url", encoding_worker_ips[0].address.apply(lambda ip: f"http://{ip}:8080"))
|
||||
pulumi.export("encoding_worker_b_url", encoding_worker_ips[1].address.apply(lambda ip: f"http://{ip}:8080"))
|
||||
|
||||
# Capacity-fallback VM exports (us-central1-a, -b)
|
||||
pulumi.export("encoding_worker_fallback_a_ip", encoding_worker_fallback_ips[0].address)
|
||||
pulumi.export("encoding_worker_fallback_b_ip", encoding_worker_fallback_ips[1].address)
|
||||
pulumi.export(
|
||||
"encoding_worker_fallback_a_url",
|
||||
encoding_worker_fallback_ips[0].address.apply(lambda ip: f"http://{ip}:8080"),
|
||||
)
|
||||
pulumi.export(
|
||||
"encoding_worker_fallback_b_url",
|
||||
encoding_worker_fallback_ips[1].address.apply(lambda ip: f"http://{ip}:8080"),
|
||||
)
|
||||
# Capacity-fallback VM exports (one per EncodingWorkerConfig.FALLBACKS entry,
|
||||
# keyed by suffix, e.g. encoding_worker_fallback_c2df_ip).
|
||||
for _fb, _fb_ip in zip(EncodingWorkerConfig.FALLBACKS, encoding_worker_fallback_ips):
|
||||
pulumi.export(f"encoding_worker_fallback_{_fb['suffix']}_ip", _fb_ip.address)
|
||||
pulumi.export(
|
||||
f"encoding_worker_fallback_{_fb['suffix']}_url",
|
||||
_fb_ip.address.apply(lambda ip: f"http://{ip}:8080"),
|
||||
)
|
||||
pulumi.export("encoding_worker_service_account", encoding_worker_sa.email)
|
||||
pulumi.export("encoding_worker_a_name", encoding_worker_instances[0].name)
|
||||
pulumi.export("encoding_worker_b_name", encoding_worker_instances[1].name)
|
||||
|
||||
@@ -3,7 +3,9 @@ Encoding Worker VM resources — blue-green deployment pair.
|
||||
|
||||
Manages two identical VMs (a/b) for zero-downtime deployments.
|
||||
Only one is active (primary) at a time; the other is stopped (secondary).
|
||||
Both auto-shutdown when idle to minimize cost.
|
||||
Both auto-shutdown when idle to minimize cost, and both run on SPOT capacity
|
||||
(preempted → STOPPED, restarted on demand; lost encodes are resubmitted). One
|
||||
on-demand fallback VM in a different family/zone absorbs Spot stockouts.
|
||||
|
||||
See docs/superpowers/specs/2026-03-24-blue-green-encoding-worker-design.md
|
||||
"""
|
||||
@@ -80,18 +82,42 @@ def create_encoding_worker_vms(
|
||||
advanced_machine_features=compute.InstanceAdvancedMachineFeaturesArgs(
|
||||
threads_per_core=2,
|
||||
),
|
||||
scheduling=_primary_pair_scheduling(),
|
||||
)
|
||||
vms.append(vm)
|
||||
return vms
|
||||
|
||||
|
||||
def _primary_pair_scheduling() -> compute.InstanceSchedulingArgs:
|
||||
"""Scheduling for the a/b pair: Spot with STOP-on-preemption.
|
||||
|
||||
STOP (not DELETE) keeps the VM, its disk and static IP, so a preempted
|
||||
worker is just a TERMINATED instance that the backend's ensure-running path
|
||||
restarts like any idle-stopped worker. automatic_restart must be False and
|
||||
on_host_maintenance TERMINATE for Spot.
|
||||
"""
|
||||
if not EncodingWorkerConfig.PRIMARY_PAIR_SPOT:
|
||||
return compute.InstanceSchedulingArgs(
|
||||
provisioning_model="STANDARD",
|
||||
preemptible=False,
|
||||
automatic_restart=True,
|
||||
on_host_maintenance="MIGRATE",
|
||||
)
|
||||
return compute.InstanceSchedulingArgs(
|
||||
provisioning_model="SPOT",
|
||||
preemptible=True,
|
||||
automatic_restart=False,
|
||||
on_host_maintenance="TERMINATE",
|
||||
instance_termination_action="STOP",
|
||||
)
|
||||
|
||||
|
||||
def create_encoding_worker_fallback_ips() -> list[compute.Address]:
|
||||
"""Create static IPs for the capacity-fallback VMs.
|
||||
|
||||
These IPs back the fallback fleet that absorbs a primary-family stockout —
|
||||
both alternate zones AND an alternate machine family (n2-highcpu-32) so a
|
||||
region-wide c4d-highcpu-32 ZONE_RESOURCE_POOL_EXHAUSTED can't take out every
|
||||
lane. One IP per entry in EncodingWorkerConfig.FALLBACKS (order-aligned).
|
||||
These IPs back the on-demand fallback that absorbs a Spot/c4d stockout of
|
||||
the primary pair (alternate zone AND machine family). One IP per entry in
|
||||
EncodingWorkerConfig.FALLBACKS (order-aligned).
|
||||
"""
|
||||
ips = []
|
||||
for fb in EncodingWorkerConfig.FALLBACKS:
|
||||
@@ -115,14 +141,13 @@ def create_encoding_worker_fallback_vms(
|
||||
) -> list[compute.Instance]:
|
||||
"""Create capacity-fallback encoding worker VMs.
|
||||
|
||||
Provisioned stopped — only started by the application when the primary zone
|
||||
rejects starts with ZONE_RESOURCE_POOL_EXHAUSTED. The fleet diversifies
|
||||
across both alternate zones AND an alternate machine family
|
||||
(n2-highcpu-32) so a region-wide c4d-highcpu-32 stockout cannot exhaust
|
||||
every lane at once (incident 2026-08-12). Each entry's machine_type and
|
||||
disk_type come from EncodingWorkerConfig.FALLBACKS — n2 uses pd-balanced
|
||||
because it does not support hyperdisk-balanced. Cost when stopped is just
|
||||
the 50 GB boot disk (~$4-5/mo each).
|
||||
Provisioned stopped — only started by the application when the Spot primary
|
||||
pair can't start (ZONE_RESOURCE_POOL_EXHAUSTED / Spot stockout). On-demand
|
||||
(default STANDARD scheduling — never preempted), in a different machine
|
||||
family and zone from the c4d pair (incident 2026-08-12). Each entry's
|
||||
machine_type and disk_type come from EncodingWorkerConfig.FALLBACKS — c2d/n2
|
||||
use pd-balanced because they don't support hyperdisk-balanced. Cost when
|
||||
stopped is just the 50 GB boot disk.
|
||||
"""
|
||||
startup_script = read_script("encoding_worker.sh")
|
||||
custom_image = f"projects/{PROJECT_ID}/global/images/family/encoding-worker"
|
||||
|
||||
+40
-60
@@ -33,7 +33,7 @@ def get_project_number() -> str:
|
||||
REGION = "us-central1"
|
||||
ZONE = f"{REGION}-a"
|
||||
|
||||
# Encoding worker zone - uses us-central1-c due to c4d-highcpu-32 availability
|
||||
# Encoding worker zone - uses us-central1-c due to c4d availability
|
||||
# (us-central1-a and us-central1-b often lack capacity for high-end C4D instances)
|
||||
ENCODING_WORKER_ZONE = f"{REGION}-c"
|
||||
|
||||
@@ -47,23 +47,19 @@ class MachineTypes:
|
||||
GITHUB_RUNNER = "e2-standard-4" # 4 vCPU, 16GB RAM
|
||||
GITHUB_BUILD_RUNNER = "e2-standard-8" # 8 vCPU, 32GB RAM - dedicated Docker build runner
|
||||
GITHUB_GPU_RUNNER = "n1-standard-4" # 4 vCPU, 15GB RAM - GPU runners need N1 series
|
||||
ENCODING_WORKER = "c4d-highcpu-32" # 32 vCPU, AMD EPYC 9B45 Turin - 4.92x faster than c4-standard-8
|
||||
# Capacity-fallback machine family, deliberately DIFFERENT from ENCODING_WORKER.
|
||||
# c4d-highcpu-32 suffered a region-wide ZONE_RESOURCE_POOL_EXHAUSTED stockout across
|
||||
# us-central1-a/-b/-c simultaneously (2026-08-12) which took out every same-family lane.
|
||||
# n2-highcpu-32 (Intel Cascade/Ice Lake) draws from a much deeper, independent pool, so a
|
||||
# c4d shortage cannot exhaust it. n2 does NOT support hyperdisk-balanced → uses pd-balanced.
|
||||
ENCODING_WORKER_ALT = "n2-highcpu-32" # 32 vCPU, Intel Cascade/Ice Lake - deep-capacity fallback pool
|
||||
# Broadened ranked pool (2026-08-15) — ≥5 x86_64, 32-vCPU, ≥32 GB highcpu types
|
||||
# across 4 distinct silicon lineages, so a stockout of the newest-gen cohort
|
||||
# (c4d/c4, the crunch) cannot exhaust every lane. Encode-speed ranking lives in
|
||||
# backend/services/encoding_worker_preference.py::SPEED_RANK. Disk-type rule:
|
||||
# next-gen Titanium families (c4/c4d/n4/n4d) support hyperdisk-balanced ONLY;
|
||||
# older families (c2d/n2/n2d) use pd-balanced. Getting this wrong = pulumi error.
|
||||
ENCODING_WORKER_C4 = "c4-highcpu-32" # 32 vCPU / 64 GB, Intel Emerald Rapids (hyperdisk-only)
|
||||
ENCODING_WORKER_N4D = "n4d-highcpu-32" # 32 vCPU / 64 GB, AMD Titanium (hyperdisk-only)
|
||||
ENCODING_WORKER_C2D = "c2d-highcpu-32" # 32 vCPU / 64 GB, AMD Milan (Zen3), deep pool (pd-balanced)
|
||||
ENCODING_WORKER_N2D = "n2d-highcpu-32" # 32 vCPU / 32 GB, AMD Rome/Milan, deep pool (pd-balanced)
|
||||
# Encoding workers (2026-09-26 cost cut, docs/archive/2026-09-26-encoding-cost-cuts.md):
|
||||
# 16 vCPU instead of 32 — an approved speed-for-cost trade (finalization x264
|
||||
# only kept ~66-78% of 32 vCPUs busy; ffmpeg auto-threads adapt to 16). The
|
||||
# worker serializes heavy jobs (ENCODING_HEAVY_CONCURRENCY=1), and highcpu-16
|
||||
# still has ~30-32 GB RAM — enough for one 4K encode (~18 GB peak).
|
||||
ENCODING_WORKER = "c4d-highcpu-16" # 16 vCPU / 30 GB, AMD EPYC Turin — Spot blue-green pair
|
||||
# The ONE on-demand capacity fallback. Deliberately a DIFFERENT machine family
|
||||
# and zone from the c4d Spot pair: c4d suffered a region-wide
|
||||
# ZONE_RESOURCE_POOL_EXHAUSTED stockout (2026-08-12), and Spot capacity can
|
||||
# vanish at any time. c2d (AMD Milan) draws from a deep, mature pool and is
|
||||
# on-demand, so it is not preemptible. c2d does NOT support hyperdisk →
|
||||
# pd-balanced boot disk.
|
||||
ENCODING_WORKER_FALLBACK = "c2d-highcpu-16" # 16 vCPU / 32 GB, AMD Milan (Zen3), on-demand
|
||||
FLACFETCH = "e2-small" # 0.5 vCPU, 2GB RAM
|
||||
|
||||
|
||||
@@ -308,56 +304,38 @@ class EncodingWorkerConfig:
|
||||
"""Configuration for blue-green encoding worker VMs."""
|
||||
VM_NAMES = ["encoding-worker-a", "encoding-worker-b"]
|
||||
IP_NAMES = ["encoding-worker-ip-a", "encoding-worker-ip-b"]
|
||||
IDLE_CHECK_SCHEDULE = "*/5 * * * *" # Every 5 minutes
|
||||
IDLE_TIMEOUT_MINUTES = 15
|
||||
# Stop idle workers fast: VMs bill per second while RUNNING, and with only
|
||||
# ~5-20 jobs/day most of the old 15-min tail was paid idle time. The function
|
||||
# still NEVER stops a VM with active jobs (fail-safe on unconfirmed /health).
|
||||
IDLE_CHECK_SCHEDULE = "*/2 * * * *" # Every 2 minutes
|
||||
IDLE_TIMEOUT_MINUTES = 5
|
||||
FUNCTION_NAME = "encoding-worker-idle-shutdown"
|
||||
FUNCTION_MEMORY = "512M" # Increased from 256M — OOM with gRPC/Firestore/Compute client libs
|
||||
FUNCTION_TIMEOUT = 120 # 2 minutes
|
||||
|
||||
# Capacity-resilience fallback fleet. Each VM is provisioned STOPPED in an
|
||||
# alternate zone / machine family and is started on demand only when the
|
||||
# primary zone rejects a start with ZONE_RESOURCE_POOL_EXHAUSTED. Cost when
|
||||
# stopped is just the 50 GB boot disk (~$4-5/mo each).
|
||||
# The a/b blue-green pair runs on SPOT capacity (~60-70% cheaper). A preempted
|
||||
# Spot VM is STOPPED (not deleted) — the backend restarts it on the next
|
||||
# request, and an encode lost to preemption is resubmitted automatically
|
||||
# (encoding_service.wait_for_completion → EncodingJobLostError).
|
||||
PRIMARY_PAIR_SPOT = True
|
||||
|
||||
# Capacity-resilience fallback. Provisioned STOPPED and started on demand only
|
||||
# when the Spot pair can't start (ZONE_RESOURCE_POOL_EXHAUSTED / Spot
|
||||
# stockout). ON-DEMAND (never preempted) and a different family + zone from the
|
||||
# c4d pair so one shortage can't take out both lanes. Cost when stopped is just
|
||||
# the 50 GB boot disk.
|
||||
#
|
||||
# Machine-family diversity is DELIBERATE. The primary pair and the two c4d
|
||||
# fallbacks are all c4d-highcpu-32, so a region-wide c4d stockout (observed
|
||||
# 2026-08-12 across us-central1-a/-b/-c at once) exhausts every lane
|
||||
# simultaneously and forces slow local encoding (→ 524 on preview, parked
|
||||
# renders). The n2-highcpu-32 fallbacks draw from an independent, much deeper
|
||||
# pool so a c4d shortage cannot take them out. n2 does not support
|
||||
# hyperdisk-balanced, hence pd-balanced boot disks on those entries.
|
||||
# Was 8 fallbacks across 6 families (2026-08-15) — cut to 1 on 2026-09-26
|
||||
# (fleet 10 → 3 VMs) to save the idle disk/IP spend; c2df was kept because it
|
||||
# is a deep-pool, pd-balanced (cheaper disk) family in a separate zone.
|
||||
#
|
||||
# Each entry: name/IP suffix, zone suffix ({REGION}-{zone_suffix}),
|
||||
# machine_type, boot disk_type. ORDER MATTERS — IPs and VMs are zipped by
|
||||
# position. (Candidate PRIORITY is no longer positional: it is decided at
|
||||
# runtime/deploy by the shared speed-rank + cooldown in
|
||||
# backend/services/encoding_worker_preference.py.) Keep the existing a/b/n2c/n2f
|
||||
# entries first and byte-identical so Pulumi does not recreate those VMs; the
|
||||
# broadened-pool entries are APPENDED so the change is purely additive
|
||||
# (verify `pulumi preview` shows only new IPs+VMs, zero replace).
|
||||
#
|
||||
# Zone spread: one machine type per zone where possible so a single
|
||||
# (type × zone) stockout can't correlate across the pool. c4d primary lives in
|
||||
# zone c (the primary pair), so the c4 fallback goes to a, n4d to b, c2d to f,
|
||||
# n2d to a — 4 lineages across 4 zones.
|
||||
# machine_type, boot disk_type. IPs and VMs are zipped by position. The
|
||||
# runtime/deploy candidate PRIORITY is decided by the shared speed-rank +
|
||||
# cooldown in backend/services/encoding_worker_preference.py.
|
||||
FALLBACKS = [
|
||||
{"suffix": "a", "zone_suffix": "a",
|
||||
"machine_type": MachineTypes.ENCODING_WORKER, "disk_type": "hyperdisk-balanced"},
|
||||
{"suffix": "b", "zone_suffix": "b",
|
||||
"machine_type": MachineTypes.ENCODING_WORKER, "disk_type": "hyperdisk-balanced"},
|
||||
{"suffix": "n2c", "zone_suffix": "c",
|
||||
"machine_type": MachineTypes.ENCODING_WORKER_ALT, "disk_type": "pd-balanced"},
|
||||
{"suffix": "n2f", "zone_suffix": "f",
|
||||
"machine_type": MachineTypes.ENCODING_WORKER_ALT, "disk_type": "pd-balanced"},
|
||||
# --- Broadened pool (2026-08-15), appended (additive-only) ---
|
||||
{"suffix": "c4a", "zone_suffix": "a",
|
||||
"machine_type": MachineTypes.ENCODING_WORKER_C4, "disk_type": "hyperdisk-balanced"},
|
||||
{"suffix": "n4db", "zone_suffix": "b",
|
||||
"machine_type": MachineTypes.ENCODING_WORKER_N4D, "disk_type": "hyperdisk-balanced"},
|
||||
{"suffix": "c2df", "zone_suffix": "f",
|
||||
"machine_type": MachineTypes.ENCODING_WORKER_C2D, "disk_type": "pd-balanced"},
|
||||
{"suffix": "n2da", "zone_suffix": "a",
|
||||
"machine_type": MachineTypes.ENCODING_WORKER_N2D, "disk_type": "pd-balanced"},
|
||||
"machine_type": MachineTypes.ENCODING_WORKER_FALLBACK, "disk_type": "pd-balanced"},
|
||||
]
|
||||
|
||||
# Derived name lists (kept for readability / any external reference).
|
||||
@@ -380,6 +358,8 @@ class ErrorMonitorConfig:
|
||||
CPU = "1"
|
||||
TIMEOUT = "300s"
|
||||
MAX_RETRIES = 0
|
||||
MONITOR_SCHEDULE = "*/15 * * * *" # Every 15 minutes UTC
|
||||
# Hourly (was every 15 min; 2026-09-26 cost cut). Must match
|
||||
# backend/services/error_monitor/config.py LOOKBACK_MINUTES (60).
|
||||
MONITOR_SCHEDULE = "0 * * * *"
|
||||
DIGEST_SCHEDULE = "0 8 * * *" # 08:00 UTC daily
|
||||
SCHEDULER_SA_NAME = "error-monitor-scheduler"
|
||||
@@ -84,7 +84,8 @@ def _inventory(only_types: Optional[set]) -> List[Dict[str, Any]]:
|
||||
if data.get("primary_vm"):
|
||||
workers.append({
|
||||
"vm": data["primary_vm"], "zone": DEFAULT_C4D_ZONE,
|
||||
"ip": data.get("primary_ip"), "machine_type": "c4d-highcpu-32",
|
||||
# Keep in sync with encoding_worker_preference.PRIMARY_MACHINE_TYPE.
|
||||
"ip": data.get("primary_ip"), "machine_type": "c4d-highcpu-16",
|
||||
})
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"WARN: could not read primary from Firestore ({e}); benchmarking fallbacks only")
|
||||
@@ -238,11 +239,19 @@ def benchmark(args) -> Dict[str, float]:
|
||||
|
||||
|
||||
def _suggest_ranks(medians: Dict[str, float]) -> Dict[str, int]:
|
||||
"""Map medians → SPEED_RANK ints (fastest = smallest), spaced by 10."""
|
||||
"""Map medians → SPEED_RANK ints (fastest = smallest), spaced by 10.
|
||||
|
||||
Keyed by machine FAMILY ("c4d-highcpu-16" → "c4d"), matching
|
||||
encoding_worker_preference.SPEED_RANK (family-keyed since 2026-09-26).
|
||||
"""
|
||||
ordered = sorted(medians.items(), key=lambda kv: kv[1])
|
||||
return {mt: (idx + 1) * 10 for idx, (mt, _) in enumerate(ordered)}
|
||||
|
||||
|
||||
def _family(machine_type: str) -> str:
|
||||
return machine_type.split("-", 1)[0].lower()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--input-gcs", dest="input_gcs", required=True,
|
||||
@@ -282,7 +291,10 @@ def main() -> int:
|
||||
for mt, secs in sorted(medians.items(), key=lambda kv: kv[1]):
|
||||
print(f" {mt:>16}: {secs:>7.1f}s → suggested SPEED_RANK {ranks[mt]}")
|
||||
|
||||
payload = {"medians_seconds": medians, "suggested_speed_rank": ranks}
|
||||
family_ranks: Dict[str, int] = {}
|
||||
for mt, rank in sorted(ranks.items(), key=lambda kv: kv[1]):
|
||||
family_ranks.setdefault(_family(mt), rank) # fastest size wins per family
|
||||
payload = {"medians_seconds": medians, "suggested_speed_rank": family_ranks}
|
||||
if args.json_out:
|
||||
with open(args.json_out, "w") as f:
|
||||
json.dump(payload, f, indent=2)
|
||||
|
||||
@@ -6,13 +6,14 @@ delegates the *decisions* to the pure functions here so the branching — the pa
|
||||
that's easy to get wrong and impossible to run locally in CI — has real unit
|
||||
tests (`backend/tests/test_deploy_promote.py`).
|
||||
|
||||
Background: us-central1 is in a persistent c4d Spot stockout, so the c4d
|
||||
primary/secondary are usually down and all traffic runs on an n2 fallback
|
||||
recorded as `active_override_vm`. A naive "start the c4d secondary and swap"
|
||||
deploy can't start the secondary and never refreshes the serving fallback, so
|
||||
worker-side changes never reach production. These helpers make the deploy pick a
|
||||
*fresh* green target (c4d secondary if it starts, else a different n2 fallback)
|
||||
and then promote that validated green to serving with zero downtime.
|
||||
Background: the c4d primary/secondary are Spot VMs (since 2026-09-26) and c4d
|
||||
capacity in us-central1 can run out, in which case traffic runs on the on-demand
|
||||
fallback recorded as `active_override_vm`. A naive "start the c4d secondary and
|
||||
swap" deploy can't start the secondary and never refreshes the serving fallback,
|
||||
so worker-side changes never reach production. These helpers make the deploy pick
|
||||
a *fresh* green target (c4d secondary if it starts, else a fallback) and then
|
||||
promote that validated green to serving with zero downtime. CI only runs this when
|
||||
worker code changed (infrastructure/encoding-worker/worker_code_paths.txt).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Paths whose changes require a blue-green redeploy of the GCE encoding worker.
|
||||
#
|
||||
# CI (.github/workflows/ci.yml, "Decide encoding-worker deploy") diffs these
|
||||
# paths between the version the serving worker was last validated at
|
||||
# (config/encoding-worker.primary_version → git tag v<version>) and HEAD. No
|
||||
# diff → the fresh-green boot + test encode + swap is skipped (it used to run on
|
||||
# every push to main). The wheel/startup.sh/version.txt are STILL uploaded to
|
||||
# GCS on every deploy, so any worker that cold-boots picks up the latest wheel.
|
||||
#
|
||||
# The worker process runs backend/services/gce_encoding/main.py and imports
|
||||
# karaoke_gen (render/encode) plus a few backend modules.
|
||||
# backend/tests/test_encoding_worker_code_paths.py derives that import closure
|
||||
# and fails if a module the worker imports is not covered here — so adding a new
|
||||
# worker import can't silently bypass the gate.
|
||||
#
|
||||
# One git pathspec per line; blank lines and # comments are ignored.
|
||||
karaoke_gen/
|
||||
backend/__init__.py
|
||||
backend/services/__init__.py
|
||||
backend/models/__init__.py
|
||||
backend/services/gce_encoding/
|
||||
backend/services/local_encoding_service.py
|
||||
backend/services/local_preview_encoding_service.py
|
||||
backend/services/theme_service.py
|
||||
backend/services/storage_service.py
|
||||
backend/services/langfuse_preloader.py
|
||||
backend/services/nltk_preloader.py
|
||||
backend/services/spacy_preloader.py
|
||||
backend/models/theme.py
|
||||
backend/utils/
|
||||
backend/config.py
|
||||
infrastructure/encoding-worker/
|
||||
infrastructure/packer/
|
||||
poetry.lock
|
||||
@@ -18,8 +18,16 @@ def sync_gcs_to_staging(
|
||||
) -> str:
|
||||
"""Copy new/changed objects from source to staging bucket.
|
||||
|
||||
Uses object metadata (updated time) to detect changes since last sync.
|
||||
The staging bucket stores a marker file with the last sync timestamp.
|
||||
Uses each object's ``time_created`` (the creation time of its current
|
||||
generation — an overwrite creates a new generation) to detect new/changed
|
||||
content since the last sync. The staging bucket stores a marker file with
|
||||
the last sync timestamp.
|
||||
|
||||
Deliberately NOT ``updated``: that is bumped by any *metadata* change,
|
||||
including Autoclass storage-class transitions (enabled on the job-files
|
||||
bucket 2026-09-26). Keying on it would re-copy every object each time it
|
||||
cooled to Nearline — and the copy's read would pull it straight back to
|
||||
Standard, defeating Autoclass.
|
||||
|
||||
Args:
|
||||
source_bucket: Source GCS bucket name.
|
||||
@@ -48,18 +56,19 @@ def sync_gcs_to_staging(
|
||||
for prefix in prefixes:
|
||||
blobs = src.list_blobs(prefix=prefix)
|
||||
for blob in blobs:
|
||||
if not blob.updated:
|
||||
created = blob.time_created
|
||||
if not created:
|
||||
continue
|
||||
|
||||
if last_sync_dt and blob.updated <= last_sync_dt:
|
||||
if last_sync_dt and created <= last_sync_dt:
|
||||
continue
|
||||
|
||||
dst_path = f"{staging_prefix}{blob.name}"
|
||||
src.copy_blob(blob, dst, dst_path)
|
||||
copied += 1
|
||||
|
||||
if latest_updated_dt is None or blob.updated > latest_updated_dt:
|
||||
latest_updated_dt = blob.updated
|
||||
if latest_updated_dt is None or created > latest_updated_dt:
|
||||
latest_updated_dt = created
|
||||
|
||||
if copied >= max_objects:
|
||||
logger.warning(f"Hit max_objects limit ({max_objects})")
|
||||
|
||||
@@ -19,9 +19,19 @@ working set, not the sum of all repos.
|
||||
A ``manifest.json`` alongside the bundles records exactly which repos existed at
|
||||
backup time (visibility, default branch, description, size, fork/archived flags)
|
||||
— essential when recreating repos and settings from scratch after a ban.
|
||||
|
||||
Incremental (2026-09-26, egress cost cut): the step runs weekly and only
|
||||
re-bundles repos that changed since their bundle last landed in S3. A repo is
|
||||
"unchanged" when S3 already holds its bundle and that S3 object was uploaded at
|
||||
least ``_UPLOAD_LAG`` after the repo's GitHub ``pushed_at``. The lag covers the
|
||||
clone -> S3-upload gap within one run (bounded by the function's 30-min
|
||||
deadline): a push that lands after the clone but before the upload is newer
|
||||
than ``LastModified - _UPLOAD_LAG`` and so is re-bundled next time. S3 itself is
|
||||
the state store — no separate bookkeeping to drift or expire.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -53,6 +63,10 @@ _MAX_PAGES = 30
|
||||
_CLONE_TIMEOUT = 1200
|
||||
_BUNDLE_TIMEOUT = 600
|
||||
|
||||
# Max gap between cloning a repo and its bundle reaching S3 in the same run
|
||||
# (function deadline is 30 min; doubled for slack). See module docstring.
|
||||
_UPLOAD_LAG = datetime.timedelta(hours=1)
|
||||
|
||||
|
||||
def get_github_token(project: str, secret_id: str = "github-backup-token") -> str:
|
||||
"""Fetch the GitHub backup PAT from Secret Manager. Returns "" if unset.
|
||||
@@ -209,6 +223,24 @@ def _repo_entry(repo: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _parse_github_time(value: str | None) -> datetime.datetime | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _is_unchanged(repo: dict, backed_up_at: datetime.datetime | None) -> bool:
|
||||
"""True if the S3 bundle (uploaded at ``backed_up_at``) already contains the
|
||||
repo's latest push. Unknown ``pushed_at`` or no S3 copy -> not unchanged."""
|
||||
pushed_at = _parse_github_time(repo.get("pushed_at"))
|
||||
if backed_up_at is None or pushed_at is None:
|
||||
return False
|
||||
return backed_up_at - _UPLOAD_LAG >= pushed_at
|
||||
|
||||
|
||||
def export_git_repos(
|
||||
staging_bucket: str,
|
||||
github_token: str,
|
||||
@@ -216,13 +248,15 @@ def export_git_repos(
|
||||
include_forks: bool = False,
|
||||
max_repo_size_kb: int = DEFAULT_MAX_REPO_SIZE_KB,
|
||||
staging_prefix: str = "git-repos/",
|
||||
existing_backups: dict | None = None,
|
||||
full_refresh: bool = False,
|
||||
) -> str:
|
||||
"""Bundle every repo under ``owners`` and write to the GCS staging bucket.
|
||||
|
||||
Bundles land at ``{staging_prefix}{owner}/{repo}.bundle`` and a
|
||||
``{staging_prefix}manifest.json`` records the full repo inventory. The
|
||||
nightly S3 upload step then ships them off-site (they are small, so unlike
|
||||
Firestore they upload every night, not weekly).
|
||||
``{staging_prefix}manifest.json`` records the full repo inventory (including
|
||||
``unchanged`` repos whose existing S3 bundle is still current). The S3
|
||||
upload step then ships them off-site.
|
||||
|
||||
Per-repo failures are recorded in the manifest and counted in the summary
|
||||
but do not abort the run (mirrors ``secrets_export`` behaviour). Only a
|
||||
@@ -238,6 +272,11 @@ def export_git_repos(
|
||||
recoverable from upstream).
|
||||
max_repo_size_kb: Skip repos larger than this (GitHub-reported size).
|
||||
staging_prefix: Prefix under the staging bucket for bundles/manifest.
|
||||
existing_backups: ``{s3_key: LastModified}`` for bundles already in S3
|
||||
(``s3_upload.list_s3_objects``). Repos whose bundle is present and
|
||||
newer than their last push are recorded as ``unchanged`` and not
|
||||
re-cloned/re-uploaded. ``None`` -> bundle everything.
|
||||
full_refresh: Ignore ``existing_backups`` and re-bundle every repo.
|
||||
|
||||
Returns:
|
||||
Summary string.
|
||||
@@ -256,8 +295,15 @@ def export_git_repos(
|
||||
gcs_client = gcs_storage.Client()
|
||||
bucket = gcs_client.bucket(staging_bucket)
|
||||
|
||||
manifest: dict = {"owners": owners, "repos": []}
|
||||
bundled = errors = skipped = 0
|
||||
existing_backups = {} if full_refresh else (existing_backups or {})
|
||||
|
||||
manifest: dict = {
|
||||
"owners": owners,
|
||||
"repos": [],
|
||||
"generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
"full_refresh": full_refresh,
|
||||
}
|
||||
bundled = errors = skipped = unchanged = 0
|
||||
|
||||
for repo in repos:
|
||||
owner = repo["owner"]["login"]
|
||||
@@ -273,10 +319,18 @@ def export_git_repos(
|
||||
manifest["repos"].append(entry)
|
||||
continue
|
||||
|
||||
dst = f"{staging_prefix}{owner}/{name}.bundle"
|
||||
backed_up_at = existing_backups.get(dst)
|
||||
if _is_unchanged(repo, backed_up_at):
|
||||
entry["status"] = "unchanged"
|
||||
entry["backed_up_at"] = backed_up_at.isoformat()
|
||||
unchanged += 1
|
||||
manifest["repos"].append(entry)
|
||||
continue
|
||||
|
||||
workdir = tempfile.mkdtemp(prefix="gitbak-")
|
||||
try:
|
||||
bundle_path = _bundle_repo(repo, github_token, workdir)
|
||||
dst = f"{staging_prefix}{owner}/{name}.bundle"
|
||||
bucket.blob(dst).upload_from_filename(bundle_path)
|
||||
entry["status"] = "bundled"
|
||||
entry["bundle_bytes"] = os.path.getsize(bundle_path)
|
||||
@@ -305,6 +359,7 @@ def export_git_repos(
|
||||
manifest["bundled"] = bundled
|
||||
manifest["errors"] = errors
|
||||
manifest["skipped"] = skipped
|
||||
manifest["unchanged"] = unchanged
|
||||
manifest["total"] = len(repos)
|
||||
|
||||
# Always write the manifest — even on a bad run it records what we saw.
|
||||
@@ -315,14 +370,17 @@ def export_git_repos(
|
||||
|
||||
summary = (
|
||||
f"Bundled {bundled}/{len(repos)} repos "
|
||||
f"({errors} errors, {skipped} skipped) to gs://{staging_bucket}/{staging_prefix}"
|
||||
f"({unchanged} unchanged, {errors} errors, {skipped} skipped) "
|
||||
f"to gs://{staging_bucket}/{staging_prefix}"
|
||||
)
|
||||
logger.info(summary)
|
||||
|
||||
# Systemic failure: nothing bundled successfully yet repos errored → surface
|
||||
# it as a hard error (bad token, git broken, network down). A run where every
|
||||
# repo was a *benign* skip (empty/oversized) or where at least one bundled is
|
||||
# not systemic, so it stays green with the counts noted in the summary.
|
||||
# Systemic failure: every repo we actually tried to bundle errored (bad
|
||||
# token, git broken, network down) → surface it as a hard error. Repos
|
||||
# skipped as unchanged/empty/oversized don't count as successes here: in
|
||||
# incremental mode almost everything is unchanged, so counting them would
|
||||
# hide a total failure of the week's changed repos. A run where at least
|
||||
# one bundle succeeded, or nothing needed bundling, stays green.
|
||||
if bundled == 0 and errors > 0:
|
||||
raise RuntimeError(summary)
|
||||
|
||||
|
||||
@@ -6,8 +6,10 @@ Nightly backup pipeline:
|
||||
2. BigQuery export to GCS staging (weekly/monthly schedule)
|
||||
3. GCS job files delta sync to staging
|
||||
4. Secret Manager export (encrypted with sealed-box public key) to staging
|
||||
4b. Git repos backup — bundle every repo under the configured GitHub owners to
|
||||
staging (nightly; survives loss of GitHub access, e.g. an account ban)
|
||||
4b. Git repos backup — bundle repos under the configured GitHub owners to
|
||||
staging (weekly on Sundays, incremental: only repos pushed since their
|
||||
bundle last reached S3; full re-bundle on the first Sunday of each month;
|
||||
survives loss of GitHub access, e.g. an account ban)
|
||||
5. Upload staging files to S3 (Firestore export held back except Sundays)
|
||||
6. Discord alert
|
||||
|
||||
@@ -31,7 +33,7 @@ from bigquery_export import export_bigquery_tables
|
||||
from gcs_sync import sync_gcs_to_staging
|
||||
from git_repos_export import export_git_repos, get_github_token
|
||||
from secrets_export import export_secrets
|
||||
from s3_upload import upload_staging_to_s3
|
||||
from s3_upload import get_s3_client, list_s3_objects, upload_staging_to_s3
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -47,6 +49,34 @@ BACKUP_ENCRYPTION_PUBKEY = os.environ.get("BACKUP_ENCRYPTION_PUBKEY", "")
|
||||
GIT_BACKUP_OWNERS = os.environ.get("GIT_BACKUP_OWNERS", "")
|
||||
|
||||
|
||||
GIT_REPOS_PREFIX = "git-repos/"
|
||||
|
||||
|
||||
def _run_git_repos_backup(full_refresh: bool) -> str:
|
||||
"""Stage bundles for repos changed since their S3 copy (or all, if
|
||||
``full_refresh``). Returns a summary string; raises on systemic failure."""
|
||||
github_token = get_github_token(GCP_PROJECT)
|
||||
if not github_token:
|
||||
logger.warning("github-backup-token has no value — skipping git repo backup")
|
||||
return "skipped (no token)"
|
||||
|
||||
existing = None
|
||||
if not full_refresh:
|
||||
try:
|
||||
existing = list_s3_objects(get_s3_client(GCP_PROJECT), S3_BUCKET, GIT_REPOS_PREFIX)
|
||||
except Exception as e: # noqa: BLE001 — can't see S3 -> safe fallback is a full bundle
|
||||
logger.warning(f"Could not list existing git bundles in S3 ({e}); bundling all repos")
|
||||
|
||||
owners = [o.strip() for o in GIT_BACKUP_OWNERS.split(",") if o.strip()] or None
|
||||
return export_git_repos(
|
||||
staging_bucket=STAGING_BUCKET,
|
||||
github_token=github_token,
|
||||
owners=owners,
|
||||
existing_backups=existing,
|
||||
full_refresh=full_refresh,
|
||||
)
|
||||
|
||||
|
||||
@functions_framework.http
|
||||
def backup_to_aws(request):
|
||||
"""Main entry point for the backup Cloud Function."""
|
||||
@@ -65,6 +95,23 @@ def backup_to_aws(request):
|
||||
)
|
||||
return json.dumps({"status": "drill_reminder_sent"}), 200
|
||||
|
||||
# Manual git-repo-only run (e.g. to verify a change or force a refresh
|
||||
# without re-running the Firestore export, which collides on same-day paths):
|
||||
# ?mode=git_repos incremental
|
||||
# ?mode=git_repos&full=1 re-bundle everything
|
||||
if request.args.get("mode") == "git_repos":
|
||||
try:
|
||||
summary = _run_git_repos_backup(full_refresh=request.args.get("full") == "1")
|
||||
upload = upload_staging_to_s3(
|
||||
staging_bucket=STAGING_BUCKET,
|
||||
s3_bucket=S3_BUCKET,
|
||||
include_prefixes=[GIT_REPOS_PREFIX],
|
||||
)
|
||||
return json.dumps({"status": "ok", "git_repos": summary, "s3_upload": upload}), 200
|
||||
except Exception as e:
|
||||
logger.error(f"Manual git repos backup failed: {e}")
|
||||
return json.dumps({"status": "failed", "errors": [f"Git repos: {e}"]}), 500
|
||||
|
||||
today = datetime.date.today()
|
||||
date_str = today.isoformat()
|
||||
results = {}
|
||||
@@ -75,6 +122,8 @@ def backup_to_aws(request):
|
||||
# weekly cadence. This is the bulk of the cross-cloud egress, so weekly
|
||||
# off-site keeps a 1-week off-site RPO while a 1-day local RPO is retained.
|
||||
firestore_to_s3_today = today.weekday() == 6 # Sunday
|
||||
git_repos_today = today.weekday() == 6 # Sunday
|
||||
git_full_refresh_today = git_repos_today and today.day <= 7 # first Sunday of the month
|
||||
|
||||
logger.info(f"Starting backup for {date_str} (firestore->S3: {firestore_to_s3_today})")
|
||||
|
||||
@@ -140,33 +189,38 @@ def backup_to_aws(request):
|
||||
logger.error(f"Secrets export failed: {e}")
|
||||
errors.append(f"Secrets: {e}")
|
||||
|
||||
# Step 4b: Git repos backup (nightly). Bundle every repo under the
|
||||
# configured GitHub owners so code + full history survives loss of GitHub
|
||||
# access (e.g. an account ban). Bundles are small, so they ship to S3 every
|
||||
# night (not held back like Firestore). Cleanly skipped if no token is set.
|
||||
try:
|
||||
github_token = get_github_token(GCP_PROJECT)
|
||||
if github_token:
|
||||
owners = [o.strip() for o in GIT_BACKUP_OWNERS.split(",") if o.strip()] or None
|
||||
results["git_repos"] = export_git_repos(
|
||||
staging_bucket=STAGING_BUCKET,
|
||||
github_token=github_token,
|
||||
owners=owners,
|
||||
)
|
||||
else:
|
||||
logger.warning("github-backup-token has no value — skipping git repo backup")
|
||||
results["git_repos"] = "skipped (no token)"
|
||||
except Exception as e:
|
||||
logger.error(f"Git repos backup failed: {e}")
|
||||
errors.append(f"Git repos: {e}")
|
||||
# Step 4b: Git repos backup (weekly, Sundays). Bundles repos so code + full
|
||||
# history survives loss of GitHub access (e.g. an account ban). Incremental:
|
||||
# only repos pushed since their bundle last landed in S3 are re-cloned and
|
||||
# re-uploaded (cross-cloud egress was a nightly full re-upload of ~120
|
||||
# bundles). The first Sunday of each month re-bundles everything as a
|
||||
# belt-and-braces refresh. Cleanly skipped if no token is set.
|
||||
if git_repos_today:
|
||||
try:
|
||||
results["git_repos"] = _run_git_repos_backup(full_refresh=git_full_refresh_today)
|
||||
except Exception as e:
|
||||
logger.error(f"Git repos backup failed: {e}")
|
||||
errors.append(f"Git repos: {e}")
|
||||
else:
|
||||
results["git_repos"] = "skipped (weekly, runs Sundays)"
|
||||
|
||||
# Step 5: Upload to S3. On non-Sundays, hold the Firestore export back
|
||||
# (it stays in GCS staging as a daily local backup); it ships to S3 weekly.
|
||||
# git-repos/ uploads only in the same invocation as the git step: the
|
||||
# incremental check trusts that a bundle's S3 LastModified is within
|
||||
# _UPLOAD_LAG of its clone. A bundle left in staging by a failed upload
|
||||
# must not ship on a later night (a push in between would then look backed
|
||||
# up); next Sunday's git step re-bundles it fresh instead.
|
||||
exclude = []
|
||||
if not firestore_to_s3_today:
|
||||
exclude.append("firestore/")
|
||||
if not git_repos_today:
|
||||
exclude.append(GIT_REPOS_PREFIX)
|
||||
try:
|
||||
results["s3_upload"] = upload_staging_to_s3(
|
||||
staging_bucket=STAGING_BUCKET,
|
||||
s3_bucket=S3_BUCKET,
|
||||
exclude_prefixes=[] if firestore_to_s3_today else ["firestore/"],
|
||||
exclude_prefixes=exclude,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"S3 upload failed: {e}")
|
||||
|
||||
@@ -6,7 +6,6 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import boto3
|
||||
from boto3.s3.transfer import TransferConfig
|
||||
from botocore.exceptions import ClientError
|
||||
from google.cloud import storage, secretmanager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -92,27 +91,65 @@ def _dedupe_final_duplicates(blobs: list) -> tuple[list, int]:
|
||||
return kept, dup_count
|
||||
|
||||
|
||||
def _s3_object_matches(s3_client, s3_bucket: str, key: str, size) -> bool:
|
||||
# Prefixes that are always overwritten in S3 (no "already present" skip). The
|
||||
# git-repo step only stages bundles whose repo actually changed, plus the
|
||||
# manifest, so everything staged under git-repos/ is new content — and a
|
||||
# changed bundle can coincidentally keep the same byte size, which the
|
||||
# size-based skip would wrongly treat as "already backed up".
|
||||
_ALWAYS_OVERWRITE_PREFIXES = ("git-repos/",)
|
||||
|
||||
|
||||
def _dir_prefix(key: str) -> str:
|
||||
return key.rsplit("/", 1)[0] + "/" if "/" in key else ""
|
||||
|
||||
|
||||
def _list_s3_sizes(s3_client, s3_bucket: str, keys) -> dict:
|
||||
"""Map ``key -> size`` for the S3 objects that share a directory with any of
|
||||
``keys``.
|
||||
|
||||
Uses ListObjectsV2 (one delimited listing per distinct directory) rather than
|
||||
a HEAD per object: the ``backup-writer`` IAM user has ``s3:ListBucket`` +
|
||||
``s3:PutObject`` but NOT ``s3:GetObject``, so S3 answers HEAD on an
|
||||
*existing* key with 403 — which made every overwrite (git bundles, manifest,
|
||||
re-written job files) fail from 2026-09-14 (#997) until 2026-09-26. Listing
|
||||
is also far fewer requests than one HEAD per file.
|
||||
"""
|
||||
sizes: dict = {}
|
||||
paginator = s3_client.get_paginator("list_objects_v2")
|
||||
for prefix in sorted({_dir_prefix(k) for k in keys}):
|
||||
for page in paginator.paginate(Bucket=s3_bucket, Prefix=prefix, Delimiter="/"):
|
||||
for obj in page.get("Contents", []):
|
||||
sizes[obj["Key"]] = obj["Size"]
|
||||
return sizes
|
||||
|
||||
|
||||
def list_s3_objects(s3_client, s3_bucket: str, prefix: str) -> dict:
|
||||
"""Map ``key -> LastModified`` (tz-aware datetime) for every S3 object under
|
||||
``prefix`` (recursive). Used by the git-repo step to find which bundles are
|
||||
already off-site and when they were uploaded."""
|
||||
found: dict = {}
|
||||
paginator = s3_client.get_paginator("list_objects_v2")
|
||||
for page in paginator.paginate(Bucket=s3_bucket, Prefix=prefix):
|
||||
for obj in page.get("Contents", []):
|
||||
found[obj["Key"]] = obj["LastModified"]
|
||||
return found
|
||||
|
||||
|
||||
def _already_in_s3(existing_sizes: dict, key: str, size) -> bool:
|
||||
"""True if S3 already holds ``key`` with the same byte size. Lets the nightly
|
||||
skip anything already backed up — making it genuinely incremental and
|
||||
self-healing (a file left in staging by a prior timeout/error is not
|
||||
re-transferred once it lands in S3)."""
|
||||
if size is None:
|
||||
if size is None or key.startswith(_ALWAYS_OVERWRITE_PREFIXES):
|
||||
return False
|
||||
try:
|
||||
head = s3_client.head_object(Bucket=s3_bucket, Key=key)
|
||||
except ClientError as e:
|
||||
if e.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):
|
||||
return False
|
||||
raise
|
||||
return head.get("ContentLength") == size
|
||||
return existing_sizes.get(key) == size
|
||||
|
||||
|
||||
def _transfer_blob(blob, s3_client, s3_bucket: str) -> str:
|
||||
def _transfer_blob(blob, s3_client, s3_bucket: str, existing_sizes: dict) -> str:
|
||||
"""Idempotently move one staging blob to S3, deleting it from staging on
|
||||
success. Returns 'uploaded', 'skipped_exists', or 'error'."""
|
||||
try:
|
||||
if _s3_object_matches(s3_client, s3_bucket, blob.name, blob.size):
|
||||
if _already_in_s3(existing_sizes, blob.name, blob.size):
|
||||
blob.delete()
|
||||
return "skipped_exists"
|
||||
with blob.open("rb") as gcs_file:
|
||||
@@ -129,6 +166,17 @@ def _transfer_blob(blob, s3_client, s3_bucket: str) -> str:
|
||||
return "error"
|
||||
|
||||
|
||||
def get_s3_client(project: str = "nomadkaraoke"):
|
||||
"""boto3 S3 client authenticated as the backup-writer IAM user."""
|
||||
aws_creds = get_aws_credentials(project)
|
||||
return boto3.client(
|
||||
"s3",
|
||||
aws_access_key_id=aws_creds["access_key_id"],
|
||||
aws_secret_access_key=aws_creds["secret_access_key"],
|
||||
region_name=aws_creds.get("region", "us-east-1"),
|
||||
)
|
||||
|
||||
|
||||
def get_aws_credentials(project: str) -> dict:
|
||||
"""Retrieve AWS credentials from GCP Secret Manager."""
|
||||
client = secretmanager.SecretManagerServiceClient()
|
||||
@@ -142,6 +190,7 @@ def upload_staging_to_s3(
|
||||
s3_bucket: str,
|
||||
project: str = "nomadkaraoke",
|
||||
exclude_prefixes: list | None = None,
|
||||
include_prefixes: list | None = None,
|
||||
) -> str:
|
||||
"""Upload staging-bucket objects to S3, incrementally and in parallel.
|
||||
|
||||
@@ -150,14 +199,16 @@ def upload_staging_to_s3(
|
||||
on non-weekly days — it stays in GCS staging as a daily local restore point
|
||||
and is uploaded only on the weekly run). Excluded objects are left in staging
|
||||
(not deleted), so they remain a local backup until the GCS lifecycle policy
|
||||
or the next weekly upload removes them.
|
||||
or the next weekly upload removes them. ``include_prefixes`` (optional)
|
||||
restricts the run to objects under those prefixes (used by the manual
|
||||
``?mode=git_repos`` trigger).
|
||||
|
||||
Efficiency:
|
||||
* **Deduped** — byte-identical duplicate finals are dropped so the largest
|
||||
data is stored/transferred once (see ``_dedupe_final_duplicates``).
|
||||
* **Incremental** — objects already in S3 (same key + size) are skipped, so
|
||||
only genuinely new/changed bytes cross the wire and a prior partial run
|
||||
self-heals (see ``_s3_object_matches``).
|
||||
* **Incremental** — objects already in S3 (same key + size, found via
|
||||
ListObjectsV2) are skipped, so only genuinely new/changed bytes cross
|
||||
the wire and a prior partial run self-heals (see ``_already_in_s3``).
|
||||
* **Parallel** — transfers fan out across a thread pool instead of a single
|
||||
serialized stream.
|
||||
|
||||
@@ -166,13 +217,7 @@ def upload_staging_to_s3(
|
||||
timeout can only cost the replaceable finals.
|
||||
"""
|
||||
exclude_prefixes = exclude_prefixes or []
|
||||
aws_creds = get_aws_credentials(project)
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
aws_access_key_id=aws_creds["access_key_id"],
|
||||
aws_secret_access_key=aws_creds["secret_access_key"],
|
||||
region_name=aws_creds.get("region", "us-east-1"),
|
||||
)
|
||||
s3_client = get_s3_client(project)
|
||||
|
||||
gcs_client = storage.Client()
|
||||
bucket = gcs_client.bucket(staging_bucket)
|
||||
@@ -182,6 +227,7 @@ def upload_staging_to_s3(
|
||||
for blob in bucket.list_blobs()
|
||||
if not (blob.name.startswith(".") or "/.last_sync" in blob.name)
|
||||
and not any(blob.name.startswith(p) for p in exclude_prefixes)
|
||||
and (include_prefixes is None or any(blob.name.startswith(p) for p in include_prefixes))
|
||||
]
|
||||
|
||||
candidates, dup_count = _dedupe_final_duplicates(candidates)
|
||||
@@ -192,6 +238,12 @@ def upload_staging_to_s3(
|
||||
critical = [b for b in candidates if not _is_large_last(b.name)]
|
||||
bulk = [b for b in candidates if _is_large_last(b.name)]
|
||||
|
||||
try:
|
||||
existing_sizes = _list_s3_sizes(s3_client, s3_bucket, [b.name for b in candidates])
|
||||
except Exception as e: # noqa: BLE001 — degrade to "upload everything", don't abort
|
||||
logger.warning(f"Could not list existing S3 objects ({e}); uploading all candidates")
|
||||
existing_sizes = {}
|
||||
|
||||
counts = {"uploaded": 0, "skipped_exists": 0, "error": 0}
|
||||
|
||||
def run_phase(phase_blobs):
|
||||
@@ -199,7 +251,7 @@ def upload_staging_to_s3(
|
||||
return
|
||||
with ThreadPoolExecutor(max_workers=_MAX_UPLOAD_WORKERS) as pool:
|
||||
for result in pool.map(
|
||||
lambda b: _transfer_blob(b, s3_client, s3_bucket), phase_blobs
|
||||
lambda b: _transfer_blob(b, s3_client, s3_bucket, existing_sizes), phase_blobs
|
||||
):
|
||||
counts[result] += 1
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Tests for gcs_sync change detection."""
|
||||
|
||||
import datetime
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from gcs_sync import sync_gcs_to_staging
|
||||
|
||||
UTC = datetime.timezone.utc
|
||||
LAST_SYNC = datetime.datetime(2026, 9, 20, tzinfo=UTC)
|
||||
|
||||
|
||||
def _blob(name, created, updated):
|
||||
b = MagicMock()
|
||||
b.name = name
|
||||
b.time_created = created
|
||||
b.updated = updated
|
||||
return b
|
||||
|
||||
|
||||
def _run(blobs):
|
||||
client = MagicMock()
|
||||
src, dst = MagicMock(), MagicMock()
|
||||
client.bucket.side_effect = lambda n: src if n == "src" else dst
|
||||
marker = MagicMock()
|
||||
marker.exists.return_value = True
|
||||
marker.download_as_text.return_value = LAST_SYNC.isoformat()
|
||||
dst.blob.return_value = marker
|
||||
src.list_blobs.return_value = blobs
|
||||
with patch("gcs_sync.storage.Client", return_value=client):
|
||||
summary = sync_gcs_to_staging("src", "dst", "gcs/job-files/", sync_prefixes=["jobs/"])
|
||||
return summary, src, marker
|
||||
|
||||
|
||||
def test_metadata_only_change_is_not_recopied():
|
||||
"""An Autoclass storage-class transition bumps `updated` but not
|
||||
`time_created`; it must not be treated as new content."""
|
||||
cooled = _blob("jobs/a/old.mp4", LAST_SYNC - datetime.timedelta(days=40), LAST_SYNC + datetime.timedelta(days=1))
|
||||
summary, src, marker = _run([cooled])
|
||||
src.copy_blob.assert_not_called()
|
||||
assert summary == "Synced 0 objects"
|
||||
|
||||
|
||||
def test_new_generation_is_copied_and_marker_advances():
|
||||
created = LAST_SYNC + datetime.timedelta(hours=3)
|
||||
new = _blob("jobs/b/final.mp4", created, created)
|
||||
summary, src, marker = _run([new])
|
||||
src.copy_blob.assert_called_once()
|
||||
marker.upload_from_string.assert_called_with(created.isoformat())
|
||||
assert summary == "Synced 1 objects"
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Tests for git_repos_export module."""
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import subprocess
|
||||
from unittest.mock import MagicMock, patch
|
||||
@@ -59,7 +60,13 @@ def _fake_gcs():
|
||||
return client, uploads
|
||||
|
||||
|
||||
def _run(pages, subprocess_side_effect=None, max_repo_size_kb=git_repos_export.DEFAULT_MAX_REPO_SIZE_KB):
|
||||
def _run(
|
||||
pages,
|
||||
subprocess_side_effect=None,
|
||||
max_repo_size_kb=git_repos_export.DEFAULT_MAX_REPO_SIZE_KB,
|
||||
existing_backups=None,
|
||||
full_refresh=False,
|
||||
):
|
||||
client, uploads = _fake_gcs()
|
||||
run_mock = MagicMock()
|
||||
if subprocess_side_effect is not None:
|
||||
@@ -76,6 +83,8 @@ def _run(pages, subprocess_side_effect=None, max_repo_size_kb=git_repos_export.D
|
||||
github_token="ghp_test",
|
||||
owners=["nomadkaraoke", "beveradb"],
|
||||
max_repo_size_kb=max_repo_size_kb,
|
||||
existing_backups=existing_backups,
|
||||
full_refresh=full_refresh,
|
||||
)
|
||||
return summary, uploads, run_mock
|
||||
|
||||
@@ -280,3 +289,103 @@ def test_get_github_token_missing_returns_empty_string():
|
||||
client.access_secret_version.side_effect = Exception("NOT_FOUND: no versions")
|
||||
with patch("git_repos_export.secretmanager.SecretManagerServiceClient", return_value=client):
|
||||
assert get_github_token("nomadkaraoke") == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Incremental (only re-bundle repos pushed since their bundle reached S3)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _utc(s):
|
||||
return datetime.datetime.fromisoformat(s).replace(tzinfo=datetime.timezone.utc)
|
||||
|
||||
|
||||
def _cloned(run_mock):
|
||||
return [c.args[0][-2] for c in run_mock.call_args_list if c.args[0][:2] == ["git", "clone"]]
|
||||
|
||||
|
||||
def test_unchanged_repo_is_not_recloned_or_restaged():
|
||||
pages = [[
|
||||
_make_repo("nomadkaraoke", "quiet", pushed_at="2026-09-01T00:00:00Z"),
|
||||
_make_repo("nomadkaraoke", "busy", pushed_at="2026-09-20T00:00:00Z"),
|
||||
]]
|
||||
existing = {
|
||||
"git-repos/nomadkaraoke/quiet.bundle": _utc("2026-09-13T05:00:00"),
|
||||
"git-repos/nomadkaraoke/busy.bundle": _utc("2026-09-13T05:00:00"),
|
||||
}
|
||||
summary, uploads, run_mock = _run(pages, existing_backups=existing)
|
||||
|
||||
assert _cloned(run_mock) == ["https://github.com/nomadkaraoke/busy.git"]
|
||||
assert "git-repos/nomadkaraoke/quiet.bundle" not in uploads
|
||||
assert "git-repos/nomadkaraoke/busy.bundle" in uploads
|
||||
manifest = _manifest(uploads)
|
||||
statuses = {r["full_name"]: r["status"] for r in manifest["repos"]}
|
||||
assert statuses == {"nomadkaraoke/quiet": "unchanged", "nomadkaraoke/busy": "bundled"}
|
||||
assert manifest["unchanged"] == 1 and manifest["bundled"] == 1
|
||||
assert "1 unchanged" in summary
|
||||
|
||||
|
||||
def test_repo_missing_from_s3_is_bundled():
|
||||
pages = [[_make_repo("nomadkaraoke", "new", pushed_at="2026-01-01T00:00:00Z")]]
|
||||
_, uploads, _ = _run(pages, existing_backups={})
|
||||
assert "git-repos/nomadkaraoke/new.bundle" in uploads
|
||||
|
||||
|
||||
def test_push_just_before_upload_is_rebundled():
|
||||
# Push landed 10 min before the bundle hit S3 — it may have been after the
|
||||
# clone, so it must NOT be treated as backed up.
|
||||
pages = [[_make_repo("nomadkaraoke", "racy", pushed_at="2026-09-13T04:50:00Z")]]
|
||||
existing = {"git-repos/nomadkaraoke/racy.bundle": _utc("2026-09-13T05:00:00")}
|
||||
_, uploads, _ = _run(pages, existing_backups=existing)
|
||||
assert "git-repos/nomadkaraoke/racy.bundle" in uploads
|
||||
|
||||
|
||||
def test_missing_pushed_at_is_bundled():
|
||||
pages = [[_make_repo("nomadkaraoke", "odd", pushed_at=None)]]
|
||||
existing = {"git-repos/nomadkaraoke/odd.bundle": _utc("2026-09-13T05:00:00")}
|
||||
_, uploads, _ = _run(pages, existing_backups=existing)
|
||||
assert "git-repos/nomadkaraoke/odd.bundle" in uploads
|
||||
|
||||
|
||||
def test_full_refresh_ignores_existing_backups():
|
||||
pages = [[_make_repo("nomadkaraoke", "quiet", pushed_at="2026-09-01T00:00:00Z")]]
|
||||
existing = {"git-repos/nomadkaraoke/quiet.bundle": _utc("2026-09-13T05:00:00")}
|
||||
_, uploads, _ = _run(pages, existing_backups=existing, full_refresh=True)
|
||||
assert "git-repos/nomadkaraoke/quiet.bundle" in uploads
|
||||
assert _manifest(uploads)["full_refresh"] is True
|
||||
|
||||
|
||||
def test_changed_repos_all_failing_is_systemic_even_with_unchanged():
|
||||
# In incremental mode nearly every repo is "unchanged"; if every repo that
|
||||
# actually needed bundling failed, that must still surface as a failure.
|
||||
def side_effect(cmd, **kw):
|
||||
raise subprocess.CalledProcessError(128, cmd, output=b"", stderr=b"fatal: not found")
|
||||
|
||||
pages = [[
|
||||
_make_repo("nomadkaraoke", "quiet", pushed_at="2026-09-01T00:00:00Z"),
|
||||
_make_repo("nomadkaraoke", "broken", pushed_at="2026-09-20T00:00:00Z"),
|
||||
]]
|
||||
existing = {"git-repos/nomadkaraoke/quiet.bundle": _utc("2026-09-13T05:00:00")}
|
||||
client, uploads = _fake_gcs()
|
||||
with patch("git_repos_export.requests.get", side_effect=_fake_requests_get(pages)), \
|
||||
patch("git_repos_export.gcs_storage.Client", return_value=client), \
|
||||
patch("git_repos_export.shutil.which", return_value="/usr/bin/git"), \
|
||||
patch("git_repos_export.subprocess.run", side_effect=side_effect), \
|
||||
patch("git_repos_export.tempfile.mkdtemp", return_value="/tmp/gitbak-x"), \
|
||||
patch("git_repos_export.shutil.rmtree"):
|
||||
with pytest.raises(RuntimeError, match="1 unchanged, 1 errors"):
|
||||
export_git_repos(
|
||||
staging_bucket="staging",
|
||||
github_token="ghp_test",
|
||||
owners=["nomadkaraoke"],
|
||||
existing_backups=existing,
|
||||
)
|
||||
manifest = _manifest(uploads)
|
||||
assert manifest["errors"] == 1 and manifest["unchanged"] == 1
|
||||
|
||||
|
||||
def test_all_unchanged_is_green():
|
||||
pages = [[_make_repo("nomadkaraoke", "quiet", pushed_at="2026-09-01T00:00:00Z")]]
|
||||
existing = {"git-repos/nomadkaraoke/quiet.bundle": _utc("2026-09-13T05:00:00")}
|
||||
summary, uploads, run_mock = _run(pages, existing_backups=existing)
|
||||
run_mock.assert_not_called()
|
||||
assert "Bundled 0/1 repos (1 unchanged" in summary
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Tests for main.backup_to_aws cadence gating (weekly git step, S3 excludes)."""
|
||||
|
||||
import datetime
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import main
|
||||
|
||||
|
||||
class _FakeDate(datetime.date):
|
||||
today_value = datetime.date(2026, 9, 28) # a Monday
|
||||
|
||||
@classmethod
|
||||
def today(cls):
|
||||
return cls.today_value
|
||||
|
||||
|
||||
def _run(today):
|
||||
_FakeDate.today_value = today
|
||||
request = MagicMock()
|
||||
request.args = {}
|
||||
with patch("main.datetime.date", _FakeDate), \
|
||||
patch("main.export_firestore", return_value="fs"), \
|
||||
patch("main.export_bigquery_tables", return_value={}), \
|
||||
patch("main.sync_gcs_to_staging", return_value="gcs"), \
|
||||
patch("main.export_secrets", return_value="sec"), \
|
||||
patch("main._run_git_repos_backup", return_value="git") as git, \
|
||||
patch("main.upload_staging_to_s3", return_value="s3") as upload, \
|
||||
patch("main.send_alert"):
|
||||
main.backup_to_aws(request)
|
||||
return git, upload
|
||||
|
||||
|
||||
def test_weekday_skips_git_and_holds_back_firestore_and_git_repos():
|
||||
git, upload = _run(datetime.date(2026, 9, 29)) # Tuesday
|
||||
git.assert_not_called()
|
||||
assert set(upload.call_args.kwargs["exclude_prefixes"]) == {"firestore/", "git-repos/"}
|
||||
|
||||
|
||||
def test_sunday_runs_incremental_git_and_uploads_everything():
|
||||
git, upload = _run(datetime.date(2026, 9, 27)) # Sunday, day 27
|
||||
git.assert_called_once_with(full_refresh=False)
|
||||
assert upload.call_args.kwargs["exclude_prefixes"] == []
|
||||
|
||||
|
||||
def test_first_sunday_of_month_is_full_refresh():
|
||||
git, _ = _run(datetime.date(2026, 10, 4)) # first Sunday of October
|
||||
git.assert_called_once_with(full_refresh=True)
|
||||
|
||||
|
||||
def test_manual_git_mode_only_uploads_git_prefix():
|
||||
request = MagicMock()
|
||||
request.args = {"mode": "git_repos", "full": "1"}
|
||||
with patch("main._run_git_repos_backup", return_value="git") as git, \
|
||||
patch("main.upload_staging_to_s3", return_value="s3") as upload, \
|
||||
patch("main.export_firestore") as fs:
|
||||
body, status = main.backup_to_aws(request)
|
||||
assert status == 200
|
||||
git.assert_called_once_with(full_refresh=True)
|
||||
assert upload.call_args.kwargs["include_prefixes"] == ["git-repos/"]
|
||||
fs.assert_not_called()
|
||||
@@ -3,9 +3,22 @@
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
_NOT_FOUND = ClientError({"Error": {"Code": "404"}}, "HeadObject")
|
||||
def _set_s3_listing(client, objects):
|
||||
"""Make the S3 client's list_objects_v2 paginator serve ``objects``
|
||||
({key: size}), filtered by Prefix + Delimiter like real S3."""
|
||||
|
||||
def paginate(Bucket, Prefix="", Delimiter=None):
|
||||
contents = []
|
||||
for key, size in objects.items():
|
||||
if not key.startswith(Prefix):
|
||||
continue
|
||||
if Delimiter and Delimiter in key[len(Prefix):]:
|
||||
continue
|
||||
contents.append({"Key": key, "Size": size})
|
||||
return [{"Contents": contents}]
|
||||
|
||||
client.get_paginator.return_value.paginate.side_effect = paginate
|
||||
|
||||
|
||||
def _blob(name, size=1234, crc32c=None):
|
||||
@@ -20,9 +33,9 @@ def _blob(name, size=1234, crc32c=None):
|
||||
|
||||
|
||||
def _mock_boto(mock_boto):
|
||||
"""Default: nothing exists in S3 yet (HEAD -> 404), so everything uploads."""
|
||||
"""Default: nothing exists in S3 yet, so everything uploads."""
|
||||
client = mock_boto.return_value
|
||||
client.head_object.side_effect = _NOT_FOUND
|
||||
_set_s3_listing(client, {})
|
||||
return client
|
||||
|
||||
|
||||
@@ -106,12 +119,7 @@ class TestUploadStagingToS3(unittest.TestCase):
|
||||
present = _blob("gcs/job-files/jobs/abc/finals/portrait_1080x1920.mp4", size=999)
|
||||
fresh = _blob("secrets/2026-09-15.bin", size=42)
|
||||
|
||||
def head(Bucket, Key):
|
||||
if Key == present.name:
|
||||
return {"ContentLength": 999}
|
||||
raise _NOT_FOUND
|
||||
|
||||
client.head_object.side_effect = head
|
||||
_set_s3_listing(client, {present.name: 999})
|
||||
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [present, fresh]
|
||||
|
||||
upload_staging_to_s3("staging", "s3b")
|
||||
@@ -166,5 +174,79 @@ class TestUploadStagingToS3(unittest.TestCase):
|
||||
self.assertEqual(bulk_phase, [final.name])
|
||||
|
||||
|
||||
@patch("s3_upload.boto3.client")
|
||||
@patch("s3_upload.storage.Client")
|
||||
@patch("s3_upload.get_aws_credentials")
|
||||
def test_never_uses_head_object(self, mock_creds, mock_storage, mock_boto):
|
||||
"""Regression (2026-09-14..26 outage): the backup-writer IAM user lacks
|
||||
s3:GetObject, so HEAD on an existing key returns 403. Existence must come from listing."""
|
||||
from s3_upload import upload_staging_to_s3
|
||||
|
||||
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
|
||||
client = _mock_boto(mock_boto)
|
||||
client.head_object.side_effect = AssertionError("HEAD must not be called")
|
||||
blob = _blob("secrets/2026-09-27.bin")
|
||||
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [blob]
|
||||
|
||||
summary = upload_staging_to_s3("staging", "s3b")
|
||||
|
||||
self.assertEqual(client.upload_fileobj.call_count, 1)
|
||||
self.assertNotIn("errors", summary)
|
||||
|
||||
@patch("s3_upload.boto3.client")
|
||||
@patch("s3_upload.storage.Client")
|
||||
@patch("s3_upload.get_aws_credentials")
|
||||
def test_git_repos_always_overwritten_even_if_same_size(self, mock_creds, mock_storage, mock_boto):
|
||||
"""A changed bundle can keep its byte size; git-repos/ is only staged
|
||||
when it changed, so it must upload regardless of the size match."""
|
||||
from s3_upload import upload_staging_to_s3
|
||||
|
||||
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
|
||||
client = mock_boto.return_value
|
||||
bundle = _blob("git-repos/nomadkaraoke/karaoke-gen.bundle", size=500)
|
||||
manifest = _blob("git-repos/manifest.json", size=77)
|
||||
_set_s3_listing(client, {bundle.name: 500, manifest.name: 77})
|
||||
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [bundle, manifest]
|
||||
|
||||
upload_staging_to_s3("staging", "s3b")
|
||||
|
||||
uploaded = {c.kwargs["Key"] for c in client.upload_fileobj.call_args_list}
|
||||
self.assertEqual(uploaded, {bundle.name, manifest.name})
|
||||
|
||||
@patch("s3_upload.boto3.client")
|
||||
@patch("s3_upload.storage.Client")
|
||||
@patch("s3_upload.get_aws_credentials")
|
||||
def test_include_prefixes_limits_upload(self, mock_creds, mock_storage, mock_boto):
|
||||
from s3_upload import upload_staging_to_s3
|
||||
|
||||
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
|
||||
client = _mock_boto(mock_boto)
|
||||
git = _blob("git-repos/manifest.json")
|
||||
sec = _blob("secrets/2026-09-27.bin")
|
||||
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [git, sec]
|
||||
|
||||
upload_staging_to_s3("staging", "s3b", include_prefixes=["git-repos/"])
|
||||
|
||||
self.assertEqual(client.upload_fileobj.call_count, 1)
|
||||
self.assertEqual(client.upload_fileobj.call_args.kwargs["Key"], git.name)
|
||||
sec.delete.assert_not_called()
|
||||
|
||||
|
||||
class TestListS3Objects(unittest.TestCase):
|
||||
def test_returns_key_to_last_modified(self):
|
||||
from s3_upload import list_s3_objects
|
||||
|
||||
client = MagicMock()
|
||||
client.get_paginator.return_value.paginate.return_value = [
|
||||
{"Contents": [{"Key": "git-repos/a/b.bundle", "LastModified": "t1"}]},
|
||||
{"Contents": [{"Key": "git-repos/a/c.bundle", "LastModified": "t2"}]},
|
||||
{},
|
||||
]
|
||||
self.assertEqual(
|
||||
list_s3_objects(client, "s3b", "git-repos/"),
|
||||
{"git-repos/a/b.bundle": "t1", "git-repos/a/c.bundle": "t2"},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Encoding Worker Idle Shutdown Cloud Function.
|
||||
|
||||
Triggered by Cloud Scheduler every 5 minutes. Checks all encoding worker
|
||||
Triggered by Cloud Scheduler every 2 minutes. Checks all encoding worker
|
||||
VMs (primary, secondary, AND multi-zone fallbacks) and stops any that
|
||||
are idle. Without checking the fallbacks, a fallback VM started during a
|
||||
capacity event could be left running indefinitely after the event clears
|
||||
@@ -11,7 +11,7 @@ iterated primary/secondary in the default zone.
|
||||
|
||||
Idle criteria (all must be true to stop a VM):
|
||||
- No active encoding jobs (from /health endpoint active_jobs)
|
||||
- No recent user activity (from Firestore last_activity_at > 15 min)
|
||||
- No recent user activity (from Firestore last_activity_at > IDLE_TIMEOUT_MINUTES)
|
||||
- Only applies to the *currently routed* VM: `active_override_vm` if
|
||||
set, else primary. Secondary and non-active fallbacks always stop on
|
||||
idle so they don't leak after a capacity event.
|
||||
@@ -20,7 +20,8 @@ Idle criteria (all must be true to stop a VM):
|
||||
Environment variables:
|
||||
- GCP_PROJECT: GCP project ID (default: nomadkaraoke)
|
||||
- GCP_ZONE: Default zone for primary/secondary (default: us-central1-c)
|
||||
- IDLE_TIMEOUT_MINUTES: Minutes of inactivity before shutdown (default: 15)
|
||||
- IDLE_TIMEOUT_MINUTES: Minutes of inactivity before shutdown (default: 5;
|
||||
Pulumi sets it from EncodingWorkerConfig.IDLE_TIMEOUT_MINUTES)
|
||||
- ENCODING_WORKER_FALLBACK_VMS: JSON list of {vm, zone, ip} for fallback
|
||||
VMs in alternate zones. Same secret the backend uses for multi-zone
|
||||
failover. Empty/missing → no fallbacks checked.
|
||||
@@ -40,7 +41,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
PROJECT_ID = os.environ.get("GCP_PROJECT", "nomadkaraoke")
|
||||
ZONE = os.environ.get("GCP_ZONE", "us-central1-c")
|
||||
IDLE_TIMEOUT_MINUTES = int(os.environ.get("IDLE_TIMEOUT_MINUTES", "15"))
|
||||
IDLE_TIMEOUT_MINUTES = int(os.environ.get("IDLE_TIMEOUT_MINUTES", "5"))
|
||||
DEPLOY_STALE_TIMEOUT_MINUTES = 20
|
||||
ENCODING_WORKER_PORT = 8080
|
||||
|
||||
@@ -218,7 +219,7 @@ def idle_shutdown(request):
|
||||
|
||||
# Fail SAFE: never stop a VM unless /health gives us a *confirmed*
|
||||
# active_jobs == 0. If we can't reach the VM or confirm its job count,
|
||||
# keep it alive this cycle (the function reruns every 5 min, so a
|
||||
# keep it alive this cycle (the function reruns every 2 min, so a
|
||||
# genuinely idle VM is reclaimed once /health responds). This prevents
|
||||
# stopping a VM mid-render — the cause of "lost contact with worker"
|
||||
# (incident 2026-06-15).
|
||||
|
||||
@@ -107,7 +107,7 @@ class TestIdleShutdown:
|
||||
|
||||
def test_skips_deploy_in_progress(self, mock_compute, mock_firestore):
|
||||
"""Should skip idle check when a deploy is in progress."""
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=2)).isoformat()
|
||||
config = _make_config(
|
||||
deploy_in_progress=True,
|
||||
deploy_in_progress_since=recent,
|
||||
@@ -147,7 +147,7 @@ class TestIdleShutdown:
|
||||
|
||||
def test_recent_activity_keeps_primary_alive(self, mock_compute, mock_firestore):
|
||||
"""Recent activity should keep the primary VM alive but stop the secondary."""
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=2)).isoformat()
|
||||
config = _make_config(last_activity_at=recent)
|
||||
_setup_firestore(mock_firestore, config)
|
||||
|
||||
@@ -163,6 +163,33 @@ class TestIdleShutdown:
|
||||
# Only secondary should be stopped
|
||||
assert mock_compute.stop.call_count == 1
|
||||
|
||||
def test_default_idle_timeout_is_five_minutes(self):
|
||||
"""2026-09-26 cost cut: idle VMs stop after 5 min (was 15)."""
|
||||
assert main.IDLE_TIMEOUT_MINUTES == 5
|
||||
|
||||
def test_review_heartbeat_within_timeout_keeps_primary_alive(self, mock_compute, mock_firestore):
|
||||
"""The lyrics-review page heartbeats every ~2 min; a heartbeat 4 min ago is
|
||||
still inside the 5-min window, so the warm primary must NOT be stopped
|
||||
while someone is reviewing (it's kept warm for the preview + final render)."""
|
||||
heartbeat = (datetime.now(timezone.utc) - timedelta(minutes=4)).isoformat()
|
||||
_setup_firestore(mock_firestore, _make_config(last_activity_at=heartbeat))
|
||||
mock_compute.get.return_value = _make_instance(status="RUNNING", ip="1.2.3.4")
|
||||
|
||||
with patch("main.check_active_jobs", return_value=0):
|
||||
response, _ = main.idle_shutdown(MagicMock())
|
||||
|
||||
assert json.loads(response)["results"]["encoding-worker-a"] == "active_session"
|
||||
|
||||
def test_activity_older_than_timeout_stops_idle_primary(self, mock_compute, mock_firestore):
|
||||
stale = (datetime.now(timezone.utc) - timedelta(minutes=6)).isoformat()
|
||||
_setup_firestore(mock_firestore, _make_config(last_activity_at=stale))
|
||||
mock_compute.get.return_value = _make_instance(status="RUNNING", ip="1.2.3.4")
|
||||
|
||||
with patch("main.check_active_jobs", return_value=0):
|
||||
response, _ = main.idle_shutdown(MagicMock())
|
||||
|
||||
assert json.loads(response)["results"]["encoding-worker-a"] == "stopped"
|
||||
|
||||
def test_skips_terminated_vms(self, mock_compute, mock_firestore):
|
||||
"""VMs that are already TERMINATED should be skipped."""
|
||||
config = _make_config()
|
||||
@@ -299,7 +326,7 @@ class TestFallbackVms:
|
||||
def test_idle_fallback_gets_stopped(self, mock_compute, mock_firestore, fallback_env):
|
||||
"""A fallback VM that's RUNNING but idle (no jobs, not active) must be stopped.
|
||||
This is the bug the fix addresses — previously fallbacks were never checked."""
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=2)).isoformat()
|
||||
config = _make_config(last_activity_at=recent)
|
||||
_setup_firestore(mock_firestore, config)
|
||||
|
||||
@@ -345,7 +372,7 @@ class TestFallbackVms:
|
||||
{"vm": "encoding-worker-fallback-n2f", "zone": "us-central1-f", "ip": "4.4.4.4"},
|
||||
]),
|
||||
)
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=2)).isoformat()
|
||||
_setup_firestore(mock_firestore, _make_config(last_activity_at=recent))
|
||||
|
||||
# Only the n2-f fallback is RUNNING+idle → it must be stopped in -f.
|
||||
@@ -376,7 +403,7 @@ class TestFallbackVms:
|
||||
"""When a capacity-fallback override is set, that fallback is the
|
||||
currently-routed VM and gets the keep-alive treatment (matching
|
||||
what primary normally gets). Primary should still stop on idle."""
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=2)).isoformat()
|
||||
config = {
|
||||
**_make_config(last_activity_at=recent),
|
||||
"active_override_vm": "encoding-worker-fallback-a",
|
||||
|
||||
@@ -12,7 +12,6 @@ from . import cloud_tasks
|
||||
from . import cloud_run
|
||||
from . import monitoring
|
||||
from . import iam
|
||||
from . import networking
|
||||
from . import runner_manager
|
||||
|
||||
__all__ = [
|
||||
@@ -24,6 +23,5 @@ __all__ = [
|
||||
"cloud_run",
|
||||
"monitoring",
|
||||
"iam",
|
||||
"networking",
|
||||
"runner_manager",
|
||||
]
|
||||
@@ -271,33 +271,23 @@ def create_audio_separation_job(
|
||||
def create_audio_download_job(
|
||||
bucket: gcp.storage.Bucket,
|
||||
service_account: gcp.serviceaccount.Account,
|
||||
vpc_connector: object = None,
|
||||
) -> cloudrunv2.Job:
|
||||
"""
|
||||
Create the Cloud Run Job for audio downloading.
|
||||
|
||||
Downloads audio from Spotify/YouTube/RED/OPS via the flacfetch VM,
|
||||
then triggers audio separation and lyrics workers.
|
||||
|
||||
Requires VPC access to reach the flacfetch VM on its internal IP.
|
||||
Downloads audio from Spotify/YouTube/RED/OPS via the flacfetch service
|
||||
(public HTTPS URL from the flacfetch-api-url secret), then triggers audio
|
||||
separation and lyrics workers.
|
||||
|
||||
Typical duration: 30s-5 minutes (depending on source)
|
||||
|
||||
Args:
|
||||
bucket: The GCS bucket for job artifacts.
|
||||
service_account: The service account to run the job.
|
||||
vpc_connector: VPC connector for accessing flacfetch VM (optional).
|
||||
|
||||
Returns:
|
||||
cloudrunv2.Job: The Cloud Run Job resource.
|
||||
"""
|
||||
# Build VPC access config if connector provided
|
||||
vpc_access = None
|
||||
if vpc_connector:
|
||||
vpc_access = cloudrunv2.JobTemplateTemplateVpcAccessArgs(
|
||||
connector=vpc_connector.id,
|
||||
egress="PRIVATE_RANGES_ONLY",
|
||||
)
|
||||
|
||||
audio_download_job = cloudrunv2.Job(
|
||||
"audio-download-job",
|
||||
@@ -351,7 +341,7 @@ def create_audio_download_job(
|
||||
),
|
||||
),
|
||||
),
|
||||
# Flacfetch API URL (internal VPC address)
|
||||
# Flacfetch API URL (public HTTPS endpoint; no VPC egress)
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="FLACFETCH_API_URL",
|
||||
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
|
||||
@@ -398,7 +388,6 @@ def create_audio_download_job(
|
||||
# strictly below this so it fails cleanly before Cloud Run kills it.
|
||||
timeout="1200s",
|
||||
max_retries=2,
|
||||
vpc_access=vpc_access,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -409,25 +398,18 @@ def create_audio_download_job(
|
||||
def create_bulk_search_job(
|
||||
bucket: gcp.storage.Bucket,
|
||||
service_account: gcp.serviceaccount.Account,
|
||||
vpc_connector: object = None,
|
||||
) -> cloudrunv2.Job:
|
||||
"""
|
||||
Create the Cloud Run Job for Bulk Mode batch audio search.
|
||||
|
||||
Processes every job in a batch (state_data.batch_id): runs each audio search
|
||||
via the flacfetch VM, auto-selects confident lossless matches (triggering the
|
||||
via flacfetch, auto-selects confident lossless matches (triggering the
|
||||
audio-download-job), and parks the rest in AWAITING_AUDIO_SELECTION.
|
||||
|
||||
Requires VPC access to reach the flacfetch VM. Longer timeout than the download
|
||||
Longer timeout than the download
|
||||
job because a batch can contain up to 100 songs. Idempotent across retries
|
||||
(only re-processes jobs still flagged bulk_pending_search), so retries=1.
|
||||
"""
|
||||
vpc_access = None
|
||||
if vpc_connector:
|
||||
vpc_access = cloudrunv2.JobTemplateTemplateVpcAccessArgs(
|
||||
connector=vpc_connector.id,
|
||||
egress="PRIVATE_RANGES_ONLY",
|
||||
)
|
||||
|
||||
bulk_search_job = cloudrunv2.Job(
|
||||
"bulk-search-job",
|
||||
@@ -503,7 +485,6 @@ def create_bulk_search_job(
|
||||
service_account=service_account.email,
|
||||
timeout="3600s", # up to 100 songs per batch
|
||||
max_retries=1,
|
||||
vpc_access=vpc_access,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -29,7 +29,9 @@ def create_database() -> dict:
|
||||
type="FIRESTORE_NATIVE",
|
||||
concurrency_mode="PESSIMISTIC",
|
||||
app_engine_integration_mode="DISABLED",
|
||||
point_in_time_recovery_enablement="POINT_IN_TIME_RECOVERY_ENABLED",
|
||||
# PITR disabled 2026-09-26 (cost cut): the backup-to-aws function exports
|
||||
# Firestore nightly to GCS staging (1-day local RPO) and weekly to S3.
|
||||
point_in_time_recovery_enablement="POINT_IN_TIME_RECOVERY_DISABLED",
|
||||
)
|
||||
resources["firestore_db"] = firestore_db
|
||||
|
||||
|
||||
@@ -80,6 +80,15 @@ def create_divebar_mirror_resources(all_secrets: dict) -> dict:
|
||||
force_destroy=False, # Protect against accidental deletion
|
||||
uniform_bucket_level_access=True,
|
||||
versioning=storage.BucketVersioningArgs(enabled=False),
|
||||
# Autoclass (2026-09-26 GCP cost cut): mirror files are read sparsely
|
||||
# (kjbox on-demand downloads), so let untouched files walk down to
|
||||
# Nearline (30d) -> Coldline (90d) -> Archive (365d). Autoclass charges
|
||||
# no retrieval/early-deletion fees and any read moves the object back
|
||||
# to Standard, so the ARCHIVE terminal class has no access penalty.
|
||||
autoclass=storage.BucketAutoclassArgs(
|
||||
enabled=True,
|
||||
terminal_storage_class="ARCHIVE",
|
||||
),
|
||||
)
|
||||
resources["files_bucket"] = files_bucket
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Error Monitor Cloud Run Job and Cloud Scheduler resources.
|
||||
|
||||
Deploys the error monitor as a Cloud Run Job triggered by Cloud Scheduler
|
||||
every 15 minutes (error checks) and daily at 08:00 UTC (digest report).
|
||||
hourly (error checks) and daily at 08:00 UTC (digest report).
|
||||
"""
|
||||
|
||||
import base64
|
||||
@@ -134,11 +134,11 @@ def create_error_monitor(
|
||||
# Shared opts: schedulers depend on IAM binding being in place first
|
||||
scheduler_opts = pulumi.ResourceOptions(depends_on=[error_monitor_job_invoker])
|
||||
|
||||
# ---- Cloud Scheduler: every-15-min monitor ----
|
||||
# ---- Cloud Scheduler: hourly monitor ----
|
||||
monitor_scheduler = cloudscheduler.Job(
|
||||
"error-monitor-scheduler",
|
||||
name="error-monitor-trigger",
|
||||
description="Trigger error monitor Cloud Run Job every 15 minutes",
|
||||
description="Trigger error monitor Cloud Run Job hourly",
|
||||
region=REGION,
|
||||
schedule=ErrorMonitorConfig.MONITOR_SCHEDULE,
|
||||
time_zone="UTC",
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
"""
|
||||
Networking resources for serverless VPC access.
|
||||
|
||||
Manages VPC connectors that allow Cloud Run to access internal VPC resources
|
||||
like the flacfetch VM via its internal IP address.
|
||||
"""
|
||||
|
||||
import pulumi
|
||||
import pulumi_gcp as gcp
|
||||
from pulumi_gcp import vpcaccess
|
||||
|
||||
from config import PROJECT_ID, REGION
|
||||
|
||||
|
||||
def enable_vpc_access_api() -> gcp.projects.Service:
|
||||
"""Enable the Serverless VPC Access API."""
|
||||
return gcp.projects.Service(
|
||||
"enable-vpcaccess-api",
|
||||
service="vpcaccess.googleapis.com",
|
||||
project=PROJECT_ID,
|
||||
disable_on_destroy=False,
|
||||
)
|
||||
|
||||
|
||||
def create_vpc_connector(
|
||||
api_service: gcp.projects.Service,
|
||||
) -> vpcaccess.Connector:
|
||||
"""
|
||||
Create VPC connector for Cloud Run to access internal resources.
|
||||
|
||||
Uses 10.8.0.0/28 which doesn't overlap with default subnet (10.128.0.0/20).
|
||||
This allows Cloud Run to reach VMs like flacfetch via their internal IPs,
|
||||
bypassing external firewall rules.
|
||||
|
||||
Args:
|
||||
api_service: The VPC Access API service (ensures API is enabled first).
|
||||
|
||||
Returns:
|
||||
vpcaccess.Connector: The VPC connector resource.
|
||||
"""
|
||||
return vpcaccess.Connector(
|
||||
"cloud-run-vpc-connector",
|
||||
name="cloud-run-connector",
|
||||
region=REGION,
|
||||
network="default",
|
||||
ip_cidr_range="10.8.0.0/28",
|
||||
min_instances=2,
|
||||
max_instances=3,
|
||||
machine_type="e2-micro",
|
||||
opts=pulumi.ResourceOptions(depends_on=[api_service]),
|
||||
)
|
||||
@@ -43,6 +43,16 @@ def create_bucket() -> storage.Bucket:
|
||||
),
|
||||
],
|
||||
versioning=storage.BucketVersioningArgs(enabled=True),
|
||||
# Autoclass (2026-09-26 GCP cost cut): objects not read for 30 days move
|
||||
# to Nearline automatically and back to Standard on the next read, with
|
||||
# no retrieval or early-deletion fees (operations bill at Standard
|
||||
# rates). Terminal class NEARLINE (not ARCHIVE) because customers
|
||||
# re-download old job outputs. Incompatible with lifecycle
|
||||
# SetStorageClass rules — only Delete rules may live below.
|
||||
autoclass=storage.BucketAutoclassArgs(
|
||||
enabled=True,
|
||||
terminal_storage_class="NEARLINE",
|
||||
),
|
||||
soft_delete_policy=storage.BucketSoftDeletePolicyArgs(retention_duration_seconds=604800),
|
||||
lifecycle_rules=[
|
||||
storage.BucketLifecycleRuleArgs(
|
||||
|
||||
@@ -10,19 +10,40 @@ Run locally with: `pytest infrastructure/test_encoding_worker_config.py`
|
||||
resource graph via `pulumi preview`).
|
||||
"""
|
||||
|
||||
from config import EncodingWorkerConfig, MachineTypes
|
||||
from config import ENCODING_WORKER_ZONE, EncodingWorkerConfig, MachineTypes
|
||||
|
||||
|
||||
def test_fallback_fleet_has_machine_family_diversity():
|
||||
"""At least one fallback must use a machine family OTHER than the primary,
|
||||
otherwise a single-family stockout takes out every lane at once."""
|
||||
families = {fb["machine_type"] for fb in EncodingWorkerConfig.FALLBACKS}
|
||||
assert MachineTypes.ENCODING_WORKER in families
|
||||
assert any(mt != MachineTypes.ENCODING_WORKER for mt in families), (
|
||||
"fallback fleet is single-machine-family — a c4d stockout would exhaust "
|
||||
"every lane (see incident 2026-08-12)"
|
||||
)
|
||||
assert MachineTypes.ENCODING_WORKER_ALT in families
|
||||
def test_fallback_is_a_different_machine_family_and_zone_from_primary():
|
||||
"""The on-demand fallback must not share the Spot pair's family or zone,
|
||||
otherwise a single c4d / Spot / zone stockout takes out every lane at once
|
||||
(incident 2026-08-12)."""
|
||||
assert EncodingWorkerConfig.FALLBACKS, "need at least one capacity fallback"
|
||||
primary_family = _family(MachineTypes.ENCODING_WORKER)
|
||||
primary_zone_suffix = ENCODING_WORKER_ZONE.rsplit("-", 1)[1]
|
||||
for fb in EncodingWorkerConfig.FALLBACKS:
|
||||
assert _family(fb["machine_type"]) != primary_family, fb
|
||||
assert fb["zone_suffix"] != primary_zone_suffix, fb
|
||||
|
||||
|
||||
def test_fleet_is_cost_cut_shape():
|
||||
"""2026-09-26 cost cut: Spot a/b pair + exactly one on-demand fallback, all
|
||||
16 vCPU. Growing this again should be a deliberate decision (update the
|
||||
fallback secret + docs), not an accident."""
|
||||
assert len(EncodingWorkerConfig.VM_NAMES) == 2
|
||||
assert len(EncodingWorkerConfig.FALLBACKS) == 1
|
||||
assert EncodingWorkerConfig.PRIMARY_PAIR_SPOT is True
|
||||
for mt in [MachineTypes.ENCODING_WORKER] + [fb["machine_type"] for fb in EncodingWorkerConfig.FALLBACKS]:
|
||||
assert mt.endswith("-16"), mt
|
||||
|
||||
|
||||
def test_idle_shutdown_is_fast_but_outlives_review_heartbeat():
|
||||
"""Idle VMs stop after 5 min, checked every 2 min. The lyrics-review page
|
||||
heartbeats every 2 min (frontend REVIEW_HEARTBEAT_INTERVAL_MS) so an active
|
||||
review keeps the warm VM alive — the timeout must leave margin over it."""
|
||||
assert EncodingWorkerConfig.IDLE_TIMEOUT_MINUTES == 5
|
||||
assert EncodingWorkerConfig.IDLE_CHECK_SCHEDULE == "*/2 * * * *"
|
||||
review_heartbeat_minutes = 2
|
||||
assert EncodingWorkerConfig.IDLE_TIMEOUT_MINUTES >= 2 * review_heartbeat_minutes
|
||||
|
||||
|
||||
def test_n2_fallbacks_use_pd_balanced_disk():
|
||||
@@ -65,18 +86,6 @@ def test_every_fallback_disk_type_matches_its_family_capability():
|
||||
assert fb["disk_type"] == _FAMILY_DISK_TYPE[fam], fb
|
||||
|
||||
|
||||
def test_pool_has_at_least_five_types_across_multiple_lineages():
|
||||
"""The broadened pool must be ≥5 distinct machine types spanning ≥3 lineages
|
||||
(AMD Turin / Intel Emerald / AMD Milan / Intel Cascade / AMD Rome) so a
|
||||
newest-gen stockout can't exhaust every lane."""
|
||||
types = {fb["machine_type"] for fb in EncodingWorkerConfig.FALLBACKS}
|
||||
# primary (c4d) + the fallback types.
|
||||
types.add(MachineTypes.ENCODING_WORKER)
|
||||
assert len(types) >= 5, f"pool has only {len(types)} types: {types}"
|
||||
families = {_family(mt) for mt in types}
|
||||
assert len(families) >= 3, f"pool spans only {families}"
|
||||
|
||||
|
||||
def test_zone_spread_avoids_same_type_same_zone():
|
||||
"""No machine type should sit twice in the same zone (correlated stockout)."""
|
||||
seen = set()
|
||||
@@ -102,18 +111,6 @@ def test_fallback_names_and_ips_are_unique_and_aligned():
|
||||
assert len(set(EncodingWorkerConfig.FALLBACK_IP_NAMES)) == len(fb)
|
||||
|
||||
|
||||
def test_original_c4d_fallbacks_unchanged():
|
||||
"""The first two entries must remain the original c4d a/b fallbacks
|
||||
(byte-identical) so `pulumi up` does NOT recreate the existing VMs —
|
||||
recreating a c4d VM would need the very capacity we're trying to avoid
|
||||
depending on."""
|
||||
a, b = EncodingWorkerConfig.FALLBACKS[0], EncodingWorkerConfig.FALLBACKS[1]
|
||||
assert a == {"suffix": "a", "zone_suffix": "a",
|
||||
"machine_type": MachineTypes.ENCODING_WORKER, "disk_type": "hyperdisk-balanced"}
|
||||
assert b == {"suffix": "b", "zone_suffix": "b",
|
||||
"machine_type": MachineTypes.ENCODING_WORKER, "disk_type": "hyperdisk-balanced"}
|
||||
|
||||
|
||||
def test_worker_boot_disk_fits_packer_image_size():
|
||||
"""GCE cannot create a boot disk smaller than its source image's disk size.
|
||||
The Packer image's `disk_size` must stay <= DiskSizes.ENCODING_WORKER, or
|
||||
|
||||
@@ -2127,6 +2127,9 @@ class JobMonitor:
|
||||
}
|
||||
|
||||
for key, blob_path in stems.items():
|
||||
# Review-waveform-only approximation (mix − user instrumental), not a deliverable
|
||||
if key == 'vocals_derived':
|
||||
continue
|
||||
if blob_path:
|
||||
# Use descriptive filename if available, otherwise use GCS filename
|
||||
filename = stem_name_mappings.get(key, Path(blob_path).name)
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.244.0"
|
||||
version = "0.245.2"
|
||||
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"
|
||||
|
||||
@@ -26,7 +26,7 @@ class TestMonitoredServiceLists:
|
||||
def test_cloud_run_jobs_count(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert len(config.MONITORED_CLOUD_RUN_JOBS) == 4
|
||||
assert len(config.MONITORED_CLOUD_RUN_JOBS) == 5
|
||||
|
||||
def test_cloud_run_jobs_contains_expected(self):
|
||||
from backend.services.error_monitor import config
|
||||
@@ -35,6 +35,7 @@ class TestMonitoredServiceLists:
|
||||
assert "lyrics-transcription-job" in config.MONITORED_CLOUD_RUN_JOBS
|
||||
assert "audio-separation-job" in config.MONITORED_CLOUD_RUN_JOBS
|
||||
assert "audio-download-job" in config.MONITORED_CLOUD_RUN_JOBS
|
||||
assert "mb-refresh" in config.MONITORED_CLOUD_RUN_JOBS
|
||||
|
||||
def test_gen2_cloud_functions_monitored_as_cloud_run_services(self):
|
||||
# Gen2 Cloud Functions log under resource.type=cloud_run_revision,
|
||||
@@ -98,12 +99,12 @@ class TestDefaultValues:
|
||||
def test_lookback_minutes_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.LOOKBACK_MINUTES == 15
|
||||
assert config.LOOKBACK_MINUTES == 60
|
||||
|
||||
def test_max_log_entries_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.MAX_LOG_ENTRIES == 500
|
||||
assert config.MAX_LOG_ENTRIES == 2000
|
||||
|
||||
def test_spike_multiplier_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
@@ -345,19 +345,19 @@ class TestIsSpike:
|
||||
m = _import_monitor_module()
|
||||
# rolling_counts of 1 each for the past 5 periods, current count = 10
|
||||
# avg = 1.0, SPIKE_MULTIPLIER=5.0, so 10 > 5 and 10 >= SPIKE_MIN_COUNT=5
|
||||
rolling_counts = [{"count": 1}, {"count": 1}, {"count": 1}, {"count": 1}, {"count": 1}]
|
||||
rolling_counts = [{"count": 1, "window_minutes": 60}, {"count": 1, "window_minutes": 60}, {"count": 1, "window_minutes": 60}, {"count": 1, "window_minutes": 60}, {"count": 1, "window_minutes": 60}]
|
||||
assert m._is_spike(current_count=10, rolling_counts=rolling_counts) is True
|
||||
|
||||
def test_rejects_non_spike_count(self):
|
||||
m = _import_monitor_module()
|
||||
rolling_counts = [{"count": 4}, {"count": 4}, {"count": 4}, {"count": 4}]
|
||||
rolling_counts = [{"count": 4, "window_minutes": 60}, {"count": 4, "window_minutes": 60}, {"count": 4, "window_minutes": 60}, {"count": 4, "window_minutes": 60}]
|
||||
# avg = 4.0, 5x = 20, current=5 → not a spike
|
||||
assert m._is_spike(current_count=5, rolling_counts=rolling_counts) is False
|
||||
|
||||
def test_rejects_spike_below_min_count(self):
|
||||
m = _import_monitor_module()
|
||||
# avg = 0.5, 5x = 2.5, current = 3 → exceeds multiplier but below SPIKE_MIN_COUNT
|
||||
rolling_counts = [{"count": 1}, {"count": 0}]
|
||||
rolling_counts = [{"count": 1, "window_minutes": 60}, {"count": 0, "window_minutes": 60}]
|
||||
assert m._is_spike(current_count=3, rolling_counts=rolling_counts) is False
|
||||
|
||||
def test_empty_rolling_counts_not_a_spike(self):
|
||||
@@ -375,16 +375,29 @@ class TestRollingAverage:
|
||||
|
||||
def test_computes_average_correctly(self):
|
||||
m = _import_monitor_module()
|
||||
rolling = [{"count": 2}, {"count": 4}, {"count": 6}]
|
||||
rolling = [{"count": 2, "window_minutes": 60}, {"count": 4, "window_minutes": 60}, {"count": 6, "window_minutes": 60}]
|
||||
result = m._rolling_average(rolling)
|
||||
assert result == pytest.approx(4.0)
|
||||
|
||||
def test_single_entry_returns_that_value(self):
|
||||
m = _import_monitor_module()
|
||||
rolling = [{"count": 7}]
|
||||
rolling = [{"count": 7, "window_minutes": 60}]
|
||||
result = m._rolling_average(rolling)
|
||||
assert result == pytest.approx(7.0)
|
||||
|
||||
def test_legacy_15_min_entries_scaled_to_current_window(self):
|
||||
m = _import_monitor_module()
|
||||
# Pre-2026-09-26 entries had no window_minutes and counted 15 min of
|
||||
# errors; at the 60-min cadence they must count 4x.
|
||||
rolling = [{"count": 2}, {"count": 8, "window_minutes": 60}]
|
||||
assert m._rolling_average(rolling) == pytest.approx((8.0 + 8.0) / 2)
|
||||
|
||||
def test_legacy_history_does_not_fake_a_spike(self):
|
||||
m = _import_monitor_module()
|
||||
# Steady 2 errors / 15 min == 8 / hour: an 8/hour run is not a spike.
|
||||
rolling = [{"count": 2}] * 10
|
||||
assert m._is_spike(current_count=8, rolling_counts=rolling) is False
|
||||
|
||||
def test_empty_list_returns_zero(self):
|
||||
m = _import_monitor_module()
|
||||
result = m._rolling_average([])
|
||||
@@ -392,7 +405,7 @@ class TestRollingAverage:
|
||||
|
||||
def test_counts_with_zeros(self):
|
||||
m = _import_monitor_module()
|
||||
rolling = [{"count": 0}, {"count": 0}, {"count": 10}]
|
||||
rolling = [{"count": 0, "window_minutes": 60}, {"count": 0, "window_minutes": 60}, {"count": 10, "window_minutes": 60}]
|
||||
result = m._rolling_average(rolling)
|
||||
assert result == pytest.approx(10 / 3)
|
||||
|
||||
@@ -849,7 +862,7 @@ class TestSpikeDetectionFlow:
|
||||
# avg=1.0, 5x=5.0, current_count=10 → spike detected
|
||||
monitor.firestore_adapter.get_pattern.return_value = {
|
||||
"pattern_id": "spike-pattern-1",
|
||||
"rolling_counts": [{"count": 1}, {"count": 1}, {"count": 1}, {"count": 1}],
|
||||
"rolling_counts": [{"count": 1, "window_minutes": 60}] * 4,
|
||||
}
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
|
||||
@@ -1888,6 +1888,32 @@ class TestJobMonitorDownloads:
|
||||
|
||||
mock_download.assert_called()
|
||||
|
||||
@patch.object(RemoteKaraokeClient, 'download_file_via_gsutil')
|
||||
@patch('pathlib.Path.mkdir')
|
||||
def test_download_outputs_skips_waveform_only_derived_vocals(self, mock_mkdir, mock_download, monitor, tmp_path):
|
||||
"""stems.vocals_derived (mix minus the user's instrumental) is a review-waveform
|
||||
aid, not a deliverable — it must not be downloaded as a vocals stem."""
|
||||
monitor.config.output_dir = str(tmp_path)
|
||||
mock_download.return_value = True
|
||||
|
||||
job_data = {
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Title",
|
||||
"state_data": {},
|
||||
"file_urls": {
|
||||
"stems": {
|
||||
"vocals_derived": "jobs/123/stems/vocals_derived.flac",
|
||||
"instrumental_clean": "jobs/123/stems/instrumental_clean.flac",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
monitor.download_outputs("job-123", job_data)
|
||||
|
||||
downloaded = " ".join(str(c) for c in mock_download.call_args_list)
|
||||
assert "vocals_derived" not in downloaded
|
||||
assert "instrumental_clean" in downloaded
|
||||
|
||||
@patch.object(RemoteKaraokeClient, 'download_file_via_gsutil')
|
||||
@patch('pathlib.Path.mkdir')
|
||||
def test_download_outputs_packages(self, mock_mkdir, mock_download, monitor, tmp_path):
|
||||
|
||||
Reference in new issue
Block a user