Compare commits

..
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 4.8 0539479281 docs: address CodeRabbit review on #913
- handoff: made self-contained (dropped agent-memory refs); reframed around the
  confirmed static finding that `ffmpeg_threads` is DEAD CONFIG (video_worker sets
  it but EncodingConfig/LocalEncodingService never read it, and the finalization
  ffmpeg commands omit -threads → default all-core), so it's a narrower
  efficiency+cleanup task, not "fix an 8-core cap"; strengthened measurement
  guidance to process-level (ffmpeg argv, per-thread CPU/RSS, per-format timings)
  and bound the encode+probes to one observed worker IP; fixed a wrong file
  pointer (backend/services/local_encoding_service.py, not the wheel).
- plan doc: c2df/n4db are now provisioned (secret v5, all 8 fallbacks live) — the
  autonomous retry loop finished them 2026-08-16; replaced the ellipsis
  `--target …` with full executable URNs.
- ARCHITECTURE: deploy-flow steps now cover the fallback-green/active_override
  branch, override clearing, drain+stop, and the no-green in-place-restart path.
- TROUBLESHOOTING: replaced the obsolete `encoding-worker` ssh host with
  active-worker (primary_vm / active_override_vm) guidance.
- GCP-COST-OPTIMIZATION: recommendation now matches the updated state (stay
  on-demand + idle-shutdown; Spot only as a future experiment).

Docs-only; no version bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 14:08:34 -04:00
Andrew BeveridgeandClaude Opus 4.8 b7c4edc7fc docs: reflect multi-instance-type encode pool + add finalization-CPU handoff
Bring all live docs in line with the v0.195.0 encode-worker mechanism (ranked
6-family pool, shared encoding_worker_preference ordering, capacity_state
cooldown, dep-baked image) and add a handoff for the next investigation.

- ARCHITECTURE.md: rewrite the "Encoding Worker" section — primary pair + 6-family
  fallback pool, shared preference module (runtime + deploy), capacity_state,
  is_primary override routing, self-sufficient dep-baked image; update the topology
  diagram + intro.
- TROUBLESHOOTING.md: capacity runbook now lists all 6 families / 8 fallbacks +
  cooldown; capacity-probe loop covers the 4 new VMs; deploy green-selection points
  at the ranked pool; "No module named" section notes the dep-bake largely fixed it
  (+ the create-time-stockout caveat).
- DEVELOPMENT.md + CLAUDE.md: fix "two VMs" framing; CLAUDE.md ssh example uses a
  real VM name (there is no VM literally named `encoding-worker`).
- GCP-COST-OPTIMIZATION.md: correct the stale "c4d running 24/7 ~$700/mo" current
  state (now on-demand pool + idle-shutdown, largely the shipped opportunities).
- LESSONS-LEARNED.md: mark the Aug-2026 2-family diversification lesson as
  superseded by the v0.195.0 pool (preserve history, redirect to current).
- NEW docs/archive/2026-08-16-finalization-cpu-efficiency-handoff.md: grounded
  handoff to investigate whether prod finalization is CPU-underutilized
  (ffmpeg_threads:8 on 32-vCPU workers), with repro + constraints.

Docs-only; no version bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 13:47:05 -04:00
16 changed files with 103 additions and 889 deletions

No files matched your search

-4
View File
@@ -96,10 +96,6 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
- Never modify GCP resources directly via console or `gcloud` CLI
- `gcloud` CLI for reading/debugging only (e.g., checking logs, SSH to VMs)
- Stop and notify user on auth issues
- **GCS ops on macOS: never use `gsutil -m`** — its fork-based multiprocessing segfaults
on macOS (crash-report popups + the parent process hangs forever). Use `gcloud storage`
instead (`gcloud storage cp/rm/rsync …`) — no fork, and faster. Plain `gsutil` (no `-m`)
is safe but slower. `~/.boto` pins `parallel_process_count=1` as a safety net; don't remove it.
### Internationalization (i18n)
+4 -25
View File
@@ -325,29 +325,10 @@ class LocalEncodingService:
output_file: str,
) -> bool:
"""
Convert the source "With Vocals" video (MOV/MKV) to a standard, portable MP4.
This produces the "(With Vocals).mp4" sing-along deliverable. It is a leaf
output — no later encode reads it — so the encode is chosen purely for the
deliverable itself:
- ``-pix_fmt yuv420p``: the renderer emits High 4:4:4 (yuv444p), which many
browsers/TVs/phones cannot decode. Normalize to 4:2:0 so it plays
everywhere and matches every other output. (Also ~halves this stage's CPU
time vs. re-encoding 4:4:4, and yields a slightly smaller file.)
- ``-preset veryfast``: this is the single longest finalization stage; a fast
preset roughly halves it (~56s → ~28s on a 32-vCPU worker) with negligible
quality difference for karaoke content (static background + text).
- ``-c:a aac``: the source audio is FLAC; FLAC-in-MP4 is non-standard. Encode
AAC 320k so the file is fully portable. Matches the documented spec
("4k H264/AAC with original vocals", see template_service.py).
Both commands force ``-pix_fmt yuv420p`` (h264_nvenc can otherwise *preserve* a
yuv444p input). Prod encoding workers are CPU-only, so ``cpu_command`` is the
real path; if the NVENC command ever errors, ``_execute_command_with_fallback``
drops to the (correct) CPU command.
Convert MOV to MP4 format.
Args:
input_file: Path to input MOV/MKV file (source "With Vocals" video)
input_file: Path to input MOV file
output_file: Path for output MP4 file
Returns:
@@ -355,13 +336,11 @@ class LocalEncodingService:
"""
gpu_command = (
f'{self._ffmpeg_base_command} {self.hwaccel_decode_flags} -i "{input_file}" '
f'-c:v {self.video_encoder} -pix_fmt yuv420p -c:a {self.aac_codec} -ar 48000 -b:a 320k '
f'{self.MP4_FLAGS} "{output_file}"'
f'-c:v {self.video_encoder} -c:a copy {self.MP4_FLAGS} "{output_file}"'
)
cpu_command = (
f'{self._ffmpeg_base_command} -i "{input_file}" '
f'-c:v libx264 -pix_fmt yuv420p -preset veryfast '
f'-c:a {self.aac_codec} -ar 48000 -b:a 320k {self.MP4_FLAGS} "{output_file}"'
f'-c:v libx264 -c:a copy {self.MP4_FLAGS} "{output_file}"'
)
return self._execute_command_with_fallback(
gpu_command, cpu_command, "Converting MOV to MP4"
+35 -164
View File
@@ -57,93 +57,61 @@ class VisibilityChangeService:
"""
Change a public job to private (fast path).
Distribute-then-delete: the track is first redistributed to the private
destination (private Dropbox archive + NOMADNP code, no YouTube/GDrive),
and only *after* that succeeds are the public outputs (YouTube, public
Dropbox folder, public GDrive files) deleted and the public NOMAD number
recycled. GCS finals are always kept.
This ordering is deliberate: YouTube deletion is irreversible, so nothing
public may be destroyed until the private archive exists. If redistribution
fails, the job is reverted to public and left fully intact (no partial
deletion, no leaked NOMADNP code — see redistribute_video's failure path).
Deletes distributed outputs (YouTube/Dropbox/GDrive) but keeps GCS finals,
then redistributes to private destination.
"""
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
db = self.job_manager.firestore.db
job_ref = db.collection("jobs").document(job_id)
# Capture the public output references BEFORE redistribution overwrites
# state_data with the new private values — we need them to delete the
# public outputs afterwards.
state_data = job.state_data or {}
public_outputs = {
"youtube_url": state_data.get("youtube_url"),
"brand_code": state_data.get("brand_code"),
"gdrive_files": state_data.get("gdrive_files"),
"dropbox_path": getattr(job, "dropbox_path", None),
"artist": job.artist,
"title": job.title,
}
# Set guard flag + flip to private so redistribution targets the private
# destination. Public outputs remain live until the private archive exists.
# No "changed to private" timeline event yet — it is only recorded once the
# move actually succeeds (this is reverted if redistribution fails).
# Set guard flag
job_ref.update({
"state_data.visibility_change_in_progress": True,
"is_private": True,
"updated_at": datetime.now(timezone.utc),
})
# Step 1: Redistribute to the private destination FIRST (public outputs
# still live). This is the only phase whose failure is safe to fully roll
# back — nothing public has been touched yet. redistribute_video verifies
# the archive actually materialized and recycles any NOMADNP code it
# allocated on failure, so a False return means "no-op, still public".
try:
# Step 1: Delete distributed outputs (keep GCS finals)
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=True)
# Step 2: Update job to private
job_ref.update({
"is_private": True,
"updated_at": datetime.now(timezone.utc),
"timeline": ArrayUnion([{
"status": "complete",
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": f"Visibility changed to private by {user_email}",
}]),
})
# Step 3: Trigger redistribution via video worker
from backend.workers.video_worker import redistribute_video
success = await redistribute_video(job_id)
except Exception as e:
logger.error(f"[job:{job_id}] Redistribution raised during visibility change: {e}", exc_info=True)
success = False
if not success:
# Roll back to public: no public outputs were deleted, so restoring
# is_private=False leaves the job fully intact and public.
logger.error(f"[job:{job_id}] Visibility change to private failed: redistribution did not succeed")
if not success:
raise RuntimeError("Redistribution failed - check worker logs")
# Clear guard flag (redistribution updates state_data with new brand_code etc.)
job_ref.update({
"is_private": False,
"state_data.visibility_change_in_progress": DELETE_FIELD,
"updated_at": datetime.now(timezone.utc),
})
raise RuntimeError("Redistribution failed - check worker logs")
# Step 2: Private archive now exists. From here we do NOT revert to public,
# even if public cleanup hiccups — the private move has committed. Deleting
# the public outputs + recycling the public NOMAD number is best-effort
# (each failure is logged inside the helper, never raised), so a stray
# orphaned public artifact cannot undo the successful private move.
await self._delete_public_outputs(job_id, public_outputs)
logger.info(f"[job:{job_id}] Visibility change to private complete")
return {
"status": "success",
"message": "Job changed to private. Outputs redistributed to private destination.",
"reprocessing_required": False,
}
# Record the completed move and clear the guard flag. redistribute_video
# already updated state_data with the new private brand_code etc.
job_ref.update({
"state_data.visibility_change_in_progress": DELETE_FIELD,
"updated_at": datetime.now(timezone.utc),
"timeline": ArrayUnion([{
"status": "complete",
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": f"Visibility changed to private by {user_email}",
}]),
})
logger.info(f"[job:{job_id}] Visibility change to private complete")
return {
"status": "success",
"message": "Job changed to private. Outputs redistributed to private destination.",
"reprocessing_required": False,
}
except Exception as e:
logger.error(f"[job:{job_id}] Visibility change to private failed: {e}", exc_info=True)
# Clear guard flag on failure
job_ref.update({
"state_data.visibility_change_in_progress": DELETE_FIELD,
})
raise
async def change_to_public(self, job_id: str, job, user_email: str) -> dict:
"""
@@ -248,103 +216,6 @@ class VisibilityChangeService:
"reprocessing_required": True,
}
async def _delete_public_outputs(self, job_id: str, public_outputs: dict):
"""Delete the captured PUBLIC outputs and recycle the public NOMAD number.
Used by change_to_private AFTER a successful private redistribution. Operates
on references captured before redistribution (which overwrites state_data with
private values). Does not touch GCS finals and does not clear state_data keys
(redistribution already set the new private values). Best-effort: individual
failures are logged, not raised, so one orphaned artifact can't undo the move.
"""
import re
# Track whether each public destination was fully cleaned. The NOMAD number
# is only recycled when every deletion succeeded — otherwise a future public
# track could reuse the number while the old public files still linger,
# producing a duplicate. (Mirrors the admin delete-outputs recycle gate.)
youtube_ok = True
dropbox_ok = True
gdrive_ok = True
youtube_url = public_outputs.get("youtube_url")
if youtube_url:
try:
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
if video_id_match:
video_id = video_id_match.group(1)
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
from backend.services.youtube_service import get_youtube_service
youtube_service = get_youtube_service()
if youtube_service.is_configured:
finalise = KaraokeFinalise(
dry_run=False, non_interactive=True,
user_youtube_credentials=youtube_service.get_credentials_dict()
)
finalise.delete_youtube_video(video_id)
logger.info(f"[job:{job_id}] Deleted public YouTube video {video_id}")
except Exception as e:
youtube_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public YouTube video: {e}")
brand_code = public_outputs.get("brand_code")
dropbox_path = public_outputs.get("dropbox_path")
if brand_code and dropbox_path:
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if dropbox.is_configured:
from karaoke_gen.utils import sanitize_filename
safe_artist = sanitize_filename(public_outputs.get("artist")) if public_outputs.get("artist") else "Unknown"
safe_title = sanitize_filename(public_outputs.get("title")) if public_outputs.get("title") else "Unknown"
folder_name = f"{brand_code} - {safe_artist} - {safe_title}"
full_path = f"{dropbox_path}/{folder_name}"
dropbox.delete_folder(full_path)
logger.info(f"[job:{job_id}] Deleted public Dropbox folder {full_path}")
except Exception as e:
dropbox_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public Dropbox folder: {e}")
gdrive_files = public_outputs.get("gdrive_files")
if gdrive_files:
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
gdrive.delete_files(file_ids)
logger.info(f"[job:{job_id}] Deleted public Google Drive files")
except Exception as e:
gdrive_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public Google Drive files: {e}")
# A track going private should also leave the public Nomad GCS fast-sync
# mirror (and thus kjbox). Prefix-keyed by the public brand_code, non-fatal.
if brand_code:
try:
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to clean up Nomad mirror for {brand_code}: {e}")
# Recycle the public NOMAD number so the next public track fills the gap —
# but only if every public deletion succeeded. If any lingered, keep the
# number reserved (a permanent gap the validator will flag) rather than
# risk a future duplicate; the leftover artifacts can then be cleaned up.
if brand_code and youtube_ok and dropbox_ok and gdrive_ok:
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)
logger.info(f"[job:{job_id}] Recycled public brand code {brand_code}")
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to recycle public brand code {brand_code}: {e}")
elif brand_code:
logger.warning(
f"[job:{job_id}] NOT recycling public brand code {brand_code}: "
f"public cleanup incomplete (youtube={youtube_ok}, dropbox={dropbox_ok}, gdrive={gdrive_ok})"
)
async def _delete_distributed_outputs(self, job_id: str, job, keep_gcs_finals: bool = False):
"""Delete distributed outputs (YouTube, Dropbox, GDrive) and recycle brand code."""
import re
+10 -93
View File
@@ -101,9 +101,7 @@ class TestChangeToPrivate:
"""Test public -> private visibility change."""
@pytest.mark.asyncio
async def test_redistributes_then_deletes_public(self):
"""Distribute-then-delete: redistribute runs, then public outputs are deleted
with the references captured before redistribution overwrote state."""
async def test_calls_redistribute(self):
mock_job_manager = MagicMock()
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
@@ -112,29 +110,18 @@ class TestChangeToPrivate:
job = _make_job(is_private=False, state_data={
"youtube_url": "https://youtube.com/watch?v=abc",
"brand_code": "NOMAD-0001",
"gdrive_files": {"mp4": "id1"},
"dropbox_link": "https://dropbox.com/test",
})
call_order = []
mock_redist = AsyncMock(return_value=True, side_effect=lambda *a, **k: call_order.append("redist") or True)
mock_delete = AsyncMock(side_effect=lambda *a, **k: call_order.append("delete"))
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", mock_delete), \
patch("backend.workers.video_worker.redistribute_video", mock_redist):
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock) as mock_delete, \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True) as mock_redist:
result = await service.change_to_private("test-123", job, "user@example.com")
assert result["status"] == "success"
assert result["reprocessing_required"] is False
mock_delete.assert_called_once_with("test-123", job, keep_gcs_finals=True)
mock_redist.assert_called_once_with("test-123")
# Redistribution must happen BEFORE any public deletion.
assert call_order == ["redist", "delete"]
# Public deletion receives the references captured before redistribution.
captured = mock_delete.call_args.args[1]
assert captured["youtube_url"] == "https://youtube.com/watch?v=abc"
assert captured["brand_code"] == "NOMAD-0001"
assert captured["gdrive_files"] == {"mp4": "id1"}
@pytest.mark.asyncio
async def test_sets_is_private_true(self):
@@ -145,7 +132,7 @@ class TestChangeToPrivate:
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=False, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", new_callable=AsyncMock), \
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True):
await service.change_to_private("test-123", job, "user@example.com")
@@ -296,33 +283,22 @@ class TestChangeToPrivateErrors:
@pytest.mark.asyncio
async def test_rollback_on_redistribute_failure(self):
"""On redistribution failure NOTHING public is deleted and the job is
reverted to public — a failed going-private is a no-op, not a partial."""
mock_job_manager = MagicMock()
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=False, state_data={
"youtube_url": "https://youtube.com/watch?v=abc",
"brand_code": "NOMAD-0001",
"gdrive_files": {"mp4": "id1"},
})
job = _make_job(is_private=False, state_data={})
mock_delete = AsyncMock()
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", mock_delete), \
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=False):
with pytest.raises(RuntimeError, match="Redistribution failed"):
await service.change_to_private("test-123", job, "user@example.com")
# Public outputs must NOT be deleted when redistribution fails.
mock_delete.assert_not_called()
# Job reverted to public + guard flag cleared (DELETE_FIELD sentinel).
last_update = mock_job_ref.update.call_args_list[-1].args[0]
assert last_update.get("is_private") is False
val = last_update.get("state_data.visibility_change_in_progress")
# Guard flag should be cleared on failure (DELETE_FIELD sentinel)
last_update = mock_job_ref.update.call_args_list[-1]
val = last_update.args[0].get("state_data.visibility_change_in_progress")
assert "delete" in str(type(val)).lower() or "sentinel" in str(val).lower()
@@ -347,65 +323,6 @@ class TestDeleteDistributedOutputs:
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
@pytest.mark.asyncio
async def test_delete_public_outputs_recycles_public_code(self):
"""_delete_public_outputs recycles the captured public NOMAD number."""
mock_job_manager = MagicMock()
service = VisibilityChangeService(job_manager=mock_job_manager)
public_outputs = {
"youtube_url": None,
"brand_code": "NOMAD-0042",
"gdrive_files": None,
"dropbox_path": None,
"artist": "A",
"title": "T",
}
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)), \
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters") as mock_mirror:
mock_brand_svc = MagicMock()
mock_bcs.return_value = mock_brand_svc
await service._delete_public_outputs("test-123", public_outputs)
# No public YouTube/Dropbox/GDrive present → all deletions "succeed" →
# the public number is recycled and the mirror is cleaned.
mock_mirror.assert_called_once_with("NOMAD-0042")
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
@pytest.mark.asyncio
async def test_delete_public_outputs_skips_recycle_on_incomplete_cleanup(self):
"""If a public deletion fails, the number is NOT recycled (avoids a future
duplicate against lingering public files)."""
mock_job_manager = MagicMock()
service = VisibilityChangeService(job_manager=mock_job_manager)
public_outputs = {
"youtube_url": None,
"brand_code": "NOMAD-0042",
"gdrive_files": {"mp4": "id1"},
"dropbox_path": None,
"artist": "A",
"title": "T",
}
with patch("backend.services.gdrive_service.get_gdrive_service") as mock_gd, \
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters"), \
patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)):
gd = MagicMock()
gd.is_configured = True
gd.delete_files.side_effect = RuntimeError("gdrive boom")
mock_gd.return_value = gd
mock_brand_svc = MagicMock()
mock_bcs.return_value = mock_brand_svc
await service._delete_public_outputs("test-123", public_outputs)
mock_brand_svc.recycle_brand_code.assert_not_called()
@pytest.mark.asyncio
async def test_clears_distribution_state_keys(self):
mock_job_manager = MagicMock()
+1 -14
View File
@@ -171,7 +171,7 @@ class TestLocalEncodingServiceEncodingMethods:
@patch.object(LocalEncodingService, "_execute_command_with_fallback")
def test_convert_mov_to_mp4(self, mock_execute):
"""Test MOV to MP4 conversion produces a standard, portable "With Vocals" mp4."""
"""Test MOV to MP4 conversion."""
mock_execute.return_value = True
service = LocalEncodingService()
@@ -182,19 +182,6 @@ class TestLocalEncodingServiceEncodingMethods:
assert result is True
mock_execute.assert_called_once()
gpu_command, cpu_command = mock_execute.call_args[0][0], mock_execute.call_args[0][1]
# The CPU (software) command is what runs on prod encoding workers (no NVENC).
# It must normalize 4:4:4 -> 4:2:0 for playback compatibility, use a fast preset
# (this is the longest finalization stage), and emit portable AAC (not FLAC-in-mp4).
assert "-pix_fmt yuv420p" in cpu_command
assert "-preset veryfast" in cpu_command
assert "-c:a aac" in cpu_command
assert "-b:a 320k" in cpu_command
assert "-c:a copy" not in cpu_command # regression guard: no FLAC-in-mp4
# GPU path also forces 4:2:0 (h264_nvenc can preserve yuv444p) and emits AAC.
assert "-pix_fmt yuv420p" in gpu_command
assert "-c:a aac" in gpu_command
assert "-b:a 320k" in gpu_command
@patch.object(LocalEncodingService, "_execute_command_with_fallback")
def test_encode_lossless_mp4_without_end(self, mock_execute):
@@ -21,7 +21,6 @@ from backend.workers.video_worker_orchestrator import (
VideoWorkerOrchestrator,
create_orchestrator_config_from_job,
)
from backend.models.job import JobStatus
class TestOrchestratorConfig:
@@ -2133,52 +2132,3 @@ class TestOriginalVocalsGuideEmit:
with patch("backend.workers.style_helper.load_style_config", side_effect=fake_load):
assert await orch._resolve_intro_seconds() == 8.0
class TestRedistributeModeProgress:
"""redistribute_mode must not attempt job status transitions.
Regression for the public->private data-loss bug: redistributing an already
`complete` job drove `_update_progress(PACKAGING)`, which raised
InvalidStateTransitionError (`complete -> packaging`) and aborted the
redistribution after the public outputs had already been deleted.
"""
def _config(self, redistribute_mode):
return OrchestratorConfig(
job_id="job-1",
artist="A",
title="T",
title_video_path="",
karaoke_video_path="",
instrumental_audio_path="",
redistribute_mode=redistribute_mode,
)
def test_redistribute_mode_skips_status_transition(self):
jm = MagicMock()
orch = VideoWorkerOrchestrator(
config=self._config(redistribute_mode=True),
job_manager=jm,
storage=MagicMock(),
job_logger=MagicMock(),
)
orch._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
jm.transition_to_state.assert_not_called()
jm.update_job.assert_called_once_with("job-1", {"progress": 90})
def test_normal_mode_drives_status_transition(self):
jm = MagicMock()
orch = VideoWorkerOrchestrator(
config=self._config(redistribute_mode=False),
job_manager=jm,
storage=MagicMock(),
job_logger=MagicMock(),
)
orch._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
jm.transition_to_state.assert_called_once()
jm.update_job.assert_not_called()
+1 -48
View File
@@ -128,10 +128,7 @@ async def _encode_via_gce(
"base_name": base_name,
"instrumental_selection": instrumental_selection,
"existing_instrumental": existing_instrumental,
# NOTE: intentionally no "ffmpeg_threads" — finalization ffmpeg commands in
# LocalEncodingService carry no -threads flag, so x264 uses its all-core auto
# default (measured ~66-78% of a 32-vCPU worker busy during the heavy libx264
# stages — not capped). See docs/archive/2026-08-16-finalization-cpu-efficiency-handoff.md.
"ffmpeg_threads": 8, # c4-standard-8 has 8 vCPUs
}
job_log.info(f"Submitting encoding job to GCE worker")
@@ -505,7 +502,6 @@ async def redistribute_video(job_id: str) -> bool:
return False
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_redist_{job_id}_")
orchestrator = None
try:
# Download existing finals from GCS by listing the finals folder
@@ -575,10 +571,6 @@ async def redistribute_video(job_id: str) -> bool:
gdrive_folder_id=dist.gdrive_folder_id,
enable_cdg=getattr(job, 'enable_cdg', False),
enable_txt=getattr(job, 'enable_txt', False),
# Redistributing an already-`complete` job: progress updates must not
# attempt status transitions (complete -> packaging is illegal and
# would abort the redistribution).
redistribute_mode=True,
)
orchestrator = VideoWorkerOrchestrator(
@@ -609,24 +601,6 @@ async def redistribute_video(job_id: str) -> bool:
await orchestrator._run_distribution()
await orchestrator._run_notifications()
# Verify the redistribution actually produced the archive before reporting
# success. The orchestrator swallows brand-code and Dropbox failures as
# non-fatal warnings, so an apparent "success" can hide a missing archive.
# Reporting success in that case would let the caller (public->private
# visibility change) delete the still-live public outputs against a
# non-existent private archive — the exact data-loss bug this path fixes.
if config.brand_prefix and not orchestrator.result.brand_code:
raise RuntimeError(
"Redistribution produced no brand code — archive identity is missing"
)
if config.dropbox_path:
dropbox_failed = any(
"Dropbox upload failed" in w
for w in (orchestrator.result.distribution_warnings or [])
)
if dropbox_failed:
raise RuntimeError("Redistribution failed to upload the Dropbox archive")
# Update job state_data with new distribution results
state_update = dict(job.state_data or {})
state_update['brand_code'] = orchestrator.result.brand_code
@@ -646,27 +620,6 @@ async def redistribute_video(job_id: str) -> bool:
except Exception as e:
logger.error(f"[job:{job_id}] WORKER_END worker=video-redistribute status=error error={e}")
# A brand code may have been allocated during _run_organization before the
# failure. It was never persisted to the job, so return it to the pool to
# avoid leaking a number (and, for a public->private change, so the caller's
# rollback leaves no orphaned NOMADNP code).
allocated = getattr(getattr(orchestrator, "result", None), "brand_code", None)
if allocated:
try:
from backend.services.brand_code_service import (
BrandCodeService,
get_brand_code_service,
)
prefix, number = BrandCodeService.parse_brand_code(allocated)
get_brand_code_service().recycle_brand_code(prefix, number)
logger.info(
f"[job:{job_id}] Recycled brand code {allocated} after failed redistribution"
)
except Exception as recycle_err:
logger.warning(
f"[job:{job_id}] Failed to recycle brand code {allocated} "
f"after failed redistribution: {recycle_err}"
)
return False
finally:
+7 -29
View File
@@ -105,14 +105,6 @@ class OrchestratorConfig:
dry_run: bool = False
non_interactive: bool = True
# Redistribution mode: when True, this orchestrator run is redistributing the
# finals of an already-`complete` job (e.g. a public->private visibility change)
# rather than driving a fresh job through its lifecycle. In this mode
# _update_progress must NOT attempt job status transitions — the job is (and
# stays) `complete`, and `complete -> packaging`/`encoding` are illegal
# transitions that would otherwise abort the redistribution.
redistribute_mode: bool = False
@dataclass
class OrchestratorResult:
@@ -242,28 +234,14 @@ class VideoWorkerOrchestrator:
return self._discord_service
def _update_progress(self, status: JobStatus, progress: int, message: str):
"""Update job progress if job_manager is available.
In redistribute_mode the job is already `complete` and must stay that way,
so we update only the progress percentage/message and skip the (illegal)
status transition. Outside redistribute_mode this drives the normal
lifecycle transition with validation.
"""
if not self.job_manager:
return
if self.config.redistribute_mode:
# Progress-only update; do not transition status (job stays `complete`).
self.job_manager.update_job(
self.config.job_id,
{"progress": progress},
"""Update job progress if job_manager is available."""
if self.job_manager:
self.job_manager.transition_to_state(
job_id=self.config.job_id,
new_status=status,
progress=progress,
message=message
)
return
self.job_manager.transition_to_state(
job_id=self.config.job_id,
new_status=status,
progress=progress,
message=message
)
async def run(self) -> OrchestratorResult:
"""
-1
View File
@@ -274,4 +274,3 @@ The cloud function does metadata-only checks via the GDrive API (fast, cheap, ca
- **2026-02-28**: Added SendGrid email (primary), kept Pushbullet (fallback). Added post-job trigger from backend. Added `scripts/check_public_share.py` for manual invocation. Motivated by NOMAD-1271 duplicate brand code incident where daily-only checks left a duplicate undetected for ~24 hours.
- **2026-03-02**: NOMAD-1276 incident fix. Post-job trigger now uses 5-minute Cloud Tasks delay instead of immediate invocation, preventing false "all clear" when E2E test files are still in GDrive during cleanup. Also fixed cross-folder gap detection (uses global max across all folders) and added 28 unit tests for the Cloud Function.
- **2026-03-06**: NOMAD-1295 gap. Stale GCE encoding cache (#499) caused job `f4a552bf` to produce bad output on first run (allocated NOMAD-1295, only CDG uploaded). Admin re-triggered the job, which allocated a new brand code (NOMAD-1297) without recycling 1295. Fix: recycled 1295 back to the pool. Updated docs to clarify that new gaps must always be investigated and fixed, never added to KNOWN_GAPS.
- **2026-08-18**: NOMAD-1537 gap. A **public→private visibility change** on job `25d076e5` (`Alma Nocturna – Mejor Cállate`) deleted the public GDrive/YouTube/Dropbox outputs and recycled 1537, then the private redistribution crashed (`redistribute_video` drove an illegal `complete → packaging` transition), so the change failed *after* the public files were already gone — a delete-first, no-rollback flow. The daily validator caught the hole; it self-closed when an unrelated public job reused the recycled 1537. **Going-private is a legitimate cause of a transient gap** (the number is recycled and refilled by the next public track) — the alert is expected and desired, not suppressed. Fixes (v0.196.1): `redistribute_video` runs in `redistribute_mode` (no status transition, stays `complete`); `change_to_private` is now **distribute-then-delete** (public outputs removed only after the private archive succeeds; on failure the job stays fully public); failed redistributions recycle any allocated `NOMADNP` code. Validator intentionally left unchanged.
@@ -1,11 +1,6 @@
# Handoff: Investigate prod finalization CPU efficiency / utilization — 2026-08-16
**Status:** ✅ RESOLVED 2026-08-16 — outcome (a): CPU already well-utilized (NOT
capped at 8 cores); removed dead `ffmpeg_threads` config. Empirical measurement +
resolution appended at the bottom under "RESOLUTION". The original investigation
brief follows unchanged for context.
**Status (original):** OPEN investigation (not started). Written for a fresh Claude session —
**Status:** OPEN investigation (not started). Written for a fresh Claude session —
self-contained; all facts you need are inlined below or in the linked repo docs.
**Origin:** surfaced by the encode-worker multi-instance-type benchmark
(`docs/archive/2026-08-15-encoding-instance-type-diversity-plan.md`; benchmark
@@ -144,71 +139,3 @@ close this out and just fix the stale comment; or (b) confirm an ~2–4× idle-c
gap → raise threads / parallelize formats, validate the speedup and RAM headroom,
ship it. Bump `pyproject.toml` version; if the fix is in the wheel's
`LocalEncodingService`, it ships via the normal wheel → `ensure_latest_wheel` path.
---
## RESOLUTION (2026-08-16) — outcome (a): already efficient; dead config removed
**Verdict: the "leaving 75% idle" fear is unfounded. Finalization uses ~21–25 of a
worker's 32 vCPUs during every heavy libx264 stage. No threading fix warranted.**
### 1. `ffmpeg_threads` is dead config — confirmed statically AND empirically
- Before this change, `grep -rn ffmpeg_threads backend/` returned exactly one hit —
the setter `"ffmpeg_threads": 8` in the `encoding_config` dict at
`video_worker.py:131` — with zero consumers; `EncodingConfig(...)` at
`gce_encoding/main.py:1111` never passes it. This change removes that setter
(line 131 is now the explanatory NOTE comment), so grep now returns no setter.
- **Empirically**, the deployed ffmpeg argv captured mid-encode (`ps`/probe on the
worker) carry **no `-threads` flag** on any finalization command — x264 runs its
all-core auto default. Sample argv observed:
- `… -i with_vocals.mkv -c:v libx264 -c:a copy … (With Vocals).mp4`
- `… concat=n=3… -c:v libx264 -c:a pcm_s16le … (Final Karaoke Lossless 4k).mp4`
- `… -i …Lossless 4k.mp4 -c:v copy -c:a aac … (Lossy 4k).mp4`
- `… -c:v libx264 -vf scale=1280:720 -preset medium -tune animation … (Lossy 720p).mp4`
### 2. Process-level CPU measurement (the point of this task)
Method: started `encoding-worker-fallback-c4a` (c4-highcpu-32, 32 vCPU / 62 GB),
recreated the bench input, POSTed `/encode` **directly to the VM IP**, and sampled
`top -bH -d 2` on that same VM for the whole run. The authoritative signal is the
system-wide `%Cpu(s)` summary line (0–100% across all 32 cores):
| Stage (serial) | ffmpeg cmd | `%Cpu us` (of 32) | ≈cores busy | peak RSS | ~duration |
|---------------------------|------------------------------------|-------------------|-------------|----------|-----------|
| "With Vocals" mp4 convert | `libx264 -c:a copy` (mkv→mp4) | 64–70% | ~21 | ~11 GB | ~59 s |
| **Lossless 4K concat** | `libx264 -c:a pcm_s16le` | 72–75% | ~23 | ~9 GB | ~45 s |
| Lossy 4K | `-c:v copy -c:a aac` (stream copy) | 3–5% | I/O-bound | <0.1 GB | ~4 s |
| MKV (YouTube) | `-c:v copy -c:a flac` (copy) | low | I/O-bound | — | ~2 s |
| 720p | `libx264 scale=1280:720 -preset medium` | 76–78% | ~25 | ~1.2 GB | ~12 s |
Full run: ~122 s of encoding + ~35 s GCS download/upload = **~158 s wall** (matches
the ~139 s c4 baseline plus I/O). An 8-core cap would show `us≈25%, idle≈75%`; we
observed the **opposite** (`us≈66–78%, idle≈22–34%`). Not capped.
### 3. Why the residual ~25–30% idle is NOT recoverable by more threads
The heavy processes already spawn 90–162 OS threads (`nlwp`); x264's auto default is
~1.5×cores. The idle is the structural ceiling of x264 **frame-threading**
(inter-frame dependencies + a partially-serial lookahead), not a thread cap. Forcing
`-threads 32`/`-x264-params threads=N` above auto gives negligible speed and can hurt
quality. **Formats are serial and dependency-chained** (`encode_all_formats` steps
3→{4,5,6}; lossy/mkv/720p all consume the lossless output), and the only overlap-able
work after lossless is two near-free stream copies (lossy, mkv) — so parallelizing
formats buys ~nothing and would raise peak RAM against the 32 GB fallback floor +
the `ENCODING_HEAVY_CONCURRENCY=1` OOM constraint. Not worth it.
### 4. What shipped
- Removed the dead `"ffmpeg_threads": 8` field + stale `c4-standard-8` comment at
`video_worker.py:131`, replaced with a NOTE explaining the measured all-core
behaviour (so nobody re-opens this). No behaviour change. Version bump only.
### 5. Follow-up worth its own task (NOT done here — out of scope, needs verification)
The single biggest CPU cost is the **"With Vocals" preview** — a full 4K libx264
re-encode (~59 s, longer than the lossless master itself). The source
`with_vocals.mkv` is **already H.264** (High 4:4:4 Predictive, 3840×2160, `yuv444p`).
If nothing downstream needs a re-encode / a different `pix_fmt`, this could become a
container remux (`-c:v copy`) and save ~40–50 s/job — a far bigger win than any
threading tweak. Requires confirming: (a) do players/consumers need `yuv420p` (4:4:4
mp4 is poorly supported), and (b) does `convert_mov_to_mp4` intentionally normalize
pix_fmt? Left for a dedicated investigation.
### Operational note
Bench VM stopped, `gs://…/bench/**` deleted after the run, per hygiene.
@@ -1,71 +0,0 @@
# "With Vocals" preview encode — faster, smaller, more portable (2026-08-16)
**Status:** ✅ SHIPPED (v0.196.0). Follow-up from the finalization-CPU investigation
(`2026-08-16-finalization-cpu-efficiency-handoff.md`), which identified the "With
Vocals" conversion as the single longest finalization stage.
## Problem
`convert_mov_to_mp4` produces the **"(With Vocals).mp4"** sing-along deliverable from
the renderer's source video. Process-level measurement on a live c4-highcpu-32 worker
showed this was the **longest single finalization stage (~59s)** — longer than the
lossless master itself.
Probing a real prod job (`faafd5ad`) revealed the encode was *accidentally* bad:
- **No `-pix_fmt`** → inherited the renderer's `High 4:4:4 Predictive / yuv444p`. This
is the **only** 4:4:4 file in the deliverable set (every other output is `yuv420p`),
and 4:4:4 H.264 is rejected by many browsers/TVs/phones.
- **Default `medium` preset** → slow.
- **`-c:a copy`** (LocalEncodingService path) → **FLAC-in-MP4**, which is non-standard,
despite the customer-facing spec (`template_service.py`) documenting the file as
"4k H264/**AAC**".
## Safety check — is the "With Vocals" mp4 used downstream?
**No.** Confirmed in both encode paths (cloud `encode_all_formats` and local
`KaraokeFinalise.remux_and_encode_output_video_files`): every later output (Karaoke.mp4,
Lossless/Lossy/720p, MKV) derives from the **source** `with_vocals` file (via
`remux_with_instrumental` → `Karaoke.mp4` → concat) and carries the **instrumental**
audio. YouTube upload uses `final_karaoke_lossless_mkv`. The "(With Vocals).mp4" is
written once and only uploaded/delivered — a leaf. So its encode can be chosen purely
for the deliverable.
## Fix
`convert_mov_to_mp4` software (CPU) command — the path that runs on prod workers
(no NVENC) — changed to:
```
-c:v libx264 -pix_fmt yuv420p -preset veryfast -c:a aac -ar 48000 -b:a 320k -movflags +faststart
```
Applied to **both** implementations (kept in sync):
- `backend/services/local_encoding_service.py::LocalEncodingService.convert_mov_to_mp4`
(cloud worker — prod)
- `karaoke_gen/karaoke_finalise/karaoke_finalise.py::KaraokeFinalise.convert_mov_to_mp4`
(local CLI; already emitted AAC, now also 4:2:0 + veryfast + 320k)
GPU/NVENC command: emits AAC 320k; `h264_nvenc` encodes 4:2:0 natively so no `-pix_fmt`
needed. (Prod workers are CPU-only; NVENC is a local/GPU path.)
## Measured result (real source: Arctic Monkeys – Riot Van, 138s 4K)
| Metric | Before (prod) | After |
|---|---|---|
| Encode time | 56 s | **29 s** (~2×) |
| File size | 22 MB | **14 MB** (~36% smaller) |
| Video | h264 High 4:4:4 / yuv444p | **h264 High / yuv420p** |
| Audio | FLAC-in-mp4 (~639 kbps) | **AAC-LC 48 kHz / 320 kbps** |
This is the longest finalization stage, so ~halving it cuts **~20-25% off total
finalization wall-time**. The file gets **smaller** (AAC 320k ≪ FLAC ~639k, and 4:2:0
< 4:4:4), so there is no size/CPU tradeoff — every axis improves, plus universal
playback and spec-alignment.
## Notes / non-goals
- Quality: for karaoke content (static background + text) `veryfast` vs `medium` is
visually negligible; CRF-based, comparable bitrate.
- The finalise-only **user-upload** path (a user's own `.mov`/`.mkv`, arbitrary codec)
still re-encodes correctly — the command is codec-agnostic (no stream-copy assumption).
- Not touched: whether a "reference" file needs to be 4K at all (a 1080p variant would
be smaller still) — a product decision, left for later.
@@ -1,204 +0,0 @@
# Plan: Fix visibility-change redistribution + make sequence-gap alerts recycle-aware
**Created:** 2026-08-18
**Branch:** feat/sess-20260818-1124-visibility-recycle-dataloss
**Status:** Draft
## Overview
Investigation of a "GDrive Validation: missing 1537" alert traced to a **public→private
visibility change** on NOMAD-1537 (`Alma Nocturna – Mejor Cállate`, job `25d076e5`),
not a brand-code allocation race. Two real defects and one policy gap were found:
1. **`redistribute_video` always crashes** on `complete → packaging`
(`video_worker_orchestrator.py:661`), so **every** public→private conversion silently
fails its private-side redistribution — the track is never archived to the
`Tracks-NonPublished` Dropbox and never gets a `NOMADNP` code. It looks fine to the
customer because downloads serve from GCS finals.
2. **`change_to_private` deletes first, rebuilds second, with no rollback**
(`visibility_change_service.py:74-114`): it deletes YouTube/Dropbox/GDrive + recycles
the public number, *then* calls the (always-failing) redistribution. Each failure also
**leaks a `NOMADNP` code** (allocated, never saved, never recycled — e.g. `NOMADNP-0214`).
3. **The gdrive-validator has no awareness of intentionally-vacated numbers.** Going-private
recycles the public number (kept behaviour — see Decisions). Between recycle and the next
public job reusing it, the number is legitimately absent from the public share, so the
daily validator fires a false "missing" alert. (Here, `e921ab26 / Luvcat – Spider` later
reused 1537, closing the gap ~5h after the alert.)
### Root-cause timeline (UTC 2026-08-18, confirmed from logs)
- `00:05:54–58` — public→private on `25d076e5`: deleted YouTube `TJUKJRyb5MQ`, Dropbox folder,
GDrive public-share files for 1537; recycled `NOMAD-1537`; cleared distribution state.
- `00:06:07` — allocated `NOMADNP-0214`, started distribution, crashed
`Invalid state transition … complete -> packaging`; redistribution aborted, **no rollback**.
- `01:00:11` — gdrive-validator daily run reports `CDG/MP4/MP4-720p: missing 1537` → the alert.
- `05:5x` — unrelated public job `e921ab26` (Luvcat – Spider) allocated the recycled `1537`
and published under it.
- `07:0x` — GCS/divebar mirror pulled `NOMAD-1537 - Luvcat - Spider.*` → gap closed.
Customer impact: **none** — `25d076e5` is a healthy private track (GCS-backed downloads work).
Internal impact: no `Tracks-NonPublished` archive / `NOMADNP` code for it; one leaked private
code; spurious operator alert.
## Decisions (from product owner, 2026-08-18)
- **Number policy: recycle & reuse (keep current).** A vacated public number returns to the
pool and the next public job fills it.
- **Validator: leave as-is — the transient gap warning is DESIRED.** Going-private is rare, the
gap fills naturally on the next public track, and the owner explicitly wants the alert even
in that case. → **Part E is dropped**; no change to `gdrive_validator/main.py` or
`check_public_share.py`. Do not add anything to static `KNOWN_GAPS` either.
- **Private archive: yes — fix redistribution.** Going-private must archive to
`Tracks-NonPublished` with a `NOMADNP` code, consistent with native-private jobs, and must
be atomic (public outputs removed only after the private archive succeeds).
Scope is therefore **A–D only** (fix + harden the redistribution path and recover the one
affected job); the alerting pipeline is intentionally untouched.
## Requirements
- [ ] **A.** `redistribute_video` runs org+distribution+notifications on a `complete` job
without an illegal status transition; job remains `complete` throughout.
- [ ] **B.** `change_to_private` is **distribute-then-delete**: private redistribution +
`NOMADNP` allocation succeed *before* public YouTube/Dropbox/GDrive deletion + public
number recycle. On any failure: no public deletion, no leaked private code, job stays
fully public and `complete`.
- [ ] **C.** No leaked `NOMADNP` codes: a private code allocated during a redistribution that
later fails is recycled (or not allocated until the success path).
- [ ] **D.** Recover `25d076e5` (create its NonPublished archive + `NOMADNP` code) and recycle
the leaked `NOMADNP-0214`.
- [ ] Regression tests for A, B, C. All existing `test_change_visibility.py` tests still pass.
- [ ] Validator and `KNOWN_GAPS` unchanged (transient going-private alert is desired).
**Out of scope (explicitly not doing):** ~~E — recycle-aware validator~~. The owner wants to keep
receiving the gap warning for going-private events; it self-resolves on the next public track.
## Technical Approach
### A. Fix the `complete → packaging` crash (proximate bug)
`redistribute_video` (`backend/workers/video_worker.py:481`) reuses
`VideoWorkerOrchestrator._run_organization/_run_distribution/_run_notifications`;
`_run_distribution` calls `self._update_progress(JobStatus.PACKAGING, 90, …)`
(`video_worker_orchestrator.py:661`), which invokes `JobManager.transition_status(...,
raise_on_invalid=True)`. From `complete` that's illegal (`models/job.py:193`:
`COMPLETE → [AWAITING_REVIEW, LYRICS_COMPLETE]`).
**Chosen fix:** add a `redistribute_mode: bool = False` flag to `OrchestratorConfig`
(or an `update_status: bool` param threaded to `_update_progress`). When set, `_update_progress`
updates the progress **percentage/message only** and **skips the status write**, leaving the job
`complete`. Rationale: a redistribution is not a lifecycle change; the job is and remains
complete. Avoids polluting `STATE_TRANSITIONS` with a `COMPLETE↔PACKAGING` round-trip that other
call sites could misuse.
- Guard: keep `raise_on_invalid=True` for the normal pipeline; the flag only bypasses the write.
- Verify no other stage in the redistribute-only path (`_run_organization`, `_run_distribution`,
`_run_notifications`) performs a status transition that assumes a fresh pipeline.
### B. Distribute-then-delete + rollback (`change_to_private`) — as implemented
1. **Capture the public output references** (`youtube_url`, `brand_code`, `gdrive_files`,
`dropbox_path`, artist/title) from the job snapshot *before* anything mutates state —
redistribution overwrites `state_data` with the new private values.
2. Set the guard flag **and** `is_private=True` up front (a *temporary* flag) so
`get_effective_distribution_for_job()` selects the private destination during redistribution.
No "changed to private" timeline event yet.
3. **Redistribute to the private destination** (`redistribute_video`): reuse GCS finals
(`keep_gcs_finals` stays true — never deleted for this path), upload to `Tracks-NonPublished`,
allocate `NOMADNP` code. Public outputs are still live at this point.
4. **If redistribution fails** (raises or returns False): revert `is_private=False`, clear the
guard flag, re-raise `RuntimeError("Redistribution failed …")`. No public output was touched,
and `redistribute_video` already recycled any `NOMADNP` code it allocated (C) — a failed
going-private is a clean no-op.
5. **On success**, the private archive exists and the move has committed — from here we do
**not** revert to public. Delete the *public* outputs (YouTube, public Dropbox folder, public
GDrive files) via `_delete_public_outputs` (best-effort, never raises) and **recycle the public
`NOMAD` number** — but only if every public deletion succeeded (else keep the number reserved
to avoid a future duplicate). Then record the "changed to private" timeline event and clear the
guard flag.
Note the YouTube deletion is irreversible, which is *why* it must be last — the old delete-first
order could never be safely rolled back. `redistribute_video` additionally verifies the archive
actually materialized (brand code allocated + Dropbox upload not failed) before returning success,
because the orchestrator swallows brand-code/Dropbox failures as warnings; without this a false
"success" would delete the public outputs against a non-existent private archive.
### C. No leaked private codes
Two options; prefer (i):
- (i) Allocate the `NOMADNP` code inside the redistribution success path only; if redistribution
fails before it is persisted, nothing to recycle. Where allocation already happens early
(orchestrator `_run_organization`), wrap the redistribute call so a failure recycles
`orchestrator.result.brand_code` if one was allocated.
- (ii) Always recycle `orchestrator.result.brand_code` in the `except` path of `change_to_private`.
### D. Recovery (operational, after A–C deployed)
- **`25d076e5`:** re-run the fixed private redistribution (finals + packages confirmed present in
`gs://…/jobs/25d076e5/{finals,packages}/`). Produces the NonPublished archive + `NOMADNP` code.
Use the admin re-distribute path or a one-off `redistribute_video('25d076e5')` invocation.
- **Leaked `NOMADNP-0214`:** recycle into `brand_code_counters/NOMADNP.recycled` (currently
`next_number=216, recycled=[215]`), or leave — private prefixes aren't validated. Recycle for
hygiene.
- No action needed on `NOMAD-1537` (already correctly reused by Luvcat, gap closed).
### E. (dropped)
Recycle-aware validator suppression is intentionally **not** implemented — see Decisions. The
transient going-private gap warning is desired and self-resolves on the next public track. The
post-job re-validation trigger (`video_worker_orchestrator.py:305`, gated on `gdrive_folder_id`)
is correct as-is for private conversions (no public folder to re-check).
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/workers/video_worker_orchestrator.py` | Modify | `redistribute_mode`/`update_status` flag; `_update_progress` skips status write when set |
| `backend/workers/video_worker.py` | Modify | `redistribute_video` passes the flag; recycle allocated code on failure |
| `backend/services/visibility_change_service.py` | Modify | Reorder `change_to_private` to distribute-then-delete; split `_delete_distributed_outputs`; recycle-on-failure |
| `backend/models/job.py` | Review | Confirm no `STATE_TRANSITIONS` change needed (preferred: none) |
| `backend/tests/test_change_visibility.py` | Modify | Real distribute-then-delete + rollback assertions (not just guard-flag) |
| `backend/tests/test_video_worker_redistribute.py` | Create | `redistribute_video` on `complete` job succeeds, no illegal transition |
| `docs/GDRIVE-VALIDATOR.md` | Modify | Add incident to History; note going-private is a legitimate (alerting) cause of gaps |
| `pyproject.toml` | Modify | Version bump |
## Testing Strategy
Follow `docs/TESTING.md`; backend unit/integration in `backend/tests/` (mock GCP), validator
unit in `infrastructure/functions/gdrive_validator/test_main.py`.
- **A:** `redistribute_video` on a `complete` job runs all three stages and does **not** raise
`InvalidStateTransitionError`; job status stays `complete`; brand_code/dropbox_link written.
- **B:** `change_to_private` — (a) success path: private redistribute called *before* any public
delete; public delete + public-code recycle happen only after; (b) failure path: redistribution
raises → **assert public YouTube/Dropbox/GDrive delete were NOT called**, `is_private` stays
False, guard flag cleared, exception re-raised. Strengthen the existing
`test_rollback_on_redistribute_failure` (today only checks the guard flag).
- **C:** redistribution failure → allocated `NOMADNP` code is recycled exactly once.
- **Regression:** full `test_change_visibility.py` + `test_brand_code_service.py` green.
- **Post-deploy (once):** re-run `python scripts/check_public_share.py` → clean; recover
`25d076e5` and confirm NonPublished archive + `NOMADNP` code appear.
## Recovery Runbook (D)
```python
# After A–C deployed. Recover the private archive for 25d076e5 (finals present in GCS).
from backend.workers.video_worker import redistribute_video
await redistribute_video("25d076e5") # job already is_private=True → NonPublished + NOMADNP
# Recycle the leaked private code
from backend.services.brand_code_service import get_brand_code_service
get_brand_code_service().recycle_brand_code("NOMADNP", 214)
```
## Open Questions
- [ ] Preferred A mechanism: config `redistribute_mode` flag vs. threading `update_status=False`
through `_update_progress`? (Leaning: config flag — single choke point.)
- [ ] For B, is it acceptable for the private `Tracks-NonPublished` archive to exist *simultaneously*
with the still-live public outputs for the few seconds before public deletion? (Expected: yes.)
## Rollback Plan
- Pure backend code; no schema changes, no infra/validator changes. Revert the PR to restore prior
behaviour.
- `redistribute_mode` is opt-in (only the redistribute path sets it); the normal pipeline is
unaffected, so A/B cannot regress fresh-job distribution.
- Recovery step (D) is idempotent-ish: re-running `redistribute_video` re-uploads from GCS finals;
safe to retry.
```
+29 -88
View File
@@ -1,20 +1,15 @@
// frontend/e2e/helpers/stripe-checkout.ts
import { Page, Locator } from '@playwright/test';
import { Page } from '@playwright/test';
/**
* Automate Stripe's hosted checkout page (checkout.stripe.com).
*
* Stripe Checkout's layout depends on how many payment methods are enabled:
* - Multiple methods → an accordion of radio buttons (Card, Cash App Pay, …);
* "Card" must be selected to reveal the card fields (historically in iframes).
* - Single method (Card only, current prod as of Aug 2026) → the card fields
* (number, expiry, CVC, name, ZIP) render directly with no radio to select.
* Because the whole page is on checkout.stripe.com, card fields are direct
* inputs rather than cross-origin iframes.
* A "Pay" button sits at the bottom in both layouts.
*
* This helper handles both layouts: it only clicks the "Card" radio when one is
* actually present, and fills fields via direct locators with an iframe fallback.
* Stripe Checkout (as of April 2026) shows:
* - "Pay with Link" / "Pay with Klarna" buttons at top
* - Payment method radio buttons: Card, Cash App Pay, Klarna, Bank
* - Clicking "Card" reveals card input fields (number, expiry, CVC)
* - Card fields are inside iframes within the page
* - A "Pay" button at the bottom
*
* Environment variables:
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY,
@@ -64,34 +59,17 @@ export async function completeStripeCheckout(page: Page): Promise<void> {
await page.screenshot({ path: 'test-results/stripe-checkout-loaded.png' });
console.log(' Stripe Checkout loaded');
// Step 2: Select "Card" payment method (only if a selector is present)
// Stripe's Checkout layout varies with the number of enabled payment methods:
// - Multiple methods → an accordion of radio buttons; "Card" must be selected.
// - Single method (Card only) → card fields render directly, no radio exists.
// As of Aug 2026 production serves the single-method layout: the card number,
// expiry and CVC are shown immediately with no "Card" radio. Waiting on a radio
// that never appears is what previously hung this step for 10s.
// Step 2: Select "Card" payment method
// Stripe uses an accordion with radio buttons overlaid by buttons.
// Use force:true to bypass the overlay interception.
console.log(' Selecting Card payment method...');
const cardNumberField = cardFieldLocator(page, 'cardNumber');
const cardRadio = page.getByRole('radio', { name: 'Card' });
await cardRadio.check({ force: true, timeout: 10_000 });
console.log(' Card payment method selected');
if (await cardNumberField.isVisible({ timeout: 5_000 }).catch(() => false)) {
console.log(' Card fields already visible (single payment method) — no radio to select');
} else {
const cardRadio = page.getByRole('radio', { name: 'Card' });
if (await cardRadio.count()) {
// Accordion layout — bypass the overlay interception with force:true.
await cardRadio.check({ force: true, timeout: 10_000 });
console.log(' Card payment method selected via radio');
} else {
console.log(' No Card radio found — waiting for card fields to render...');
}
// Give Stripe a moment to render the card inputs (iframes or direct fields).
await cardNumberField
.waitFor({ state: 'visible', timeout: 15_000 })
.catch(() => console.log(' WARNING: card number field not visible after selecting Card'));
}
await page.waitForTimeout(1000);
// Wait for card input fields to appear after selecting Card
// Stripe renders card fields inside iframes after the radio is clicked
await page.waitForTimeout(2000);
await page.screenshot({ path: 'test-results/stripe-card-selected.png' });
// Step 3: Fill card number
@@ -110,10 +88,7 @@ export async function completeStripeCheckout(page: Page): Promise<void> {
// Step 6: Fill cardholder name if field exists
if (card.name) {
const nameInput = page
.locator('#billingName, input[name="billingName"], input[placeholder="Full name on card"]')
.or(page.getByRole('textbox', { name: /cardholder name/i }))
.first();
const nameInput = page.locator('#billingName, input[name="billingName"]');
if (await nameInput.isVisible({ timeout: 2000 }).catch(() => false)) {
console.log(' Filling cardholder name...');
await nameInput.fill(card.name);
@@ -121,10 +96,7 @@ export async function completeStripeCheckout(page: Page): Promise<void> {
}
// Step 6b: Fill ZIP code (required for US cards)
const zipInput = page
.locator('#billingPostalCode, input[name="billingPostalCode"], input[placeholder="ZIP"]')
.or(page.getByRole('textbox', { name: /^zip$|postal code/i }))
.first();
const zipInput = page.locator('#billingPostalCode, input[name="billingPostalCode"], input[placeholder="ZIP"]');
if (await zipInput.isVisible({ timeout: 2000 }).catch(() => false)) {
console.log(' Filling ZIP code...');
await zipInput.fill(process.env.E2E_STRIPE_ZIP || '10001');
@@ -158,57 +130,26 @@ export async function completeStripeCheckout(page: Page): Promise<void> {
}
/**
* Accessible-name and placeholder metadata for each Stripe card field, used to
* build robust locators that work whether Stripe renders the field as a direct
* input (current single-payment-method layout) or inside an iframe.
*/
const CARD_FIELD_META: Record<string, { name: RegExp; placeholder?: string }> = {
cardNumber: { name: /card number/i, placeholder: '1234 1234 1234 1234' },
cardExpiry: { name: /expiration|expiry/i, placeholder: 'MM / YY' },
cardCvc: { name: /^cvc$|security code/i },
};
/**
* Locator for a Stripe card field rendered directly in the main frame (i.e. not
* inside an iframe). Matches by Stripe's stable field-name attribute, element id,
* input name, or placeholder — whichever the current Checkout layout uses.
*/
function cardFieldLocator(page: Page, fieldName: string): Locator {
const meta = CARD_FIELD_META[fieldName];
const selectors = [
`[data-elements-stable-field-name="${fieldName}"]`,
`#${fieldName}`,
`input[name="${fieldName}"]`,
];
if (meta?.placeholder) selectors.push(`input[placeholder="${meta.placeholder}"]`);
return page.locator(selectors.join(', ')).first();
}
/**
* Fill a card field by name. Tries direct inputs (id / stable-field-name /
* placeholder / accessible name) first, then falls back to iframe-based inputs.
* Fill a card field by name. Tries direct input first, then iframe-based.
*
* Stripe Checkout renders card fields as direct inputs in the single-payment-
* method layout, or inside iframes when using the classic Elements accordion.
* Stripe Checkout card fields use IDs like #cardNumber, #cardExpiry, #cardCvc
* when rendered as direct inputs, or are inside iframes when using Elements.
*/
async function fillCardField(page: Page, fieldName: string, value: string): Promise<void> {
// Try 1: Direct input by stable-field-name / id / name / placeholder
const directInput = cardFieldLocator(page, fieldName);
// Try 1: Direct input by ID
const directInput = page.locator(`#${fieldName}`);
if (await directInput.isVisible({ timeout: 3000 }).catch(() => false)) {
await directInput.click();
await directInput.type(value, { delay: 50 });
return;
}
// Try 2: Direct input by accessible name (aria-label)
const meta = CARD_FIELD_META[fieldName];
if (meta) {
const roleInput = page.getByRole('textbox', { name: meta.name }).first();
if (await roleInput.isVisible({ timeout: 2000 }).catch(() => false)) {
await roleInput.click();
await roleInput.type(value, { delay: 50 });
return;
}
// Try 2: Direct input by data attribute
const dataInput = page.locator(`[data-elements-stable-field-name="${fieldName}"]`);
if (await dataInput.isVisible({ timeout: 2000 }).catch(() => false)) {
await dataInput.click();
await dataInput.type(value, { delay: 50 });
return;
}
// Try 3: Input inside an iframe (Stripe Elements)
@@ -886,28 +886,19 @@ class KaraokeFinalise:
self.execute_command(ffmpeg_command, "Remuxing video with instrumental audio")
def convert_mov_to_mp4(self, input_file, output_file):
"""Convert the source "With Vocals" video (MOV/MKV) to a standard, portable MP4.
Produces the "(With Vocals).mp4" sing-along deliverable — a leaf output (no
later encode reads it). ``-preset veryfast`` roughly halves this stage (the
longest finalization stage) with negligible quality impact for karaoke content;
AAC 320k keeps the audio portable. yuv420p (playback compatibility) comes from
``self.mp4_flags``, which already carries ``-pix_fmt yuv420p``. Kept in sync
with LocalEncodingService.convert_mov_to_mp4 (whose MP4_FLAGS lacks pix_fmt, so
that variant sets ``-pix_fmt yuv420p`` explicitly).
"""
# Hardware-accelerated version (pix_fmt yuv420p supplied via self.mp4_flags)
"""Convert MOV file to MP4 format with hardware acceleration support"""
# Hardware-accelerated version
gpu_command = (
f'{self.ffmpeg_base_command} {self.hwaccel_decode_flags} -i "{input_file}" '
f'-c:v {self.video_encoder} {self.get_nvenc_quality_settings("high")} -c:a {self.aac_codec} -ar 48000 -b:a 320k {self.mp4_flags} "{output_file}"'
f'-c:v {self.video_encoder} {self.get_nvenc_quality_settings("high")} -c:a {self.aac_codec} -ar 48000 {self.mp4_flags} "{output_file}"'
)
# Software fallback version
cpu_command = (
f'{self.ffmpeg_base_command} -i "{input_file}" '
f'-c:v libx264 -preset veryfast -c:a {self.aac_codec} -ar 48000 -b:a 320k {self.mp4_flags} "{output_file}"'
f'-c:v libx264 -c:a {self.aac_codec} -ar 48000 {self.mp4_flags} "{output_file}"'
)
self.execute_command_with_fallback(gpu_command, cpu_command, "Converting MOV video to MP4")
def encode_lossless_mp4(self, title_mov_file, karaoke_mp4_file, env_mov_input, ffmpeg_filter, output_file):
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.196.1"
version = "0.195.1"
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"
@@ -138,11 +138,11 @@ def test_convert_mov_to_mp4_aac(mock_execute_fallback, finaliser_with_aac):
expected_gpu_cmd = (
f'{finaliser_with_aac.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -preset p4 -tune hq -cq 18 -c:a aac -ar 48000 -b:a 320k {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -preset p4 -tune hq -cq 18 -c:a aac -ar 48000 {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
expected_cpu_cmd = (
f'{finaliser_with_aac.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -preset veryfast -c:a aac -ar 48000 -b:a 320k {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -c:a aac -ar 48000 {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
mock_execute_fallback.assert_called_once_with(expected_gpu_cmd, expected_cpu_cmd, "Converting MOV video to MP4")
@@ -153,11 +153,11 @@ def test_convert_mov_to_mp4_aac_at(mock_execute_fallback, finaliser_with_aac_at)
expected_gpu_cmd = (
f'{finaliser_with_aac_at.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -preset p4 -tune hq -cq 18 -c:a aac_at -ar 48000 -b:a 320k {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -preset p4 -tune hq -cq 18 -c:a aac_at -ar 48000 {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
expected_cpu_cmd = (
f'{finaliser_with_aac_at.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -preset veryfast -c:a aac_at -ar 48000 -b:a 320k {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -c:a aac_at -ar 48000 {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
mock_execute_fallback.assert_called_once_with(expected_gpu_cmd, expected_cpu_cmd, "Converting MOV video to MP4")
@@ -398,11 +398,11 @@ def test_convert_mov_to_mp4_aac_nvenc(mock_execute_fallback, finaliser_with_nven
expected_gpu_cmd = (
f'{finaliser_with_nvenc_aac.ffmpeg_base_command} {finaliser_with_nvenc_aac.hwaccel_decode_flags} -i "{WITH_VOCALS_MOV}" '
f'-c:v h264_nvenc -preset p4 -tune hq -cq 18 -c:a aac -ar 48000 -b:a 320k {finaliser_with_nvenc_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v h264_nvenc -preset p4 -tune hq -cq 18 -c:a aac {finaliser_with_nvenc_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
expected_cpu_cmd = (
f'{finaliser_with_nvenc_aac.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -preset veryfast -c:a aac -ar 48000 -b:a 320k {finaliser_with_nvenc_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -c:a aac {finaliser_with_nvenc_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
mock_execute_fallback.assert_called_once_with(expected_gpu_cmd, expected_cpu_cmd, "Converting MOV video to MP4")
@@ -414,11 +414,11 @@ def test_convert_mov_to_mp4_aac_at_nvenc(mock_execute_fallback, finaliser_with_n
expected_gpu_cmd = (
f'{finaliser_with_nvenc_aac_at.ffmpeg_base_command} {finaliser_with_nvenc_aac_at.hwaccel_decode_flags} -i "{WITH_VOCALS_MOV}" '
f'-c:v h264_nvenc -preset p4 -tune hq -cq 18 -c:a aac_at -ar 48000 -b:a 320k {finaliser_with_nvenc_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v h264_nvenc -preset p4 -tune hq -cq 18 -c:a aac_at {finaliser_with_nvenc_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
expected_cpu_cmd = (
f'{finaliser_with_nvenc_aac_at.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
f'-c:v libx264 -preset veryfast -c:a aac_at -ar 48000 -b:a 320k {finaliser_with_nvenc_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
f'-c:v libx264 -c:a aac_at {finaliser_with_nvenc_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
)
mock_execute_fallback.assert_called_once_with(expected_gpu_cmd, expected_cpu_cmd, "Converting MOV video to MP4")