Compare commits

...
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude c7b7f4bee5 fix: gate brand code recycling on full GDrive cleanup confirmation (#418)
## Summary

- Brand code `NOMAD-1271` was reused for a real song (Hot Mulligan - Pop
Shuvit) while old E2E test job files still existed in Google Drive,
creating a duplicate in the public share
- Root cause: `cleanup-distribution` endpoint had two bugs that allowed
brand codes to be recycled before GDrive was confirmed clean

## Root Causes

1. **Empty dict was falsy**: `if gdrive_files:` skips cleanup when
`gdrive_files = {}` (empty dict). This happened when GDrive uploads
silently failed (pre-PR #417), so test job files accumulated in GDrive
without ever being cleaned
2. **Brand code recycled too early**: Brand code was recycled
immediately after Dropbox cleanup succeeded, *without* confirming GDrive
was also clean — a new job could claim the recycled code while old
GDrive files still existed

## Changes

- **`gdrive_service.py`**: Added `find_files_by_brand_code()` — searches
CDG/, MP4/, MP4-720p/ subfolders by brand code prefix as a fallback when
tracked file IDs aren't available (old jobs, or jobs where upload failed
silently). Raises `RuntimeError` if any subfolder search fails so
callers can't misread an incomplete search as "GDrive is clean"
- **`jobs.py` (`cleanup-distribution`)**: Now uses tracked file IDs
(fast path) OR falls back to brand_code search; brand code is only
recycled after **both** Dropbox AND GDrive are confirmed clean. Fixed
`method` key being lost when results dict was replaced (use local
variable instead of interim mutation)
- **`scripts/cleanup_test_job_gdrive.py`**: Remediation script to delete
existing stranded test job files from GDrive

## Testing

- 41 tests passing, 94% coverage on `gdrive_service.py`
- New `TestDeleteFile` class (5 tests for `delete_file`/`delete_files` —
previously uncovered)
- New `test_cleanup_distribution.py` (9 tests covering fast path,
fallback, and brand code gating logic)
- Updated error handling test to verify `RuntimeError` is raised (not
swallowed) on subfolder search failure
- [x] CodeRabbit CLI review completed, 2 findings fixed

@coderabbitai ignore

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

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-27 17:35:50 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 0f5ddb0092 Fix silent Google Drive upload failures with retry + alerting (#417)
## Summary
- Added tenacity retry with connection reset to Google Drive API calls
(`get_or_create_folder`, `upload_file`, `delete_file`) to handle stale
HTTP connections on idle Cloud Run containers
- Added `distribution_warnings` field to `OrchestratorResult` and
`_handle_native_distribution()` to track non-fatal upload failures
(YouTube, Dropbox, GDrive)
- Added Pushbullet notification when distribution uploads fail, so
operator is alerted immediately
- Added backfill script (`scripts/backfill_gdrive_uploads.py`) for
affected jobs - already run successfully for 12 affected jobs
- Updated docs: LESSONS-LEARNED.md and TROUBLESHOOTING.md with GDrive
stale connection pattern

## Context
Every GDrive upload silently failed for ~1 month (64 errors, 12+
affected jobs). The root cause was the singleton `GoogleDriveService`
caching its HTTP connection, which went stale when Cloud Run containers
sat idle between jobs. The orchestrator caught all exceptions and
continued, so jobs completed with `gdrive_files: {}` and no alert was
sent.

## Test plan
- [x] 5 new retry behavior tests in `test_gdrive_service.py`
(BrokenPipeError, SSLError, give up after 3, service reset, no retry on
non-transient)
- [x] 3 new distribution warnings tests in
`test_video_worker_orchestrator.py`
- [x] All 76 affected tests pass
- [x] Full backend test suite passes
- [x] Backfill script already run successfully for all 12 affected jobs

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:47:30 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 23a8b0fb98 Fix missing CDG ZIP packages: fail-fast validation + remediation (#416)
## Summary

- **Systemic fix**: Orchestrator now validates CDG/TXT outputs after
packaging, before encoding. If `enable_cdg=True` but no CDG ZIP was
produced, the job fails immediately with a clear error instead of
silently completing without the package.
- **Remediation**: Created `scripts/regenerate_cdg.py` to regenerate and
distribute CDG/TXT packages for affected jobs (5b6aba25, 5161b069).
Packages uploaded to GCS, GDrive, and Dropbox.
- **Root cause**: Before b671b83f, `instrumental_selection: custom` had
no case in the orchestrator config builder — fell through to "Backing"
suffix, CDG generator looked for wrong filename, `FileNotFoundError` was
silently caught.

## Changes

| File | Change |
|------|--------|
| `backend/workers/video_worker_orchestrator.py` | Post-packaging
validation + LRC-missing check update |
| `backend/tests/test_video_worker_orchestrator.py` | 8 new tests in
`TestPackagingValidation` |
| `scripts/regenerate_cdg.py` | One-time remediation script (GCS +
Firestore + GDrive + Dropbox) |
| `docs/LESSONS-LEARNED.md` | Pipeline stage validation pattern |
| `docs/TROUBLESHOOTING.md` | CDG missing recovery runbook |
| `docs/README.md` | Updated recent changes |
| `pyproject.toml` | Version 0.119.6 → 0.119.7 |

## Test plan

- [x] 8 new tests in `TestPackagingValidation` (CDG fails, TXT fails,
combined CDG+TXT fails, CDG succeeds, CDG disabled, LRC missing raises
with CDG, LRC missing raises with TXT, LRC missing skips without CDG)
- [x] All 2062+ backend tests pass
- [x] Remediation script run successfully for both affected jobs
- [x] Verified CDG/TXT ZIPs in GCS, Firestore, GDrive, and Dropbox

> **CodeRabbit note**: 1 finding (unreachable `else` branch in
`_run_packaging` LRC check) — kept as defensive code since the test
`test_lrc_missing_skips_when_cdg_disabled` exercises this path directly.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:13:22 +00:00
Andrew Beveridge ☄️ 028e9f40d4 docs: add TROUBLESHOOTING.md with encoding recovery runbook (#415)
Follows up on #414 — that PR got merged before the force-push landed, so
TROUBLESHOOTING.md was missing.

- Creates `docs/TROUBLESHOOTING.md` with the encoding recovery runbook
- Trims the verbose block from CLAUDE.md down to a one-line pointer
- Adds TROUBLESHOOTING.md to the quick reference table in CLAUDE.md

Docs-only, no code changes.

<!-- @coderabbitai ignore -->
2026-02-27 12:53:45 -05:00
Andrew Beveridge ☄️ c04397d1d1 docs: add stuck encoding job recovery procedure (#414)
Adds a clear recovery procedure to CLAUDE.md for the known scenario
where a Cloud Run deployment kills a poller mid-encoding, leaving a job
stuck at `encoding` status.

**What's added:**
- Diagnosis steps (health endpoint, GCE worker status check)
- Recovery command (re-trigger video worker)
- Note that SSH restart is no longer needed since PR #413 made `/encode`
idempotent

This is purely documentation — no code changes.

<!-- @coderabbitai ignore -->

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-02-27 12:39:03 -05:00
15 changed files with 2581 additions and 125 deletions

No files matched your search

+8 -5
View File
@@ -19,6 +19,7 @@
| **Testing & code quality** | `docs/TESTING.md` |
| API reference | `docs/API.md` |
| Past learnings | `docs/LESSONS-LEARNED.md` |
| **Operational runbooks** | `docs/TROUBLESHOOTING.md` |
| **Product communication** | `docs/PRODUCT-COMMUNICATION-GUIDE.md` |
| Brand style guide | `docs/BRAND-STYLE-GUIDE.md` |
@@ -128,15 +129,17 @@ EOF
### GCE Encoding Worker
```bash
# SSH to restart service (clears in-memory job queue)
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
# Check health
# Check health (includes wheel_version)
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="curl -s http://localhost:8080/health"
# Restart service (pick up new wheel after a deploy)
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
```
For job stuck at `encoding` status, see [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md).
### What Doesn't Work
- `gcloud auth print-identity-token` - Wrong token type for internal endpoints
- Cloud Tasks without proper service account - Gets 401 from Cloud Run
+80 -23
View File
@@ -1655,6 +1655,7 @@ async def cleanup_distribution(
# Clean up Dropbox
brand_code = state_data.get('brand_code')
dropbox_path = getattr(job, 'dropbox_path', None)
dropbox_cleaned = False
if brand_code and dropbox_path:
try:
from backend.services.dropbox_service import get_dropbox_service
@@ -1664,22 +1665,11 @@ async def cleanup_distribution(
folder_name = f"{brand_code} - {base_name}"
full_path = f"{dropbox_path}/{folder_name}"
success = dropbox.delete_folder(full_path)
dropbox_cleaned = success
results["dropbox"] = {
"status": "success" if success else "failed",
"path": full_path
}
# Recycle the brand code number so it can be reused
if success:
try:
from backend.services.brand_code_service import (
BrandCodeService, get_brand_code_service
)
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
results["dropbox"]["recycled_brand_code"] = True
except (ValueError, Exception) as e:
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
results["dropbox"]["recycled_brand_code"] = False
else:
results["dropbox"] = {"status": "failed", "reason": "Dropbox credentials not configured"}
except Exception as e:
@@ -1687,25 +1677,92 @@ async def cleanup_distribution(
results["dropbox"] = {"status": "error", "error": str(e)}
# Clean up Google Drive
# Use tracked file IDs if available; otherwise fall back to searching by brand code.
# This handles old jobs where gdrive_files was not persisted (e.g., uploaded before
# file ID tracking was implemented, or when GDrive upload silently failed and a
# previous test run left files behind).
gdrive_files = state_data.get('gdrive_files')
if gdrive_files:
gdrive_folder_id = getattr(job, 'gdrive_folder_id', None)
gdrive_cleaned = False
if gdrive_files or (gdrive_folder_id and brand_code):
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
# gdrive_files is a dict like {"mp4": "file_id", "mp4_720p": "file_id", "cdg": "file_id"}
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
results["gdrive"] = {
"status": "success" if all_success else "partial",
"files": delete_results
}
file_ids: list = []
gdrive_method = None # track how files were located for response
if gdrive_files and isinstance(gdrive_files, dict):
# Fast path: delete using tracked file IDs from state_data
file_ids = [v for v in gdrive_files.values() if v]
logger.info(
f"GDrive cleanup for job {job_id}: "
f"using {len(file_ids)} tracked file IDs"
)
if not file_ids and gdrive_folder_id and brand_code:
# Fallback: search by brand code prefix in CDG/, MP4/, MP4-720p/ subfolders.
# Handles jobs where gdrive_files was not tracked (old jobs, or jobs where
# GDrive upload succeeded but file IDs were lost).
logger.info(
f"GDrive cleanup for job {job_id}: "
f"no tracked file IDs, searching by brand_code '{brand_code}'"
)
file_ids = gdrive.find_files_by_brand_code(gdrive_folder_id, brand_code)
gdrive_method = "brand_code_search"
if file_ids:
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
gdrive_cleaned = all_success
results["gdrive"] = {
"status": "success" if all_success else "partial",
"files": delete_results,
}
if gdrive_method:
results["gdrive"]["method"] = gdrive_method
else:
gdrive_cleaned = True # Nothing to delete
results["gdrive"] = {
"status": "skipped",
"reason": "no files found to delete",
}
else:
results["gdrive"] = {"status": "failed", "reason": "Google Drive credentials not configured"}
results["gdrive"] = {
"status": "failed",
"reason": "Google Drive credentials not configured",
}
except Exception as e:
logger.error(f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True)
logger.error(
f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True
)
results["gdrive"] = {"status": "error", "error": str(e)}
else:
if not gdrive_folder_id:
results["gdrive"]["reason"] = "no gdrive_folder_id on job and no tracked file IDs"
# Recycle the brand code so it can be reused — but only after GDrive is confirmed clean.
# If we recycle before GDrive cleanup, a new job could claim the same brand code and
# collide with leftover files on GDrive (duplicate brand code in public share).
if dropbox_cleaned and brand_code and gdrive_cleaned:
try:
from backend.services.brand_code_service import (
BrandCodeService, get_brand_code_service
)
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
results["dropbox"]["recycled_brand_code"] = True
logger.info(f"Recycled brand code {brand_code} after full distribution cleanup")
except (ValueError, Exception) as e:
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
results["dropbox"]["recycled_brand_code"] = False
elif dropbox_cleaned and brand_code:
logger.warning(
f"Brand code {brand_code} NOT recycled: GDrive cleanup did not confirm success "
f"(gdrive_cleaned={gdrive_cleaned}). Brand code will remain reserved to prevent "
f"collisions with leftover GDrive files."
)
# Delete the job if requested
if delete_job:
+189 -66
View File
@@ -12,13 +12,19 @@ shared with YouTube credentials if scopes include drive.file.
import json
import logging
import os
import ssl
from typing import Any, Dict, Optional
from tenacity import Retrying, stop_after_attempt, wait_exponential, retry_if_exception_type
from backend.config import get_settings
from karaoke_gen.utils import sanitize_filename
logger = logging.getLogger(__name__)
# Transient errors that indicate a stale HTTP connection (Cloud Run idle containers)
TRANSIENT_ERRORS = (BrokenPipeError, ConnectionResetError, ConnectionError, ssl.SSLError)
class GoogleDriveService:
"""Google Drive operations using native API."""
@@ -33,6 +39,11 @@ class GoogleDriveService:
self._credentials_data: Optional[Dict[str, Any]] = None
self._loaded = False
def _reset_service(self):
"""Reset the cached Drive service to force a fresh connection on next use."""
logger.info("Resetting Google Drive service connection")
self._service = None
def _load_credentials(self) -> Optional[Dict[str, Any]]:
"""Load OAuth credentials from Secret Manager."""
if self._loaded:
@@ -127,6 +138,9 @@ class GoogleDriveService:
"""
Get existing folder or create new one, return folder ID.
Retries on transient connection errors (BrokenPipeError, SSLError)
that occur when Cloud Run containers sit idle between jobs.
Args:
parent_id: Parent folder ID
folder_name: Name of folder to find or create
@@ -134,33 +148,41 @@ class GoogleDriveService:
Returns:
Folder ID
"""
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
for attempt in Retrying(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=8),
retry=retry_if_exception_type(TRANSIENT_ERRORS),
before_sleep=lambda retry_state: self._reset_service(),
reraise=True,
):
with attempt:
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
# Search for existing folder
# Escape single quotes in folder name for Google Drive API query syntax
escaped_folder_name = folder_name.replace("'", "\\'")
query = (
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = self.service.files().list(q=query, fields="files(id, name)").execute()
# Search for existing folder
# Escape single quotes in folder name for Google Drive API query syntax
escaped_folder_name = folder_name.replace("'", "\\'")
query = (
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = self.service.files().list(q=query, fields="files(id, name)").execute()
if results.get("files"):
folder_id = results["files"][0]["id"]
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
return folder_id
if results.get("files"):
folder_id = results["files"][0]["id"]
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
return folder_id
# Create folder
logger.info(f"Creating new folder '{folder_name}'")
metadata = {
"name": folder_name,
"mimeType": "application/vnd.google-apps.folder",
"parents": [parent_id],
}
folder = self.service.files().create(body=metadata, fields="id").execute()
folder_id = folder["id"]
logger.info(f"Created folder '{folder_name}': {folder_id}")
return folder_id
# Create folder
logger.info(f"Creating new folder '{folder_name}'")
metadata = {
"name": folder_name,
"mimeType": "application/vnd.google-apps.folder",
"parents": [parent_id],
}
folder = self.service.files().create(body=metadata, fields="id").execute()
folder_id = folder["id"]
logger.info(f"Created folder '{folder_name}': {folder_id}")
return folder_id
def upload_file(
self,
@@ -172,6 +194,9 @@ class GoogleDriveService:
"""
Upload a file to a specific Drive folder.
Retries on transient connection errors (BrokenPipeError, SSLError)
that occur when Cloud Run containers sit idle between jobs.
Args:
local_path: Local file path
parent_id: Parent folder ID in Google Drive
@@ -183,49 +208,57 @@ class GoogleDriveService:
"""
from googleapiclient.http import MediaFileUpload
file_size = os.path.getsize(local_path)
logger.info(
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
f"as '{filename}' to folder {parent_id}"
)
for attempt in Retrying(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=8),
retry=retry_if_exception_type(TRANSIENT_ERRORS),
before_sleep=lambda retry_state: self._reset_service(),
reraise=True,
):
with attempt:
file_size = os.path.getsize(local_path)
logger.info(
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
f"as '{filename}' to folder {parent_id}"
)
# Determine MIME type
ext = os.path.splitext(local_path)[1].lower()
mime_types = {
".mp4": "video/mp4",
".mkv": "video/x-matroska",
".zip": "application/zip",
".flac": "audio/flac",
".mp3": "audio/mpeg",
".wav": "audio/wav",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
}
mime_type = mime_types.get(ext, "application/octet-stream")
# Determine MIME type
ext = os.path.splitext(local_path)[1].lower()
mime_types = {
".mp4": "video/mp4",
".mkv": "video/x-matroska",
".zip": "application/zip",
".flac": "audio/flac",
".mp3": "audio/mpeg",
".wav": "audio/wav",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
}
mime_type = mime_types.get(ext, "application/octet-stream")
# Check for existing file with same name
if replace_existing:
# Escape single quotes in filename for Google Drive API query syntax
escaped_filename = filename.replace("'", "\\'")
query = (
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
)
results = self.service.files().list(q=query, fields="files(id)").execute()
for existing_file in results.get("files", []):
logger.info(f"Deleting existing file: {existing_file['id']}")
self.service.files().delete(fileId=existing_file["id"]).execute()
# Check for existing file with same name
if replace_existing:
# Escape single quotes in filename for Google Drive API query syntax
escaped_filename = filename.replace("'", "\\'")
query = (
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
)
results = self.service.files().list(q=query, fields="files(id)").execute()
for existing_file in results.get("files", []):
logger.info(f"Deleting existing file: {existing_file['id']}")
self.service.files().delete(fileId=existing_file["id"]).execute()
# Upload file
metadata = {"name": filename, "parents": [parent_id]}
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
# Upload file
metadata = {"name": filename, "parents": [parent_id]}
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
file_result = (
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
)
file_id = file_result["id"]
logger.info(f"Successfully uploaded '{filename}': {file_id}")
return file_id
file_result = (
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
)
file_id = file_result["id"]
logger.info(f"Successfully uploaded '{filename}': {file_id}")
return file_id
def upload_to_public_share(
self,
@@ -308,6 +341,9 @@ class GoogleDriveService:
"""
Delete a file from Google Drive.
Retries on transient connection errors (BrokenPipeError, SSLError)
that occur when Cloud Run containers sit idle between jobs.
Args:
file_id: Google Drive file ID to delete
@@ -317,9 +353,17 @@ class GoogleDriveService:
logger.info(f"Deleting Google Drive file: {file_id}")
try:
self.service.files().delete(fileId=file_id).execute()
logger.info(f"Successfully deleted file: {file_id}")
return True
for attempt in Retrying(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=8),
retry=retry_if_exception_type(TRANSIENT_ERRORS),
before_sleep=lambda retry_state: self._reset_service(),
reraise=True,
):
with attempt:
self.service.files().delete(fileId=file_id).execute()
logger.info(f"Successfully deleted file: {file_id}")
return True
except Exception as e:
# Check if it's a 404 (already deleted)
if hasattr(e, 'resp') and e.resp.status == 404:
@@ -343,6 +387,85 @@ class GoogleDriveService:
results[file_id] = self.delete_file(file_id)
return results
def find_files_by_brand_code(self, root_folder_id: str, brand_code: str) -> list[str]:
"""
Search for files in public share subfolders matching a brand code prefix.
Used as a fallback when gdrive_files is not tracked in state_data (e.g., old
jobs uploaded before file ID tracking was implemented, or jobs where GDrive
upload succeeded but file IDs were not saved due to a bug).
Searches CDG/, MP4/, MP4-720p/ subfolders for files whose name starts with
'{brand_code} - '.
Args:
root_folder_id: Root Google Drive folder ID for the public share
brand_code: Brand code prefix to search for (e.g., "NOMAD-1271")
Returns:
List of file IDs found matching the brand code
"""
found_ids = []
subfolders = ["CDG", "MP4", "MP4-720p"]
search_errors: list[Exception] = []
for subfolder in subfolders:
try:
# Find the subfolder
escaped_subfolder = subfolder.replace("'", "\\'")
query = (
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = self.service.files().list(
q=query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
if not results.get("files"):
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
continue
subfolder_id = results["files"][0]["id"]
# Search for files whose name starts with the brand code
# Use contains for efficiency, then filter by exact prefix
escaped_brand = brand_code.replace("'", "\\'")
file_query = (
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
f"and trashed=false"
)
file_results = self.service.files().list(
q=file_query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
for f in file_results.get("files", []):
if f["name"].startswith(f"{brand_code} - "):
found_ids.append(f["id"])
logger.info(
f"Found GDrive file to clean up in {subfolder}/: "
f"{f['name']} ({f['id']})"
)
except Exception as e:
logger.error(
f"Error searching for brand_code '{brand_code}' in '{subfolder}': {e}",
exc_info=True,
)
search_errors.append(e)
if search_errors:
# Raise so the caller knows the search was incomplete.
# This prevents the cleanup endpoint from treating an uncertain result
# as "GDrive is clean" and incorrectly recycling the brand code.
raise RuntimeError(
f"GDrive brand_code search incomplete: "
f"{len(search_errors)}/{len(subfolders)} subfolder(s) failed"
)
return found_ids
# Singleton instance
_gdrive_service: Optional[GoogleDriveService] = None
+381
View File
@@ -0,0 +1,381 @@
"""
Tests for the cleanup-distribution endpoint in jobs.py.
Verifies:
- GDrive cleanup uses tracked file IDs from state_data when available (fast path)
- GDrive cleanup falls back to brand_code search when gdrive_files is empty (fallback path)
- Brand code is recycled ONLY after both Dropbox AND GDrive are confirmed clean
- Brand code is NOT recycled when GDrive cleanup fails or is skipped
- Endpoint returns correct status for each distribution service
The cleanup-distribution endpoint is used by the E2E happy-path test (Step 12)
to remove test job files from YouTube, Dropbox, and Google Drive after the test.
"""
import pytest
from unittest.mock import Mock, patch, MagicMock
from fastapi.testclient import TestClient
from fastapi import FastAPI
from datetime import datetime, UTC
from backend.api.routes.jobs import router
from backend.api.dependencies import require_admin, require_auth, AuthResult, UserType
from backend.models.job import Job, JobStatus
# ─── Test App ────────────────────────────────────────────────────────────────
def get_mock_admin():
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Admin authenticated",
user_email="admin@example.com",
is_admin=True,
)
app = FastAPI()
app.include_router(router, prefix="/api")
app.dependency_overrides[require_admin] = get_mock_admin
app.dependency_overrides[require_auth] = get_mock_admin
@pytest.fixture
def client():
return TestClient(app)
# ─── Fixtures ────────────────────────────────────────────────────────────────
def _make_job(
*,
brand_code="NOMAD-1271",
gdrive_files=None,
gdrive_folder_id="root-folder-id",
dropbox_path="/Tracks-PublicShare",
artist="piri",
title="dog",
):
"""Make a mock Job in COMPLETE state with the given distribution data."""
job = Mock(spec=Job)
job.job_id = "test-job-id"
job.status = JobStatus.COMPLETE
job.artist = artist
job.title = title
job.dropbox_path = dropbox_path
job.gdrive_folder_id = gdrive_folder_id
job.state_data = {
"brand_code": brand_code,
"gdrive_files": gdrive_files if gdrive_files is not None else {},
}
return job
# ─── GDrive Cleanup — Fast Path (tracked file IDs) ───────────────────────────
class TestCleanupDistributionGDriveTrackedFileIDs:
"""GDrive cleanup uses tracked file IDs from state_data when available."""
def test_gdrive_cleanup_uses_tracked_file_ids(self, client):
"""When gdrive_files has file IDs, delete_files is called with those IDs."""
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.delete_files.return_value = {"file-id-mp4": True, "file-id-cdg": True}
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
# Should have used the tracked file IDs (fast path)
mock_gdrive.delete_files.assert_called_once_with(["file-id-mp4", "file-id-cdg"])
# Should NOT have searched by brand code
mock_gdrive.find_files_by_brand_code.assert_not_called()
assert data["gdrive"]["status"] == "success"
def test_gdrive_cleanup_reports_partial_when_some_deletes_fail(self, client):
"""When some file deletes fail, status is 'partial'."""
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.delete_files.return_value = {
"file-id-mp4": True,
"file-id-cdg": False, # This one failed
}
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
assert data["gdrive"]["status"] == "partial"
# ─── GDrive Cleanup — Fallback Path (brand_code search) ──────────────────────
class TestCleanupDistributionGDriveFallback:
"""GDrive cleanup searches by brand_code when gdrive_files is empty."""
def test_falls_back_to_brand_code_search_when_gdrive_files_empty(self, client):
"""When gdrive_files={}, search GDrive by brand_code and delete found files."""
job = _make_job(gdrive_files={}) # Empty — simulates old jobs / silently-failed uploads
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
# find_files_by_brand_code returns file IDs found by searching GDrive
mock_gdrive.find_files_by_brand_code.return_value = ["old-file-id-cdg", "old-file-id-mp4"]
mock_gdrive.delete_files.return_value = {
"old-file-id-cdg": True,
"old-file-id-mp4": True,
}
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
# Should have searched by brand code (fallback path)
mock_gdrive.find_files_by_brand_code.assert_called_once_with(
"root-folder-id", "NOMAD-1271"
)
# Should have deleted the found files
mock_gdrive.delete_files.assert_called_once()
assert data["gdrive"]["status"] == "success"
def test_falls_back_to_brand_code_search_when_gdrive_files_none(self, client):
"""When gdrive_files not in state_data (old job), search by brand_code."""
job = _make_job(gdrive_files=None)
job.state_data = {"brand_code": "NOMAD-1271"} # No gdrive_files key at all
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.find_files_by_brand_code.return_value = ["legacy-file-id"]
mock_gdrive.delete_files.return_value = {"legacy-file-id": True}
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
mock_gdrive.find_files_by_brand_code.assert_called_once()
def test_reports_skipped_when_no_files_found_by_brand_code(self, client):
"""When brand_code search finds nothing, GDrive status is 'skipped'."""
job = _make_job(gdrive_files={})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.find_files_by_brand_code.return_value = [] # Nothing found
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
assert data["gdrive"]["status"] == "skipped"
assert "no files found" in data["gdrive"]["reason"]
# ─── Brand Code Recycling — Gated on GDrive Success ──────────────────────────
class TestCleanupDistributionBrandCodeRecycling:
"""Brand code is recycled only after BOTH Dropbox AND GDrive are confirmed clean."""
def test_brand_code_recycled_when_both_dropbox_and_gdrive_cleaned(self, client):
"""Brand code is recycled when Dropbox delete succeeds and GDrive cleanup succeeds."""
job = _make_job(gdrive_files={"cdg": "file-id"})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True # Dropbox success
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.delete_files.return_value = {"file-id": True} # GDrive success
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.BrandCodeService") as mock_bcs_class, \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
# Brand code should be recycled
mock_brand_service.recycle_brand_code.assert_called_once()
assert data["dropbox"].get("recycled_brand_code") is True
def test_brand_code_not_recycled_when_gdrive_cleanup_partial(self, client):
"""Brand code is NOT recycled when GDrive delete only partially succeeded.
If GDrive still has files with this brand code, recycling would allow a new
job to get the same brand code, creating a duplicate in the public share.
"""
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True # Dropbox success
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.delete_files.return_value = {
"file-id-mp4": True,
"file-id-cdg": False, # CDG file still on GDrive
}
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
# Brand code should NOT be recycled because GDrive still has a file
mock_brand_service.recycle_brand_code.assert_not_called()
# recycled_brand_code key should be absent (recycling never attempted)
assert "recycled_brand_code" not in data.get("dropbox", {})
def test_brand_code_not_recycled_when_gdrive_not_configured(self, client):
"""Brand code is NOT recycled when GDrive is not configured.
Without GDrive credentials, we cannot confirm that GDrive was cleaned.
A previous upload may have succeeded (e.g., different credentials rotation).
"""
job = _make_job(gdrive_files={"cdg": "file-id"})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = False # GDrive not configured
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
# Brand code NOT recycled — GDrive might still have files
mock_brand_service.recycle_brand_code.assert_not_called()
def test_brand_code_recycled_when_gdrive_finds_nothing_to_delete(self, client):
"""Brand code IS recycled when GDrive search finds nothing (already clean)."""
job = _make_job(gdrive_files={}) # Empty — no tracked IDs
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.find_files_by_brand_code.return_value = [] # GDrive already clean
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.BrandCodeService") as mock_bcs_class, \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
# GDrive was confirmed clean (nothing found), so brand code IS recycled
mock_brand_service.recycle_brand_code.assert_called_once()
assert data["dropbox"].get("recycled_brand_code") is True
+433 -5
View File
@@ -9,6 +9,7 @@ These tests mock the Google API client and Secret Manager to verify:
"""
import json
import os
import ssl
import pytest
from unittest.mock import Mock, MagicMock, patch
@@ -501,24 +502,451 @@ class TestUploadToPublicShare:
assert len(result) == 1
class TestRetryBehavior:
"""Test retry behavior for transient connection errors."""
@patch("backend.services.gdrive_service.get_settings")
def test_retries_on_broken_pipe(self, mock_get_settings):
"""Test that BrokenPipeError triggers retry and succeeds on second attempt."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
# First call raises BrokenPipeError, second succeeds
mock_list_result.execute.side_effect = [
BrokenPipeError("[Errno 32] Broken pipe"),
{"files": [{"id": "folder-123", "name": "MP4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to clear but re-set the mock (avoid real OAuth)
def mock_reset():
service._service = mock_drive
service._reset_service = mock_reset
folder_id = service.get_or_create_folder("parent-123", "MP4")
assert folder_id == "folder-123"
assert mock_list_result.execute.call_count == 2
@patch("backend.services.gdrive_service.get_settings")
def test_gives_up_after_3_attempts(self, mock_get_settings):
"""Test that 3 consecutive failures raises the exception."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = BrokenPipeError("[Errno 32] Broken pipe")
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to re-set the mock (avoid real OAuth)
service._reset_service = lambda: setattr(service, '_service', mock_drive)
with pytest.raises(BrokenPipeError):
service.get_or_create_folder("parent-123", "MP4")
assert mock_list_result.execute.call_count == 3
@patch("backend.services.gdrive_service.get_settings")
def test_service_reset_on_retry(self, mock_get_settings):
"""Test that _service is reset to None between retry attempts."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
BrokenPipeError("[Errno 32] Broken pipe"),
{"files": [{"id": "folder-123", "name": "MP4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to track calls but still do the reset
original_reset = service._reset_service
reset_calls = []
def tracked_reset():
reset_calls.append(True)
original_reset()
# Re-set mock service so the retry works
service._service = mock_drive
service._reset_service = tracked_reset
folder_id = service.get_or_create_folder("parent-123", "MP4")
assert folder_id == "folder-123"
assert len(reset_calls) == 1 # Reset called once between attempt 1 and 2
@patch("backend.services.gdrive_service.get_settings")
def test_retries_on_ssl_error(self, mock_get_settings):
"""Test that SSLError triggers retry."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
ssl.SSLError("SSL: UNEXPECTED_EOF_WHILE_READING"),
{"files": [{"id": "folder-123", "name": "MP4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to re-set the mock (avoid real OAuth)
service._reset_service = lambda: setattr(service, '_service', mock_drive)
folder_id = service.get_or_create_folder("parent-123", "MP4")
assert folder_id == "folder-123"
assert mock_list_result.execute.call_count == 2
@patch("backend.services.gdrive_service.get_settings")
def test_no_retry_on_non_transient_error(self, mock_get_settings):
"""Test that non-transient errors are not retried."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = ValueError("bad value")
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
with pytest.raises(ValueError):
service.get_or_create_folder("parent-123", "MP4")
assert mock_list_result.execute.call_count == 1
class TestDeleteFile:
"""Test delete_file and delete_files methods."""
def _make_service(self, mock_get_settings):
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
return service
@patch("backend.services.gdrive_service.get_settings")
def test_delete_file_success(self, mock_get_settings):
"""Successful delete returns True."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_delete = Mock()
mock_delete.execute.return_value = None
mock_files_api.delete.return_value = mock_delete
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.delete_file("file-id-123")
assert result is True
mock_files_api.delete.assert_called_once_with(fileId="file-id-123")
@patch("backend.services.gdrive_service.get_settings")
def test_delete_file_returns_true_on_404(self, mock_get_settings):
"""404 (already deleted) returns True — idempotent cleanup."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_delete = Mock()
not_found = Exception("File not found")
not_found.resp = Mock()
not_found.resp.status = 404
mock_delete.execute.side_effect = not_found
mock_files_api.delete.return_value = mock_delete
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.delete_file("already-gone-id")
assert result is True
@patch("backend.services.gdrive_service.get_settings")
def test_delete_file_returns_false_on_error(self, mock_get_settings):
"""Non-404 errors return False."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_delete = Mock()
mock_delete.execute.side_effect = Exception("Permission denied")
mock_files_api.delete.return_value = mock_delete
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.delete_file("restricted-file")
assert result is False
@patch("backend.services.gdrive_service.get_settings")
def test_delete_files_calls_delete_file_for_each_id(self, mock_get_settings):
"""delete_files returns a per-ID success dict."""
service = self._make_service(mock_get_settings)
# Stub delete_file: first ID succeeds, second fails
results_by_id = {"id-1": True, "id-2": False}
service.delete_file = lambda fid: results_by_id[fid]
result = service.delete_files(["id-1", "id-2"])
assert result == {"id-1": True, "id-2": False}
@patch("backend.services.gdrive_service.get_settings")
def test_delete_files_empty_list(self, mock_get_settings):
"""delete_files with empty list returns empty dict."""
service = self._make_service(mock_get_settings)
result = service.delete_files([])
assert result == {}
class TestFindFilesByBrandCode:
"""Test find_files_by_brand_code method — used as fallback in cleanup-distribution."""
def _make_service(self, mock_get_settings):
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
service._loaded = True
service._credentials_data = {
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
}
return service
def _attach_mock_drive(self, service, list_side_effects):
"""Attach a mock Drive client whose files().list().execute() returns given values."""
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = list_side_effects
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
return mock_files_api
@patch("backend.services.gdrive_service.get_settings")
def test_finds_files_in_all_subfolders(self, mock_get_settings):
"""Test finds matching files across CDG/, MP4/, MP4-720p/ subfolders."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
# Responses: for each subfolder: (1) find subfolder, (2) search for files
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]}, # CDG subfolder found
{"files": [{"id": "cdg-file-1", "name": "NOMAD-1271 - piri - dog.zip"}]},
{"files": [{"id": "mp4-folder"}]}, # MP4 subfolder found
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
{"files": [{"id": "mp4720-folder"}]}, # MP4-720p subfolder found
{"files": [{"id": "mp4720-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert len(result) == 3
assert "cdg-file-1" in result
assert "mp4-file-1" in result
assert "mp4720-file-1" in result
@patch("backend.services.gdrive_service.get_settings")
def test_returns_empty_when_subfolder_not_found(self, mock_get_settings):
"""Test returns empty list when public share subfolders don't exist."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
# All subfolder lookups return empty
mock_list_result.execute.return_value = {"files": []}
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == []
@patch("backend.services.gdrive_service.get_settings")
def test_filters_by_exact_brand_code_prefix(self, mock_get_settings):
"""Test only returns files whose name starts with '{brand_code} - '."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]},
{
"files": [
{"id": "match-id", "name": "NOMAD-1271 - piri - dog.zip"},
# This one contains NOMAD-1271 but doesn't START with it — should be excluded
{"id": "no-match-id", "name": "BONUS-NOMAD-1271 - other.zip"},
]
},
{"files": []}, # MP4 subfolder not found
{"files": []}, # MP4-720p subfolder not found
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == ["match-id"]
@patch("backend.services.gdrive_service.get_settings")
def test_returns_empty_when_no_files_match_brand_code(self, mock_get_settings):
"""Test returns empty list when subfolder exists but has no matching files."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]},
{"files": [{"id": "other-id", "name": "NOMAD-1300 - someone else.zip"}]},
{"files": []}, # MP4 not found
{"files": []}, # MP4-720p not found
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == []
@patch("backend.services.gdrive_service.get_settings")
def test_raises_after_all_subfolders_when_any_error(self, mock_get_settings):
"""When any subfolder search errors, raises RuntimeError after processing all subfolders.
This prevents the cleanup endpoint from treating an incomplete search result
as "GDrive is clean" and incorrectly recycling the brand code.
"""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]},
Exception("API error"), # CDG file search fails
{"files": [{"id": "mp4-folder"}]},
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
{"files": [{"id": "mp4720-folder"}]},
{"files": []},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
# Should raise after processing all subfolders — an incomplete search must not
# be silently treated as "nothing found" by the caller
with pytest.raises(RuntimeError, match="search incomplete"):
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
class TestGetGdriveService:
"""Test get_gdrive_service singleton."""
@patch("backend.services.gdrive_service.get_settings")
def test_get_gdrive_service_singleton(self, mock_get_settings):
"""Test get_gdrive_service returns singleton instance."""
from backend.services.gdrive_service import get_gdrive_service
import backend.services.gdrive_service as gdrive_module
# Reset singleton
gdrive_module._gdrive_service = None
mock_settings = Mock()
mock_settings.get_secret.return_value = None
mock_get_settings.return_value = mock_settings
service1 = get_gdrive_service()
service2 = get_gdrive_service()
assert service1 is service2
+293 -7
View File
@@ -250,8 +250,28 @@ class TestVideoWorkerOrchestratorPackaging:
"""Test packaging stage."""
@pytest.mark.asyncio
async def test_run_packaging_no_lrc(self):
"""Test packaging stage with no LRC file."""
async def test_run_packaging_no_lrc_cdg_disabled(self):
"""Test packaging stage with no LRC file and CDG disabled skips silently."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=False,
lrc_file_path=None,
)
orchestrator = VideoWorkerOrchestrator(config)
# Should not raise, just skip
await orchestrator._run_packaging()
assert orchestrator.result.final_karaoke_cdg_zip is None
@pytest.mark.asyncio
async def test_run_packaging_no_lrc_cdg_enabled_raises(self):
"""Test packaging stage raises when CDG enabled but no LRC file."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
@@ -264,10 +284,8 @@ class TestVideoWorkerOrchestratorPackaging:
)
orchestrator = VideoWorkerOrchestrator(config)
# Should not raise, just skip
await orchestrator._run_packaging()
assert orchestrator.result.final_karaoke_cdg_zip is None
with pytest.raises(RuntimeError, match="LRC file not available"):
await orchestrator._run_packaging()
@pytest.mark.asyncio
async def test_run_packaging_cdg(self):
@@ -368,6 +386,209 @@ class TestVideoWorkerOrchestratorPackaging:
"countdown_padding_seconds must be passed for CDG timestamp adjustment"
class TestPackagingValidation:
"""Test CDG/TXT packaging validation checks.
These tests verify that the orchestrator fails fast when CDG/TXT
generation is enabled but fails, rather than silently proceeding
to expensive encoding. This prevents jobs from completing without
their requested CDG/TXT packages.
Added after jobs 5b6aba25 and 5161b069 completed with enable_cdg=True
but no CDG ZIP was produced due to a FileNotFoundError being silently caught.
"""
@pytest.mark.asyncio
async def test_cdg_validation_fails_when_enabled_but_not_produced(self):
"""Test that orchestrator raises when CDG enabled but not produced."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
)
orchestrator = VideoWorkerOrchestrator(config)
# Mock _run_packaging to NOT set result.final_karaoke_cdg_zip (simulates failure)
async def mock_packaging():
pass # CDG generation "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
assert result.success is False
assert "CDG generation was enabled but failed" in result.error_message
mock_encoding.assert_not_called() # Should not reach encoding
@pytest.mark.asyncio
async def test_txt_validation_fails_when_enabled_but_not_produced(self):
"""Test that orchestrator raises when TXT enabled but not produced."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_txt=True,
)
orchestrator = VideoWorkerOrchestrator(config)
async def mock_packaging():
pass # TXT generation "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
assert result.success is False
assert "TXT generation was enabled but failed" in result.error_message
mock_encoding.assert_not_called()
@pytest.mark.asyncio
async def test_pipeline_succeeds_when_cdg_disabled(self):
"""Test that pipeline succeeds normally when CDG is not enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=False,
enable_txt=False,
)
orchestrator = VideoWorkerOrchestrator(config)
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_pkg, \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
result = await orchestrator.run()
assert result.success is True
mock_pkg.assert_not_called() # Packaging skipped entirely
@pytest.mark.asyncio
async def test_cdg_validation_passes_when_cdg_produced(self):
"""Test that validation passes when CDG is successfully produced."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
)
orchestrator = VideoWorkerOrchestrator(config)
async def mock_packaging_success():
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_success), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
result = await orchestrator.run()
assert result.success is True
@pytest.mark.asyncio
async def test_both_cdg_and_txt_validation_fail_together(self):
"""Test that orchestrator catches CDG failure when both CDG and TXT enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
enable_txt=True,
)
orchestrator = VideoWorkerOrchestrator(config)
async def mock_packaging():
pass # Both CDG and TXT "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
assert result.success is False
# CDG validation is checked first
assert "CDG generation was enabled but failed" in result.error_message
mock_encoding.assert_not_called()
@pytest.mark.asyncio
async def test_lrc_missing_raises_when_cdg_enabled(self):
"""Test that missing LRC file raises when CDG is enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
lrc_file_path="/nonexistent/path.lrc",
)
orchestrator = VideoWorkerOrchestrator(config)
with pytest.raises(RuntimeError, match="LRC file not available"):
await orchestrator._run_packaging()
@pytest.mark.asyncio
async def test_lrc_missing_raises_when_txt_enabled(self):
"""Test that missing LRC file raises when TXT is enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_txt=True,
lrc_file_path=None,
)
orchestrator = VideoWorkerOrchestrator(config)
with pytest.raises(RuntimeError, match="LRC file not available"):
await orchestrator._run_packaging()
@pytest.mark.asyncio
async def test_lrc_missing_skips_when_cdg_disabled(self):
"""Test that missing LRC file just skips packaging when CDG/TXT disabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=False,
enable_txt=False,
lrc_file_path=None,
)
orchestrator = VideoWorkerOrchestrator(config)
# Should not raise, just skip
await orchestrator._run_packaging()
assert orchestrator.result.final_karaoke_cdg_zip is None
class TestVideoWorkerOrchestratorEncoding:
"""Test encoding stage."""
@@ -772,8 +993,12 @@ class TestVideoWorkerOrchestratorFullPipeline:
)
orchestrator = VideoWorkerOrchestrator(config)
# Mock packaging to set CDG result (validation requires it when enable_cdg=True)
async def mock_packaging_with_result():
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
# Mock all stages
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_packaging, \
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_with_result) as mock_packaging, \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding, \
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock) as mock_org, \
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock) as mock_dist, \
@@ -1287,3 +1512,64 @@ class TestOrchestratorCountdownPadding:
assert captured_input is not None, "encode() should have been called"
assert captured_input.options.get("countdown_padding_seconds") == 3.0, \
"Orchestrator must pass countdown_padding_seconds in EncodingInput.options"
class TestDistributionWarnings:
"""Test distribution_warnings tracking in OrchestratorResult."""
def test_result_has_distribution_warnings_field(self):
"""Test that OrchestratorResult has distribution_warnings as empty list by default."""
result = OrchestratorResult(success=True)
assert result.distribution_warnings == []
@pytest.mark.asyncio
async def test_gdrive_failure_populates_warnings(self):
"""Test that Google Drive upload failure populates distribution_warnings."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
gdrive_folder_id="folder-123",
)
orchestrator = VideoWorkerOrchestrator(config)
orchestrator.result.brand_code = "NOMAD-0001"
with patch("backend.services.gdrive_service.get_gdrive_service") as mock_get:
mock_gdrive = MagicMock()
mock_gdrive.is_configured = True
mock_gdrive.upload_to_public_share.side_effect = Exception("Connection refused")
mock_get.return_value = mock_gdrive
await orchestrator._upload_to_gdrive()
assert len(orchestrator.result.distribution_warnings) == 1
assert "Google Drive upload failed" in orchestrator.result.distribution_warnings[0]
@pytest.mark.asyncio
async def test_dropbox_failure_populates_warnings(self):
"""Test that Dropbox upload failure populates distribution_warnings."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
dropbox_path="/Public Share",
)
orchestrator = VideoWorkerOrchestrator(config)
orchestrator.result.brand_code = "NOMAD-0001"
with patch("backend.services.dropbox_service.get_dropbox_service") as mock_get:
mock_dropbox = MagicMock()
mock_dropbox.is_configured = True
mock_dropbox.upload_folder.side_effect = Exception("Auth expired")
mock_get.return_value = mock_dropbox
await orchestrator._upload_to_dropbox()
assert len(orchestrator.result.distribution_warnings) == 1
assert "Dropbox upload failed" in orchestrator.result.distribution_warnings[0]
+77 -17
View File
@@ -339,15 +339,26 @@ async def generate_video_orchestrated(job_id: str) -> bool:
# Store result metadata in job BEFORE transitioning to COMPLETE
# This ensures youtube_url is available when completion email is sent
logger.info(f"[job:{job_id}] Video generation complete")
job_manager.update_job(job_id, {
'state_data': {
**job.state_data,
'brand_code': result.brand_code,
'youtube_url': result.youtube_url,
'dropbox_link': result.dropbox_link,
'gdrive_files': result.gdrive_files,
}
})
state_update = {
**job.state_data,
'brand_code': result.brand_code,
'youtube_url': result.youtube_url,
'dropbox_link': result.dropbox_link,
'gdrive_files': result.gdrive_files,
}
if result.distribution_warnings:
state_update['distribution_warnings'] = result.distribution_warnings
job_manager.update_job(job_id, {'state_data': state_update})
# Send Pushbullet alert if any distribution uploads failed
if result.distribution_warnings:
_send_distribution_warning_notification(
job_id=job_id,
artist=job.artist,
title=job.title,
warnings=result.distribution_warnings,
settings=settings,
)
# Mark job as complete (triggers completion email with youtube_url now available)
job_manager.transition_to_state(
@@ -841,6 +852,7 @@ async def _handle_native_distribution(
job_log.warning(f"Dropbox SDK not installed: {e}")
except Exception as e:
job_log.error(f"Native Dropbox upload failed: {e}", exc_info=True)
result.setdefault('distribution_warnings', []).append(f"Dropbox upload failed: {e}")
# Don't fail the job - distribution is optional
# Upload to Google Drive using native API
@@ -884,6 +896,7 @@ async def _handle_native_distribution(
job_log.warning(f"Google API packages not installed: {e}")
except Exception as e:
job_log.error(f"Native Google Drive upload failed: {e}", exc_info=True)
result.setdefault('distribution_warnings', []).append(f"Google Drive upload failed: {e}")
# Don't fail the job - distribution is optional
elif existing_gdrive_files:
job_log.info(f"Skipping Google Drive upload - orchestrator already uploaded {len(existing_gdrive_files)} files")
@@ -891,17 +904,64 @@ async def _handle_native_distribution(
# Update job state_data with brand code and links
if brand_code or result.get('dropbox_link') or result.get('gdrive_files'):
try:
job_manager.update_job(job_id, {
'state_data': {
**job.state_data,
'brand_code': brand_code,
'dropbox_link': result.get('dropbox_link'),
'gdrive_files': result.get('gdrive_files'),
}
})
state_update = {
**job.state_data,
'brand_code': brand_code,
'dropbox_link': result.get('dropbox_link'),
'gdrive_files': result.get('gdrive_files'),
}
if result.get('distribution_warnings'):
state_update['distribution_warnings'] = result['distribution_warnings']
job_manager.update_job(job_id, {'state_data': state_update})
except Exception as e:
job_log.warning(f"Failed to update job state_data: {e}")
# Send Pushbullet alert if any distribution uploads failed
if result.get('distribution_warnings'):
_send_distribution_warning_notification(
job_id=job_id,
artist=job.artist,
title=job.title,
warnings=result['distribution_warnings'],
settings=settings,
)
def _send_distribution_warning_notification(
job_id: str,
artist: str,
title: str,
warnings: list[str],
settings=None,
) -> None:
"""Send Pushbullet notification when distribution uploads fail."""
try:
if settings is None:
settings = get_settings()
api_key = settings.get_secret("pushbullet-api-key")
if not api_key:
logger.warning("Pushbullet API key not found, skipping distribution warning notification")
return
import requests as req
push_title = f"Distribution Warning: {artist} - {title}"
body = f"Job {job_id} completed but {len(warnings)} upload(s) failed:\n\n"
body += "\n".join(f" - {w}" for w in warnings)
resp = req.post(
"https://api.pushbullet.com/v2/pushes",
headers={"Access-Token": api_key, "Content-Type": "application/json"},
json={"type": "note", "title": push_title, "body": body},
timeout=10,
)
if resp.ok:
logger.info(f"[job:{job_id}] Distribution warning notification sent via Pushbullet")
else:
logger.warning(f"[job:{job_id}] Pushbullet notification failed: {resp.status_code} {resp.text}")
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to send Pushbullet notification: {e}")
def _validate_prerequisites(job) -> bool:
"""Validate that all prerequisites are met for video generation."""
@@ -109,6 +109,9 @@ class OrchestratorResult:
dropbox_link: Optional[str] = None
gdrive_files: Optional[Dict[str, str]] = field(default_factory=dict)
# Distribution warnings (non-fatal upload failures)
distribution_warnings: List[str] = field(default_factory=list)
# Timing
encoding_time_seconds: Optional[float] = None
total_time_seconds: Optional[float] = None
@@ -228,6 +231,18 @@ class VideoWorkerOrchestrator:
if self.config.enable_cdg or self.config.enable_txt:
await self._run_packaging()
# Validate required packaging outputs before expensive encoding
if self.config.enable_cdg and not self.result.final_karaoke_cdg_zip:
raise RuntimeError(
"CDG generation was enabled but failed. "
"Check worker logs for CDG-related errors."
)
if self.config.enable_txt and not self.result.final_karaoke_txt_zip:
raise RuntimeError(
"TXT generation was enabled but failed. "
"Check worker logs for TXT-related errors."
)
# Stage 2: Encoding
await self._run_encoding()
@@ -259,6 +274,10 @@ class VideoWorkerOrchestrator:
self.job_log.info("Starting packaging stage (CDG/TXT)")
if not self.config.lrc_file_path or not os.path.isfile(self.config.lrc_file_path):
if self.config.enable_cdg or self.config.enable_txt:
raise RuntimeError(
f"CDG/TXT generation enabled but LRC file not available: {self.config.lrc_file_path}"
)
self.job_log.warning("No LRC file available, skipping CDG/TXT packaging")
return
@@ -587,6 +606,7 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.error(f"YouTube upload failed: {e}")
self.result.distribution_warnings.append(f"YouTube upload failed: {e}")
# Don't fail the pipeline - YouTube is optional
async def _upload_to_dropbox(self):
@@ -623,6 +643,7 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.error(f"Dropbox upload failed: {e}")
self.result.distribution_warnings.append(f"Dropbox upload failed: {e}")
# Don't fail the pipeline - Dropbox is optional
async def _upload_to_gdrive(self):
@@ -659,6 +680,7 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.error(f"Google Drive upload failed: {e}")
self.result.distribution_warnings.append(f"Google Drive upload failed: {e}")
# Don't fail the pipeline - GDrive is optional
async def _run_notifications(self):
+32
View File
@@ -30,6 +30,17 @@ When two sequential human review steps can be combined into one, do it. We origi
## Common Gotchas
### Gate Resource Recycling on Full Cleanup Confirmation (Feb 2026)
**What happened**: Brand code NOMAD-1271 was recycled and reused for a real song while old E2E test job files still existed in Google Drive, creating a duplicate in the public share.
**Root causes**:
1. `if gdrive_files:` skips cleanup when `gdrive_files = {}` (empty dict is falsy) — any falsy check on a collection will silently skip work
2. Brand code recycled after Dropbox cleanup success, *before* confirming GDrive was clean — partial cleanup allowed resource reuse with orphaned files
**Fix**: Use `if gdrive_files is not None` (or check explicitly). Gate resource recycling on **all** cleanup steps succeeding, not just the first one. When a resource has been distributed to N places, it's only safe to recycle when all N locations are confirmed clean.
**Pattern**: Treat resource IDs (brand codes, sequential IDs) like distributed transactions — either all distribution points are cleaned, or the ID stays reserved.
### Fail Fast, Don't Fall Back
Silent fallbacks hide configuration errors. When critical configuration is missing (themes, credentials, etc.), raise clear errors instead of falling back to defaults. Better to fail loudly during testing than silently produce incorrect output in production. Example: Theme validation (v0.109.0) now raises `ValueError` on incomplete themes instead of merging with defaults. This ensures all cloud jobs use complete, explicit themes with no silent degradation.
@@ -58,6 +69,15 @@ When multiple code paths create jobs (file upload, audio search, webhooks), use
**Pattern**: When a function can fail, prefer exceptions over boolean returns. Silent failures accumulate into production bugs. Use centralized helpers for multi-step operations (state change + side effects) to prevent divergent implementations.
### Validate Pipeline Stage Outputs Before Proceeding (Feb 2026)
**What happened**: Jobs 5b6aba25 and 5161b069 completed with `enable_cdg=True` but no CDG ZIP was produced. The orchestrator silently caught a `FileNotFoundError` during CDG generation and proceeded to 11+ minutes of GPU encoding, distribution, and notifications — all for an incomplete output.
**Root cause**: CDG generation failed because `instrumental_selection: custom` had no case in the filename construction (fell through to "Backing" suffix). The `FileNotFoundError` was caught by a broad `except Exception` that just logged and continued, since "CDG is optional."
**Fix**: Add validation gates between pipeline stages. After packaging completes but before expensive encoding begins, verify that all enabled outputs were actually produced. If `enable_cdg=True` but no CDG ZIP exists, raise `RuntimeError` immediately. This fails fast, saves encoding costs, and makes the error visible.
**Pattern**: When a pipeline stage produces optional outputs that were explicitly requested, validate their existence before proceeding to the next stage. "Optional" means "can be disabled," not "can silently fail when enabled."
### Fix Both Sides of Dual Code Paths
When fixing a bug in a system with multiple code paths (e.g., legacy vs orchestrator, local vs cloud), verify ALL paths are fixed. PR #271 fixed the GCE worker to READ `instrumental_selection` but only checked the legacy path which was already SENDING it. The orchestrator path (production default) wasn't sending it. **Pattern**: If a component receives config from multiple callers, check ALL callers when fixing the receiving side. Write integration tests that cover each path.
@@ -213,6 +233,18 @@ When deferring processing from one worker to another, you MUST update the job st
### Google Drive Query Escaping
Escape special chars in Google Drive API queries: `'` → `\'`, `\` → `\\\\`.
### Google Drive Stale Connection on Cloud Run (Feb 2026)
**What happened**: Every GDrive upload silently failed for ~1 month (64 errors, 12+ jobs). Errors: `[Errno 32] Broken pipe` or `[SSL: UNEXPECTED_EOF_WHILE_READING]`. Jobs completed with `gdrive_files: {}` and no alert was sent.
**Root cause**: The singleton `GoogleDriveService` caches its HTTP connection. When Cloud Run containers sit idle between jobs, the underlying TCP connection goes stale. The next API call hits a dead socket. The orchestrator catches all exceptions in distribution and continues silently.
**Fix** (v0.119.7):
1. Added tenacity retry with `_reset_service()` (sets `self._service = None` to force fresh connection) on transient errors (`BrokenPipeError`, `ConnectionResetError`, `ssl.SSLError`)
2. Added `distribution_warnings` field to `OrchestratorResult` to track non-fatal upload failures
3. Added Pushbullet notification when distribution uploads fail, so operator is alerted immediately
**Pattern**: Any singleton service that caches HTTP connections should have retry logic with connection reset for stale connection errors. Cloud Run containers can idle for minutes between requests, killing keep-alive connections. Also, never silently swallow distribution failures - always track and alert on them.
### FFmpeg Path Escaping
For subprocess without shell, FFmpeg filter paths need: apostrophes escaped as `'\\''`, special chars as `\\[char]`.
+5 -1
View File
@@ -34,7 +34,7 @@
## Known Issues
- CDG format generation requires additional style configuration
(No known issues)
## Pending Work
@@ -42,6 +42,10 @@
## Recent Changes
- **GDrive Cleanup Robustness + Brand Code Race Fix** (2026-02-27): Fixed duplicate brand codes appearing in the public Google Drive share after the daily E2E test (NOMAD-1271 appearing for both the test job "piri - dog" and real song "Hot Mulligan - Pop Shuvit"). **Root causes**: (1) `if gdrive_files:` was falsy for empty dict `{}` — when GDrive upload silently failed (pre-PR #417), the entire GDrive cleanup block was skipped, (2) Brand code was recycled immediately after Dropbox cleanup succeeded, without confirming GDrive was also clean — a new job could claim the recycled code while old GDrive files still existed. **Fixes**: Added `find_files_by_brand_code()` fallback to `GoogleDriveService` that searches CDG/MP4/MP4-720p subfolders by brand code prefix when tracked file IDs aren't available. `cleanup-distribution` endpoint now: (a) uses tracked file IDs (fast path) or falls back to brand_code search, (b) only recycles the brand code after **both** Dropbox AND GDrive are confirmed clean. Added `scripts/cleanup_test_job_gdrive.py` remediation script. Added 14 new tests (94% coverage on gdrive_service.py).
- **CDG Packaging Fail-Fast Validation** (2026-02-27): Fixed silent CDG generation failures where jobs completed with `enable_cdg=True` but no CDG ZIP was produced. **Root cause**: Jobs 5b6aba25 and 5161b069 had `instrumental_selection: custom` but before commit b671b83f, the orchestrator had no `custom` case — it fell through to `"Backing"` suffix. The CDG generator then hit a `FileNotFoundError` looking for the wrong filename, which was silently caught. **Fix**: (1) Orchestrator now validates CDG/TXT outputs after packaging stage and before encoding — if `enable_cdg=True` but no CDG ZIP was produced, the pipeline fails fast instead of silently continuing to expensive encoding, (2) Missing LRC file now raises when CDG/TXT is enabled instead of silently skipping, (3) Added `scripts/regenerate_cdg.py` remediation script for affected jobs. Removed "CDG requires additional style configuration" known issue (the nomad theme has complete CDG styles). Added 7 new tests for validation logic.
- **GCE Encoding Pipeline Resilience** (2026-02-26): Made encoding pipeline resilient to Cloud Run deployment interruptions. A deployment killed a poller mid-encoding, leaving job a03ad39c permanently stuck at `encoding` status. Three fixes: (1) GCE worker `/encode` endpoint now idempotent — returns cached results for completed jobs, allows retry on failure, returns status for in-progress (previously hard 409 reject), (2) `encoding_service.py` handles cached/in_progress responses and falls back to status check on 409, (3) Health service detects jobs stuck in `encoding` >50 min. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#resilient-remote-worker-interactions-feb-2026).
- **Private (Non-Published) Tracks** (2026-02-24): Added `is_private` flag on jobs for private/non-published track production. Private jobs upload to Dropbox `Tracks-NonPublished` folder with `NOMADNP` brand prefix, skip YouTube and Google Drive entirely, and send completion emails without the YouTube section. Available as a checkbox on all job creation tabs and as an admin toggle (auto-deletes outputs when toggling a completed job to private). See [archive/2026-02-24-private-tracks-plan.md](archive/2026-02-24-private-tracks-plan.md).
+94
View File
@@ -0,0 +1,94 @@
# Troubleshooting
Operational runbooks for known production issues.
---
## Job stuck at `encoding` status
**Cause:** A Cloud Run deployment killed the poller mid-encoding. The GCE worker finished but nobody received the result. The health service will flag this as `encoding_stuck` after 50 minutes.
**Recovery:**
```bash
# 1. Confirm the job is flagged
curl -s "https://api.nomadkaraoke.com/api/health/job-consistency" \
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
| python3 -m json.tool | grep -A3 "encoding_stuck"
# 2. Check what the GCE worker knows about the job
WORKER_URL=$(gcloud secrets versions access latest --secret=encoding-worker-url --project=nomadkaraoke)
WORKER_KEY=$(gcloud secrets versions access latest --secret=encoding-worker-api-key --project=nomadkaraoke)
curl -s "$WORKER_URL/status/YOUR_JOB_ID" -H "X-API-Key: $WORKER_KEY" | python3 -m json.tool
# 3. Re-trigger the video worker — it will pick up the cached GCE result if encoding
# already finished, or rejoin the poll if it's still running
curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
-H "Content-Type: application/json" \
-d '{"job_id": "YOUR_JOB_ID"}'
```
**Note:** SSH-restarting the encoding worker is **not needed** since v0.119.6 (PR #413). The `/encode` endpoint is now idempotent — re-triggering the video worker is sufficient.
---
## CDG/TXT packages missing from completed job
**Cause:** Before v0.119.7, CDG/TXT generation failures were silently caught. Jobs would complete with `enable_cdg=True` but no CDG ZIP in outputs. Fixed in v0.119.7 with fail-fast validation — new jobs will now fail loudly if CDG/TXT generation fails.
**Recovery** (for jobs that already completed without CDG/TXT):
```bash
# Regenerate and distribute CDG/TXT packages for specific jobs
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python -m scripts.regenerate_cdg JOB_ID [JOB_ID ...]
# Example:
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python -m scripts.regenerate_cdg 5b6aba25 5161b069
```
The script is idempotent — re-running it skips regeneration if the CDG ZIP already exists in GCS and proceeds to any missing distribution steps (GDrive, Dropbox).
---
## GCE encoding worker on wrong wheel version
**Cause:** Worker picks up a new deploy but doesn't restart automatically.
```bash
# Check current wheel version
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="curl -s http://localhost:8080/health | python3 -m json.tool"
# Restart to pick up latest wheel
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
```
---
## Google Drive uploads missing (gdrive_files empty)
**Symptoms:** Jobs complete successfully but `state_data.gdrive_files` is empty `{}`. Cloud Run logs show `BrokenPipeError` or `SSL: UNEXPECTED_EOF_WHILE_READING`.
**Cause:** Stale HTTP connections in the singleton `GoogleDriveService`. Since v0.119.7, this is handled automatically with retry + connection reset.
**Backfill affected jobs:**
```bash
# Dry run - list affected jobs
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python scripts/backfill_gdrive_uploads.py --all-missing --dry-run
# Run for real
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python scripts/backfill_gdrive_uploads.py --all-missing
# Specific jobs
python scripts/backfill_gdrive_uploads.py --job-ids JOB1,JOB2
```
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.119.6"
version = "0.119.9"
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"
+303
View File
@@ -0,0 +1,303 @@
#!/usr/bin/env python3
"""
Backfill Google Drive uploads for jobs that completed with empty gdrive_files.
This addresses the issue where GDrive uploads silently failed due to stale
HTTP connections (BrokenPipeError / SSLError) on idle Cloud Run containers.
Usage:
# Dry run - show what would be uploaded
python scripts/backfill_gdrive_uploads.py --dry-run --job-ids ca408e46,99baa198
# Upload specific jobs
python scripts/backfill_gdrive_uploads.py --job-ids ca408e46,99baa198
# Find and upload all jobs with empty gdrive_files
python scripts/backfill_gdrive_uploads.py --all-missing
# Override gdrive folder ID (instead of using DEFAULT_GDRIVE_FOLDER_ID env var)
python scripts/backfill_gdrive_uploads.py --job-ids ca408e46 --gdrive-folder-id 1abc...
Requires:
- google-cloud-firestore
- google-cloud-storage
- google-api-python-client, google-auth
- GOOGLE_APPLICATION_CREDENTIALS or gcloud auth application-default login
"""
import argparse
import logging
import os
import sys
import tempfile
# Add project root to path so we can import backend modules
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from google.cloud import firestore, storage
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
logger = logging.getLogger(__name__)
GCS_BUCKET = "karaoke-gen-storage-nomadkaraoke"
PROJECT = "nomadkaraoke"
# Default GDrive public share folder (from infrastructure/config.py)
DEFAULT_GDRIVE_FOLDER_ID = "1laRKAyxo0v817SstfM5XkpbWiNKNAMSX"
# Known affected jobs from the incident
KNOWN_AFFECTED_JOBS = [
"ca408e46", "99baa198", "1e15d1dd", "ebba0996",
"cb744c24", "1389f765", "fde3ae7d", "21f4b34f",
"443c34a1", "56192d3a", "fdb4dc63", "4eeaa729",
]
def get_job(db: firestore.Client, job_id: str) -> dict | None:
"""Fetch job document from Firestore."""
doc = db.collection("jobs").document(job_id).get()
if doc.exists:
return doc.to_dict()
return None
def find_jobs_with_missing_gdrive(db: firestore.Client) -> list[dict]:
"""Find completed jobs that have empty gdrive_files in state_data.
Looks for jobs that have a brand_code (indicating they went through
distribution) but have empty or missing gdrive_files.
"""
jobs = []
query = db.collection("jobs").where("status", "==", "complete")
for doc in query.stream():
data = doc.to_dict()
state_data = data.get("state_data", {})
gdrive_files = state_data.get("gdrive_files", {})
brand_code = state_data.get("brand_code")
# Job should have had GDrive uploads if it has a brand_code
# but gdrive_files is empty/missing
if brand_code and not gdrive_files:
jobs.append({"job_id": doc.id, **data})
return jobs
def _classify_blob(filename: str) -> str | None:
"""Classify a GCS blob filename to an output_files key, or None to skip.
Only returns keys for the 3 file types that get uploaded to GDrive:
lossy 4K MP4, lossy 720p MP4, and CDG ZIP.
"""
lower = filename.lower()
if lower.endswith(".zip") and "cdg" in lower:
return "final_karaoke_cdg_zip"
if "720p" in lower and lower.endswith(".mp4"):
return "final_karaoke_lossy_720p_mp4"
if "lossy" in lower and lower.endswith(".mp4") and "720p" not in lower:
return "final_karaoke_lossy_mp4"
return None
def download_finals(gcs_client: storage.Client, job_id: str, temp_dir: str) -> dict:
"""Download only the final output files needed for GDrive upload.
Only downloads lossy 4K MP4, lossy 720p MP4, and CDG ZIP — skips
lossless files, MKVs, karaoke video, etc. to save bandwidth.
Returns dict mapping output_files keys to local paths.
"""
bucket = gcs_client.bucket(GCS_BUCKET)
prefix = f"jobs/{job_id}/finals/"
blobs = list(bucket.list_blobs(prefix=prefix))
output_files = {}
for blob in blobs:
filename = os.path.basename(blob.name)
if not filename:
continue
key = _classify_blob(filename)
if key is None:
continue
if key in output_files:
continue # already have this type
local_path = os.path.join(temp_dir, filename)
logger.info(f" Downloading {filename} ({blob.size / 1024 / 1024:.1f} MB)")
blob.download_to_filename(local_path)
output_files[key] = local_path
return output_files
def list_finals(gcs_client: storage.Client, job_id: str) -> list[str]:
"""List uploadable final output files in GCS without downloading."""
bucket = gcs_client.bucket(GCS_BUCKET)
prefix = f"jobs/{job_id}/finals/"
blobs = list(bucket.list_blobs(prefix=prefix))
return [
f"{os.path.basename(b.name)} ({b.size / 1024 / 1024:.1f} MB)"
for b in blobs
if os.path.basename(b.name) and _classify_blob(os.path.basename(b.name))
]
def backfill_job(
db: firestore.Client,
gcs_client: storage.Client,
job_id: str,
gdrive_folder_id: str,
dry_run: bool = False,
) -> bool:
"""Backfill GDrive upload for a single job.
Returns True if successful (or dry run).
"""
logger.info(f"Processing job {job_id}")
# Fetch job data
job_data = get_job(db, job_id)
if not job_data:
logger.error(f" Job {job_id} not found in Firestore")
return False
state_data = job_data.get("state_data", {})
artist = job_data.get("artist", "Unknown")
title = job_data.get("title", "Unknown")
brand_code = state_data.get("brand_code")
status = job_data.get("status")
logger.info(f" {artist} - {title} (brand: {brand_code}, status: {status})")
# Check existing gdrive_files
existing = state_data.get("gdrive_files", {})
if existing:
logger.info(f" Already has gdrive_files: {existing}")
logger.info(f" Skipping (already uploaded)")
return True
if not brand_code:
logger.warning(f" No brand code, skipping")
return False
if dry_run:
# List what files are available in GCS
files = list_finals(gcs_client, job_id)
if files:
logger.info(f" [DRY RUN] Would upload {len(files)} files to GDrive folder {gdrive_folder_id}:")
for f in files:
logger.info(f" - {f}")
else:
logger.warning(f" [DRY RUN] No final files found in GCS")
return True
# Download files and upload
with tempfile.TemporaryDirectory(prefix=f"backfill-{job_id}-") as temp_dir:
# Download finals from GCS
logger.info(f" Downloading finals from GCS...")
output_files = download_finals(gcs_client, job_id, temp_dir)
if not output_files:
logger.warning(f" No final files found in GCS")
return False
logger.info(f" Found {len(output_files)} files to upload")
# Upload to GDrive
from backend.services.gdrive_service import GoogleDriveService
gdrive = GoogleDriveService()
if not gdrive.is_configured:
logger.error(f" Google Drive not configured")
return False
base_name = f"{artist} - {title}"
uploaded = gdrive.upload_to_public_share(
root_folder_id=gdrive_folder_id,
brand_code=brand_code,
base_name=base_name,
output_files=output_files,
)
logger.info(f" Uploaded {len(uploaded)} files: {uploaded}")
# Update Firestore
db.collection("jobs").document(job_id).update({
"state_data.gdrive_files": uploaded,
})
logger.info(f" Updated Firestore state_data.gdrive_files")
return True
def main():
parser = argparse.ArgumentParser(
description="Backfill Google Drive uploads for jobs with empty gdrive_files"
)
parser.add_argument(
"--job-ids",
help="Comma-separated list of job IDs to process",
)
parser.add_argument(
"--all-missing",
action="store_true",
help="Find and process all jobs with missing gdrive_files",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be done without making changes",
)
parser.add_argument(
"--gdrive-folder-id",
default=os.getenv("DEFAULT_GDRIVE_FOLDER_ID", DEFAULT_GDRIVE_FOLDER_ID),
help=f"Google Drive folder ID for public share (default: {DEFAULT_GDRIVE_FOLDER_ID})",
)
args = parser.parse_args()
if not args.job_ids and not args.all_missing:
parser.error("Specify --job-ids or --all-missing")
db = firestore.Client(project=PROJECT)
gcs_client = storage.Client(project=PROJECT)
if args.job_ids:
job_ids = [j.strip() for j in args.job_ids.split(",")]
elif args.all_missing:
logger.info("Searching for jobs with missing GDrive uploads...")
jobs = find_jobs_with_missing_gdrive(db)
job_ids = [j["job_id"] for j in jobs]
logger.info(f"Found {len(job_ids)} jobs with missing uploads")
if args.dry_run:
logger.info("[DRY RUN MODE]")
logger.info(f"GDrive folder: {args.gdrive_folder_id}")
success_count = 0
fail_count = 0
for job_id in job_ids:
try:
ok = backfill_job(
db, gcs_client, job_id,
gdrive_folder_id=args.gdrive_folder_id,
dry_run=args.dry_run,
)
if ok:
success_count += 1
else:
fail_count += 1
except Exception as e:
logger.error(f" Failed: {e}", exc_info=True)
fail_count += 1
logger.info(f"\nDone: {success_count} succeeded, {fail_count} failed out of {len(job_ids)} jobs")
if __name__ == "__main__":
main()
+268
View File
@@ -0,0 +1,268 @@
#!/usr/bin/env python3
"""
Remove stranded E2E test job files from the Google Drive public share.
These files were left behind by the daily happy-path E2E test before the
cleanup-distribution endpoint existed (pre-PR #411) or when the GDrive
cleanup was silently skipped because gdrive_files was empty.
Usage:
# Dry run - show what would be deleted
python scripts/cleanup_test_job_gdrive.py --dry-run
# Delete all test job files (files whose name contains test song patterns)
python scripts/cleanup_test_job_gdrive.py
# Delete files with a specific brand code
python scripts/cleanup_test_job_gdrive.py --brand-code NOMAD-1271
# Use a different GDrive folder ID
python scripts/cleanup_test_job_gdrive.py --gdrive-folder-id 1abc...
Requires:
- google-api-python-client, google-auth
- DEFAULT_GDRIVE_FOLDER_ID env var (or --gdrive-folder-id flag)
- GOOGLE_APPLICATION_CREDENTIALS or gcloud auth application-default login
(alternatively: gdrive-oauth-credentials secret in Secret Manager)
The test song used by the E2E happy path is:
Artist: piri
Title: dog
"""
import argparse
import json
import logging
import os
import sys
# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
logger = logging.getLogger(__name__)
# Patterns that identify test job files
# These match files created by the E2E happy-path test
TEST_FILE_PATTERNS = [
"piri - dog", # Current test song (artist: piri, title: dog)
]
PUBLIC_SHARE_SUBFOLDERS = ["CDG", "MP4", "MP4-720p"]
def build_gdrive_service():
"""Build Google Drive API service from credentials."""
try:
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
# Try Secret Manager first
try:
import google.cloud.secretmanager as sm
client = sm.SecretManagerServiceClient()
name = "projects/nomadkaraoke/secrets/gdrive-oauth-credentials/versions/latest"
response = client.access_secret_version(request={"name": name})
creds_data = json.loads(response.payload.data.decode("utf-8"))
credentials = Credentials(
token=creds_data.get("token"),
refresh_token=creds_data.get("refresh_token"),
token_uri=creds_data.get("token_uri", "https://oauth2.googleapis.com/token"),
client_id=creds_data.get("client_id"),
client_secret=creds_data.get("client_secret"),
scopes=creds_data.get("scopes", ["https://www.googleapis.com/auth/drive.file"]),
)
logger.info("Using GDrive credentials from Secret Manager")
except Exception as e:
logger.warning(f"Secret Manager failed ({e}), falling back to ADC")
import google.auth
credentials, _ = google.auth.default(
scopes=["https://www.googleapis.com/auth/drive"]
)
return build("drive", "v3", credentials=credentials)
except ImportError as e:
logger.error(f"Missing dependency: {e}")
logger.error("Install with: pip install google-api-python-client google-auth google-cloud-secret-manager")
sys.exit(1)
def find_test_files(service, root_folder_id: str, patterns: list[str]) -> list[dict]:
"""
Search CDG/, MP4/, MP4-720p/ subfolders for files matching test song patterns.
Returns list of dicts: {name, id, subfolder}
"""
found = []
for subfolder in PUBLIC_SHARE_SUBFOLDERS:
escaped = subfolder.replace("'", "\\'")
query = (
f"name='{escaped}' and '{root_folder_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = service.files().list(
q=query, fields="files(id, name)",
supportsAllDrives=True, includeItemsFromAllDrives=True
).execute()
if not results.get("files"):
logger.debug(f"Subfolder '{subfolder}' not found, skipping")
continue
subfolder_id = results["files"][0]["id"]
logger.debug(f"Found subfolder '{subfolder}': {subfolder_id}")
# List all files in this subfolder
page_token = None
while True:
kwargs = dict(
q=f"'{subfolder_id}' in parents and trashed=false",
fields="nextPageToken, files(id, name)",
supportsAllDrives=True,
includeItemsFromAllDrives=True,
pageSize=200,
)
if page_token:
kwargs["pageToken"] = page_token
response = service.files().list(**kwargs).execute()
for f in response.get("files", []):
name_lower = f["name"].lower()
for pattern in patterns:
if pattern.lower() in name_lower:
found.append({
"name": f["name"],
"id": f["id"],
"subfolder": subfolder,
})
break
page_token = response.get("nextPageToken")
if not page_token:
break
return found
def find_files_by_brand_code(service, root_folder_id: str, brand_code: str) -> list[dict]:
"""Find all files with a specific brand code prefix in the public share subfolders."""
found = []
for subfolder in PUBLIC_SHARE_SUBFOLDERS:
escaped = subfolder.replace("'", "\\'")
query = (
f"name='{escaped}' and '{root_folder_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = service.files().list(
q=query, fields="files(id, name)",
supportsAllDrives=True, includeItemsFromAllDrives=True
).execute()
if not results.get("files"):
continue
subfolder_id = results["files"][0]["id"]
escaped_brand = brand_code.replace("'", "\\'")
file_query = (
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents and trashed=false"
)
file_results = service.files().list(
q=file_query, fields="files(id, name)",
supportsAllDrives=True, includeItemsFromAllDrives=True
).execute()
for f in file_results.get("files", []):
if f["name"].startswith(f"{brand_code} - "):
found.append({
"name": f["name"],
"id": f["id"],
"subfolder": subfolder,
})
return found
def main():
parser = argparse.ArgumentParser(
description="Remove stranded E2E test job files from Google Drive public share"
)
parser.add_argument("--dry-run", action="store_true", help="Show what would be deleted")
parser.add_argument(
"--gdrive-folder-id",
default=os.getenv("DEFAULT_GDRIVE_FOLDER_ID"),
help="Root Google Drive folder ID (defaults to DEFAULT_GDRIVE_FOLDER_ID env var)",
)
parser.add_argument(
"--brand-code",
help="Delete only files with this specific brand code (e.g., NOMAD-1271)",
)
parser.add_argument(
"--patterns",
nargs="+",
default=TEST_FILE_PATTERNS,
help="Filename patterns to match (default: piri - dog)",
)
args = parser.parse_args()
if not args.gdrive_folder_id:
logger.error(
"No GDrive folder ID. Set DEFAULT_GDRIVE_FOLDER_ID env var "
"or pass --gdrive-folder-id"
)
sys.exit(1)
logger.info(f"GDrive root folder: {args.gdrive_folder_id}")
if args.dry_run:
logger.info("DRY RUN - no files will be deleted")
service = build_gdrive_service()
if args.brand_code:
logger.info(f"Searching for files with brand code: {args.brand_code}")
files = find_files_by_brand_code(service, args.gdrive_folder_id, args.brand_code)
else:
logger.info(f"Searching for test job files matching patterns: {args.patterns}")
files = find_test_files(service, args.gdrive_folder_id, args.patterns)
if not files:
logger.info("No test job files found")
return
logger.info(f"\nFound {len(files)} file(s) to delete:")
for f in files:
logger.info(f" [{f['subfolder']}] {f['name']} (id: {f['id']})")
if args.dry_run:
logger.info("\nDry run complete - no files deleted")
return
confirm = input(f"\nDelete {len(files)} file(s)? [y/N] ")
if confirm.lower() != "y":
logger.info("Aborted")
return
deleted = 0
failed = 0
for f in files:
try:
service.files().delete(
fileId=f["id"], supportsAllDrives=True
).execute()
logger.info(f"Deleted: [{f['subfolder']}] {f['name']}")
deleted += 1
except Exception as e:
logger.error(f"Failed to delete {f['name']}: {e}")
failed += 1
logger.info(f"\nDone: {deleted} deleted, {failed} failed")
if __name__ == "__main__":
main()
+395
View File
@@ -0,0 +1,395 @@
#!/usr/bin/env python3
"""
Regenerate CDG ZIP packages for jobs that completed without them.
This one-time remediation script handles the case where jobs completed with
enable_cdg=True but the CDG ZIP wasn't produced (e.g., due to the custom
instrumental path bug fixed in b671b83f).
For each job, the script:
1. Fetches job data from Firestore
2. Downloads LRC and instrumental audio from GCS
3. Loads theme CDG styles
4. Generates CDG package using PackagingService
5. Uploads CDG ZIP to GCS
6. Updates file_urls.packages.cdg_zip in Firestore
7. Uploads CDG ZIP to Google Drive (if GDrive was used)
8. Updates state_data.gdrive_files in Firestore
9. Uploads CDG/TXT ZIPs to Dropbox (if Dropbox was used)
Usage:
python -m scripts.regenerate_cdg JOB_ID [JOB_ID ...]
python -m scripts.regenerate_cdg 5b6aba25 5161b069
Requirements:
- GOOGLE_CLOUD_PROJECT=nomadkaraoke (or set via gcloud config)
- gcloud auth application-default login (for GCS/Firestore access)
"""
import argparse
import logging
import os
import sys
import tempfile
from pathlib import Path
# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent))
os.environ.setdefault("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
from backend.services.storage_service import StorageService
from backend.services.job_manager import JobManager
from backend.services.packaging_service import PackagingService
from karaoke_gen.style_loader import get_cdg_format
from karaoke_gen.utils import sanitize_filename
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("regenerate_cdg")
def get_instrumental_gcs_key(instrumental_selection: str) -> str:
"""Get the GCS file_urls.stems key for the instrumental selection."""
if instrumental_selection == "custom":
return "custom_instrumental"
elif instrumental_selection == "clean":
return "instrumental_clean"
else: # with_backing
return "instrumental_with_backing"
def get_instrumental_suffix(instrumental_selection: str) -> str:
"""Get the filename suffix for the instrumental selection."""
if instrumental_selection == "custom":
return "Custom"
elif instrumental_selection == "clean":
return "Clean"
else:
return "Backing"
def regenerate_cdg_for_job(job_id: str, storage: StorageService, job_manager: JobManager, dry_run: bool = False):
"""Regenerate CDG ZIP for a single job."""
logger.info(f"=== Processing job {job_id} ===")
# 1. Fetch job from Firestore
job = job_manager.get_job(job_id)
if not job:
logger.error(f"Job {job_id} not found in Firestore")
return False
logger.info(f"Job: {job.artist} - {job.title}")
logger.info(f" enable_cdg: {job.enable_cdg}")
logger.info(f" status: {job.status}")
if not job.enable_cdg:
logger.warning(f"Job {job_id} does not have enable_cdg=True, skipping")
return False
# Check if CDG already exists in GCS
existing_cdg = job.file_urls.get("packages", {}).get("cdg_zip")
cdg_already_in_gcs = existing_cdg and storage.file_exists(existing_cdg)
if cdg_already_in_gcs:
logger.info(f"CDG ZIP already exists in GCS: {existing_cdg}")
elif existing_cdg:
logger.warning("CDG ZIP in Firestore but NOT in GCS, will regenerate")
# Get instrumental selection
instrumental_selection = job.state_data.get("instrumental_selection", "clean")
logger.info(f" instrumental_selection: {instrumental_selection}")
# Get lyrics metadata for countdown padding
lyrics_metadata = job.state_data.get("lyrics_metadata", {})
lrc_has_countdown_padding = lyrics_metadata.get("has_countdown_padding", False)
countdown_padding_seconds = lyrics_metadata.get("countdown_padding_seconds", 3.0)
logger.info(f" countdown_padding: {lrc_has_countdown_padding} ({countdown_padding_seconds}s)")
# Check required files exist in file_urls
lrc_url = job.file_urls.get("lyrics", {}).get("lrc")
if not lrc_url:
logger.error(f"Job {job_id} has no LRC file URL")
return False
instrumental_key = get_instrumental_gcs_key(instrumental_selection)
instrumental_url = job.file_urls.get("stems", {}).get(instrumental_key)
if not instrumental_url:
logger.error(f"Job {job_id} has no instrumental URL for key '{instrumental_key}'")
return False
# Get style_params for CDG styles
style_params_url = job.style_params_gcs_path
if dry_run:
logger.info(f"DRY RUN: Would regenerate CDG for {job.artist} - {job.title}")
return True
# 2. Download or regenerate CDG/TXT packages
with tempfile.TemporaryDirectory(prefix=f"cdg-regen-{job_id}-") as temp_dir:
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
base_name = f"{safe_artist} - {safe_title}"
instrumental_suffix = get_instrumental_suffix(instrumental_selection)
brand_code = getattr(job, "brand_code", None) or job.state_data.get("brand_code", "UNKNOWN")
cdg_zip_path = os.path.join(temp_dir, f"{base_name} (Final Karaoke CDG).zip")
txt_zip_path = os.path.join(temp_dir, f"{base_name} (Final Karaoke TXT).zip")
if cdg_already_in_gcs:
# Download existing CDG ZIP from GCS for distribution
logger.info("Downloading existing CDG ZIP from GCS for distribution...")
storage.download_file(existing_cdg, cdg_zip_path)
# Also download TXT if it exists
existing_txt = job.file_urls.get("packages", {}).get("txt_zip")
if existing_txt and storage.file_exists(existing_txt):
logger.info("Downloading existing TXT ZIP from GCS...")
storage.download_file(existing_txt, txt_zip_path)
else:
# Regenerate: download source files and generate packages
# Download LRC
lrc_path = os.path.join(temp_dir, f"{base_name} (Karaoke).lrc")
logger.info(f"Downloading LRC: {lrc_url}")
storage.download_file(lrc_url, lrc_path)
# Download instrumental
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental {instrumental_suffix}).flac")
logger.info(f"Downloading instrumental: {instrumental_url}")
storage.download_file(instrumental_url, instrumental_path)
# Download and parse style_params
import json
style_params_path = os.path.join(temp_dir, "style_params.json")
style_params = None
if style_params_url:
try:
logger.info(f"Downloading style params: {style_params_url}")
storage.download_file(style_params_url, style_params_path)
with open(style_params_path) as f:
style_params = json.load(f)
except Exception as e:
logger.warning(f"Failed to download style_params from {style_params_url}: {e}")
# Fallback: load theme style_params from GCS theme directory
if style_params is None:
theme_id = getattr(job, "theme_id", "nomad") or "nomad"
theme_path = f"themes/{theme_id}/style_params.json"
logger.info(f"Trying theme style_params: {theme_path}")
try:
storage.download_file(theme_path, style_params_path)
with open(style_params_path) as f:
style_params = json.load(f)
except Exception as e:
logger.error(f"Failed to load theme style_params: {e}")
return False
# Download CDG style assets (font, backgrounds) referenced in style_params
cdg_section = style_params.get("cdg", {})
style_dir = os.path.join(temp_dir, "style")
os.makedirs(style_dir, exist_ok=True)
# Resolve asset GCS paths. Per-job style_params have full paths like
# "themes/nomad/assets/AvenirNext-Bold.ttf". Theme-level style_params
# have bare filenames like "AvenirNext-Bold.ttf" that need to be
# resolved against the theme's assets directory.
theme_id = getattr(job, "theme_id", "nomad") or "nomad"
theme_assets_prefix = f"themes/{theme_id}/assets"
for asset_key in ["font_path", "instrumental_background", "title_screen_background", "outro_background"]:
asset_path = cdg_section.get(asset_key)
if not asset_path or not isinstance(asset_path, str) or os.path.isabs(asset_path):
continue
# Determine the GCS path — bare filenames need the theme prefix
if "/" not in asset_path:
gcs_path = f"{theme_assets_prefix}/{asset_path}"
else:
gcs_path = asset_path
local_path = os.path.join(style_dir, os.path.basename(asset_path))
try:
storage.download_file(gcs_path, local_path)
cdg_section[asset_key] = local_path
logger.info(f"Downloaded CDG asset {asset_key}: {gcs_path}")
except Exception as e:
logger.warning(f"Failed to download CDG asset {asset_key} from {gcs_path}: {e}")
# 3. Extract CDG styles
cdg_styles = get_cdg_format(style_params)
if not cdg_styles:
logger.error(f"No CDG styles found in theme for job {job_id}")
return False
logger.info("CDG styles loaded successfully")
# 4. Generate CDG package
packaging_service = PackagingService(
cdg_styles=cdg_styles,
dry_run=False,
non_interactive=True,
)
mp3_path = os.path.join(temp_dir, f"{base_name} (Karaoke).mp3")
cdg_path = os.path.join(temp_dir, f"{base_name} (Karaoke).cdg")
logger.info("Generating CDG package...")
zip_file, mp3_file, cdg_file = packaging_service.create_cdg_package(
lrc_file=lrc_path,
audio_file=instrumental_path,
output_zip_path=cdg_zip_path,
artist=job.artist,
title=job.title,
output_mp3_path=mp3_path,
output_cdg_path=cdg_path,
lrc_has_countdown_padding=lrc_has_countdown_padding,
countdown_padding_seconds=countdown_padding_seconds,
)
if not os.path.isfile(cdg_zip_path):
logger.error(f"CDG ZIP not created at expected path: {cdg_zip_path}")
return False
zip_size = os.path.getsize(cdg_zip_path)
logger.info(f"CDG ZIP created: {cdg_zip_path} ({zip_size / 1024:.1f} KB)")
# 5. Upload CDG ZIP to GCS
gcs_cdg_path = f"jobs/{job_id}/packages/cdg_zip.zip"
logger.info(f"Uploading CDG ZIP to GCS: {gcs_cdg_path}")
storage.upload_file(cdg_zip_path, gcs_cdg_path)
# 6. Update Firestore file_urls
logger.info("Updating Firestore file_urls.packages.cdg_zip")
job_manager.update_file_url(job_id, "packages", "cdg_zip", gcs_cdg_path)
# Also generate TXT if enabled
if job.enable_txt:
logger.info("Job also has enable_txt=True, generating TXT package...")
try:
txt_zip, txt_file = packaging_service.create_txt_package(
lrc_file=lrc_path,
mp3_file=mp3_path,
output_zip_path=txt_zip_path,
)
if os.path.isfile(txt_zip_path):
gcs_txt_path = f"jobs/{job_id}/packages/txt_zip.zip"
storage.upload_file(txt_zip_path, gcs_txt_path)
job_manager.update_file_url(job_id, "packages", "txt_zip", gcs_txt_path)
logger.info(f"TXT ZIP uploaded: {gcs_txt_path}")
except Exception as e:
logger.error(f"TXT generation failed: {e}")
# === Distribution steps (run for both new and existing packages) ===
# 7. Upload to GDrive if job uses it
gdrive_files = job.state_data.get("gdrive_files", {})
if gdrive_files and "cdg" not in gdrive_files:
logger.info("Uploading CDG ZIP to Google Drive...")
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
gdrive_folder_id = getattr(job, "gdrive_folder_id", None)
if gdrive_folder_id:
safe_base = sanitize_filename(f"{job.artist} - {job.title}")
filename_base = f"{brand_code} - {safe_base}"
cdg_folder_id = gdrive.get_or_create_folder(gdrive_folder_id, "CDG")
file_id = gdrive.upload_file(
cdg_zip_path,
cdg_folder_id,
f"{filename_base}.zip",
)
logger.info(f"Uploaded CDG to GDrive: {file_id}")
# 8. Update state_data.gdrive_files
gdrive_files["cdg"] = file_id
job_manager.update_job(job_id, {"state_data.gdrive_files": gdrive_files})
logger.info("Updated Firestore state_data.gdrive_files")
else:
logger.warning("No gdrive_folder_id on job, skipping GDrive upload")
else:
logger.warning("GDrive not configured, skipping upload")
except Exception as e:
logger.error(f"GDrive upload failed (non-fatal): {e}")
elif gdrive_files:
logger.info("GDrive already has CDG file, skipping GDrive upload")
else:
logger.info("No existing GDrive files, skipping GDrive upload")
# 9. Upload to Dropbox if job uses it
dropbox_path = job.dropbox_path
if dropbox_path:
logger.info("Uploading packages to Dropbox...")
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if dropbox.is_configured:
safe_base = sanitize_filename(f"{job.artist} - {job.title}")
folder_name = f"{brand_code} - {safe_base}"
remote_folder = f"{dropbox_path}/{folder_name}"
# Upload CDG ZIP
if os.path.isfile(cdg_zip_path):
cdg_remote = f"{remote_folder}/{os.path.basename(cdg_zip_path)}"
dropbox.upload_file(cdg_zip_path, cdg_remote)
logger.info(f"Uploaded CDG to Dropbox: {cdg_remote}")
# Upload TXT ZIP
if os.path.isfile(txt_zip_path):
txt_remote = f"{remote_folder}/{os.path.basename(txt_zip_path)}"
dropbox.upload_file(txt_zip_path, txt_remote)
logger.info(f"Uploaded TXT to Dropbox: {txt_remote}")
else:
logger.warning("Dropbox not configured, skipping upload")
except Exception as e:
logger.error(f"Dropbox upload failed (non-fatal): {e}")
else:
logger.info("No dropbox_path on job, skipping Dropbox upload")
logger.info(f"=== Job {job_id} CDG regeneration complete ===")
return True
def main():
parser = argparse.ArgumentParser(
description="Regenerate CDG ZIP packages for jobs that completed without them."
)
parser.add_argument(
"job_ids",
nargs="+",
help="Job IDs to regenerate CDG for",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be done without making changes",
)
args = parser.parse_args()
storage = StorageService()
job_manager = JobManager()
results = {}
for job_id in args.job_ids:
try:
success = regenerate_cdg_for_job(job_id, storage, job_manager, dry_run=args.dry_run)
results[job_id] = "OK" if success else "FAILED"
except Exception as e:
logger.exception(f"Error processing job {job_id}: {e}")
results[job_id] = f"ERROR: {e}"
# Summary
logger.info("\n=== Summary ===")
for job_id, status in results.items():
logger.info(f" {job_id}: {status}")
# Exit with error if any failed
if any(s != "OK" for s in results.values()):
sys.exit(1)
if __name__ == "__main__":
main()