mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 01:31:32 +09:00
36b331f3d7411ecf97c05bf15146e83161ab94de
8
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
62843f0286 |
Incident hardening: detection & guardrails (D1 + G1 shadow + D2) (#985)
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> |
||
|
|
7c03834aaf |
fix(encoding): map GCE finals by format tag, not whole filename (NOMAD-1632 720p gap) (#982)
## Problem
Validator alert: `MP4-720p: missing 1632`. This was **NOMAD-1632 — Nat
King Cole – "Portrait of Jennie"** (job `21150e73`). Only the **720p**
variant was missing; MP4 and CDG were present and correct (so recycling
the brand code would have been *wrong*).
## Root cause — filename/title substring collision
The encoder produced and uploaded the 720p to GCS correctly (`… (Final
Karaoke Lossy 720p).mp4`), but `GCEEncodingBackend.encode()` mapped the
worker's returned file list to format keys by scanning the **whole
filename**, checking `"portrait"` (to detect the 9:16 portrait video)
**before** `"720p"`. The title contains "Portrait", so the 720p matched
the portrait branch → `mp4_720p` never set → `final_video_720p=None` →
`upload_to_public_share` **silently skips** a `None` path → published to
MP4/ + CDG/ with no MP4-720p/ entry. Deterministic for **any** song
whose artist/title contains a format word ("portrait", "720p", "4k",
"lossless", "vocals", …). Only the daily validator caught it, ~24h
later.
## Fix
- **`classify_encoded_output()`** — a shared, title-collision-proof
classifier that matches the trailing **format parenthetical only** (plus
system short-names), never artist/title text. Used by both
`GCEEncodingBackend.encode()` and `redistribute_video` (same latent
bug).
- **Completeness guard** (defense-in-depth) — `encode()` now returns
`success=False` (orchestrator raises → retry + immediate alert) if the
worker returns fewer formats than requested, so *any* partial-encode
cause fails loud instead of publishing an incomplete release.
- **Portrait Video download button** in `OutputLinks` (shown when the
job has `finals.portrait_1080x1920`) — the feature shipped but had no UI
download. Added the backend download filename suffix and the
`outputLinks.portrait` string translated to all 33 locales.
- Docs: `GDRIVE-VALIDATOR.md` History entry; version bump 0.222.1 →
0.222.2.
## Live gap remediation (already done, outside this PR)
The correct 720p already existed in GCS, so it was uploaded directly to
the `MP4-720p/` public-share folder as `NOMAD-1632 - Nat King Cole -
Portrait of Jennie.mp4` (verified present; mirror backfills nightly). No
re-render, no YouTube disruption. 1632 was **not** recycled.
## Testing
- `test_encoding_interface.py` — 37 pass, incl. a NOMAD-1632
reproduction (`Portrait of Jennie` 720p → `mp4_720p`),
title-with-"720p"/"4k" leakage cases, short-name coverage, and a
completeness-guard failure test.
- `OutputLinks.test.tsx` — portrait button show/hide (frontend unit
suite: 1252 pass).
- Orchestrator (82) + change-visibility (25) suites pass.
- Full backend unit run: 4373 pass (8 failures are pre-existing
`test_emulator_integration` env failures — emulator not running locally;
unrelated to this change).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- **New Features**
- Added downloadable portrait-format video output at 1080×1920.
- Added localized “Portrait Video” labels across supported languages.
- **Bug Fixes**
- Improved output recognition so video titles containing format terms
are classified correctly.
- Prevented incomplete encoding results from being published when a
requested format is missing.
- Corrected portrait-format filenames for clearer downloads.
- **Chores**
- Updated the application version to 0.222.2.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
9d4f70a747 |
fix: clean up published outputs before job delete; admin orphaned-outputs cleanup (v0.206.0) (#952)
## Summary
Fixes the root cause of tonight's **NOMAD-1583 duplicate brand code**
incident and adds the tooling needed to clean up the orphaned files.
**Incident**: job `e97475ff` (Mazzy Star – Fade Into You) published with
NOMAD-1583 at 02:15 UTC, was deleted at 03:02 via `DELETE
/api/jobs/{id}?delete_files=true` — which recycled the brand code but
left every published output live (GDrive ×3, Dropbox folder, YouTube
video, kjbox mirror ×2). At 04:16, job `326e1aef` (Chase & Status – No
Problem) reused the recycled 1583 → duplicate in all three public share
folders, validator alerting on every subsequent job.
## Changes
- **`DELETE /api/jobs/{id}` no longer blind-recycles brand codes.** When
a job's outputs are still published, it now runs the full distribution
cleanup first (YouTube + Dropbox + GDrive + kjbox GCS mirror) via a
shared `_run_distribution_cleanup()` helper (extracted from
`cleanup-distribution`); recycle stays gated on Dropbox+GDrive success.
Incomplete cleanup aborts the delete (502) so the job record — the only
place holding the file IDs — is preserved for retry.
`delete_files=false` is rejected (400) for published jobs. Jobs whose
outputs were already deleted no longer re-recycle the code.
- **New `POST /api/admin/orphaned-outputs/cleanup`** — removes
distributed outputs by explicit IDs (YouTube video ID, Dropbox path,
GDrive file IDs, mirror filename prefix) when the owning job doc is
gone. Needed to clean up the Mazzy Star orphans.
- **`NomadMasterMirror.delete_track_objects_by_filename_prefix`** —
single-track mirror delete requiring a `NOMAD-#### - Artist...` prefix,
delimiter-bounded so it can never match the other track legitimately
holding a recycled code.
- New i18n key `jobs.deletePublishedRequiresFiles` translated to all 33
locales.
- Runbook + incident history in `docs/GDRIVE-VALIDATOR.md`.
## Testing
- 4111 backend tests pass (18 new: DELETE-route cleanup semantics, admin
endpoint, mirror prefix guardrails/delimiter bounding).
- Local CodeRabbit review: 2 cycles, all 4 findings addressed
(abort-on-incomplete-cleanup, delete_files honored, delimiter-bounded
prefix, unsafe-prefix 400).
- Post-deploy: will run the orphaned-outputs cleanup for the Mazzy Star
files and re-run the GDrive validator to confirm a clean report.
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
cd4c88ca3e |
fix(visibility): make public→private atomic; fix redistribute crash (NOMAD-1537 gap) (#917)
## Summary Investigated a `⚠️ GDrive Validation: missing NOMAD-1537` alert. Root cause was **not** a brand-code allocation race — it was a **public→private visibility change** on job `25d076e5` (`Alma Nocturna – Mejor Cállate`) that: 1. deleted the public YouTube/Dropbox/GDrive outputs and recycled `NOMAD-1537`, **then** 2. crashed the private redistribution on an illegal `complete → packaging` state transition (`redistribute_video` drove the normal orchestrator progress path on an already-`complete` job). So the flow was **delete-first with no rollback**: public files gone, private archive never created. The gap self-closed when an unrelated public job (`Luvcat – Spider`) reused the recycled number. The customer track was fine (GCS-backed downloads intact + correctly private), but every public→private conversion was silently failing its private-side archive, and each leaked a `NOMADNP` code. ## Changes - **A — fix the crash:** `OrchestratorConfig.redistribute_mode`; `_update_progress` updates progress only and skips status transitions when redistributing a `complete` job. `redistribute_video` sets it. - **B — distribute-then-delete:** `change_to_private` captures the public refs, redistributes to the private destination first, and only on success deletes the public outputs + recycles the public number. On redistribution failure it reverts to public — nothing deleted (YouTube deletion is irreversible, so it must be last). - **C — no leaked codes:** a redistribution that fails after allocating a `NOMADNP` code recycles it. - **Hardening (from local CodeRabbit review):** `redistribute_video` verifies the archive actually materialized (brand code + Dropbox upload) before reporting success — the orchestrator swallows those failures as warnings; the public number is recycled only when every public deletion succeeded; revert-to-public happens only pre-deletion. **Validator intentionally unchanged.** Going-private is a rare, legitimate cause of a transient gap that the next public track refills; the owner wants to keep receiving that warning. ## Testing - New/updated unit tests: distribute-then-delete ordering, real rollback (no public deletion + revert on failure), `redistribute_mode` skips status transition, public/private brand-code recycle, recycle-gating on incomplete cleanup. - Green: `test_change_visibility.py`, `test_video_worker_orchestrator.py`, `test_brand_code_service.py`, `test_private_tracks.py`, `test_cleanup_distribution.py`, `test_admin_delete_outputs.py` (326 tests). ## Follow-up (post-merge, operational) - Recover job `25d076e5`: re-run `redistribute_video('25d076e5')` (GCS finals intact) to create its NonPublished archive + `NOMADNP` code. - Recycle the leaked `NOMADNP-0214`. Full analysis + plan: `docs/archive/2026-08-18-visibility-change-recycle-dataloss-plan.md`. @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
a45798bb4d |
fix: remove SendGrid leftovers; consolidate on Postmark (#779)
## Summary - Fixes the failing e2e-daily notification job ([run #25983930960](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/25983930960/job/76378786060)) which still used \`smtp.sendgrid.net\` — SendGrid was cancelled ~3 weeks ago - Drops the \`sendgrid\` Python dep, removes \`SendGridEmailProvider\`, simplifies provider selection in \`email_service.py\` - Removes \`SENDGRID_API_KEY\` env bindings from Pulumi (gdrive-validator Cloud Function + video Cloud Run Job) and from ci.yml's Cloud Run \`--set-secrets\` - \`sendgrid-api-key\` Secret resource intentionally kept in \`infrastructure/modules/secrets.py\` with a "delete manually" marker so an unrelated \`pulumi up\` doesn't destroy the live secret + versions - Version bumped 0.174.10 → 0.174.11 ## Pulumi applied \`pulumi up --target\` already run locally with the two affected resources (video-encoding-job + gdrive-validator-function). PR #776's runner-manager state intentionally untouched. @coderabbitai ignore ## Test plan - [x] Full backend test suite (3178 tests) passes locally - [x] CodeRabbit local review: no findings - [x] Pulumi up applied locally (clean) - [ ] CI green on this PR - [ ] After merge: e2e-daily.yml notification job should pass on next scheduled run - [ ] Verify gdrive-validator function still emails on next post-job trigger 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
8694099073 |
docs: Add sequence gap investigation runbook (#500)
## Summary - Replaced "False Positive Gaps" section (which advised adding to KNOWN_GAPS) with a full **Sequence Gap Detected** investigation runbook in `docs/GDRIVE-VALIDATOR.md` - Added quick reference section in `docs/TROUBLESHOOTING.md` - Clarified KNOWN_GAPS is historical only (pre-generator era) — new gaps are always bugs - Added NOMAD-1295 incident to history ## Context NOMAD-1295 gap was caused by a job re-trigger (stale GCE cache fix) allocating a new brand code without recycling the old one. Recycled the brand code in Firestore so the next public job fills the gap. ## Test plan - [x] Documentation-only change, no code logic affected - [x] Comment added to `main.py` KNOWN_GAPS is informational only @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
324b7a3240 |
fix: guided flow private mode + delayed GDrive validation (#443)
## Summary Two fixes for the NOMAD-1276 incident where the GDrive validator reported "no issues" while NOMAD-1276 was actually missing: - **Fix 1: Private mode in guided flow** — The `is_private` checkbox in Step 3 (Customize) had no effect because the job was created in Step 2 with `is_private=false`. Now the select endpoint accepts optional overrides (`is_private`, `display_artist`, `display_title`) and applies them before the pipeline starts. - **Fix 2: Delayed GDrive validation** — Post-job validator fired immediately after upload, before E2E test cleanup could delete test files, causing false "all clear" reports. Now uses Cloud Tasks with a 5-minute delay, with fallback to immediate trigger if scheduling fails. Also includes cross-folder gap detection improvements in the Cloud Function (uses global max across all folders instead of per-folder max). ## Changes ### Backend - `AudioSelectRequest` model accepts optional `is_private`, `display_artist`, `display_title` overrides - New `/internal/trigger-gdrive-validation` endpoint for delayed Cloud Tasks invocation - `WorkerService.schedule_gdrive_validation()` method with 5-minute delay - Orchestrator uses delayed scheduling with immediate fallback ### Frontend - `selectAudioResult()` passes overrides from Step 3 state - E2E test verifies overrides reach the backend ### Infrastructure - New `gdrive-validation-queue` Cloud Tasks queue (Pulumi) - Cloud Function cross-folder gap detection fix + 28 unit tests ## Test plan - [x] 19 new backend tests (6 select overrides + 13 delayed validation) - [x] 2 new frontend API tests for override behavior - [x] 28 new Cloud Function unit tests - [x] Updated E2E test to verify overrides reach backend - [x] Full backend suite: 2139 passed - [x] Full frontend suite: 485 passed - [x] CodeRabbit: no findings <!-- @coderabbitai ignore --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
e0c8645fea |
Add email alerts, manual trigger, and post-job check to GDrive validator (#419)
@coderabbitai ignore ## Summary - **Email notifications via SendGrid** — replaces Pushbullet as the primary notification channel for the GDrive validator cloud function. Pushbullet kept as secondary fallback. - **Post-job trigger** — the backend orchestrator now triggers GDrive validation after each job that uploads to the public share, catching duplicates within minutes instead of up to 24 hours. - **Manual CLI** — `python scripts/check_public_share.py` for on-demand validation checks with formatted output and `--json` flag. - **Comprehensive docs** — `docs/GDRIVE-VALIDATOR.md` with architecture, configuration, troubleshooting, and operational reference. Motivated by the NOMAD-1271 duplicate brand code incident where daily-only checks left a duplicate undetected for ~24 hours. ## Changes | File | Change | |------|--------| | `infrastructure/functions/gdrive_validator/main.py` | Add `send_email_notification()` via SendGrid, unified `send_notification()` sends both email + Pushbullet | | `infrastructure/functions/gdrive_validator/requirements.txt` | Add `sendgrid>=6.0.0` | | `infrastructure/functions/gdrive_validator/deploy.sh` | Add SendGrid secret + email env vars | | `infrastructure/__main__.py` | Add SendGrid secret to function, backend SA invoker IAM (Cloud Functions + Cloud Run) | | `infrastructure/modules/secrets.py` | Add `gdrive-validator-url` secret | | `.github/workflows/ci.yml` | Add `GDRIVE_VALIDATOR_URL` to Cloud Run deploy secrets | | `backend/services/gdrive_validator_client.py` | **New**: HTTP client with OIDC auth, fire-and-forget pattern | | `backend/workers/video_worker_orchestrator.py` | Add Stage 6: post-distribution GDrive validation (only when `gdrive_folder_id` set) | | `scripts/check_public_share.py` | **New**: CLI tool for manual validation checks | | `docs/GDRIVE-VALIDATOR.md` | **New**: Comprehensive validator documentation | | `pyproject.toml` | Version bump to 0.119.9 | ## Already deployed - Pulumi infrastructure applied (IAM bindings, secrets, function config) - Cloud Function redeployed with SendGrid support - `gdrive-validator-url` secret set in Secret Manager - Tested via `check_public_share.py` — validated 3,608 files, email sent successfully ## Test plan - [x] `make test` — 170 passed, 3 skipped (1 pre-existing failure in credit-enforcement unrelated to this PR) - [x] `pulumi preview` — clean, 3 creates + 1 update - [x] `pulumi up` — applied successfully - [x] Cloud Function deployed and tested end-to-end - [x] `python scripts/check_public_share.py` — formatted output works - [x] `python scripts/check_public_share.py --json` — JSON output works - [x] Email received at gen@nomadkaraoke.com (notification_sent: true) - [ ] Post-job trigger: will verify on next job completion (backend needs redeploy via CI merge) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |