File size: 10,662 Bytes
d835db0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220c87b
 
 
d835db0
 
 
9ec8d34
 
 
fe40b87
9ec8d34
d835db0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77fa8e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220c87b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
from concurrent.futures import ThreadPoolExecutor
import pytest
from fastapi.testclient import TestClient
from baseball_batting.api import create_app
from baseball_batting.api_jobs import JobStore,JobService
from baseball_batting.storage import atomic_json,sha256_file
from baseball_batting.motion_contract import MotionInput
from test_api import fake_service,settings,wait_until,AUTH
from test_motion_player import build,inputs


def stored(service,video):
    lineage=service.store.create_motion(20);job=service.job_directory(lineage['job_id']);job.mkdir()
    manifest,_,_=build(job,video,inputs(annotated_videos=False,timing={'kind':'unretimed','source':'Fixture clock'}))
    # Match the actual immutable queue lineage used by the API.
    manifest.analysis_id=lineage['analysis_id'];manifest.job_id=lineage['job_id']
    atomic_json(job/'result.json',manifest.model_dump(mode='json'))
    atomic_json(job/'request.json',MotionInput.model_validate(manifest.pipeline['inputs']).model_dump(mode='json'))
    atomic_json(job/'lineage.json',lineage)
    service.store.update(job.name,'completed',result_hash=sha256_file(job/'result.json'))
    return job,manifest


def test_motion_upload_auth_readiness_validation_queue_and_cancel(tmp_path,video,monkeypatch):
    import baseball_batting.motion_api as module
    service=fake_service(settings(tmp_path),delay=30)
    monkeypatch.setattr(module,'configured_record',lambda:{'configured':True})
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        files={'video':('swing.mp4',video.read_bytes(),'video/mp4')}
        assert client.post('/v1/motion-analyses',files=files).status_code==401
        assert client.post('/v1/motion-analyses',files=files,headers=AUTH,data={'options':'{"worker_python":"bad"}'}).status_code==422
        r=client.post('/v1/motion-analyses',files=files,headers=AUTH)
        assert r.status_code==202
        data=r.json();job=service.job_directory(data['job_id'])
        assert service.store.get(job.name)['kind']=='motion_player'
        assert json.loads((job/'request.json').read_text())['coaching'] is False
        assert client.get(data['result_url'],headers=AUTH).status_code==409
        assert client.get(data['status_url'],headers=AUTH).json()['analysis_revision']==1
        assert client.delete(data['status_url'],headers=AUTH).status_code==202
        # The public status route holds the mutation lock through cleanup; a raw
        # SQLite read can see the intermediate state before rmtree finishes.
        wait_until(lambda:client.get(data['status_url'],headers=AUTH).json()['status']=='cancelled')
        assert not job.exists()
        assert client.get('/v1/motion-analyses/output-schema',headers=AUTH).status_code==200
        assert client.get('/v1/motion-analyses/input-schema').status_code==401
        capabilities=client.get('/v1/motion-analyses/capabilities',headers=AUTH).json()
        assert capabilities['joint_count']==20
        direction=capabilities['automatic_pitcher_direction']
        assert direction['method']=='automatic_body_swing_direction_v2'
        assert not direction['requires_home_plate'] and not direction['requires_user_direction_input']
        monkeypatch.setattr(module,'configured_record',lambda:None)
        assert client.post('/v1/motion-analyses',files=files,headers=AUTH).status_code==503


def test_verified_artifacts_source_ranges_and_integrity(tmp_path,video):
    service=fake_service(settings(tmp_path));job,manifest=stored(service,video)
    root='/v1/motion-analyses/'+job.name
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        assert client.get(root+'/result').status_code==401
        assert client.get(root+'/result',headers=AUTH).json()['job_id']==job.name
        for key in ('motion','measurements','events','quality','projections','source'):
            url=root+'/artifacts/'+key
            assert client.get(url).status_code==401
            asset=manifest.artifacts[key]
            # Fixture artifacts have URLs for this actual job directory.
            assert client.head(url,headers=AUTH).headers['content-type']==asset.media_type
            assert client.get(url,headers=AUTH).content==(job/asset.filename).read_bytes()
        part=client.get(root+'/artifacts/source',headers={**AUTH,'Range':'bytes=0-9'})
        assert part.status_code==206 and part.content==video.read_bytes()[:10]
        assert client.get(root+'/artifacts/sam-raw-private.npz',headers=AUTH).status_code==404
        assert client.get(root+'/artifacts/mesh',headers=AUTH).status_code==409
        (job/'motion.jsonl').write_text('tampered')
        assert client.get(root+'/artifacts/motion',headers=AUTH).status_code==500
        assert client.get('/v1/sam-batting/analyses/'+job.name+'/result',headers=AUTH).status_code==404


def test_revisions_preserve_parent_and_reuse_source_with_new_immutable_revision(tmp_path,video,monkeypatch):
    import baseball_batting.motion_api as module
    monkeypatch.setattr(module,'configured_record',lambda:{'configured':True})
    service=fake_service(settings(tmp_path),delay=30);parent,manifest=stored(service,video)
    original=(parent/'result.json').read_bytes()
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        r=client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,json={
            'options':{'windows':[{'start_frame':0,'end_frame':7,'stride_start_frame':1,'landing_frame':5}]}})
        assert r.status_code==202,r.text
        data=r.json();child=service.job_directory(data['job_id'])
        assert data['analysis_id']==manifest.analysis_id and data['analysis_revision']==2
        assert (child/'input.mp4').read_bytes()==video.read_bytes()
        options=json.loads((child/'request.json').read_text())
        assert options['timing']['kind']=='unretimed' and options['windows'][0]['landing_frame']==5
        assert (parent/'result.json').read_bytes()==original
        client.delete(data['status_url'],headers=AUTH)
        wait_until(lambda:service.store.get(child.name)['status']=='cancelled')
        assert (parent/'source.mp4').exists()
        assert client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,json={'options':{'model_path':'bad'}}).status_code==422
        assert client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,content=b'x'*(512*1024+1)).status_code==413
        asset=client.post('/v1/motion-analyses',headers=AUTH,data={'source_asset_id':parent.name,'options':'{}'})
        assert asset.status_code==202
        assert asset.json()['analysis_id']!=manifest.analysis_id and asset.json()['analysis_revision']==1
        client.delete(asset.json()['status_url'],headers=AUTH)


def test_revision_numbers_are_unique_under_concurrent_requests_and_worker_is_isolated(tmp_path):
    store=JobStore(tmp_path);first=store.create_motion(30)
    with ThreadPoolExecutor(max_workers=4) as pool:
        children=list(pool.map(lambda _:store.create_motion(30,first['job_id']),range(8)))
    assert sorted(c['analysis_revision'] for c in children)==list(range(2,10))
    assert all(c['analysis_id']==first['analysis_id'] for c in children)
    service=JobService(settings(tmp_path))
    command=service.job_command(service.job_directory(first['job_id']))
    assert 'baseball_batting.motion_worker' in command and '--retention-s' in command


def test_failed_job_reservation_does_not_leak_queue_slots(tmp_path,video,monkeypatch):
    import baseball_batting.motion_api as module
    service=fake_service(settings(tmp_path))
    monkeypatch.setattr(module,'configured_record',lambda:{'configured':True})
    def fail(*args,**kwargs):raise OSError('Fixture unavailable storage')
    monkeypatch.setattr(module,'atomic_json',fail)
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        with pytest.raises(OSError):client.post('/v1/motion-analyses',headers=AUTH,
            files={'video':('swing.mp4',video.read_bytes(),'video/mp4')})
        with service.store.connect() as db:
            assert db.execute('SELECT COUNT(*) FROM jobs').fetchone()[0]==0
            assert db.execute('SELECT COUNT(*) FROM motion_revisions').fetchone()[0]==0
        assert not list(service.jobs_root.iterdir())


@pytest.mark.parametrize('model',['sam3d','gvhmr'])
def test_floor_selection_round_trips_upload_and_revision_without_mutating_parent(tmp_path,video,monkeypatch,model):
    import baseball_batting.motion_api as module
    monkeypatch.setattr(module,'configured_record',lambda:{'configured':True})
    monkeypatch.setattr(module.gvhmr_runtime,'configured_record',lambda:{'configured':True})
    service=fake_service(settings(tmp_path),delay=30);parent,manifest=stored(service,video)
    original=(parent/'result.json').read_bytes()
    camera={'fx':100,'fy':110,'cx':80,'cy':40,'source':'Known fixture calibration','calibration_status':'calibrated'}
    points={'source_frame_index':2,'near_batter':[40,100],'toward_pitcher':[120,90]}
    options={'model':model,'camera':camera,'pitcher_floor_points':points}
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        r=client.post('/v1/motion-analyses',headers=AUTH,
            files={'video':('swing.mp4',video.read_bytes(),'video/mp4')},data={'options':json.dumps(options)})
        assert r.status_code==202,r.text
        job=service.job_directory(r.json()['job_id']);data=json.loads((job/'request.json').read_text())
        assert data['model']==model and data['camera']['calibration_status']=='calibrated'
        assert data['pitcher_floor_points']['source_frame_index']==2
        assert data['pitcher_floor_points']['near_batter']==[40,100]
        client.delete(r.json()['status_url'],headers=AUTH)
        wait_until(lambda:service.store.get(job.name)['status']=='cancelled')
        child=client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,json={'options':options})
        assert child.status_code==202,child.text
        path=service.job_directory(child.json()['job_id']);saved=json.loads((path/'request.json').read_text())
        assert saved['pitcher_floor_points']==data['pitcher_floor_points']
        assert saved['up_vector']==manifest.pipeline['inputs']['up_vector']
        assert (parent/'result.json').read_bytes()==original
        client.delete(child.json()['status_url'],headers=AUTH)
        wait_until(lambda:service.store.get(path.name)['status']=='cancelled')