From d3d58ffcde0d814307775163df1521844ad7f89c Mon Sep 17 00:00:00 2001 From: jetson Date: Wed, 28 Oct 2026 15:47:28 +0700 Subject: [PATCH] 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). --- CHANGELOG.md | 9 ++ ERD.md | 3 +- README.md | 3 +- app.py | 16 ++- .../plans/2026-10-28-post-job-compression.md | 18 ++++ src/compress.py | 74 ++++++++++++-- src/job.py | 5 + tests/test_compress.py | 87 +++++++++++++++++ tests/test_download_compress.py | 32 +++++- tests/test_job.py | 97 +++++++++++++++++++ 10 files changed, 325 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d6ba54..d7146f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,6 +62,15 @@ version tags are cut in this repo — `main` is the release line). after the job (`scripts/purge_expired_outputs.py`, cron daily 03:17); the job directory, the thumbnail and the sample frames stay, so the jobs list still renders. +- **Output lifecycle hardening** (review of `5e2a317`): the download route no + longer overrides `Content-Length` (it broke ranged requests — a 206 with a + full-length body length), so `Range` downloads work again; the encode temp + is now unique per attempt and is validated (playable video, fsynced) before + it replaces the original, and a failing `os.replace` keeps the original and + cleans up instead of 500-ing the download; the route serves video + extensions only (never the temp of an encode in flight); a stale temp of a + killed encode is swept after 2 h instead of 5 days; cancelled and failed + jobs are not re-encoded; the job shows "Compressing…" while it runs. - **Batch lifecycle now matches FCP's** (`1c313d9`, `59d8c55`): the line counter is fed on **every** frame (FCP `predict.py:1066-1067` — it used to run only while a batch was open, so crossings before the batch opened were diff --git a/ERD.md b/ERD.md index 2a98ed7..18292e7 100644 --- a/ERD.md +++ b/ERD.md @@ -132,8 +132,9 @@ PENDING ──▶ RUNNING ──▶ COMPLETED | `$UPLOAD_DIR/[_N].` | source videos; `secure_filename` + extension whitelist | | `$OUTPUT_DIR/job-/` | per-job output: annotated mp4, `thumbnail.jpg`, `samples/`, `predictions.csv` | | `$OUTPUT_DIR/job-/samples/.cached` | newline list of extracted sample frame paths | +| `$OUTPUT_DIR/job-/.mp4` | the annotated video: compressed **in place** when the job finishes (same name, `os.replace`); swept 5 days after the job | +| `$OUTPUT_DIR/job-/.*.compress.tmp` | temp of an encode in flight; a stale one (killed encode) is swept after 2 h | | `/tmp/feedmill_preview_.jpg` | live MJPEG frame, deleted in worker `finally` | -| `$OUTPUT_DIR/*_compressed.mp4` | ffmpeg download cache, invalidated by mtime vs source | | `zones.json` | `presets[]` + `active_preset`, geometry only | | `models/.{engine,pt,onnx}` | weight files grouped by stem | | `config.yaml` | single source of truth for tunables (detection, roi, stabilizer, pipeline) | diff --git a/README.md b/README.md index 71c099a..b3db93d 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,8 @@ recounter --video PATH Input video file download name is the plain one — there is no `_compressed` file. - Job videos are **deleted 5 days** after the job (`scripts/purge_expired_outputs.py`, run daily by cron). The job - directory, the thumbnail and the sample frames stay. + directory, the thumbnail and the sample frames stay. A temp file of an + encode in flight is swept after 2 h. ## API Endpoints diff --git a/app.py b/app.py index b05fdd8..9588727 100644 --- a/app.py +++ b/app.py @@ -402,13 +402,6 @@ def jobs_list(): return render_template("jobs.html", jobs=jobs) -def _remove_quiet(path: str) -> None: - try: - os.remove(path) - except OSError: - pass - - @app.route("/download//") def download(job_id, filename): job = job_queue.get_job(job_id) @@ -421,12 +414,15 @@ def download(job_id, filename): file_path = os.path.abspath(os.path.join(job.output_dir, safe_filename)) if os.path.commonpath([output_dir_abs, file_path]) != output_dir_abs: return "File not found", 404 + # Videos only: never a temp file of an encode in flight, never a stray file. + if not safe_filename.lower().endswith(VIDEO_EXTENSIONS): + return "File not found", 404 if not os.path.isfile(file_path): return "File not found", 404 send_path = compress_in_place(file_path) or file_path - resp = send_file(send_path, as_attachment=True, download_name=os.path.basename(send_path)) - resp.headers["Content-Length"] = str(os.path.getsize(send_path)) - return resp + # send_file sets Content-Length (and the 206/Content-Range of a ranged + # request) itself - overriding it here would describe a body we do not send. + return send_file(send_path, as_attachment=True, download_name=os.path.basename(send_path)) @app.route("/api/videos") diff --git a/docs/superpowers/plans/2026-10-28-post-job-compression.md b/docs/superpowers/plans/2026-10-28-post-job-compression.md index ced2353..6c30887 100644 --- a/docs/superpowers/plans/2026-10-28-post-job-compression.md +++ b/docs/superpowers/plans/2026-10-28-post-job-compression.md @@ -191,3 +191,21 @@ Cron (new line, daily, off the minute): - Compressing the uploaded source in `uploads/` (kept for re-processing). - A UI indicator for "compressing" beyond `job.current_model`. - Per-job retention settings (fixed 5 days for all jobs). + +## Review fix pass (after `d7c1415`) + +A review of `ce93c68..d7c1415` found one Important and a few real Minors; all fixed here: + +- The download route no longer sets `Content-Length` itself — `send_file` does that, and the + manual override broke ranged requests (a 206 that announced the full length while sending + a slice). +- The encode temp is unique per attempt (`tempfile.mkstemp`), validated (a playable video, + fsynced) before it replaces the original, and a failing `os.replace` keeps the original + and cleans the temp up instead of raising into the route. +- The route serves video extensions only — never the temp of an encode in flight. +- A stale temp of a killed encode is swept after 2 h, not after the 5-day video expiry. +- Cancelled and failed jobs are not re-encoded. +- `job.current_model` shows "Compressing…" while the encode runs. + +Deferred: the status page still renders a Download button for a job whose video the 5-day +sweep already deleted (the route answers 404) — the page should say "expired". diff --git a/src/compress.py b/src/compress.py index 2bc3bd6..1e87855 100644 --- a/src/compress.py +++ b/src/compress.py @@ -10,6 +10,7 @@ from __future__ import annotations import os import subprocess +import tempfile import threading import time @@ -34,6 +35,11 @@ _COMPRESS_LOCK = threading.Lock() # the sample frames stay (small - the jobs list still renders). RETENTION_DAYS = 5.0 +# A temp file of a killed encode is dead weight (up to the size of the +# source) and must go long before the video itself expires. The margin over +# the 1 h encode timeout keeps an encode in flight alive. +_TMP_MAX_AGE_SECONDS = 2 * 3600 + def _remove_quiet(path: str) -> None: try: @@ -42,6 +48,35 @@ def _remove_quiet(path: str) -> None: pass +def _fsync(path: str) -> None: + """Flush the file (or the directory entry) to disk, best effort.""" + try: + fd = os.open(path, os.O_RDONLY) + except OSError: + return + try: + os.fsync(fd) + except OSError: + pass + finally: + os.close(fd) + + +def _tmp_path(file_path: str) -> str: + """A unique encode target next to the source. + + Unique per attempt, so two processes on the same output dir never write + to the same path. + """ + fd, tmp_path = tempfile.mkstemp( + dir=os.path.dirname(file_path) or ".", + prefix=os.path.basename(file_path) + ".", + suffix=_TMP_SUFFIX, + ) + os.close(fd) + return tmp_path + + def compress_in_place(file_path: str, max_bytes: int = MAX_BYTES) -> str | None: """Shrink file_path to max_bytes, replacing it under the same name. @@ -66,7 +101,11 @@ def compress_in_place(file_path: str, max_bytes: int = MAX_BYTES) -> str | None: int((max_bytes * 8 * 0.92) / duration) - _AUDIO_BITRATE, _MIN_VIDEO_BITRATE, ) - tmp_path = file_path + _TMP_SUFFIX + try: + mode = os.stat(file_path).st_mode & 0o777 + except OSError: + mode = 0o644 + tmp_path = _tmp_path(file_path) try: subprocess.run( ["ffmpeg", "-y", "-i", file_path, "-c:v", "libx264", @@ -82,9 +121,30 @@ def compress_in_place(file_path: str, max_bytes: int = MAX_BYTES) -> str | None: if not os.path.isfile(tmp_path) or os.path.getsize(tmp_path) > max_bytes: _remove_quiet(tmp_path) return None + # The temp must be a playable video, not just a file that fits. + try: + tmp_duration = float(probe_video(tmp_path).get("duration") or 0) + except Exception: + tmp_duration = 0.0 + if tmp_duration <= 0: + _remove_quiet(tmp_path) + return None + _fsync(tmp_path) + # The temp is created private (0600); the video keeps the mode of the + # file it replaces. + try: + os.chmod(tmp_path, mode) + except OSError: + pass # Atomic: the compressed video takes the original's name, the source # is gone, and there is never a moment without a file. - os.replace(tmp_path, file_path) + try: + os.replace(tmp_path, file_path) + except OSError: + # The original is still there; drop the temp and carry on. + _remove_quiet(tmp_path) + return None + _fsync(os.path.dirname(file_path) or ".") return file_path @@ -97,11 +157,12 @@ def purge_expired_media( Age comes from the file mtime - jobs live in memory only, so the file timestamp is the only restart-proof clock. Stale '*.compress.tmp' - leftovers of a killed encode go too; a fresh one (an encode in flight) - stays. + leftovers of a killed encode go much earlier (they are dead weight); + a fresh one (an encode in flight) stays. """ now = time.time() if now is None else now cutoff = now - max_age_days * 86400 + tmp_cutoff = now - _TMP_MAX_AGE_SECONDS deleted: list[str] = [] root = os.path.abspath(output_dir) if not os.path.isdir(root): @@ -113,11 +174,12 @@ def purge_expired_media( if not os.path.isdir(d): continue for name in sorted(os.listdir(d)): - if not (name.endswith(".mp4") or name.endswith(_TMP_SUFFIX)): + is_tmp = name.endswith(_TMP_SUFFIX) + if not (is_tmp or name.endswith(".mp4")): continue p = os.path.join(d, name) try: - if os.path.getmtime(p) >= cutoff: + if os.path.getmtime(p) >= (tmp_cutoff if is_tmp else cutoff): continue os.remove(p) except OSError: diff --git a/src/job.py b/src/job.py index 4bb306e..0776ea4 100644 --- a/src/job.py +++ b/src/job.py @@ -226,6 +226,9 @@ class JobQueue: replaces the uncompressed source (atomically). A file that cannot be compressed is left as it is - the job still succeeded. """ + if job.status in (JobStatus.CANCELLED, JobStatus.FAILED): + # A partial video is not worth minutes of re-encoding. + return for r in job.results: path = r.output_path if not path: @@ -378,6 +381,8 @@ class JobQueue: # The job is done: shrink the annotated video in place. One video # per job, under its original name - the uncompressed source is # replaced by the compressed copy. + with self._lock: + job.current_model = "Compressing..." self._compress_outputs(job) with self._lock: diff --git a/tests/test_compress.py b/tests/test_compress.py index 0e7e1e8..bd6432f 100644 --- a/tests/test_compress.py +++ b/tests/test_compress.py @@ -6,6 +6,7 @@ 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 @@ -108,6 +109,75 @@ def test_probe_failure_keeps_the_original(tmp_path): 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" @@ -164,6 +234,23 @@ def test_purge_keeps_a_recent_temp_file(tmp_path): 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" diff --git a/tests/test_download_compress.py b/tests/test_download_compress.py index 6e28736..f092142 100644 --- a/tests/test_download_compress.py +++ b/tests/test_download_compress.py @@ -109,6 +109,36 @@ def test_download_route_404_when_the_file_is_gone(client): assert resp.status_code == 404 +def test_download_route_rejects_a_non_video_filename(client): + """The route serves videos only - never a temp file or a stray file.""" + job, _path = _completed_job_with_file() + # a temp of an encode in flight, and a stray file, both in the job dir + tmp = os.path.join(job.output_dir, "out.mp4.compress.tmp") + with open(tmp, "wb") as fh: + fh.write(b"partial") + stray = os.path.join(job.output_dir, "notes.txt") + with open(stray, "wb") as fh: + fh.write(b"text") + + for name in ("out.mp4.compress.tmp", "notes.txt"): + resp = client.get(f"/download/{job.job_id}/{name}") + assert resp.status_code == 404, name + + +def test_range_request_gets_the_right_content_length(client): + """A ranged request must announce the length of the body it sends.""" + job, _path = _completed_job_with_file(content=b"x" * 10_000) + + resp = client.get( + f"/download/{job.job_id}/out.mp4", + headers={"Range": "bytes=0-999"}, + ) + + assert resp.status_code == 206 + assert resp.headers["Content-Length"] == "1000" + assert len(resp.data) == 1000 + + # ── one encode for concurrent downloads ────────────────────────────────── @@ -166,5 +196,5 @@ def test_real_ffmpeg_smoke(tmp_path): assert out == str(src) assert os.path.getsize(out) <= max_bytes - assert not os.path.exists(out + ".compress.tmp") + assert list(tmp_path.glob("*.compress.tmp")) == [] assert [p.name for p in tmp_path.iterdir()] == ["tiny.mp4"] diff --git a/tests/test_job.py b/tests/test_job.py index cc37012..7123abc 100644 --- a/tests/test_job.py +++ b/tests/test_job.py @@ -619,3 +619,100 @@ def test_run_job_compresses_the_output_when_the_job_finishes(tmp_path, monkeypat # the compressed video replaced the source, under the same name assert out_path.read_bytes() == b"compressed" assert [p.name for p in out_dir.iterdir()] == ["a_annotated_clip.mp4"] + + +def test_cancelled_job_is_not_compressed(tmp_path, monkeypatch): + """A cancelled job's partial video is not worth minutes of re-encoding.""" + import src.job as job_mod + from src.job import Job, JobQueue, JobStatus + from src.model_registry import ModelConfig + + out_dir = tmp_path / "job-cancel" + out_dir.mkdir() + out_path = out_dir / "a_annotated_clip.mp4" + out_path.write_bytes(b"x" * 300_000) + + compressed = [] + + def fake_compress(path, **kwargs): + compressed.append(path) + return path + + monkeypatch.setattr(job_mod, "compress_in_place", fake_compress, raising=False) + + q = JobQueue(output_dir=str(tmp_path)) + job = Job( + job_id="job-cancel", + video_path="/tmp/test.mp4", + model_configs=[ + ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a", + known_classes=["sack", "box", "truck"]) + ], + output_dir=str(out_dir), + ) + q._jobs[job.job_id] = job + + def run_pipeline(**kwargs): + # the user cancels while the pipeline is running + job.status = JobStatus.CANCELLED + return _fake_result(out_path) + + monkeypatch.setattr(job_mod, "run_pipeline", run_pipeline) + q._run_job(job.job_id) + + assert job.status == JobStatus.CANCELLED + assert compressed == [] + assert out_path.read_bytes() == b"x" * 300_000 + + +def test_failed_job_is_not_compressed(tmp_path, monkeypatch): + """A failed job keeps its partial output as it is.""" + import src.job as job_mod + from src.job import Job, JobQueue, JobStatus + from src.model_registry import ModelConfig + + out_dir = tmp_path / "job-fail" + out_dir.mkdir() + out_path = out_dir / "a_annotated_clip.mp4" + out_path.write_bytes(b"x" * 300_000) + + def boom(**kwargs): + raise RuntimeError("pipeline died") + + compressed = [] + monkeypatch.setattr(job_mod, "run_pipeline", boom) + monkeypatch.setattr( + job_mod, "compress_in_place", + lambda path, **kwargs: compressed.append(path), raising=False, + ) + + q = JobQueue(output_dir=str(tmp_path)) + job = Job( + job_id="job-fail", + video_path="/tmp/test.mp4", + model_configs=[ + ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a", + known_classes=["sack", "box", "truck"]) + ], + output_dir=str(out_dir), + ) + q._jobs[job.job_id] = job + q._run_job(job.job_id) + + assert job.status == JobStatus.FAILED + assert compressed == [] + + +def _fake_result(out_path): + from src.pipeline import PipelineResult + return PipelineResult( + output_path=str(out_path), + frame_count=10, + loading_count=5, + unloading_count=2, + batch_count=1, + duration_seconds=1.0, + model_name="a.pt", + class_filter=None, + ) +