|
| 1 | +"""Regression tests for cancelling a running prediction session (issue #51). |
| 2 | +
|
| 3 | +Cancelling mid-run (e.g. a GUI "stop" button wired to a progress callback) must |
| 4 | +raise inside ``run()`` and then let the ``with`` block exit promptly, instead of |
| 5 | +hanging in ``ProcessManager.join()`` while it drains the worker queues. |
| 6 | +""" |
| 7 | + |
| 8 | +import shutil |
| 9 | +import threading |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +import pytest |
| 13 | + |
| 14 | +from birdnet.acoustic.inference.core.perf_tracker import AcousticProgressStats |
| 15 | +from birdnet.model_loader import load |
| 16 | +from birdnet_tests.test_files import TEST_FILE_LONG |
| 17 | + |
| 18 | + |
| 19 | +def _load_model(): # noqa: ANN202 |
| 20 | + return load("acoustic", "2.4", "tf", precision="fp32", library="tflite") |
| 21 | + |
| 22 | + |
| 23 | +# Generous upper bound on cancel-to-teardown time: we cancel at ~10% progress, so |
| 24 | +# only a little inference runs and a clean teardown finishes well under this. Kept |
| 25 | +# below the global 300s per-test timeout, and enforced from a helper thread, so a |
| 26 | +# regression fails the assertion fast instead of hanging and killing the worker. |
| 27 | +_TEARDOWN_DEADLINE_S = 120.0 |
| 28 | + |
| 29 | + |
| 30 | +def test_cancel_from_progress_callback_tears_down_cleanly(tmp_path: Path) -> None: |
| 31 | + model = _load_model() |
| 32 | + |
| 33 | + # Enough audio across multiple workers that the run lasts well beyond the first |
| 34 | + # progress callback, so cancelling then reliably lands mid-run with many |
| 35 | + # segments (and buffered result batches) still outstanding -- exactly the state |
| 36 | + # that used to deadlock teardown. The run is cancelled almost immediately, so |
| 37 | + # the large file list does not make the test slow. |
| 38 | + # |
| 39 | + # validate_input_files de-duplicates inputs by absolute path (it collects them |
| 40 | + # into a set), so passing the same file N times collapses to a SINGLE input -- |
| 41 | + # the run then finishes before the first progress callback can cancel it, and |
| 42 | + # run() returns without raising. Materialise N distinct copies so the run |
| 43 | + # genuinely spans multiple files and workers. |
| 44 | + src = Path(TEST_FILE_LONG) |
| 45 | + files = [ |
| 46 | + str(shutil.copyfile(src, tmp_path / f"copy_{i}{src.suffix}")) for i in range(8) |
| 47 | + ] |
| 48 | + |
| 49 | + holder: dict = {} |
| 50 | + cancelled = threading.Event() |
| 51 | + |
| 52 | + def on_progress(stats: AcousticProgressStats) -> None: |
| 53 | + # on_progress is only invoked once at least one prediction has been made, so |
| 54 | + # the very first call already means the run is under way with work remaining. |
| 55 | + session = holder.get("session") |
| 56 | + if session is not None and not cancelled.is_set(): |
| 57 | + cancelled.set() |
| 58 | + # Mirrors cancelling from a GUI "stop" button; runs on the dispatcher thread. |
| 59 | + session.cancel() |
| 60 | + |
| 61 | + errors: list[BaseException] = [] |
| 62 | + finished = threading.Event() |
| 63 | + |
| 64 | + def run_session() -> None: |
| 65 | + try: |
| 66 | + with model.predict_session( |
| 67 | + n_workers=2, |
| 68 | + top_k=5, |
| 69 | + show_stats="progress", |
| 70 | + progress_callback=on_progress, |
| 71 | + ) as session: |
| 72 | + holder["session"] = session |
| 73 | + with pytest.raises(RuntimeError, match="cancelled"): |
| 74 | + session.run(files) |
| 75 | + # Reaching here means __exit__ (join + teardown) returned without hanging. |
| 76 | + except BaseException as exc: # noqa: BLE001 - surfaced via the assertions below |
| 77 | + errors.append(exc) |
| 78 | + finally: |
| 79 | + finished.set() |
| 80 | + |
| 81 | + worker = threading.Thread( |
| 82 | + target=run_session, name="cancel-teardown-test", daemon=True |
| 83 | + ) |
| 84 | + worker.start() |
| 85 | + |
| 86 | + completed = finished.wait(timeout=_TEARDOWN_DEADLINE_S) |
| 87 | + assert completed, ( |
| 88 | + f"session did not tear down within {_TEARDOWN_DEADLINE_S:.0f}s after " |
| 89 | + f"cancel() -- ProcessManager.join() likely hung" |
| 90 | + ) |
| 91 | + assert cancelled.is_set(), "progress callback never reached the cancel threshold" |
| 92 | + assert not errors, f"unexpected error during cancelled run/teardown: {errors!r}" |
0 commit comments