Part 1 of 3 of the **Incident hardening (post-NOMAD-1632)** initiative (plan: `docs/archive/2026-09-12-incident-hardening-plan.md`, shipped in #984). Follow-up hardening for the incident class — a silent partial publish caught ~24h late, then its fix over-firing and failing real jobs, caught only when a human saw the UI. This PR bundles the three **detection & guardrail** items (the other two PRs cover test-seam/contract/process and deploy/CI/runner robustness). ## D1 — near-real-time alert on ANY job failure The production error monitor is **spike-based** and mathematically blind to a novel low-volume error (`rolling_avg == 0` → never a spike) — exactly why the 2-job guard-over-fire outage went unnoticed. New `backend/services/ops_alerts.py` hooks the single status-write chokepoint (`FirestoreService.update_job_status`) on any transition to `FAILED` and sends an immediate Discord alert to the ops channel, de-duped by a normalized error signature (reuses the error-monitor normalizer). **Novel signatures always alert regardless of count.** - Best-effort: fully wrapped, **never raises** into the status write. - Gated to deployed environments (`is_production`/`FAILURE_ALERTS_ENABLED`); skips `test`/`development` jobs. - Throttle window collapses a burst of the same signature into one alert (configurable). ## G1 — publish-boundary completeness invariant, SHADOW-first New `backend/services/publish_completeness.py` computes the outputs a public GDrive release *should* have shipped (lossy 4K + 720p, CDG when enabled) and compares against what was actually distributed (`gdrive_files`). The orchestrator logs + alerts any shortfall at the end of `_run_distribution` **without failing the job** (shadow mode). Closes the residual silent-partial hole the original encode()-boundary fix leaves open (a `None` slot arising *after* `encode()` — e.g. a per-file download failure — still publishes a partial today), at the right altitude. ## D2 — same-day silent-partial detection The post-job trigger now carries the just-published `brand_code` through (orchestrator → Cloud Tasks → internal endpoint → Cloud Function → validator). The validator verifies that track is present in all expected folders **same-run**, independent of the global-max gap logic (which only notices a missing latest track once a *later* track raises the max). Surfaces as a `missing_for_track` issue ~5 min post-job instead of up to 24h later. `brand_code` is optional; absent → full-scan behaviour as before. ## Tests - `backend/tests/test_ops_alerts.py` — novelty, throttle/collapse, skip-env, fail-open, best-effort-never-raises. - `backend/tests/test_publish_completeness.py` — incl. the exact 720p-missing (NOMAD-1632) case. - `infrastructure/functions/gdrive_validator/test_main.py` — `check_track_completeness` incl. the 720p-missing case + prefix-not-substring. - `backend/tests/test_services.py::TestFirestoreService` — FAILED fires the alert, non-FAILED doesn't, alerter error never breaks the status write. All new + touched-area tests pass locally (`test_ops_alerts`, `test_publish_completeness`, `test_gdrive_validation_delay`, `test_video_worker_orchestrator`, validator suite, `TestFirestoreService`). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added targeted validation confirming published tracks appear in required Google Drive folders. * Added conditional CDG checks based on whether a CDG package was produced. * Added near-real-time job-failure alerts with duplicate suppression and retry eligibility after delivery failures. * Added completeness checks for public releases, including missing video and CDG outputs. * Added highlighted partial-publish notifications when track files are missing. * **Bug Fixes** * Prevented alert content from triggering Discord mentions. * **Documentation** * Documented targeted validation and failure-alerting lessons. * **Chores** * Updated the project version to 0.223.2. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Infrastructure as Code with Pulumi
This directory contains Pulumi infrastructure code that manages all Google Cloud Platform resources for the karaoke generator backend.
Directory Structure
infrastructure/
├── __main__.py # Entry point - wires modules together (~340 lines)
├── config.py # Centralized configuration constants
├── Pulumi.yaml # Pulumi project config
├── Pulumi.prod.yaml # Production stack config
├── requirements.txt # Python dependencies
│
├── modules/ # Core GCP resources
│ ├── database.py # Firestore database + indexes
│ ├── storage.py # GCS bucket + lifecycle rules
│ ├── artifact_registry.py # Docker repository
│ ├── secrets.py # Secret Manager secrets
│ ├── cloud_tasks.py # Task queues
│ ├── cloud_run.py # Domain mapping, Cloud Run Jobs
│ ├── monitoring.py # Alert policies
│ └── iam/ # IAM by purpose
│ ├── backend_sa.py # karaoke-backend service account
│ ├── github_actions_sa.py # WIF + deployer permissions
│ ├── claude_automation_sa.py # Claude Code automation
│ └── worker_sas.py # VM service accounts
│
├── compute/ # VM-based resources
│ ├── flacfetch_vm.py # Audio download service
│ ├── encoding_worker_vm.py # Video encoding VM
│ ├── github_runners.py # Self-hosted CI runners
│ └── startup_scripts/ # VM startup scripts (.sh)
│ ├── flacfetch.sh
│ ├── encoding_worker.sh
│ └── github_runner.sh
│
├── functions/ # Cloud Functions
│ └── gdrive_validator/
│ ├── main.py
│ ├── requirements.txt
│ └── deploy.sh # Source upload script
│
└── monitoring/ # Monitoring configs
├── dashboard.json
└── job-inspector.html
Resources Managed
| Category | Resources |
|---|---|
| Database | Firestore (Native mode), 10 indexes, TTL policy |
| Storage | GCS bucket with lifecycle rules |
| Registry | Artifact Registry for Docker images |
| Secrets | 18 Secret Manager secrets |
| IAM | 7 service accounts, WIF, 50+ IAM bindings |
| Compute | Encoding worker, Flacfetch, 10 GitHub runners |
| Tasks | 5 Cloud Tasks queues |
| Monitoring | 4 alert policies |
| Functions | GDrive validator + scheduler |
Quick Start
cd infrastructure
# Preview changes
pulumi preview --diff
# Apply changes
pulumi up
# View outputs
pulumi stack output
Prerequisites
- Pulumi CLI:
brew install pulumi - Pulumi Account: Sign up at https://app.pulumi.com
- Google Cloud SDK: With authenticated account
- Python 3.10+: For running Pulumi
Module Guide
config.py
Centralized configuration for the entire infrastructure:
- Project ID, region, zone
- Machine types and disk sizes
- Google Drive folder ID
- Number of GitHub runners
modules/database.py
Firestore database and composite indexes. Indexes are required for queries that filter/order by multiple fields.
modules/storage.py
GCS bucket with lifecycle rules:
- 7-day cleanup of staging data
- 24-hour cleanup of raw audio files
modules/iam/
Service accounts organized by purpose:
backend_sa.py: Cloud Run backend permissionsgithub_actions_sa.py: CI/CD via Workload Identity Federationworker_sas.py: VM service accounts (flacfetch, encoding, runners)
compute/
VM definitions with startup scripts as separate files. Each module creates:
- Static IP (where needed)
- VM instance
- Firewall rules
Adding Secret Values
After pulumi up, add actual secret values:
# API keys
echo -n "key" | gcloud secrets versions add audioshake-api-key --data-file=-
echo -n "key" | gcloud secrets versions add genius-api-key --data-file=-
# Private tracker credentials
echo -n "key" | gcloud secrets versions add red-api-key --data-file=-
echo -n "url" | gcloud secrets versions add red-api-url --data-file=-
# GitHub runner PAT (admin:org scope for org-level runners)
echo -n "ghp_xxx" | gcloud secrets versions add github-runner-pat --data-file=-
GDrive Validator
The Cloud Function validates your public Google Drive folder daily:
- Checks for duplicate sequence numbers
- Validates filename formats
- Detects sequence gaps
- Sends Pushbullet notifications
Deploy:
cd functions/gdrive_validator
./deploy.sh
Note: deploy.sh uploads the source ZIP to GCS. Pulumi creates the function resources but doesn't handle source upload.
Self-Hosted GitHub Runners
20 GCP VMs serve as organization-level self-hosted runners, available to all repos in the nomadkaraoke org:
- 200GB SSD (vs 14GB on GitHub-hosted)
- Pre-installed: Docker, Python 3.13, Node 20, Java 21, FFmpeg
- Labels:
self-hosted,linux,x64,gcp,large-disk
PAT Requirements: The github-runner-pat secret requires admin:org scope (specifically manage_runners:org) for organization-level runner registration.
Usage in workflows (any nomadkaraoke repo):
runs-on: [self-hosted, linux, gcp]
Troubleshooting:
# View startup logs
gcloud compute ssh github-runner-1 --zone=us-central1-a -- \
"sudo cat /var/log/github-runner-startup.log"
# Check runner service
gcloud compute ssh github-runner-1 --zone=us-central1-a -- \
"sudo systemctl status actions.runner.*"
Encoding Worker
High-performance VM for video encoding:
- Machine: c4-standard-8 (8 vCPU, 32GB RAM)
- Disk: 100GB hyperdisk-balanced
- Pre-installed: FFmpeg (static build), Python 3.13, Noto fonts
API Endpoints:
POST /encode- Full encoding jobPOST /encode-preview- Quick 480p previewGET /status/{job_id}- Job statusGET /health- Health check
Troubleshooting:
gcloud compute ssh encoding-worker --zone=us-central1-c -- \
"sudo systemctl status encoding-worker"
State Management
Pulumi state is stored in Pulumi Cloud. To sync with actual cloud resources:
pulumi refresh
Multi-Environment
pulumi stack init dev
pulumi config set gcp:project nomadkaraoke-dev
pulumi up
pulumi stack select prod # Switch stacks
Troubleshooting
"Resource already exists"
Import manually-created resources:
pulumi import gcp:storage/bucket:Bucket karaoke-storage karaoke-gen-storage-nomadkaraoke
State conflicts
pulumi refresh # Sync state with cloud
Permissions errors
Ensure your gcloud account has Owner or Editor role, or specific roles like Cloud Build Editor, Storage Admin.
Future Improvements
Phase 5: Custom Machine Images (Planned)
The encoding worker currently takes ~10 minutes to start because it builds Python 3.13 from source on every boot. A Packer-built custom image would reduce this to ~30 seconds.
See: docs/PHASE5-PACKER-IMAGE-PLAN.md for the implementation plan.
Benefits:
- Startup time: 10 min → 30 sec
- Pre-baked: Python 3.13, FFmpeg, fonts
- Hot updates: karaoke-gen wheel still downloaded at runtime