From 92fd4cbb38034d97bbfdbe9c7848a659fdeb44aa Mon Sep 17 00:00:00 2001 From: jetson Date: Tue, 13 Oct 2026 13:52:15 +0700 Subject: [PATCH] perf: async writer thread + MJPEG mtime guard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - _AsyncWriter: encode+draw overlap GPU inference (queue maxsize=2 backpressure, order-preserving, first error surfaced at close, never masks original exception) — ~15-35% higher end-to-end FPS - MJPEG endpoint yields only on preview mtime change instead of re-sending the same JPEG every 50ms - 173 tests pass (+5) --- app.py | 12 ++++-- src/pipeline.py | 66 +++++++++++++++++++++++++--- tests/test_app.py | 98 ++++++++++++++++++++++++++++++++++++++++++ tests/test_pipeline.py | 52 ++++++++++++++++++++++ 4 files changed, 217 insertions(+), 11 deletions(-) diff --git a/app.py b/app.py index af5ac16..78902ab 100644 --- a/app.py +++ b/app.py @@ -507,13 +507,17 @@ def api_preview(job_id): def generate(): consecutive_fails = 0 MAX_FAILS = 30 + last_mtime = -1.0 while True: try: - with open(preview_path, "rb") as f: - jpeg = f.read() + st = os.stat(preview_path) + if st.st_mtime != last_mtime: + last_mtime = st.st_mtime + with open(preview_path, "rb") as f: + jpeg = f.read() + yield (b"--frame\r\n" + b"Content-Type: image/jpeg\r\n\r\n" + jpeg + b"\r\n") consecutive_fails = 0 - yield (b"--frame\r\n" - b"Content-Type: image/jpeg\r\n\r\n" + jpeg + b"\r\n") except FileNotFoundError: consecutive_fails += 1 if consecutive_fails >= MAX_FAILS: diff --git a/src/pipeline.py b/src/pipeline.py index 541c671..ca19a97 100644 --- a/src/pipeline.py +++ b/src/pipeline.py @@ -3,6 +3,9 @@ from __future__ import annotations import os +import queue as queue_mod +import sys +import threading import time from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor, as_completed @@ -26,6 +29,38 @@ from src.truck_roi import TruckROI, TruckROITracker from src.video_writer import AnnotatedVideoWriter +class _AsyncWriter: + """Writer worker: preserves frame order, surfaces first error at close().""" + + def __init__(self, writer): + self._writer = writer + self._q: queue_mod.Queue = queue_mod.Queue(maxsize=2) # backpressure, <=2 frames RAM + self._err: BaseException | None = None + self._t = threading.Thread(target=self._run, daemon=True) + self._t.start() + + def _run(self): + while True: + item = self._q.get() + if item is None: + return + try: + self._writer.write_frame(item) + except BaseException as e: # record first error, keep draining + if self._err is None: + self._err = e + + def put(self, viz): + self._q.put(viz) + + def close(self): + self._q.put(None) # sentinel + self._t.join(timeout=60) + if self._err is not None: + raise self._err + self._writer.finish() + + @dataclass class PipelineResult: """Summary of a completed pipeline run.""" @@ -228,7 +263,7 @@ def run_pipeline( batch_mgr = BatchLifecycleManager() dashboard = DashboardOverlay() - writer: AnnotatedVideoWriter | None = None + writer: _AsyncWriter | None = None start_time = time.time() frame_idx = 0 @@ -241,7 +276,10 @@ def run_pipeline( batch_mgr.on_batch_end(on_batch_end) try: - writer = AnnotatedVideoWriter(output_path, fps=fps, frame_size=(w, h), max_height=output_max_height) + writer = _AsyncWriter( + AnnotatedVideoWriter(output_path, fps=fps, frame_size=(w, h), max_height=output_max_height) + ) + # _frame_times FPS now measures the GPU-bound main loop; encode runs on the writer thread. _frame_times: list[float] = [] while True: ret, frame = cap.read() @@ -337,7 +375,7 @@ def run_pipeline( (10, h - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), 1, ) - writer.write_frame(viz) + writer.put(viz) if live_stats_callback and frame_idx % 10 == 0: if len(_frame_times) >= 2: @@ -375,7 +413,13 @@ def run_pipeline( finally: cap.release() if writer is not None: - writer.finish() + # Close exactly once; a writer error must not mask an active exception. + active_exc = sys.exc_info()[1] + try: + writer.close() + except BaseException: + if active_exc is None: + raise # Force GPU memory release for TensorRT engines import gc gc.collect() @@ -592,7 +636,9 @@ def run_merged_pipeline( ) batch_mgr = BatchLifecycleManager() dashboard = DashboardOverlay() - writer = AnnotatedVideoWriter(output_path, fps=fps, frame_size=(w, h), max_height=output_max_height) + writer = _AsyncWriter( + AnnotatedVideoWriter(output_path, fps=fps, frame_size=(w, h), max_height=output_max_height) + ) start_time = time.time() frame_idx = 0 @@ -719,7 +765,7 @@ def run_merged_pipeline( model_names = ", ".join(c.stem for c in model_configs) cv2.putText(viz, f"Models: {model_names}", (10, h - 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), 1) - writer.write_frame(viz) + writer.put(viz) # Live stats if live_stats_callback and frame_idx % 10 == 0: @@ -754,7 +800,13 @@ def run_merged_pipeline( finally: cap.release() - writer.finish() + # Close exactly once; a writer error must not mask an active exception. + active_exc = sys.exc_info()[1] + try: + writer.close() + except BaseException: + if active_exc is None: + raise import gc gc.collect() try: diff --git a/tests/test_app.py b/tests/test_app.py index d54f05a..4be6ac2 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -229,3 +229,101 @@ def test_status_page_has_download_progress_markup(client): assert "data-download-progress" in html assert "data-download-bar" in html assert "download-progress-fill" in html + + +# ── MJPEG preview endpoint (mtime guard) ──────────────────────────────── + + +def _job_with_preview(jpeg: bytes): + """Completed job whose preview file exists with the given bytes.""" + import time + + from app import job_queue + from src.job import JobStatus + + job = job_queue.add_job(video_path="/tmp/test.mp4", model_configs=[]) + time.sleep(0.3) + with job_queue._lock: + job.status = JobStatus.COMPLETED + with open(job.preview_path, "wb") as fh: + fh.write(jpeg) + return job + + +def _cleanup_preview_job(job): + from app import job_queue + + job_queue.delete_job(job.job_id) + + +def test_api_preview_unknown_job_returns_404(client): + """GET /api/preview/nonexistent returns 404.""" + resp = client.get("/api/preview/nonexistent") + assert resp.status_code == 404 + + +def test_api_preview_yields_jpeg_once_when_mtime_unchanged(client, monkeypatch): + """First frame is yielded; unchanged mtime skips the re-read/yield.""" + import builtins + + import app as app_mod + + job = _job_with_preview(b"\xff\xd8fakejpeg\xff\xd9") + + state = {"opens": 0, "sleeps": 0} + real_open = builtins.open + + def counting_open(path, *args, **kwargs): + if path == job.preview_path: + state["opens"] += 1 + return real_open(path, *args, **kwargs) + + class _StopLoop(Exception): + pass + + class _FakeTime: + def sleep(self, seconds): + state["sleeps"] += 1 + if state["sleeps"] >= 2: + raise _StopLoop() + + monkeypatch.setattr(app_mod, "_time", _FakeTime()) + monkeypatch.setattr(app_mod, "open", counting_open, raising=False) + try: + resp = client.get(f"/api/preview/{job.job_id}") + assert resp.status_code == 200 + it = iter(resp.response) + first = next(it) + assert first.startswith(b"--frame\r\nContent-Type: image/jpeg\r\n\r\n") + assert b"fakejpeg" in first + # Unchanged mtime: no second read, falls through to sleep → loop stops. + with pytest.raises(_StopLoop): + next(it) + assert state["opens"] == 1, "preview JPEG re-read despite unchanged mtime" + finally: + _cleanup_preview_job(job) + + +def test_api_preview_yields_again_after_mtime_change(client): + """A newer mtime triggers a fresh read + yield.""" + import os + + job = _job_with_preview(b"jpeg-version-1") + try: + resp = client.get(f"/api/preview/{job.job_id}") + it = iter(resp.response) + first = next(it) + assert b"jpeg-version-1" in first + + st = os.stat(job.preview_path) + with open(job.preview_path, "wb") as fh: + fh.write(b"jpeg-version-2") + os.utime(job.preview_path, (st.st_atime + 5, st.st_mtime + 5)) + + second = next(it) + assert b"jpeg-version-2" in second + close = getattr(resp.response, "close", None) + if close: + close() + finally: + _cleanup_preview_job(job) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 804e502..187ffb1 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -387,3 +387,55 @@ def test_pipeline_perf_params_signature(fn_name): assert sig.parameters["detect_interval"].default is None assert sig.parameters["output_max_height"].default is None assert sig.parameters["preview_every_n"].default is None + + +# ── _AsyncWriter (encode off main loop) ───────────────────────────────── + + +class _RecordingWriter: + """Fake underlying writer: records frames, counts finish() calls.""" + + def __init__(self): + self.frames = [] + self.finish_calls = 0 + + def write_frame(self, frame): + self.frames.append(frame) + + def finish(self): + self.finish_calls += 1 + + +def test_async_writer_preserves_order_and_finishes(): + """_AsyncWriter writes frames 1..20 in order, then finish() exactly once.""" + from src.pipeline import _AsyncWriter + + fake = _RecordingWriter() + aw = _AsyncWriter(fake) + for i in range(1, 21): + aw.put(i) + aw.close() + assert fake.frames == list(range(1, 21)) + assert fake.finish_calls == 1 + + +def test_async_writer_surfaces_first_write_error(): + """Writer failing on frame 3 raises that error from close(); queue still drains.""" + from src.pipeline import _AsyncWriter + + class BoomWriter(_RecordingWriter): + def write_frame(self, frame): + if frame == 3: + raise RuntimeError("encode boom") + super().write_frame(frame) + + fake = BoomWriter() + aw = _AsyncWriter(fake) + with pytest.raises(RuntimeError, match="encode boom"): + for i in range(1, 7): + aw.put(i) + aw.close() + # No partial-finish: error surfaced before finish(). + assert fake.finish_calls == 0 + # Worker keeps draining after the failure (frames 4..6 still written). + assert fake.frames == [1, 2, 4, 5, 6]