"""Regressions for the exported Colab run with all CUDA vision branches failed.""" import json import subprocess import sys from types import SimpleNamespace import numpy as np import pytest from baseball_batting.config import EngineConfig from baseball_batting.ingest import ingest from baseball_batting.observations import run_observations from baseball_batting.pipeline import run_engine from baseball_batting.preflight import vision_ready from baseball_batting.storage import StageCache def test_failed_vision_is_a_failed_analysis_and_visible_report(video, tmp_path): missing = str(tmp_path / "missing.onnx") result = run_engine(video, tmp_path / "out", EngineConfig( body_pose_path=missing, person_detector_path=missing, object_detector_path=missing, device="cuda", export_video=False)) assert result["status"] == "failed" assert result["stages"]["observations"]["status"] == "failed" assert result["diagnostics"]["body_frames"] == 0 assert result["diagnostics"]["available_metrics"] == 0 assert len(result["diagnostics"]["model_failures"]) == 3 report = (tmp_path / "out/report.html").read_text() assert "Analysis failed:" in report and "0 / 8 frames" in report assert all(m["value"] is None for m in result["metrics"]) def test_failed_chunks_retry_after_environment_repair(video, tmp_path, monkeypatch): import baseball_batting.observations as module capture = ingest(video, {}) cache = StageCache(tmp_path, "observations", "same-models-and-config") cfg = EngineConfig(body_pose_path="pose.onnx", person_detector_path="person.onnx", chunk_size=3) def fail(*args, **kwargs): raise RuntimeError("Requested CUDA session did not initialize on CUDA") monkeypatch.setattr(module, "RTMWPose", fail) monkeypatch.setattr(module, "YOLOXDetector", fail) first = run_observations(video, capture, cfg, cache) assert all(s == "unknown" for f in first["frames"] for s in f["body_states"]) class Pose: def __init__(self, *args): pass def __call__(self, image, box): return np.full((133, 2), 20.), np.ones(133) class Detector: def __init__(self, *args): pass def __call__(self, image): return [{"class_id": 0, "box": [10, 10, 100, 110], "score": .9}] monkeypatch.setattr(module, "RTMWPose", Pose) monkeypatch.setattr(module, "YOLOXDetector", Detector) second = run_observations(video, capture, cfg, cache) assert second["branch_status"]["body_pose"]["status"] == "ready" assert all(s == "model_inferred" for f in second["frames"] for s in f["body_states"]) # Successful chunks remain resumable without constructing a model again. monkeypatch.setattr(module, "RTMWPose", fail) assert run_observations(video, capture, cfg, cache)["frames"] == second["frames"] def test_cuda_provider_registration_does_not_hide_cpu_fallback(tmp_path, monkeypatch): import baseball_batting.detection as module artifact = tmp_path / "model.onnx"; artifact.write_bytes(b"fixture") profile = tmp_path / "profile.json"; profile.write_text("[]") class Options: pass class Session: def __init__(self, *args, **kwargs): pass def get_providers(self): return ["CPUExecutionProvider"] def end_profiling(self): return str(profile) fake = SimpleNamespace(__version__="1.26.0", get_available_providers=lambda: ["CUDAExecutionProvider", "CPUExecutionProvider"], SessionOptions=Options, InferenceSession=Session, preload_dlls=lambda: None) monkeypatch.setitem(sys.modules, "onnxruntime", fake) with pytest.raises(RuntimeError, match="CUDA/cuDNN"): module.ort_session(artifact, "cuda") assert not profile.exists() def test_preflight_gate_requires_actual_pose_and_detector(): ready = {name: {"status": "ready"} for name in ("numpy", "scipy", "opencv", "pyav", "body_pose", "person_detector")} assert vision_ready(ready) ready["body_pose"] = {"status": "failed_preflight"} assert not vision_ready(ready) ready["body_pose"] = {"status": "ready"} ready["person_detector"] = {"status": "failed_preflight"} assert not vision_ready(ready) ready["object_detector"] = {"status": "ready"} assert vision_ready(ready) def test_cli_preflight_fails_before_empty_analysis(tmp_path): completed = subprocess.run([sys.executable, "-m", "baseball_batting.cli", "preflight", "--require-vision", "--output", str(tmp_path)], capture_output=True, text=True) assert completed.returncode == 2 assert "Vision preflight failed" in completed.stderr assert json.loads((tmp_path / "runtime_profile.json").read_text())["vision_ready"] is False def test_full_notebook_routes_vision_to_full_worker(tmp_path, monkeypatch): """Execute the setup cell with fake installers, verifying the selected worker.""" from pathlib import Path import nbformat root = Path(__file__).resolve().parents[1] nb = nbformat.read(root / "notebooks/batting_engine.ipynb", as_version=4) cell = next(c.source for c in nb.cells if c.cell_type == "code" and c.source.startswith("BUILD_FULL_WORKER")) workspace = tmp_path / "workspace"; workspace.mkdir() output = tmp_path / "output"; output.mkdir() full_python = str(workspace / ".runtime-full/bin/python") record = {name: name for name in ("sam_repo", "sam_checkpoint", "sam_config", "mhr_path", "mstcn_repo")} record["worker_python"] = full_python (workspace / "full-worker.json").write_text(json.dumps(record)) calls = [] def run(arguments, **kwargs): calls.append(arguments) if "preflight-optional" in arguments: profile = output / "preflight-full"; profile.mkdir() (profile / "optional_runtime_profile.json").write_text(json.dumps({ "tests": {name: {"status": "ready"} for name in ("torch", "mhr", "anatomy")}})) return SimpleNamespace(returncode=0) monkeypatch.setattr(subprocess, "run", run) config = {} scope = dict(PROFILE="gpu_candidate", WORKSPACE_ROOT=workspace, ENGINE_ROOT=root, OUTPUT_ROOT=output, CONFIG_PATH=workspace / "config.json", config=config, json=json, subprocess=subprocess, sys=sys) exec(cell.replace("BUILD_FULL_WORKER = False", "BUILD_FULL_WORKER = True", 1), scope) assert config["stage_python"]["observations"] == full_python vision = next(c for c in calls if "preflight" in c) assert vision[0] == full_python and "--require-vision" in vision