File size: 18,787 Bytes
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21e264
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3192171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f771d3b
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4800905
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4800905
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
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_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"] == []