fix(jobs): never report a clip that was never rendered

main.py's clip worker pool swallows a per-clip exception (it only prints
"Clip N failed") and the process still exits 0, and the metadata JSON is
written BEFORE any clip renders. app.py rebuilt the finished job's result
from that metadata and named every clip through _canonical_clip_file,
which returns a filename whether or not the file exists.

So a job whose renders ALL failed was reported as completed with N clips:
the minute reservation was committed, ClipsDelivered fired, archive_job
skipped every missing file and uploaded the metadata alone (returning
before it writes the Project row, so the job was neither restorable nor
visible in history), and the dashboard offered clips whose only existence
was a title. Hitting "download all" on one then answered 404 "No clip
files found for this job" - reported as ticket #4711, job 89d76bbc: two
titles, two viral scores, blank players, minutes gone.

Measured over the R2 archive on 7-sep-2026, this is not an edge case:
195 of 1687 archived jobs hold a metadata file and not one clip, across
184 users. On a 200-job sample since 1-aug, 14.6% of all promised clips
were never delivered while every one of those jobs was billed and
counted as a success.

_clips_actually_rendered keeps only the clips whose file is on disk and
non-empty, preferring main.py's own CLIP_READY marker (what the file IS)
over the name rebuilt from the convention (a guess). A job that rendered
nothing is now marked failed, so _settle_reservation releases the
minutes instead of committing them and the outcome is tracked as
JobFailed.

Claude-Session: https://claude.ai/code/session_01UZGqjYcZyfmKww1gcyKrp5
This commit is contained in:
juancarlos.cavero 2026-09-07 15:31:08 +02:00
parent 925583efdd
commit ff2ad3d1b4
2 changed files with 180 additions and 5 deletions

62
app.py
View file

@ -500,6 +500,50 @@ def _canonical_clip_file(output_dir, base_name, index):
return os.path.basename(max(derived, key=os.path.getmtime)) return os.path.basename(max(derived, key=os.path.getmtime))
def _clips_actually_rendered(job_id, output_dir, base_name, clips):
"""Keep only the clips whose file is really on disk. Returns (kept, missing).
The metadata JSON is written BEFORE any clip renders, and main.py's worker
pool swallows a per-clip exception (it only prints "❌ Clip N failed") and
still exits 0. So ``shorts`` is what Gemini promised, not what ffmpeg
produced, and ``_canonical_clip_file`` happily returns the name of a file
that was never written.
Handing those back as delivered clips is what let a job that rendered
NOTHING be marked completed: the minutes were committed, ClipsDelivered
fired, ``archive_job`` skipped every missing file and uploaded the metadata
alone — which, because it returns before writing the Project row, left the
job unrestorable and invisible in history — and the dashboard offered clips
whose only existence was a title, so "download all" answered 404 "No clip
files found for this job" (ticket #4711, job 89d76bbc, 6-sep-2026).
Measured over the R2 archive on 7-sep-2026: 195 of 1687 archived jobs held
a metadata file and not one clip, across 184 users.
Trust the disk, not the promise.
"""
# main.py announces the file it actually finished for each clip
# (CLIP_READY, printed after the whole reframe/watermark/hook/caption
# chain). Prefer it over rebuilding the name: the marker is what the file
# IS, _canonical_clip_file is a guess from the naming convention.
ready_files = (jobs.get(job_id) or {}).get('ready_files') or {}
kept = []
for i, clip in enumerate(clips):
clip_filename = (ready_files.get(i)
or _canonical_clip_file(output_dir, base_name, i))
clip_path = os.path.join(output_dir, clip_filename)
try:
present = os.path.getsize(clip_path) > 0
except OSError:
present = False
if not present:
print(f"⚠️ Clip {i + 1} of {job_id} never rendered "
f"({clip_filename}) — dropping it from the result.")
continue
clip['video_url'] = f"/videos/{job_id}/{clip_filename}"
kept.append(clip)
return kept, len(clips) - len(kept)
def _strip_burned_captions(output_dir, filename): def _strip_burned_captions(output_dir, filename):
"""Walk ``subtitled_<ts>_`` prefixes back to the file without burned captions. """Walk ``subtitled_<ts>_`` prefixes back to the file without burned captions.
@ -1898,11 +1942,19 @@ async def run_job(job_id, job_data):
clips = data.get('shorts', []) clips = data.get('shorts', [])
cost_analysis = data.get('cost_analysis') cost_analysis = data.get('cost_analysis')
for i, clip in enumerate(clips): rendered, missing = _clips_actually_rendered(
clip_filename = _canonical_clip_file(output_dir, base_name, i) job_id, output_dir, base_name, clips)
clip['video_url'] = f"/videos/{job_id}/{clip_filename}" if not rendered:
# Nothing to hand over: fail the job so _settle_reservation
jobs[job_id]['result'] = {'clips': clips, 'cost_analysis': cost_analysis} # releases the minutes instead of committing them.
jobs[job_id]['status'] = 'failed'
jobs[job_id]['logs'].append(
"No clips could be rendered from this video.")
else:
if missing:
jobs[job_id]['logs'].append(
f"⚠️ {missing} of {len(clips)} clips failed to render.")
jobs[job_id]['result'] = {'clips': rendered, 'cost_analysis': cost_analysis}
else: else:
jobs[job_id]['status'] = 'failed' jobs[job_id]['status'] = 'failed'
jobs[job_id]['logs'].append("No metadata file generated.") jobs[job_id]['logs'].append("No metadata file generated.")

123
tests/test_phantom_clips.py Normal file
View file

@ -0,0 +1,123 @@
"""A clip that never rendered must not be reported as delivered.
The metadata JSON is written BEFORE the clips render, and main.py's worker pool
swallows a per-clip exception (it only prints "❌ Clip N failed") and still
exits 0. app.py then rebuilt the job result from that metadata and named every
clip through _canonical_clip_file, which returns a name whether or not the file
exists. A job whose renders all failed was therefore reported as completed with
N clips: the minutes were committed, ClipsDelivered fired, archive_job skipped
every missing file and uploaded the metadata alone (returning before it writes
the Project row, so the job could not even be restored), and the dashboard
offered clips whose only existence was a title — "download all" then answered
404 "No clip files found for this job".
Reported as ticket #4711 (job 89d76bbc, 6-sep-2026): two titles, two viral
scores, blank players, and 404 on download. Measured over the R2 archive on
7-sep-2026: 195 of 1687 archived jobs held a metadata file and not one clip,
across 184 users.
"""
import os
import pytest
app = pytest.importorskip("app")
def _clip(title):
return {"video_title_for_youtube_short": title, "start": 0.0, "end": 20.0}
def _write(job_dir, name, size=1024):
path = os.path.join(job_dir, name)
with open(path, "wb") as f:
f.write(b"\0" * size)
return path
class TestPhantomClips:
"""_clips_actually_rendered is the gate between 'promised' and 'delivered'."""
def test_drops_clips_whose_file_was_never_written(self, tmp_path):
job_dir = str(tmp_path)
_write(job_dir, "MKG_clip_1.mp4") # only clip 1 rendered
kept, missing = app._clips_actually_rendered(
"job-1", job_dir, "MKG", [_clip("one"), _clip("two")])
assert [c["video_title_for_youtube_short"] for c in kept] == ["one"]
assert missing == 1
assert kept[0]["video_url"] == "/videos/job-1/MKG_clip_1.mp4"
def test_a_job_that_rendered_nothing_keeps_nothing(self, tmp_path):
"""The ticket #4711 shape: metadata on disk, not a single mp4."""
kept, missing = app._clips_actually_rendered(
"89d76bbc", str(tmp_path), "89d76bbc_MKG ep 3 draft 4_6",
[_clip("This Car Design Detail Is Perfection"),
_clip("Why This Car Is In A League Of Its Own")])
assert kept == []
assert missing == 2
def test_a_zero_byte_clip_is_not_a_clip(self, tmp_path):
"""ffmpeg can leave an empty file behind when it dies mid-write."""
_write(str(tmp_path), "MKG_clip_1.mp4", size=0)
kept, missing = app._clips_actually_rendered(
"job-2", str(tmp_path), "MKG", [_clip("one")])
assert kept == []
assert missing == 1
def test_a_fully_rendered_job_is_untouched(self, tmp_path):
job_dir = str(tmp_path)
_write(job_dir, "MKG_clip_1.mp4")
_write(job_dir, "MKG_clip_2.mp4")
kept, missing = app._clips_actually_rendered(
"job-3", job_dir, "MKG", [_clip("one"), _clip("two")])
assert len(kept) == 2
assert missing == 0
def test_the_derived_file_still_wins(self, tmp_path):
"""Captions/hooks are served from the derived file, as before the fix."""
job_dir = str(tmp_path)
_write(job_dir, "MKG_clip_1.mp4")
_write(job_dir, "subtitled_2_hooked_1_MKG_clip_1.mp4")
kept, _ = app._clips_actually_rendered(
"job-4", job_dir, "MKG", [_clip("one")])
assert kept[0]["video_url"] == (
"/videos/job-4/subtitled_2_hooked_1_MKG_clip_1.mp4")
def test_a_name_with_spaces_and_parens_resolves(self, tmp_path):
"""Uploads keep the user's own filename as the stem (app.py:2434)."""
stem = "89d76bbc_MK Garage Season 1 episode 1 (Pilot)_2"
_write(str(tmp_path), f"{stem}_clip_1.mp4")
kept, missing = app._clips_actually_rendered(
"89d76bbc", str(tmp_path), stem, [_clip("one")])
assert missing == 0
assert kept[0]["video_url"] == f"/videos/89d76bbc/{stem}_clip_1.mp4"
def test_the_clip_ready_marker_wins_over_the_guessed_name(self, tmp_path):
"""main.py names the finished file; the convention is only a fallback."""
job_dir = str(tmp_path)
_write(job_dir, "dubbed_9_MKG_clip_1.mp4") # a prefix no glob covers
app.jobs["job-5"] = {"ready_files": {0: "dubbed_9_MKG_clip_1.mp4"}}
try:
kept, missing = app._clips_actually_rendered(
"job-5", job_dir, "MKG", [_clip("one")])
finally:
app.jobs.pop("job-5", None)
assert missing == 0
assert kept[0]["video_url"] == "/videos/job-5/dubbed_9_MKG_clip_1.mp4"
def test_a_marker_for_a_file_that_vanished_is_still_dropped(self, tmp_path):
app.jobs["job-6"] = {"ready_files": {0: "gone_MKG_clip_1.mp4"}}
try:
kept, missing = app._clips_actually_rendered(
"job-6", str(tmp_path), "MKG", [_clip("one")])
finally:
app.jobs.pop("job-6", None)
assert kept == []
assert missing == 1