mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-05 01:26:07 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5181e42b46 | ||
|
|
eb1c914e4a | ||
|
|
b90ad82d90 | ||
|
|
0fa10e4330 | ||
|
|
8490ab75eb | ||
|
|
49464e8fcc | ||
|
|
e4dc50d9e3 | ||
|
|
dd795c66a0 | ||
|
|
17d60c58a0 |
No files matched your search
@@ -21,7 +21,7 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
variants:
|
||||
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all"'
|
||||
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all" (= all except build)'
|
||||
required: false
|
||||
default: 'all'
|
||||
skip_prune:
|
||||
@@ -55,7 +55,10 @@ jobs:
|
||||
run: |
|
||||
requested='${{ github.event.inputs.variants || 'all' }}'
|
||||
if [[ "$requested" == "all" || -z "$requested" ]]; then
|
||||
echo 'variants=["general","build","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
|
||||
# "build" (docker-build label) is excluded from "all": no job uses it
|
||||
# since deploy-backend moved to ubuntu-latest + Cloud Build
|
||||
# (2026-10-01). Still buildable via an explicit variants=build.
|
||||
echo 'variants=["general","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
json="$(echo "$requested" | tr ',' '\n' | jq -R . | jq -sc .)"
|
||||
echo "variants=$json" >> "$GITHUB_OUTPUT"
|
||||
|
||||
+155
-231
@@ -1033,6 +1033,11 @@ jobs:
|
||||
PR_NUM=""
|
||||
PR_TITLE=""
|
||||
fi
|
||||
# The backend deploy splices PR_TITLE into the comma-delimited
|
||||
# `gcloud run deploy --set-env-vars "...,PR_TITLE=..."` (inside a
|
||||
# double-quoted shell string): a comma in a PR title broke the v0.261.2
|
||||
# deploy. Commas → ';', drop newlines and shell-active chars.
|
||||
PR_TITLE=$(printf '%s' "$PR_TITLE" | tr ',' ';' | tr -d '\n\r"`$\\')
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
@@ -1090,7 +1095,10 @@ jobs:
|
||||
deploy-backend:
|
||||
name: "Deploy - Backend (Cloud Run)"
|
||||
needs: [package-build]
|
||||
runs-on: [self-hosted, linux, gcp, docker-build]
|
||||
# GitHub-hosted (free for this public repo). Docker images are built in
|
||||
# Cloud Build us-central1 (see "Build and push images" below), so nothing
|
||||
# large is pulled from Artifact Registry to this runner.
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -1117,28 +1125,6 @@ jobs:
|
||||
CPU_JOBS_REPOSITORY: karaoke-backend-gpu
|
||||
CPU_JOBS_IMAGE_NAME: karaoke-backend-cpu
|
||||
steps:
|
||||
- name: Check disk space (aggressive for Docker builds)
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 50 ]; then
|
||||
echo "Disk usage above 50%, cleaning unused images..."
|
||||
docker system prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After image cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Still above 70%, clearing build cache..."
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After build cache cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -1172,6 +1158,11 @@ jobs:
|
||||
PR_NUM=""
|
||||
PR_TITLE=""
|
||||
fi
|
||||
# The backend deploy splices PR_TITLE into the comma-delimited
|
||||
# `gcloud run deploy --set-env-vars "...,PR_TITLE=..."` (inside a
|
||||
# double-quoted shell string): a comma in a PR title broke the v0.261.2
|
||||
# deploy. Commas → ';', drop newlines and shell-active chars.
|
||||
PR_TITLE=$(printf '%s' "$PR_TITLE" | tr ',' ';' | tr -d '\n\r"`$\\')
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
@@ -1759,14 +1750,19 @@ jobs:
|
||||
gcloud auth configure-docker ${{ env.GPU_REGISTRY }} --quiet
|
||||
|
||||
# ============================================
|
||||
# Docker Build with BuildKit + Registry Cache
|
||||
# This replaces expensive Cloud Build with free GitHub Actions
|
||||
# Registry cache persists between builds for fast rebuilds
|
||||
# Image builds run in Cloud Build (us-central1), not on this runner.
|
||||
#
|
||||
# This job runs on a free GitHub-hosted runner. The app images are built
|
||||
# FROM large bases in us-central1 AR (CPU ~4.2 GB, GPU ~13 GB compressed);
|
||||
# pulling those to a GitHub-hosted runner is GCP internet egress
|
||||
# (~$0.12/GB → ~$2/deploy, far more than the old self-hosted build VM).
|
||||
# Cloud Build in us-central1 pulls them same-region (free) and the
|
||||
# e2-standard-2 default pool is in the 2,500 build-min/month free tier
|
||||
# (~7 min/deploy, CPU+GPU built in parallel). Only the hash checks below
|
||||
# (manifest + ~10KB config blob) touch AR from here.
|
||||
# See infrastructure/cloudbuild/build-backend-images.sh.
|
||||
# ============================================
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Calculate base image hash
|
||||
id: base-hash
|
||||
run: |
|
||||
@@ -1781,7 +1777,6 @@ jobs:
|
||||
BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest"
|
||||
|
||||
# Fetch hash label directly from registry (10KB config blob, not full image)
|
||||
# This avoids issues with stale local Docker cache on GitHub runners
|
||||
EXISTING_HASH=""
|
||||
|
||||
# Get the manifest (small JSON, ~1KB) - includes config digest
|
||||
@@ -1812,71 +1807,133 @@ jobs:
|
||||
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Build and push base image (if needed)
|
||||
if: steps.check-base.outputs.needs_rebuild == 'true'
|
||||
timeout-minutes: 20
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile.base
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:${{ github.sha }}
|
||||
# Registry cache for ALL layers (mode=max) - persists between builds
|
||||
# ignore-error=true allows build to continue if cache doesn't exist yet
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
build-args: |
|
||||
BUILD_DATE=${{ github.run_id }}
|
||||
BUILD_ID=${{ github.sha }}
|
||||
BASE_CONTENT_HASH=${{ steps.base-hash.outputs.hash }}
|
||||
# Provenance disabled for smaller image and faster push
|
||||
provenance: false
|
||||
|
||||
- name: Ensure local base image is current (if not rebuilt)
|
||||
if: steps.check-base.outputs.needs_rebuild == 'false'
|
||||
- name: Calculate GPU base image hash
|
||||
id: gpu-base-hash
|
||||
run: |
|
||||
BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest"
|
||||
# Hash Dockerfile.gpu-base + poetry.lock (resolved deps that affect GPU image)
|
||||
# Using poetry.lock instead of pyproject.toml so that version-only bumps
|
||||
# (which don't change dependencies) don't trigger expensive GPU base rebuilds
|
||||
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base poetry.lock | sha256sum | cut -d' ' -f1)
|
||||
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
|
||||
echo "📋 GPU base content hash: $CURRENT_HASH"
|
||||
|
||||
# Get the config digest from registry manifest (identifies the image content)
|
||||
# This is the same value as Docker's Image ID for the same image
|
||||
REGISTRY_CONFIG_DIGEST=$(docker manifest inspect $BASE_IMAGE 2>/dev/null | jq -r '.config.digest' || echo "")
|
||||
- name: Check if GPU base image exists and is current
|
||||
id: check-gpu-base
|
||||
run: |
|
||||
WANT_HASH="${{ steps.gpu-base-hash.outputs.hash }}"
|
||||
GPU_BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
|
||||
|
||||
# Get local image's ID (which is the config digest)
|
||||
LOCAL_IMAGE_ID=$(docker image inspect $BASE_IMAGE --format='{{.Id}}' 2>/dev/null || echo "")
|
||||
# Read the base.content.hash label without pulling the image
|
||||
# (manifest ~1KB + config blob ~10KB). The GPU base lives in
|
||||
# us-central1 (karaoke-repo), next to Cloud Build. The one-time copy
|
||||
# from the legacy us-east4 location was removed: it ran via
|
||||
# `buildx imagetools create` on THIS runner, which on a GitHub-hosted
|
||||
# runner would stream ~13 GB through internet egress.
|
||||
host="${GPU_BASE_IMAGE%%/*}"
|
||||
path="${GPU_BASE_IMAGE#*/}"
|
||||
path="${path%:*}"
|
||||
MANIFEST=$(docker manifest inspect "$GPU_BASE_IMAGE" 2>/dev/null || echo "")
|
||||
# A base copied with `buildx imagetools create` is a single-entry
|
||||
# index — follow it to the image manifest.
|
||||
CHILD=$(echo "$MANIFEST" | jq -r '.manifests[0].digest // ""' 2>/dev/null || echo "")
|
||||
if [ -n "$CHILD" ] && [ "$CHILD" != "null" ]; then
|
||||
MANIFEST=$(docker manifest inspect "${GPU_BASE_IMAGE%:*}@${CHILD}" 2>/dev/null || echo "")
|
||||
fi
|
||||
DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
|
||||
EXISTING_HASH=""
|
||||
if [ -n "$DIGEST" ] && [ "$DIGEST" != "null" ]; then
|
||||
EXISTING_HASH=$(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 "")
|
||||
fi
|
||||
echo "📋 Registry GPU base image hash: ${EXISTING_HASH:-<none>}"
|
||||
|
||||
echo "Registry config digest: $REGISTRY_CONFIG_DIGEST"
|
||||
echo "Local image ID: $LOCAL_IMAGE_ID"
|
||||
|
||||
if [ -z "$LOCAL_IMAGE_ID" ]; then
|
||||
echo "📥 Base image not in local cache - pulling from registry"
|
||||
docker pull $BASE_IMAGE
|
||||
elif [ "$LOCAL_IMAGE_ID" != "$REGISTRY_CONFIG_DIGEST" ]; then
|
||||
echo "🔄 Local cache has different image - pulling latest"
|
||||
docker pull $BASE_IMAGE
|
||||
if [ -n "$EXISTING_HASH" ] && [ "$EXISTING_HASH" = "$WANT_HASH" ]; then
|
||||
echo "✅ GPU base image is up to date"
|
||||
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "✅ Local cache matches registry - skipping pull"
|
||||
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"
|
||||
fi
|
||||
|
||||
- name: Build and push app image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:latest
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:latest
|
||||
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
# Registry cache for app layers
|
||||
# ignore-error=true allows build to continue if cache doesn't exist yet
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
- name: Build and push images (Cloud Build us-central1)
|
||||
id: images
|
||||
env:
|
||||
BUILD_BASE: ${{ steps.check-base.outputs.needs_rebuild }}
|
||||
BUILD_GPU_BASE: ${{ steps.check-gpu-base.outputs.needs_rebuild }}
|
||||
BASE_HASH: ${{ steps.base-hash.outputs.hash }}
|
||||
GPU_BASE_HASH: ${{ steps.gpu-base-hash.outputs.hash }}
|
||||
VERSION: ${{ steps.version_check.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Normal deploy: app layers only → free-tier e2-standard-2 (~7 min,
|
||||
# measured). A base rebuild (≈monthly, on poetry.lock / Dockerfile.*base
|
||||
# changes) gets a bigger paid machine + disk + timeout.
|
||||
if [ "$BUILD_BASE" = "true" ] || [ "$BUILD_GPU_BASE" = "true" ]; then
|
||||
MACHINE_ARGS=(--machine-type=e2-highcpu-8 --disk-size=300 --timeout=7200s)
|
||||
echo "🔄 Base rebuild needed (cpu=$BUILD_BASE gpu=$BUILD_GPU_BASE) → e2-highcpu-8"
|
||||
else
|
||||
MACHINE_ARGS=(--disk-size=150 --timeout=3600s)
|
||||
fi
|
||||
|
||||
# Minimal build context (what the Dockerfiles COPY + the build script).
|
||||
SRC="$RUNNER_TEMP/backend-image-src.tgz"
|
||||
tar -czf "$SRC" backend karaoke_gen lyrics_transcriber_temp \
|
||||
pyproject.toml poetry.lock README.md LICENSE .dockerignore \
|
||||
infrastructure/cloudbuild
|
||||
|
||||
BUILD_ID=$(gcloud builds submit "$SRC" \
|
||||
--region=us-central1 \
|
||||
--project=${{ env.PROJECT_ID }} \
|
||||
--config=infrastructure/cloudbuild/backend-images.yaml \
|
||||
"${MACHINE_ARGS[@]}" \
|
||||
--substitutions="_SHA=${{ github.sha }},_VERSION=${VERSION},_RUN_ID=${{ github.run_id }},_BUILD_BASE=${BUILD_BASE},_BASE_HASH=${BASE_HASH},_BUILD_GPU_BASE=${BUILD_GPU_BASE},_GPU_BASE_HASH=${GPU_BASE_HASH}" \
|
||||
--async --format='value(id)')
|
||||
# Recorded before waiting so the cancel step below can stop the build
|
||||
# if this job is cancelled (ci concurrency cancels superseded deploys;
|
||||
# an orphaned build would otherwise still push :latest tags).
|
||||
echo "$BUILD_ID" > "$RUNNER_TEMP/cloudbuild_id"
|
||||
echo "build_id=$BUILD_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "☁️ Cloud Build: https://console.cloud.google.com/cloud-build/builds;region=us-central1/${BUILD_ID}?project=${{ env.PROJECT_ID }}"
|
||||
|
||||
# Stream logs (returns when the build finishes), then check status.
|
||||
gcloud builds log "$BUILD_ID" --region=us-central1 --project=${{ env.PROJECT_ID }} --stream \
|
||||
|| echo "::warning::log streaming ended early; checking build status"
|
||||
# Tolerate transient API errors: a failed poll must not abort the
|
||||
# step (the cancel step below would then kill a healthy build).
|
||||
FAILS=0
|
||||
while true; do
|
||||
if ! STATUS=$(gcloud builds describe "$BUILD_ID" --region=us-central1 \
|
||||
--project=${{ env.PROJECT_ID }} --format='value(status)'); then
|
||||
FAILS=$((FAILS + 1))
|
||||
if [ "$FAILS" -ge 5 ]; then
|
||||
echo "::error::Cannot read Cloud Build $BUILD_ID status"
|
||||
exit 1
|
||||
fi
|
||||
sleep 15
|
||||
continue
|
||||
fi
|
||||
FAILS=0
|
||||
case "$STATUS" in
|
||||
QUEUED|PENDING|WORKING) sleep 15 ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
echo "Cloud Build status: $STATUS"
|
||||
if [ "$STATUS" != "SUCCESS" ]; then
|
||||
echo "::error::Cloud Build $BUILD_ID finished with status $STATUS"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Cancel Cloud Build if this job did not finish
|
||||
if: always() && steps.images.outcome != 'success' && steps.images.outcome != 'skipped'
|
||||
run: |
|
||||
ID_FILE="$RUNNER_TEMP/cloudbuild_id"
|
||||
[ -s "$ID_FILE" ] || exit 0
|
||||
gcloud builds cancel "$(cat "$ID_FILE")" --region=us-central1 \
|
||||
--project=${{ env.PROJECT_ID }} --quiet || true
|
||||
|
||||
- name: Pre-import CPU image for us-east4 jobs
|
||||
# A new image digest costs a one-time ~2.5 min "Container image import" on
|
||||
@@ -1895,142 +1952,6 @@ jobs:
|
||||
--quiet \
|
||||
|| echo "::warning::us-east4 CPU image pre-import execution failed to start (non-fatal)"
|
||||
|
||||
# ============================================
|
||||
# GPU Image Build (for audio worker with L4 GPU)
|
||||
# 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
|
||||
id: gpu-base-hash
|
||||
run: |
|
||||
# Hash Dockerfile.gpu-base + poetry.lock (resolved deps that affect GPU image)
|
||||
# Using poetry.lock instead of pyproject.toml so that version-only bumps
|
||||
# (which don't change dependencies) don't trigger expensive GPU base rebuilds
|
||||
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base poetry.lock | sha256sum | cut -d' ' -f1)
|
||||
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
|
||||
echo "📋 GPU base content hash: $CURRENT_HASH"
|
||||
|
||||
- name: Check if GPU base image exists and is current
|
||||
id: check-gpu-base
|
||||
run: |
|
||||
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"
|
||||
|
||||
# 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 ""
|
||||
}
|
||||
|
||||
EXISTING_HASH=$(image_hash "$GPU_BASE_IMAGE")
|
||||
echo "📋 Registry GPU base image hash (us-central1): ${EXISTING_HASH:-<none>}"
|
||||
|
||||
if [ -n "$EXISTING_HASH" ] && [ "$EXISTING_HASH" = "$WANT_HASH" ]; then
|
||||
echo "✅ GPU base image is up to date"
|
||||
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
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile.gpu-base
|
||||
push: true
|
||||
tags: |
|
||||
${{ 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 }}
|
||||
BASE_CONTENT_HASH=${{ steps.gpu-base-hash.outputs.hash }}
|
||||
provenance: false
|
||||
|
||||
- name: Build and push GPU app image
|
||||
# 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.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
|
||||
|
||||
# ============================================
|
||||
# Deploy to Cloud Run
|
||||
# ============================================
|
||||
@@ -2075,9 +1996,13 @@ jobs:
|
||||
# forced scale-out, and each overflow request waited out a ~16s app
|
||||
# cold start (2026-09-22 16-tab test: warm instance served in 1.2s,
|
||||
# freshly-spawned ones in 16-19s). 32 + --min-instances 2 gave 64
|
||||
# warm slots; min-instances was cut to 1 on 2026-09-26 (GCP cost cut,
|
||||
# accepted perf trade-off: big bursts may hit a ~15s cold start) while
|
||||
# staying far below the wedge-era 80. --clear-vpc-connector: the
|
||||
# warm slots; min-instances was cut to 1 on 2026-09-26 and to 0 on
|
||||
# 2026-10-01 (GCP cost cuts, ~$24/mo idle min-instance charge; Andrew
|
||||
# accepts a ~15s cold start on the first request after idle). In
|
||||
# practice the 60s /api/health uptime check and the */10 Cloud
|
||||
# Scheduler jobs keep an instance warm most of the time — with
|
||||
# --cpu-throttling (request-based billing) a warm-but-idle non-min
|
||||
# instance costs nothing. Concurrency stays far below the wedge-era 80. --clear-vpc-connector: the
|
||||
# serverless VPC connector was deleted (flacfetch is public now).
|
||||
gcloud run deploy karaoke-backend \
|
||||
--image $IMAGE \
|
||||
@@ -2094,10 +2019,10 @@ jobs:
|
||||
--timeout 1800 \
|
||||
--concurrency 32 \
|
||||
--max-instances 20 \
|
||||
--min-instances 1 \
|
||||
--min-instances 0 \
|
||||
--clear-vpc-connector \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,GEMINI_API_KEY=gemini-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"
|
||||
|
||||
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
|
||||
- name: Smoke candidate revision
|
||||
@@ -2243,8 +2168,7 @@ jobs:
|
||||
echo "Branch: ${{ github.ref_name }}"
|
||||
echo "Run: ${{ github.run_number }}"
|
||||
echo ""
|
||||
echo "📊 Built on self-hosted GCP runner (200GB SSD, no disk space issues)"
|
||||
echo " Runner: gcp-runner with 4 vCPU, 16GB RAM"
|
||||
echo "📊 Images built in Cloud Build us-central1: ${{ steps.images.outputs.build_id }}"
|
||||
|
||||
# NOTE: Pulumi infrastructure deploys are done locally, not in CI.
|
||||
# CI runners run on the infrastructure Pulumi manages, creating a circular
|
||||
|
||||
@@ -60,8 +60,10 @@ jobs:
|
||||
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
|
||||
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
|
||||
# sees the S3 (off-site) copy, so their limits must allow a full week
|
||||
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
|
||||
# files and secrets DO upload to S3 nightly, so they stay at 36h.
|
||||
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. Secrets DO
|
||||
# upload to S3 nightly, so they stay at 36h. GCS job files are NOT
|
||||
# tracked: their off-site copy was stopped 2026-10-01 (egress cost
|
||||
# cut) — they rely on GCS versioning + soft-delete only.
|
||||
# Git repos are also weekly (Sundays) AND incremental since
|
||||
# 2026-09-26 — only repos pushed that week get a fresh bundle, so a
|
||||
# quiet week legitimately leaves every .bundle older than 8 days.
|
||||
@@ -70,7 +72,6 @@ jobs:
|
||||
# a run where every repo failed still reads as stale.
|
||||
TARGETS = [
|
||||
("Firestore", "firestore/", 192, None),
|
||||
("GCS job files", "gcs/job-files/", 36, None),
|
||||
("Encrypted secrets", "secrets/", 36, None),
|
||||
("BigQuery weekly", "bigquery/daily-refresh/", 192, None),
|
||||
("Git repos", "git-repos/manifest.json", 192, None),
|
||||
|
||||
@@ -112,7 +112,7 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
|
||||
- Only `/admin/*` is English-only — it has no `[locale]/admin` counterpart and inherits `DefaultIntlProvider` from the root layout
|
||||
- Internal links use `Link` from `@/i18n/routing` (locale-aware)
|
||||
- After adding/changing English strings: `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
|
||||
- Translation uses Gemini 3.8 Flash via Vertex AI with GCS cache for efficiency
|
||||
- Translation uses Gemini 3.8 Flash via the **Gemini Developer API** (key: `GEMINI_API_KEY`, else Secret Manager `gemini-api-key` via your gcloud login — `frontend/scripts/gemini_client.py`) with GCS cache for efficiency. **Vertex AI is disabled in the GCP project — never use `vertexai=True`; backend code uses `backend/services/gemini_client.get_genai_client()`.**
|
||||
- CI validates all locale files have matching keys — **PR will fail if translations are missing**
|
||||
- Pre-commit hook auto-translates when en.json changes (enable: `git config core.hooksPath .githooks`)
|
||||
- Don't hardcode user-facing strings — add to `messages/en.json` and use `t('key')`
|
||||
|
||||
@@ -47,6 +47,7 @@ _db_singleton = None
|
||||
EventType = Literal[
|
||||
"banner_reconnecting",
|
||||
"banner_unavailable",
|
||||
"banner_waking",
|
||||
"lyrics_load_failed",
|
||||
"waveform_slow",
|
||||
"waveform_failed",
|
||||
|
||||
@@ -312,16 +312,14 @@ async def flacfetch_health() -> Dict[str, Any]:
|
||||
|
||||
|
||||
def check_audio_separator_status() -> Dict[str, Any]:
|
||||
"""Check audio separator availability without calling the remote GPU service."""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
"""Report audio separation availability.
|
||||
|
||||
Separation runs in the ``audio-separation-job`` GPU Cloud Run Job (local
|
||||
GPU mode, models baked into the image). The standalone ``audio-separator``
|
||||
Cloud Run GPU service was shut down on 2026-10-01 (cost cut), so there is
|
||||
no remote service to probe — this reports the installed package version
|
||||
only and never calls out to anything.
|
||||
"""
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
@@ -331,6 +329,7 @@ def check_audio_separator_status() -> Dict[str, Any]:
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"mode": "gpu_job",
|
||||
"version": pkg_version,
|
||||
}
|
||||
|
||||
@@ -338,34 +337,12 @@ def check_audio_separator_status() -> Dict[str, Any]:
|
||||
@router.get("/health/audio-separator")
|
||||
async def audio_separator_health() -> Dict[str, Any]:
|
||||
"""
|
||||
Return the installed audio-separator package version.
|
||||
Return audio separation status (installed audio-separator package version).
|
||||
|
||||
Does NOT call the remote GPU service — that would cold-start an expensive
|
||||
Cloud Run GPU instance (~$0.07 per wake). Instead reports the locally
|
||||
installed package version, which matches what the audio worker uses.
|
||||
|
||||
No authentication required.
|
||||
Does NOT call any remote service — separation runs in the
|
||||
audio-separation-job GPU Cloud Run Job. No authentication required.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
except Exception:
|
||||
pkg_version = None
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": pkg_version,
|
||||
}
|
||||
return check_audio_separator_status()
|
||||
|
||||
|
||||
def _get_encoding_worker_manager():
|
||||
|
||||
@@ -15,9 +15,9 @@ steps:
|
||||
- '-f'
|
||||
- 'backend/Dockerfile.gpu-base'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:latest'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- '--build-arg'
|
||||
- 'BUILD_DATE=$_BUILD_DATE'
|
||||
- '--build-arg'
|
||||
@@ -25,8 +25,8 @@ steps:
|
||||
- '.'
|
||||
|
||||
images:
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:latest'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
|
||||
timeout: '3600s'
|
||||
|
||||
|
||||
+2
-2
@@ -82,9 +82,9 @@ class Settings(BaseSettings):
|
||||
|
||||
# Agentic AI Correction (for lyrics correction via LLM)
|
||||
# Only used when skip_correction=false
|
||||
# When enabled, uses Gemini via Vertex AI for intelligent lyrics correction
|
||||
# When enabled, uses Gemini (Developer API, key GEMINI_API_KEY) for intelligent lyrics correction
|
||||
use_agentic_ai: bool = os.getenv("USE_AGENTIC_AI", "true").lower() in ("true", "1", "yes")
|
||||
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "vertexai/gemini-3.8-flash")
|
||||
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "gemini/gemini-3.8-flash")
|
||||
# Timeout for agentic correction in seconds. If correction takes longer, abort and
|
||||
# use uncorrected transcription - human review will fix any issues.
|
||||
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
|
||||
|
||||
@@ -54,8 +54,10 @@ MODEL_PRICING: dict[str, _Rate] = {
|
||||
"claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.5},
|
||||
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.3},
|
||||
"claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.1},
|
||||
# --- Gemini (ESTIMATE — Vertex 3.x Pro preview, <=200K-token context
|
||||
# tier; confirm against current Google pricing before trusting USD) ---
|
||||
# --- Gemini (ESTIMATE — 3.x Pro preview, <=200K-token context tier;
|
||||
# confirm against current Google pricing before trusting USD). Calls go
|
||||
# via the Gemini Developer API (paid tier), assumed at Vertex list-price
|
||||
# parity. ---
|
||||
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
|
||||
# Promo rate through 2026-12-31; see _RATE_CHANGES for the standard rate.
|
||||
"gemini-3.8-flash": {"input": 0.75, "output": 3.75, "cache_read": 0.075},
|
||||
|
||||
@@ -710,22 +710,19 @@ class AutoCorrectService:
|
||||
def _call_gemini(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
# Milliseconds; bounds the call so a hung model never strands the UI.
|
||||
http_options=types.HttpOptions(timeout=120_000),
|
||||
)
|
||||
from backend.services.gemini_client import get_genai_client, note_gemini_failure
|
||||
|
||||
# Deep-copy: the google-genai SDK mutates the schema dict in place,
|
||||
# which would poison the shared module-level constant for other
|
||||
# providers running in the same process.
|
||||
import copy
|
||||
|
||||
try:
|
||||
# Gemini Developer API (API key). Timeout in milliseconds bounds the
|
||||
# call so a hung model never strands the UI.
|
||||
client = get_genai_client(timeout_ms=120_000)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
@@ -736,6 +733,15 @@ class AutoCorrectService:
|
||||
),
|
||||
)
|
||||
except Exception as exc: # surface as 502, never a stuck job
|
||||
if note_gemini_failure("auto_correct", exc):
|
||||
# Quota / prepaid credit / key problem: retrying won't help.
|
||||
# Non-retryable so compare mode drops the Gemini leg at once
|
||||
# and keeps the other model's (Opus) suggestions.
|
||||
raise AutoCorrectServiceError(
|
||||
"Gemini is unavailable (quota/billing/key) — skipped",
|
||||
status_code=503,
|
||||
retryable=False,
|
||||
) from exc
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
|
||||
@@ -295,16 +295,17 @@ class CreditEvaluationService:
|
||||
"""Call Gemini and return the response text."""
|
||||
from google import genai
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
)
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
client = get_genai_client(timeout_ms=60_000)
|
||||
response = client.models.generate_content(
|
||||
model=self.settings.credit_eval_model,
|
||||
contents=prompt,
|
||||
config=genai.types.GenerateContentConfig(
|
||||
system_instruction=SYSTEM_PROMPT,
|
||||
# Grant/deny classification over a short signal list: low
|
||||
# thinking is ample (Gemini 3 Flash defaults to high).
|
||||
thinking_config=genai.types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return response.text
|
||||
@@ -402,7 +403,13 @@ class CreditEvaluationService:
|
||||
feedback_content=feedback_content,
|
||||
)
|
||||
|
||||
response_text = self._call_gemini(prompt)
|
||||
try:
|
||||
response_text = self._call_gemini(prompt)
|
||||
except Exception as gemini_exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("credit_evaluation", gemini_exc)
|
||||
raise
|
||||
evaluation = _parse_gemini_response(response_text)
|
||||
evaluation.signals = signals
|
||||
|
||||
|
||||
@@ -562,36 +562,43 @@ class CustomLyricsService:
|
||||
pdf_bytes: Optional[bytes],
|
||||
settings: GenerationSettings,
|
||||
) -> list[str]:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
)
|
||||
from backend.services.gemini_client import get_genai_client, note_gemini_failure
|
||||
|
||||
contents: list = [user_prompt]
|
||||
if pdf_bytes is not None:
|
||||
contents.append(
|
||||
types.Part.from_bytes(mime_type="application/pdf", data=pdf_bytes)
|
||||
)
|
||||
|
||||
response = client.models.generate_content(
|
||||
model=self.settings.custom_lyrics_model,
|
||||
contents=contents,
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
temperature=0.4,
|
||||
response_mime_type="application/json",
|
||||
response_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"lines": {"type": "array", "items": {"type": "string"}}
|
||||
try:
|
||||
# Bounded so a stalled call can't hang the request (Gemini Developer API).
|
||||
client = get_genai_client(timeout_ms=300_000)
|
||||
response = client.models.generate_content(
|
||||
model=self.settings.custom_lyrics_model,
|
||||
contents=contents,
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
temperature=0.4,
|
||||
response_mime_type="application/json",
|
||||
response_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"lines": {"type": "array", "items": {"type": "string"}}
|
||||
},
|
||||
"required": ["lines"],
|
||||
},
|
||||
"required": ["lines"],
|
||||
},
|
||||
),
|
||||
)
|
||||
),
|
||||
)
|
||||
except Exception as exc:
|
||||
if note_gemini_failure("custom_lyrics", exc):
|
||||
raise CustomLyricsServiceError(
|
||||
"The AI lyrics service is temporarily unavailable. Please try "
|
||||
"again later, or edit the lyrics manually.",
|
||||
status_code=503,
|
||||
) from exc
|
||||
raise
|
||||
# The model can return no text (safety block, MAX_TOKENS with no content,
|
||||
# empty candidate). `response.text` is then None and json.loads(None) would
|
||||
# raise a raw TypeError -> uncaught 500 without CORS headers -> the browser
|
||||
|
||||
@@ -11,9 +11,13 @@ import html
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import smtplib
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from email.message import EmailMessage
|
||||
from email.utils import formataddr
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import NamedTuple, Optional, List
|
||||
from zoneinfo import ZoneInfo
|
||||
@@ -175,29 +179,40 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
|
||||
API_URL = "https://api.postmarkapp.com/email"
|
||||
|
||||
# Seconds to sleep before each retry of a transient failure. Postmark's edge
|
||||
# intermittently answers some us-central1 Cloud Run egress IPs with a bare
|
||||
# nginx HTML 403 (not its JSON error format) — a fresh connection a moment
|
||||
# later often succeeds. Kept short: magic-link sends block the request.
|
||||
# SMTP fallback for when Postmark's API edge blocks us. Since 2026-09-30 the
|
||||
# edge has answered us-central1 Cloud Run egress IPs with a bare nginx HTML
|
||||
# 403 for hours at a time, so retrying the API doesn't help; SMTP is served
|
||||
# by separate infrastructure. Auth = server token as username and password.
|
||||
SMTP_HOST = "smtp.postmarkapp.com"
|
||||
SMTP_PORT = 587
|
||||
SMTP_TIMEOUT = 15
|
||||
MESSAGE_STREAM = "outbound"
|
||||
|
||||
# Seconds to sleep before each retry of a transient failure (429 / 5xx /
|
||||
# connect timeout). Kept short: magic-link sends block the request.
|
||||
RETRY_DELAYS = (1.0, 3.0)
|
||||
|
||||
@staticmethod
|
||||
def _is_transient_failure(response: requests.Response) -> bool:
|
||||
"""True for failures worth retrying: 429, 5xx, or a non-JSON 403.
|
||||
"""True for failures worth retrying against the API: 429 or 5xx."""
|
||||
status = response.status_code
|
||||
return status == 429 or status >= 500
|
||||
|
||||
@staticmethod
|
||||
def _is_edge_block(response: requests.Response) -> bool:
|
||||
"""True for a 403 without a JSON body: an IP-level block at Postmark's edge.
|
||||
|
||||
Postmark's own API errors (bad token, invalid payload, suppressed
|
||||
recipient) come back as JSON and are deterministic, so retrying them
|
||||
would just repeat the same answer. A 403 without a JSON body is an
|
||||
edge/IP-level block, not a verdict on the request itself.
|
||||
recipient) come back as JSON and are verdicts on the request itself; a
|
||||
bare HTML 403 never reached the API, so the message was not accepted and
|
||||
it's safe to resend it over SMTP.
|
||||
"""
|
||||
status = response.status_code
|
||||
if status == 429 or status >= 500:
|
||||
if response.status_code != 403:
|
||||
return False
|
||||
try:
|
||||
response.json()
|
||||
except ValueError:
|
||||
return True
|
||||
if status == 403:
|
||||
try:
|
||||
response.json()
|
||||
except ValueError:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _post_with_retry(self, payload: dict) -> requests.Response:
|
||||
@@ -295,7 +310,20 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
if bcc_emails:
|
||||
payload["Bcc"] = ", ".join(_dedupe_emails(bcc_emails))
|
||||
|
||||
response = self._post_with_retry(payload)
|
||||
try:
|
||||
response = self._post_with_retry(payload)
|
||||
except requests.ConnectTimeout:
|
||||
# Never connected, so Postmark didn't accept it: safe to resend.
|
||||
logger.warning("Postmark API connect timed out on every attempt; falling back to SMTP")
|
||||
return self._send_via_smtp(to_email, subject, html_content, text_content,
|
||||
cc_emails, bcc_emails, sender_email)
|
||||
|
||||
if self._is_edge_block(response):
|
||||
logger.warning(
|
||||
f"Postmark API edge returned HTML 403 for {to_email}; falling back to SMTP"
|
||||
)
|
||||
return self._send_via_smtp(to_email, subject, html_content, text_content,
|
||||
cc_emails, bcc_emails, sender_email)
|
||||
|
||||
if 200 <= response.status_code < 300:
|
||||
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
|
||||
@@ -338,6 +366,58 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
logger.exception("Failed to send email via Postmark")
|
||||
return SendResult(success=False, message_id=None)
|
||||
|
||||
def _send_via_smtp(
|
||||
self,
|
||||
to_email: str,
|
||||
subject: str,
|
||||
html_content: str,
|
||||
text_content: Optional[str],
|
||||
cc_emails: Optional[List[str]],
|
||||
bcc_emails: Optional[List[str]],
|
||||
sender_email: str,
|
||||
) -> SendResult:
|
||||
"""Send through Postmark's SMTP endpoint (used when the API is unreachable).
|
||||
|
||||
SMTP returns no Postmark MessageID and can't report suppressed
|
||||
recipients synchronously (Postmark logs those as bounces instead).
|
||||
"""
|
||||
cc = _dedupe_emails(cc_emails) if cc_emails else []
|
||||
bcc = _dedupe_emails(bcc_emails) if bcc_emails else []
|
||||
try:
|
||||
msg = EmailMessage()
|
||||
msg["From"] = formataddr((self.from_name, sender_email))
|
||||
msg["To"] = to_email
|
||||
msg["Subject"] = subject
|
||||
msg["X-PM-Message-Stream"] = self.MESSAGE_STREAM
|
||||
if cc:
|
||||
msg["Cc"] = ", ".join(cc)
|
||||
if text_content:
|
||||
msg.set_content(text_content)
|
||||
msg.add_alternative(html_content, subtype="html")
|
||||
else:
|
||||
msg.set_content(html_content, subtype="html")
|
||||
|
||||
smtp = smtplib.SMTP(self.SMTP_HOST, self.SMTP_PORT, timeout=self.SMTP_TIMEOUT)
|
||||
try:
|
||||
smtp.starttls(context=ssl.create_default_context())
|
||||
smtp.login(self.server_token, self.server_token)
|
||||
smtp.send_message(msg, to_addrs=[to_email, *cc, *bcc])
|
||||
finally:
|
||||
# A failed QUIT after an accepted send must not fail the send
|
||||
# (a caller retry would then duplicate the email).
|
||||
try:
|
||||
smtp.quit()
|
||||
except (smtplib.SMTPException, OSError):
|
||||
smtp.close()
|
||||
except (smtplib.SMTPException, OSError, ValueError):
|
||||
# ValueError: EmailMessage rejects CR/LF in header values.
|
||||
logger.exception(f"Failed to send email to {to_email} via Postmark SMTP fallback")
|
||||
return SendResult(success=False, message_id=None)
|
||||
|
||||
logger.info(f"Email sent to {to_email} via Postmark SMTP fallback")
|
||||
self.last_message_id = None
|
||||
return SendResult(success=True, message_id=None)
|
||||
|
||||
|
||||
# Query params that carry single-use auth/capability tokens (magic-link sign-in,
|
||||
# lyrics/instrumental review access, referral codes). We persist a redacted copy
|
||||
|
||||
@@ -110,7 +110,6 @@ Shared infrastructure:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
LLM_ANALYSIS_MODEL: str = os.environ.get("LLM_ANALYSIS_MODEL", "gemini-3.8-flash")
|
||||
LLM_VERTEX_LOCATION: str = os.environ.get("LLM_VERTEX_LOCATION", "global")
|
||||
|
||||
#: Minimum number of active error patterns required before triggering LLM analysis.
|
||||
MIN_PATTERNS_FOR_ANALYSIS: int = 3
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""LLM-powered incident analysis and duplicate detection for the error monitor.
|
||||
|
||||
Uses Gemini Flash via the google-generativeai library to:
|
||||
Uses Gemini Flash via the Gemini Developer API (backend.services.gemini_client) to:
|
||||
1. Group related error patterns into incidents with root-cause analysis.
|
||||
2. Identify near-duplicate patterns that the regex normalizer missed.
|
||||
|
||||
@@ -17,13 +17,11 @@ import time
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
|
||||
from backend.services.gemini_client import get_genai_client, note_gemini_failure
|
||||
from backend.services.error_monitor.config import (
|
||||
GCP_PROJECT,
|
||||
LLM_ANALYSIS_MODEL,
|
||||
LLM_VERTEX_LOCATION,
|
||||
MIN_PATTERNS_FOR_ANALYSIS,
|
||||
SERVICE_DEPENDENCY_MAP,
|
||||
)
|
||||
@@ -96,11 +94,7 @@ def _call_llm(
|
||||
|
||||
for attempt in range(_RETRY_ATTEMPTS):
|
||||
try:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=GCP_PROJECT,
|
||||
location=LLM_VERTEX_LOCATION,
|
||||
)
|
||||
client = get_genai_client(timeout_ms=120_000)
|
||||
response = client.models.generate_content(
|
||||
model=LLM_ANALYSIS_MODEL,
|
||||
contents=user_prompt,
|
||||
@@ -111,6 +105,10 @@ def _call_llm(
|
||||
)
|
||||
return response.text
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if note_gemini_failure("error_monitor", exc):
|
||||
# Quota/credit/key problem: don't retry — callers fall back to
|
||||
# alerts without the AI summary.
|
||||
raise
|
||||
last_exc = exc
|
||||
delay = _RETRY_BASE_DELAY * (2**attempt)
|
||||
logger.warning(
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Shared Gemini client for the backend: Gemini Developer API (API key), not Vertex.
|
||||
|
||||
Every backend Gemini call goes through :func:`get_genai_client`. Vertex AI is
|
||||
disabled in the nomadkaraoke GCP project so AI spend never lands on it; calls are
|
||||
billed to whichever AI Studio key is stored in Secret Manager ``gemini-api-key``.
|
||||
|
||||
Key resolution (via :meth:`backend.config.Settings.get_secret`):
|
||||
1. ``GEMINI_API_KEY`` env var — injected on Cloud Run from
|
||||
``gemini-api-key:latest`` (CI ``--set-secrets`` for the service, Pulumi
|
||||
for the jobs).
|
||||
2. Secret Manager ``gemini-api-key`` (latest) — read directly with the
|
||||
runtime service account / your ADC when the env var isn't set.
|
||||
|
||||
Rotating the key: add a new version of ``gemini-api-key``. New instances / job
|
||||
executions pick it up; no code change.
|
||||
|
||||
Degradation: when the key's quota or prepaid credit is exhausted (or the key is
|
||||
rejected), callers must degrade rather than fail jobs. Use
|
||||
:func:`is_quota_or_billing_error` to classify and :func:`note_gemini_failure`
|
||||
from the caller's ``except`` block — it also sends a Discord ops alert at most
|
||||
once per ``GEMINI_QUOTA_ALERT_HOURS`` (default 6h) across all instances.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SECRET_NAME = "gemini-api-key"
|
||||
|
||||
QUOTA_EXHAUSTED_MESSAGE = (
|
||||
"Gemini quota/credit exhausted — top up AI Studio or rotate gemini-api-key "
|
||||
"(add a new version of Secret Manager secret 'gemini-api-key' in project nomadkaraoke)."
|
||||
)
|
||||
|
||||
# Firestore dedup doc id (in ops_alerts' collection) shared by every instance/job.
|
||||
_ALERT_KEY = "gemini-quota-exhausted"
|
||||
_DEFAULT_ALERT_HOURS = 6.0
|
||||
|
||||
|
||||
class GeminiKeyUnavailableError(RuntimeError):
|
||||
"""No Gemini API key could be resolved (env var unset and Secret Manager failed)."""
|
||||
|
||||
|
||||
def get_api_key() -> str:
|
||||
"""Return the Gemini Developer API key or raise GeminiKeyUnavailableError."""
|
||||
env_key = os.environ.get("GEMINI_API_KEY", "").strip()
|
||||
if env_key:
|
||||
return env_key
|
||||
from backend.config import get_settings
|
||||
|
||||
key = (get_settings().get_secret(SECRET_NAME) or "").strip()
|
||||
if not key:
|
||||
raise GeminiKeyUnavailableError(
|
||||
"GEMINI_API_KEY is not set and Secret Manager secret 'gemini-api-key' "
|
||||
"could not be read"
|
||||
)
|
||||
return key
|
||||
|
||||
|
||||
def get_genai_client(timeout_ms: Optional[int] = None) -> Any:
|
||||
"""Build a google-genai client for the Gemini Developer API.
|
||||
|
||||
``timeout_ms`` bounds each HTTP request (milliseconds). No project/location:
|
||||
those only apply to Vertex AI.
|
||||
"""
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
http_options = types.HttpOptions(timeout=int(timeout_ms)) if timeout_ms else None
|
||||
# vertexai=False pins the Developer API even if GOOGLE_GENAI_USE_VERTEXAI is set.
|
||||
return genai.Client(vertexai=False, api_key=get_api_key(), http_options=http_options)
|
||||
|
||||
|
||||
# Message fragments that mean "the key/account can't pay or isn't valid" — a
|
||||
# retry won't help; a human must top up credit or rotate the key.
|
||||
_QUOTA_PATTERNS = re.compile(
|
||||
r"RESOURCE_EXHAUSTED|exceeded your current quota|quota exceeded|"
|
||||
r"billing (details|account)|prepa(id|yment)|credits? (are |is |have been )?"
|
||||
r"(exhausted|depleted|used up)|insufficient (credit|funds|balance)|"
|
||||
r"API_KEY_INVALID|API key not valid|API key expired|API_KEY_SERVICE_BLOCKED|"
|
||||
r"\b429 Too Many Requests",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# A 429 that names a per-minute quota / carries a retry delay is an ordinary
|
||||
# rate limit (transient — retry with backoff), not exhausted credit.
|
||||
_RATE_LIMIT_PATTERNS = re.compile(r"PerMinute|retryDelay|retry in \d", re.IGNORECASE)
|
||||
# ...unless it names a per-day quota: that won't clear for hours — treat as exhausted.
|
||||
_DAILY_QUOTA_PATTERN = re.compile(r"PerDay", re.IGNORECASE)
|
||||
|
||||
|
||||
def _is_rate_limit(text: str) -> bool:
|
||||
return bool(_RATE_LIMIT_PATTERNS.search(text)) and not _DAILY_QUOTA_PATTERN.search(text)
|
||||
|
||||
|
||||
def is_quota_or_billing_error(exc: Optional[BaseException]) -> bool:
|
||||
"""True if ``exc`` (or anything in its ``__cause__`` chain) is a Gemini quota,
|
||||
prepaid-credit, billing or API-key error — i.e. needs a top-up/key rotation,
|
||||
not a retry.
|
||||
|
||||
Matches google-genai ``APIError`` (``.code`` 429 / 403 or status
|
||||
RESOURCE_EXHAUSTED / PERMISSION_DENIED, or a billing/key message on a 400),
|
||||
a missing key, and wrapped/stringified errors from other layers (LangChain).
|
||||
Per-minute rate limits (429 naming a ``PerMinute`` quota or a retry delay)
|
||||
are NOT matched — those are transient; retry them.
|
||||
"""
|
||||
seen: set[int] = set()
|
||||
while exc is not None and id(exc) not in seen:
|
||||
seen.add(id(exc))
|
||||
if isinstance(exc, GeminiKeyUnavailableError):
|
||||
return True
|
||||
code = getattr(exc, "code", None)
|
||||
if code is None:
|
||||
code = getattr(exc, "status_code", None)
|
||||
status = str(getattr(exc, "status", "") or "")
|
||||
if code == 429 or status == "RESOURCE_EXHAUSTED":
|
||||
return not _is_rate_limit(str(exc))
|
||||
if code == 403 or status == "PERMISSION_DENIED":
|
||||
return True
|
||||
text = str(exc)
|
||||
if _QUOTA_PATTERNS.search(text) and not _is_rate_limit(text):
|
||||
return True
|
||||
# Only explicit chaining (`raise X from e`): implicit __context__ could
|
||||
# attribute an unrelated earlier error (e.g. a Firestore 403) to Gemini.
|
||||
exc = exc.__cause__
|
||||
return False
|
||||
|
||||
|
||||
def _alert_hours() -> float:
|
||||
try:
|
||||
return float(os.environ.get("GEMINI_QUOTA_ALERT_HOURS", _DEFAULT_ALERT_HOURS))
|
||||
except (TypeError, ValueError):
|
||||
return _DEFAULT_ALERT_HOURS
|
||||
|
||||
|
||||
# In-process throttle so a burst of failures in one instance doesn't hit
|
||||
# Firestore on every call; the Firestore doc throttles across instances/jobs.
|
||||
_last_alert_attempt: float = 0.0
|
||||
_alert_lock = threading.Lock()
|
||||
# Alert I/O (Firestore + Secret Manager + Discord) runs on a daemon thread so it
|
||||
# never blocks the caller — several callers are on the asyncio event loop.
|
||||
# Tests flip this off to run it inline.
|
||||
_ALERT_IN_BACKGROUND = True
|
||||
|
||||
|
||||
def note_gemini_failure(caller: str, exc: BaseException) -> bool:
|
||||
"""Classify a Gemini failure; on quota/billing/key errors log + alert.
|
||||
|
||||
Call from a caller's ``except`` block. Returns True when the error is a
|
||||
quota/billing/key error (caller should skip retries and degrade). Never raises.
|
||||
"""
|
||||
try:
|
||||
if not is_quota_or_billing_error(exc):
|
||||
return False
|
||||
logger.error("Gemini unavailable (quota/billing/key) in %s: %s", caller, exc)
|
||||
_maybe_alert(caller, exc)
|
||||
return True
|
||||
except Exception: # noqa: BLE001 - classification/alerting must never raise
|
||||
logger.warning("note_gemini_failure failed", exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
def _maybe_alert(caller: str, exc: BaseException) -> None:
|
||||
global _last_alert_attempt
|
||||
window = _alert_hours() * 3600
|
||||
now = time.monotonic()
|
||||
with _alert_lock:
|
||||
if _last_alert_attempt and now - _last_alert_attempt < window:
|
||||
return
|
||||
_last_alert_attempt = now
|
||||
if _ALERT_IN_BACKGROUND:
|
||||
threading.Thread(
|
||||
target=_send_alert, args=(caller, exc, window), name="gemini-quota-alert", daemon=True
|
||||
).start()
|
||||
else:
|
||||
_send_alert(caller, exc, window)
|
||||
|
||||
|
||||
def _send_alert(caller: str, exc: BaseException, window: float) -> None:
|
||||
global _last_alert_attempt
|
||||
from backend.services import ops_alerts
|
||||
|
||||
err = str(exc).strip()
|
||||
if len(err) > 800:
|
||||
err = err[:800] + " …[truncated]"
|
||||
message = (
|
||||
"🟠 **Gemini API unavailable — quota / prepaid credit / key problem**\n"
|
||||
f"**First seen in:** `{caller}`\n"
|
||||
"Callers are degrading (auto-correct keeps Opus only, match-judge/parse-titles "
|
||||
"return no suggestion, credit evals go to manual review, translations are "
|
||||
"skipped).\n"
|
||||
f"**Fix:** {QUOTA_EXHAUSTED_MESSAGE}\n"
|
||||
f"**Error:** ```{err}```"
|
||||
)
|
||||
try:
|
||||
ops_alerts.send_throttled_ops_alert(_ALERT_KEY, message, throttle_minutes=int(window / 60))
|
||||
except Exception: # noqa: BLE001 - alerting must never raise
|
||||
logger.warning("Gemini quota alert failed", exc_info=True)
|
||||
# Let the next failure in this instance try again.
|
||||
with _alert_lock:
|
||||
_last_alert_attempt = 0.0
|
||||
@@ -176,15 +176,11 @@ class LyricsTranslationService:
|
||||
# ---- model ----
|
||||
|
||||
def _call_gemini(self, user_prompt: str) -> Any:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=90_000), # 2 attempts: render waits <= ~3 min
|
||||
)
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
client = get_genai_client(timeout_ms=90_000) # 2 attempts: render waits <= ~3 min
|
||||
response = client.models.generate_content(
|
||||
model=self.model,
|
||||
contents=[user_prompt],
|
||||
@@ -245,6 +241,14 @@ class LyricsTranslationService:
|
||||
except (LyricsTranslationError, ValueError) as exc: # malformed output: retry
|
||||
last_error = exc
|
||||
except Exception as exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
if note_gemini_failure("lyrics_translation", exc):
|
||||
# Quota/credit/key problem: don't retry; the render goes ahead
|
||||
# without the translation row.
|
||||
raise LyricsTranslationError(
|
||||
"translation service unavailable (Gemini quota/billing) — rendered without translation"
|
||||
) from exc
|
||||
if not _is_transient(exc):
|
||||
raise LyricsTranslationError(f"translation model error: {exc}") from exc
|
||||
last_error = exc
|
||||
|
||||
@@ -149,18 +149,14 @@ async def _default_generate(model: str, system_prompt: str, user_prompt: str) ->
|
||||
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
import copy
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
timeout_ms = int(getattr(settings, "match_judge_timeout_ms", 3000))
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=timeout_ms),
|
||||
)
|
||||
client = get_genai_client(timeout_ms=timeout_ms)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
@@ -169,6 +165,9 @@ def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -141,6 +141,9 @@ async def resolve_free_text(query: str, *, generate: Optional[Generate] = None,
|
||||
data = await (generate or _default_generate)(
|
||||
model or _model(), _SYSTEM_PROMPT, f'Singer typed: "{query}"')
|
||||
except Exception as e:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("match_judge_free_text", e)
|
||||
logger.warning(f"resolve_free_text failed: {e}")
|
||||
return _none(query, "unavailable")
|
||||
return verdict_from_response(data, query)
|
||||
@@ -200,17 +203,13 @@ async def _default_generate(model: str, system_prompt: str, user_prompt: str) ->
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=int(getattr(settings, "match_judge_timeout_ms", 12000))),
|
||||
)
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
client = get_genai_client(timeout_ms=int(getattr(settings, "match_judge_timeout_ms", 12000)))
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
@@ -219,6 +218,9 @@ def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -126,7 +126,10 @@ async def judge_match(
|
||||
|
||||
try:
|
||||
return await ai(artist, title, candidates, audio_tier)
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("match_judge", exc)
|
||||
# Graceful degradation: returning no-suggestion is a safe fallback (the
|
||||
# user just gets no auto-match). Log at WARNING (with traceback) so a
|
||||
# transient AI blip does not page as a red "new error pattern".
|
||||
|
||||
@@ -134,7 +134,9 @@ def _signature(error_message: str) -> str:
|
||||
return hashlib.sha256((error_message or "").encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _should_alert(db: Any, signature: str, now: datetime) -> tuple[bool, bool, int, Any]:
|
||||
def _should_alert(
|
||||
db: Any, signature: str, now: datetime, throttle_minutes: Optional[int] = None
|
||||
) -> tuple[bool, bool, int, Any]:
|
||||
"""Decide whether to send, WITHOUT yet acknowledging delivery.
|
||||
|
||||
Returns ``(should_send, is_novel, suppressed_since_last, doc_ref)``:
|
||||
@@ -182,7 +184,8 @@ def _should_alert(db: Any, signature: str, now: datetime) -> tuple[bool, bool, i
|
||||
if last_alerted_raw:
|
||||
try:
|
||||
last_alerted = datetime.fromisoformat(last_alerted_raw)
|
||||
within_window = (now - last_alerted) < timedelta(minutes=_throttle_minutes())
|
||||
window = throttle_minutes if throttle_minutes is not None else _throttle_minutes()
|
||||
within_window = (now - last_alerted) < timedelta(minutes=window)
|
||||
except (TypeError, ValueError):
|
||||
within_window = False
|
||||
|
||||
@@ -225,6 +228,36 @@ def _mark_alerted(doc_ref: Any, now: datetime) -> None:
|
||||
logger.debug("ops_alerts: could not record alert delivery: %s", exc)
|
||||
|
||||
|
||||
def send_throttled_ops_alert(key: str, message: str, throttle_minutes: int) -> bool:
|
||||
"""Send an ops alert at most once per ``throttle_minutes`` for ``key``.
|
||||
|
||||
The throttle lives in Firestore (same dedup collection as job-failure
|
||||
alerts), so it holds across every Cloud Run instance and job execution.
|
||||
Fails open (sends) if Firestore is unreachable. Best-effort; never raises.
|
||||
Returns True if an alert was sent.
|
||||
"""
|
||||
try:
|
||||
if not _is_enabled():
|
||||
return False
|
||||
from backend.services.firestore_service import get_firestore_client
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
should_send, _novel, suppressed, doc_ref = _should_alert(
|
||||
get_firestore_client(), key, now, throttle_minutes=throttle_minutes
|
||||
)
|
||||
if not should_send:
|
||||
return False
|
||||
if suppressed:
|
||||
message += f"\n_(Collapsed {suppressed} earlier occurrence(s).)_"
|
||||
sent = send_ops_alert(message)
|
||||
if sent:
|
||||
_mark_alerted(doc_ref, now)
|
||||
return sent
|
||||
except Exception as exc: # noqa: BLE001 - alerting must never raise
|
||||
logger.warning("ops_alerts: throttled alert %s failed: %s", key, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _retry_pending(state_data: dict) -> bool:
|
||||
"""True if state_data.cloud_run_retry_pending is set and unexpired."""
|
||||
pending = (state_data or {}).get("cloud_run_retry_pending")
|
||||
|
||||
@@ -123,18 +123,14 @@ async def _default_generate(model: str, system: str, user: str) -> dict:
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system: str, user: str) -> dict:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
timeout_ms = int(getattr(settings, "parse_titles_timeout_ms", 20000))
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=timeout_ms),
|
||||
)
|
||||
client = get_genai_client(timeout_ms=timeout_ms)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user],
|
||||
@@ -143,6 +139,9 @@ def _blocking_generate(model: str, system: str, user: str) -> dict:
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -56,6 +56,9 @@ async def _parse_chunk(chunk: list[dict], *, model, generate) -> list[dict]:
|
||||
try:
|
||||
results = await ai.ai_parse(chunk, model=model, generate=generate)
|
||||
except Exception as exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("parse_titles", exc)
|
||||
logger.warning(
|
||||
"parse_titles chunk degraded (%s); blanks for %d items", exc, len(chunk))
|
||||
return _blanks(chunk)
|
||||
|
||||
@@ -431,6 +431,9 @@ def analyze_filenames(
|
||||
llm_rows, leftover = _llm_analyze(leftover, generate)
|
||||
rows.extend(llm_rows)
|
||||
except Exception as e: # pragma: no cover - resilience guard
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("tenant_bulk_analyze", e)
|
||||
logger.warning("Bulk-analyze LLM pass failed, using regex result: %s", e)
|
||||
|
||||
unpaired = [_describe_unpaired(fn) for fn in leftover]
|
||||
@@ -438,7 +441,7 @@ def analyze_filenames(
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Default Vertex-Gemini generate (mirrors backend.services.match_judge.ai)
|
||||
# Default Gemini generate (mirrors backend.services.match_judge.ai)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _default_model() -> str:
|
||||
@@ -451,22 +454,18 @@ def _default_model() -> str:
|
||||
|
||||
|
||||
def default_generate(system_prompt: str, user_prompt: str) -> dict:
|
||||
"""Blocking Vertex-Gemini call producing schema-constrained JSON.
|
||||
"""Blocking Gemini (Developer API) call producing schema-constrained JSON.
|
||||
|
||||
Wrap in ``asyncio.to_thread`` when calling from async code.
|
||||
"""
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
timeout_ms = int(getattr(settings, "tenant_bulk_timeout_ms", 30000))
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=timeout_ms),
|
||||
)
|
||||
client = get_genai_client(timeout_ms=timeout_ms)
|
||||
response = client.models.generate_content(
|
||||
model=_default_model(),
|
||||
contents=[user_prompt],
|
||||
@@ -475,6 +474,9 @@ def default_generate(system_prompt: str, user_prompt: str) -> dict:
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -18,6 +18,8 @@ if 'FIRESTORE_EMULATOR_HOST' not in os.environ:
|
||||
os.environ.setdefault('GCS_BUCKET_NAME', 'test-bucket')
|
||||
os.environ.setdefault('FIRESTORE_COLLECTION', 'jobs')
|
||||
os.environ.setdefault('ENVIRONMENT', 'test')
|
||||
# Gemini Developer API key: never let a test fall through to Secret Manager.
|
||||
os.environ.setdefault('GEMINI_API_KEY', 'test-gemini-key')
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, AsyncMock, patch
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Tests for backend.services.gemini_client (Gemini Developer API helper) and the
|
||||
per-caller graceful degradation when Gemini's quota/credit/key is unusable."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services import gemini_client
|
||||
from backend.services.gemini_client import (
|
||||
GeminiKeyUnavailableError,
|
||||
get_api_key,
|
||||
get_genai_client,
|
||||
is_quota_or_billing_error,
|
||||
note_gemini_failure,
|
||||
)
|
||||
|
||||
|
||||
class FakeAPIError(Exception):
|
||||
"""Mimics google.genai.errors.APIError (numeric ``code`` + ``status``)."""
|
||||
|
||||
def __init__(self, code, status, message=""):
|
||||
super().__init__(f"{code} {status}. {message}")
|
||||
self.code = code
|
||||
self.status = status
|
||||
|
||||
|
||||
QUOTA = FakeAPIError(429, "RESOURCE_EXHAUSTED", "Your prepayment credits are depleted")
|
||||
RATE_LIMIT = FakeAPIError(
|
||||
429, "RESOURCE_EXHAUSTED",
|
||||
"quotaId: GenerateRequestsPerMinutePerProjectPerModel-PaidTier, retryDelay: 5s",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_alert_throttle(monkeypatch):
|
||||
monkeypatch.setattr(gemini_client, "_last_alert_attempt", 0.0)
|
||||
monkeypatch.setattr(gemini_client, "_ALERT_IN_BACKGROUND", False)
|
||||
|
||||
|
||||
# ---- classifier -------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exc",
|
||||
[
|
||||
QUOTA,
|
||||
FakeAPIError(429, "RESOURCE_EXHAUSTED", "You exceeded your current quota"),
|
||||
FakeAPIError(403, "PERMISSION_DENIED", "Generative Language API has not been used"),
|
||||
FakeAPIError(400, "INVALID_ARGUMENT", "API key not valid. Please pass a valid API key."),
|
||||
FakeAPIError(400, "FAILED_PRECONDITION", "check your plan and billing details"),
|
||||
RuntimeError("API key expired. Please renew the API key."),
|
||||
GeminiKeyUnavailableError("no key"),
|
||||
RuntimeError("429 RESOURCE_EXHAUSTED quotaId GenerateRequestsPerDayPerProjectPerModel, retryDelay 3600s"),
|
||||
],
|
||||
)
|
||||
def test_classifier_positive(exc):
|
||||
assert is_quota_or_billing_error(exc)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exc",
|
||||
[
|
||||
RATE_LIMIT,
|
||||
FakeAPIError(500, "INTERNAL", "Internal error"),
|
||||
FakeAPIError(503, "UNAVAILABLE", "The model is overloaded"),
|
||||
FakeAPIError(400, "INVALID_ARGUMENT", "Request contains an invalid argument."),
|
||||
TimeoutError("timed out"),
|
||||
ValueError("processed 429 tokens"),
|
||||
None,
|
||||
],
|
||||
)
|
||||
def test_classifier_negative(exc):
|
||||
assert not is_quota_or_billing_error(exc)
|
||||
|
||||
|
||||
def test_classifier_walks_cause_chain():
|
||||
try:
|
||||
try:
|
||||
raise QUOTA
|
||||
except FakeAPIError as inner:
|
||||
raise RuntimeError("wrapped") from inner
|
||||
except RuntimeError as outer:
|
||||
assert is_quota_or_billing_error(outer)
|
||||
|
||||
|
||||
# ---- key + client -------------------------------------------------------------
|
||||
|
||||
|
||||
def test_env_key_wins(monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_API_KEY", " env-key ")
|
||||
with patch("backend.config.Settings.get_secret") as get_secret:
|
||||
assert get_api_key() == "env-key"
|
||||
get_secret.assert_not_called()
|
||||
|
||||
|
||||
def test_falls_back_to_secret_manager(monkeypatch):
|
||||
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
|
||||
with patch("backend.config.Settings.get_secret", return_value="sm-key") as get_secret:
|
||||
assert get_api_key() == "sm-key"
|
||||
get_secret.assert_called_once_with("gemini-api-key")
|
||||
|
||||
|
||||
def test_missing_key_raises(monkeypatch):
|
||||
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
|
||||
with patch("backend.config.Settings.get_secret", return_value=None):
|
||||
with pytest.raises(GeminiKeyUnavailableError):
|
||||
get_api_key()
|
||||
|
||||
|
||||
def test_client_uses_api_key_never_vertex(monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "k")
|
||||
with patch("google.genai.Client") as client_cls:
|
||||
get_genai_client(timeout_ms=1234)
|
||||
kwargs = client_cls.call_args.kwargs
|
||||
assert kwargs["api_key"] == "k"
|
||||
assert kwargs["http_options"].timeout == 1234
|
||||
assert kwargs["vertexai"] is False and "project" not in kwargs and "location" not in kwargs
|
||||
|
||||
|
||||
# ---- note_gemini_failure / alert throttle --------------------------------------
|
||||
|
||||
|
||||
def test_note_failure_ignores_ordinary_errors():
|
||||
with patch.object(gemini_client, "_maybe_alert") as alert:
|
||||
assert note_gemini_failure("x", RATE_LIMIT) is False
|
||||
alert.assert_not_called()
|
||||
|
||||
|
||||
def test_note_failure_alerts_once_per_window():
|
||||
with patch("backend.services.ops_alerts.send_throttled_ops_alert", return_value=True) as send:
|
||||
assert note_gemini_failure("auto_correct", QUOTA) is True
|
||||
assert note_gemini_failure("match_judge", QUOTA) is True
|
||||
send.assert_called_once()
|
||||
key, message = send.call_args.args
|
||||
assert key == "gemini-quota-exhausted"
|
||||
assert "auto_correct" in message and "rotate gemini-api-key" in message
|
||||
assert send.call_args.kwargs["throttle_minutes"] == 360
|
||||
|
||||
|
||||
def test_note_failure_never_raises_and_rearms_after_failed_send():
|
||||
with patch("backend.services.ops_alerts.send_throttled_ops_alert", side_effect=RuntimeError) as send:
|
||||
assert note_gemini_failure("x", QUOTA) is True
|
||||
assert note_gemini_failure("x", QUOTA) is True
|
||||
# A failed send doesn't silence the instance for 6h.
|
||||
assert send.call_count == 2
|
||||
|
||||
|
||||
def test_alert_runs_in_background_thread(monkeypatch):
|
||||
import threading
|
||||
|
||||
monkeypatch.setattr(gemini_client, "_ALERT_IN_BACKGROUND", True)
|
||||
done = threading.Event()
|
||||
seen = {}
|
||||
|
||||
def fake_send(*_a, **_k):
|
||||
seen["thread"] = threading.current_thread().name
|
||||
done.set()
|
||||
return True
|
||||
|
||||
with patch("backend.services.ops_alerts.send_throttled_ops_alert", side_effect=fake_send):
|
||||
assert note_gemini_failure("x", QUOTA) is True
|
||||
assert done.wait(5)
|
||||
assert seen["thread"] == "gemini-quota-alert"
|
||||
|
||||
|
||||
def test_throttled_ops_alert_respects_firestore_window(monkeypatch):
|
||||
from backend.services import ops_alerts
|
||||
|
||||
monkeypatch.setenv("FAILURE_ALERTS_ENABLED", "true")
|
||||
db = MagicMock()
|
||||
with patch("backend.services.firestore_service.get_firestore_client", return_value=db), \
|
||||
patch.object(ops_alerts, "_should_alert", return_value=(False, False, 0, None)) as should, \
|
||||
patch.object(ops_alerts, "send_ops_alert") as send:
|
||||
assert ops_alerts.send_throttled_ops_alert("k", "msg", throttle_minutes=360) is False
|
||||
send.assert_not_called()
|
||||
assert should.call_args.kwargs["throttle_minutes"] == 360
|
||||
|
||||
with patch("backend.services.firestore_service.get_firestore_client", return_value=db), \
|
||||
patch.object(ops_alerts, "_should_alert", return_value=(True, False, 2, "ref")), \
|
||||
patch.object(ops_alerts, "send_ops_alert", return_value=True) as send, \
|
||||
patch.object(ops_alerts, "_mark_alerted") as mark:
|
||||
assert ops_alerts.send_throttled_ops_alert("k", "msg", throttle_minutes=360) is True
|
||||
assert "Collapsed 2" in send.call_args.args[0]
|
||||
mark.assert_called_once()
|
||||
|
||||
|
||||
# ---- per-caller degradation ----------------------------------------------------
|
||||
|
||||
|
||||
def _quota_client():
|
||||
client = MagicMock()
|
||||
client.models.generate_content.side_effect = QUOTA
|
||||
return client
|
||||
|
||||
|
||||
def test_auto_correct_quota_is_non_retryable_and_skips_gemini_leg():
|
||||
from backend.services.auto_correct.service import AutoCorrectService, AutoCorrectServiceError
|
||||
|
||||
service = AutoCorrectService()
|
||||
with patch("backend.services.gemini_client.get_genai_client", return_value=_quota_client()), \
|
||||
patch.object(gemini_client, "_maybe_alert"), \
|
||||
patch("backend.services.auto_correct.service.time.sleep") as sleep:
|
||||
with pytest.raises(AutoCorrectServiceError) as ei:
|
||||
service._call_model("gemini-3.8-flash", "sys", "user", job_id="j")
|
||||
assert ei.value.retryable is False and ei.value.status_code == 503
|
||||
sleep.assert_not_called()
|
||||
|
||||
|
||||
def test_auto_correct_compare_keeps_opus_when_gemini_quota_exhausted():
|
||||
from backend.services.auto_correct.service import AutoCorrectService, AutoCorrectServiceError
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
segments = [{"id": "s1", "words": [{"id": "w0", "text": "glory"}]}]
|
||||
refs = {"genius": {"segments": [{"text": "chlorine"}]}}
|
||||
sugg = {"op": "replace", "start_idx": 0, "end_idx": 0, "new_text": "chlorine",
|
||||
"reason": "r", "category": "mishearing", "confidence": 0.9}
|
||||
|
||||
def fake_call(model, *_a, **_k):
|
||||
if model.startswith("gemini"):
|
||||
raise AutoCorrectServiceError("Gemini is unavailable", status_code=503)
|
||||
return {"suggestions": [sugg]}, None
|
||||
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service.settings, "auto_correct_compare_models", "claude-opus-5-5;gemini-3.8-flash"), \
|
||||
patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_call_model", side_effect=fake_call):
|
||||
result = service.suggest(
|
||||
job_id="j", segments=segments, reference_lyrics=refs, artist="A", title="T",
|
||||
settings=AutoCorrectSettings(compare_models=True),
|
||||
)
|
||||
assert result.model == "claude-opus-5-5"
|
||||
assert any("gemini-3.8-flash failed" in w for w in result.warnings)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_judge_quota_returns_no_suggestion_and_alerts():
|
||||
from backend.services.match_judge import service as mj
|
||||
|
||||
async def no_candidates(*_a, **_k):
|
||||
return []
|
||||
|
||||
async def boom(*_a, **_k):
|
||||
raise QUOTA
|
||||
|
||||
with patch.object(gemini_client, "_maybe_alert") as alert:
|
||||
verdict = await mj.judge_match(
|
||||
"A", "T", search_tracks=no_candidates, ai_judge=boom, enabled=True
|
||||
)
|
||||
assert verdict.reason == "ai failed"
|
||||
alert.assert_called_once()
|
||||
|
||||
|
||||
def test_custom_lyrics_quota_is_clean_503():
|
||||
from backend.services.custom_lyrics.settings import GenerationSettings
|
||||
from backend.services.custom_lyrics_service import CustomLyricsService, CustomLyricsServiceError
|
||||
|
||||
service = CustomLyricsService()
|
||||
with patch("backend.services.gemini_client.get_genai_client", return_value=_quota_client()), \
|
||||
patch.object(gemini_client, "_maybe_alert"):
|
||||
with pytest.raises(CustomLyricsServiceError) as ei:
|
||||
service._call_gemini(system_prompt="s", user_prompt="u", pdf_bytes=None,
|
||||
settings=GenerationSettings())
|
||||
assert ei.value.status_code == 503
|
||||
assert "temporarily unavailable" in str(ei.value)
|
||||
|
||||
|
||||
def test_credit_eval_quota_goes_to_manual_review():
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
|
||||
svc = CreditEvaluationService.__new__(CreditEvaluationService)
|
||||
svc.settings = MagicMock(credit_eval_enabled=True, credit_eval_model="gemini-3.8-flash")
|
||||
signals = {"fingerprint_matches": [{"x": 1}], "ip_matches": [], "recent_signups_ip": 0,
|
||||
"recent_signups_fp": 0, "user_data": {}, "ip_geo": None, "user_agent": None}
|
||||
with patch.object(svc, "_collect_signals", return_value=signals), \
|
||||
patch.object(svc, "_log_evaluation"), \
|
||||
patch("backend.services.gemini_client.get_genai_client", return_value=_quota_client()), \
|
||||
patch.object(gemini_client, "_maybe_alert") as alert:
|
||||
evaluation = svc.evaluate("a@b.c", "welcome")
|
||||
assert evaluation.decision == "pending_review"
|
||||
alert.assert_called_once()
|
||||
|
||||
|
||||
def test_error_monitor_llm_does_not_retry_on_quota():
|
||||
from backend.services.error_monitor import llm_analysis
|
||||
|
||||
with patch.object(llm_analysis, "get_genai_client", return_value=_quota_client()), \
|
||||
patch.object(gemini_client, "_maybe_alert"), \
|
||||
patch.object(llm_analysis.time, "sleep") as sleep:
|
||||
with pytest.raises(FakeAPIError):
|
||||
llm_analysis._call_llm("sys", "user")
|
||||
sleep.assert_not_called()
|
||||
|
||||
|
||||
def test_classifier_ignores_implicit_context():
|
||||
"""A Gemini-unrelated 403 raised earlier must not be blamed on Gemini."""
|
||||
try:
|
||||
try:
|
||||
raise FakeAPIError(403, "PERMISSION_DENIED", "firestore says no")
|
||||
except FakeAPIError:
|
||||
raise ValueError("later, unrelated failure") # implicit __context__ only
|
||||
except ValueError as exc:
|
||||
assert not is_quota_or_billing_error(exc)
|
||||
@@ -51,6 +51,15 @@ class TestReportClientEvent:
|
||||
# Query string (may carry tokens) must be stripped before persisting.
|
||||
assert "SECRET" not in doc["url"]
|
||||
|
||||
def test_cold_start_waking_event_accepted(self, client, fresh_limiter_and_db):
|
||||
resp = client.post(
|
||||
"/api/client-events",
|
||||
json=_event(type="banner_waking", detail={"stall_ms": 5000, "since_reachable_ms": None}),
|
||||
)
|
||||
assert resp.status_code == 202
|
||||
(doc,) = fresh_limiter_and_db.collection.return_value.add.call_args[0]
|
||||
assert doc["type"] == "banner_waking"
|
||||
|
||||
def test_unknown_event_type_rejected(self, client):
|
||||
resp = client.post("/api/client-events", json=_event(type="something_else"))
|
||||
assert resp.status_code == 422
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import json
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -103,11 +104,11 @@ def test_text_only_happy_path(service: CustomLyricsService) -> None:
|
||||
assert result.line_count_mismatch is False
|
||||
assert result.iterations_used == 0
|
||||
assert result.model == "gemini-3.1-pro-preview"
|
||||
assert mock_client_cls.call_args.kwargs == {
|
||||
"vertexai": True,
|
||||
"project": "test-project",
|
||||
"location": "global",
|
||||
}
|
||||
# Gemini Developer API (API key) — never Vertex AI.
|
||||
kwargs = mock_client_cls.call_args.kwargs
|
||||
assert kwargs["api_key"] == os.environ["GEMINI_API_KEY"]
|
||||
assert kwargs["vertexai"] is False and "project" not in kwargs
|
||||
assert kwargs["http_options"].timeout == 300_000
|
||||
|
||||
|
||||
def test_docx_input_parsed_to_text(
|
||||
|
||||
@@ -285,25 +285,101 @@ class TestPostmarkRetry:
|
||||
def provider(self):
|
||||
return PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
|
||||
def test_html_403_then_success_is_retried(self, provider):
|
||||
"""The prod failure mode: nginx HTML 403 from Postmark's edge, then OK."""
|
||||
@pytest.fixture
|
||||
def mock_smtp(self):
|
||||
with patch("backend.services.email_service.smtplib.SMTP") as smtp_cls:
|
||||
self.smtp = smtp_cls.return_value
|
||||
yield smtp_cls
|
||||
|
||||
def test_html_403_falls_back_to_smtp_without_api_retries(self, provider, mock_smtp):
|
||||
"""The prod failure mode: nginx HTML 403 from Postmark's edge lasts hours."""
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.side_effect = [self._response(403, json_body=False), self._response(200)]
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is True
|
||||
assert result.message_id == "abc"
|
||||
assert mock_post.call_count == 2
|
||||
self.mock_sleep.assert_called_once_with(1.0)
|
||||
assert result.message_id is None
|
||||
assert mock_post.call_count == 1
|
||||
self.mock_sleep.assert_not_called()
|
||||
mock_smtp.assert_called_once_with("smtp.postmarkapp.com", 587, timeout=15)
|
||||
self.smtp.starttls.assert_called_once()
|
||||
self.smtp.login.assert_called_once_with("t", "t")
|
||||
msg = self.smtp.send_message.call_args.args[0]
|
||||
assert msg["To"] == "user@example.com"
|
||||
assert msg["From"] == "Nomad Karaoke <f@e.com>"
|
||||
assert msg["X-PM-Message-Stream"] == "outbound"
|
||||
assert self.smtp.send_message.call_args.kwargs["to_addrs"] == ["user@example.com"]
|
||||
|
||||
def test_html_403_gives_up_after_all_attempts(self, provider):
|
||||
def test_smtp_fallback_builds_multipart_with_cc_bcc(self, provider, mock_smtp):
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = provider.send_email_detailed(
|
||||
to_email="user@example.com",
|
||||
subject="Ünïcode subject",
|
||||
html_content="<p>hi</p>",
|
||||
text_content="hi",
|
||||
cc_emails=["cc@example.com", "CC@example.com"],
|
||||
bcc_emails=["bcc@example.com"],
|
||||
from_email_override="tenant@example.com",
|
||||
)
|
||||
|
||||
assert result.success is True
|
||||
msg = self.smtp.send_message.call_args.args[0]
|
||||
assert msg["Cc"] == "cc@example.com"
|
||||
assert msg["Bcc"] is None # BCC never appears in headers
|
||||
assert msg["Subject"] == "Ünïcode subject"
|
||||
assert msg["From"] == "Nomad Karaoke <tenant@example.com>"
|
||||
assert msg.get_body(("plain",)).get_content().strip() == "hi"
|
||||
assert msg.get_body(("html",)).get_content().strip() == "<p>hi</p>"
|
||||
assert self.smtp.send_message.call_args.kwargs["to_addrs"] == [
|
||||
"user@example.com", "cc@example.com", "bcc@example.com"
|
||||
]
|
||||
|
||||
def test_smtp_fallback_failure_reports_failure(self, provider, mock_smtp):
|
||||
import smtplib as _smtplib
|
||||
self.smtp.login.side_effect = _smtplib.SMTPAuthenticationError(535, b"bad")
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is False
|
||||
assert mock_post.call_count == 3
|
||||
assert [c.args[0] for c in self.mock_sleep.call_args_list] == [1.0, 3.0]
|
||||
|
||||
def test_smtp_fallback_connection_error_reports_failure(self, provider, mock_smtp):
|
||||
mock_smtp.side_effect = OSError("unreachable")
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is False
|
||||
|
||||
def test_smtp_fallback_rejects_header_injection_without_raising(self, provider, mock_smtp):
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = provider.send_email_detailed(
|
||||
to_email="user@example.com", subject="Song\nBcc: evil@example.com", html_content="<p>x</p>"
|
||||
)
|
||||
|
||||
assert result.success is False
|
||||
self.smtp.send_message.assert_not_called()
|
||||
|
||||
def test_quit_failure_after_send_still_reports_success(self, provider, mock_smtp):
|
||||
"""Postmark already accepted the message; a failed QUIT must not trigger a resend."""
|
||||
import smtplib as _smtplib
|
||||
self.smtp.quit.side_effect = _smtplib.SMTPServerDisconnected("gone")
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is True
|
||||
self.smtp.close.assert_called_once()
|
||||
|
||||
def test_smtp_success_clears_stale_message_id(self, provider, mock_smtp):
|
||||
provider.last_message_id = "old"
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
self._send(provider)
|
||||
|
||||
assert provider.last_message_id is None
|
||||
|
||||
@pytest.mark.parametrize("status", [429, 500, 503])
|
||||
def test_rate_limit_and_server_errors_are_retried(self, provider, status):
|
||||
@@ -340,14 +416,15 @@ class TestPostmarkRetry:
|
||||
assert result.success is True
|
||||
assert mock_post.call_count == 2
|
||||
|
||||
def test_connect_timeout_on_every_attempt_fails_cleanly(self, provider):
|
||||
def test_connect_timeout_on_every_attempt_falls_back_to_smtp(self, provider, mock_smtp):
|
||||
import requests as _requests
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.side_effect = _requests.ConnectTimeout("slow")
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is False
|
||||
assert result.success is True
|
||||
assert mock_post.call_count == 3
|
||||
self.smtp.send_message.assert_called_once()
|
||||
|
||||
def test_read_timeout_not_retried_to_avoid_duplicate_send(self, provider):
|
||||
"""Postmark may have accepted the message; it has no idempotency key."""
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Simple classification/extraction Gemini callers must request LOW thinking.
|
||||
|
||||
Gemini 3 Flash defaults to high/dynamic thinking, and thinking tokens are billed
|
||||
as output — the dominant Vertex cost. These callers do short structured
|
||||
extraction or grant/deny classification, so low thinking is ample (cost cut
|
||||
2026-10-01). Quality-sensitive callers (auto-correct, custom lyrics, lyrics
|
||||
translation) deliberately keep the model default and are not covered here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _fake_client():
|
||||
client = MagicMock()
|
||||
client.models.generate_content.return_value = SimpleNamespace(text="{}")
|
||||
return client
|
||||
|
||||
|
||||
def _thinking_level(client) -> str:
|
||||
config = client.models.generate_content.call_args.kwargs["config"]
|
||||
return config.thinking_config.thinking_level.value.lower()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"module_path",
|
||||
[
|
||||
"backend.services.match_judge.ai",
|
||||
"backend.services.match_judge.free_text",
|
||||
"backend.services.parse_titles.ai",
|
||||
],
|
||||
)
|
||||
def test_blocking_generate_uses_low_thinking(module_path) -> None:
|
||||
import importlib
|
||||
|
||||
mod = importlib.import_module(module_path)
|
||||
client = _fake_client()
|
||||
with patch("google.genai.Client", return_value=client):
|
||||
mod._blocking_generate("gemini-3.8-flash", "sys", "user")
|
||||
assert _thinking_level(client) == "low"
|
||||
|
||||
|
||||
def test_tenant_bulk_generate_uses_low_thinking() -> None:
|
||||
from backend.services.tenant_bulk import analyze
|
||||
|
||||
client = _fake_client()
|
||||
with patch("google.genai.Client", return_value=client):
|
||||
analyze.default_generate("sys", "user")
|
||||
assert _thinking_level(client) == "low"
|
||||
|
||||
|
||||
def test_credit_eval_uses_low_thinking() -> None:
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
|
||||
client = _fake_client()
|
||||
svc = CreditEvaluationService.__new__(CreditEvaluationService)
|
||||
svc.settings = SimpleNamespace(google_cloud_project="p", credit_eval_model="gemini-3.8-flash")
|
||||
with patch("google.genai.Client", return_value=client):
|
||||
svc._call_gemini("prompt")
|
||||
assert _thinking_level(client) == "low"
|
||||
@@ -106,7 +106,8 @@ def test_gives_up_after_max_attempts():
|
||||
|
||||
|
||||
def test_transient_error_retried_permanent_error_raised():
|
||||
transient = Exception("429 RESOURCE_EXHAUSTED")
|
||||
# Per-minute rate limit: transient, retried.
|
||||
transient = Exception("429 RESOURCE_EXHAUSTED quotaId GenerateRequestsPerMinutePerProjectPerModel")
|
||||
svc = make_service([transient, {"translations": ["uno"]}])
|
||||
assert svc.translate_lines(["one"], "es") == ["uno"]
|
||||
|
||||
@@ -116,6 +117,19 @@ def test_transient_error_retried_permanent_error_raised():
|
||||
assert svc._call_gemini.call_count == 1
|
||||
|
||||
|
||||
def test_quota_exhausted_not_retried_and_alerts():
|
||||
class QuotaError(Exception):
|
||||
code = 403
|
||||
status = "PERMISSION_DENIED"
|
||||
|
||||
svc = make_service([QuotaError("Your prepayment credits are depleted")])
|
||||
with patch("backend.services.gemini_client._maybe_alert") as alert:
|
||||
with pytest.raises(LyricsTranslationError, match="unavailable"):
|
||||
svc.translate_lines(["one"], "es")
|
||||
assert svc._call_gemini.call_count == 1
|
||||
alert.assert_called_once()
|
||||
|
||||
|
||||
def test_unsupported_language_raises():
|
||||
with pytest.raises(LyricsTranslationError):
|
||||
make_service([]).translate_lines(["one"], "xx")
|
||||
|
||||
@@ -122,3 +122,228 @@ async def test_lyrics_worker_trigger_swallows_errors() -> None:
|
||||
with patch("backend.services.worker_service.WorkerService", return_value=ws):
|
||||
await _trigger_proactive_auto_correct("job-1", job_log) # must not raise
|
||||
job_log.warning.assert_called()
|
||||
|
||||
|
||||
# ---- de-duplication (lyrics trigger vs screens pre-apply race) ----
|
||||
|
||||
import google.api_core.exceptions as gexc # noqa: E402
|
||||
|
||||
|
||||
class _FakeBlob:
|
||||
def __init__(self, bucket, path):
|
||||
self.bucket, self.path = bucket, path
|
||||
self.generation = None
|
||||
|
||||
def upload_from_string(self, data, content_type=None, if_generation_match=None):
|
||||
current = self.bucket.objects.get(self.path)
|
||||
current_gen = current[0] if current else 0
|
||||
if if_generation_match is not None and if_generation_match != current_gen:
|
||||
raise gexc.PreconditionFailed("generation mismatch")
|
||||
self.bucket.next_gen += 1
|
||||
self.generation = self.bucket.next_gen
|
||||
self.bucket.objects[self.path] = (self.generation, data)
|
||||
|
||||
def download_as_bytes(self):
|
||||
return self.bucket.objects[self.path][1].encode()
|
||||
|
||||
def delete(self, if_generation_match=None):
|
||||
current = self.bucket.objects.get(self.path)
|
||||
if current is None:
|
||||
raise gexc.NotFound("gone")
|
||||
if if_generation_match is not None and if_generation_match != current[0]:
|
||||
raise gexc.PreconditionFailed("generation mismatch")
|
||||
del self.bucket.objects[self.path]
|
||||
|
||||
|
||||
class _FakeBucket:
|
||||
def __init__(self):
|
||||
self.objects: dict = {}
|
||||
self.next_gen = 100
|
||||
|
||||
def blob(self, path):
|
||||
return _FakeBlob(self, path)
|
||||
|
||||
def get_blob(self, path):
|
||||
if path not in self.objects:
|
||||
return None
|
||||
b = _FakeBlob(self, path)
|
||||
b.generation = self.objects[path][0]
|
||||
return b
|
||||
|
||||
def put_lease(self, job_id, acquired_at):
|
||||
import json as _json
|
||||
self.next_gen += 1
|
||||
self.objects[f"jobs/{job_id}/lyrics/auto_correct_inflight.json"] = (
|
||||
self.next_gen, _json.dumps({"acquired_at": acquired_at}))
|
||||
|
||||
|
||||
def _patch_with_bucket(service):
|
||||
p_set, p_st, p_jm, _p_svc, storage = _patch(service=service)
|
||||
bucket = _FakeBucket()
|
||||
storage.bucket = bucket
|
||||
storage.file_exists.side_effect = lambda p: p.endswith("corrections.json") or p in bucket.objects
|
||||
return p_set, p_st, p_jm, storage, bucket
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_calls_on_same_instance_share_one_run() -> None:
|
||||
"""Regression (job 96cf1100): the lyrics trigger and the screens pre-apply
|
||||
both called this within seconds and each ran the multi-model suggest."""
|
||||
import asyncio as _asyncio
|
||||
import threading
|
||||
|
||||
release = threading.Event()
|
||||
svc = MagicMock()
|
||||
|
||||
def _slow_suggest(**_kw):
|
||||
release.wait(5)
|
||||
return SimpleNamespace(suggestions=[1, 2, 3], model="m", elapsed_seconds=1.0)
|
||||
|
||||
svc.suggest.side_effect = _slow_suggest
|
||||
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
|
||||
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
|
||||
first = _asyncio.create_task(process_proactive_auto_correct("job-dup"))
|
||||
await _asyncio.sleep(0.05)
|
||||
assert "jobs/job-dup/lyrics/auto_correct_inflight.json" in bucket.objects # lease held
|
||||
second = _asyncio.create_task(process_proactive_auto_correct("job-dup"))
|
||||
await _asyncio.sleep(0.05)
|
||||
release.set()
|
||||
r1, r2 = await _asyncio.gather(first, second)
|
||||
assert svc.suggest.call_count == 1
|
||||
assert r1 == r2 == {"status": "generated", "suggestions": 3}
|
||||
assert bucket.objects == {} # our lease released
|
||||
|
||||
# A later (non-concurrent) call isn't blocked by a leftover in-flight entry.
|
||||
await process_proactive_auto_correct("job-dup")
|
||||
assert svc.suggest.call_count == 2 # in prod this hits the service's own GCS cache
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_peer_instance_holding_lease_is_awaited_not_duplicated(monkeypatch) -> None:
|
||||
import time as _time
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
monkeypatch.setattr(w, "PEER_POLL_SECONDS", 0)
|
||||
svc = MagicMock()
|
||||
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
|
||||
bucket.put_lease("job-peer", _time.time()) # fresh lease held by another instance
|
||||
peer_cache = iter([None, None, [{"id": "s1"}, {"id": "s2"}]])
|
||||
with p_set, p_st, p_jm, \
|
||||
patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc), \
|
||||
patch("backend.services.auto_approval.executor._load_ai_suggestions",
|
||||
side_effect=lambda *_a: next(peer_cache)):
|
||||
result = await process_proactive_auto_correct("job-peer")
|
||||
assert result == {"status": "deduped", "suggestions": 2}
|
||||
svc.suggest.assert_not_called()
|
||||
assert "jobs/job-peer/lyrics/auto_correct_inflight.json" in bucket.objects # never released theirs
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stale_peer_lease_is_taken_over_with_generation_fence() -> None:
|
||||
svc = MagicMock()
|
||||
svc.suggest.return_value = SimpleNamespace(suggestions=[1], model="m", elapsed_seconds=1.0)
|
||||
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
|
||||
bucket.put_lease("job-stale", 0) # leftover from a crashed instance
|
||||
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
|
||||
result = await process_proactive_auto_correct("job-stale")
|
||||
assert result["status"] == "generated"
|
||||
svc.suggest.assert_called_once()
|
||||
assert bucket.objects == {}
|
||||
|
||||
|
||||
def test_stale_takeover_loses_to_a_concurrent_takeover() -> None:
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
bucket = _FakeBucket()
|
||||
bucket.put_lease("j", 0)
|
||||
storage = SimpleNamespace(bucket=bucket)
|
||||
real_get_blob = bucket.get_blob
|
||||
|
||||
def _get_blob_then_race(path):
|
||||
observed = real_get_blob(path)
|
||||
bucket.put_lease("j", 0) # another instance takes over after our read
|
||||
return observed
|
||||
|
||||
bucket.get_blob = _get_blob_then_race
|
||||
assert w._acquire_lease(storage, "j") == (False, None)
|
||||
|
||||
|
||||
def test_own_lease_after_lost_create_response_counts_as_held(monkeypatch) -> None:
|
||||
"""Upload retry after a lost response 412s on our own write: still ours."""
|
||||
import json as _json
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
bucket = _FakeBucket()
|
||||
storage = SimpleNamespace(bucket=bucket)
|
||||
monkeypatch.setattr(w.uuid, "uuid4", lambda: SimpleNamespace(hex="mytoken"))
|
||||
real_blob = bucket.blob
|
||||
|
||||
def _blob_lost_response(path):
|
||||
b = real_blob(path)
|
||||
orig = b.upload_from_string
|
||||
|
||||
def _upload(data, content_type=None, if_generation_match=None):
|
||||
orig(data, content_type=content_type, if_generation_match=if_generation_match)
|
||||
raise gexc.PreconditionFailed("retry of a create that already landed")
|
||||
|
||||
b.upload_from_string = _upload
|
||||
return b
|
||||
|
||||
bucket.blob = _blob_lost_response
|
||||
held, gen = w._acquire_lease(storage, "j")
|
||||
assert held and gen == bucket.objects["jobs/j/lyrics/auto_correct_inflight.json"][0]
|
||||
assert _json.loads(bucket.objects["jobs/j/lyrics/auto_correct_inflight.json"][1])["token"] == "mytoken"
|
||||
|
||||
|
||||
def test_release_never_deletes_a_lease_someone_else_took_over() -> None:
|
||||
import time as _time
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
bucket = _FakeBucket()
|
||||
storage = SimpleNamespace(bucket=bucket)
|
||||
held, gen = w._acquire_lease(storage, "j")
|
||||
assert held and gen is not None
|
||||
bucket.put_lease("j", _time.time()) # superseded (e.g. our run outlived the TTL)
|
||||
w._release_lease(storage, "j", gen)
|
||||
assert "jobs/j/lyrics/auto_correct_inflight.json" in bucket.objects
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_peer_failure_does_not_regenerate(monkeypatch) -> None:
|
||||
import time as _time
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
monkeypatch.setattr(w, "PEER_POLL_SECONDS", 0)
|
||||
svc = MagicMock()
|
||||
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
|
||||
bucket.put_lease("job-peer-fail", _time.time())
|
||||
lease = "jobs/job-peer-fail/lyrics/auto_correct_inflight.json"
|
||||
|
||||
def _no_cache(*_a):
|
||||
bucket.objects.pop(lease, None) # peer finishes (fails) without writing a cache
|
||||
return None
|
||||
|
||||
with p_set, p_st, p_jm, \
|
||||
patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc), \
|
||||
patch("backend.services.auto_approval.executor._load_ai_suggestions", side_effect=_no_cache):
|
||||
result = await process_proactive_auto_correct("job-peer-fail")
|
||||
assert result == {"status": "skipped", "reason": "peer_failed"}
|
||||
svc.suggest.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_timed_out_run_keeps_its_lease(monkeypatch) -> None:
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
svc = MagicMock()
|
||||
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
|
||||
|
||||
async def _timeout(*_a, **_k):
|
||||
raise TimeoutError()
|
||||
|
||||
monkeypatch.setattr(w, "_run_suggest", _timeout)
|
||||
with p_set, p_st, p_jm:
|
||||
result = await process_proactive_auto_correct("job-slow")
|
||||
assert result["status"] == "error"
|
||||
# suggest() may still be running in its thread: the lease must stay until TTL.
|
||||
assert "jobs/job-slow/lyrics/auto_correct_inflight.json" in bucket.objects
|
||||
@@ -205,3 +205,27 @@ class TestSystemStatusAdmin:
|
||||
assert admin["active_zone"] == "us-central1-a"
|
||||
# "n2c" family token → n2-highcpu-16 (inferred from the VM name).
|
||||
assert admin["active_machine_type"] == "n2-highcpu-16"
|
||||
|
||||
|
||||
class TestAudioSeparatorStatus:
|
||||
"""Separation runs in the audio-separation-job GPU Cloud Run Job; the
|
||||
standalone audio-separator service was shut down (2026-10-01), so the
|
||||
status must not depend on AUDIO_SEPARATOR_API_URL or call anything."""
|
||||
|
||||
def test_reports_ok_without_api_url(self, monkeypatch):
|
||||
from backend.api.routes.health import check_audio_separator_status
|
||||
|
||||
monkeypatch.delenv("AUDIO_SEPARATOR_API_URL", raising=False)
|
||||
status = check_audio_separator_status()
|
||||
assert status["available"] is True
|
||||
assert status["status"] == "ok"
|
||||
assert status["mode"] == "gpu_job"
|
||||
assert "version" in status
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_endpoint_matches_status_helper(self):
|
||||
from backend.api.routes.health import audio_separator_health
|
||||
|
||||
from backend.api.routes.health import check_audio_separator_status
|
||||
|
||||
assert await audio_separator_health() == check_audio_separator_status()
|
||||
@@ -14,30 +14,177 @@ failure just means the UI does the call on demand instead.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from typing import Dict, Optional, Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# --- De-duplication -------------------------------------------------------
|
||||
# Two callers race to generate the same suggestions: the lyrics worker's HTTP
|
||||
# trigger (internal /workers/auto-correct) and the screens worker's pre-apply
|
||||
# (ensure_and_pre_apply → generate on cache miss). Screens is triggered BEFORE
|
||||
# the lyrics worker fires its proactive trigger, so the pre-apply routinely
|
||||
# checks the cache while the proactive run is still in flight and starts a
|
||||
# second identical multi-model run (prod 2026-09-17..10-01: 92/167 jobs ran it
|
||||
# twice, ~$0.07 each). Two guards:
|
||||
# 1. In-process single-flight: a concurrent caller on the same instance awaits
|
||||
# the in-flight run instead of starting another (~90% of duplicates).
|
||||
# 2. Cross-instance GCS lease (create-only object): a caller on another
|
||||
# instance waits for the holder's cache instead of regenerating.
|
||||
_INFLIGHT: Dict[str, "asyncio.Task[dict]"] = {}
|
||||
|
||||
LEASE_PATH = "jobs/{job_id}/lyrics/auto_correct_inflight.json"
|
||||
# Generation is bounded at 180s; anything older is a crashed holder's leftover.
|
||||
LEASE_TTL_SECONDS = 240
|
||||
# How long a non-holder waits for the holder's cache (fits inside the lyrics
|
||||
# trigger's 200s HTTP timeout).
|
||||
PEER_WAIT_SECONDS = 150
|
||||
PEER_POLL_SECONDS = 3
|
||||
|
||||
|
||||
def _precondition_failed():
|
||||
try:
|
||||
from google.api_core.exceptions import PreconditionFailed
|
||||
return PreconditionFailed
|
||||
except Exception: # pragma: no cover - google libs always present in prod
|
||||
return ()
|
||||
|
||||
|
||||
def _write_lease(storage, path: str, if_generation_match: int, token: str) -> Optional[int]:
|
||||
"""Conditional lease write; returns the generation we wrote (our fence token)."""
|
||||
blob = storage.bucket.blob(path)
|
||||
blob.upload_from_string(
|
||||
json.dumps({"acquired_at": time.time(), "token": token}),
|
||||
content_type="application/json",
|
||||
if_generation_match=if_generation_match,
|
||||
)
|
||||
return blob.generation
|
||||
|
||||
|
||||
def _acquire_lease(storage, job_id: str) -> Tuple[bool, Optional[int]]:
|
||||
"""Try to take the cross-instance lease.
|
||||
|
||||
Returns ``(held, generation)``. Every write is generation-fenced: create-only
|
||||
first, and a stale-lease takeover only succeeds against the exact generation
|
||||
we observed, so two instances can't both take over the same stale lease.
|
||||
Fails OPEN (``(True, None)``) on unexpected storage errors — the lease is an
|
||||
optimisation and must never stop suggestions from being generated.
|
||||
"""
|
||||
path = LEASE_PATH.format(job_id=job_id)
|
||||
precondition_failed = _precondition_failed()
|
||||
token = uuid.uuid4().hex
|
||||
try:
|
||||
try:
|
||||
return True, _write_lease(storage, path, if_generation_match=0, token=token)
|
||||
except precondition_failed:
|
||||
pass
|
||||
existing = storage.bucket.get_blob(path)
|
||||
if existing is None: # holder released between our two calls — retry once
|
||||
try:
|
||||
return True, _write_lease(storage, path, if_generation_match=0, token=token)
|
||||
except precondition_failed:
|
||||
return False, None
|
||||
try:
|
||||
lease = json.loads(existing.download_as_bytes())
|
||||
except Exception: # noqa: BLE001 — unreadable lease → treat as stale
|
||||
lease = {}
|
||||
if lease.get("token") == token:
|
||||
# Our own create succeeded but its response was lost and the client's
|
||||
# retry hit the precondition — we DO hold it.
|
||||
return True, existing.generation
|
||||
acquired_at = float(lease.get("acquired_at") or 0)
|
||||
if time.time() - acquired_at <= LEASE_TTL_SECONDS:
|
||||
return False, None
|
||||
# Stale (crashed holder): take over only the generation we just read.
|
||||
try:
|
||||
return True, _write_lease(storage, path, if_generation_match=existing.generation, token=token)
|
||||
except precondition_failed:
|
||||
return False, None # another instance took it over first
|
||||
except Exception as e: # noqa: BLE001 — fail open
|
||||
logger.info("[job:%s] auto-correct lease unavailable, proceeding: %s", job_id, e)
|
||||
return True, None
|
||||
|
||||
|
||||
def _release_lease(storage, job_id: str, generation: Optional[int]) -> None:
|
||||
"""Delete OUR lease generation only — never a lease someone else took over."""
|
||||
if generation is None:
|
||||
return # unknown fence token: let it go stale rather than risk deleting another's
|
||||
try:
|
||||
storage.bucket.blob(LEASE_PATH.format(job_id=job_id)).delete(if_generation_match=generation)
|
||||
except Exception as e: # noqa: BLE001 — gone/superseded/failed: it just goes stale
|
||||
logger.info("[job:%s] auto-correct lease not released: %s", job_id, e)
|
||||
|
||||
|
||||
async def _wait_for_peer(storage, job_id: str) -> dict:
|
||||
"""Another instance is generating: wait for its cache instead of re-running."""
|
||||
from backend.services.auto_approval.executor import _load_ai_suggestions
|
||||
|
||||
lease_path = LEASE_PATH.format(job_id=job_id)
|
||||
deadline = time.monotonic() + PEER_WAIT_SECONDS
|
||||
while time.monotonic() < deadline:
|
||||
# Off-loop: these are blocking GCS calls, polled repeatedly.
|
||||
suggestions = await asyncio.to_thread(_load_ai_suggestions, storage, job_id)
|
||||
if suggestions is not None:
|
||||
logger.info("[job:%s] proactive auto-correct deduped: used peer's cache", job_id)
|
||||
return {"status": "deduped", "suggestions": len(suggestions)}
|
||||
if not await asyncio.to_thread(storage.file_exists, lease_path):
|
||||
# Holder finished without a cache (its run failed). Don't retry here:
|
||||
# the review UI requests suggestions on demand as the fallback.
|
||||
suggestions = await asyncio.to_thread(_load_ai_suggestions, storage, job_id)
|
||||
if suggestions is not None:
|
||||
return {"status": "deduped", "suggestions": len(suggestions)}
|
||||
return {"status": "skipped", "reason": "peer_failed"}
|
||||
await asyncio.sleep(PEER_POLL_SECONDS)
|
||||
logger.info("[job:%s] proactive auto-correct: peer still running after %ss", job_id, PEER_WAIT_SECONDS)
|
||||
return {"status": "skipped", "reason": "peer_timeout"}
|
||||
|
||||
|
||||
async def process_proactive_auto_correct(job_id: str) -> dict:
|
||||
"""Generate + cache auto-correct suggestions for a job. Never raises.
|
||||
|
||||
Returns a small status dict for the endpoint to echo. Gated by
|
||||
settings.auto_correct_proactive_enabled; reads the corrections.json the
|
||||
Single-flight per job (see the de-duplication note above): concurrent
|
||||
callers share one generation run.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
if not get_settings().auto_correct_proactive_enabled:
|
||||
return {"status": "disabled"}
|
||||
|
||||
existing = _INFLIGHT.get(job_id)
|
||||
if existing is not None:
|
||||
logger.info("[job:%s] proactive auto-correct already in flight here; joining it", job_id)
|
||||
try:
|
||||
# shield: a cancelled joiner must not cancel the shared run
|
||||
return await asyncio.shield(existing)
|
||||
except Exception as e: # noqa: BLE001 — never raise
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
task = asyncio.ensure_future(_generate(job_id))
|
||||
_INFLIGHT[job_id] = task
|
||||
|
||||
def _clear(t, _job_id=job_id):
|
||||
if _INFLIGHT.get(_job_id) is t:
|
||||
_INFLIGHT.pop(_job_id, None)
|
||||
|
||||
task.add_done_callback(_clear)
|
||||
try:
|
||||
return await asyncio.shield(task)
|
||||
except Exception as e: # noqa: BLE001 — never raise
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
|
||||
async def _generate(job_id: str) -> dict:
|
||||
"""Generate + cache auto-correct suggestions for a job. Never raises.
|
||||
|
||||
Returns a small status dict for the endpoint to echo. Reads the corrections.json the
|
||||
lyrics worker just wrote (the same data the review UI loads on first open)
|
||||
and runs the multi-model path with default settings so the cache key lines
|
||||
up with the UI request.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.auto_correct_proactive_enabled:
|
||||
return {"status": "disabled"}
|
||||
|
||||
try:
|
||||
from backend.services.auto_correct import get_auto_correct_service
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
storage = StorageService()
|
||||
@@ -57,30 +204,52 @@ async def process_proactive_auto_correct(job_id: str) -> dict:
|
||||
)
|
||||
return {"status": "skipped", "reason": "no_references"}
|
||||
|
||||
job = JobManager().get_job(job_id)
|
||||
service = get_auto_correct_service()
|
||||
result = await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
service.suggest,
|
||||
job_id=job_id,
|
||||
segments=segments,
|
||||
reference_lyrics=reference_lyrics,
|
||||
artist=getattr(job, "artist", None) if job else None,
|
||||
title=getattr(job, "title", None) if job else None,
|
||||
# Must match what the review UI sends (default settings,
|
||||
# multi-model) or the cache key won't line up.
|
||||
settings=AutoCorrectSettings(compare_models=True),
|
||||
# Already loaded — saves the service re-fetching it for the
|
||||
# deterministic (P4/P5) generators.
|
||||
correction_data=data,
|
||||
),
|
||||
timeout=180,
|
||||
)
|
||||
logger.info(
|
||||
"[job:%s] proactive auto-correct done: %d suggestions cached (models=%s, %.1fs)",
|
||||
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
|
||||
)
|
||||
return {"status": "generated", "suggestions": len(result.suggestions)}
|
||||
# Off-loop: up to 4 blocking GCS round-trips.
|
||||
held, lease_generation = await asyncio.to_thread(_acquire_lease, storage, job_id)
|
||||
if not held:
|
||||
return await _wait_for_peer(storage, job_id)
|
||||
|
||||
try:
|
||||
return await _run_suggest(job_id, data, segments, reference_lyrics)
|
||||
except asyncio.TimeoutError:
|
||||
# wait_for can't stop the worker thread: suggest() may still finish
|
||||
# and write the cache. Keep the lease (it expires via the TTL) so no
|
||||
# one starts a duplicate run meanwhile.
|
||||
lease_generation = None
|
||||
raise
|
||||
finally:
|
||||
await asyncio.to_thread(_release_lease, storage, job_id, lease_generation)
|
||||
except Exception as e: # noqa: BLE001 — proactive is best-effort, never fatal
|
||||
logger.warning("[job:%s] proactive auto-correct failed (non-fatal): %s", job_id, e, exc_info=True)
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
|
||||
async def _run_suggest(job_id: str, data: dict, segments: list, reference_lyrics: dict) -> dict:
|
||||
from backend.services.auto_correct import get_auto_correct_service
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
job = JobManager().get_job(job_id)
|
||||
service = get_auto_correct_service()
|
||||
result = await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
service.suggest,
|
||||
job_id=job_id,
|
||||
segments=segments,
|
||||
reference_lyrics=reference_lyrics,
|
||||
artist=getattr(job, "artist", None) if job else None,
|
||||
title=getattr(job, "title", None) if job else None,
|
||||
# Must match what the review UI sends (default settings,
|
||||
# multi-model) or the cache key won't line up.
|
||||
settings=AutoCorrectSettings(compare_models=True),
|
||||
# Already loaded — saves the service re-fetching it for the
|
||||
# deterministic (P4/P5) generators.
|
||||
correction_data=data,
|
||||
),
|
||||
timeout=180,
|
||||
)
|
||||
logger.info(
|
||||
"[job:%s] proactive auto-correct done: %d suggestions cached (models=%s, %.1fs)",
|
||||
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
|
||||
)
|
||||
return {"status": "generated", "suggestions": len(result.suggestions)}
|
||||
+6
-5
@@ -736,7 +736,7 @@ Content-Type: application/json
|
||||
|
||||
AI correction suggestions for the lyrics review UI. Stateless: one whole-song
|
||||
LLM call per model (Claude models use the Anthropic API via the
|
||||
`anthropic-api-key` secret, Gemini models use Vertex AI) compares the
|
||||
`anthropic-api-key` secret, Gemini models use the Gemini Developer API, key `gemini-api-key`) compares the
|
||||
client's current transcription against the reference sources and returns
|
||||
word-id-keyed suggestions. Nothing is applied server-side — the reviewer
|
||||
accepts/rejects each suggestion in the UI and persistence flows through the
|
||||
@@ -1017,7 +1017,7 @@ Content-Type: application/json
|
||||
```
|
||||
|
||||
Decides the official formatting for a typed artist/title and whether it matches a
|
||||
real song. A deterministic normalizer + the catalog run first; a light Vertex
|
||||
real song. A deterministic normalizer + the catalog run first; a light Gemini
|
||||
Gemini model (`MATCH_JUDGE_MODEL`, default `gemini-3.8-flash`) is consulted
|
||||
**only** when those aren't confident. `audio_confidence_tier` (1=strong..3=weak,
|
||||
optional) lets the judge tell whether weak audio results hint at a typo. The call
|
||||
@@ -1340,7 +1340,7 @@ Artist/Title. Pure analysis — filenames only, no uploads, no state written.
|
||||
- **Auth:** tenant session required; gated on the tenant's `features.bulk_upload` flag (403 otherwise).
|
||||
- **Limits:** max 100 audio files per request (non-audio files don't count toward the cap; 2000-filename payload guard).
|
||||
- **Two passes:** deterministic regex for the `S<code>-<1|2> Artist - Title <Guide|BV|Instru>`
|
||||
convention, then a Vertex-Gemini pass (`backend/services/tenant_bulk/analyze.py`) for
|
||||
convention, then a Gemini pass (`backend/services/tenant_bulk/analyze.py`) for
|
||||
whatever the regex couldn't confidently pair. Falls back to regex-only if the model errors.
|
||||
|
||||
Response:
|
||||
@@ -2930,8 +2930,9 @@ POST /api/client-events
|
||||
```
|
||||
|
||||
Unauthenticated, rate-limited (120/min/IP — sized so a many-tab burst from one IP is fully recorded), bot-filtered. The frontend reports every
|
||||
user-visible degraded-service surface: `banner_reconnecting`, `banner_unavailable`
|
||||
(the connectivity banner — reported by `BackendStatusBanner`), `lyrics_load_failed`
|
||||
user-visible degraded-service surface: `banner_reconnecting`, `banner_unavailable`,
|
||||
`banner_waking` (the connectivity banner — reported by `BackendStatusBanner`; `banner_waking`
|
||||
is the calm "starting up our karaoke servers" cold-start state), `lyrics_load_failed`
|
||||
(review page "temporarily unavailable"), `waveform_slow` / `waveform_failed`
|
||||
(Waveforms-mode strips late or missing). Body: `{type, url, job_id?, user_email?,
|
||||
locale, release, detail?}` — `detail` is size-capped server-side (≤12 keys, ≤200
|
||||
|
||||
@@ -252,7 +252,7 @@ LyricsTranscriber LyricsTranscriber
|
||||
|---------|---------|----------|
|
||||
| Cloud Run GPU Job (L4, us-east4) | Audio stem separation — `Separator` runs directly in the audio worker Job (no HTTP hop) | Yes |
|
||||
| AudioShake | Lyrics transcription | Yes |
|
||||
| Vertex AI | Agentic AI correction (Gemini 3.8 Flash) | Default off (SKIP_CORRECTION=false to enable) |
|
||||
| Gemini Developer API (`gemini-api-key`) | Agentic AI correction (Gemini 3.8 Flash) | Default off (SKIP_CORRECTION=false to enable) |
|
||||
| Genius | Reference lyrics | Yes |
|
||||
| Flacfetch | Audio downloads (YouTube, torrents) | Recommended* |
|
||||
| YouTube API | Video upload | Optional |
|
||||
@@ -605,10 +605,13 @@ Audio stem separation runs **directly inside the audio worker Cloud Run Job**
|
||||
- **Two-stage ensemble preset** — `instrumental_clean` (stage 1) + `karaoke` (stage 2).
|
||||
- **Model cache** — Models are downloaded to `model_file_dir` (GCS-backed or local) and reused across executions.
|
||||
|
||||
**The `audio-separator` Cloud Run GPU service** (us-east4, scale-to-zero) is no longer used by
|
||||
prod gen jobs, but it still serves external remote-separation clients (`audio-separator-remote` /
|
||||
local `karaoke-gen` CLI with `AUDIO_SEPARATOR_API_URL`; ~40 `/separate` calls/month as of
|
||||
2026-09). Keep it at min-instances 0; don't remove it without checking its request logs first.
|
||||
**The `audio-separator` Cloud Run GPU service** (us-east4) was **shut down on 2026-10-01**
|
||||
(GCP cost cut, ~$22/mo). Prod gen jobs never used it; its only callers were Andrew's own
|
||||
remote-separation clients (`audio-separator-remote` / local `karaoke-gen` CLI with
|
||||
`AUDIO_SEPARATOR_API_URL`). Leave `AUDIO_SEPARATOR_API_URL` unset to separate locally. It
|
||||
is still defined in Pulumi behind the `audioSeparatorServiceEnabled` flag — see
|
||||
[GCP-COST-OPTIMIZATION.md](GCP-COST-OPTIMIZATION.md#audio-separator-service-shut-down-on-demand-redeploy)
|
||||
to bring it back on demand.
|
||||
|
||||
### Quick version (kjbox make-it jobs)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Disaster Recovery Runbook
|
||||
|
||||
**Last updated:** 2026-06-18
|
||||
**Last updated:** 2026-10-01
|
||||
**Design doc:** `docs/archive/2026-03-27-business-continuity-design.md`
|
||||
**Implementation plan:** `docs/archive/2026-03-29-business-continuity-plan.md`
|
||||
**External services reference:** `docs/archive/2026-03-29-external-services-config.md`
|
||||
@@ -13,7 +13,7 @@
|
||||
| BigQuery (weekly) | S3 `bigquery/daily-refresh/` | Load Parquet files | 7 days |
|
||||
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
|
||||
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
|
||||
| GCS job files | S3 `gcs/job-files/` | Sync to new bucket | 24h |
|
||||
| GCS job files | **GCS only** — object versioning (non-current kept 30d) + soft-delete (7d). Off-site S3 copy **stopped 2026-10-01**; S3 `gcs/job-files/` is a frozen snapshot up to 2026-09-30 | Restore non-current/soft-deleted generation in GCS | N/A off-site (frozen); in-GCS recovery window 7–30d |
|
||||
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 7 days (weekly, Sundays; incremental) |
|
||||
| Secret Manager | S3 `secrets/YYYY-MM-DD.bin` (sealed-box encrypted) | Decrypt with private key from KeepassXC | 24h |
|
||||
| AWS credentials (function) | GCP Secret Manager `aws-backup-credentials` | Read directly | On-change |
|
||||
@@ -109,7 +109,7 @@ gcloud storage cp gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/file.flac#GE
|
||||
gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/file.flac
|
||||
```
|
||||
|
||||
**Option C — Restore from S3 (if A and B both miss the window):**
|
||||
**Option C — Restore from S3 (if A and B both miss the window; only works for files that existed by 2026-09-30 — the nightly S3 copy of job files was stopped 2026-10-01, see § "Job files: off-site copy stopped"):**
|
||||
```bash
|
||||
aws s3 sync s3://nomadkaraoke-backup/gcs/job-files/jobs/JOB_ID/ /tmp/gcs-restore/
|
||||
|
||||
@@ -209,7 +209,9 @@ aws s3api restore-object --bucket nomadkaraoke-backup \
|
||||
# Create new bucket
|
||||
gsutil mb -l US-CENTRAL1 gs://karaoke-gen-storage-nomadkaraoke-v2/
|
||||
|
||||
# Sync from S3 (146 GB last we measured — needs a host with comparable disk + bandwidth)
|
||||
# Sync from S3 (146 GB last we measured — needs a host with comparable disk + bandwidth).
|
||||
# NOTE: frozen snapshot — job files created/changed after 2026-09-30 are NOT in S3
|
||||
# (off-site copy stopped 2026-10-01). Newer outputs must be regenerated.
|
||||
aws s3 sync s3://nomadkaraoke-backup/gcs/job-files/ /tmp/gcs-restore/
|
||||
gsutil -m cp -r /tmp/gcs-restore/ gs://karaoke-gen-storage-nomadkaraoke-v2/
|
||||
```
|
||||
@@ -301,7 +303,7 @@ Some external services lock to redirect URIs or treat the old GCP project ID as
|
||||
- YouTube OAuth (redirect URIs)
|
||||
- Stripe webhook endpoint URL (secret regenerates)
|
||||
- AudioShake API key (rotate as a precaution if old project was compromised)
|
||||
- Gemini / Vertex API (project-scoped — needs new project enabled)
|
||||
- Gemini Developer API key (`gemini-api-key` secret; key lives in an AI Studio project outside nomadkaraoke — just copy the secret)
|
||||
- Discord webhook URLs (re-issue if old GCP exposure could have leaked them)
|
||||
- Cloudflare API tokens (rotate)
|
||||
|
||||
@@ -462,13 +464,13 @@ export AWS_DEFAULT_REGION=us-east-1
|
||||
|
||||
## Backup freshness monitor
|
||||
|
||||
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/manifest.json` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
|
||||
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/manifest.json` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
|
||||
|
||||
Per-prefix limits reflect each prefix's **S3 (off-site)** cadence, which is not the same as its GCS-staging cadence:
|
||||
|
||||
| Prefix | S3 upload cadence | Monitor limit |
|
||||
|--------|-------------------|---------------|
|
||||
| `gcs/job-files/`, `secrets/` | nightly | 36h |
|
||||
| `secrets/` | nightly | 36h |
|
||||
| `firestore/`, `bigquery/daily-refresh/` | weekly (Sundays) | 192h (≈8 days) |
|
||||
| `git-repos/manifest.json` | weekly (Sundays), incremental | 192h (≈8 days) + manifest must show 0 bundle errors |
|
||||
|
||||
@@ -549,6 +551,23 @@ re-import). The raw source files are not.
|
||||
| Full Spotify dataset retrieval + transfer (~100 GB) | ~$25 total |
|
||||
| Full GCS job-files egress (~150 GB) | ~$14 |
|
||||
|
||||
## Job files: off-site copy stopped (2026-10-01)
|
||||
|
||||
The nightly `backup-to-aws` step that delta-synced `karaoke-gen-storage-nomadkaraoke`
|
||||
(`jobs/`, `tenants/`, `themes/`) → staging `gcs/job-files/` → S3 was removed on
|
||||
2026-10-01 as a GCP cost cut (~$15/mo cross-cloud egress; business cash constraint).
|
||||
Job outputs are regenerable from their inputs, and the primary bucket keeps
|
||||
**object versioning** (non-current versions deleted 30 days after being superseded)
|
||||
plus **7-day soft-delete**, which covers accidental overwrite/delete. What is
|
||||
*not* covered any more: loss of the whole GCP project/bucket for files created after
|
||||
2026-09-30. The existing S3 `gcs/job-files/` objects were deliberately left in place
|
||||
(frozen snapshot). Firestore (weekly), secrets (nightly), BigQuery, kn-data and git
|
||||
bundle backups are unchanged. The freshness monitor no longer checks `gcs/job-files/`.
|
||||
|
||||
To re-enable: restore the Step 3 `sync_gcs_to_staging(source_bucket="karaoke-gen-storage-nomadkaraoke", staging_prefix="gcs/job-files/")`
|
||||
call in `infrastructure/functions/backup_to_aws/main.py` (see git history) and
|
||||
re-add the `gcs/job-files/` row to `.github/workflows/dr-backup-freshness.yml`.
|
||||
|
||||
## Incident: S3 overwrites silently failing 2026-09-14 → 2026-09-26
|
||||
|
||||
The incremental S3 upload (#997) checked "already in S3?" with `HeadObject`,
|
||||
|
||||
@@ -170,10 +170,19 @@ 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.
|
||||
the GCE runners still request them: 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.
|
||||
|
||||
**2026-10-01:** `deploy-backend` also moved off the `docker-build` (`gha-build-*`,
|
||||
e2-standard-8) runners to `ubuntu-latest`; its Docker images are now built by
|
||||
Cloud Build in us-central1 (`infrastructure/cloudbuild/`). Building on the
|
||||
hosted runner itself was rejected: the app images are built FROM ~4.2 GB (CPU)
|
||||
and ~13 GB (GPU) bases in us-central1 AR, so every deploy would pull ~17 GB over
|
||||
GCP internet egress (~$2/deploy, ~$250/mo). Cloud Build pulls them same-region
|
||||
for free and its e2-standard-2 minutes are in the 2,500 min/month free tier
|
||||
(~7 min/deploy). The `build` family stays in the dispatcher but is unused and
|
||||
excluded from the monthly image bake (`variants=all`).
|
||||
|
||||
## High-level architecture
|
||||
|
||||
|
||||
@@ -171,6 +171,7 @@ 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-10-01:** Retired the `gha-build-*` build runner (~$21/mo at ~120 deploys/mo). `deploy-backend` runs on free `ubuntu-latest`; images build in Cloud Build us-central1 (same-region AR pulls, e2-standard-2 free tier, ~7 build-min/deploy). Not built on the hosted runner because pulling the 4.2 GB CPU + 13 GB GPU bases is internet egress (~$2/deploy).
|
||||
|
||||
## 2026-09-26 cuts (post-credit-expiry, target: whole project < $300/mo)
|
||||
|
||||
@@ -185,5 +186,53 @@ If all optimizations implemented:
|
||||
| Firestore PITR disabled (nightly export remains) | `database.py` | PITR storage |
|
||||
| `recover-stuck-downloads` / `retry-pending-render-jobs` every 5 → 10 min | `__main__.py` | ~half their Firestore reads |
|
||||
|
||||
Kept: the `audio-separator` Cloud Run GPU service (still used by external remote-CLI
|
||||
clients; already scale-to-zero).
|
||||
Kept (at the time): the `audio-separator` Cloud Run GPU service — shut down in round 2 below.
|
||||
|
||||
## 2026-10-01 cuts, round 2 (run-rate ~$400 → target < $300/mo)
|
||||
|
||||
| Change | Where | Est. saving |
|
||||
|--------|-------|-------------|
|
||||
| `karaoke-backend` min-instances 1 → 0 (Andrew accepts a ~15s cold start on the first request after idle). With `--cpu-throttling` (request-based billing), idle non-min instances are free, so the 60s `/api/health` uptime check and the `*/10` schedulers keeping it warm don't cost idle charges | `ci.yml` | ~$24/mo |
|
||||
| `audio-separator` Cloud Run GPU service (us-east4) + its SA, IAM, output bucket and `audio-separator` AR repo (~42 GB) **deleted**; python-audio-separator's `deploy-to-cloudrun.yml` made manual-only | `__main__.py` (flag `audioSeparatorServiceEnabled`, default off) | ~$22/mo |
|
||||
| `backup-to-aws` no longer copies job files to S3 (they rely on GCS versioning + soft-delete); freshness monitor no longer checks `gcs/job-files/` | `functions/backup_to_aws/main.py`, `dr-backup-freshness.yml`, `DISASTER-RECOVERY.md` | ~$15/mo egress |
|
||||
| Artifact Registry cleanup: per package keep the 20 most recent versions (≈10 tagged deploy images; each build also leaves a cache manifest) + tags `latest`/`content-`/`cache`, delete everything else (tagged *or* untagged) older than 7 days. **Applied in DRY-RUN mode** (`CLEANUP_POLICY_DRY_RUN = True` in `artifact_registry.py`) — flip to `False` + targeted `pulumi up` on `karaoke-artifact-repo` / `karaoke-backend-gpu-artifact-repo` after reviewing the dry-run audit logs. After the next GPU base rebuild, delete the superseded `karaoke-backend-gpu-base:content-daa414741653` tag by hand (the `content-` KEEP rule would otherwise keep it forever). Before, tagged per-commit images were never deleted (~265 + ~244 tagged backend versions had piled up). Legacy 13 GB `karaoke-backend-gpu-base` package in us-east4 deleted (gcloud). `gcf-artifacts` (Google-managed, not in Pulumi) got a gcloud policy (also dry-run for now; enable with `gcloud artifacts repositories set-cleanup-policies gcf-artifacts --location=us-central1 --policy=<file> --no-dry-run`): keep 3 most recent + all tagged, delete untagged > 7d | `artifact_registry.py`, `gpu_artifact_registry.py` | ~$8–10/mo |
|
||||
| Secret Manager: 12 superseded versions disabled → destroyed (none pinned; all consumers use `:latest`) | gcloud (out of Pulumi) | < $1/mo |
|
||||
|
||||
### Audio separator service (shut down, on-demand redeploy)
|
||||
|
||||
The standalone `audio-separator` API (L4 GPU Cloud Run service, us-east4) is still
|
||||
defined in `infrastructure/modules/audio_separator_service.py`, gated behind a Pulumi
|
||||
config flag. To bring it back:
|
||||
|
||||
```bash
|
||||
cd infrastructure
|
||||
STACK=nomadkaraoke/karaoke-gen-infrastructure/prod
|
||||
PULUMI="env -u GOOGLE_APPLICATION_CREDENTIALS GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token --account=admin@nomadkaraoke.com) pulumi"
|
||||
pulumi config set audioSeparatorServiceEnabled true --stack $STACK
|
||||
# 1) Create ONLY the (empty) Artifact Registry repo first — the service references
|
||||
# api:latest, which must exist before Cloud Run will accept the service.
|
||||
$PULUMI up --stack $STACK --target 'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:artifactregistry/repository:Repository::audio-separator-artifact-repo'
|
||||
# 2) Build + push api:<sha> and api:latest (from a python-audio-separator checkout)
|
||||
gcloud builds submit --config cloudbuild.yaml --region=us-east4 --project=nomadkaraoke --substitutions=SHORT_SHA=$(git rev-parse --short=8 HEAD)
|
||||
# 3) Create the service, SA, IAM and output bucket
|
||||
$PULUMI up --stack $STACK
|
||||
# Later image updates: gh workflow run deploy-to-cloudrun.yml --repo nomadkaraoke/python-audio-separator
|
||||
export AUDIO_SEPARATOR_API_URL=$(gcloud run services describe audio-separator --region us-east4 --project nomadkaraoke --format='value(status.url)')
|
||||
```
|
||||
|
||||
The output bucket is protected by the project's `deny-destructive-operations` IAM deny
|
||||
policy. When you shut the service down again (`pulumi config rm audioSeparatorServiceEnabled`
|
||||
+ `pulumi up`), delete the bucket first with
|
||||
`gcloud storage rm -r gs://nomadkaraoke-audio-separator-outputs --impersonate-service-account=break-glass@nomadkaraoke.iam.gserviceaccount.com`,
|
||||
then `pulumi refresh --target <bucket urn>`.
|
||||
|
||||
### Out-of-Pulumi changes (2026-10-01)
|
||||
|
||||
- `gcloud artifacts packages delete karaoke-backend-gpu-base --repository=karaoke-backend-gpu --location=us-east4`
|
||||
(13 GB legacy base; the base has lived in us-central1 `karaoke-repo` since 2026-09-27; the CI one-time-copy fallback that read it was removed).
|
||||
- `gcloud artifacts repositories set-cleanup-policies gcf-artifacts --location=us-central1` (policy above).
|
||||
- Secret versions disabled, then destroyed: `encoding-worker-fallback-vms` v1–4, `flacfetch-api-url` v1,
|
||||
`github-runner-pat` v1, `pushbullet-api-key` v1–2, `rapidapi-key` v1, `spotify-cookie` v1,
|
||||
`discord-releases-webhook` v1–2. App-rotated secrets (`dropbox-oauth-credentials`, `spotify-oauth-token`,
|
||||
`youtube-cookies`) keep their own retention and were left alone, as was `gemini-api-key`.
|
||||
- `gs://nomadkaraoke-audio-separator-outputs` deleted via break-glass SA (IAM deny policy blocks Pulumi).
|
||||
+24
-4
@@ -1403,11 +1403,31 @@ For indefinite loops (like polling), use outer timeout (total duration) + inner
|
||||
### Secret Manager Access
|
||||
Service account needs `roles/secretmanager.secretAccessor`. Mount as env var or volume. Use GCP workload identity, not key files.
|
||||
|
||||
### Vertex AI Auth
|
||||
Use `project` parameter with `ChatGoogleGenerativeAI` to trigger Vertex AI backend with ADC. Don't require `GOOGLE_API_KEY`.
|
||||
### Gemini: Developer API key, never Vertex (2026-10-01)
|
||||
All Gemini calls use the **Gemini Developer API** (AI Studio key in Secret Manager
|
||||
`gemini-api-key`, billed outside the nomadkaraoke project) via
|
||||
`backend/services/gemini_client.get_genai_client()`; `aiplatform.googleapis.com` and
|
||||
`generativelanguage.googleapis.com` are **disabled** in nomadkaraoke so no AI spend lands
|
||||
on it. Key = `GEMINI_API_KEY` env (CI `--set-secrets` for the service, Pulumi for jobs),
|
||||
else Secret Manager read at runtime. Rotate = add a secret version (new instances/job
|
||||
executions pick it up). Classify failures with `note_gemini_failure(caller, exc)`:
|
||||
quota/billing/key errors (not per-minute 429s) skip retries, degrade, and Discord-alert
|
||||
at most once per 6h. (Supersedes the old "Vertex AI Auth" / "global location" notes —
|
||||
the Developer API has no project/location.)
|
||||
|
||||
### Gemini 3 Requires Global Location
|
||||
Gemini 3 models require `location="global"`, not regional endpoints like `us-central1`.
|
||||
**Manual (non-Pulumi) changes made 2026-10-02 (admin@nomadkaraoke.com), after v0.262.0
|
||||
deployed and Vertex `request_count` stayed at zero:**
|
||||
- 02:46Z `roles/aiplatform.user` binding for `karaoke-backend` deleted (Pulumi, targeted).
|
||||
- 02:47Z removed cross-project `roles/aiplatform.user` for
|
||||
`aquarius-backend@aquarius-fundraising-mvp.iam.gserviceaccount.com` (zero traffic).
|
||||
- 02:48Z `gcloud services disable aiplatform.googleapis.com generativelanguage.googleapis.com`
|
||||
(no `--force` needed). Re-enable with `gcloud services enable ...` if ever required.
|
||||
- 02:49Z deleted unused restricted API key `98073667-…` ("Generative Language API Key";
|
||||
0 valid requests in 30 days; undelete possible for 30 days via `gcloud services api-keys undelete`).
|
||||
- `gemini-api-key` belongs to AI Studio project `gen-lang-client-0983596166` (number
|
||||
810524901596), billed to "Aquarius Billing". To swap keys: `printf '%s' "$KEY" | gcloud
|
||||
secrets versions add gemini-api-key --project=nomadkaraoke --data-file=-`, then roll the
|
||||
service (any new revision) — jobs pick it up on their next execution.
|
||||
|
||||
### LangChain: REST over gRPC
|
||||
Use `langchain-google-genai` (REST) instead of `langchain-google-vertexai` (gRPC) to avoid silent hangs.
|
||||
|
||||
@@ -132,7 +132,7 @@ Commercial producers pay for API access or custom integration to generate tracks
|
||||
### What Works
|
||||
- Audio upload and separation (Cloud Run GPU)
|
||||
- Lyrics transcription (AudioShake API)
|
||||
- Agentic AI correction (Gemini 3 Flash via Vertex AI)
|
||||
- Agentic AI correction (Gemini 3 Flash via the Gemini Developer API)
|
||||
- Human lyrics review (React UI)
|
||||
- Preview video generation
|
||||
- Instrumental selection (clean vs. with backing vocals)
|
||||
@@ -190,7 +190,7 @@ Commercial producers pay for API access or custom integration to generate tracks
|
||||
- **Secrets**: Google Secret Manager
|
||||
- **Audio Separation**: Cloud Run GPU (L4, us-east4)
|
||||
- **Lyrics Transcription**: AudioShake API
|
||||
- **AI Correction**: Vertex AI (Gemini 3 Flash)
|
||||
- **AI Correction**: Gemini Developer API (Gemini 3 Flash)
|
||||
- **Payments**: Stripe
|
||||
- **Email**: Postmark
|
||||
- **IaC**: Pulumi
|
||||
|
||||
@@ -57,6 +57,8 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Gemini moved off Vertex AI** (2026-10-01, v0.262.0): every Gemini call (auto-correct compare leg, match-judge, parse-titles, credit eval, tenant bulk analyze, custom lyrics, lyrics translation, error-monitor LLM, agentic correction, translate.py) now uses the Gemini Developer API with the `gemini-api-key` secret via `backend/services/gemini_client.py`, so no AI spend lands on the nomadkaraoke project (Vertex APIs disabled there). Quota/billing/key failures degrade per caller and send one Discord ops alert per 6h. See LESSONS-LEARNED "Gemini: Developer API key, never Vertex".
|
||||
|
||||
- **Translated lyrics follow-ups + review waveform spinner** (2026-10-01, v0.261.0):
|
||||
- The translation row now renders at 70% of the unsung colour's opacity, with outline and shadow faded to match, so it reads as secondary to the sung line (`subtitles.py:TRANSLATION_OPACITY`). A theme's `karaoke.translation_color` still wins.
|
||||
- Published videos with translations get "(With Translation into X)" in the YouTube title, before "(Karaoke)". Only the artist/title get truncated, never the label. The description also gets a notice. This applies to the live upload and the quota queue, but only when `state_data.lyrics_translation.status == "translated"` (`youtube_description.build_youtube_title`).
|
||||
|
||||
@@ -99,7 +99,7 @@ the same KaraokeNerds check the normal job-submission flow uses runs at two poin
|
||||
- **Auth:** reuses gen's passwordless magic-link system. Board sign-in sends
|
||||
`purpose="requests_board"`, which creates an identity **without** granting a welcome credit and
|
||||
with a higher per-IP signup cap (so a whole venue on shared WiFi can sign in).
|
||||
- **Auto-correct:** reuses `match_judge` (Vertex Gemini) — the same artist/title canonicalizer the
|
||||
- **Auto-correct:** reuses `match_judge` (Gemini) — the same artist/title canonicalizer the
|
||||
job-submission flow uses.
|
||||
- **Storage:** two Firestore collections — `song_requests` (one doc per song, with a denormalized
|
||||
`vote_count`) and `song_request_votes` (one doc per person per day, id `{email}__{YYYY-MM-DD}`,
|
||||
|
||||
@@ -31,7 +31,7 @@ GitHub-hosted runners work but are slower (2 vCPU, 7GB RAM) and costs scale line
|
||||
| Component | Spec | Purpose |
|
||||
|-----------|------|---------|
|
||||
| General runners | 3x `github-runner-{1..3}`, `e2-standard-4`, 200GB SSD | Execute CI jobs (lint, test, type check, build) |
|
||||
| Build runner | 1x `github-build-runner`, `e2-standard-8`, 200GB SSD | Docker image builds (needs more CPU/RAM) |
|
||||
| Build runner | 1x `github-build-runner`, `e2-standard-8`, 200GB SSD | **Unused since 2026-10-01** — `deploy-backend` runs on `ubuntu-latest` and builds images in Cloud Build (see EPHEMERAL-GHA-RUNNERS.md) |
|
||||
| GPU runners | 3x `github-gpu-runner-{1..3}`, `n1-standard-4` + T4 GPU, 200GB SSD | Audio separation model testing |
|
||||
| Cloud Function | `github-runner-manager`, Gen2, Python 3.12, 5min timeout | Start/stop VMs based on webhooks and idle checks |
|
||||
| Cloud Scheduler | `runner-manager-idle-check`, every 5 min | Orphan cleanup + stalled-job re-dispatch (see EPHEMERAL-GHA-RUNNERS.md) |
|
||||
@@ -52,7 +52,7 @@ All runner VMs are in `us-central1-a`.
|
||||
| Label Set | VMs | Used By |
|
||||
|-----------|-----|---------|
|
||||
| `[self-hosted, linux, x64, gcp, large-disk]` | general runners | Most CI jobs |
|
||||
| `[self-hosted, linux, x64, gcp, large-disk, docker-build]` | build runner | Docker image builds |
|
||||
| `[self-hosted, linux, x64, gcp, large-disk, docker-build]` | build runner | Unused since 2026-10-01 (images build in Cloud Build) |
|
||||
| `[self-hosted, linux, x64, gcp, gpu]` | GPU runners | Audio separation tests |
|
||||
|
||||
## How Auto-Scaling Works
|
||||
|
||||
+17
-9
@@ -68,25 +68,33 @@ defense-in-depth beneath the signing-free review path.
|
||||
`Failed to send magic link email to …`.
|
||||
|
||||
**Cause:** a bare nginx HTML 403 (not Postmark's JSON error format) is an edge/IP-level
|
||||
block at `api.postmarkapp.com`, not a token or payload problem. Seen intermittently
|
||||
from `karaoke-backend` (us-central1, shared Cloud Run egress IPs) since 2026-09-30;
|
||||
us-east4 Cloud Run Jobs were unaffected. A JSON 403 (`ErrorCode=10`) is a real bad-token error instead.
|
||||
block at `api.postmarkapp.com`, not a token or payload problem. Seen from
|
||||
`karaoke-backend` and karaoke-decide (us-central1, shared Cloud Run egress IPs) since
|
||||
2026-09-30, in blocks lasting hours (all sends failed 2026-10-02 11:25 UTC onward);
|
||||
us-east4 Cloud Run Jobs were unaffected. IP Allowlisting is OFF in Postmark (checked
|
||||
2026-10-02), so this is Postmark's network firewall — ticket #11562402. A JSON 403
|
||||
(`ErrorCode=10`) is a real bad-token error instead.
|
||||
|
||||
**Mitigation in code:** `PostmarkEmailProvider` retries 429 / 5xx / non-JSON 403 /
|
||||
connect timeouts (backoff 1s, 3s). JSON Postmark errors and read timeouts are not
|
||||
retried (deterministic, or risk of a duplicate send).
|
||||
**Mitigation in code:** on an HTML 403, `PostmarkEmailProvider` immediately re-sends via
|
||||
Postmark SMTP (`smtp.postmarkapp.com:587`, STARTTLS, server token as user+password,
|
||||
`X-PM-Message-Stream: outbound`) — API retries never got past a block. Also falls back
|
||||
when every API attempt hits a connect timeout. 429 / 5xx / connect timeouts are still
|
||||
retried on the API (backoff 1s, 3s). JSON Postmark errors and read timeouts never fall
|
||||
back (deterministic, or risk of a duplicate send). SMTP sends log
|
||||
`Email sent to … via Postmark SMTP fallback` and have no Postmark MessageID; SMTP access
|
||||
must stay enabled on the Postmark server (Server → Settings).
|
||||
|
||||
**Diagnosis:**
|
||||
```bash
|
||||
gcloud logging read 'resource.labels.service_name="karaoke-backend" AND (textPayload:"Postmark returned status" OR textPayload:"Failed to send")' \
|
||||
gcloud logging read 'resource.labels.service_name="karaoke-backend" AND (textPayload:"Postmark returned status" OR textPayload:"Failed to send" OR textPayload:"SMTP")' \
|
||||
--project nomadkaraoke --freshness 2d --limit 50 --format='value(timestamp,textPayload)'
|
||||
```
|
||||
The E2E `waitForEmail` helper now checks `GET /api/admin/users/{email}/emails` on
|
||||
timeout and reports whether the backend sent anything ("backend has NO record…" =
|
||||
server-side send failure; "backend sent N email(s)…" = delivery/testmail problem).
|
||||
|
||||
**If it persists after retries:** contact Postmark support with failure timestamps, or
|
||||
give the backend a static egress IP (Direct VPC egress + Cloud NAT).
|
||||
**If SMTP fallback also fails:** follow up on the Postmark ticket, or give the backend a
|
||||
static egress IP (Direct VPC egress + Cloud NAT).
|
||||
|
||||
## Fast rollback (bad backend deploy)
|
||||
|
||||
|
||||
@@ -6,10 +6,14 @@
|
||||
* and backend calls are addressed with relative "/api/..." URLs.
|
||||
*/
|
||||
|
||||
import { apiFetch, BackendUnavailableError, __backendHealthProbe } from '@/lib/api'
|
||||
import { apiFetch, BackendUnavailableError, __backendHealthProbe, __backendPrewarm } from '@/lib/api'
|
||||
import {
|
||||
getBackendStatus,
|
||||
configureHealthProbe,
|
||||
configurePrewarm,
|
||||
markBackendReachable,
|
||||
prewarmBackend,
|
||||
__resetBackendStatusForTest,
|
||||
STALL_RECONNECTING_MS,
|
||||
STALL_UNAVAILABLE_MS,
|
||||
} from '@/lib/backend-status'
|
||||
@@ -44,8 +48,14 @@ describe('apiFetch', () => {
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset()
|
||||
;(globalThis as unknown as { fetch: unknown }).fetch = fetchMock
|
||||
// Re-register the real probe so its cached verdict resets between tests.
|
||||
// Reset the store (reachability, in-flight reads) and re-register the real
|
||||
// probe so its cached verdict resets between tests.
|
||||
__resetBackendStatusForTest()
|
||||
configureHealthProbe(__backendHealthProbe)
|
||||
configurePrewarm(__backendPrewarm)
|
||||
// Default to a WARM session (backend answered moments ago); cold-start tests
|
||||
// reset this explicitly.
|
||||
markBackendReachable()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -155,6 +165,9 @@ describe('apiFetch', () => {
|
||||
|
||||
it('surfaces the banner for a stalled GET once the health probe confirms the outage, then clears', async () => {
|
||||
jest.useFakeTimers()
|
||||
// The backend WAS answering moments ago, so this stall is a recycle/outage,
|
||||
// not a cold start — the normal reconnecting/unavailable path applies.
|
||||
markBackendReachable()
|
||||
// Everything hangs — the backend is genuinely unreachable (recycle-style: the
|
||||
// origin holds requests open, so the probe only fails via its own timeout).
|
||||
let settleGet!: (r: Response) => void
|
||||
@@ -190,6 +203,58 @@ describe('apiFetch', () => {
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('shows the calm waking state (not the warning) when a fresh session hits a cold backend', async () => {
|
||||
jest.useFakeTimers()
|
||||
__resetBackendStatusForTest()
|
||||
configureHealthProbe(__backendHealthProbe)
|
||||
// Nothing has answered yet this session; Cloud Run queues every request
|
||||
// (including /api/health) for ~18s while an instance boots.
|
||||
let settleGet!: (r: Response) => void
|
||||
fetchMock.mockImplementation((url: unknown) => {
|
||||
if (String(url).includes('/api/health')) return new Promise<Response>(() => {})
|
||||
return new Promise<Response>((res) => {
|
||||
settleGet = res
|
||||
})
|
||||
})
|
||||
|
||||
const p = apiFetch('/api/jobs')
|
||||
p.catch(() => {})
|
||||
|
||||
// Cold mode probes at 1s; the probe times out at 4s → waking by ~6s.
|
||||
await jest.advanceTimersByTimeAsync(3_000)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
await jest.advanceTimersByTimeAsync(3_000)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
// Still calm at 18s — never the reconnecting/unavailable warning.
|
||||
await jest.advanceTimersByTimeAsync(12_000)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
|
||||
// Instance is up: the queued GET completes (no hard-timeout at 45s hit).
|
||||
settleGet(mockResponse(200, { jobs: [] }))
|
||||
const res = await p
|
||||
expect(res.status).toBe(200)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('prewarm sends an untracked, preflight-free GET /api/health and marks the backend reachable', async () => {
|
||||
jest.useFakeTimers()
|
||||
__resetBackendStatusForTest()
|
||||
fetchMock.mockResolvedValue(mockResponse(200))
|
||||
prewarmBackend()
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(String(url)).toMatch(/\/api\/health$/)
|
||||
expect(init).toEqual({ cache: 'no-store', keepalive: true }) // no headers → no preflight
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
|
||||
// Reachable now, so a later stall is treated as a recycle (normal path),
|
||||
// and a second prewarm within the freshness window is a no-op.
|
||||
prewarmBackend()
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('never surfaces the banner for a slow GET while the backend is reachable (health probe OK)', async () => {
|
||||
jest.useFakeTimers()
|
||||
// The read is legitimately slow (e.g. first-time instrumental-analysis
|
||||
|
||||
@@ -12,9 +12,19 @@ import {
|
||||
beginRequest,
|
||||
endRequest,
|
||||
configureHealthProbe,
|
||||
configurePrewarm,
|
||||
markBackendReachable,
|
||||
prewarmBackend,
|
||||
installBackendPrewarm,
|
||||
__resetBackendStatusForTest,
|
||||
STALL_RECONNECTING_MS,
|
||||
STALL_UNAVAILABLE_MS,
|
||||
PROBE_FRESH_MS,
|
||||
REACHABLE_FRESH_MS,
|
||||
WAKING_SHOW_MS,
|
||||
WAKING_ESCALATE_MS,
|
||||
COLD_PROBE_AFTER_MS,
|
||||
PREWARM_AFTER_HIDDEN_MS,
|
||||
} from '@/lib/backend-status'
|
||||
|
||||
describe('backend-status store (stall-based)', () => {
|
||||
@@ -23,6 +33,10 @@ describe('backend-status store (stall-based)', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
open = []
|
||||
// These suites cover a WARM session (the backend answered moments ago), so
|
||||
// a stall is a recycle/outage rather than a cold start.
|
||||
__resetBackendStatusForTest()
|
||||
markBackendReachable()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -98,6 +112,10 @@ describe('backend-status store (health-probe confirmation)', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
open = []
|
||||
// These suites cover a WARM session (the backend answered moments ago), so
|
||||
// a stall is a recycle/outage rather than a cold start.
|
||||
__resetBackendStatusForTest()
|
||||
markBackendReachable()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -209,3 +227,235 @@ describe('backend-status store (health-probe confirmation)', () => {
|
||||
expect(debug.lastProbeOk).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('backend-status store (cold start / waking)', () => {
|
||||
let open: number[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
open = []
|
||||
__resetBackendStatusForTest() // fresh page load: nothing has answered yet
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
open.forEach((id) => endRequest(id))
|
||||
__resetBackendStatusForTest()
|
||||
jest.clearAllTimers()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
/** A probe that hangs like a cold instance and fails via its 4s timeout. */
|
||||
const coldProbe = () =>
|
||||
jest.fn(() => new Promise<boolean>((res) => setTimeout(() => res(false), 4000)))
|
||||
|
||||
it('cold start: shows the calm waking state within seconds, then clears when the read completes', async () => {
|
||||
const probe = coldProbe()
|
||||
configureHealthProbe(probe)
|
||||
|
||||
const id = beginRequest()
|
||||
open.push(id)
|
||||
expect(probe).not.toHaveBeenCalled() // a normal fast load never probes
|
||||
await jest.advanceTimersByTimeAsync(COLD_PROBE_AFTER_MS)
|
||||
expect(probe).toHaveBeenCalledTimes(1) // probed at 1s, not at 10s
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
|
||||
await jest.advanceTimersByTimeAsync(WAKING_SHOW_MS)
|
||||
expect(getBackendStatus()).toBe('online') // probe has no verdict yet (t=4s)
|
||||
|
||||
await jest.advanceTimersByTimeAsync(1000) // t=5s: probe failed at its 4s timeout
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
|
||||
// Through a typical ~18s cold start it stays calm — never the warning.
|
||||
await jest.advanceTimersByTimeAsync(13_000) // t=18s
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
|
||||
markBackendReachable()
|
||||
endRequest(id)
|
||||
open = []
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('cold start: a read that answers quickly never shows anything', async () => {
|
||||
configureHealthProbe(coldProbe())
|
||||
const id = beginRequest()
|
||||
await jest.advanceTimersByTimeAsync(2000)
|
||||
markBackendReachable()
|
||||
endRequest(id)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('cold start: a warm backend with a merely slow endpoint shows nothing (probe OK)', async () => {
|
||||
configureHealthProbe(() => Promise.resolve(true))
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 5000)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('cold start that drags on past WAKING_ESCALATE_MS escalates to the normal banner', async () => {
|
||||
configureHealthProbe(coldProbe())
|
||||
open.push(beginRequest())
|
||||
|
||||
await jest.advanceTimersByTimeAsync(WAKING_ESCALATE_MS - 1000)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
|
||||
await jest.advanceTimersByTimeAsync(2000)
|
||||
// Many consecutive probe failures by now → straight to the full message.
|
||||
expect(getBackendStatus()).toBe('unavailable')
|
||||
})
|
||||
|
||||
it('escalation is measured from the start of the cold episode, so a long outage never flaps back to waking', async () => {
|
||||
configureHealthProbe(coldProbe())
|
||||
const first = beginRequest()
|
||||
open.push(first)
|
||||
await jest.advanceTimersByTimeAsync(30_000)
|
||||
open.push(beginRequest()) // e.g. a polling read starting mid-episode
|
||||
await jest.advanceTimersByTimeAsync(31_000) // t=61s
|
||||
expect(getBackendStatus()).toBe('unavailable')
|
||||
|
||||
// The first read times out; the newer one (only 31s old) is now the oldest.
|
||||
endRequest(first)
|
||||
open = open.filter((id) => id !== first)
|
||||
await jest.advanceTimersByTimeAsync(1000)
|
||||
expect(getBackendStatus()).toBe('unavailable') // not back to 'waking'
|
||||
})
|
||||
|
||||
it('a stale failed-probe verdict from before the backend answered cannot trigger waking', async () => {
|
||||
// An earlier episode leaves a failed verdict behind...
|
||||
configureHealthProbe(() => Promise.resolve(false))
|
||||
const old = beginRequest()
|
||||
await jest.advanceTimersByTimeAsync(6000)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
markBackendReachable()
|
||||
endRequest(old)
|
||||
expect(getBackendStatusDebug().lastProbeOk).toBeNull() // verdict dropped
|
||||
|
||||
// ...much later (backend idle-timeout window passed, but kept warm by others),
|
||||
// a read that's merely slow: the fresh probe answers OK → nothing shown.
|
||||
configureHealthProbe(() => new Promise<boolean>((res) => setTimeout(() => res(true), 2500)))
|
||||
markBackendReachable()
|
||||
await jest.advanceTimersByTimeAsync(REACHABLE_FRESH_MS + 1000)
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(3500) // past WAKING_SHOW_MS, probe still pending
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
await jest.advanceTimersByTimeAsync(5000)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('previously reachable, then a stall → normal reconnecting banner (recycle, not a cold start)', async () => {
|
||||
configureHealthProbe(coldProbe())
|
||||
markBackendReachable()
|
||||
await jest.advanceTimersByTimeAsync(30_000) // backend answered 30s ago
|
||||
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(8000)
|
||||
expect(getBackendStatus()).toBe('online') // no waking state for a recycle
|
||||
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS) // probe at 10s, fails at 14s
|
||||
expect(getBackendStatus()).toBe('reconnecting')
|
||||
})
|
||||
|
||||
it('reachable long ago (backend idled to zero) → a new stall is treated as a cold start', async () => {
|
||||
configureHealthProbe(coldProbe())
|
||||
markBackendReachable()
|
||||
await jest.advanceTimersByTimeAsync(REACHABLE_FRESH_MS + 1000)
|
||||
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(6000)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
})
|
||||
|
||||
it('without a probe (pure stall mode) a cold stall still shows waking, not the warning', async () => {
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(WAKING_SHOW_MS)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
})
|
||||
|
||||
it('exposes time since the backend last answered for telemetry', async () => {
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBeNull()
|
||||
markBackendReachable()
|
||||
await jest.advanceTimersByTimeAsync(1500)
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBe(1500)
|
||||
})
|
||||
})
|
||||
|
||||
describe('backend-status prewarm', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
__resetBackendStatusForTest()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
configurePrewarm(null)
|
||||
__resetBackendStatusForTest()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
it('installBackendPrewarm registers the passed fetch when api.ts has not', async () => {
|
||||
configurePrewarm(null)
|
||||
const warm = jest.fn(() => Promise.resolve(true))
|
||||
installBackendPrewarm(warm)
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(warm).toHaveBeenCalledTimes(1)
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBe(0)
|
||||
})
|
||||
|
||||
it('fires once while in flight and marks the backend reachable on success', async () => {
|
||||
let finish!: (ok: boolean) => void
|
||||
const warm = jest.fn(() => new Promise<boolean>((res) => (finish = res)))
|
||||
configurePrewarm(warm)
|
||||
|
||||
prewarmBackend()
|
||||
prewarmBackend() // de-duped while the first is in flight
|
||||
expect(warm).toHaveBeenCalledTimes(1)
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBeNull()
|
||||
|
||||
finish(true)
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBe(0)
|
||||
|
||||
// Recently reachable → no need to warm again.
|
||||
prewarmBackend()
|
||||
expect(warm).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('a failed prewarm does not mark the backend reachable and can be retried', async () => {
|
||||
const warm = jest.fn(() => Promise.resolve(false))
|
||||
configurePrewarm(warm)
|
||||
prewarmBackend()
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBeNull()
|
||||
prewarmBackend()
|
||||
expect(warm).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('re-warms when the tab returns after a long absence, but not after a short one', async () => {
|
||||
const warm = jest.fn(() => Promise.resolve(true))
|
||||
configurePrewarm(warm)
|
||||
let visibility: DocumentVisibilityState = 'visible'
|
||||
Object.defineProperty(document, 'visibilityState', {
|
||||
configurable: true,
|
||||
get: () => visibility,
|
||||
})
|
||||
const setVisibility = (v: DocumentVisibilityState) => {
|
||||
visibility = v
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
}
|
||||
|
||||
installBackendPrewarm()
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(warm).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Short absence: no re-warm.
|
||||
setVisibility('hidden')
|
||||
await jest.advanceTimersByTimeAsync(60_000)
|
||||
setVisibility('visible')
|
||||
expect(warm).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Long absence (backend may have scaled to zero): re-warm.
|
||||
setVisibility('hidden')
|
||||
await jest.advanceTimersByTimeAsync(PREWARM_AFTER_HIDDEN_MS + 1000)
|
||||
setVisibility('visible')
|
||||
expect(warm).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import React, { useEffect, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { getAccessToken } from "@/lib/api"
|
||||
import { getAccessToken, __backendPrewarm } from "@/lib/api"
|
||||
import { installBackendPrewarm } from "@/lib/backend-status"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { Loader2 } from "lucide-react"
|
||||
@@ -104,6 +105,12 @@ export default function AdminLayout({
|
||||
// to satisfy React's Rules of Hooks
|
||||
const { showTestData, setShowTestData } = useAdminSettings()
|
||||
|
||||
// Admin isn't under [locale] (no BackendStatusBanner), so pre-warm a possibly
|
||||
// scaled-to-zero backend here too.
|
||||
useEffect(() => {
|
||||
installBackendPrewarm(__backendPrewarm)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const token = getAccessToken()
|
||||
if (!token) {
|
||||
|
||||
@@ -6,9 +6,11 @@ import { Loader2, CloudOff, X } from "lucide-react"
|
||||
import {
|
||||
useBackendStatus,
|
||||
getBackendStatusDebug,
|
||||
installBackendPrewarm,
|
||||
__installBackendStatusDevHook,
|
||||
} from "@/lib/backend-status"
|
||||
import { reportDegradationEvent } from "@/lib/degradation-events"
|
||||
import { __backendPrewarm } from "@/lib/api"
|
||||
|
||||
/**
|
||||
* App-wide, non-blocking banner that reacts to backend connectivity (see
|
||||
@@ -17,6 +19,8 @@ import { reportDegradationEvent } from "@/lib/degradation-events"
|
||||
* broken and any in-flight karaoke renders keep running. Rather than every screen
|
||||
* showing its own scary error, this shows a single reassuring message:
|
||||
*
|
||||
* - "waking": a calm, branded "starting up our karaoke servers" card while a
|
||||
* scaled-to-zero backend cold-starts (~15-20s). No warning colours.
|
||||
* - "reconnecting": a subtle pill with a spinner while we transparently retry.
|
||||
* - "unavailable": a gentle card explaining it's temporary and that ongoing jobs
|
||||
* are unaffected, once trouble persists past the threshold.
|
||||
@@ -29,8 +33,11 @@ export function BackendStatusBanner() {
|
||||
const t = useTranslations("backendStatus")
|
||||
const [dismissed, setDismissed] = useState(false)
|
||||
|
||||
// Expose the dev/preview trigger (window.__nkBackendStatus) for manual UX review.
|
||||
// Expose the dev/preview trigger (window.__nkBackendStatus) for manual UX review,
|
||||
// and pre-warm a possibly scaled-to-zero backend as early as possible (this
|
||||
// banner is mounted app-wide, so every page that talks to the backend gets it).
|
||||
useEffect(() => {
|
||||
installBackendPrewarm(__backendPrewarm)
|
||||
__installBackendStatusDevHook()
|
||||
}, [])
|
||||
|
||||
@@ -49,18 +56,45 @@ export function BackendStatusBanner() {
|
||||
if (status === "unavailable" && dismissed) return
|
||||
const debug = getBackendStatusDebug()
|
||||
reportDegradationEvent(
|
||||
status === "unavailable" ? "banner_unavailable" : "banner_reconnecting",
|
||||
status === "unavailable"
|
||||
? "banner_unavailable"
|
||||
: status === "waking"
|
||||
? "banner_waking"
|
||||
: "banner_reconnecting",
|
||||
{
|
||||
stall_ms: debug.oldestStallMs,
|
||||
in_flight: debug.inFlightCount,
|
||||
probe_ok: debug.lastProbeOk,
|
||||
probe_failures: debug.consecutiveProbeFailures,
|
||||
since_reachable_ms: debug.sinceReachableMs,
|
||||
},
|
||||
)
|
||||
}, [status, dismissed])
|
||||
|
||||
if (status === "online") return null
|
||||
|
||||
if (status === "waking") {
|
||||
return (
|
||||
<div
|
||||
className="fixed top-3 left-1/2 z-[60] w-[calc(100%-1.5rem)] max-w-md -translate-x-1/2 pointer-events-none"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
data-testid="backend-waking"
|
||||
>
|
||||
<div className="flex items-center gap-3 rounded-xl border border-[var(--card-border)] bg-[var(--card)]/95 px-4 py-3 text-[var(--text)] shadow-2xl backdrop-blur">
|
||||
<Loader2
|
||||
className="h-5 w-5 shrink-0 animate-spin"
|
||||
style={{ color: "var(--tenant-primary)" }}
|
||||
/>
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-sm font-semibold">{t("waking.title")}</p>
|
||||
<p className="text-xs leading-relaxed text-[var(--text-muted)]">{t("waking.body")}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (status === "reconnecting") {
|
||||
return (
|
||||
<div
|
||||
|
||||
+27
-1
@@ -5,7 +5,13 @@
|
||||
import type { VideoThemeSummary, VideoThemeDetail, ThemesListResponse, ThemeDetailResponse, ColorOverrides } from './video-themes';
|
||||
import type { MagicLinkResponse, VerifyMagicLinkResponse, UserProfileResponse, ReferralInterstitial, ReferralDashboard, ReferralLink, VanityRequest, BoardResponse, SubmitRequestResponse, SongRequestPublic, DailyVoteStatus, ClaimWelcomeCreditResponse } from './types';
|
||||
import type { CorrectionData, CorrectionAnnotation, EditLog, SearchLyricsResponse, AddLyricsResult } from './lyrics-review/types';
|
||||
import { beginRequest, endRequest, configureHealthProbe } from './backend-status';
|
||||
import {
|
||||
beginRequest,
|
||||
endRequest,
|
||||
configureHealthProbe,
|
||||
configurePrewarm,
|
||||
markBackendReachable,
|
||||
} from './backend-status';
|
||||
import { ApiError } from './api-error';
|
||||
import { putFileToSignedUrl, uploadFilesToSignedUrls, type UploadProgress } from './upload';
|
||||
|
||||
@@ -546,6 +552,20 @@ export function __backendHealthProbe(): Promise<boolean> {
|
||||
}
|
||||
configureHealthProbe(__backendHealthProbe);
|
||||
|
||||
// Cold-start pre-warm (see prewarmBackend in backend-status.ts): an untracked,
|
||||
// fire-and-forget GET /api/health so a scaled-to-zero backend starts booting while
|
||||
// the user is still reading the page. Deliberately NOT time-boxed: aborting it
|
||||
// would gain nothing, and letting it complete is how we learn the backend is up.
|
||||
// A plain GET with no custom headers, so it never needs a CORS preflight.
|
||||
/** Exported for tests. */
|
||||
export function __backendPrewarm(): Promise<boolean> {
|
||||
return globalThis
|
||||
.fetch(`${API_BASE_URL}/api/health`, { cache: 'no-store', keepalive: true })
|
||||
.then((res) => res.ok)
|
||||
.catch(() => false);
|
||||
}
|
||||
configurePrewarm(__backendPrewarm);
|
||||
|
||||
/** True only for calls to our own backend API — GCS signed-URL uploads and any other
|
||||
* third-party host pass straight through apiFetch untouched (no timeout/retry/status).
|
||||
* Resolves relative URLs and Request inputs (whose `.url` is always absolute) against
|
||||
@@ -664,6 +684,12 @@ export async function apiFetch(
|
||||
}
|
||||
cleanup();
|
||||
|
||||
if (!TRANSIENT_STATUS.has(response.status)) {
|
||||
// The backend answered (even a 4xx is proof it's up) — this is what lets
|
||||
// the status store tell a later stall (recycle) from a cold start.
|
||||
markBackendReachable();
|
||||
}
|
||||
|
||||
if (TRANSIENT_STATUS.has(response.status)) {
|
||||
if (allowRetry && attempt < maxAttempts) {
|
||||
if (response.status === 429) {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/**
|
||||
* Global backend-connectivity status.
|
||||
*
|
||||
* The backend runs on Cloud Run with `--min-instances 1`. When Cloud Run recycles
|
||||
* The backend runs on Cloud Run (now min-instances 0, see COLD STARTS below). When it recycles
|
||||
* that single instance (routine host maintenance / instance max-lifetime), there is
|
||||
* a brief window where the origin is unreachable and requests HANG (Cloud Run holds
|
||||
* them during the cold start) even though nothing is actually broken — and any
|
||||
@@ -30,6 +30,28 @@
|
||||
* hangs) lets the banner surface.
|
||||
*/
|
||||
|
||||
/*
|
||||
* COLD STARTS (min-instances 0). The backend now scales to zero when idle, so the
|
||||
* first request after a quiet spell waits ~15-20s while Cloud Run starts an
|
||||
* instance (requests are QUEUED, so reads hang rather than fail, and the health
|
||||
* probe times out exactly like it does during a recycle). From the client a cold
|
||||
* start and a recycle look identical, so we tell them apart by recency:
|
||||
*
|
||||
* - If no backend response has succeeded in the REACHABLE_FRESH_MS before the
|
||||
* oldest stalled read began (fresh page load, or a tab left idle long enough
|
||||
* for the backend to scale to zero), a confirmed stall is a cold start: show
|
||||
* the calm 'waking' state ("Starting up our karaoke servers...") from
|
||||
* WAKING_SHOW_MS, without warning colours.
|
||||
* - If that stall outlasts WAKING_ESCALATE_MS it's no longer a plausible cold
|
||||
* start, so the normal reconnecting/unavailable logic takes over.
|
||||
* - If the backend WAS answering just before the stall, it's a recycle/outage:
|
||||
* the normal reconnecting/unavailable logic applies straight away.
|
||||
*
|
||||
* prewarmBackend() fires an untracked GET /api/health on app load (and when a tab
|
||||
* returns after a long absence) so the instance starts while the user is still
|
||||
* reading the page; its success also marks the backend reachable.
|
||||
*/
|
||||
|
||||
import { useSyncExternalStore } from 'react'
|
||||
|
||||
export type BackendStatus =
|
||||
@@ -39,6 +61,9 @@ export type BackendStatus =
|
||||
| 'reconnecting'
|
||||
/** A read has been stalled long enough to show the full "temporarily unavailable". */
|
||||
| 'unavailable'
|
||||
/** Cold start: the backend hasn't answered recently and is (most likely) waking
|
||||
* up from scale-to-zero. Calm "starting up our servers" message. */
|
||||
| 'waking'
|
||||
|
||||
/** A tracked read must be outstanding at least this long before we show ANYTHING —
|
||||
* so a normal slow-but-successful load never surfaces the banner. */
|
||||
@@ -52,6 +77,25 @@ export const PROBE_FRESH_MS = 10_000
|
||||
* transcode pinning the CPU) is not an outage. The reconnecting pill still
|
||||
* shows after a single failure; the assertive message waits for confirmation. */
|
||||
export const UNAVAILABLE_PROBE_FAILURES = 2
|
||||
/** A backend response this recent (relative to when the oldest stalled read began)
|
||||
* means the backend was up and has since stopped answering: a recycle/outage,
|
||||
* not a cold start. Cloud Run scales an idle service to zero after ~15 min, so
|
||||
* anything older than this may well be a cold start. */
|
||||
export const REACHABLE_FRESH_MS = 10 * 60_000
|
||||
/** Cold-start mode: show the calm waking state once a read has been outstanding
|
||||
* this long AND the health probe has failed (it times out at ~4s on a cold
|
||||
* instance, so in practice the waking state appears ~4-5s into a cold start). */
|
||||
export const WAKING_SHOW_MS = 3_000
|
||||
/** Cold-start mode probes once the oldest read has been outstanding this long
|
||||
* (instead of waiting for STALL_RECONNECTING_MS). Short enough that the waking
|
||||
* state appears ~5s into a cold start; long enough that the normal warm-backend
|
||||
* page load (reads done in well under a second) never sends an extra probe. */
|
||||
export const COLD_PROBE_AFTER_MS = 1_000
|
||||
/** Cold starts take ~15-20s. A stall past this is no longer plausibly a cold
|
||||
* start, so we escalate to the normal reconnecting/unavailable banner. */
|
||||
export const WAKING_ESCALATE_MS = 60_000
|
||||
/** Re-prewarm when a tab becomes visible after being hidden at least this long. */
|
||||
export const PREWARM_AFTER_HIDDEN_MS = 10 * 60_000
|
||||
|
||||
let nextId = 1
|
||||
/** id -> startedAt (ms) for every tracked backend GET currently in flight. */
|
||||
@@ -75,6 +119,11 @@ let consecutiveProbeFailures = 0
|
||||
/** Bumped on configureHealthProbe so a probe from a previous config can't land. */
|
||||
let probeEpoch = 0
|
||||
|
||||
/** When a backend response last succeeded (0 = never in this page session). */
|
||||
let lastReachableAt = 0
|
||||
/** Start of the current cold-start episode (null = none); cleared by any response. */
|
||||
let coldEpisodeStartedAt: number | null = null
|
||||
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
function emit() {
|
||||
@@ -87,18 +136,39 @@ function setStatus(next: BackendStatus) {
|
||||
emit()
|
||||
}
|
||||
|
||||
function computeFromStalls(): BackendStatus {
|
||||
if (inFlight.size === 0) return 'online'
|
||||
function oldestStartedAt(): number {
|
||||
let oldest = Infinity
|
||||
for (const startedAt of inFlight.values()) {
|
||||
if (startedAt < oldest) oldest = startedAt
|
||||
}
|
||||
const age = Date.now() - oldest
|
||||
return oldest
|
||||
}
|
||||
|
||||
function computeFromStalls(): BackendStatus {
|
||||
if (inFlight.size === 0) return 'online'
|
||||
const age = Date.now() - oldestStartedAt()
|
||||
if (age >= STALL_UNAVAILABLE_MS) return 'unavailable'
|
||||
if (age >= STALL_RECONNECTING_MS) return 'reconnecting'
|
||||
return 'online'
|
||||
}
|
||||
|
||||
/** True when the oldest outstanding read is (plausibly) waiting on a cold start:
|
||||
* nothing from the backend succeeded in the REACHABLE_FRESH_MS before it began,
|
||||
* and it hasn't yet outlasted a plausible cold start. */
|
||||
function inColdStartWindow(): boolean {
|
||||
if (inFlight.size === 0) return false
|
||||
const oldest = oldestStartedAt()
|
||||
const notRecentlyReachable =
|
||||
lastReachableAt === 0 || lastReachableAt < oldest - REACHABLE_FRESH_MS
|
||||
if (!notRecentlyReachable) return false
|
||||
// Escalation is measured from when this cold episode BEGAN, not from the oldest
|
||||
// read still pending — otherwise, as stalled reads time out and newer (e.g.
|
||||
// polling) reads become the oldest, a genuine outage would flap
|
||||
// unavailable → waking → unavailable. Only a backend response ends the episode.
|
||||
if (coldEpisodeStartedAt === null) coldEpisodeStartedAt = oldest
|
||||
return Date.now() - coldEpisodeStartedAt < WAKING_ESCALATE_MS
|
||||
}
|
||||
|
||||
/** Fire a health probe if one isn't running and the last verdict has gone stale. */
|
||||
function maybeStartProbe() {
|
||||
if (!healthProbe || probeInFlight) return
|
||||
@@ -109,6 +179,7 @@ function maybeStartProbe() {
|
||||
if (epoch !== probeEpoch) return
|
||||
lastProbeOk = ok
|
||||
consecutiveProbeFailures = ok ? 0 : consecutiveProbeFailures + 1
|
||||
if (ok) lastReachableAt = Date.now()
|
||||
}
|
||||
healthProbe()
|
||||
.then(
|
||||
@@ -124,6 +195,17 @@ function maybeStartProbe() {
|
||||
}
|
||||
|
||||
function recompute() {
|
||||
if (devOverride === null && inColdStartWindow()) {
|
||||
// Cold start: probe after just COLD_PROBE_AFTER_MS (rather than waiting for
|
||||
// the 10s stall threshold) so the calm waking state can appear within a few seconds. The
|
||||
// probe still gates it: a warm backend answers /api/health instantly, so a
|
||||
// merely slow endpoint never shows the waking state.
|
||||
const age = Date.now() - oldestStartedAt()
|
||||
if (healthProbe && age >= COLD_PROBE_AFTER_MS) maybeStartProbe()
|
||||
const probeSaysDown = !healthProbe || lastProbeOk === false
|
||||
setStatus(age >= WAKING_SHOW_MS && probeSaysDown ? 'waking' : 'online')
|
||||
return
|
||||
}
|
||||
let next = devOverride ?? computeFromStalls()
|
||||
// A stall only becomes a banner once the health probe CONFIRMS the backend is
|
||||
// unreachable. While the probe answers OK (or hasn't answered yet), the stalled
|
||||
@@ -169,6 +251,84 @@ export function endRequest(id: number): void {
|
||||
if (inFlight.delete(id)) recompute()
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that the backend just answered (any non-transient HTTP response, from any
|
||||
* request). This is what distinguishes "was up, now stalled" (recycle/outage:
|
||||
* normal banner) from "hasn't answered lately" (cold start: calm waking state).
|
||||
*/
|
||||
export function markBackendReachable(): void {
|
||||
lastReachableAt = Date.now()
|
||||
coldEpisodeStartedAt = null
|
||||
// The backend just answered, so any earlier failed-probe verdict is stale: drop
|
||||
// it rather than let it vouch for a future stall (re-probe instead).
|
||||
if (lastProbeOk === false) {
|
||||
lastProbeOk = null
|
||||
consecutiveProbeFailures = 0
|
||||
}
|
||||
if (inFlight.size > 0 || status !== 'online') recompute()
|
||||
}
|
||||
|
||||
/** Untracked warm-up request (GET /api/health). Must never reject. */
|
||||
type Prewarm = () => Promise<boolean>
|
||||
let prewarmFn: Prewarm | null = null
|
||||
let prewarmInFlight = false
|
||||
let hiddenAt: number | null = null
|
||||
let visibilityListenerInstalled = false
|
||||
|
||||
/** Registered once by lib/api.ts (keeps this module free of fetch/URL concerns). */
|
||||
export function configurePrewarm(fn: Prewarm | null): void {
|
||||
prewarmFn = fn
|
||||
prewarmInFlight = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire-and-forget wake-up for a backend that may have scaled to zero, so the cold
|
||||
* start overlaps with the user reading the page instead of blocking their first
|
||||
* action. Untracked: it never drives the banner itself. A no-op if one is already
|
||||
* in flight or the backend answered within REACHABLE_FRESH_MS.
|
||||
*/
|
||||
export function prewarmBackend(): void {
|
||||
if (!prewarmFn || prewarmInFlight) return
|
||||
if (lastReachableAt !== 0 && Date.now() - lastReachableAt < REACHABLE_FRESH_MS) return
|
||||
prewarmInFlight = true
|
||||
prewarmFn()
|
||||
.then(
|
||||
(ok) => {
|
||||
if (ok) markBackendReachable()
|
||||
},
|
||||
() => {},
|
||||
)
|
||||
.finally(() => {
|
||||
prewarmInFlight = false
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-warm now, and again whenever the tab becomes visible after being hidden for
|
||||
* PREWARM_AFTER_HIDDEN_MS (long enough that the backend may have scaled to zero).
|
||||
* Idempotent; call from any client component mounted app-wide, passing
|
||||
* `__backendPrewarm` from lib/api.ts.
|
||||
*/
|
||||
export function installBackendPrewarm(fn?: Prewarm): void {
|
||||
if (typeof document === 'undefined') return
|
||||
// Callers pass the fetch explicitly so the pre-warm works even on a page that
|
||||
// hasn't (yet) loaded lib/api.ts, which is where it's otherwise registered.
|
||||
if (fn && !prewarmFn) configurePrewarm(fn)
|
||||
prewarmBackend()
|
||||
if (visibilityListenerInstalled) return
|
||||
visibilityListenerInstalled = true
|
||||
if (document.visibilityState === 'hidden') hiddenAt = Date.now()
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
hiddenAt = Date.now()
|
||||
return
|
||||
}
|
||||
const wasHiddenFor = hiddenAt === null ? 0 : Date.now() - hiddenAt
|
||||
hiddenAt = null
|
||||
if (wasHiddenFor >= PREWARM_AFTER_HIDDEN_MS) prewarmBackend()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the reachability probe used to confirm a stall before the banner shows.
|
||||
* The probe must never reject and must settle within a few seconds (race against
|
||||
@@ -190,19 +350,34 @@ export function getBackendStatusDebug(): {
|
||||
inFlightCount: number
|
||||
lastProbeOk: boolean | null
|
||||
consecutiveProbeFailures: number
|
||||
/** ms since the backend last answered (null = never this session). */
|
||||
sinceReachableMs: number | null
|
||||
} {
|
||||
let oldest = Infinity
|
||||
for (const startedAt of inFlight.values()) {
|
||||
if (startedAt < oldest) oldest = startedAt
|
||||
}
|
||||
return {
|
||||
oldestStallMs: inFlight.size === 0 ? 0 : Date.now() - oldest,
|
||||
oldestStallMs: inFlight.size === 0 ? 0 : Date.now() - oldestStartedAt(),
|
||||
inFlightCount: inFlight.size,
|
||||
lastProbeOk,
|
||||
consecutiveProbeFailures,
|
||||
sinceReachableMs: lastReachableAt === 0 ? null : Date.now() - lastReachableAt,
|
||||
}
|
||||
}
|
||||
|
||||
/** Test-only: reset all module state (reachability, prewarm, in-flight reads). */
|
||||
export function __resetBackendStatusForTest(): void {
|
||||
inFlight.clear()
|
||||
devOverride = null
|
||||
lastReachableAt = 0
|
||||
coldEpisodeStartedAt = null
|
||||
prewarmInFlight = false
|
||||
hiddenAt = null
|
||||
configureHealthProbe(null)
|
||||
if (ticker) {
|
||||
clearInterval(ticker)
|
||||
ticker = null
|
||||
}
|
||||
status = 'online'
|
||||
}
|
||||
|
||||
export function getBackendStatus(): BackendStatus {
|
||||
return status
|
||||
}
|
||||
@@ -236,6 +411,7 @@ export function __installBackendStatusDevHook() {
|
||||
recompute()
|
||||
}
|
||||
;(window as unknown as { __nkBackendStatus?: unknown }).__nkBackendStatus = {
|
||||
waking: () => simulate('waking'),
|
||||
reconnecting: () => simulate('reconnecting'),
|
||||
unavailable: () => simulate('unavailable'),
|
||||
online: () => simulate(null),
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
export type DegradationEventType =
|
||||
| 'banner_reconnecting'
|
||||
| 'banner_unavailable'
|
||||
| 'banner_waking'
|
||||
| 'lyrics_load_failed'
|
||||
| 'waveform_slow'
|
||||
| 'waveform_failed'
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "أي مقاطع فيديو كاريوكي يتم إنشاؤها حالياً لن تتأثر وستستمر قيد المعالجة.",
|
||||
"title": "نواجه مشكلة في الوصول إلى خوادمنا"
|
||||
},
|
||||
"dismiss": "تجاهل"
|
||||
"dismiss": "تجاهل",
|
||||
"waking": {
|
||||
"body": "يستغرق هذا عادةً حوالي 20 ثانية. شكرًا لصبرك!",
|
||||
"title": "جارٍ تشغيل خوادم الكاريوكي…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "تتم الآن معالجة {count} من المسارات.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Els vídeos de karaoke que s'estiguin creant ara mateix no es veuran afectats i es continuaran processant.",
|
||||
"title": "Tenim problemes per connectar amb els nostres servidors"
|
||||
},
|
||||
"dismiss": "Descarta"
|
||||
"dismiss": "Descarta",
|
||||
"waking": {
|
||||
"body": "Normalment triga uns 20 segons. Gràcies per la teva paciència!",
|
||||
"title": "S'estan iniciant els nostres servidors de karaoke…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "S'estan processant {count} pistes.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Právě vytvářená karaoke videa nejsou nijak ovlivněna a budou se nadále zpracovávat.",
|
||||
"title": "Nedaří se nám spojit s našimi servery"
|
||||
},
|
||||
"dismiss": "Zavřít"
|
||||
"dismiss": "Zavřít",
|
||||
"waking": {
|
||||
"body": "Obvykle to trvá asi 20 sekund. Díky za trpělivost!",
|
||||
"title": "Spouštíme naše karaoke servery…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} skladeb se nyní zpracovává.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Eventuelle karaokevideoer, der i øjeblikket bliver lavet, påvirkes ikke og vil fortsat blive behandlet.",
|
||||
"title": "Vi har problemer med at få forbindelse til vores servere"
|
||||
},
|
||||
"dismiss": "Afvis"
|
||||
"dismiss": "Afvis",
|
||||
"waking": {
|
||||
"body": "Det tager normalt omkring 20 sekunder. Tak for din tålmodighed!",
|
||||
"title": "Starter vores karaokeservere…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} numre bliver nu behandlet.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Alle Karaoke-Videos, die gerade erstellt werden, sind davon nicht betroffen und werden weiterverarbeitet.",
|
||||
"title": "Wir haben Probleme, unsere Server zu erreichen"
|
||||
},
|
||||
"dismiss": "Ausblenden"
|
||||
"dismiss": "Ausblenden",
|
||||
"waking": {
|
||||
"body": "Das dauert normalerweise etwa 20 Sekunden. Danke für deine Geduld!",
|
||||
"title": "Unsere Karaoke-Server werden gestartet…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} Tracks werden jetzt verarbeitet.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Τυχόν βίντεο καραόκε που δημιουργούνται αυτήν τη στιγμή δεν επηρεάζονται και η επεξεργασία τους θα συνεχιστεί.",
|
||||
"title": "Αντιμετωπίζουμε πρόβλημα σύνδεσης με τους διακομιστές μας"
|
||||
},
|
||||
"dismiss": "Απόρριψη"
|
||||
"dismiss": "Απόρριψη",
|
||||
"waking": {
|
||||
"body": "Αυτό συνήθως διαρκεί περίπου 20 δευτερόλεπτα. Ευχαριστούμε για την υπομονή σου!",
|
||||
"title": "Εκκίνηση των διακομιστών καραόκε μας…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} κομμάτια βρίσκονται τώρα σε επεξεργασία.",
|
||||
|
||||
@@ -371,6 +371,10 @@
|
||||
},
|
||||
"backendStatus": {
|
||||
"reconnecting": "Reconnecting…",
|
||||
"waking": {
|
||||
"title": "Starting up our karaoke servers…",
|
||||
"body": "This usually takes about 20 seconds. Thanks for your patience!"
|
||||
},
|
||||
"unavailable": {
|
||||
"title": "We're having trouble reaching our servers",
|
||||
"body": "This is usually temporary — please try again in a couple of minutes.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Los videos de karaoke que se estén creando en este momento no se verán afectados y seguirán procesándose.",
|
||||
"title": "Tenemos problemas para conectar con nuestros servidores"
|
||||
},
|
||||
"dismiss": "Descartar"
|
||||
"dismiss": "Descartar",
|
||||
"waking": {
|
||||
"body": "Esto suele tardar unos 20 segundos. ¡Gracias por tu paciencia!",
|
||||
"title": "Iniciando nuestros servidores de karaoke…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} pistas se están procesando ahora.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Tämä ei vaikuta parhaillaan luotaviin karaokevideoihin, vaan niiden käsittely jatkuu normaalisti.",
|
||||
"title": "Palvelimiimme yhdistämisessä on ongelmia"
|
||||
},
|
||||
"dismiss": "Ohita"
|
||||
"dismiss": "Ohita",
|
||||
"waking": {
|
||||
"body": "Tämä kestää yleensä noin 20 sekuntia. Kiitos kärsivällisyydestäsi!",
|
||||
"title": "Käynnistetään karaokepalvelimiamme…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} kappaletta on nyt käsittelyssä.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Les vidéos de karaoké en cours de création ne sont pas affectées et continueront d'être traitées.",
|
||||
"title": "Nous avons des difficultés à joindre nos serveurs"
|
||||
},
|
||||
"dismiss": "Ignorer"
|
||||
"dismiss": "Ignorer",
|
||||
"waking": {
|
||||
"body": "Cela prend généralement une vingtaine de secondes. Merci de ta patience !",
|
||||
"title": "Démarrage de nos serveurs de karaoké…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} pistes sont maintenant en cours de traitement.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "סרטוני קריוקי שנוצרים כרגע לא יושפעו וימשיכו בתהליך העיבוד.",
|
||||
"title": "אנחנו מתקשים להתחבר לשרתים שלנו"
|
||||
},
|
||||
"dismiss": "התעלם"
|
||||
"dismiss": "התעלם",
|
||||
"waking": {
|
||||
"body": "זה בדרך כלל לוקח כ-20 שניות. תודה על הסבלנות!",
|
||||
"title": "מפעילים את שרתי הקריוקי שלנו…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} רצועות נמצאות כעת בעיבוד.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "अभी बन रहे किसी भी कराओके वीडियो पर कोई असर नहीं पड़ा है और उनकी प्रोसेसिंग जारी रहेगी।",
|
||||
"title": "हमें अपने सर्वर तक पहुँचने में परेशानी हो रही है"
|
||||
},
|
||||
"dismiss": "हटाओ"
|
||||
"dismiss": "हटाओ",
|
||||
"waking": {
|
||||
"body": "इसमें आमतौर पर लगभग 20 सेकंड लगते हैं। तुम्हारे धैर्य के लिए धन्यवाद!",
|
||||
"title": "हमारे कराओके सर्वर शुरू हो रहे हैं…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} ट्रैक्स अब प्रोसेस किए जा रहे हैं।",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Ovo ne utječe na karaoke videozapise koji se trenutno izrađuju i njihova će se obrada nastaviti.",
|
||||
"title": "Imamo problema s povezivanjem na naše servere"
|
||||
},
|
||||
"dismiss": "Odbaci"
|
||||
"dismiss": "Odbaci",
|
||||
"waking": {
|
||||
"body": "Ovo obično traje oko 20 sekundi. Hvala ti na strpljenju!",
|
||||
"title": "Pokrećemo naše karaoke poslužitelje…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} pjesama se sada obrađuje.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "A jelenleg készülő karaoke videókat ez nem érinti, a feldolgozásuk zavartalanul folytatódik.",
|
||||
"title": "Nem tudjuk elérni a szervereinket"
|
||||
},
|
||||
"dismiss": "Elvetés"
|
||||
"dismiss": "Elvetés",
|
||||
"waking": {
|
||||
"body": "Ez általában körülbelül 20 másodpercet vesz igénybe. Köszönjük a türelmedet!",
|
||||
"title": "Karaokeszervereink indítása…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} szám feldolgozása folyamatban van.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Video karaoke yang sedang dibuat tidak akan terpengaruh dan akan terus diproses.",
|
||||
"title": "Kami kesulitan terhubung ke server"
|
||||
},
|
||||
"dismiss": "Abaikan"
|
||||
"dismiss": "Abaikan",
|
||||
"waking": {
|
||||
"body": "Proses ini biasanya membutuhkan waktu sekitar 20 detik. Terima kasih atas kesabaran Anda!",
|
||||
"title": "Menyalakan server karaoke kami…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} trek sedang diproses.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "I video karaoke attualmente in fase di creazione non subiranno interruzioni e continueranno a essere elaborati.",
|
||||
"title": "Abbiamo problemi a raggiungere i nostri server"
|
||||
},
|
||||
"dismiss": "Ignora"
|
||||
"dismiss": "Ignora",
|
||||
"waking": {
|
||||
"body": "Di solito ci vogliono circa 20 secondi. Grazie per la pazienza!",
|
||||
"title": "Avvio dei nostri server karaoke in corso…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} tracce sono ora in fase di elaborazione.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "現在作成中のカラオケ動画に影響はありません。そのまま処理が継続されます。",
|
||||
"title": "サーバーへの接続に問題が発生しています"
|
||||
},
|
||||
"dismiss": "閉じる"
|
||||
"dismiss": "閉じる",
|
||||
"waking": {
|
||||
"body": "通常約20秒かかります。そのまま少々お待ちください!",
|
||||
"title": "カラオケサーバーを起動しています…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count}曲のトラックを処理しています。",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "현재 생성 중인 노래방 영상은 영향을 받지 않고 정상적으로 처리됩니다.",
|
||||
"title": "서버에 연결하는 데 문제가 발생했습니다"
|
||||
},
|
||||
"dismiss": "닫기"
|
||||
"dismiss": "닫기",
|
||||
"waking": {
|
||||
"body": "보통 20초 정도 걸려요. 잠시만 기다려 주세요!",
|
||||
"title": "가라오케 서버를 시작하는 중…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count}개의 트랙이 현재 처리 중입니다.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Sebarang video karaoke yang sedang dihasilkan tidak terjejas dan akan terus diproses.",
|
||||
"title": "Kami menghadapi masalah menyambung ke pelayan kami"
|
||||
},
|
||||
"dismiss": "Tutup"
|
||||
"dismiss": "Tutup",
|
||||
"waking": {
|
||||
"body": "Ini biasanya mengambil masa kira-kira 20 saat. Terima kasih atas kesabaran anda!",
|
||||
"title": "Memulakan pelayan karaoke kami…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} trek sedang diproses sekarang.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Eventuelle karaokevideoer som lages akkurat nå påvirkes ikke, og vil fortsette å behandles.",
|
||||
"title": "Vi har problemer med å nå serverne våre"
|
||||
},
|
||||
"dismiss": "Lukk"
|
||||
"dismiss": "Lukk",
|
||||
"waking": {
|
||||
"body": "Dette tar vanligvis rundt 20 sekunder. Takk for tålmodigheten!",
|
||||
"title": "Starter opp karaokeserverne våre…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} låter blir nå behandlet.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Karaokevideo's die momenteel worden gemaakt, ondervinden hier geen hinder van en worden gewoon verder verwerkt.",
|
||||
"title": "We kunnen onze servers even niet bereiken"
|
||||
},
|
||||
"dismiss": "Sluiten"
|
||||
"dismiss": "Sluiten",
|
||||
"waking": {
|
||||
"body": "Dit duurt meestal ongeveer 20 seconden. Bedankt voor je geduld!",
|
||||
"title": "Onze karaokeservers worden opgestart…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} tracks worden nu verwerkt.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Obecnie tworzone filmy karaoke są bezpieczne i będą nadal przetwarzane.",
|
||||
"title": "Mamy problem z połączeniem z naszymi serwerami"
|
||||
},
|
||||
"dismiss": "Zamknij"
|
||||
"dismiss": "Zamknij",
|
||||
"waking": {
|
||||
"body": "Zwykle zajmuje to około 20 sekund. Dziękujemy za cierpliwość!",
|
||||
"title": "Uruchamiamy nasze serwery karaoke…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} utworów jest teraz przetwarzanych.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Os vídeos de karaokê que estão sendo criados no momento não serão afetados e continuarão sendo processados.",
|
||||
"title": "Estamos com problemas para acessar nossos servidores"
|
||||
},
|
||||
"dismiss": "Dispensar"
|
||||
"dismiss": "Dispensar",
|
||||
"waking": {
|
||||
"body": "Isso geralmente leva cerca de 20 segundos. Agradecemos a sua paciência!",
|
||||
"title": "Iniciando nossos servidores de karaokê…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} faixas estão sendo processadas agora.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Videoclipurile de karaoke aflate în curs de creare nu sunt afectate și vor continua să fie procesate.",
|
||||
"title": "Întâmpinăm probleme la conectarea cu serverele noastre"
|
||||
},
|
||||
"dismiss": "Închide"
|
||||
"dismiss": "Închide",
|
||||
"waking": {
|
||||
"body": "De obicei, durează aproximativ 20 de secunde. Îți mulțumim pentru răbdare!",
|
||||
"title": "Pornim serverele de karaoke…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} piese sunt acum în curs de procesare.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Это не повлияет на караоке-видео, которые сейчас создаются — они продолжат обрабатываться.",
|
||||
"title": "Возникли проблемы с подключением к нашим серверам"
|
||||
},
|
||||
"dismiss": "Скрыть"
|
||||
"dismiss": "Скрыть",
|
||||
"waking": {
|
||||
"body": "Обычно это занимает около 20 секунд. Спасибо за терпение!",
|
||||
"title": "Запускаем наши караоке-серверы…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "Сейчас обрабатывается {count} треков.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Karaoke videá, ktoré sa práve vytvárajú, to neovplyvní a ich spracovanie bude pokračovať.",
|
||||
"title": "Máme problémy s pripojením k našim serverom"
|
||||
},
|
||||
"dismiss": "Zavrieť"
|
||||
"dismiss": "Zavrieť",
|
||||
"waking": {
|
||||
"body": "Zvyčajne to trvá približne 20 sekúnd. Ďakujeme za trpezlivosť!",
|
||||
"title": "Spúšťame naše karaoke servery…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} skladieb sa teraz spracúva.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Karaokevideor som håller på att skapas påverkas inte, utan fortsätter att bearbetas.",
|
||||
"title": "Vi har problem med att nå våra servrar"
|
||||
},
|
||||
"dismiss": "Avfärda"
|
||||
"dismiss": "Avfärda",
|
||||
"waking": {
|
||||
"body": "Det brukar ta cirka 20 sekunder. Tack för ditt tålamod!",
|
||||
"title": "Startar våra karaokeservrar…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} spår bearbetas nu.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "วิดีโอคาราโอเกะที่กำลังสร้างอยู่จะไม่ได้รับผลกระทบ และจะประมวลผลต่อไป",
|
||||
"title": "เราพบปัญหาในการเชื่อมต่อกับเซิร์ฟเวอร์"
|
||||
},
|
||||
"dismiss": "ปิดทิ้ง"
|
||||
"dismiss": "ปิดทิ้ง",
|
||||
"waking": {
|
||||
"body": "ขั้นตอนนี้มักใช้เวลาประมาณ 20 วินาที ขอบคุณที่รออย่างอดทนนะครับ/ค่ะ!",
|
||||
"title": "กำลังเริ่มการทำงานของเซิร์ฟเวอร์คาราโอเกะ…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "กำลังประมวลผลเพลงจำนวน {count} เพลง",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Ang anumang karaoke video na kasalukuyang ginagawa ay hindi maaapektuhan at patuloy na ipoproseso.",
|
||||
"title": "Nahihirapan kaming kumonekta sa aming mga server"
|
||||
},
|
||||
"dismiss": "I-dismiss"
|
||||
"dismiss": "I-dismiss",
|
||||
"waking": {
|
||||
"body": "Karaniwang tumatagal ito nang mga 20 segundo. Salamat sa iyong paghihintay!",
|
||||
"title": "Sinisimulan na ang aming mga karaoke server…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "Pinoproseso na ang {count} track.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Şu anda oluşturulmakta olan karaoke videoları bu durumdan etkilenmez ve işlenmeye devam eder.",
|
||||
"title": "Sunucularımıza ulaşmakta sorun yaşıyoruz"
|
||||
},
|
||||
"dismiss": "Kapat"
|
||||
"dismiss": "Kapat",
|
||||
"waking": {
|
||||
"body": "Bu işlem genellikle yaklaşık 20 saniye sürer. Sabrın için teşekkürler!",
|
||||
"title": "Karaoke sunucularımız başlatılıyor…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} parça şu anda işleniyor.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Це не вплине на караоке-відео, які зараз створюються, їхня обробка продовжиться.",
|
||||
"title": "Виникли проблеми зі зв'язком із нашими серверами"
|
||||
},
|
||||
"dismiss": "Закрити"
|
||||
"dismiss": "Закрити",
|
||||
"waking": {
|
||||
"body": "Зазвичай це займає близько 20 секунд. Дякуємо за терпіння!",
|
||||
"title": "Запускаємо наші караоке-сервери…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} треків зараз обробляються.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Các video karaoke đang được tạo sẽ không bị ảnh hưởng và vẫn tiếp tục được xử lý.",
|
||||
"title": "Chúng tôi đang gặp sự cố khi kết nối với máy chủ"
|
||||
},
|
||||
"dismiss": "Bỏ qua"
|
||||
"dismiss": "Bỏ qua",
|
||||
"waking": {
|
||||
"body": "Quá trình này thường mất khoảng 20 giây. Cảm ơn bạn đã kiên nhẫn chờ đợi!",
|
||||
"title": "Đang khởi động hệ thống máy chủ karaoke…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} bài hát hiện đang được xử lý.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "当前正在制作的卡拉OK视频不会受到影响,系统将继续进行处理。",
|
||||
"title": "我们连接服务器时遇到了一些问题"
|
||||
},
|
||||
"dismiss": "忽略"
|
||||
"dismiss": "忽略",
|
||||
"waking": {
|
||||
"body": "通常需要大约 20 秒,感谢您的耐心等待!",
|
||||
"title": "正在启动卡拉OK服务器…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} 首曲目正在处理中。",
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Gemini Developer API (Google AI Studio) client helper for local scripts.
|
||||
|
||||
All Gemini calls go through the Developer API with an API key, NOT Vertex AI
|
||||
(Vertex is disabled in the nomadkaraoke GCP project to keep AI spend off it).
|
||||
|
||||
Key resolution (first match wins):
|
||||
1. ``GEMINI_API_KEY`` environment variable
|
||||
2. ``gcloud secrets versions access latest --secret=gemini-api-key
|
||||
--project=nomadkaraoke`` (your own gcloud login)
|
||||
|
||||
The key is cached in-process only; it is never written to disk or printed.
|
||||
|
||||
Rotating the key (e.g. prepaid credit exhausted): add a new secret version —
|
||||
no code change needed:
|
||||
printf '%s' "$NEW_KEY" | gcloud secrets versions add gemini-api-key \
|
||||
--project=nomadkaraoke --data-file=-
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
SECRET_NAME = "gemini-api-key"
|
||||
SECRET_PROJECT = "nomadkaraoke"
|
||||
|
||||
QUOTA_EXHAUSTED_MESSAGE = (
|
||||
"Gemini quota/credit exhausted — top up AI Studio or rotate gemini-api-key "
|
||||
f"(add a new version of Secret Manager secret '{SECRET_NAME}' in project "
|
||||
f"'{SECRET_PROJECT}')."
|
||||
)
|
||||
|
||||
|
||||
def quota_exhausted_message() -> str:
|
||||
"""QUOTA_EXHAUSTED_MESSAGE plus a hint when the key came from the environment."""
|
||||
if os.environ.get("GEMINI_API_KEY", "").strip():
|
||||
return (
|
||||
QUOTA_EXHAUSTED_MESSAGE
|
||||
+ " Note: the key came from the GEMINI_API_KEY environment variable — "
|
||||
"unset it to use the Secret Manager key instead."
|
||||
)
|
||||
return QUOTA_EXHAUSTED_MESSAGE
|
||||
|
||||
|
||||
class GeminiKeyUnavailableError(RuntimeError):
|
||||
"""The Gemini API key could not be resolved (env var unset and gcloud failed)."""
|
||||
|
||||
|
||||
_cached_key: str | None = None
|
||||
|
||||
|
||||
def get_api_key() -> str:
|
||||
"""Return the Gemini Developer API key (env var, else Secret Manager via gcloud)."""
|
||||
global _cached_key
|
||||
env_key = os.environ.get("GEMINI_API_KEY", "").strip()
|
||||
if env_key:
|
||||
return env_key
|
||||
if _cached_key:
|
||||
return _cached_key
|
||||
cmd = [
|
||||
"gcloud", "secrets", "versions", "access", "latest",
|
||||
f"--secret={SECRET_NAME}", f"--project={SECRET_PROJECT}",
|
||||
]
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired) as e:
|
||||
raise GeminiKeyUnavailableError(
|
||||
f"GEMINI_API_KEY is not set and `gcloud secrets versions access` failed: {e}"
|
||||
) from e
|
||||
key = (result.stdout or "").strip()
|
||||
if result.returncode != 0 or not key:
|
||||
stderr = (result.stderr or "").strip()[-300:]
|
||||
raise GeminiKeyUnavailableError(
|
||||
"GEMINI_API_KEY is not set and reading Secret Manager secret "
|
||||
f"'{SECRET_NAME}' (project {SECRET_PROJECT}) failed — run `gcloud auth login` "
|
||||
f"or export GEMINI_API_KEY. gcloud said: {stderr}"
|
||||
)
|
||||
_cached_key = key
|
||||
return key
|
||||
|
||||
|
||||
def get_genai_client():
|
||||
"""Build a google-genai client for the Gemini Developer API."""
|
||||
from google import genai
|
||||
|
||||
# vertexai=False pins the Developer API even if GOOGLE_GENAI_USE_VERTEXAI is set.
|
||||
return genai.Client(vertexai=False, api_key=get_api_key())
|
||||
|
||||
|
||||
# Message fragments that mean "the key/account can't pay or isn't valid" — a
|
||||
# retry won't help; a human must top up credit or rotate the key.
|
||||
_QUOTA_PATTERNS = re.compile(
|
||||
r"RESOURCE_EXHAUSTED|exceeded your current quota|quota exceeded|"
|
||||
r"billing (details|account)|prepa(id|yment)|credits? (are |is |have been )?"
|
||||
r"(exhausted|depleted|used up)|insufficient (credit|funds|balance)|"
|
||||
r"API_KEY_INVALID|API key not valid|API key expired|API_KEY_SERVICE_BLOCKED|"
|
||||
r"\b429 Too Many Requests",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# A 429 that names a per-minute quota / carries a retry delay is an ordinary
|
||||
# rate limit (transient — retry with backoff), not exhausted credit.
|
||||
_RATE_LIMIT_PATTERNS = re.compile(r"PerMinute|retryDelay|retry in \d", re.IGNORECASE)
|
||||
# ...unless it names a per-day quota: that won't clear for hours — treat as exhausted.
|
||||
_DAILY_QUOTA_PATTERN = re.compile(r"PerDay", re.IGNORECASE)
|
||||
|
||||
|
||||
def _is_rate_limit(text: str) -> bool:
|
||||
return bool(_RATE_LIMIT_PATTERNS.search(text)) and not _DAILY_QUOTA_PATTERN.search(text)
|
||||
|
||||
|
||||
def is_quota_or_billing_error(exc: BaseException | None) -> bool:
|
||||
"""True if ``exc`` (or anything in its ``__cause__`` chain) is a Gemini quota,
|
||||
prepaid-credit, billing or API-key error — i.e. needs a top-up/key rotation,
|
||||
not a retry.
|
||||
|
||||
Matches google-genai ``APIError`` (``.code`` 429 / 403, or 400 with a
|
||||
billing/key message) and wrapped/stringified errors from other layers.
|
||||
Per-minute rate limits (429 naming a ``PerMinute`` quota or a retry delay)
|
||||
are NOT matched — those are transient; retry them.
|
||||
"""
|
||||
seen: set[int] = set()
|
||||
while exc is not None and id(exc) not in seen:
|
||||
seen.add(id(exc))
|
||||
if isinstance(exc, GeminiKeyUnavailableError):
|
||||
return True
|
||||
code = getattr(exc, "code", None)
|
||||
if code is None:
|
||||
code = getattr(exc, "status_code", None)
|
||||
status = str(getattr(exc, "status", "") or "")
|
||||
if code == 429 or status == "RESOURCE_EXHAUSTED":
|
||||
return not _is_rate_limit(str(exc))
|
||||
if code == 403 or status == "PERMISSION_DENIED":
|
||||
return True
|
||||
text = str(exc)
|
||||
if _QUOTA_PATTERNS.search(text) and not _is_rate_limit(text):
|
||||
return True
|
||||
# Only explicit chaining (`raise X from e`): implicit __context__ could
|
||||
# attribute an unrelated earlier error (e.g. a Firestore 403) to Gemini.
|
||||
exc = exc.__cause__
|
||||
return False
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Unit tests for scripts/gemini_client.py (run: python -m pytest scripts/test_gemini_client.py)."""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
|
||||
import gemini_client # noqa: E402
|
||||
from gemini_client import ( # noqa: E402
|
||||
GeminiKeyUnavailableError,
|
||||
get_api_key,
|
||||
is_quota_or_billing_error,
|
||||
)
|
||||
|
||||
|
||||
class FakeAPIError(Exception):
|
||||
"""Mimics google.genai.errors.APIError (numeric ``code`` + ``status``)."""
|
||||
|
||||
def __init__(self, code, status, message):
|
||||
super().__init__(f"{code} {status}. {message}")
|
||||
self.code = code
|
||||
self.status = status
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_cache(monkeypatch):
|
||||
monkeypatch.setattr(gemini_client, "_cached_key", None)
|
||||
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
|
||||
|
||||
|
||||
class TestIsQuotaOrBillingError:
|
||||
@pytest.mark.parametrize(
|
||||
"exc",
|
||||
[
|
||||
FakeAPIError(429, "RESOURCE_EXHAUSTED", "You exceeded your current quota"),
|
||||
FakeAPIError(403, "PERMISSION_DENIED", "Your prepayment credits are depleted"),
|
||||
FakeAPIError(400, "INVALID_ARGUMENT", "API key not valid. Please pass a valid API key."),
|
||||
FakeAPIError(400, "FAILED_PRECONDITION", "Please check your plan and billing details"),
|
||||
RuntimeError("429 RESOURCE_EXHAUSTED quota"),
|
||||
RuntimeError("Your credits have been exhausted"),
|
||||
GeminiKeyUnavailableError("no key"),
|
||||
RuntimeError("429 RESOURCE_EXHAUSTED quotaId GenerateRequestsPerDayPerProjectPerModel, retryDelay 3600s"),
|
||||
],
|
||||
)
|
||||
def test_positive(self, exc):
|
||||
assert is_quota_or_billing_error(exc)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exc",
|
||||
[
|
||||
FakeAPIError(500, "INTERNAL", "Internal error"),
|
||||
FakeAPIError(503, "UNAVAILABLE", "The model is overloaded"),
|
||||
FakeAPIError(400, "INVALID_ARGUMENT", "Request contains an invalid argument."),
|
||||
TimeoutError("timed out"),
|
||||
ValueError("bad JSON from model, processed 429 tokens"),
|
||||
FakeAPIError(
|
||||
429,
|
||||
"RESOURCE_EXHAUSTED",
|
||||
"You exceeded your current quota. quotaId: "
|
||||
"GenerateRequestsPerMinutePerProjectPerModel-PaidTier, retryDelay: 7s",
|
||||
),
|
||||
RuntimeError("429 RESOURCE_EXHAUSTED ... Please retry in 7.2s"),
|
||||
None,
|
||||
],
|
||||
)
|
||||
def test_negative(self, exc):
|
||||
assert not is_quota_or_billing_error(exc)
|
||||
|
||||
def test_walks_cause_chain(self):
|
||||
try:
|
||||
try:
|
||||
raise FakeAPIError(429, "RESOURCE_EXHAUSTED", "quota")
|
||||
except FakeAPIError as inner:
|
||||
raise RuntimeError("translation failed") from inner
|
||||
except RuntimeError as outer:
|
||||
assert is_quota_or_billing_error(outer)
|
||||
|
||||
|
||||
class TestGetApiKey:
|
||||
def test_env_var_wins(self, monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_API_KEY", " from-env ")
|
||||
with mock.patch.object(subprocess, "run") as run:
|
||||
assert get_api_key() == "from-env"
|
||||
run.assert_not_called()
|
||||
|
||||
def test_falls_back_to_gcloud_and_caches(self):
|
||||
done = subprocess.CompletedProcess([], 0, stdout="from-secret\n", stderr="")
|
||||
with mock.patch.object(subprocess, "run", return_value=done) as run:
|
||||
assert get_api_key() == "from-secret"
|
||||
assert get_api_key() == "from-secret"
|
||||
assert run.call_count == 1
|
||||
cmd = run.call_args.args[0]
|
||||
assert "--secret=gemini-api-key" in cmd and "--project=nomadkaraoke" in cmd
|
||||
|
||||
def test_gcloud_failure_raises(self):
|
||||
failed = subprocess.CompletedProcess([], 1, stdout="", stderr="PERMISSION_DENIED")
|
||||
with mock.patch.object(subprocess, "run", return_value=failed):
|
||||
with pytest.raises(GeminiKeyUnavailableError):
|
||||
get_api_key()
|
||||
|
||||
def test_gcloud_missing_raises(self):
|
||||
with mock.patch.object(subprocess, "run", side_effect=FileNotFoundError("gcloud")):
|
||||
with pytest.raises(GeminiKeyUnavailableError):
|
||||
get_api_key()
|
||||
|
||||
|
||||
def test_quota_message_hints_env_key(monkeypatch):
|
||||
assert "environment" not in gemini_client.quota_exhausted_message()
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "x")
|
||||
assert "GEMINI_API_KEY environment variable" in gemini_client.quota_exhausted_message()
|
||||
|
||||
|
||||
def test_client_pins_developer_api(monkeypatch):
|
||||
"""vertexai=False even if GOOGLE_GENAI_USE_VERTEXAI is set in the environment."""
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "k")
|
||||
monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "true")
|
||||
with mock.patch("google.genai.Client") as client_cls:
|
||||
gemini_client.get_genai_client()
|
||||
kwargs = client_cls.call_args.kwargs
|
||||
assert kwargs["vertexai"] is False and kwargs["api_key"] == "k"
|
||||
@@ -2,7 +2,7 @@
|
||||
"""
|
||||
LLM Translation Pipeline for Nomad Karaoke i18n.
|
||||
|
||||
Two-pass translation using Gemini via Vertex AI:
|
||||
Two-pass translation using Gemini (Developer API):
|
||||
1. Translate English JSON to target language
|
||||
2. Review and polish translations for fluency
|
||||
|
||||
@@ -24,7 +24,9 @@ Usage:
|
||||
|
||||
Requires:
|
||||
- google-genai SDK (pip install google-genai)
|
||||
- GCP Application Default Credentials (gcloud auth application-default login)
|
||||
- Gemini Developer API key: GEMINI_API_KEY env var, else read from Secret
|
||||
Manager (gemini-api-key) via your gcloud login — see gemini_client.py
|
||||
- GCP Application Default Credentials for the GCS translation cache
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -34,14 +36,18 @@ import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from gemini_client import (
|
||||
quota_exhausted_message,
|
||||
GeminiKeyUnavailableError,
|
||||
get_genai_client,
|
||||
is_quota_or_billing_error,
|
||||
)
|
||||
from translation_cache import TranslationCache
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
MODEL = "gemini-3.8-flash"
|
||||
PROJECT = "nomadkaraoke"
|
||||
LOCATION = "global"
|
||||
|
||||
MAX_CONCURRENT = 5
|
||||
MAX_RETRIES = 3
|
||||
@@ -319,13 +325,14 @@ async def _call_with_retry(client: genai.Client, prompt: str) -> str:
|
||||
model=MODEL,
|
||||
contents=prompt,
|
||||
config=types.GenerateContentConfig(
|
||||
thinking_config=types.ThinkingConfig(thinking_level="medium"),
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
temperature=0.3,
|
||||
),
|
||||
)
|
||||
return response.text
|
||||
except Exception as e:
|
||||
if attempt == MAX_RETRIES - 1:
|
||||
# Quota/credit/key errors won't fix themselves — fail fast.
|
||||
if attempt == MAX_RETRIES - 1 or is_quota_or_billing_error(e):
|
||||
raise
|
||||
wait = 2 ** (attempt + 1)
|
||||
print(f" Retry {attempt + 1}/{MAX_RETRIES} after error: {e}")
|
||||
@@ -576,12 +583,14 @@ async def async_main(args):
|
||||
elif not args.full:
|
||||
print("No snapshot found — will use missing-keys mode (use --full to force full retranslation)")
|
||||
|
||||
# Initialize Vertex AI client
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=PROJECT,
|
||||
location=LOCATION,
|
||||
)
|
||||
# Gemini Developer API client (API key; not needed for --dry-run)
|
||||
client = None
|
||||
if not args.dry_run:
|
||||
try:
|
||||
client = get_genai_client()
|
||||
except GeminiKeyUnavailableError as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
cache = TranslationCache(
|
||||
bucket_name=args.cache_bucket,
|
||||
@@ -589,7 +598,7 @@ async def async_main(args):
|
||||
)
|
||||
|
||||
print(f"Using model: {MODEL}")
|
||||
print(f"Project: {PROJECT}, Location: {LOCATION}")
|
||||
print("Backend: Gemini Developer API (gemini-api-key)")
|
||||
print(f"Locales: {', '.join(locales)} ({len(locales)} total)")
|
||||
if args.full:
|
||||
print("Mode: full (forced)")
|
||||
@@ -655,10 +664,14 @@ async def async_main(args):
|
||||
else:
|
||||
print()
|
||||
|
||||
if any(isinstance(r, BaseException) and is_quota_or_billing_error(r) for r in results):
|
||||
print(f"\nError: {quota_exhausted_message()}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Translate i18n message files using Gemini via Vertex AI"
|
||||
description="Translate i18n message files using the Gemini Developer API"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--messages-dir",
|
||||
|
||||
+26
-14
@@ -655,18 +655,29 @@ divebar_sync_compute_admin = gcp.projects.IAMMember(
|
||||
backup_resources = backup.create_backup_resources(all_secrets)
|
||||
|
||||
# ==================== Audio Separator GPU Service ====================
|
||||
# Cloud Run GPU (L4) service for audio stem separation — replaces Modal
|
||||
audio_separator_resources = audio_separator_service.create_all_resources()
|
||||
|
||||
# Grant audio separator read access to main storage bucket (for GCS URI passthrough)
|
||||
gcp.storage.BucketIAMMember(
|
||||
"audio-separator-storage-reader",
|
||||
bucket=bucket.name,
|
||||
role="roles/storage.objectViewer",
|
||||
member=audio_separator_resources["service_account"].email.apply(
|
||||
lambda email: f"serviceAccount:{email}"
|
||||
),
|
||||
# Standalone Cloud Run GPU (L4, us-east4) audio-separator API service.
|
||||
# SHUT DOWN 2026-10-01 (GCP cost cut, ~$22/mo): prod jobs never used it —
|
||||
# separation runs in the `audio-separation-job` GPU Cloud Run Job (local GPU
|
||||
# mode). Its only callers were Andrew's own tools (kjbox original-vocals
|
||||
# scripts, kjbox/fastgen). To bring it back on demand, see
|
||||
# docs/GCP-COST-OPTIMIZATION.md § "Audio separator service (shut down, on-demand redeploy)":
|
||||
# pulumi config set audioSeparatorServiceEnabled true && pulumi up --target ...
|
||||
AUDIO_SEPARATOR_SERVICE_ENABLED = (
|
||||
pulumi.Config().get_bool("audioSeparatorServiceEnabled") or False
|
||||
)
|
||||
audio_separator_resources = None
|
||||
if AUDIO_SEPARATOR_SERVICE_ENABLED:
|
||||
audio_separator_resources = audio_separator_service.create_all_resources()
|
||||
|
||||
# Grant audio separator read access to main storage bucket (for GCS URI passthrough)
|
||||
gcp.storage.BucketIAMMember(
|
||||
"audio-separator-storage-reader",
|
||||
bucket=bucket.name,
|
||||
role="roles/storage.objectViewer",
|
||||
member=audio_separator_resources["service_account"].email.apply(
|
||||
lambda email: f"serviceAccount:{email}"
|
||||
),
|
||||
)
|
||||
|
||||
# ==================== Compute VMs ====================
|
||||
|
||||
@@ -837,9 +848,10 @@ pulumi.export("divebar_lookup_function_url", divebar_lookup_resources["function"
|
||||
pulumi.export("divebar_sync_vm_name", divebar_sync_instance.name)
|
||||
pulumi.export("divebar_sync_scheduler_name", divebar_sync_scheduler.name)
|
||||
|
||||
# Audio separator GPU service
|
||||
pulumi.export("audio_separator_service_url", audio_separator_resources["service"].uri)
|
||||
pulumi.export("audio_separator_service_account", audio_separator_resources["service_account"].email)
|
||||
# Audio separator GPU service (only when re-enabled on demand)
|
||||
if audio_separator_resources is not None:
|
||||
pulumi.export("audio_separator_service_url", audio_separator_resources["service"].uri)
|
||||
pulumi.export("audio_separator_service_account", audio_separator_resources["service_account"].email)
|
||||
|
||||
# Encoding worker idle shutdown
|
||||
pulumi.export("encoding_worker_idle_function_url", encoding_worker_idle_resources["function"].url)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# Backend image build, submitted by the deploy-backend job in
|
||||
# .github/workflows/ci.yml (`gcloud builds submit --region us-central1`).
|
||||
# The CPU and GPU images build in parallel; the actual logic lives in
|
||||
# build-backend-images.sh (see its header for why this runs in Cloud Build).
|
||||
#
|
||||
# Machine type / disk / timeout are passed on the gcloud command line so CI can
|
||||
# use the free-tier e2-standard-2 for normal deploys and a bigger machine only
|
||||
# when a base image must be rebuilt.
|
||||
substitutions:
|
||||
_SHA: ""
|
||||
_VERSION: ""
|
||||
_RUN_ID: ""
|
||||
_BUILD_BASE: "false"
|
||||
_BASE_HASH: ""
|
||||
_BUILD_GPU_BASE: "false"
|
||||
_GPU_BASE_HASH: ""
|
||||
|
||||
steps:
|
||||
- id: cpu
|
||||
name: gcr.io/cloud-builders/docker
|
||||
entrypoint: bash
|
||||
args: ["infrastructure/cloudbuild/build-backend-images.sh", "cpu"]
|
||||
waitFor: ["-"]
|
||||
env:
|
||||
- "SHA=${_SHA}"
|
||||
- "VERSION=${_VERSION}"
|
||||
- "RUN_ID=${_RUN_ID}"
|
||||
- "BUILD_BASE=${_BUILD_BASE}"
|
||||
- "BASE_HASH=${_BASE_HASH}"
|
||||
|
||||
- id: gpu
|
||||
name: gcr.io/cloud-builders/docker
|
||||
entrypoint: bash
|
||||
args: ["infrastructure/cloudbuild/build-backend-images.sh", "gpu"]
|
||||
waitFor: ["-"]
|
||||
env:
|
||||
- "SHA=${_SHA}"
|
||||
- "VERSION=${_VERSION}"
|
||||
- "RUN_ID=${_RUN_ID}"
|
||||
- "BUILD_GPU_BASE=${_BUILD_GPU_BASE}"
|
||||
- "GPU_BASE_HASH=${_GPU_BASE_HASH}"
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds + pushes the backend container images. Runs INSIDE Cloud Build
|
||||
# (gcr.io/cloud-builders/docker, us-central1) — invoked by
|
||||
# infrastructure/cloudbuild/backend-images.yaml, which the deploy-backend job in
|
||||
# .github/workflows/ci.yml submits.
|
||||
#
|
||||
# Why Cloud Build and not the GitHub-hosted runner: the app images are built
|
||||
# FROM large bases (CPU ~4.2 GB, GPU ~13 GB compressed) that live in
|
||||
# us-central1 Artifact Registry. Pulling them to a GitHub-hosted runner is GCP
|
||||
# internet egress (~$0.12/GB → ~$2/deploy); pulling them to Cloud Build in
|
||||
# us-central1 is same-region (free), and e2-standard-2 build-minutes are in the
|
||||
# 2,500 min/month free tier. See docs/EPHEMERAL-GHA-RUNNERS.md.
|
||||
#
|
||||
# Usage: build-backend-images.sh cpu|gpu
|
||||
# Env (from Cloud Build substitutions): SHA, VERSION, RUN_ID,
|
||||
# BUILD_BASE, BASE_HASH (cpu) / BUILD_GPU_BASE, GPU_BASE_HASH (gpu)
|
||||
set -euo pipefail
|
||||
|
||||
TARGET="${1:?usage: build-backend-images.sh cpu|gpu}"
|
||||
|
||||
REG="us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo"
|
||||
# us-east4 repo: GPU app image (audio-separation job) + CPU app copy for the
|
||||
# latency-critical us-east4 CPU jobs. Only the changed app layers cross regions.
|
||||
EAST="us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu"
|
||||
BUILDER="nk-${TARGET}"
|
||||
|
||||
# Cloud Build pre-seeds ~/.docker/config.json with a static access token. A
|
||||
# GPU base rebuild can run long enough to outlive it, so log in with a fresh
|
||||
# metadata-server token before every build.
|
||||
refresh_auth() {
|
||||
local token
|
||||
token=$(curl -sf -H 'Metadata-Flavor: Google' \
|
||||
'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' \
|
||||
| sed -E 's/.*"access_token" *: *"([^"]+)".*/\1/')
|
||||
if [ -z "$token" ]; then
|
||||
echo "ERROR: could not fetch access token from metadata server" >&2
|
||||
exit 1
|
||||
fi
|
||||
for host in us-central1-docker.pkg.dev us-east4-docker.pkg.dev; do
|
||||
echo "$token" | docker login -u oauth2accesstoken --password-stdin "https://${host}" >/dev/null
|
||||
done
|
||||
}
|
||||
|
||||
# Each target gets its own docker-container builder: the cpu and gpu steps run
|
||||
# in parallel and must not race creating/bootstrapping a shared one.
|
||||
docker buildx create --name "$BUILDER" --driver docker-container >/dev/null
|
||||
docker buildx inspect "$BUILDER" --bootstrap >/dev/null
|
||||
|
||||
build() {
|
||||
refresh_auth
|
||||
docker buildx build --builder "$BUILDER" --push --provenance=false --progress=plain "$@" .
|
||||
}
|
||||
|
||||
case "$TARGET" in
|
||||
cpu)
|
||||
if [ "${BUILD_BASE:-false}" = "true" ]; then
|
||||
echo "=== Building CPU base image (karaoke-backend-base) ==="
|
||||
build -f backend/Dockerfile.base \
|
||||
-t "$REG/karaoke-backend-base:latest" \
|
||||
-t "$REG/karaoke-backend-base:$SHA" \
|
||||
--build-arg "BUILD_DATE=$RUN_ID" \
|
||||
--build-arg "BUILD_ID=$SHA" \
|
||||
--build-arg "BASE_CONTENT_HASH=$BASE_HASH" \
|
||||
--cache-from "type=registry,ref=$REG/karaoke-backend-base:cache" \
|
||||
--cache-to "type=registry,ref=$REG/karaoke-backend-base:cache,mode=max,ignore-error=true"
|
||||
fi
|
||||
echo "=== Building CPU app image (karaoke-backend + us-east4 karaoke-backend-cpu) ==="
|
||||
build -f backend/Dockerfile \
|
||||
-t "$REG/karaoke-backend:latest" \
|
||||
-t "$REG/karaoke-backend:$SHA" \
|
||||
-t "$REG/karaoke-backend:v$VERSION" \
|
||||
-t "$EAST/karaoke-backend-cpu:latest" \
|
||||
-t "$EAST/karaoke-backend-cpu:$SHA" \
|
||||
-t "$EAST/karaoke-backend-cpu:v$VERSION" \
|
||||
--cache-from "type=registry,ref=$REG/karaoke-backend:cache" \
|
||||
--cache-to "type=registry,ref=$REG/karaoke-backend:cache,mode=max,ignore-error=true"
|
||||
;;
|
||||
gpu)
|
||||
if [ "${BUILD_GPU_BASE:-false}" = "true" ]; then
|
||||
echo "=== Building GPU base image (karaoke-backend-gpu-base) ==="
|
||||
build -f backend/Dockerfile.gpu-base \
|
||||
-t "$REG/karaoke-backend-gpu-base:latest" \
|
||||
-t "$REG/karaoke-backend-gpu-base:$SHA" \
|
||||
--build-arg "BUILD_DATE=$RUN_ID" \
|
||||
--build-arg "BUILD_ID=$SHA" \
|
||||
--build-arg "BASE_CONTENT_HASH=$GPU_BASE_HASH" \
|
||||
--cache-from "type=registry,ref=$REG/karaoke-backend-gpu-base:cache" \
|
||||
--cache-to "type=registry,ref=$REG/karaoke-backend-gpu-base:cache,mode=max,ignore-error=true"
|
||||
fi
|
||||
# Base + cache in us-central1 (same region as Cloud Build); final image
|
||||
# → us-east4, same region as the audio-separation job that pulls it.
|
||||
echo "=== Building GPU app image (us-east4 karaoke-backend) ==="
|
||||
build -f backend/Dockerfile \
|
||||
-t "$EAST/karaoke-backend:latest" \
|
||||
-t "$EAST/karaoke-backend:$SHA" \
|
||||
-t "$EAST/karaoke-backend:v$VERSION" \
|
||||
--build-arg "BASE_IMAGE=$REG/karaoke-backend-gpu-base:latest" \
|
||||
--cache-from "type=registry,ref=$REG/karaoke-backend-gpu:cache" \
|
||||
--cache-to "type=registry,ref=$REG/karaoke-backend-gpu:cache,mode=max,ignore-error=true"
|
||||
;;
|
||||
*)
|
||||
echo "unknown target: $TARGET (expected cpu|gpu)" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "=== $TARGET images pushed ==="
|
||||
@@ -4,7 +4,10 @@ Backup to AWS Cloud Function.
|
||||
Nightly backup pipeline:
|
||||
1. Firestore export to GCS staging (nightly; uploaded to S3 weekly on Sundays)
|
||||
2. BigQuery export to GCS staging (weekly/monthly schedule)
|
||||
3. GCS job files delta sync to staging
|
||||
3. GCS delta sync of nomadkaraoke-kn-data to staging. (Job files from the
|
||||
karaoke-gen-storage bucket are NOT copied off-site any more — stopped
|
||||
2026-10-01 to save ~$15/mo egress; they rely on GCS object versioning
|
||||
+ soft-delete only. See docs/DISASTER-RECOVERY.md.)
|
||||
4. Secret Manager export (encrypted with sealed-box public key) to staging
|
||||
4b. Git repos backup — bundle repos under the configured GitHub owners to
|
||||
staging (weekly on Sundays, incremental: only repos pushed since their
|
||||
@@ -50,6 +53,7 @@ GIT_BACKUP_OWNERS = os.environ.get("GIT_BACKUP_OWNERS", "")
|
||||
|
||||
|
||||
GIT_REPOS_PREFIX = "git-repos/"
|
||||
JOB_FILES_PREFIX = "gcs/job-files/"
|
||||
|
||||
|
||||
def _run_git_repos_backup(full_refresh: bool) -> str:
|
||||
@@ -152,16 +156,11 @@ def backup_to_aws(request):
|
||||
logger.error(f"BigQuery export failed: {e}")
|
||||
errors.append(f"BigQuery: {e}")
|
||||
|
||||
# Step 3: GCS delta sync (nightly) — primary job-files bucket
|
||||
try:
|
||||
results["gcs_sync"] = sync_gcs_to_staging(
|
||||
source_bucket="karaoke-gen-storage-nomadkaraoke",
|
||||
staging_bucket=STAGING_BUCKET,
|
||||
staging_prefix="gcs/job-files/",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"GCS sync failed: {e}")
|
||||
errors.append(f"GCS sync: {e}")
|
||||
# Step 3 (removed 2026-10-01): the nightly delta sync of job files
|
||||
# (karaoke-gen-storage-nomadkaraoke -> gcs/job-files/) was the bulk of the
|
||||
# remaining cross-cloud egress (~$15/mo) for regenerable outputs. Job files
|
||||
# now rely on GCS object versioning + soft-delete only; existing S3 copies
|
||||
# under gcs/job-files/ are left in place. See docs/DISASTER-RECOVERY.md.
|
||||
|
||||
# Step 3b: GCS delta sync — nomadkaraoke-kn-data (small, irreplaceable
|
||||
# internal sync data from KaraokeNerds API; not publicly regenerable).
|
||||
@@ -211,7 +210,9 @@ def backup_to_aws(request):
|
||||
# _UPLOAD_LAG of its clone. A bundle left in staging by a failed upload
|
||||
# must not ship on a later night (a push in between would then look backed
|
||||
# up); next Sunday's git step re-bundles it fresh instead.
|
||||
exclude = []
|
||||
# gcs/job-files/ is never shipped any more (off-site job-file copy stopped
|
||||
# 2026-10-01) — also skip anything a pre-change run left in staging.
|
||||
exclude = [JOB_FILES_PREFIX]
|
||||
if not firestore_to_s3_today:
|
||||
exclude.append("firestore/")
|
||||
if not git_repos_today:
|
||||
|
||||
@@ -33,13 +33,13 @@ def _run(today):
|
||||
def test_weekday_skips_git_and_holds_back_firestore_and_git_repos():
|
||||
git, upload = _run(datetime.date(2026, 9, 29)) # Tuesday
|
||||
git.assert_not_called()
|
||||
assert set(upload.call_args.kwargs["exclude_prefixes"]) == {"firestore/", "git-repos/"}
|
||||
assert set(upload.call_args.kwargs["exclude_prefixes"]) == {"gcs/job-files/", "firestore/", "git-repos/"}
|
||||
|
||||
|
||||
def test_sunday_runs_incremental_git_and_uploads_everything():
|
||||
git, upload = _run(datetime.date(2026, 9, 27)) # Sunday, day 27
|
||||
git.assert_called_once_with(full_refresh=False)
|
||||
assert upload.call_args.kwargs["exclude_prefixes"] == []
|
||||
assert upload.call_args.kwargs["exclude_prefixes"] == ["gcs/job-files/"]
|
||||
|
||||
|
||||
def test_first_sunday_of_month_is_full_refresh():
|
||||
@@ -58,3 +58,24 @@ def test_manual_git_mode_only_uploads_git_prefix():
|
||||
git.assert_called_once_with(full_refresh=True)
|
||||
assert upload.call_args.kwargs["include_prefixes"] == ["git-repos/"]
|
||||
fs.assert_not_called()
|
||||
|
||||
|
||||
def test_job_files_bucket_is_not_synced_off_site():
|
||||
"""Job files stopped going to S3 on 2026-10-01 (egress cost cut); only the
|
||||
small kn-data bucket is still delta-synced to staging."""
|
||||
_FakeDate.today_value = datetime.date(2026, 9, 29)
|
||||
request = MagicMock()
|
||||
request.args = {}
|
||||
with patch("main.datetime.date", _FakeDate), \
|
||||
patch("main.export_firestore", return_value="fs"), \
|
||||
patch("main.export_bigquery_tables", return_value={}), \
|
||||
patch("main.sync_gcs_to_staging", return_value="gcs") as sync, \
|
||||
patch("main.export_secrets", return_value="sec") as secrets, \
|
||||
patch("main._run_git_repos_backup", return_value="git"), \
|
||||
patch("main.upload_staging_to_s3", return_value="s3"), \
|
||||
patch("main.send_alert"):
|
||||
main.backup_to_aws(request)
|
||||
sources = [c.kwargs["source_bucket"] for c in sync.call_args_list]
|
||||
assert sources == ["nomadkaraoke-kn-data"]
|
||||
assert all(c.kwargs["staging_prefix"] != "gcs/job-files/" for c in sync.call_args_list)
|
||||
secrets.assert_called_once()
|
||||
@@ -10,6 +10,70 @@ from pulumi_gcp import artifactregistry
|
||||
|
||||
from config import PROJECT_ID, REGION
|
||||
|
||||
# True = AR only *logs* what the cleanup policies would delete (Cloud Audit
|
||||
# Logs) instead of deleting. Applied in dry-run first on 2026-10-01; flip to
|
||||
# False (+ targeted pulumi up on both repos) once the dry-run logs are reviewed.
|
||||
CLEANUP_POLICY_DRY_RUN = True
|
||||
|
||||
# Tags that must never be auto-deleted regardless of age:
|
||||
# latest — what jobs/services pinned to :latest pull
|
||||
# content- — the GPU base image child manifest (content-<hash>), deliberately
|
||||
# tagged so the untagged-delete rule can't orphan it
|
||||
# cache — BuildKit registry cache manifests (cache-from/cache-to)
|
||||
PROTECTED_TAG_PREFIXES = ["latest", "content-", "cache"]
|
||||
|
||||
|
||||
def standard_cleanup_policies() -> list:
|
||||
"""Shared cleanup policy set for the Docker repos (GCP cost cut 2026-10-01).
|
||||
|
||||
KEEP rules always win over DELETE rules in Artifact Registry, so a version
|
||||
survives if it is among the 20 most recent versions of its package (≈10
|
||||
tagged deploy images, since each build also leaves a cache manifest) OR
|
||||
carries a protected tag. Everything else is deleted once older than 7 days
|
||||
(untagged digests AND old per-commit ``<sha>``/``v<version>`` tags — before
|
||||
this, tagged images were never deleted and every CI deploy accumulated).
|
||||
The currently deployed image of every Cloud Run service/job is always among
|
||||
the most recent (or is pinned to :latest), so rollback to recent revisions
|
||||
keeps working. NOTE: ``content-`` keeps a superseded GPU base child forever
|
||||
(~13 GB); after the next GPU base rebuild, delete the old
|
||||
``karaoke-backend-gpu-base:content-daa414741653`` tag by hand.
|
||||
"""
|
||||
return [
|
||||
artifactregistry.RepositoryCleanupPolicyArgs(
|
||||
id="keep-recent-20",
|
||||
action="KEEP",
|
||||
most_recent_versions=artifactregistry.RepositoryCleanupPolicyMostRecentVersionsArgs(
|
||||
# 20 versions ≈ 10 tagged deploy images: every build also leaves
|
||||
# an untagged BuildKit cache manifest in the same package.
|
||||
keep_count=20,
|
||||
),
|
||||
),
|
||||
artifactregistry.RepositoryCleanupPolicyArgs(
|
||||
id="keep-protected-tags",
|
||||
action="KEEP",
|
||||
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
|
||||
tag_state="TAGGED",
|
||||
tag_prefixes=PROTECTED_TAG_PREFIXES,
|
||||
),
|
||||
),
|
||||
artifactregistry.RepositoryCleanupPolicyArgs(
|
||||
id="delete-untagged-after-7d",
|
||||
action="DELETE",
|
||||
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
|
||||
tag_state="UNTAGGED",
|
||||
older_than="604800s", # 7 days
|
||||
),
|
||||
),
|
||||
artifactregistry.RepositoryCleanupPolicyArgs(
|
||||
id="delete-tagged-after-7d",
|
||||
action="DELETE",
|
||||
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
|
||||
tag_state="TAGGED",
|
||||
older_than="604800s", # 7 days
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def create_repository() -> artifactregistry.Repository:
|
||||
"""
|
||||
@@ -24,27 +88,8 @@ def create_repository() -> artifactregistry.Repository:
|
||||
location=REGION,
|
||||
format="DOCKER",
|
||||
description="Docker repository for karaoke backend images",
|
||||
# Cost control: keep the 10 most recent versions for rollback, and
|
||||
# delete untagged digests older than 7 days (orphaned layers left by
|
||||
# repeated :latest pushes). Tagged images are never auto-deleted.
|
||||
cleanup_policies=[
|
||||
artifactregistry.RepositoryCleanupPolicyArgs(
|
||||
id="keep-recent-10",
|
||||
action="KEEP",
|
||||
most_recent_versions=artifactregistry.RepositoryCleanupPolicyMostRecentVersionsArgs(
|
||||
keep_count=10,
|
||||
),
|
||||
),
|
||||
artifactregistry.RepositoryCleanupPolicyArgs(
|
||||
id="delete-untagged-after-7d",
|
||||
action="DELETE",
|
||||
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
|
||||
tag_state="UNTAGGED",
|
||||
older_than="604800s", # 7 days
|
||||
),
|
||||
),
|
||||
],
|
||||
cleanup_policy_dry_run=False,
|
||||
cleanup_policies=standard_cleanup_policies(),
|
||||
cleanup_policy_dry_run=CLEANUP_POLICY_DRY_RUN,
|
||||
)
|
||||
|
||||
return artifact_repo
|
||||
|
||||
@@ -2,7 +2,12 @@
|
||||
Audio Separator Cloud Run GPU Service.
|
||||
|
||||
Deploys the audio-separator API as a Cloud Run service with L4 GPU acceleration.
|
||||
Replaces the Modal deployment for audio stem separation.
|
||||
Replaced the Modal deployment for audio stem separation.
|
||||
|
||||
DISABLED BY DEFAULT since 2026-10-01 (GCP cost cut): only created when the
|
||||
Pulumi config flag ``audioSeparatorServiceEnabled`` is true. Prod jobs never
|
||||
call it (they use the audio-separation-job GPU Cloud Run Job). See
|
||||
docs/GCP-COST-OPTIMIZATION.md for the on-demand redeploy steps.
|
||||
|
||||
Resources created:
|
||||
- Artifact Registry repository for audio-separator Docker images
|
||||
@@ -139,6 +144,9 @@ def create_service(
|
||||
"audio-separator-service",
|
||||
name="audio-separator",
|
||||
location=AUDIO_SEPARATOR_REGION,
|
||||
# Off by default and only brought up on demand (see __main__.py), so
|
||||
# it must be destroyable by flipping audioSeparatorServiceEnabled off.
|
||||
deletion_protection=False,
|
||||
ingress="INGRESS_TRAFFIC_ALL",
|
||||
template=cloudrunv2.ServiceTemplateArgs(
|
||||
scaling=cloudrunv2.ServiceTemplateScalingArgs(
|
||||
|
||||
@@ -153,6 +153,17 @@ def create_lyrics_transcription_job(
|
||||
name="GCS_BUCKET_NAME",
|
||||
value=bucket.name,
|
||||
),
|
||||
# Gemini Developer API key (AI Studio; Vertex AI is
|
||||
# disabled in this project). Rotate = new secret version.
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GEMINI_API_KEY",
|
||||
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
|
||||
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
|
||||
secret=f"projects/{PROJECT_ID}/secrets/gemini-api-key",
|
||||
version="latest",
|
||||
),
|
||||
),
|
||||
),
|
||||
# Genius API token (for lyrics fetching)
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GENIUS_API_TOKEN",
|
||||
@@ -588,6 +599,17 @@ def create_video_encoding_job(
|
||||
name="DEFAULT_BRAND_PREFIX",
|
||||
value="NOMAD",
|
||||
),
|
||||
# Gemini Developer API key (AI Studio; Vertex AI is
|
||||
# disabled in this project). Rotate = new secret version.
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GEMINI_API_KEY",
|
||||
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
|
||||
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
|
||||
secret=f"projects/{PROJECT_ID}/secrets/gemini-api-key",
|
||||
version="latest",
|
||||
),
|
||||
),
|
||||
),
|
||||
# Discord webhook for release notifications
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="DEFAULT_DISCORD_WEBHOOK_URL",
|
||||
|
||||
@@ -91,6 +91,17 @@ def create_error_monitor(
|
||||
name="ENVIRONMENT",
|
||||
value="production",
|
||||
),
|
||||
# Gemini Developer API key (AI Studio; Vertex AI is
|
||||
# disabled in this project). Rotate = new secret version.
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GEMINI_API_KEY",
|
||||
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
|
||||
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
|
||||
secret=f"projects/{PROJECT_ID}/secrets/gemini-api-key",
|
||||
version="latest",
|
||||
),
|
||||
),
|
||||
),
|
||||
# Discord webhook for alert notifications
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="DISCORD_WEBHOOK_URL",
|
||||
|
||||
@@ -2,13 +2,16 @@
|
||||
Artifact Registry for GPU Docker images.
|
||||
|
||||
Located in us-east4 (co-located with L4 GPU instances).
|
||||
Stores the karaoke-backend-gpu base image used by the audio worker.
|
||||
Stores the final GPU app image (karaoke-backend) pulled by the audio-separation
|
||||
job and the CPU job image (karaoke-backend-cpu). The ~13 GB GPU *base* image
|
||||
moved to us-central1 karaoke-repo on 2026-09-27.
|
||||
"""
|
||||
|
||||
import pulumi_gcp as gcp
|
||||
from pulumi_gcp import artifactregistry
|
||||
|
||||
from config import PROJECT_ID
|
||||
from modules.artifact_registry import CLEANUP_POLICY_DRY_RUN, standard_cleanup_policies
|
||||
|
||||
GPU_REGION = "us-east4"
|
||||
|
||||
@@ -21,24 +24,7 @@ def create_gpu_artifact_repo() -> artifactregistry.Repository:
|
||||
location=GPU_REGION,
|
||||
format="DOCKER",
|
||||
description="Docker repository for GPU-enabled karaoke-backend images (audio worker)",
|
||||
# Cost control: GPU images are multi-GB. Keep 10 most recent versions
|
||||
# for rollback; delete untagged digests older than 7 days.
|
||||
cleanup_policies=[
|
||||
artifactregistry.RepositoryCleanupPolicyArgs(
|
||||
id="keep-recent-10",
|
||||
action="KEEP",
|
||||
most_recent_versions=artifactregistry.RepositoryCleanupPolicyMostRecentVersionsArgs(
|
||||
keep_count=10,
|
||||
),
|
||||
),
|
||||
artifactregistry.RepositoryCleanupPolicyArgs(
|
||||
id="delete-untagged-after-7d",
|
||||
action="DELETE",
|
||||
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
|
||||
tag_state="UNTAGGED",
|
||||
older_than="604800s", # 7 days
|
||||
),
|
||||
),
|
||||
],
|
||||
cleanup_policy_dry_run=False,
|
||||
# Cost control: GPU images are multi-GB. See standard_cleanup_policies().
|
||||
cleanup_policies=standard_cleanup_policies(),
|
||||
cleanup_policy_dry_run=CLEANUP_POLICY_DRY_RUN,
|
||||
)
|
||||
@@ -80,13 +80,9 @@ def grant_backend_permissions(
|
||||
member=service_account.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant Vertex AI User permissions (for Gemini agentic AI correction)
|
||||
bindings["vertex_ai_iam"] = gcp.projects.IAMMember(
|
||||
"karaoke-backend-vertexai-user",
|
||||
project=PROJECT_ID,
|
||||
role="roles/aiplatform.user",
|
||||
member=service_account.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
# No Vertex AI role: Gemini is called via the Gemini Developer API with the
|
||||
# `gemini-api-key` secret (read via the project-level secretAccessor role
|
||||
# above), and aiplatform.googleapis.com is disabled in this project.
|
||||
|
||||
# Grant backend service account permission to enqueue Cloud Tasks
|
||||
bindings["cloud_tasks_enqueuer"] = gcp.projects.IAMMember(
|
||||
|
||||
@@ -240,6 +240,11 @@ class AudioProcessor:
|
||||
except Exception as e:
|
||||
error_str = str(e)
|
||||
self.logger.error(f"Remote API processing failed: {error_str}")
|
||||
self.logger.error(
|
||||
"Note: Nomad Karaoke's hosted audio-separator API (Cloud Run, us-east4) "
|
||||
"was shut down on 2026-10-01 to cut costs. Unset AUDIO_SEPARATOR_API_URL "
|
||||
"to separate locally on this machine, or point it at your own deployment."
|
||||
)
|
||||
# Never fall back for API processing errors (download failures,
|
||||
# missing files, etc.) — retrying locally won't help.
|
||||
# Only fall back for transient network errors AND only when
|
||||
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user