File size: 27,444 Bytes
35e80ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4800905
 
 
 
 
 
 
35e80ff
 
 
3249fe4
4800905
 
35e80ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6686c0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413b142
35e80ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40fe6bf
35e80ff
 
 
 
 
 
 
 
 
 
40fe6bf
 
6f63794
 
35e80ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b016f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3249fe4
4800905
7b016f3
 
 
 
4800905
 
7b016f3
 
 
 
 
 
 
 
 
 
 
 
 
e798a49
6686c0f
 
7b016f3
 
 
 
 
 
 
 
 
4800905
7b016f3
 
 
 
 
4800905
7b016f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40fe6bf
 
7b016f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40fe6bf
 
7b016f3
 
 
6f63794
40fe6bf
 
 
 
 
6f63794
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40fe6bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
"""Combined engine/agent contracts, evidence validation and protected retrieval.

Model responses in these tests are fixtures, not evidence of coaching accuracy.
"""
from copy import deepcopy
import json
from pathlib import Path

import pytest

pytest.importorskip("ai_coach")
from ai_coach.config import Settings
from ai_coach.service import CoachService
from ai_coach.schemas import Usage
from ai_coach.timing import parse_timing, build_timing_section
from ai_coach.video_review import review_video
from baseball_batting.api_contract import AnalysisInput
from baseball_batting.product import coach_input, build_product, sample_review_frames
from baseball_batting.storage import sha256_file, atomic_json
from baseball_batting.load_timing import build_load_timing_report
from baseball_batting.timing_evidence import build_timing_evidence
from test_api import settings, fake_service, wait_until, AUTH
from test_load_timing import timing_result


def combined_fixture():
    result = timing_result()
    result['coach_payload'] = {'schema_version':'2.0', 'discipline':'hitting',
        'capture': {'ok':True, 'reasons':[]}, 'reps':[{'rep':1,'metrics':[]}]}
    result['pose_track']['video']['capture_fps'] = 120
    report = build_load_timing_report(result)
    rich = build_timing_evidence(report,result,AnalysisInput(practice_type='front_toss'))
    return result, rich


def coach_settings(tmp_path, **kw):
    return Settings(_env_file=None, cache_path=tmp_path/'cache.sqlite3', log_dir=tmp_path/'logs',
                    google_api_key=None, **kw)


def note():
    return {'features':[
        {'key':'load_timing','status':'observed','rep':1,'observation':'The hands move back before moving forward.', 'evidence_frame_ids':[0,1]},
        {'key':'hip_shoulder_separation','status':'unclear','rep':1,'observation':'The camera angle hides the turning order.', 'evidence_frame_ids':[]},
        {'key':'bat_path_contact','status':'unclear','rep':1,'observation':'The ball is unseen, so contact is unclear.', 'evidence_frame_ids':[]}],
        'priority':{'feature':'load_timing','reason':'Practice a smooth preparation followed by a forward swing.', 'drill_id':'hit_04'}}


def frames():
    return [{'frame':i,'reps':[1],'playback_t_s':i/30,'capture_t_s':None,'jpeg':b'image'} for i in range(3)]


def test_engine_31_context_reasons_and_frame_cadence_reach_agent():
    result,rich = combined_fixture()
    old = deepcopy(rich)
    session = coach_input(result,rich,'session-test')
    parsed = parse_timing(session['timing'])
    assert parsed.reps[0].context.practice_type == 'front_toss'
    assert parsed.capture.capture_fps == 120
    assert parsed.reps[0].frame_interval_ms.median == pytest.approx(1000/120)
    assert parsed.reps[0].metrics[3].reason_codes
    assert all(not m.judgment_eligible for m in parsed.reps[0].metrics)
    section=build_timing_section(parsed)
    assert {o.metric_key for o in section.observations} == {'load_to_swing_ms','foot_down_to_swing_ms'}
    assert 'after' in section.observations[1].text
    assert rich == old
    # Standalone engine output also normalizes shared context/singular codes.
    direct=parse_timing(rich)
    assert direct.reps[0].context.practice_type == 'front_toss'
    assert direct.reps[0].metrics[3].reason_codes


def test_proxy_never_becomes_actual_contact_source():
    result,rich=combined_fixture()
    metric=rich['reps'][0]['metrics'][2]
    metric.update(value=200.,status='estimated',end_event='contact')
    session=coach_input(result,rich,'test')
    assert 'end_event_source' not in session['timing']['reps'][0]['metrics'][2]
    assert not any(o.metric_key=='swing_duration_ms' for o in build_timing_section(parse_timing(session['timing'])).observations)
    rich['reps'][0]['events'].append({'event':'contact','method':'observed_bat_and_ball',
        'uncertainty_kind':'visual_contact_interval'})
    session=coach_input(result,rich,'test')
    assert session['timing']['reps'][0]['metrics'][2]['end_event_source']=='visual_bat_ball_interaction'


def test_known_capture_times_variable_cadence_and_unknown_clock():
    result,rich=combined_fixture()
    result['pose_track']['video']['capture_fps']=None
    session=coach_input(result,rich,'test')
    assert parse_timing(session['timing']).reps[0].frame_interval_ms.median is not None
    result['pose_track']['frames']['t_s']=[i/60 for i in range(150)]
    rich=build_timing_evidence(build_load_timing_report(result),result,AnalysisInput())
    section=build_timing_section(parse_timing(coach_input(result,rich,'test')['timing']))
    assert any('typical gap between recorded frames' in line for line in section.data_quality)
    result['pose_track']['frames']['t_s']=[None]*150
    result['pose_track']['video']['time_source']='unknown'
    rich['capture']['ok']=False
    session=coach_input(result,rich,'test')
    assert session['timing']['reps'][0]['frame_interval_ms'] is None
    parsed=parse_timing(session['timing'])
    assert parsed.capture.time_source=='unknown'
    assert build_timing_section(parsed).observations==[]


def test_malformed_timing_still_returns_the_agents_input_error():
    from ai_coach.input_builder import InputError
    with pytest.raises(InputError):
        parse_timing({'schema_version':'3.1','reps':[{'metrics':None}]})


def test_product_without_provider_preserves_coach_contract(tmp_path):
    result,rich=combined_fixture()
    from baseball_batting.swing_clips import SwingsManifest, Swing, Clip
    bounds=result['pose_track']['reps'][0]
    manifest=SwingsManifest(session_id=tmp_path.name,swings=[Swing(
        rep=1,start_frame=bounds['start_frame'],end_frame=bounds['end_frame'],
        boundary_method='caller_supplied',source_start_playback_s=None,source_end_playback_s=None,
        clip=Clip(status='unavailable',reason_code='source_timestamps_unavailable'))]).model_dump(mode='json')
    atomic_json(tmp_path/'swings.json',manifest)
    svc=CoachService(settings=coach_settings(tmp_path))
    product=build_product(tmp_path,Path('unused.mp4'),result,rich,AnalysisInput(coaching_mode='poc_video'),service=svc)
    assert product['coaching']['response_version']=='2.0'
    assert product['schema_version']=='1.1'
    assert product['swings']==manifest['swings']
    assert product['swings_url']==f'/v1/analyses/{tmp_path.name}/swings'
    assert product['coaching']['timing']['observations']
    assert product['visual_review']['reason_code']=='model_not_configured'
    assert product['coaching']['focus']==[] and product['coaching']['drill'] is None
    assert product['visual_review']['judgment_eligible'] is False
    assert (tmp_path/'coach-input.json').is_file() and (tmp_path/'product.json').is_file()


def test_bounded_sampling_rotation_multiple_reps_and_unknown_time(video,tmp_path):
    track={'video':{'rotation_degrees_applied':90},
        'frames':{'t_s':[None]*8,'playback_t_s':[i/30 for i in range(8)]},
        'reps':[{'rep':1,'start_frame':0,'end_frame':3,'events':{}},
                {'rep':2,'start_frame':4,'end_frame':7,'events':{}}]}
    samples=sample_review_frames(video,track,tmp_path/'frames',max_frames=6,max_reps=2)
    assert len(samples)<=6 and {r for f in samples for r in f['reps']}=={1,2}
    assert all(f['capture_t_s'] is None for f in samples)
    import cv2
    img=cv2.imread(str(tmp_path/'frames'/f"{samples[0]['frame']}.jpg"))
    assert img.shape[:2]==(160,120)
    assert sha256_file(tmp_path/'frames'/f"{samples[0]['frame']}.jpg")==samples[0]['sha256']
    limited=sample_review_frames(video,track,tmp_path/'limited',max_frames=4,max_reps=1)
    assert all(f['reps']==[1] for f in limited)


def test_visual_review_success_uses_library_drill_and_no_measurement_upgrade(tmp_path):
    result=review_video(frames(),{},coach_settings(tmp_path),generator=lambda *a:(json.dumps(note()),Usage(input_tokens=100,output_tokens=20)))
    assert result['status']=='completed'
    assert result['drill']['name']=='Slow-Motion Load Dry Swings'
    assert result['accuracy_validated'] is False and result['judgment_eligible'] is False


def test_observation_presentation_keeps_evidence_and_handles_spacing(tmp_path):
    data = note()
    data['features'][0]['observation'] = '  the hands  move back , then forward\n'
    original = deepcopy(data)
    result = review_video(frames(), {}, coach_settings(tmp_path),
                          generator=lambda *a: (json.dumps(data), Usage()))
    assert result['status'] == 'completed'
    assert result['features'][0]['observation'] == 'The hands move back, then forward.'
    assert result['features'][0]['evidence_frame_ids'] == [0, 1]
    assert data == original
    from ai_coach.video_review import review_is_current
    assert review_is_current(result)
    legacy = deepcopy(result)
    legacy.pop('text_style_version')
    assert not review_is_current(legacy)


@pytest.mark.parametrize('bad',['invented_frame','wrong_rep','duplicate','reversed','one_frame','angle','numeric_priority','wrong_drill','unclear_priority','duplicate_feature'])
def test_visual_review_rejects_unsupported_responses(tmp_path,bad):
    raw=note(); f=raw['features'][0]
    if bad=='invented_frame': f['evidence_frame_ids']=[0,500]
    if bad=='wrong_rep': f['rep']=2
    if bad=='duplicate': f['evidence_frame_ids']=[0,0]
    if bad=='reversed': f['evidence_frame_ids']=[1,0]
    if bad=='one_frame': f['evidence_frame_ids']=[0]
    if bad=='angle': f['observation']='The hips rotate forty degrees.'
    if bad=='numeric_priority': raw['priority']['reason']='You started 10 ms late.'
    if bad=='wrong_drill': raw['priority']['drill_id']='hit_14'
    if bad=='unclear_priority': f['status']='unclear'
    if bad=='duplicate_feature': raw['features'][2]['key']='load_timing'
    result=review_video(frames(),{},coach_settings(tmp_path),generator=lambda *a:(json.dumps(raw),Usage()))
    assert result['status']=='unavailable' and result['reason_code']=='invalid_visual_response'
    assert result['priority'] is None


def test_provider_failure_budget_and_no_key_do_not_fabricate_feedback(tmp_path):
    def broken(*a): raise RuntimeError('secret-provider-error')
    result=review_video(frames(),{},coach_settings(tmp_path),generator=broken)
    assert result['reason_code']=='provider_failed' and 'secret' not in json.dumps(result)
    result=review_video(frames(),{},coach_settings(tmp_path,daily_budget_usd=0),generator=broken)
    assert result['reason_code']=='daily_budget_exhausted'
    assert review_video(frames(),{},coach_settings(tmp_path))['reason_code']=='model_not_configured'
    assert review_video([],{},coach_settings(tmp_path))['reason_code']=='no_swing_evidence'


def test_actual_sdk_request_uses_images_schema_timeouts_and_billed_usage(tmp_path,monkeypatch):
    from google import genai
    from google.genai import types
    from ai_coach.video_review import gemini_generate
    calls=[]
    class Models:
        def generate_content(self,**kwargs):
            calls.append(kwargs)
            return types.GenerateContentResponse(
                candidates=[types.Candidate(content=types.Content(parts=[types.Part.from_text(text=json.dumps(note()))]))],
                usage_metadata=types.GenerateContentResponseUsageMetadata(prompt_token_count=50,
                    candidates_token_count=20,thoughts_token_count=5,cached_content_token_count=10))
    class Client:
        def __init__(self,**kwargs):
            assert kwargs['http_options'].timeout==90000
            assert kwargs['http_options'].retry_options.attempts==1
            self.models=Models()
        def __enter__(self):return self
        def __exit__(self,*a):pass
    monkeypatch.setattr(genai,'Client',Client)
    configured=coach_settings(tmp_path).model_copy(update={'google_api_key':__import__('pydantic').SecretStr('test-not-a-key')})
    raw,usage=gemini_generate(configured,frames(),{'capture_clock_known':False})
    assert json.loads(raw)['features'][0]['key']=='load_timing'
    assert usage.input_tokens==50 and usage.output_tokens==25 and usage.cached_tokens==10
    assert calls[0]['config'].response_mime_type=='application/json'
    assert calls[0]['config'].max_output_tokens==8000
    assert calls[0]['config'].thinking_config.thinking_level.value=='LOW'
    assert calls[0]['config'].response_schema is None
    assert calls[0]['config'].response_json_schema['properties']['features']['minItems']==3
    assert len([p for p in calls[0]['contents'] if p.inline_data])==3
    assert 'test-not-a-key' not in str(calls)


def test_provider_preflight_checks_metadata_without_generation(tmp_path,monkeypatch):
    from google import genai
    from ai_coach.video_review import provider_status
    from pydantic import SecretStr
    configured=coach_settings(tmp_path).model_copy(update={'google_api_key':SecretStr('test-not-a-key')})
    class Client:
        def __init__(self,**kw):self.models=self
        def __enter__(self):return self
        def __exit__(self,*a):pass
        def get(self,*,model):return {'name':model}
    monkeypatch.setattr(genai,'Client',Client)
    assert provider_status(configured)['status']=='available'
    assert provider_status(coach_settings(tmp_path))['status']=='not_configured'
    class Broken(Client):
        def get(self,**kw):raise ValueError('secret')
    monkeypatch.setattr(genai,'Client',Broken)
    result=provider_status(configured)
    assert result['status']=='provider_unavailable' and 'secret' not in json.dumps(result)


def test_product_routes_auth_integrity_frames_and_cancellation(tmp_path,video):
    from fastapi.testclient import TestClient
    from baseball_batting.api import create_app
    service=fake_service(settings(tmp_path))
    identifier=service.store.create(8); job=service.job_directory(identifier);job.mkdir()
    (job/'review-frames').mkdir(); (job/'review-frames/0.jpg').write_bytes(b'frame')
    product={'coaching':{'response_version':'2.0'},'evidence':{'frames':[{'frame':0,'sha256':sha256_file(job/'review-frames/0.jpg')}]}}
    atomic_json(job/'product.json',product)
    service.store.update(identifier,'completed',product_hash=sha256_file(job/'product.json'))
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        assert client.get('/').status_code==200
        url=f'/v1/analyses/{identifier}'
        assert client.get(url+'/product').status_code==401
        assert client.get(url+'/product',headers=AUTH).json()==product
        assert client.get(url+'/coaching',headers=AUTH).json()==product['coaching']
        assert client.get(url+'/frames/0',headers=AUTH).content==b'frame'
        assert client.get(url+'/frames/-1',headers=AUTH).status_code==404
        (job/'review-frames/0.jpg').write_bytes(b'tampered')
        assert client.get(url+'/frames/0',headers=AUTH).status_code==500
        (job/'product.json').write_text('{}')
        assert client.get(url+'/product',headers=AUTH).status_code==500
        assert client.delete(url,headers=AUTH).status_code==202
        assert service.store.get(identifier)['product_sha256'] is None
        assert not job.exists()
        assert client.get(url+'/product',headers=AUTH).status_code==409


def test_product_upload_default_and_legacy_opt_in(video,tmp_path):
    from fastapi.testclient import TestClient
    from baseball_batting.api import create_app
    service=fake_service(settings(tmp_path,job_timeout_s=60),delay=20)
    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/swing-coach/analyses',files=files).status_code==401
        r=client.post('/v1/swing-coach/analyses',files=files,headers=AUTH)
        assert r.status_code==202
        job=service.job_directory(r.json()['job_id'])
        assert json.loads((job/'request.json').read_text())['coaching_mode']=='poc_video'
        assert r.json()['product_url']
        old=client.post('/v1/analyses',files=files,headers=AUTH)
        assert old.json()['product_url'] is None
        assert json.loads((service.job_directory(old.json()['job_id'])/'request.json').read_text())['coaching_mode']=='disabled'
        for response in (r,old):client.delete(response.json()['status_url'],headers=AUTH)


@pytest.mark.parametrize('code,reason',[(400,'provider_request_rejected'),(401,'provider_auth_failed'),
    (403,'provider_access_denied'),(404,'provider_model_unavailable'),(429,'provider_rate_limited'),(503,'provider_unavailable')])
def test_google_failures_have_safe_actionable_reasons(tmp_path,code,reason):
    from google.genai.errors import APIError
    def broken(*args):
        raise APIError(code,{'error':{'message':'private-key-and-user-image','details':[
            {'violations':[{'quotaMetric':'generativelanguage.googleapis.com/generate_content_free_tier_requests'},
                           {'quotaMetric':'private-project-id'}]}]}})
    result=review_video(frames(),{},coach_settings(tmp_path),generator=broken)
    assert result['reason_code']==reason and result['provider_http_status']==code
    assert 'private' not in json.dumps(result)
    assert result['message'] and result['quota_metrics']==['generativelanguage.googleapis.com/generate_content_free_tier_requests']


def test_google_timeout_and_invalid_key_are_distinguished(tmp_path):
    import httpx
    from google.genai.errors import APIError
    def timeout(*args):raise httpx.ReadTimeout('secret-key')
    result=review_video(frames(),{},coach_settings(tmp_path),generator=timeout)
    assert result['reason_code']=='provider_timeout' and result['retryable']
    def bad_key(*args):raise APIError(400,{'error':{'message':'private','details':[{'reason':'API_KEY_INVALID'}]}})
    assert review_video(frames(),{},coach_settings(tmp_path),generator=bad_key)['reason_code']=='provider_auth_failed'


def retained_review_job(tmp_path):
    service=fake_service(settings(tmp_path))
    identifier=service.store.create(8);job=service.job_directory(identifier);job.mkdir()
    (job/'review-frames').mkdir();(job/'review-frames/0.jpg').write_bytes(b'original-image')
    atomic_json(job/'request.json',AnalysisInput(coaching_mode='poc_video').model_dump(mode='json'))
    product={'session_id':identifier,'coaching':{'response_version':'2.0'},
             'swings':[{'rep':1,'clip':{'status':'available','url':f'/v1/analyses/{identifier}/swings/1/clip'}}],
             'visual_review':{'status':'unavailable','reason_code':'provider_failed'},
             'evidence':{'frames':[{'frame':0,'reps':[1],'sha256':sha256_file(job/'review-frames/0.jpg')}]}}
    atomic_json(job/'product.json',product)
    service.store.update(identifier,'completed',result_hash='original-result-hash',coach_hash='original-coach-hash',
        timing_hash='original-timing-hash',evidence_hash='original-evidence-hash',product_hash=sha256_file(job/'product.json'),
        swings_hash='original-swings-hash')
    return service,identifier,job,product


def test_retry_review_preserves_measurements_auth_and_checksums(tmp_path,monkeypatch):
    from fastapi.testclient import TestClient
    from baseball_batting.api import create_app
    from baseball_batting.product import retry_video_review
    import ai_coach.video_review as review
    service,identifier,job,product=retained_review_job(tmp_path)
    calls=[]
    def fake_review(frames,facts,*args,**kwargs):
        calls.append(frames)
        assert frames[0]['jpeg']==b'original-image'
        from ai_coach.visual_scoring import unavailable_score
        return {'status':'completed','features':[], 'text_style_version':review.TEXT_STYLE_VERSION,
                'score':unavailable_score('insufficient_visible_features')}
    monkeypatch.setattr(review,'review_video',fake_review)
    # Exercise the actual retained-frame loader, not a replacement retry handler.
    assert retry_video_review(job,product,AnalysisInput())['visual_review']['status']=='completed'
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        url=f'/v1/analyses/{identifier}/video-review'
        assert client.post(url).status_code==401
        r=client.post(url,headers=AUTH)
        assert r.status_code==200 and r.json()['coaching']==product['coaching']
        assert r.json()['swings']==product['swings']
        saved=service.store.get(identifier)
        assert saved['result_sha256']=='original-result-hash'
        assert saved['coach_payload_sha256']=='original-coach-hash'
        assert saved['load_timing_sha256']=='original-timing-hash'
        assert saved['timing_evidence_sha256']=='original-evidence-hash'
        assert saved['swings_sha256']=='original-swings-hash'
        assert saved['product_sha256']==sha256_file(job/'product.json')
        assert client.post(url,headers=AUTH).status_code==200
        assert len(calls)==2  # Completed retries are idempotent; no extra billed call.


def test_retry_never_resurrects_deleted_job_or_accepts_bad_frames(tmp_path,monkeypatch):
    from fastapi.testclient import TestClient
    from baseball_batting.api import create_app
    import ai_coach.video_review as review
    service,identifier,job,product=retained_review_job(tmp_path)
    def cancelled(*args,**kw):
        service.delete(identifier)
        return {'status':'completed','features':[]}
    monkeypatch.setattr(review,'review_video',cancelled)
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        (job/'review-frames/0.jpg').write_bytes(b'tampered')
        url=f'/v1/analyses/{identifier}/video-review'
        assert client.post(url,headers=AUTH).status_code==500
        assert service.store.get(identifier)['status']=='completed'
        (job/'review-frames/0.jpg').write_bytes(b'original-image')
        assert client.post(url,headers=AUTH).status_code==409
        assert not job.exists() and service.store.get(identifier)['status']=='cancelled'


def test_retry_storage_failure_keeps_the_previous_product(tmp_path,monkeypatch):
    from fastapi.testclient import TestClient
    from baseball_batting.api import create_app
    import ai_coach.video_review as review
    service,identifier,job,product=retained_review_job(tmp_path)
    monkeypatch.setattr(review,'review_video',lambda *a,**k:{'status':'completed','features':[]})
    def broken(*args):raise OSError('database unavailable')
    monkeypatch.setattr(service.store,'update_product',broken)
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        url=f'/v1/analyses/{identifier}'
        assert client.post(url+'/video-review',headers=AUTH).status_code==500
        assert client.get(url+'/product',headers=AUTH).json()==product


@pytest.mark.parametrize('thinking_level',['low','auto'])
def test_real_google_sdk_serializes_our_schema_and_decodes_response(tmp_path,monkeypatch,thinking_level):
    from google import genai
    from google.genai import types
    from pydantic import SecretStr
    from ai_coach.video_review import gemini_generate
    sdk_client=genai.Client
    requests=[]
    def make_client(**kw):
        client=sdk_client(**kw)
        def transport(method,path,body,*args):
            requests.append(body)
            return types.HttpResponse(body=json.dumps({'candidates':[{'content':{'parts':[{'text':json.dumps(note())}]},
                'finishReason':'STOP'}], 'usageMetadata':{'promptTokenCount':50,'candidatesTokenCount':20}}))
        client._api_client.request=transport
        return client
    monkeypatch.setattr(genai,'Client',make_client)
    configured=coach_settings(tmp_path).model_copy(update={'google_api_key':SecretStr('test-not-a-key'),
        'video_review_thinking_level':thinking_level})
    raw,usage=gemini_generate(configured,frames(),{})
    assert json.loads(raw)['features'][0]['key']=='load_timing'
    assert usage.input_tokens==50 and usage.output_tokens==20
    config=requests[0]['generationConfig']
    assert config['maxOutputTokens']==8000
    if thinking_level=='auto':
        assert 'thinkingConfig' not in config
    else:
        assert config['thinkingConfig']['thinking_level']=='LOW'
    assert 'responseSchema' not in config
    schema=config['responseJsonSchema']
    assert schema['properties']['features']['minItems']==3
    assert schema['additionalProperties'] is False
    assert schema['$defs']['FeatureReview']['properties']['rep']['minimum']==1
    assert schema['$defs']['FeatureReview']['properties']['key']['enum']==[
        'load_timing','hip_shoulder_separation','bat_path_contact']
    assert schema['properties']['priority']['anyOf'][1]=={'type':'null'}
    for unsupported in ('minLength','maxLength','default','min_items','additional_properties'):
        assert unsupported not in json.dumps(schema)


def test_provider_schema_subset_keeps_local_length_and_evidence_validation(tmp_path):
    from ai_coach.video_review import review_video
    too_long=note()
    too_long['features'][0]['observation']='x'*551
    result=review_video(frames(),{},coach_settings(tmp_path),generator=lambda *a:(json.dumps(too_long),Usage()))
    assert result['reason_code']=='invalid_visual_response'
    assert result['validation_reasons']==['string_too_long']


def test_truncated_google_response_reports_safe_reason_and_keeps_billed_usage(tmp_path,monkeypatch):
    from google import genai
    from google.genai import types
    from pydantic import SecretStr
    from ai_coach.cost import UsageLedger
    from ai_coach.video_review import review_video
    configured=coach_settings(tmp_path).model_copy(update={'google_api_key':SecretStr('test-not-a-key')})
    class Client:
        def __init__(self,**kw):self.models=self
        def __enter__(self):return self
        def __exit__(self,*a):pass
        def generate_content(self,**kw):
            return types.GenerateContentResponse(candidates=[types.Candidate(finish_reason='MAX_TOKENS',
                content=types.Content(parts=[types.Part.from_text(text='private model content')]))],
                usage_metadata=types.GenerateContentResponseUsageMetadata(prompt_token_count=100,
                    thoughts_token_count=2500))
    monkeypatch.setattr(genai,'Client',Client)
    ledger=UsageLedger(configured.resolved_ledger_path,1)
    result=review_video(frames(),{},configured,ledger=ledger)
    assert result['validation_reason']=='output_truncated'
    assert 'private model content' not in json.dumps(result)
    assert ledger._query('SELECT input_tokens, output_tokens, reasoning_tokens, cost_usd FROM calls')[0][:3]==(100,2500,2500)
    assert ledger._query('SELECT cost_usd FROM calls')[0][0]>0


@pytest.mark.parametrize('alter,reason',[
    (lambda n:n['features'][0].update(evidence_frame_ids=[2,1]),'evidence_order'),
    (lambda n:n['features'][0].update(evidence_frame_ids=[1,999]),'evidence_reference'),
    (lambda n:n['features'][0].update(observation='Your swing took 100 ms.'),'unsupported_claim')])
def test_visual_validation_reports_allowlisted_reason_without_model_text(tmp_path,alter,reason):
    from ai_coach.video_review import review_video
    bad=note();alter(bad)
    result=review_video(frames(),{},coach_settings(tmp_path),generator=lambda *a:(json.dumps(bad),Usage()))
    assert result['validation_reason']==reason
    assert bad['features'][0]['observation'] not in json.dumps(result)