File size: 13,935 Bytes
df8b40e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffb9fd9
df8b40e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffb9fd9
df8b40e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6e922f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9210696
 
 
ffb9fd9
9210696
 
 
 
 
 
 
 
 
 
ffb9fd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9210696
 
 
 
 
 
 
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
"""Estimated coaching rubric, grounded evidence and missing-data invariance."""
from copy import deepcopy
import json
import pytest
pytest.importorskip('ai_coach')
from ai_coach.group_review import available_facts,build_reviews,RatingBatch,ASPECTS
from ai_coach.config import Settings
from ai_coach.service import CoachService
from baseball_batting.sam_batting_contract import MeasurementGroup,SamMeasurement,SwingMeasurements,SamGroupReviewRequest
from baseball_batting.sam_measurements import DEFINITIONS
from baseball_batting.swing_clips import Clip


def group_fixture():
    samples={'rotation':{'hip_shoulder_separation_deg':30,'hip_rotation_from_start_deg':80},
        'timing':{'hip_peak_time_ms':100,'hands_peak_time_ms':200,'hand_speed_relative_m_s':4},
        'posture':{'forward_lean_deg':20,'head_excursion_relative_cm':5},
        'stance':{'stance_span_cm':50,'left_foot_heading_deg':80,'right_foot_heading_deg':100}}
    groups=[]
    for key,values in samples.items():
        rows=[]
        for name,value in values.items():
            label,unit,formula=DEFINITIONS[name]
            rows.append(SamMeasurement(key=name,label=label,value=value,unit=unit,
                reference='fixed_starting_hip_axis',statistic='at_baseline',status='estimated',formula=formula,source_frame_ids=[10]))
        groups.append(MeasurementGroup(key=key,label=key,annotated_video=Clip(status='unavailable',reason_code='fixture'),
            swings=[SwingMeasurements(rep=1,window_source='reviewed',start_frame=0,end_frame=90,
                baseline_frame=0,forward_rotation_sign=1,lead_foot='left',quality_flags=[],measurements=rows)]))
    return groups


def provider_response(groups,grade=3):
    facts,_=available_facts(groups);result=[]
    for group in facts:
        ids=[r['metric_id'] for r in group['measurements']]
        point={'text':'Keep practicing this measured movement with a controlled setup.','evidence_ids':ids[:1]}
        result.append({'key':group['key'],'aspects':[{'key':a['key'],'grade':grade,
            'explanation':'The measured pattern provides a useful starting point for practice.','evidence_ids':a['evidence_ids'][:1]} for a in group['aspects']],
            'summary':'This measured pattern offers a practical focus for the next session.',
            'what_went_well':[point],'what_needs_work':[point],'next_step':point})
    return {'groups':result}


def test_scores_are_real_rubric_grades_not_measurement_coverage():
    groups=group_fixture();facts,evidence=available_facts(groups)
    raw=provider_response(groups);raw['groups'][0]['aspects'][0]['grade']=1
    result=build_reviews(RatingBatch.model_validate(raw),facts,evidence,'fixture-model')
    assert result[raw['groups'][0]['key']]['score']['value']==5
    for key,row in result.items():
        assert 0<=row['score']['value']<=10
        assert row['score']['accuracy_validated'] is False
        assert row['coaching']['next_step']['evidence'][0]['value'] is not None
    # Zero is a legitimate rubric score, not a missing result.
    zero=build_reviews(RatingBatch.model_validate(provider_response(groups,grade=0)),facts,evidence,'fixture')
    assert all(r['score']['value']==0 for r in zero.values())


def test_missing_measurements_do_not_change_facts_score_or_denominator():
    groups=group_fixture();before=available_facts(groups)
    groups[2].swings[0].measurements.append(SamMeasurement(key='center_of_mass_displacement_cm',label='Mass',
        value=None,unit='cm',status='unavailable',reference='ground',statistic='maximum',formula='mass model',reason_code='missing_mass_model'))
    assert available_facts(groups)==before
    facts,evidence=before;raw=provider_response(groups)
    a=build_reviews(RatingBatch.model_validate(raw),facts,evidence,'fixture')
    b=build_reviews(RatingBatch.model_validate(raw),*available_facts(groups),'fixture')
    assert a==b
    # Exclude a genuinely unassessed aspect and renormalize the remaining grades.
    groups[3].swings[0].measurements=[m for m in groups[3].swings[0].measurements if m.key=='stance_span_cm']
    facts,evidence=available_facts(groups)
    assert len(next(g for g in facts if g['key']=='stance')['aspects'])==1
    r=build_reviews(RatingBatch.model_validate(provider_response(groups)),facts,evidence,'fixture')
    assert r['stance']['score']['value']==7.5


@pytest.mark.parametrize('tamper',['bad_metric','cross_group','cross_aspect','duplicate_aspect','bad_grade'])
def test_provider_cannot_invent_evidence_quantities_or_change_score_rules(tamper):
    groups=group_fixture();facts,evidence=available_facts(groups);raw=provider_response(groups)
    row=raw['groups'][0]
    if tamper=='bad_metric':row['next_step']['evidence_ids']=['invented']
    elif tamper=='cross_group':row['next_step']['evidence_ids']=[next(g for g in facts if g['key']!=row['key'])['measurements'][0]['metric_id']]
    elif tamper=='cross_aspect':row['aspects'][0]['evidence_ids']=row['aspects'][1]['evidence_ids']
    elif tamper=='duplicate_aspect':row['aspects'][1]['key']=row['aspects'][0]['key']
    elif tamper=='bad_grade':row['aspects'][0]['grade']=5
    with pytest.raises(ValueError):build_reviews(RatingBatch.model_validate(raw),facts,evidence,'fixture')


def test_agent_uses_shared_cache_and_budget_without_changing_measurements(tmp_path,monkeypatch):
    from google import genai
    from google.genai import types
    from pydantic import SecretStr
    calls=[];groups=group_fixture();original=[[m.model_dump() for m in g.swings[0].measurements] for g in groups]
    class Client:
        def __init__(self,**kwargs):self.models=self
        def __enter__(self):return self
        def __exit__(self,*a):pass
        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(provider_response(groups)))]))],
                usage_metadata=types.GenerateContentResponseUsageMetadata(prompt_token_count=100,candidates_token_count=200))
    monkeypatch.setattr(genai,'Client',Client)
    service=CoachService(Settings(_env_file=None,google_api_key=SecretStr('fixture-not-a-key'),cache_path=tmp_path/'cache.db',log_dir=tmp_path/'logs'))
    service.review_groups(groups)
    assert all(g.score.status=='estimated' and g.score.value==7.5 and g.coaching for g in groups)
    assert [[m.model_dump() for m in g.swings[0].measurements] for g in groups]==original
    service.review_groups(group_fixture());assert len(calls)==1
    assert 'image/jpeg' not in str(calls[0])
    assert 'missing_mass_model' not in calls[0]['contents']


def test_provider_failure_does_not_invent_a_default_score_or_lose_values(tmp_path):
    groups=group_fixture()
    service=CoachService(Settings(_env_file=None,google_api_key=None,cache_path=tmp_path/'cache.db',log_dir=tmp_path/'logs'))
    service.review_groups(groups)
    assert all(g.score.value is None and g.score.reason_code=='coach_not_configured' for g in groups)
    assert groups[0].swings[0].measurements[0].value==30


@pytest.mark.parametrize('repaired',[True,False])
def test_invalid_provider_response_has_one_billed_repair_and_never_fabricates_a_score(tmp_path,monkeypatch,repaired):
    from google import genai
    from google.genai import types
    from pydantic import SecretStr
    groups=group_fixture();calls=[];billed=[]
    class Client:
        def __init__(self,**kwargs):self.models=self
        def __enter__(self):return self
        def __exit__(self,*a):pass
        def generate_content(self,**kwargs):
            calls.append(kwargs);raw=provider_response(groups)
            if len(calls)==1 or not repaired:raw['groups'][0]['next_step']['evidence_ids']=['invented']
            return types.GenerateContentResponse(candidates=[types.Candidate(content=types.Content(parts=[types.Part.from_text(text=json.dumps(raw))]))],
                usage_metadata=types.GenerateContentResponseUsageMetadata(prompt_token_count=100,candidates_token_count=200))
    monkeypatch.setattr(genai,'Client',Client)
    service=CoachService(Settings(_env_file=None,google_api_key=SecretStr('fixture-not-a-key'),cache_path=tmp_path/'cache.db',log_dir=tmp_path/'logs'))
    monkeypatch.setattr(service.ledger,'record_call',lambda **kw:billed.append(kw))
    service.review_groups(groups)
    assert len(calls)==len(billed)==2 and [b['attempt'] for b in billed]==[1,2]
    assert 'REPAIR:' in calls[1]['contents']
    if repaired:assert all(g.score.value==7.5 for g in groups)
    else:assert all(g.score.value is None and g.score.reason_code=='coach_response_invalid' for g in groups)
    assert groups[0].swings[0].measurements[0].value==30


def test_standalone_review_rejects_wrong_group_keys_and_units():
    groups=group_fixture();SamGroupReviewRequest(groups=groups)
    groups[0].swings[0].measurements[0].unit='ms'
    with pytest.raises(ValueError):SamGroupReviewRequest(groups=groups)


def test_actual_sdk_serializes_inline_provider_schema():
    import httpx
    from google import genai
    from google.genai import types
    from ai_coach.group_review import provider_schema
    captured=[]
    def handler(request):
        captured.append(json.loads(request.content))
        return httpx.Response(200,json={'candidates':[{'content':{'parts':[{'text':'{"groups":[]}'}]}}]})
    with genai.Client(api_key='fixture-not-a-key',http_options=types.HttpOptions(client_args={'transport':httpx.MockTransport(handler)})) as client:
        client.models.generate_content(model='gemini-3.8-flash',contents='Fixture',config=types.GenerateContentConfig(
            response_mime_type='application/json',response_json_schema=provider_schema()))
    wire=json.dumps(captured[0]['generationConfig']['responseJsonSchema'])
    assert '$defs' not in wire and '$ref' not in wire and 'minItems' not in wire


def test_provider_error_details_are_typed_and_redact_the_key(tmp_path,monkeypatch):
    from google import genai
    from pydantic import SecretStr
    class ProviderError(Exception):
        code=429
        message='Rejected request using fixture-not-a-key'
    class Client:
        def __init__(self,**kwargs):self.models=self
        def __enter__(self):return self
        def __exit__(self,*a):pass
        def generate_content(self,**kwargs):raise ProviderError()
    monkeypatch.setattr(genai,'Client',Client)
    service=CoachService(Settings(_env_file=None,google_api_key=SecretStr('fixture-not-a-key'),cache_path=tmp_path/'cache.db',log_dir=tmp_path/'logs'))
    groups=group_fixture();service.review_groups(groups)
    assert all(g.score.reason_code=='coach_provider_http_429' for g in groups)
    assert all('fixture-not-a-key' not in g.score.failure_detail and '[redacted]' in g.score.failure_detail for g in groups)


@pytest.mark.parametrize('claim',[
    'Your bat speed was 99 mph.',
    'Your lean was maintained throughout the motion.',
    'The stance provided a repeatable base.',
    'Hand acceleration was synchronized with the pelvis.',
    'Hip rotation ended with abrupt deceleration.',
    'Make the initial foot headings symmetrical.',
    'Missing data prevents judging this movement.'
])
def test_scalar_evidence_cannot_be_laundered_into_dynamic_or_symmetry_claims(claim):
    groups=group_fixture();facts,evidence=available_facts(groups);raw=provider_response(groups)
    raw['groups'][0]['summary']=claim
    result=build_reviews(RatingBatch.model_validate(raw),facts,evidence,'fixture')
    repaired=result[raw['groups'][0]['key']]
    assert repaired['score']['value']==7.5
    assert repaired['coaching']['summary']!=claim
    assert repaired['coaching']['summary_source']=='rules'
    assert repaired['coaching']['source']=='mixed'
    assert all(r['score']['value']==7.5 for r in result.values())


def test_bad_paragraphs_are_replaced_individually_without_losing_valid_feedback():
    groups=group_fixture();facts,evidence=available_facts(groups);raw=provider_response(groups)
    timing=next(g for g in raw['groups'] if g['key']=='timing')
    timing['summary']='Hand acceleration was synchronized with the pelvis.'
    timing['aspects'][0]['explanation']='Your bat speed was 99 mph.'
    timing['what_needs_work'][0]={**timing['what_needs_work'][0],
        'text':'Missing data prevents judging this movement.'}
    result=build_reviews(RatingBatch.model_validate(raw),facts,evidence,'fixture')
    row=result['timing']
    assert row['score']['value']==7.5 and row['coaching']['source']=='mixed'
    assert row['score']['aspects'][0]['explanation_source']=='rules'
    assert row['coaching']['what_needs_work'][0]['source']=='rules'
    assert row['coaching']['next_step']['source']=='coach_agent'
    assert row['coaching']['what_went_well'][0]['text']==timing['what_went_well'][0]['text']
    assert 'before the hand-speed peak' in row['coaching']['summary']
    assert result['rotation']['coaching']['source']=='coach_agent'
    # All additions remain valid public response DTOs, including provenance.
    from baseball_batting.sam_batting_contract import SamGroupReviewResponse
    SamGroupReviewResponse(groups=[{'key':key,**r} for key,r in result.items()])


def test_factual_replacements_do_not_confuse_ground_relative_or_partial_stance_data():
    from ai_coach.group_review import _fact_text
    row={'key':'head_excursion_ground_cm','rep':1,'value':4,'reference':'ground'}
    assert 'ground reference' in _fact_text([row]) and 'hip midpoint' not in _fact_text([row])
    row['key']='stance_span_cm'
    assert 'projected' not in _fact_text([row])
    row['key']='stance_width_baseline_cm'
    assert 'projected' in _fact_text([row])


def test_practice_goals_are_distinct_from_claims_about_current_motion():
    from ai_coach.group_review import _text
    goal='Practice a repeatable setup before each swing.'
    assert _text(goal,suggestion=True)==goal
    with pytest.raises(ValueError):_text(goal)