Files
karaoke-gen/backend/tests/test_nomad_master_mirror.py
T
Andrew Beveridge ☄️andClaude Fable 5 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>
2026-08-29 01:16:47 -04:00

298 lines
11 KiB
Python

"""Unit tests for the Nomad master fast-sync mirror (Phase 1)."""
from unittest.mock import MagicMock
import pytest
from google.cloud.exceptions import NotFound
from backend.services.nomad_master_mirror import (
NomadMasterMirror,
is_nomad_public_brand,
)
@pytest.mark.parametrize(
"brand_code, expected",
[
("NOMAD-1500", True),
("NOMAD-0001", True),
("NOMAD-1500", True),
("NOMADNP-1234", False), # private tracks must never enter the public mirror
("nomadnp-1", False),
("TRACK-0000", False),
("VOCALSTAR-12", False),
("", False),
(None, False),
],
)
def test_is_nomad_public_brand(brand_code, expected):
assert is_nomad_public_brand(brand_code) is expected
def _mirror_with_mock():
"""NomadMasterMirror wired to a mock GCS client; returns (mirror, blob)."""
blob = MagicMock()
bucket = MagicMock()
bucket.blob.return_value = blob
client = MagicMock()
client.bucket.return_value = bucket
mirror = NomadMasterMirror(client=client)
return mirror, bucket, blob
def test_push_720p_uses_exact_divebar_object_name_and_uploads():
mirror, bucket, blob = _mirror_with_mock()
ok = mirror.push_720p(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.mp4",
"NOMAD-1500 - Rush - The Spirit of Radio.mp4",
)
assert ok is True
# Object name MUST match the nightly VM's layout exactly (idempotency).
bucket.blob.assert_called_once_with(
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
)
blob.upload_from_filename.assert_called_once_with(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
)
def test_push_720p_is_non_fatal_on_error():
mirror, _bucket, blob = _mirror_with_mock()
blob.upload_from_filename.side_effect = RuntimeError("boom")
# Must not raise; returns False so the pipeline continues.
assert mirror.push_720p("/tmp/x.mp4", "NOMAD-1 - A - B.mp4") is False
def test_delete_720p_removes_blob():
mirror, bucket, blob = _mirror_with_mock()
assert mirror.delete_720p("NOMAD-1500 - Rush - The Spirit of Radio.mp4") is True
bucket.blob.assert_called_once_with(
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
)
blob.delete.assert_called_once()
def test_delete_720p_missing_is_noop():
mirror, _bucket, blob = _mirror_with_mock()
blob.delete.side_effect = NotFound("gone")
assert mirror.delete_720p("NOMAD-9 - X - Y.mp4") is False
def test_delete_720p_is_non_fatal_on_error():
mirror, _bucket, blob = _mirror_with_mock()
blob.delete.side_effect = RuntimeError("boom")
assert mirror.delete_720p("NOMAD-9 - X - Y.mp4") is False
# --- delete_masters_by_brand (prefix delete; covers renames) ---
def _mirror_with_blobs(names):
blobs = []
for n in names:
b = MagicMock()
b.name = n
blobs.append(b)
bucket = MagicMock()
bucket.list_blobs.return_value = blobs
client = MagicMock()
client.bucket.return_value = bucket
return NomadMasterMirror(client=client), bucket, blobs
def test_delete_masters_by_brand_deletes_all_matching_by_prefix():
# Two objects for the same release (e.g. an old + renamed title) both go.
mirror, bucket, blobs = _mirror_with_blobs([
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - Spirit of Radio.mp4",
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4",
])
n = mirror.delete_masters_by_brand("NOMAD-1500")
assert n == 2
bucket.list_blobs.assert_called_once_with(
prefix="files/Nomad Karaoke/MP4-720p/NOMAD-1500 - "
)
for b in blobs:
b.delete.assert_called_once()
@pytest.mark.parametrize("brand", ["NOMADNP-1500", "VOCALSTAR-1", "", None, "NOMAD"])
def test_delete_masters_by_brand_refuses_non_nomad_or_bare(brand):
# Must never list/delete for a non-Nomad or bare brand — a broad prefix could
# wipe unrelated objects.
mirror, bucket, _blobs = _mirror_with_blobs([])
assert mirror.delete_masters_by_brand(brand) == 0
bucket.list_blobs.assert_not_called()
def test_delete_masters_by_brand_is_non_fatal_on_list_error():
mirror, bucket, _blobs = _mirror_with_blobs([])
bucket.list_blobs.side_effect = RuntimeError("gcs down")
assert mirror.delete_masters_by_brand("NOMAD-1500") == 0
# --- vocals guide push / delete (parallel to the master methods) ---
def test_push_vocals_guide_uses_vocals_prefix_and_uploads():
mirror, bucket, blob = _mirror_with_mock()
ok = mirror.push_vocals_guide(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.flac",
"NOMAD-1500 - Rush - The Spirit of Radio.flac",
)
assert ok is True
bucket.blob.assert_called_once_with(
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - The Spirit of Radio.flac"
)
blob.upload_from_filename.assert_called_once_with(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.flac"
)
def test_push_vocals_guide_is_non_fatal_on_error():
mirror, _bucket, blob = _mirror_with_mock()
blob.upload_from_filename.side_effect = RuntimeError("boom")
assert mirror.push_vocals_guide("/tmp/x.flac", "NOMAD-1 - A - B.flac") is False
def test_delete_vocals_guides_by_brand_deletes_all_matching_by_prefix():
mirror, bucket, blobs = _mirror_with_blobs([
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - Spirit of Radio.flac",
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - The Spirit of Radio.flac",
])
n = mirror.delete_vocals_guides_by_brand("NOMAD-1500")
assert n == 2
bucket.list_blobs.assert_called_once_with(
prefix="files/Nomad Karaoke/vocals-padded/NOMAD-1500 - "
)
for b in blobs:
b.delete.assert_called_once()
@pytest.mark.parametrize("brand", ["NOMADNP-1500", "VOCALSTAR-1", "", None, "NOMAD"])
def test_delete_vocals_guides_by_brand_refuses_non_nomad_or_bare(brand):
mirror, bucket, _blobs = _mirror_with_blobs([])
assert mirror.delete_vocals_guides_by_brand(brand) == 0
bucket.list_blobs.assert_not_called()
def test_delete_vocals_guides_by_brand_is_non_fatal_on_list_error():
mirror, bucket, _blobs = _mirror_with_blobs([])
bucket.list_blobs.side_effect = RuntimeError("gcs down")
assert mirror.delete_vocals_guides_by_brand("NOMAD-1500") == 0
def test_cleanup_nomad_masters_delegates_for_nomad(monkeypatch):
from backend.services import nomad_master_mirror as mod
inst = MagicMock()
inst.delete_masters_by_brand.return_value = 3
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: inst)
assert mod.cleanup_nomad_masters("NOMAD-1500") == 3
inst.delete_masters_by_brand.assert_called_once_with("NOMAD-1500")
# Brand recycle must also clear the release's original-vocals guide(s).
inst.delete_vocals_guides_by_brand.assert_called_once_with("NOMAD-1500")
@pytest.mark.parametrize("brand", ["NOMADNP-1", "OTHER-1", "", None])
def test_cleanup_nomad_masters_noop_for_non_nomad(brand, monkeypatch):
from backend.services import nomad_master_mirror as mod
# Must not even construct the mirror (no GCS client) for non-Nomad brands.
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: (_ for _ in ()).throw(AssertionError("should not construct")))
assert mod.cleanup_nomad_masters(brand) == 0
# --- delete_track_objects_by_filename_prefix (single-track orphan cleanup) ---
def _blob(name):
b = MagicMock()
b.name = name
return b
def _mirror_with_blobs_per_prefix(blobs_by_prefix):
"""Mirror whose bucket.list_blobs returns blobs matching the requested prefix,
like real GCS (the shared-list shortcut breaks delimiter-bound tests)."""
bucket = MagicMock()
def list_blobs(prefix):
return [b for b in blobs_by_prefix if b.name.startswith(prefix)]
bucket.list_blobs.side_effect = list_blobs
client = MagicMock()
client.bucket.return_value = bucket
return NomadMasterMirror(client=client), bucket
def test_delete_track_objects_by_filename_prefix_deletes_from_both_prefixes():
# One master + one vocals guide for the orphaned track; both must go.
master = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
guide = _blob("files/Nomad Karaoke/vocals-padded/NOMAD-1583 - Mazzy Star - Fade Into You.flac")
mirror, bucket = _mirror_with_blobs_per_prefix([master, guide])
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 1}
prefixes = [c.kwargs.get("prefix") or c.args[0] for c in bucket.list_blobs.call_args_list]
assert prefixes == [
"files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star",
"files/Nomad Karaoke/vocals-padded/NOMAD-1583 - Mazzy Star",
]
master.delete.assert_called_once()
guide.delete.assert_called_once()
def test_delete_track_objects_by_filename_prefix_is_delimiter_bounded():
# "NOMAD-1583 - Mazzy Star" must NOT match a different track by a longer-named
# artist that happens to share the recycled brand code and the string prefix.
orphan = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
other = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Starlight - Other Song.mp4")
mirror, _bucket = _mirror_with_blobs_per_prefix([orphan, other])
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 0}
orphan.delete.assert_called_once()
other.delete.assert_not_called()
def test_delete_track_objects_full_stem_matches_extension_boundary():
# A full "brand - artist - title" stem must still match its own files (".mp4").
master = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
mirror, _bucket = _mirror_with_blobs_per_prefix([master])
counts = mirror.delete_track_objects_by_filename_prefix(
"NOMAD-1583 - Mazzy Star - Fade Into You"
)
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 0}
master.delete.assert_called_once()
@pytest.mark.parametrize("prefix", [
"NOMAD-1583", # bare brand code — would match BOTH tracks sharing it
"NOMAD-1583 - ", # brand code + separator but no artist text
"NOMADNP-0001 - X", # private prefix
"Mazzy Star", # no brand code
"",
None,
])
def test_delete_track_objects_by_filename_prefix_refuses_unsafe_prefixes(prefix):
mirror, bucket, _blobs = _mirror_with_blobs([])
with pytest.raises(ValueError):
mirror.delete_track_objects_by_filename_prefix(prefix)
bucket.list_blobs.assert_not_called()
def test_delete_track_objects_by_filename_prefix_non_fatal_on_list_error():
mirror, bucket, _blobs = _mirror_with_blobs([])
bucket.list_blobs.side_effect = RuntimeError("gcs down")
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
assert counts == {"masters_deleted": 0, "vocals_guides_deleted": 0}