import json from pathlib import Path import sys import time import numpy as np import pytest pytest.importorskip("fastapi") from fastapi.testclient import TestClient from baseball_batting.api import create_app from baseball_batting.api_contract import AnalysisInput from baseball_batting.api_jobs import ApiSettings, JobService, JobStore, QueueFull from baseball_batting.api_output import build_api_result from baseball_batting.ingest import ingest from baseball_batting.observations import run_observations from baseball_batting.storage import StageCache, atomic_json KEY = "fixture-key-this-is-not-a-credential" AUTH = {"Authorization": "Bearer " + KEY} def wait_until(predicate, timeout=5): deadline = time.monotonic() + timeout while time.monotonic() < deadline: result = predicate() if result: return result time.sleep(.02) raise AssertionError("Condition did not become true") def settings(tmp_path, **overrides): overrides.setdefault('model_root', tmp_path/'models') return ApiSettings(api_key=KEY, data_root=tmp_path, minimum_free_bytes=0, **overrides) def fake_service(s, *, delay=0, preflight_ok=True): def command(directory): script = ("import json,time; from pathlib import Path; " f"p=Path({str(directory)!r}); " "(p/'progress.json').write_text(json.dumps({'stage':'pose_2d','completed_frames':1,'total_frames':2})); " f"time.sleep({delay}); " "(p/'result.json').write_text(json.dumps({'pose_track':{'frames':{'kp':[]}},'measurements':{'reps':[]}})); " "(p/'coach-payload.json').write_text(json.dumps({'schema_version':'2.0','discipline':'hitting','capture':{'ok':False,'reasons':['no_person']},'reps':[]}))") return [sys.executable, "-c", script] return JobService(s, command_factory=command, preflight_command=[sys.executable, "-c", f"raise SystemExit({0 if preflight_ok else 1})"]) def upload(client, video, **kwargs): return client.post("/v1/analyses", headers=AUTH, files={"video": ("swing.mp4", video.read_bytes(), "video/mp4")}, **kwargs) def test_retired_contact_endpoints_are_not_exposed(tmp_path): s = settings(tmp_path) service = fake_service(s) app = create_app(s, service) paths = app.openapi()['paths'] assert not any(path.startswith('/v1/contact-analyses') for path in paths) for path in ('/v1/analyses', '/v1/load-timing/analyses', '/v1/swing-coach/analyses', '/v1/sam-batting/analyses', '/v1/motion-analyses'): assert 'post' in paths[path] with TestClient(app) as client: wait_until(lambda: service.ready) assert client.post('/v1/contact-analyses', headers=AUTH).status_code == 404 assert client.get('/v1/contact-analyses/input-schema', headers=AUTH).status_code == 404 assert client.get('/v1/contact-analyses/' + 'a' * 32, headers=AUTH).status_code == 404 def test_recovery_retires_contact_jobs_and_preserves_existing_data(tmp_path): service = fake_service(settings(tmp_path)) # Reuse a database from a deployment which still had the contact API. with service.store.connect() as db: db.execute('ALTER TABLE jobs ADD COLUMN contact_artifacts_sha256 TEXT') store = JobStore(tmp_path) contact_jobs = [] for status in ('uploading', 'queued', 'running', 'cancel_requested', 'completed'): identifier = store.create(16, kind='contact') store.update(identifier, status) directory = service.job_directory(identifier) directory.mkdir() (directory/'result.json').write_text('{"retained": true}') contact_jobs.append((identifier, status)) legacy = store.create(16) store.update(legacy, 'running') motion = store.create(16, kind='motion_player') store.update(motion, 'queued') assert store.recover() == [] for identifier, status in contact_jobs: record = store.get(identifier) assert record['status'] == ('completed' if status == 'completed' else 'failed') assert record['error'] == (None if status == 'completed' else 'api_removed') assert (service.job_directory(identifier)/'result.json').read_text() == '{"retained": true}' with pytest.raises(ValueError, match='Unsupported analysis job kind'): service.job_command(service.job_directory(identifier)) assert store.get(legacy)['status'] == 'queued' assert store.get(motion)['status'] == 'queued' assert {store.claim(), store.claim()} == {legacy, motion} assert store.claim() is None def test_upload_poll_fetch_delete_and_auth(video, tmp_path): s = settings(tmp_path) service = fake_service(s, delay=.2) with TestClient(create_app(s, service)) as client: wait_until(lambda: service.ready) assert client.get("/healthz").json()["body_3d"] is False assert client.get("/v1/capabilities").status_code == 401 assert client.post("/v1/analyses", content=b"malformed").status_code == 401 assert client.get("/v1/capabilities", headers=AUTH).json()["device"] == "cuda" assert client.get("/v1/input-schema", headers=AUTH).status_code == 200 assert client.get("/v1/output-schema", headers=AUTH).status_code == 200 assert client.get("/v1/coach-payload-schema", headers=AUTH).status_code == 200 response = upload(client, video) assert response.status_code == 202, response.text job_id = response.json()["job_id"] assert client.get(response.json()["result_url"], headers=AUTH).status_code == 409 wait_until(lambda: service.store.get(job_id)["status"] == "completed") status = client.get(response.json()["status_url"], headers=AUTH).json() assert status["status"] == "completed" and status["progress"]["stage"] == "pose_2d" result = client.get(response.json()["result_url"], headers=AUTH) assert result.status_code == 200 and result.headers["cache-control"] == "no-store" assert "pose_track" in result.json() coach = client.get(response.json()["coach_payload_url"], headers=AUTH) assert coach.status_code == 200 and coach.headers["cache-control"] == "no-store" assert "pose_track" not in coach.json() and coach.json()["schema_version"] == "2.0" wait_until(lambda: not list(service.job_directory(job_id).glob("input.*"))) assert client.delete(response.json()["status_url"], headers=AUTH).status_code == 202 assert not service.job_directory(job_id).exists() assert client.get(response.json()["result_url"], headers=AUTH).status_code == 409 def test_invalid_options_forbid_3d_and_paths(video, tmp_path): s = settings(tmp_path) service = fake_service(s) with TestClient(create_app(s, service)) as client: wait_until(lambda: service.ready) for options in ({"body3d_enabled": True}, {"device": "cpu"}, {"discipline": "pitching"}, {"annotations_path": "/etc/passwd"}, {"timing": {"kind": "unretimed"}}, {"body_height_px": 400}, {"level": "professional"}, {"timing": {"kind": "constant_slowdown", "source": "camera", "factor": 8}}, {"reps": [{"start_frame": 10, "end_frame": 2}]}, {"reps": [{"start_frame": 0, "end_frame": 5}, {"start_frame": 3, "end_frame": 7}]}): response = upload(client, video, data={"options": json.dumps(options)}) assert response.status_code == 422, response.text assert list(service.jobs_root.iterdir()) == [] def test_selectable_3d_backend_preserves_options_and_reports_configuration(video, tmp_path, monkeypatch): s = settings(tmp_path, model_root=tmp_path/"models") monkeypatch.delenv("BASEBALL_SAM_WORKER_RECORD", raising=False) service = fake_service(s) with TestClient(create_app(s, service)) as client: wait_until(lambda: service.ready) capability = client.get("/v1/capabilities", headers=AUTH).json() assert capability["body_3d"] is True assert capability["measurement_backends"]["rtmw3d"]["configured"] is False assert capability["measurement_backends"]["sam3d"]["configured"] is False for backend in ("2d", "rtmw3d", "sam3d"): response = upload(client, video, data={"options": json.dumps({"measurement_backend": backend})}) assert response.status_code == 202 job = service.job_directory(response.json()["job_id"]) assert json.loads((job/"request.json").read_text())["measurement_backend"] == backend assert upload(client, video, data={"options": '{"measurement_backend":"sam3d","sam_repo":"/tmp"}'}).status_code == 422 def test_gpu_readiness_fails_closed(video, tmp_path): s = settings(tmp_path) service = fake_service(s, preflight_ok=False) with TestClient(create_app(s, service)) as client: wait_until(lambda: service.readiness_reason == "gpu_preflight_failed") assert client.get("/readyz").status_code == 503 assert upload(client, video).status_code == 503 def test_upload_limits_and_empty_video(video, tmp_path): s = settings(tmp_path, max_upload_bytes=32) service = fake_service(s) with TestClient(create_app(s, service)) as client: wait_until(lambda: service.ready) assert upload(client, video).status_code == 413 assert client.post("/v1/analyses", headers=AUTH, files={"video": ("x.mp4", b"")}).status_code == 422 assert client.post("/v1/analyses", headers=AUTH, files={"video": ("x.py", b"123")}).status_code == 415 assert list(service.jobs_root.iterdir()) == [] def test_streamed_body_limit_without_content_length(tmp_path): s = settings(tmp_path, max_upload_bytes=32) service = fake_service(s) def chunks(): yield b'--boundary\r\nContent-Disposition: form-data; name="video"; filename="swing.mp4"\r\nContent-Type: video/mp4\r\n\r\n' for _ in range(512): yield b"x" * 4096 yield b"\r\n--boundary--\r\n" with TestClient(create_app(s, service)) as client: wait_until(lambda: service.ready) response = client.post("/v1/analyses", headers={**AUTH, "Content-Type": "multipart/form-data; boundary=boundary"}, content=chunks()) assert response.status_code == 413, response.text def test_queue_full_and_cancel_running(video, tmp_path): s = settings(tmp_path, max_active_jobs=1) service = fake_service(s, delay=30) with TestClient(create_app(s, service)) as client: wait_until(lambda: service.ready) first = upload(client, video).json() wait_until(lambda: service.store.get(first["job_id"])["status"] == "running") second = upload(client, video) assert second.status_code == 429 assert client.delete(first["status_url"], headers=AUTH).json()["status"] == "cancel_requested" wait_until(lambda: service.store.get(first["job_id"])["status"] == "cancelled") assert not service.job_directory(first["job_id"]).exists() def test_worker_timeout(video, tmp_path): s = settings(tmp_path, job_timeout_s=.1) service = fake_service(s, delay=30) with TestClient(create_app(s, service)) as client: wait_until(lambda: service.ready) job = upload(client, video).json() wait_until(lambda: service.store.get(job["job_id"])["status"] == "failed") assert client.get(job["status_url"], headers=AUTH).json()["error"] == "job_timeout" def test_result_checksum_and_id_validation(video, tmp_path): s = settings(tmp_path) service = fake_service(s) with TestClient(create_app(s, service)) as client: wait_until(lambda: service.ready) job = upload(client, video).json() wait_until(lambda: service.store.get(job["job_id"])["status"] == "completed") (service.job_directory(job["job_id"]) / "result.json").write_text("corrupt") assert client.get(job["result_url"], headers=AUTH).status_code == 500 (service.job_directory(job["job_id"]) / "coach-payload.json").write_text("corrupt") assert client.get(job["coach_payload_url"], headers=AUTH).status_code == 500 assert client.get(job["coach_payload_url"]).status_code == 401 assert client.get("/v1/analyses/bogus", headers=AUTH).status_code == 404 def test_recovery_retention_and_single_worker_lock(tmp_path): s = settings(tmp_path) service = fake_service(s) running = service.store.create(8); service.store.update(running, "running") uploading = service.store.create(8) directory = service.job_directory(uploading); directory.mkdir() service.start() try: second = fake_service(s) with pytest.raises(RuntimeError, match="already has an API worker"): second.start() assert service.store.get(uploading) is None and not directory.exists() # The recovered job has no fixture input, so fake runner fails normally. wait_until(lambda: service.store.get(running)["status"] == "failed") expired = service.store.create(8); service.store.update(expired, "completed") with service.store.connect() as db: db.execute("UPDATE jobs SET updated=0 WHERE id=?", (expired,)) service.cleanup() assert service.store.get(expired) is None finally: service.stop() def test_shutdown_requeues_and_kills_worker(video, tmp_path): s = settings(tmp_path) service = fake_service(s, delay=30) with TestClient(create_app(s, service)) as client: wait_until(lambda: service.ready) job = upload(client, video).json() wait_until(lambda: service.store.get(job["job_id"])["status"] == "running") assert service.store.get(job["job_id"])["status"] == "queued" assert list(service.job_directory(job["job_id"]).glob("input.*")) resumed = fake_service(s) with TestClient(create_app(s, resumed)): wait_until(lambda: resumed.store.get(job["job_id"])["status"] == "completed") def test_pose_handoff_real_decoding_raw_points_and_unknown_time(video, tmp_path, monkeypatch): import baseball_batting.observations as module class Pose: def __init__(self, *args): pass def __call__(self, image, box): points = np.column_stack([np.arange(133), np.arange(133)]) + 10. points[0] = [-1, 10] # Out-of-image predictions must become null + zero. scores = np.full(133, .8); scores[5] = .1 return points, scores class Detector: def __init__(self, *args): pass def __call__(self, image): return [{"class_id": 0, "box": [10, 10, 110, 110], "score": .9}, {"class_id": 0, "box": [1, 1, 20, 20], "score": .9}] monkeypatch.setattr(module, "RTMWPose", Pose) monkeypatch.setattr(module, "YOLOXDetector", Detector) from baseball_batting.config import EngineConfig capture = ingest(video, {}) observations = run_observations(video, capture, EngineConfig(body_pose_path="pose.onnx", person_detector_path="person.onnx"), StageCache(tmp_path, "observations", "fixture")) result = build_api_result(capture, observations, AnalysisInput(single_swing=True), {"body_pose": "fixture", "person_detector": "fixture"}) frames = result["pose_track"]["frames"] assert all(len(value) == 8 for value in frames.values()) assert frames["kp"][0][0] is None and frames["conf"][0][0] == 0 assert frames["kp"][0][5] is None and frames["conf"][0][5] == 0 assert len(frames["kp"][0]) == 17 and len(frames["kp_extra"][0]) == 6 assert frames["kp_extra"][0][0] == [27., 27.] assert frames["people_count"] == [1] * 8 # tiny background proposal is not an athlete assert frames["t_s"] == [None] * 8 and frames["playback_t_s"][1] == pytest.approx(.033) assert not result["measurements"]["capture"]["ok"] assert result["pose_track"]["reps"][0]["events"] == {} assert "kp3d" not in result["pose_track"] and "findings" not in result json.dumps(result, allow_nan=False) import jsonschema schema = json.loads((Path(__file__).resolve().parents[1] / "docs/api-result.schema.json").read_text()) jsonschema.Draft202012Validator.check_schema(schema) jsonschema.validate(result, schema) options = AnalysisInput(timing={"kind": "constant_slowdown", "source": "camera export", "factor": 4, "all_captured_frames_retained": True}) slow = ingest(video, options.engine_metadata()) rescaled = build_api_result(slow, observations, options, {"body_pose": "fixture", "person_detector": "fixture"}) assert rescaled["pose_track"]["frames"]["t_s"][1] == pytest.approx(.033 / 4) # Variable frame intervals are preserved and not presented as constant capture FPS. assert rescaled["pose_track"]["video"]["capture_fps"] is None assert rescaled["pose_track"]["reps"] == [] with pytest.raises(ValueError, match="exceeds"): build_api_result(capture, observations, AnalysisInput(reps=[{"start_frame": 0, "end_frame": 99}]), {"body_pose": "fixture", "person_detector": "fixture"}) def test_bounded_decoding(video): with pytest.raises(ValueError, match="frame limit"): ingest(video, {}, max_frames=2) with pytest.raises(ValueError, match="pixel limit"): ingest(video, {}, max_pixels=10) with pytest.raises(ValueError, match="duration limit"): ingest(video, {}, max_duration_s=.01) def test_decoder_blocks_network_playlist_segments(tmp_path): import av from baseball_batting.ingest import iter_frames playlist = tmp_path / "recording.m3u8" playlist.write_text('#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-MEDIA-SEQUENCE:0\n' '#EXT-X-TARGETDURATION:1\n#EXTINF:1.0,\n' 'http://127.0.0.1:1/remote.ts\n#EXT-X-ENDLIST\n') old_level = av.logging.get_level() av.logging.set_level(av.logging.ERROR) try: with av.logging.Capture() as logs: with pytest.raises(av.error.FFmpegError): list(iter_frames(playlist)) assert any("Protocol 'http' not on whitelist" in line for _, _, line in logs) finally: av.logging.set_level(old_level) def test_model_gate_requires_correct_checkpoints(tmp_path): from baseball_batting.api_worker import model_files with pytest.raises(ValueError, match="Missing or incorrect"): model_files(tmp_path) def test_worker_environment_excludes_api_secret(tmp_path, monkeypatch): monkeypatch.setenv("BASEBALL_API_KEY", KEY) service = fake_service(settings(tmp_path)) assert "BASEBALL_API_KEY" not in service.environment() assert service.environment()["MPLBACKEND"] == "Agg" def test_existing_job_database_migrates_without_losing_records(tmp_path): import sqlite3 identifier = "a"*32 with sqlite3.connect(tmp_path / "jobs.sqlite3") as db: db.execute("CREATE TABLE jobs (id TEXT PRIMARY KEY,status TEXT,created REAL,updated REAL,error TEXT,result_sha256 TEXT)") db.execute("INSERT INTO jobs VALUES (?, 'completed', 1, 1, NULL, 'old-hash')", (identifier,)) store = JobStore(tmp_path) assert store.get(identifier)["result_sha256"] == "old-hash" assert store.get(identifier)["coach_payload_sha256"] is None assert store.get(identifier)["swings_sha256"] is None fresh = store.create(8) store.update(fresh, "completed", result_hash="result", coach_hash="coach") assert store.get(fresh)["coach_payload_sha256"] == "coach" def test_no_person_worker_returns_record_again_payload(video, tmp_path, monkeypatch): from baseball_batting.api_worker import run_analysis import baseball_batting.api_worker as worker import baseball_batting.observations as observation_module import shutil shutil.copy2(video, tmp_path / "input.mp4") atomic_json(tmp_path / "request.json", {}) monkeypatch.setattr(worker, "model_files", lambda models: ({"body_pose":"pose", "person_detector":"person"}, {"body_pose":"test", "person_detector":"test"})) def absent(video, capture, config, cache, progress=None): assert not config.body3d_enabled and not config.temporal3d_enabled and not config.anatomy_enabled return {"branch_status":{"body_pose":{"status":"ready"},"person_detector":{"status":"ready"}}, "frames":[{"frame_id":i,"body_points":[None]*133,"body_scores":[0]*133, "body_states":["unknown"]*133,"person":None,"people_count":0} for i in range(capture["frame_count"])]} monkeypatch.setattr(observation_module, "run_observations", absent) result = run_analysis(tmp_path, tmp_path, device="cpu") payload = json.loads((tmp_path / "coach-payload.json").read_text()) assert payload == result["coach_payload"] assert payload["capture"]["ok"] is False and "no_person" in payload["capture"]["reasons"] assert payload["reps"] == [] assert "pose_track" not in payload assert json.loads((tmp_path / "swings.json").read_text())["swings"] == []