File size: 7,303 Bytes
35e80ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Property-style checks: the rule-based baseline must never break its own guardrails, whatever the measurements are.

Two sweeps: a grid (every problem x level x every other metric present as an estimate, missing or in range) and a seeded
random sweep over measurements, confidences, nulls, capture reasons, levels, overrides and arm care. The review that added
this found that library wording collided with the estimate-mention rule in about 3% of random sessions.
"""

import random

import pytest

from ai_coach import knowledge as kb
from ai_coach.fallback import build_fallback_note
from ai_coach.guardrails import check_note
from ai_coach.input_builder import build_coach_input

LEVELS = ("hs_jv", "hs_varsity", "college")
CONFIDENCES = ("high", "medium", "est")
CAPTURE_REASONS = kb._load("bounds.yaml")["capture_reasons"]
GRID_REPS = 6


def midpoint(discipline, key, level):
    rng = kb.metric_range(discipline, key, level)
    if rng:
        return (rng.low + rng.high) / 2
    lo, hi = kb._load("bounds.yaml")[discipline][key]
    return (lo + hi) / 2


def session(discipline, level, series, **extra):
    """series: key -> (confidence, [value per rep]); units come from the knowledge files."""
    n = max(len(v[1]) for v in series.values())
    reps = [
        {"metrics": [{"key": k, "value": vals[i], "unit": "", "confidence": c} for k, (c, vals) in series.items()]}
        for i in range(n)
    ]
    out = {"discipline": discipline, "fps": 240.0, "level": level, "capture": {"ok": True, "reasons": []}, "reps": reps}
    if discipline == "pitching":
        out["arm_care"] = {
            "known": True,
            "pitch_count_today": 40,
            "daily_max": 95,
            "next_eligible_date": "2026-10-13",
            "alerts": [],
        }
    out.update(extra)
    return out


def trigger(discipline, level, problem_key):
    """Overrides and series that make one problem eligible (bands are added where the library has none)."""
    spec = kb.problems(discipline)[problem_key]
    series, overrides = {}, {}
    for rule in spec["rules"]:
        key = rule["metric"]
        if rule["type"] == "never":
            continue
        if rule["type"] == "spread":
            series[key] = ("medium", [40.0, 75.0, 45.0, 72.0, 41.0, 74.0])
            continue
        rng = kb.metric_range(discipline, key, level)
        if rng is None or not rng.comparable:
            lo, hi = kb._load("bounds.yaml")[discipline][key]
            band = (lo + (hi - lo) * 0.4, lo + (hi - lo) * 0.5)
            overrides[key] = band
            rng = kb.metric_range(discipline, key, level, {key: band})
        miss = rng.width * 1.5
        value = rng.high + miss if rule["direction"] == "above" else rng.low - miss
        series[key] = ("high", [value] * GRID_REPS)
    return series, overrides


def violations(data, overrides=None):
    coach_input = build_coach_input(data, range_overrides=overrides)
    note = build_fallback_note(coach_input)
    return [str(v) for v in check_note(note, coach_input)], coach_input


@pytest.mark.parametrize("discipline", ["hitting", "pitching"])
def test_grid_every_problem_with_every_other_metric_as_estimate_missing_or_in_range(discipline):
    failures, cases, with_problem = [], 0, 0
    for problem_key, spec in kb.problems(discipline).items():
        if all(r["type"] == "never" for r in spec["rules"]):
            continue
        for level in LEVELS:
            base, overrides = trigger(discipline, level, problem_key)
            for other in kb.metric_keys(discipline):
                if other in base:
                    continue
                for mode in ("est", "null", "in_range"):
                    series = dict(base)
                    if mode == "est":
                        series[other] = ("est", [midpoint(discipline, other, level)] * GRID_REPS)
                    elif mode == "null":
                        series[other] = ("high", [None] * GRID_REPS)
                    else:
                        mid = midpoint(discipline, other, level)
                        series[other] = ("high", [mid] * GRID_REPS)
                        if kb.metric_range(discipline, other, level) is None:  # a coach target makes it praise-worthy
                            overrides = {**overrides, other: (mid - 1.0, mid + 1.0)}
                    found, coach_input = violations(session(discipline, level, series), overrides)
                    cases += 1
                    with_problem += any(p.key == problem_key for p in coach_input.problems)
                    if found:
                        failures.append((problem_key, level, other, mode, found[:2]))
    assert not failures, f"{len(failures)} of {cases} cases broke the guardrails, e.g. {failures[:3]}"
    assert with_problem > cases * 0.75, "the grid must actually exercise the problems it claims to"


def random_session(rng):
    discipline = rng.choice(["hitting", "pitching"])
    level = rng.choice([*LEVELS, None, "pro"])
    bounds = kb._load("bounds.yaml")[discipline]
    keys = rng.sample(kb.metric_keys(discipline), rng.randint(1, len(kb.metric_keys(discipline))))
    n = rng.randint(1, 8)
    series, overrides = {}, {}
    for key in keys:
        lo, hi = bounds[key]
        rngi = kb.metric_range(discipline, key, level if level in LEVELS else "hs_varsity")
        centre, spread = ((rngi.low + rngi.high) / 2, rngi.width * 1.2) if rngi else ((lo + hi) / 2, (hi - lo) * 0.3)
        vals = [None if rng.random() < 0.15 else min(hi, max(lo, rng.gauss(centre, spread))) for _ in range(n)]
        series[key] = (rng.choice(CONFIDENCES), vals)
        if rngi is None and rng.random() < 0.3:
            overrides[key] = (lo + (hi - lo) * 0.3, lo + (hi - lo) * 0.5)
    capture = {"ok": rng.random() < 0.85, "reasons": rng.sample(CAPTURE_REASONS, rng.randint(0, 4))}
    extra = {"capture": capture, "fps": rng.choice([30.0, 60.0, 120.0, 240.0])}
    if discipline == "pitching" and rng.random() < 0.7:
        extra["arm_care"] = {
            "known": True,
            "pitch_count_today": rng.randint(0, 120),
            "daily_max": rng.choice([75, 95, 105]),
            "next_eligible_date": rng.choice(["2026-10-13", "2026-11-02", None]),
            "alerts": rng.choice(
                [[], [{"message": "Daily max reached today."}], [{"message": "Three days in a row: rest tomorrow."}]]
            ),
            "fatigue_watch": rng.choice([None, {"message": "Mechanics drift: check in."}]),
        }
    data = session(discipline, level or "hs_varsity", series, **extra)
    if level is None:
        data.pop("level")
    return data, overrides


def test_random_sessions_never_break_the_rule_based_baseline():
    rng = random.Random(20261010)
    failures, with_problem, judged = [], 0, 0
    for i in range(3000):
        data, overrides = random_session(rng)
        found, coach_input = violations(data, overrides)
        with_problem += bool(coach_input.problems)
        judged += coach_input.has_anything_to_judge
        if found:
            failures.append((i, found[:2]))
    assert not failures, f"{len(failures)} of 3000 random sessions broke the guardrails, e.g. {failures[:3]}"
    assert with_problem > 200 and judged > 1000, "the sweep must exercise supported problems and judged notes"