Files
jetson d3d58ffcde fix: harden the output lifecycle (range requests, temp files, job gate)
Review of the compression branch (ce93c68..d7c1415): one Important and the
cheap real Minors, each with a RED test first.

- app.py: drop the manual Content-Length override - it broke ranged
  requests (206 announcing the full length while sending a slice).
  send_file sets it and the 206/Content-Range itself.
- app.py: the download route serves video extensions only, never the temp
  of an encode in flight.
- src/compress.py: the encode temp is unique per attempt (mkstemp), is
  validated (playable video) and fsynced before it replaces the original;
  a failing os.replace keeps the original and cleans the temp up instead
  of raising into the route. The compressed video keeps the source mode.
- src/compress.py: a stale temp of a killed encode is swept after 2 h
  instead of the 5-day video expiry.
- src/job.py: cancelled and failed jobs are not re-encoded; the job shows
  "Compressing..." while the encode runs.
- ERD.md: the $OUTPUT_DIR/*_compressed.mp4 row is gone.

328 tests pass (was 319).
2026-10-28 15:47:28 +07:00

294 lines
10 KiB
Python

"""Tests for the annotated-output lifecycle: compress in place, expire.
A finished job must leave exactly ONE video behind: the compressed one,
under the original file name. The uncompressed source is gone.
"""
import os
import subprocess
import time
from unittest import mock
import src.compress as compress_module
from src.compress import compress_in_place, purge_expired_media
def _fake_run(payload=b"compressed"):
def run(cmd, **kwargs):
with open(cmd[-1], "wb") as fh:
fh.write(payload)
return subprocess.CompletedProcess(cmd, 0)
return run
# ── compress_in_place ─────────────────────────────────────────────────────
def test_small_file_is_left_alone(tmp_path):
"""A file within the cap is not touched."""
f = tmp_path / "small.mp4"
f.write_bytes(b"tiny")
assert compress_in_place(str(f)) is None
assert f.read_bytes() == b"tiny"
def test_missing_file_returns_none(tmp_path):
assert compress_in_place(str(tmp_path / "nope.mp4")) is None
def test_oversized_file_is_replaced_in_place(tmp_path):
"""The compressed video replaces the original under the SAME name."""
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \
mock.patch.object(compress_module.subprocess, "run", side_effect=_fake_run(b"c")):
out = compress_in_place(str(f), max_bytes=1024)
assert out == str(f)
assert f.read_bytes() == b"c"
# exactly one file in the directory - no _compressed sibling
assert [p.name for p in tmp_path.iterdir()] == ["big.mp4"]
def test_encode_targets_a_temp_file_and_leaves_the_original_intact(tmp_path):
"""The original must survive the whole encode until the atomic replace."""
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
seen = {}
def fake_run(cmd, **kwargs):
seen["target"] = cmd[-1]
seen["original_during_encode"] = f.read_bytes()
with open(cmd[-1], "wb") as fh:
fh.write(b"c")
return subprocess.CompletedProcess(cmd, 0)
with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \
mock.patch.object(compress_module.subprocess, "run", side_effect=fake_run):
compress_in_place(str(f), max_bytes=1024)
assert seen["target"] != str(f)
assert seen["original_during_encode"] == b"x" * 300_000
def test_failed_encode_keeps_the_original(tmp_path):
"""ffmpeg missing or failing must not lose the video."""
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \
mock.patch.object(compress_module.subprocess, "run", side_effect=OSError("no ffmpeg")):
assert compress_in_place(str(f), max_bytes=1024) is None
assert f.read_bytes() == b"x" * 300_000
assert list(tmp_path.glob("*.tmp")) == []
def test_oversized_result_is_discarded(tmp_path):
"""An encode that still overshoots the cap is thrown away."""
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \
mock.patch.object(compress_module.subprocess, "run", side_effect=_fake_run(b"y" * 5000)):
assert compress_in_place(str(f), max_bytes=1024) is None
assert f.read_bytes() == b"x" * 300_000
assert list(tmp_path.glob("*.tmp")) == []
def test_probe_failure_keeps_the_original(tmp_path):
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
with mock.patch.object(compress_module, "probe_video", side_effect=FileNotFoundError):
assert compress_in_place(str(f), max_bytes=1024) is None
assert f.exists()
def test_replace_failure_keeps_the_original_and_leaves_no_temp(tmp_path):
"""A filesystem error on the replace must not 500 the download route."""
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \
mock.patch.object(compress_module.subprocess, "run", side_effect=_fake_run(b"c")), \
mock.patch.object(compress_module.os, "replace", side_effect=OSError("EIO")):
assert compress_in_place(str(f), max_bytes=1024) is None
assert f.read_bytes() == b"x" * 300_000
assert list(tmp_path.glob("*.compress.tmp")) == []
def test_temp_name_is_unique_per_attempt(tmp_path):
"""Two encodes must never share a temp path (a second process could)."""
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
targets = []
def fake_run(cmd, **kwargs):
targets.append(cmd[-1])
with open(cmd[-1], "wb") as fh:
fh.write(b"c")
return subprocess.CompletedProcess(cmd, 0)
with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \
mock.patch.object(compress_module.subprocess, "run", side_effect=fake_run):
compress_in_place(str(f), max_bytes=1024)
f.write_bytes(b"x" * 300_000)
compress_in_place(str(f), max_bytes=1024)
assert len(targets) == 2
assert targets[0] != targets[1]
# not a fixed, predictable name next to the source
assert targets[0] != str(f) + ".compress.tmp"
def test_unplayable_encode_is_discarded(tmp_path):
"""The temp must be a playable video, not just a small file."""
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
def probe(path):
if path == str(f):
return {"duration": 100.0}
return {"duration": 0.0}
with mock.patch.object(compress_module, "probe_video", side_effect=probe), \
mock.patch.object(compress_module.subprocess, "run", side_effect=_fake_run(b"c")):
assert compress_in_place(str(f), max_bytes=1024) is None
assert f.read_bytes() == b"x" * 300_000
assert list(tmp_path.glob("*.compress.tmp")) == []
def test_compressed_video_keeps_the_mode_of_the_source(tmp_path):
"""The temp is created private - the delivered video must not be."""
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
os.chmod(f, 0o644)
with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \
mock.patch.object(compress_module.subprocess, "run", side_effect=_fake_run(b"c")):
compress_in_place(str(f), max_bytes=1024)
assert oct(os.stat(f).st_mode & 0o777) == oct(0o644)
def test_video_bitrate_leaves_room_for_the_audio_track(tmp_path):
"""The audio budget is subtracted from the video bitrate."""
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \
mock.patch.object(compress_module.subprocess, "run", side_effect=_fake_run(b"c")) as run:
compress_in_place(str(f), max_bytes=1024)
cmd = run.call_args[0][0]
assert int(cmd[cmd.index("-b:v") + 1]) == 100_000
# ── purge_expired_media ──────────────────────────────────────────────────
def test_purge_deletes_videos_older_than_the_retention(tmp_path):
"""Videos older than the retention are removed; everything else stays."""
job_dir = tmp_path / "job-1"
job_dir.mkdir()
old = job_dir / "annotated.mp4"
old.write_bytes(b"old")
os.utime(old, (1000, 1000))
fresh = job_dir / "fresh.mp4"
fresh.write_bytes(b"new")
thumb = job_dir / "thumbnail.jpg"
thumb.write_bytes(b"jpg")
samples = job_dir / "samples"
samples.mkdir()
(samples / "f1.jpg").write_bytes(b"j")
stale_tmp = job_dir / "annotated.mp4.compress.tmp"
stale_tmp.write_bytes(b"t")
os.utime(stale_tmp, (1000, 1000))
deleted = purge_expired_media(str(tmp_path), max_age_days=5)
assert not old.exists()
assert fresh.exists()
assert thumb.exists()
assert (samples / "f1.jpg").exists()
assert not stale_tmp.exists()
assert str(old) in deleted
def test_purge_keeps_a_recent_temp_file(tmp_path):
"""An encode in flight must not be swept away."""
job_dir = tmp_path / "job-2"
job_dir.mkdir()
tmp_file = job_dir / "annotated.mp4.compress.tmp"
tmp_file.write_bytes(b"t")
purge_expired_media(str(tmp_path), max_age_days=5)
assert tmp_file.exists()
def test_purge_sweeps_a_stale_temp_long_before_the_retention(tmp_path):
"""A temp of a killed encode is dead weight long before the 5-day sweep."""
job_dir = tmp_path / "job-3"
job_dir.mkdir()
stale = job_dir / "annotated.mp4.123.compress.tmp"
stale.write_bytes(b"t")
now = time.time()
os.utime(stale, (now - 3 * 3600, now - 3 * 3600))
in_flight = job_dir / "annotated.mp4.456.compress.tmp"
in_flight.write_bytes(b"t")
purge_expired_media(str(tmp_path), max_age_days=5)
assert not stale.exists()
assert in_flight.exists()
def test_purge_ignores_files_outside_job_dirs(tmp_path):
"""Only job output dirs are swept."""
stray = tmp_path / "stray.mp4"
stray.write_bytes(b"s")
os.utime(stray, (1000, 1000))
purge_expired_media(str(tmp_path), max_age_days=5)
assert stray.exists()
def test_purge_on_a_missing_output_dir_is_harmless(tmp_path):
assert purge_expired_media(str(tmp_path / "nope"), max_age_days=5) == []
# ── the purge CLI ────────────────────────────────────────────────────────
def test_purge_script_deletes_expired_videos(tmp_path):
"""The CLI does the same as the function."""
import subprocess as sp
import sys
job_dir = tmp_path / "job-cli"
job_dir.mkdir()
old = job_dir / "annotated.mp4"
old.write_bytes(b"old")
os.utime(old, (1000, 1000))
fresh = job_dir / "fresh.mp4"
fresh.write_bytes(b"new")
res = sp.run(
[sys.executable, "scripts/purge_expired_outputs.py",
"--output-dir", str(tmp_path), "--max-age-days", "5"],
capture_output=True, text=True, timeout=120,
)
assert res.returncode == 0, res.stderr
assert not old.exists()
assert fresh.exists()