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

719 lines
23 KiB
Python

# tests/test_job.py
"""Tests for job queue (src/job.py)."""
import pytest
from src.job import JobQueue, Job, JobStatus
def test_job_initial_status():
"""New job starts in PENDING status."""
job = Job(
job_id="test-1",
video_path="/tmp/test.mp4",
model_configs=[],
output_dir="/tmp/output",
)
assert job.status == JobStatus.PENDING
def test_job_has_latest_frame():
"""Job dataclass has latest_frame field defaulting to None."""
job = Job(
job_id="test-1",
video_path="/tmp/test.mp4",
model_configs=[],
output_dir="/tmp/output",
)
assert job.latest_frame is None
def test_job_latest_frame_settable():
"""Job.latest_frame can be set to bytes."""
job = Job(
job_id="test-1",
video_path="/tmp/test.mp4",
model_configs=[],
output_dir="/tmp/output",
)
job.latest_frame = b"\xff\xd8\xff\xe0"
assert job.latest_frame == b"\xff\xd8\xff\xe0"
def test_queue_add_job():
"""Adding a job returns the job with PENDING status."""
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[])
assert job.job_id.startswith("job-")
assert job.status in (JobStatus.PENDING, JobStatus.RUNNING, JobStatus.COMPLETED)
def test_add_job_downgrades_fixed_mode_without_a_zone():
""""fixed" without a calibrated ROI would be a lie — the job counts dynamically."""
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[], zone_mode="fixed")
assert job.zone_mode == "dynamic"
assert job.fixed_zone is None
def test_add_job_keeps_fixed_mode_with_a_zone():
"""A calibrated ROI keeps the "fixed" label."""
from src.truck_roi import TruckROI
roi = TruckROI(x1=400, y1=228, x2=936, y2=718, line_y=220,
confidence=1.0, fixed=True)
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[],
zone_mode="fixed", fixed_zone=roi)
assert job.zone_mode == "fixed"
assert job.fixed_zone is roi
def test_queue_get_job():
"""get_job returns the job by ID."""
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[])
fetched = q.get_job(job.job_id)
assert fetched is not None
assert fetched.job_id == job.job_id
def test_queue_get_nonexistent():
"""get_job returns None for unknown ID."""
q = JobQueue(output_dir="/tmp/output")
assert q.get_job("nope") is None
def test_queue_list_jobs():
"""list_jobs returns all jobs."""
q = JobQueue(output_dir="/tmp/output")
q.add_job(video_path="/tmp/a.mp4", model_configs=[])
q.add_job(video_path="/tmp/b.mp4", model_configs=[])
jobs = q.list_jobs()
assert len(jobs) >= 2
def test_queue_cancel_pending():
"""Canceling a pending job sets status to CANCELLED."""
q = JobQueue(output_dir="/tmp/output")
# Add job without starting (simulate by adding then immediately canceling)
# Since add_job starts a thread, we test cancel on a job we control
job = q.add_job(video_path="/nonexistent.mp4", model_configs=[])
# Wait briefly for thread to start
import time
time.sleep(0.1)
assert q.cancel_job(job.job_id) in (True, False) # may have already started
def test_job_empty_config_completes():
"""add_job with [] model_configs completes with COMPLETED + empty results."""
import time
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[])
deadline = time.time() + 5.0
while time.time() < deadline:
fetched = q.get_job(job.job_id)
if fetched is not None and fetched.status == JobStatus.COMPLETED:
break
time.sleep(0.05)
fetched = q.get_job(job.job_id)
assert fetched is not None
assert fetched.status == JobStatus.COMPLETED
assert fetched.results == []
def test_queue_status_counts():
"""status_counts returns correct tally."""
q = JobQueue(output_dir="/tmp/output")
j1 = q.add_job(video_path="/nonexistent1.mp4", model_configs=[])
j2 = q.add_job(video_path="/nonexistent2.mp4", model_configs=[])
import time
time.sleep(0.5) # let them fail quickly
counts = q.status_counts()
assert isinstance(counts, dict)
# At least some count should be populated
assert sum(counts.values()) >= 2
# ── Box count propagation to JobResult (Task 2) ─────────────────────────
def test_job_result_box_fields_default_zero():
"""JobResult has box fields defaulting to 0."""
from src.job import JobResult
r = JobResult(
model_name="a.pt",
output_path="/tmp/out.mp4",
loading_count=5,
unloading_count=2,
net_count=3,
batch_count=1,
frame_count=10,
duration_seconds=1.0,
)
assert (r.box_loading_count, r.box_unloading_count, r.box_net_count) == (0, 0, 0)
def test_job_result_box_fields_accept_values():
from src.job import JobResult
r = JobResult(
model_name="a.pt",
output_path="/tmp/out.mp4",
loading_count=5,
unloading_count=2,
net_count=3,
batch_count=1,
frame_count=10,
duration_seconds=1.0,
box_loading_count=4,
box_unloading_count=1,
box_net_count=3,
)
assert (r.box_loading_count, r.box_unloading_count, r.box_net_count) == (4, 1, 3)
def test_run_job_single_model_propagates_box_counts(tmp_path, monkeypatch):
"""_run_job single-model branch copies box counts from PipelineResult."""
import src.job as job_mod
from src.job import Job, JobQueue, JobStatus
from src.model_registry import ModelConfig
from src.pipeline import PipelineResult
fake = PipelineResult(
output_path=str(tmp_path / "out.mp4"),
frame_count=10,
loading_count=5,
unloading_count=2,
batch_count=1,
duration_seconds=1.0,
model_name="a.pt",
class_filter=None,
box_loading_count=4,
box_unloading_count=1,
)
monkeypatch.setattr(job_mod, "run_pipeline", lambda **kwargs: fake)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-t2-single",
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(tmp_path / "job-t2-single"),
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert job.status == JobStatus.COMPLETED
r = job.results[0]
assert r.loading_count == 5
assert r.box_loading_count == 4
assert r.box_unloading_count == 1
assert r.box_net_count == 3
def test_run_job_merged_propagates_box_counts(tmp_path, monkeypatch):
"""_run_job merged branch copies box counts from MergedPipelineResult."""
import src.job as job_mod
from src.job import Job, JobQueue, JobStatus
from src.model_registry import ModelConfig
from src.pipeline import MergedPipelineResult
fake = MergedPipelineResult(
output_path=str(tmp_path / "merged.mp4"),
frame_count=10,
loading_count=9,
unloading_count=4,
batch_count=2,
duration_seconds=2.0,
model_names=["a.pt", "b.pt"],
class_filter=None,
box_loading_count=6,
box_unloading_count=2,
)
monkeypatch.setattr(job_mod, "run_merged_pipeline", lambda **kwargs: fake)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-t2-merged",
video_path="/tmp/test.mp4",
model_configs=[
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack", "box", "truck"]),
ModelConfig(filename="b.pt", path=str(tmp_path / "b.pt"), stem="b",
known_classes=["sack", "box"]),
],
output_dir=str(tmp_path / "job-t2-merged"),
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert job.status == JobStatus.COMPLETED
r = job.results[0]
assert r.box_loading_count == 6
assert r.box_unloading_count == 2
assert r.box_net_count == 4
# ── output_max_height plumbing ──────────────────────────────────────────
def test_job_output_max_height_default_none():
"""Job.output_max_height defaults to None."""
job = Job(
job_id="test-oh",
video_path="/tmp/test.mp4",
model_configs=[],
output_dir="/tmp/output",
)
assert job.output_max_height is None
def test_queue_add_job_output_max_height():
"""add_job passes output_max_height through to the Job."""
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[],
output_max_height=720)
assert job.output_max_height == 720
def test_queue_add_job_output_max_height_default():
"""add_job without output_max_height keeps None."""
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[])
assert job.output_max_height is None
def _fake_single_job(tmp_path, output_max_height, monkeypatch):
import src.job as job_mod
from src.model_registry import ModelConfig
from src.pipeline import PipelineResult
seen = {}
def fake_run_pipeline(**kwargs):
seen.update(kwargs)
return PipelineResult(
output_path=str(tmp_path / "out.mp4"),
frame_count=10,
loading_count=1,
unloading_count=0,
batch_count=1,
duration_seconds=1.0,
model_name="a.pt",
class_filter=None,
)
monkeypatch.setattr(job_mod, "run_pipeline", fake_run_pipeline)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-oh-single",
video_path="/tmp/test.mp4",
model_configs=[
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack", "truck"])
],
output_dir=str(tmp_path / "job-oh-single"),
output_max_height=output_max_height,
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
return job, seen
def test_run_job_single_passes_output_max_height(tmp_path, monkeypatch):
"""_run_job single branch forwards output_max_height=720 to run_pipeline."""
job, seen = _fake_single_job(tmp_path, 720, monkeypatch)
assert job.status == JobStatus.COMPLETED
assert seen.get("output_max_height") == 720
def test_run_job_single_output_max_height_none(tmp_path, monkeypatch):
"""_run_job single branch forwards output_max_height=None."""
job, seen = _fake_single_job(tmp_path, None, monkeypatch)
assert job.status == JobStatus.COMPLETED
assert seen.get("output_max_height") is None
def test_run_job_merged_passes_output_max_height(tmp_path, monkeypatch):
"""_run_job merged branch forwards output_max_height to run_merged_pipeline."""
import src.job as job_mod
from src.job import Job, JobQueue, JobStatus
from src.model_registry import ModelConfig
from src.pipeline import MergedPipelineResult
seen = {}
def fake_run_merged(**kwargs):
seen.update(kwargs)
return MergedPipelineResult(
output_path=str(tmp_path / "merged.mp4"),
frame_count=10,
loading_count=3,
unloading_count=1,
batch_count=1,
duration_seconds=1.0,
model_names=["a.pt", "b.pt"],
class_filter=None,
)
monkeypatch.setattr(job_mod, "run_merged_pipeline", fake_run_merged)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-oh-merged",
video_path="/tmp/test.mp4",
model_configs=[
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack", "truck"]),
ModelConfig(filename="b.pt", path=str(tmp_path / "b.pt"), stem="b",
known_classes=["sack"]),
],
output_dir=str(tmp_path / "job-oh-merged"),
output_max_height=720,
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert job.status == JobStatus.COMPLETED
assert seen.get("output_max_height") == 720
# ── Orphan registration (jobs lost across restart) ────────────────────
def test_orphan_output_dirs_registered_on_init(tmp_path):
"""Stale output/job-* dirs re-attach as COMPLETED jobs so UI can delete them."""
import os
import time as _time
stale = tmp_path / "job-abcd1234"
stale.mkdir()
(stale / "merged_annotated.mp4").write_bytes(b"video")
old = _time.time() - 3600
os.utime(stale, (old, old))
q = JobQueue(output_dir=str(tmp_path))
job = q.get_job("job-abcd1234")
assert job is not None
assert job.status == JobStatus.COMPLETED
assert job.output_dir == str(stale)
# And the normal delete flow frees the storage
assert q.delete_job("job-abcd1234") is True
assert not stale.exists()
def test_fresh_output_dir_skipped(tmp_path):
"""Dirs younger than the grace window may belong to a live job — not registered."""
fresh = tmp_path / "job-99999999"
fresh.mkdir() # mtime = now
q = JobQueue(output_dir=str(tmp_path))
assert q.get_job("job-99999999") is None
assert fresh.exists()
def test_orphan_registration_off(tmp_path):
"""register_orphans=False leaves disk state alone (used by tests/tools)."""
import os
import time as _time
stale = tmp_path / "job-abcd1234"
stale.mkdir()
old = _time.time() - 3600
os.utime(stale, (old, old))
q = JobQueue(output_dir=str(tmp_path), register_orphans=False)
assert q.get_job("job-abcd1234") is None
# ── Output naming (source clip name appended) ─────────────────────────
def test_single_model_output_name_uses_source_stem(tmp_path, monkeypatch):
"""Annotated file name carries the source clip name."""
import os
import src.job as job_mod
from src.job import Job, JobQueue
from src.model_registry import ModelConfig
from src.pipeline import PipelineResult
seen = {}
def fake(**kwargs):
seen.update(kwargs)
return PipelineResult(
output_path=kwargs["output_path"], frame_count=10, loading_count=0,
unloading_count=0, batch_count=0, duration_seconds=1.0,
model_name="a.pt", class_filter=None,
)
monkeypatch.setattr(job_mod, "run_pipeline", fake)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-nm-single",
video_path="/tmp/clip_1.mp4",
model_configs=[ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"),
stem="a", known_classes=["sack"])],
output_dir=str(tmp_path / "job-nm-single"),
source_stem="clip",
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert os.path.basename(seen["output_path"]) == "a_annotated_clip.mp4"
def test_merged_output_name_falls_back_to_stored_file_name(tmp_path, monkeypatch):
"""Without a client name the stored file name is used."""
import os
import src.job as job_mod
from src.job import Job, JobQueue
from src.model_registry import ModelConfig
from src.pipeline import MergedPipelineResult
seen = {}
def fake(**kwargs):
seen.update(kwargs)
return MergedPipelineResult(
output_path=kwargs["output_path"], frame_count=10, loading_count=0,
unloading_count=0, batch_count=0, duration_seconds=1.0,
model_names=["a.pt"], class_filter=None,
)
monkeypatch.setattr(job_mod, "run_merged_pipeline", fake)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-nm-merged",
video_path="/tmp/clip_1.mp4",
model_configs=[
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack"]),
ModelConfig(filename="b.pt", path=str(tmp_path / "b.pt"), stem="b",
known_classes=["sack"]),
],
output_dir=str(tmp_path / "job-nm-merged"),
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert os.path.basename(seen["output_path"]) == "merged_annotated_clip_1.mp4"
# ── Truncated clip flag (Task 10) ───────────────────────────────────────
def test_job_result_exposes_truncation():
from src.job import JobResult
r = JobResult(model_name="m", output_path="", loading_count=1, unloading_count=0,
net_count=1, batch_count=1, frame_count=40, duration_seconds=1.0,
truncated=True, frames_expected=100)
assert r.truncated is True
assert r.frames_expected == 100
@pytest.mark.parametrize("merged", [False, True])
def test_run_job_propagates_truncation(tmp_path, monkeypatch, merged):
"""_run_job copies truncated/frames_expected from the pipeline result."""
import src.job as job_mod
from src.job import Job, JobQueue, JobStatus
from src.model_registry import ModelConfig
from src.pipeline import MergedPipelineResult, PipelineResult
common = dict(
output_path=str(tmp_path / "out.mp4"),
frame_count=40,
loading_count=1,
unloading_count=0,
batch_count=1,
duration_seconds=1.0,
class_filter=None,
frames_expected=100,
truncated=True,
)
models = [
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack"]),
]
if merged:
monkeypatch.setattr(
job_mod, "run_merged_pipeline",
lambda **kwargs: MergedPipelineResult(model_names=["a.pt"], **common),
)
models.append(ModelConfig(filename="b.pt", path=str(tmp_path / "b.pt"), stem="b",
known_classes=["sack"]))
else:
monkeypatch.setattr(
job_mod, "run_pipeline",
lambda **kwargs: PipelineResult(model_name="a.pt", **common),
)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-t10",
video_path="/tmp/test.mp4",
model_configs=models,
output_dir=str(tmp_path / "job-t10"),
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert job.status == JobStatus.COMPLETED
r = job.results[0]
assert r.truncated is True
assert r.frames_expected == 100
def test_run_job_compresses_the_output_when_the_job_finishes(tmp_path, monkeypatch):
"""A finished job leaves ONE video: the compressed one, under its name."""
import src.job as job_mod
from src.job import Job, JobQueue, JobStatus
from src.model_registry import ModelConfig
from src.pipeline import PipelineResult
out_dir = tmp_path / "job-compress"
out_dir.mkdir()
out_path = out_dir / "a_annotated_clip.mp4"
out_path.write_bytes(b"x" * 300_000)
fake = 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,
)
monkeypatch.setattr(job_mod, "run_pipeline", lambda **kwargs: fake)
def fake_compress(path, **kwargs):
with open(path, "wb") as fh:
fh.write(b"compressed")
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-compress",
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.COMPLETED
# 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,
)