Compare commits

..
5 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 5.5 2db5407a5d feat: archive deleted jobs (doc + logs) instead of losing them (v0.295.0) (#1261)
## Why
When NOMAD-1875 was deleted (2026-11-09), its Firestore record and logs
were gone for good, so we couldn't use them to debug the delete-outputs
result afterwards. Andrew's call: job records are **system data**. Keep
them forever, and on account deletion redact the user's identity rather
than deleting the record.

## What
- `FirestoreService.archive_job()` copies `jobs/{id}` to
`jobs_archive/{id}`, adding `archived_at`, `archived_by` and
`archive_reason`. It also copies the `logs` subcollection to
`archived_logs` without `ttl_expiry` (the TTL policy is on the `logs`
collection group, so otherwise they'd expire after 30 days), and the
`audio_edit_sessions` subcollection.
- `JobManager.delete_job()` archives first and **aborts the delete if
the archive fails**.
- Callers pass who deleted the job and why: `admin_delete` /
`owner_delete` from `DELETE /api/jobs/{id}`, and
`cleanup_distribution_delete`.
- **Account deletion** now also redacts archived jobs: owner/customer
email becomes `deleted:<uuid>`, and IPs, notes and contact fields are
removed. These are single-field queries, so no new composite index is
needed. Archived jobs are never deleted.
- Bulk test cleanup (`delete_jobs_by_filter`) still hard-deletes.
- `scripts/get_job.py` falls back to the archive. Documented in
`docs/ARCHITECTURE.md`.

No infra change: Firestore creates the collection on first write, and no
TTL policy is set because archived jobs are kept forever.

## Testing
- Unit: archive happens before delete; the delete is aborted when the
archive fails; archived jobs are redacted on account deletion (including
made-for-you customer jobs).
- Emulator: `backend/tests/emulator/test_job_archive_emulator.py` checks
the doc, logs (no `ttl_expiry`) and audio-edit sessions are copied, and
that a missing job returns False.
- `test_account_deletion`, `test_job_manager`, `test_jobs_api`,
`test_services`, `test_api_integration`: 195 passed.
- Local CodeRabbit: no findings.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_012RYLVUwKapcjF8czVQrPD5

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 12:06:51 -05:00
Andrew Beveridge ☄️andClaude Opus 5.5 47c6691823 fix(admin): delete-outputs dialog shows success as green; YouTube 404 = already deleted (v0.294.3) (#1260)
## Summary
When Andrew deleted NOMAD-1875's outputs (2026-11-09), the result dialog
showed **YouTube, Dropbox and Google Drive all red** ("Partial
Success"). In reality:
- **Dropbox and Drive were deleted fine.** The backend logged `Dropbox:
success, GDrive: success`, and the brand code was recycled, which only
happens when both succeed. The dialog only treats `"deleted"` as green,
but the shared cleanup helpers (`published_outputs_cleanup.py`) return
`"success"`. The regression E2E mocks also used `"deleted"`, which is
why they never caught it.
- **The YouTube video was already gone.** The API returned 404 and
yt-dlp says "removed by the uploader", so it was removed outside gen.
The delete reported this as `failed`, with no message in the dialog.

## Changes
- `frontend/app/admin/jobs/page.tsx`: green for `success`.
`failed`/`partial` now show a reason, and a partial Drive delete lists
the files left behind ("Not deleted: cdg").
- `KaraokeFinalise.delete_youtube_video`: an HTTP 404 counts as already
deleted (warning log, returns True). Other errors (e.g. 403) still fail.
- `frontend/e2e/regression/admin-job-detail.spec.ts`: mocks now use the
real backend statuses, plus a partial-Drive assertion.
- Version 0.294.3.

## Testing
- `tests/unit/test_karaoke_finalise/test_youtube_integration.py -k
delete`: 6 passed (2 new: 404 = success, 403 = still a failure).
- Playwright regression spec: left to CI, since frontend deps aren't
installed in this worktree.
- Local CodeRabbit: 1 minor finding (show per-file Drive outcomes),
fixed.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_012RYLVUwKapcjF8czVQrPD5

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 11:57:38 -05:00
Andrew Beveridge ☄️andClaude Opus 5.5 d59b5bf3bd fix(gdrive-validator): don't report gaps for tracks still uploading (#1259)
## Summary
On 2026-11-07 the validator emailed **"SEQUENCE GAPS: CDG missing 1872,
MP4-720p missing 1872"**. That was a false alarm, caused by a race:

- NOMAD-1871 completed at 12:20:23 UTC. Its delayed post-job check ran
at **12:24:47**.
- NOMAD-1872 was in `packaging` from 12:23:39 to 12:25:40. Its 4K MP4
was already in Drive, but the 720p MP4 and the CDG were not.
- The global-max gap logic saw 1872 in MP4 but not in the other two
folders. All three files (`gdrive_files` in Firestore) landed about a
minute later, and the later post-job runs (12:29 and 12:36) found no
issues.

## Change
- `list_folder_contents` can now also collect each file's Drive
`createdTime`.
- New helper `recently_uploaded_sequences()`: a track with any file
created within `IN_FLIGHT_GRACE_MINUTES` (default 30) counts as still
uploading, and `validate_files(..., in_flight=...)` leaves it out of the
gap check.
- These tracks are still covered by their own post-job trigger (the
targeted `brand_code` completeness check, which this change doesn't
touch) and by the daily 9 PM run.
- Docs: `docs/GDRIVE-VALIDATOR.md` (new env var, plus a note on the race
in the gap runbook).

## Testing
- `infrastructure/functions/gdrive_validator/test_main.py`: 40 passed. 3
new tests cover a track still uploading, an old missing track (still
reported), and bad timestamps.
- `backend/tests/test_gdrive_validation_delay.py`: 13 passed.
- Local CodeRabbit review: 2 minor findings, both fixed (env var parse
fallback, offset-less timestamps).

## Deploy
This only affects the Cloud Function, so no backend version bump.
Deploying it takes
`infrastructure/functions/gdrive_validator/deploy.sh`, which needs
`/gcp-admin`.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_012RYLVUwKapcjF8czVQrPD5

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:23:25 -05:00
Andrew Beveridge ☄️andClaude Opus 5.5 bb01e9e36a feat(kn-data-sync): live Spotify songs in the song-id export (v0.294.2) (#1258)
## Summary
Companion to the karaoke-decide PR that keeps every live Spotify search
result forever (`karaoke_decide.spotify_live_tracks`). With this change,
those songs join the daily **song-id export**, which feeds:
- the kjbox on-device matcher (`song_id.db`);
- decide's song-search service;
- the mobile app's offline index.

So a song we look up once, like "Cole Phillips – Roll of Dice" (a 2025
release missing from the July 2025 Spotify snapshot and from
MusicBrainz), is known everywhere from the next build on, with no
Spotify or Gemini call.

## Changes
- `kn_data_sync/main.py`: `SPOTIFY_LIVE_UNION` is appended to
`SONG_ID_SQL` when the table exists. Before decide's first live search
creates it, the union is skipped with an INFO log.
  - Grouped by lowercased artist/title.
- Popularity uses the D5a estimate: 0.8 × the artist's popularity (via
`art`), capped at 50, else 30. The API no longer returns track
popularity.
- Docs: API.md. Version 0.294.2.

## Testing
- `test_main.py`: union added when the table exists, skipped when it
doesn't, four columns and the estimate (9 passed).
- **BigQuery dry run** of the full export with the union (inline row in
place of the table): valid, ~8.2 GB scanned (unchanged).
- Local CodeRabbit review: 0 findings.

## Deploy
The function is deployed by hand:
`infrastructure/functions/kn_data_sync/deploy.sh` (`gcloud functions
deploy`). CI doesn't deploy it, and it needs `/gcp-admin`.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_012RYLVUQ68KFYtZF7vEfhAq

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:57:47 -05:00
Andrew Beveridge ☄️andClaude Opus 5.5 c133b64c7d fix(quick-version): retry LRCLIB with a cleaned title + honour lyrics overrides (v0.294.1) (#1257)
## Why
At a kjbox show on 2026-11-06, the make-it quick version for Sombr "My
Body Isn't Ready (Orchestral Version Live From Sound City)" (job
`f9764a9f`) rendered with only "(lyrics unavailable)" on screen. The
singer heard the backing track with no lyrics. LRCLIB only has this song
under the plain title.

## What
- `fetch_lrclib_lyrics`: if the exact `/get` and `/search` find nothing,
retry `/search` once with the title cleaned (`clean_title`: trailing
`(…)`/`[…]` groups and `- Live …`/`- Remaster` style suffixes removed).
- A synced hit from the retry keeps its timing only when its length is
within **4 s** of the audio, because a different length usually means a
different recording (studio vs live). Any other hit is used as plain
lyrics (constant crawl).
- Plain lyrics found under the exact title still win, and titles with
nothing to clean make no extra request.
- The quick render now searches with the job's
`lyrics_artist`/`lyrics_title` overrides, else the title without a tempo
label, the same names the review page uses. The displayed artist/title
are unchanged.
- Companion: kjbox v0.150.0 (nomadkaraoke/kjbox#314, deployed) lets the
KJ add lyrics on the box when a draft still comes back without any.

## Testing
- `backend/tests/test_quick_version.py`: 56 pass, including 17 new tests
(cleaned-title retry: matching sync, wrong-length sync downgraded to
plain, no duration, exact plain wins, failure paths, no retry for plain
titles; `clean_title` cases; lyrics-search names incl. tempo label and
overrides).
- Live LRCLIB check: `fetch_lrclib_lyrics('Sombr', "My Body Isn't Ready
(Orchestral Version Live From Sound City)", 224.5)` returns **synced, 37
lines**. Before this change it returned nothing.
- Local CodeRabbit review: 0 findings. Full suite left to CI.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_012RYLVWXLyvTmHNnqQu3rzA

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:56:59 -05:00
24 changed files with 619 additions and 32 deletions

No files matched your search

+10 -2
View File
@@ -887,7 +887,12 @@ def delete_job(
detail=t(locale, "jobs.cleanupFailed", services=", ".join(incomplete)),
)
job_manager.delete_job(job_id, delete_files=delete_files)
job_manager.delete_job(
job_id,
delete_files=delete_files,
archived_by=auth_result.user_email,
reason="admin_delete" if auth_result.is_admin else "owner_delete",
)
# A requests-board pick whose owner deleted the job goes back on the board (or is
# removed if nobody backs it) instead of staying "in progress" on a dead job.
@@ -2810,7 +2815,10 @@ def cleanup_distribution(
# Delete the job if requested
if delete_job:
try:
job_manager.delete_job(job_id, delete_files=True)
job_manager.delete_job(
job_id, delete_files=True, archived_by=auth_result.user_email,
reason="cleanup_distribution_delete",
)
results["job_deleted"] = True
logger.info(f"Deleted job {job_id} after distribution cleanup")
except Exception as e:
+21 -4
View File
@@ -260,6 +260,20 @@ class AccountDeletionService:
def _owned_jobs(self, email: str) -> List[Any]:
return list(self._jobs().where(filter=FieldFilter("user_email", "==", email)).stream())
def _archived_jobs(self, email: str) -> List[Any]:
"""Deleted jobs kept in ``<jobs>_archive`` (system data, redacted like live jobs).
Single-field queries only, so the archive needs no composite index;
made-for-you is filtered here rather than in the query.
"""
archive = self.db.collection(f"{self.jobs_collection}_archive")
owned = list(archive.where(filter=FieldFilter("user_email", "==", email)).stream())
customer = [
snap for snap in archive.where(filter=FieldFilter("customer_email", "==", email)).stream()
if (snap.to_dict() or {}).get("made_for_you")
]
return owned + customer
def _customer_jobs(self, email: str) -> List[Any]:
"""Made-for-you orders: owned by the admin, delivered to ``customer_email``."""
return list(
@@ -442,10 +456,12 @@ class AccountDeletionService:
def _scrub_jobs(self, email: str, deletion_id: str) -> dict:
totals = {"jobs": 0, "input_objects_deleted": 0, "dropbox_links_revoked": 0}
seen = set()
for snap in self._owned_jobs(email) + self._customer_jobs(email):
if snap.id in seen:
tagged = [("live", snap) for snap in self._owned_jobs(email) + self._customer_jobs(email)]
tagged += [("archive", snap) for snap in self._archived_jobs(email)]
for where, snap in tagged:
if (where, snap.id) in seen:
continue
seen.add(snap.id)
seen.add((where, snap.id))
result = self._scrub_job(snap, email, deletion_id)
totals["jobs"] += 1
totals["input_objects_deleted"] += result["input_objects_deleted"]
@@ -517,7 +533,8 @@ class AccountDeletionService:
if "client_ip" in (data.get("request_metadata") or {}):
updates["request_metadata.client_ip"] = DELETE_FIELD
if updates:
self._jobs().document(job_id).update(updates)
# snap.reference: the live job or its archived copy in <jobs>_archive.
snap.reference.update(updates)
return {"input_objects_deleted": deleted, "dropbox_link_revoked": revoked}
# Step 8
+50
View File
@@ -481,6 +481,56 @@ class FirestoreService:
logger.error(f"Error deleting jobs by filter: {e}")
raise
# Deleted jobs are archived here (forever) instead of being lost: the job doc
# plus its logs and audio-edit sessions, so a deleted job can still be debugged.
# Logs go under ``archived_logs`` without ``ttl_expiry``: the TTL policy on the
# ``logs`` collection group would otherwise expire them on the original schedule.
ARCHIVE_SUBCOLLECTIONS = {"logs": "archived_logs", "audio_edit_sessions": "audio_edit_sessions"}
@property
def archive_collection(self) -> str:
return f"{self.collection}_archive"
def archive_job(
self, job_id: str, archived_by: Optional[str] = None, reason: Optional[str] = None
) -> bool:
"""Copy a job (doc + subcollections) into the archive collection.
Returns False if the job doesn't exist. Raises on any write failure, so the
caller can refuse to delete a job whose archive copy didn't land.
"""
src = self.db.collection(self.collection).document(job_id)
snap = src.get()
if not snap.exists:
return False
dest = self.db.collection(self.archive_collection).document(job_id)
data = snap.to_dict() or {}
data["archived_at"] = datetime.now(timezone.utc)
data["archived_by"] = archived_by
data["archive_reason"] = reason
dest.set(data)
copied = {}
for src_name, dest_name in self.ARCHIVE_SUBCOLLECTIONS.items():
count = 0
batch = self.db.batch()
pending = 0
for doc in src.collection(src_name).stream():
entry = doc.to_dict() or {}
entry.pop("ttl_expiry", None)
batch.set(dest.collection(dest_name).document(doc.id), entry)
pending += 1
count += 1
if pending >= 400:
batch.commit()
batch = self.db.batch()
pending = 0
if pending:
batch.commit()
copied[src_name] = count
logger.info(f"Archived job {job_id} to {self.archive_collection} ({copied}) by {archived_by}: {reason}")
return True
def delete_job(self, job_id: str) -> None:
"""Delete a job from Firestore."""
try:
+16 -2
View File
@@ -567,9 +567,23 @@ class JobManager:
return urls
def delete_job(self, job_id: str, delete_files: bool = True) -> None:
"""Delete a job, its files, and its logs subcollection."""
def delete_job(
self,
job_id: str,
delete_files: bool = True,
archived_by: Optional[str] = None,
reason: str = "deleted",
) -> None:
"""Delete a job, its files, and its logs subcollection.
The job doc, logs and audio-edit sessions are first copied to the archive
collection (``jobs_archive``). If that copy fails the delete is aborted, so a
deleted job is never lost. Bulk test cleanup (``delete_jobs_by_filter``) does
not archive.
"""
job = self.get_job(job_id)
if job:
self.firestore.archive_job(job_id, archived_by=archived_by, reason=reason)
# Refund credit if job never completed (and wasn't already refunded via fail/cancel)
if job:
+67 -2
View File
@@ -49,6 +49,30 @@ TimedLine = Tuple[str, Optional[float]]
_LRC_RE = re.compile(r"\[(\d+):(\d+(?:\.\d+)?)\]")
# A synced LRCLIB result found under a *cleaned* title is often a different
# recording (studio vs "Live From ..."), so its timing is only trusted when the
# lengths agree this closely; otherwise its words scroll at a constant pace.
CLEAN_TITLE_SYNC_TOLERANCE_S = 4.0
# Trailing "(...)" / "[...]" groups and " - Live at ..." style suffixes that stop
# LRCLIB matching the plain song (kjbox quick_lyrics.clean_title mirrors this).
_TRAILING_GROUP_RE = re.compile(r"\s*[\(\[][^\(\)\[\]]*[\)\]]\s*$")
_DASH_SUFFIX_RE = re.compile(
r"\s+-\s+.*\b(live|version|remaster(ed)?|mix|edit|acoustic|orchestral|session|demo|mono|stereo)\b.*$",
re.IGNORECASE)
def clean_title(title: str) -> str:
"""'Song (Live From X) [HD]' / 'Song - 2011 Remaster' → 'Song' (never empty)."""
t = (title or "").strip()
while True:
stripped = _TRAILING_GROUP_RE.sub("", t)
if stripped == t or not stripped.strip():
break
t = stripped
t = _DASH_SUFFIX_RE.sub("", t)
return t.strip() or (title or "").strip()
@dataclass
class Lyrics:
@@ -151,9 +175,46 @@ def fetch_lrclib_lyrics(
except (requests.RequestException, ValueError) as exc:
logger.warning(f"LRCLIB search failed: {exc}")
# Decorated titles ("My Song (Orchestral Version Live From X)") rarely match
# on LRCLIB: retry once with the plain title. Exact-title plain lyrics still
# win over this looser match.
cleaned = clean_title(title)
if exact_plain is None and cleaned and cleaned.casefold() != (title or "").strip().casefold():
exact_plain = _search_cleaned_title(artist, cleaned, duration, timeout, session)
return exact_plain
def _search_cleaned_title(artist: str, cleaned: str, duration: Optional[float], timeout: float,
session: requests.Session) -> Optional[Lyrics]:
"""Search LRCLIB with a cleaned title. Synced timing is kept only for a hit
whose length matches the audio; any other hit is used as plain lyrics."""
try:
r = lrclib_client.get(f"{LRCLIB_BASE}/search", {"q": f"{artist} {cleaned}"}, user_agent=USER_AGENT,
timeout=timeout, session=session, retry=False)
if r.status_code != 200:
return None
hits = [h for h in (r.json() or []) if isinstance(h, dict)]
except (requests.RequestException, ValueError) as exc:
logger.warning(f"LRCLIB cleaned-title search failed: {exc}")
return None
fallback: Optional[Lyrics] = None
for hit in sorted(hits, key=lambda h: 0 if h.get("syncedLyrics") else 1):
got = lyrics_from_lrclib_payload(hit)
if got is None:
continue
hit_duration = hit.get("duration")
if (got.kind == "synced" and duration and isinstance(hit_duration, (int, float))
and abs(hit_duration - duration) <= CLEAN_TITLE_SYNC_TOLERANCE_S):
logger.info(f"Quick lyrics: synced match via cleaned title {cleaned!r}")
return got
if fallback is None and got.plain.strip():
fallback = Lyrics("plain", got.plain)
if fallback is not None:
logger.info(f"Quick lyrics: plain lyrics via cleaned title {cleaned!r} (no length-matched sync)")
return fallback
def resolve_timed_lines(lyrics: Optional[Lyrics]) -> Tuple[List[TimedLine], str]:
"""Lyrics → (line, anchor|None) pairs + tier label (synced / constant / none)."""
if lyrics is None:
@@ -326,15 +387,19 @@ def render_quick_video(
workdir: str,
lyrics: Optional[Lyrics] = None,
fetch_lyrics: bool = True,
lyrics_artist: Optional[str] = None,
lyrics_title: Optional[str] = None,
settings: Optional[RenderSettings] = None,
ffmpeg_timeout: float = 600.0,
) -> RenderResult:
"""Render the quick video. ``lyrics`` overrides the LRCLIB fetch."""
"""Render the quick video. ``lyrics`` overrides the LRCLIB fetch;
``lyrics_artist``/``lyrics_title`` (the job's lyrics-search overrides) are
what LRCLIB is searched with, while ``artist``/``title`` are displayed."""
s = settings or RenderSettings()
duration = probe_duration(instrumental_path)
if lyrics is None and fetch_lyrics:
lyrics = fetch_lrclib_lyrics(artist, title, duration)
lyrics = fetch_lrclib_lyrics(lyrics_artist or artist, lyrics_title or title, duration)
timed_lines, tier = resolve_timed_lines(lyrics)
if tier == "synced":
+9 -1
View File
@@ -29,6 +29,7 @@ from typing import Any, Callable, Dict, Optional, Tuple
from backend.services.job_notification_service import is_kjbox_job
from backend.services.quick_version.renderer import render_quick_video
from backend.services.tempo_label import strip_tempo_suffix
logger = logging.getLogger(__name__)
@@ -161,10 +162,13 @@ class QuickVersionRender:
def __init__(self, job_id: str, artist: str, title: str, instrumental: str, vocals: Optional[str],
workdir: str, job_manager: Any, storage: Any, job_log: Any = None,
started_monotonic: Optional[float] = None, separation_seconds: Optional[float] = None):
started_monotonic: Optional[float] = None, separation_seconds: Optional[float] = None,
lyrics_artist: Optional[str] = None, lyrics_title: Optional[str] = None):
self.job_id = job_id
self.artist = artist or "Unknown"
self.title = title or "Unknown"
self.lyrics_artist = lyrics_artist
self.lyrics_title = lyrics_title
self.instrumental = instrumental
self.vocals = vocals
self.workdir = workdir
@@ -195,6 +199,7 @@ class QuickVersionRender:
result = render_quick_video(
instrumental_path=self.instrumental, vocals_path=self.vocals,
artist=self.artist, title=self.title, out_path=out_path, workdir=render_dir,
lyrics_artist=self.lyrics_artist, lyrics_title=self.lyrics_title,
)
render_seconds = time.monotonic() - t0
gcs_path = f"jobs/{self.job_id}/quick/quick.mp4"
@@ -259,6 +264,9 @@ def start_quick_version(
return QuickVersionRender(
job_id, job.artist, job.title, inst, vocals, workdir, job_manager, storage, job_log,
started_monotonic=started, separation_seconds=sep_seconds,
# Same lyrics-search names the review page uses (never a tempo label).
lyrics_artist=getattr(job, "lyrics_artist", None) or job.artist,
lyrics_title=getattr(job, "lyrics_title", None) or strip_tempo_suffix(job.title),
).start()
except Exception as exc:
logger.warning(f"[job:{job_id}] Quick version skipped after error (non-fatal): {exc}", exc_info=True)
@@ -0,0 +1,64 @@
"""
Emulator test: deleting a job archives it (doc + logs + audio-edit sessions).
Run with: ./scripts/run-emulator-tests.sh
"""
import os
import time
from datetime import datetime, timedelta, timezone
import pytest
import requests
def emulators_running() -> bool:
try:
requests.get("http://127.0.0.1:8080", timeout=1) # Firestore
requests.get("http://127.0.0.1:4443", timeout=1) # GCS (same check as conftest)
return True
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
return False
pytestmark = pytest.mark.skipif(
not emulators_running(),
reason="GCP emulators not running. Start with: scripts/start-emulators.sh",
)
os.environ["FIRESTORE_EMULATOR_HOST"] = "127.0.0.1:8080"
os.environ["GOOGLE_CLOUD_PROJECT"] = "test-project"
def test_archive_job_copies_doc_and_subcollections_without_ttl():
from google.cloud import firestore
from backend.services.firestore_service import FirestoreService
svc = FirestoreService()
svc.db = firestore.Client(project="test-project")
svc.collection = f"test-archive-jobs-{int(time.time() * 1000)}"
job_id = "arch-job-1"
job_ref = svc.db.collection(svc.collection).document(job_id)
job_ref.set({"job_id": job_id, "status": "complete", "artist": "Invented Band", "title": "Made Up Song"})
expiry = datetime.now(timezone.utc) + timedelta(days=30)
for i in range(3):
job_ref.collection("logs").document(f"log{i}").set(
{"message": f"line {i}", "ttl_expiry": expiry, "level": "INFO"}
)
job_ref.collection("audio_edit_sessions").document("s1").set({"edits": 2})
assert svc.archive_job(job_id, archived_by="admin@nomadkaraoke.com", reason="admin_delete") is True
arch = svc.db.collection(svc.archive_collection).document(job_id)
data = arch.get().to_dict()
assert data["artist"] == "Invented Band"
assert data["archived_by"] == "admin@nomadkaraoke.com"
assert data["archive_reason"] == "admin_delete"
assert data["archived_at"] is not None
logs = {d.id: d.to_dict() for d in arch.collection("archived_logs").stream()}
assert sorted(logs) == ["log0", "log1", "log2"]
assert all("ttl_expiry" not in entry for entry in logs.values())
assert [d.id for d in arch.collection("audio_edit_sessions").stream()] == ["s1"]
assert svc.archive_job("does-not-exist") is False
+24
View File
@@ -699,6 +699,30 @@ def test_completed_made_for_you_order_anonymised(client, db):
assert job["customer_notes"] is None
def test_archived_jobs_redacted_not_deleted(client, db):
"""Deleted jobs live on in jobs_archive as system data; account deletion redacts them."""
_seed_user(db)
archived = dict(_seed_job(db, "arch1"), archived_by="admin@nomadkaraoke.com", archive_reason="admin_delete")
db.collection("jobs").docs.pop("arch1")
db.collection("jobs_archive").docs["arch1"] = archived
mfy = dict(_seed_job(db, "arch2", email="admin@nomadkaraoke.com", made_for_you=True, customer_email=EMAIL))
db.collection("jobs").docs.pop("arch2")
db.collection("jobs_archive").docs["arch2"] = mfy
body = _delete(client).json()
tomb = f"deleted:{body['summary']['deletion_id']}"
a1 = db.collection("jobs_archive").docs["arch1"]
assert a1["user_email"] == tomb
assert a1["creation_ip"] is None
assert "client_ip" not in a1["request_metadata"]
assert "customer_email" not in a1["state_data"]
assert a1["artist"] == "Invented Band" # system data kept
assert a1["archive_reason"] == "admin_delete"
a2 = db.collection("jobs_archive").docs["arch2"]
assert a2["user_email"] == "admin@nomadkaraoke.com"
assert a2["customer_email"] == tomb
def test_other_users_jobs_untouched(client, db):
_seed_user(db)
_seed_job(db, "j9", email=OTHER)
+34
View File
@@ -515,6 +515,40 @@ class TestJobDeletion:
mock_firestore_service.delete_job.assert_called_once_with("test123")
def test_delete_job_archives_first(self, job_manager, mock_firestore_service):
"""The job is copied to jobs_archive before the doc is deleted."""
existing_job = Job(
job_id="test123", status=JobStatus.COMPLETE, progress=100,
created_at=datetime.now(UTC), updated_at=datetime.now(UTC), output_files={},
)
mock_firestore_service.get_job.return_value = existing_job
order = []
mock_firestore_service.archive_job.side_effect = lambda *a, **k: order.append("archive") or True
mock_firestore_service.delete_job.side_effect = lambda *a, **k: order.append("delete")
job_manager.delete_job("test123", archived_by="admin@nomadkaraoke.com", reason="admin_delete")
mock_firestore_service.archive_job.assert_called_once_with(
"test123", archived_by="admin@nomadkaraoke.com", reason="admin_delete"
)
assert order == ["archive", "delete"]
def test_delete_job_aborts_when_archive_fails(self, job_manager, mock_firestore_service):
"""A job whose archive copy didn't land is never deleted."""
existing_job = Job(
job_id="test123", status=JobStatus.COMPLETE, progress=100,
created_at=datetime.now(UTC), updated_at=datetime.now(UTC), output_files={},
)
mock_firestore_service.get_job.return_value = existing_job
mock_firestore_service.archive_job.side_effect = RuntimeError("firestore down")
with pytest.raises(RuntimeError):
job_manager.delete_job("test123")
mock_firestore_service.delete_job.assert_not_called()
mock_firestore_service.delete_logs_subcollection.assert_not_called()
class TestDeleteStateDataKeys:
"""Tests for delete_state_data_key and delete_state_data_keys methods.
+88
View File
@@ -12,6 +12,20 @@ from backend.services.quick_version import renderer as r
from backend.services.quick_version import service as qs
class TestCleanTitle:
@pytest.mark.parametrize("raw,clean", [
("My Body Isn't Ready (Orchestral Version Live From Sound City)", "My Body Isn't Ready"),
("Creep (Acoustic) [Remastered 2009]", "Creep"),
("Song - Live at Wembley", "Song"),
("Song - 2011 Remaster", "Song"),
("Rock - Paper - Scissors", "Rock - Paper - Scissors"),
("(Intro)", "(Intro)"),
("", ""),
])
def test_clean_title(self, raw, clean):
assert r.clean_title(raw) == clean
# --------------------------------------------------------------------------- #
# Lyrics parsing / tiers
# --------------------------------------------------------------------------- #
@@ -70,6 +84,56 @@ class TestFetchLrclib:
got = r.fetch_lrclib_lyrics("A", "T", None)
assert got.kind == "plain" and got.plain == "plain words"
def test_decorated_title_retries_cleaned_with_length_matched_sync(self):
sess = self._session([
_resp(404, {}),
_resp(200, []),
_resp(200, [
{"syncedLyrics": "[00:01.00]studio", "duration": 217},
{"syncedLyrics": "[00:02.00]live", "duration": 223},
]),
])
with patch.object(r.requests, "Session", return_value=sess):
got = r.fetch_lrclib_lyrics("Sombr", "My Body Isn't Ready (Orchestral Version Live From X)", 224.5)
assert got.kind == "synced" and got.timed == [(2.0, "live")]
assert sess.get.call_args.kwargs["params"] == {"q": "Sombr My Body Isn't Ready"}
def test_cleaned_title_sync_with_wrong_length_becomes_plain(self):
sess = self._session([
_resp(404, {}),
_resp(200, []),
_resp(200, [{"syncedLyrics": "[00:01.00]a\n[00:02.00]b", "duration": 180}]),
])
with patch.object(r.requests, "Session", return_value=sess):
got = r.fetch_lrclib_lyrics("A", "Song (Live)", 224.5)
assert got.kind == "plain" and got.plain == "a\nb" and got.timed is None
def test_cleaned_title_without_duration_never_trusts_sync(self):
sess = self._session([_resp(404, {}), _resp(200, []),
_resp(200, [{"syncedLyrics": "[00:01.00]a", "duration": 200}])])
with patch.object(r.requests, "Session", return_value=sess):
assert r.fetch_lrclib_lyrics("A", "Song (Live)", None).kind == "plain"
def test_exact_plain_beats_cleaned_retry(self):
sess = self._session([_resp(200, {"plainLyrics": "exact"}), _resp(200, [])])
with patch.object(r.requests, "Session", return_value=sess):
got = r.fetch_lrclib_lyrics("A", "Song (Live)", 200)
assert got.plain == "exact" and sess.get.call_count == 2
def test_cleaned_retry_failures_return_none(self):
err = r.requests.RequestException("down")
for third in (err, _resp(500, {}), _resp(200, [{"plainLyrics": " "}, "junk"])):
sess = self._session([_resp(404, {}), _resp(200, []), third])
with patch.object(r.requests, "Session", return_value=sess):
assert r.fetch_lrclib_lyrics("A", "Song (Live)", 200) is None
assert sess.get.call_count == 3
def test_undecorated_title_does_not_retry(self):
sess = self._session([_resp(404, {}), _resp(200, [])])
with patch.object(r.requests, "Session", return_value=sess):
assert r.fetch_lrclib_lyrics("A", "Song", 200) is None
assert sess.get.call_count == 2
def test_network_errors_return_none(self):
err = r.requests.RequestException("down")
sess = self._session([err, err])
@@ -289,6 +353,30 @@ class TestStartQuickVersion:
ready = jm.update_state_data.call_args_list[-1].args[2]
assert ready["lyrics_tier"] == "synced" and ready["line_count"] == 42 and "ready_at" in ready
@pytest.mark.parametrize("overrides,expected", [
({}, ("Artist", "Song")),
({"title": "Song (90% Tempo)"}, ("Artist", "Song")),
({"lyrics_artist": "LA", "lyrics_title": "LT"}, ("LA", "LT")),
])
def test_lyrics_search_names(self, tmp_path, overrides, expected):
seen = {}
def fake_render(**kw):
seen.update(kw)
open(kw["out_path"], "wb").write(b"x")
return r.RenderResult(kw["out_path"], "synced", 1, 1.0)
job = _job()
job.artist, job.title = "Artist", "Song"
for k, v in overrides.items():
setattr(job, k, v)
with patch.object(qs, "render_quick_video", side_effect=fake_render):
run = qs.start_quick_version(job, "a.flac", str(tmp_path), "/m", Mock(), Mock(),
separator_factory=_FakeSeparator)
assert run.join(10)
assert (seen["lyrics_artist"], seen["lyrics_title"]) == expected
assert seen["title"] == job.title # display title untouched
def test_separation_failure_is_non_fatal(self, tmp_path):
jm = Mock()
+1
View File
@@ -1105,6 +1105,7 @@ missing from it.
candidates or in one more Spotify lookup of the AI's song. Otherwise it comes back
`confident: false` with reason "… [unconfirmed: not in catalog or Spotify]". Clients show that as
"Did you mean…?" and never apply it.
- Every live result is kept forever by decide (Firestore query cache + BigQuery `spotify_live_tracks`), and kn-data-sync adds those songs to the daily song-id export. So a song looked up once is known to the kjbox on-device matcher, decide's song search and the mobile app's offline index from the next build on (v0.294.2).
- Spotify unavailable means no evidence, so AI corrections aren't confident. That is conservative on
purpose. Incident: kjbox 2026-11-05, job `f01c9997`, "Roll of Dice" became "Roll of the Dice".
+9
View File
@@ -467,6 +467,8 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
**Worker Logs**: Stored in subcollection (`jobs/{job_id}/logs`) instead of embedded array to avoid Firestore's 1MB document size limit. TTL policy auto-deletes logs after 30 days. Feature flag: `USE_LOG_SUBCOLLECTION` (default: true). See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#firestore-document-1mb-limit-with-embedded-arrays).
**Deleted jobs are archived, not lost** (since v0.295.0): `JobManager.delete_job` first copies the job doc to `jobs_archive/{job_id}` (plus `archived_at`, `archived_by`, `archive_reason`: `admin_delete` / `owner_delete` / `cleanup_distribution_delete`), its logs to `jobs_archive/{job_id}/archived_logs` (without `ttl_expiry`, because the TTL policy is on the `logs` collection group, so archived logs are kept forever), and its `audio_edit_sessions`. If the copy fails, the delete is aborted. Archived jobs are kept forever as system data. Account deletion redacts them like live jobs (owner/customer email → `deleted:<uuid>`, IPs, notes and contact fields removed). Bulk test cleanup (`DELETE /api/jobs?…`, `delete_jobs_by_filter`) still hard-deletes. `scripts/get_job.py <id>` falls back to the archive.
## Encoding Worker: blue-green primary pair + multi-family fallback pool
> **2026-11 update:** the c4d Spot pair (`encoding-worker-a`/`-b`) is **retired and deleted**. The preferred encoder (and distribution worker) is the AWS EC2 box `aws-encoding-worker-1`; the only GCE VM is the on-demand fallback `encoding-worker-fallback-c2df` (us-central1-f). `config/encoding-worker` keeps `primary_vm`/`secondary_vm` empty, so every selection path routes to a fallback and records it as `active_override_*`. CI blue-green deploys now just validate the new wheel on c2df and stop it again (the AWS override keeps serving); the worker-change gate diffs against `validated_version`. The pair-specific text below is historical.
@@ -827,6 +829,13 @@ full NOMAD version. Code: `backend/services/quick_version/` (a port of kjbox `fa
crawl PNG + one ffmpeg `overlay` pass, 854×480, vocals mixed back in at 30% as a guide. Every
ffmpeg input and the output are bounded with `-t <duration>`: the GPU image's ffmpeg 4.4 never
ends on `-shortest` alone once `amix` is involved (first prod job ran into the 300 s join timeout).
LRCLIB is searched with the job's `lyrics_artist`/`lyrics_title` overrides (else artist + title
without a tempo label). If the exact title finds nothing, it retries once with the title's
decorations stripped (`clean_title`: trailing `(…)`/`[…]`, `- Live …`/`- Remaster` suffixes). A
synced hit from that retry keeps its timing only when its length is within 4 s of the audio
(otherwise it is likely another recording, e.g. studio vs live), and anything else becomes a constant
crawl. Added after a "… (Orchestral Version Live From Sound City)" draft rendered with no lyrics
(2026-11-06). kjbox can also add lyrics to a lyric-less draft on the box (kjbox v0.150.0).
3. Uploads `jobs/{id}/quick/quick.mp4` → `file_urls.quick.video_mp4`, and records
`state_data.quick_version = {status: separating|rendering|ready|failed, lyrics_tier, ready_at, …}`.
4. The worker joins the render (≤300 s) before cleaning up its temp dir — even when the ensemble
+12 -1
View File
@@ -96,9 +96,10 @@ Notifications are sent when:
| Variable | Value | Description |
|----------|-------|-------------|
| `GDRIVE_FOLDER_ID` | `1laRKAyxo0v817SstfM5XkpbWiNKNAMSX` | Root folder of public share |
| `NOTIFY_ON_SUCCESS` | `true` | Send daily "all clear" summary |
| `NOTIFY_ON_SUCCESS` | `false` (prod) | Send an "all clear" email on every clean run; off in prod because the post-job trigger runs after every job |
| `EMAIL_TO` | `gen@nomadkaraoke.com` | Email recipient |
| `EMAIL_FROM` | `gen@nomadkaraoke.com` | Email sender |
| `IN_FLIGHT_GRACE_MINUTES` | `30` (default) | Tracks with any file created in Drive this recently count as still uploading and are left out of the gap check |
### Secrets (Cloud Function)
@@ -202,6 +203,16 @@ The post-job trigger uses a 5-minute Cloud Tasks delay (via `gdrive-validation-q
**IMPORTANT: Never add new entries to `KNOWN_GAPS`.** The existing known gaps are historical (pre-generator era, over a year old). Every new gap is a real bug that must be investigated and fixed.
**Tracks still uploading are not gaps.** A job's packaging step uploads MP4, then
MP4-720p, then CDG over ~2 minutes, and another job's post-job trigger can run in that
window. On 2026-11-07 NOMAD-1871's check ran at 12:24:47 UTC while NOMAD-1872 was
uploading (12:23:39–12:25:40) and emailed "CDG/MP4-720p: missing 1872"; the files were
all there a minute later. Since then the validator reads each file's Drive `createdTime`
and leaves out of the gap check any track with a file created in the last
`IN_FLIGHT_GRACE_MINUTES` (30). That track is still checked by its own post-job trigger
(which names its `brand_code`) and by the daily 9 PM run. If you get a gap alert for the
newest track, first check whether that job was in `packaging` at the alert time.
**Investigation steps:**
1. **Identify the missing brand code(s)** from the alert (e.g., "MP4: missing 1295")
+20 -6
View File
@@ -1835,7 +1835,7 @@ function AdminJobsPageContent() {
{/* YouTube */}
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className={`w-2 h-2 rounded-full mt-1.5 ${
deleteOutputsResult.deleted_services.youtube.status === "deleted"
deleteOutputsResult.deleted_services.youtube.status === "success"
? "bg-green-500"
: deleteOutputsResult.deleted_services.youtube.status === "skipped"
? "bg-gray-400"
@@ -1844,7 +1844,7 @@ function AdminJobsPageContent() {
<div className="flex-1 min-w-0">
<div className="font-medium text-sm">YouTube</div>
<div className="text-xs text-muted-foreground">
{deleteOutputsResult.deleted_services.youtube.status === "deleted" && (
{deleteOutputsResult.deleted_services.youtube.status === "success" && (
<>Deleted video: <code className="text-xs bg-muted px-1 rounded">{deleteOutputsResult.deleted_services.youtube.video_id}</code></>
)}
{deleteOutputsResult.deleted_services.youtube.status === "skipped" && (
@@ -1853,6 +1853,9 @@ function AdminJobsPageContent() {
{deleteOutputsResult.deleted_services.youtube.status === "error" && (
<span className="text-red-500">{deleteOutputsResult.deleted_services.youtube.error}</span>
)}
{(deleteOutputsResult.deleted_services.youtube.status === "failed" || deleteOutputsResult.deleted_services.youtube.status === "partial") && (
<span className="text-red-500">{deleteOutputsResult.deleted_services.youtube.reason || deleteOutputsResult.deleted_services.youtube.error || "Delete failed, check the job logs"}</span>
)}
</div>
</div>
</div>
@@ -1860,7 +1863,7 @@ function AdminJobsPageContent() {
{/* Dropbox */}
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className={`w-2 h-2 rounded-full mt-1.5 ${
deleteOutputsResult.deleted_services.dropbox.status === "deleted"
deleteOutputsResult.deleted_services.dropbox.status === "success"
? "bg-green-500"
: deleteOutputsResult.deleted_services.dropbox.status === "skipped"
? "bg-gray-400"
@@ -1869,7 +1872,7 @@ function AdminJobsPageContent() {
<div className="flex-1 min-w-0">
<div className="font-medium text-sm">Dropbox</div>
<div className="text-xs text-muted-foreground">
{deleteOutputsResult.deleted_services.dropbox.status === "deleted" && (
{deleteOutputsResult.deleted_services.dropbox.status === "success" && (
<>Deleted folder: <code className="text-xs bg-muted px-1 rounded break-all">{deleteOutputsResult.deleted_services.dropbox.path}</code></>
)}
{deleteOutputsResult.deleted_services.dropbox.status === "skipped" && (
@@ -1878,6 +1881,9 @@ function AdminJobsPageContent() {
{deleteOutputsResult.deleted_services.dropbox.status === "error" && (
<span className="text-red-500">{deleteOutputsResult.deleted_services.dropbox.error}</span>
)}
{(deleteOutputsResult.deleted_services.dropbox.status === "failed" || deleteOutputsResult.deleted_services.dropbox.status === "partial") && (
<span className="text-red-500">{deleteOutputsResult.deleted_services.dropbox.reason || deleteOutputsResult.deleted_services.dropbox.error || "Delete failed, check the job logs"}</span>
)}
</div>
</div>
</div>
@@ -1885,7 +1891,7 @@ function AdminJobsPageContent() {
{/* Google Drive */}
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className={`w-2 h-2 rounded-full mt-1.5 ${
deleteOutputsResult.deleted_services.gdrive.status === "deleted"
deleteOutputsResult.deleted_services.gdrive.status === "success"
? "bg-green-500"
: deleteOutputsResult.deleted_services.gdrive.status === "skipped"
? "bg-gray-400"
@@ -1894,7 +1900,7 @@ function AdminJobsPageContent() {
<div className="flex-1 min-w-0">
<div className="font-medium text-sm">Google Drive</div>
<div className="text-xs text-muted-foreground">
{deleteOutputsResult.deleted_services.gdrive.status === "deleted" && deleteOutputsResult.deleted_services.gdrive.files && (
{deleteOutputsResult.deleted_services.gdrive.status === "success" && deleteOutputsResult.deleted_services.gdrive.files && (
<>Deleted {Object.keys(deleteOutputsResult.deleted_services.gdrive.files).length} file(s)</>
)}
{deleteOutputsResult.deleted_services.gdrive.status === "skipped" && (
@@ -1903,6 +1909,14 @@ function AdminJobsPageContent() {
{deleteOutputsResult.deleted_services.gdrive.status === "error" && (
<span className="text-red-500">{deleteOutputsResult.deleted_services.gdrive.error}</span>
)}
{(deleteOutputsResult.deleted_services.gdrive.status === "failed" || deleteOutputsResult.deleted_services.gdrive.status === "partial") && (
<span className="text-red-500">{
deleteOutputsResult.deleted_services.gdrive.files &&
Object.values(deleteOutputsResult.deleted_services.gdrive.files).some((ok) => !ok)
? `Not deleted: ${Object.entries(deleteOutputsResult.deleted_services.gdrive.files).filter(([, ok]) => !ok).map(([k]) => k).join(", ")}`
: deleteOutputsResult.deleted_services.gdrive.reason || deleteOutputsResult.deleted_services.gdrive.error || "Delete failed, check the job logs"
}</span>
)}
</div>
</div>
</div>
@@ -581,8 +581,8 @@ test.describe('Admin Job Detail Page', () => {
job_id: 'test-job-123',
message: 'All outputs deleted successfully',
deleted_services: {
youtube: { status: 'deleted', video_id: 'xyz789' },
dropbox: { status: 'deleted', path: '/Karaoke/NK001 - Test Artist - Test Song' },
youtube: { status: 'success', video_id: 'xyz789' },
dropbox: { status: 'success', path: '/Karaoke/NK001 - Test Artist - Test Song' },
gdrive: { status: 'skipped', reason: 'No Google Drive files found' },
},
cleared_state_data: ['youtube_url', 'youtube_video_id', 'dropbox_link', 'brand_code'],
@@ -653,8 +653,8 @@ test.describe('Admin Job Detail Page', () => {
message: 'Some outputs could not be deleted',
deleted_services: {
youtube: { status: 'error', error: 'Video not found or already deleted' },
dropbox: { status: 'deleted', path: '/Karaoke/NK001 - Test Artist - Test Song' },
gdrive: { status: 'skipped', reason: 'No Google Drive files found' },
dropbox: { status: 'success', path: '/Karaoke/NK001 - Test Artist - Test Song' },
gdrive: { status: 'partial', files: { mp4: true, cdg: false } },
},
cleared_state_data: ['dropbox_link', 'brand_code'],
outputs_deleted_at: '2026-01-15T10:00:00Z',
@@ -693,6 +693,9 @@ test.describe('Admin Job Detail Page', () => {
// Should show Dropbox success
await expect(page.getByText(/NK001.*Test Artist.*Test Song/)).toBeVisible();
// A partial Drive delete names the file(s) left behind
await expect(page.getByText('Not deleted: cdg')).toBeVisible();
});
test('delete outputs button is disabled when outputs already deleted', async ({ page }) => {
@@ -53,7 +53,7 @@ gcloud functions deploy "${FUNCTION_NAME}" \
--min-instances=0 \
--max-instances=1 \
--service-account="gdrive-validator@${PROJECT_ID}.iam.gserviceaccount.com" \
--set-env-vars="GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,EMAIL_TO=gen@nomadkaraoke.com,EMAIL_FROM=gen@nomadkaraoke.com,NOTIFY_ON_SUCCESS=true" \
--set-env-vars="GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,EMAIL_TO=gen@nomadkaraoke.com,EMAIL_FROM=gen@nomadkaraoke.com,NOTIFY_ON_SUCCESS=false,LOG_EXECUTION_ID=true" \
--set-secrets="PUSHBULLET_API_KEY=pushbullet-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest" \
--project="${PROJECT_ID}"
@@ -16,6 +16,7 @@ import re
import json
import logging
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from typing import Union
import functions_framework
import requests
@@ -38,6 +39,21 @@ EMAIL_FROM = os.environ.get("EMAIL_FROM", "gen@nomadkaraoke.com")
# Set to "false" to only receive notifications when issues are detected
NOTIFY_ON_SUCCESS = os.environ.get("NOTIFY_ON_SUCCESS", "true").lower() == "true"
# A track whose newest file landed in Drive this recently is treated as still
# uploading: a job's packaging step uploads MP4, then MP4-720p, then CDG over a
# couple of minutes, and the post-job trigger for an earlier job can fire right
# in the middle (2026-11-07: NOMAD-1871's check flagged NOMAD-1872 mid-upload).
# Gaps for such tracks are held back; the track's own post-job trigger (which
# names its brand_code) and the daily run still check it once the upload ends.
def _grace_minutes() -> int:
try:
return int(os.environ.get("IN_FLIGHT_GRACE_MINUTES", "30"))
except ValueError:
return 30
IN_FLIGHT_GRACE_MINUTES = _grace_minutes()
# Known gaps configuration - matches the local validate_and_sync.py script
# These are HISTORICAL ONLY (pre-generator era, before Dec 2024). Do NOT add new entries.
# New gaps are bugs — see docs/GDRIVE-VALIDATOR.md § "Sequence Gap Detected" for fix procedure.
@@ -93,7 +109,9 @@ def get_drive_service():
return build('drive', 'v3', credentials=credentials)
def list_folder_contents(service, folder_id: str) -> dict[str, list[str]]:
def list_folder_contents(
service, folder_id: str, created_times: dict[str, str] | None = None
) -> dict[str, list[str]]:
"""
List all files in a Google Drive folder and its subfolders.
@@ -102,6 +120,9 @@ def list_folder_contents(service, folder_id: str) -> dict[str, list[str]]:
- CDG/ (contains .zip files)
- MP4/ (contains .mp4 files)
- MP4-720p/ (contains .mp4 files)
If ``created_times`` is given, it is filled with ``{filename: createdTime}``
(RFC 3339) so the caller can tell which tracks are still being uploaded.
"""
results = {}
@@ -134,12 +155,15 @@ def list_folder_contents(service, folder_id: str) -> dict[str, list[str]]:
query = f"'{folder_id_inner}' in parents and trashed=false and mimeType!='application/vnd.google-apps.folder'"
response = service.files().list(
q=query,
fields="nextPageToken, files(name)",
fields="nextPageToken, files(name, createdTime)",
pageSize=1000,
pageToken=page_token
).execute()
files.extend([f['name'] for f in response.get('files', [])])
for f in response.get('files', []):
files.append(f['name'])
if created_times is not None and f.get('createdTime'):
created_times[f['name']] = f['createdTime']
page_token = response.get('nextPageToken')
if not page_token:
@@ -187,10 +211,39 @@ def get_sequence_number(filename: str) -> int | None:
return None
def validate_files(files_by_folder: dict[str, list[str]]) -> dict:
def recently_uploaded_sequences(
created_times: dict[str, str],
now: datetime | None = None,
grace_minutes: int = IN_FLIGHT_GRACE_MINUTES,
) -> set[int]:
"""Sequence numbers that have any file created within the grace window."""
now = now or datetime.now(timezone.utc)
cutoff = now - timedelta(minutes=grace_minutes)
recent = set()
for filename, created in created_times.items():
seq = get_sequence_number(filename)
if seq is None:
continue
try:
ts = datetime.fromisoformat(created.replace("Z", "+00:00"))
except (TypeError, ValueError):
continue
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
if ts >= cutoff:
recent.add(seq)
return recent
def validate_files(
files_by_folder: dict[str, list[str]], in_flight: set[int] | None = None
) -> dict:
"""
Validate all files and return a dict of issues found.
``in_flight`` sequence numbers (tracks still uploading) are not reported
as gaps.
Returns:
{
'duplicates': {'MP4': {1107: ['file1.mp4', 'file2.mp4']}, ...},
@@ -255,7 +308,7 @@ def validate_files(files_by_folder: dict[str, list[str]]) -> dict:
min_num = min(sequence_numbers)
expected_range = set(range(min_num, global_max + 1))
excluded = EXCLUDED_NUMBERS.get(folder_name, set())
missing = sorted(expected_range - sequence_numbers - excluded)
missing = sorted(expected_range - sequence_numbers - excluded - (in_flight or set()))
if missing:
issues['gaps'][folder_name] = missing
@@ -501,7 +554,8 @@ def validate_gdrive(request):
service = get_drive_service()
# List all files
files_by_folder = list_folder_contents(service, GDRIVE_FOLDER_ID)
created_times: dict[str, str] = {}
files_by_folder = list_folder_contents(service, GDRIVE_FOLDER_ID, created_times)
if not files_by_folder:
logger.warning("No folders found in Google Drive")
@@ -511,7 +565,10 @@ def validate_gdrive(request):
}), 200, {"Content-Type": "application/json"}
# Validate files
issues = validate_files(files_by_folder)
in_flight = recently_uploaded_sequences(created_times)
if in_flight:
logger.info("Holding back gap checks for tracks still uploading: %s", sorted(in_flight))
issues = validate_files(files_by_folder, in_flight=in_flight)
# Targeted same-run completeness for the just-published track.
if brand_code:
@@ -31,6 +31,7 @@ from main import ( # noqa: E402
expand_gaps,
has_issues,
check_track_completeness,
recently_uploaded_sequences,
)
@@ -333,3 +334,35 @@ class TestHasIssues:
def test_has_gaps(self):
assert has_issues({"duplicates": {}, "invalid_filenames": {}, "gaps": {"MP4": [3]}})
class TestInFlightUploads:
"""2026-11-07: NOMAD-1871's post-job check ran while NOMAD-1872 was mid-upload
(MP4 done, 720p + CDG not yet) and emailed a false sequence-gap alert."""
NOW = __import__("datetime").datetime(2026, 11, 7, 12, 24, 47, tzinfo=__import__("datetime").timezone.utc)
def _files(self):
return {
"MP4": [make_mp4(i) for i in range(100, 106)],
"MP4-720p": [make_mp4(i) for i in range(100, 105)],
"CDG": [make_cdg(i) for i in range(100, 105)],
}
def test_track_still_uploading_is_not_a_gap(self):
created = {make_mp4(105): "2026-11-07T12:24:30.000Z", make_mp4(104): "2026-11-06T09:00:00.000Z"}
in_flight = recently_uploaded_sequences(created, now=self.NOW, grace_minutes=30)
assert in_flight == {105}
issues = validate_files(self._files(), in_flight=in_flight)
assert issues["gaps"] == {}
def test_old_track_missing_is_still_a_gap(self):
created = {make_mp4(105): "2026-11-07T10:00:00.000Z"}
in_flight = recently_uploaded_sequences(created, now=self.NOW, grace_minutes=30)
assert in_flight == set()
issues = validate_files(self._files(), in_flight=in_flight)
assert issues["gaps"] == {"MP4-720p": [105], "CDG": [105]}
def test_bad_timestamps_and_non_track_files_ignored(self):
created = {"desktop.ini": "2026-11-07T12:24:00Z", make_mp4(105): "garbage"}
assert recently_uploaded_sequences(created, now=self.NOW) == set()
+35 -1
View File
@@ -36,7 +36,7 @@ DATASET_ID = "karaoke_decide"
# kjbox song-identification index: every song a singer might mean, exported daily
# after the KN refresh and downloaded by the NomadPC's nomad-catalog-sync. Design:
# kjbox docs/SONG-IDENTIFICATION.md. Rows from three sources, merged/deduped on the
# kjbox docs/SONG-IDENTIFICATION.md. Rows from these sources, merged/deduped on the
# device (scripts/build_song_id_db.py keeps the highest popularity per song):
# - MusicBrainz recordings (weekly-refreshed by karaoke-decide's mb-refresh — the
# source that keeps NEW songs coming). Kept when Spotify track popularity >= 30
@@ -48,6 +48,7 @@ DATASET_ID = "karaoke_decide"
# (an estimate must not outrank a measured score).
# - the static July 2025 Spotify snapshot (popularity >= 30)
# - every KaraokeNerds song (daily; karaoke = 1)
# - every song a live Spotify search returned (SPOTIFY_LIVE_UNION below)
# ListenBrainz (karaoke-decide's lb-refresh, fortnightly dumps) is mapped onto Spotify's
# 0-100 scale per stats range: score = offset + slope * log10(listeners), fitted to the
# median Spotify popularity of songs that have both (2026-09-29; e.g. 100 this_year
@@ -119,6 +120,26 @@ UNION ALL SELECT sp.best.a, sp.best.t, sp.p, 0 FROM sp
UNION ALL SELECT a, t, CAST(NULL AS INT64), 1 FROM kn
"""
# Every song a live Spotify search ever returned (karaoke-decide keeps them forever in
# `spotify_live_tracks`, 2026-11-08), so a song someone looked up once, e.g. a 2025 release
# missing from the July 2025 snapshot and MusicBrainz, is in the index from then on. The API
# has no popularity, so the estimate is the D5a one: 0.8 x the artist's popularity capped at 50,
# else 30. Appended only when the table exists (decide creates it on the first live search).
SPOTIFY_LIVE_TABLE = "spotify_live_tracks"
SPOTIFY_LIVE_UNION = r"""
UNION ALL
SELECT sl.a, sl.t, COALESCE(CAST(LEAST(art.apop * 0.8, 50) AS INT64), 30), 0
FROM (
SELECT ANY_VALUE(artist_name) a, ANY_VALUE(track_name) t,
TRIM(REGEXP_REPLACE(REGEXP_REPLACE(la, r'[^a-z0-9 ]', ' '), r' +', ' ')) na
FROM (SELECT artist_name, track_name, LOWER(artist_name) la, LOWER(track_name) lt
FROM `{project}.{dataset}.spotify_live_tracks`
WHERE artist_name IS NOT NULL AND track_name IS NOT NULL
AND TRIM(artist_name) != '' AND TRIM(track_name) != '')
GROUP BY la, lt) sl
LEFT JOIN art ON art.name_normalized = sl.na
"""
# API endpoints
SONGS_URL = "https://karaokenerds.com/Data/Songs"
COMMUNITY_URL = "https://karaokenerds.com/Data/Community"
@@ -256,6 +277,15 @@ def _load_community_to_bigquery(raw_bytes: bytes) -> int:
return load_job.output_rows
def _table_exists(client, table: str) -> bool:
from google.api_core.exceptions import NotFound
try:
client.get_table(f"{GCP_PROJECT_ID}.{DATASET_ID}.{table}")
return True
except NotFound:
return False
def _export_song_id_index() -> dict:
"""EXPORT DATA the song-identification index to GCS + write the manifest.
@@ -267,6 +297,10 @@ def _export_song_id_index() -> dict:
folder = f"{SONG_ID_PREFIX}/{run}"
client = bigquery.Client(project=GCP_PROJECT_ID)
select = SONG_ID_SQL.format(project=GCP_PROJECT_ID, dataset=DATASET_ID)
if _table_exists(client, SPOTIFY_LIVE_TABLE):
select = select.rstrip() + "\n" + SPOTIFY_LIVE_UNION.format(project=GCP_PROJECT_ID, dataset=DATASET_ID)
else:
logger.info("song-id export: %s not created yet, skipping live Spotify songs", SPOTIFY_LIVE_TABLE)
export = (
f"EXPORT DATA OPTIONS(uri='gs://{GCS_BUCKET}/{folder}/songs-*.tsv.gz', format='CSV', "
"field_delimiter='\t', header=false, compression='GZIP', overwrite=true) AS " + select
@@ -137,3 +137,27 @@ def test_song_id_sql_uses_listenbrainz_and_keeps_the_four_columns():
assert f"`p.d.{table}`" in sql
# the device's build_song_id_db.py reads exactly these columns, in this order
assert "SELECT artist, title, popularity, karaoke FROM mb_kept" in sql
def test_export_adds_live_spotify_songs_when_the_table_exists(clients):
bq, _gcs = clients
bq.get_table.return_value = object()
main._export_song_id_index()
sql = bq.query.call_args[0][0]
assert "`nomadkaraoke.karaoke_decide.spotify_live_tracks`" in sql
assert sql.rstrip().endswith("LEFT JOIN art ON art.name_normalized = sl.na")
assert "{" not in sql.split(" AS ", 1)[1].replace("{project}", "") # placeholders filled
def test_export_skips_live_spotify_songs_before_the_table_exists(clients):
from google.api_core.exceptions import NotFound
bq, _gcs = clients
bq.get_table.side_effect = NotFound("no table")
main._export_song_id_index()
assert "spotify_live_tracks" not in bq.query.call_args[0][0]
def test_live_union_keeps_the_four_columns_and_estimates_popularity():
union = main.SPOTIFY_LIVE_UNION.format(project="p", dataset="d")
assert "{" not in union and "`p.d.spotify_live_tracks`" in union
assert union.strip().startswith("UNION ALL\nSELECT sl.a, sl.t, COALESCE(CAST(LEAST(art.apop * 0.8, 50) AS INT64), 30), 0")
@@ -504,6 +504,11 @@ class KaraokeFinalise:
self.logger.info(f"Successfully deleted YouTube video with ID: {video_id}")
return True
except Exception as e:
# 404 = the video is already gone (e.g. removed in YouTube Studio).
# The goal of the delete is met, so report success, not failure.
if getattr(getattr(e, "resp", None), "status", None) == 404:
self.logger.warning(f"YouTube video {video_id} not found; treating as already deleted")
return True
self.logger.error(f"Failed to delete YouTube video with ID {video_id}: {e}")
return False
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.294.0"
version = "0.295.0"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
+5
View File
@@ -22,6 +22,11 @@ def get_job(job_id: str) -> dict | None:
if doc.exists:
return doc.to_dict()
# Deleted jobs are archived (doc + archived_logs) instead of lost.
archived = db.collection('jobs_archive').document(job_id).get()
if archived.exists:
print(f"(job {job_id} was deleted; showing jobs_archive copy)", file=sys.stderr)
return archived.to_dict()
return None
@@ -472,6 +472,25 @@ def test_delete_youtube_video_failure(mock_auth, finaliser_for_yt, mock_youtube_
mock_youtube_service.videos().delete.assert_called_once_with(id=video_id)
finaliser_for_yt.logger.error.assert_any_call(f"Failed to delete YouTube video with ID {video_id}: API Error")
@patch.object(KaraokeFinalise, 'authenticate_youtube')
def test_delete_youtube_video_already_gone_404_counts_as_deleted(mock_auth, finaliser_for_yt, mock_youtube_service):
"""A 404 means the video was already removed (e.g. in YouTube Studio): success, not failure."""
from googleapiclient.errors import HttpError
mock_auth.return_value = mock_youtube_service
resp = MagicMock(status=404, reason="Not Found")
mock_youtube_service.videos.return_value.delete.return_value.execute.side_effect = HttpError(resp, b"{}")
assert finaliser_for_yt.delete_youtube_video("gone_video") is True
finaliser_for_yt.logger.error.assert_not_called()
@patch.object(KaraokeFinalise, 'authenticate_youtube')
def test_delete_youtube_video_403_still_fails(mock_auth, finaliser_for_yt, mock_youtube_service):
"""Other HTTP errors (e.g. 403 wrong channel) are still failures."""
from googleapiclient.errors import HttpError
mock_auth.return_value = mock_youtube_service
resp = MagicMock(status=403, reason="Forbidden")
mock_youtube_service.videos.return_value.delete.return_value.execute.side_effect = HttpError(resp, b"{}")
assert finaliser_for_yt.delete_youtube_video("other_video") is False
@patch.object(KaraokeFinalise, 'authenticate_youtube')
def test_delete_youtube_video_dry_run(mock_auth, finaliser_for_yt, mock_youtube_service):
"""Test video deletion dry run."""