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')