import pytest from ai_coach.chain import GenerationError from ai_coach.config import Settings from ai_coach.fallback import build_fallback_note from ai_coach.input_builder import build_coach_input from ai_coach.schemas import CaptureInput, CoachNote, DrillNote, Usage from ai_coach.service import CoachService, render_note from .helpers import FakeGenerator, example_note, good_note, load_example, make_input, measurements BAD = good_note(headline="Your swing is good but terrible too.") # banned words def service(keyed_settings, script, **settings_overrides): settings = keyed_settings.model_copy(update=settings_overrides) gen = FakeGenerator(script) return CoachService(settings, generator=gen), gen def test_good_note_is_returned_and_cached(keyed_settings): svc, gen = service(keyed_settings, [good_note()]) first = svc.coach_from_input(make_input()) assert (first.source, first.model, first.attempts, first.cache_hit) == ("llm", "gemini-3.1-flash-lite", 1, False) assert first.usage.cost_usd > 0 and first.note == good_note() second = svc.coach_from_input(make_input()) assert second.cache_hit and second.attempts == 0 and second.usage.cost_usd == 0 assert len(gen.calls) == 1 # the second request never reached the model def test_session_json_sent_to_the_model_is_compact_and_free_of_media(keyed_settings): svc, gen = service(keyed_settings, [example_note("hitting_overstride_240fps")]) svc.coach(load_example("hitting_overstride_240fps")) sent = gen.calls[0]["session_json"] assert len(sent) < 4000 and "keypoint" not in sent and "video" not in sent and "player_id" not in sent def test_guardrail_failure_triggers_one_repair_on_the_same_model(keyed_settings): svc, gen = service(keyed_settings, [BAD, good_note()]) result = svc.coach_from_input(make_input()) assert result.source == "llm" and result.attempts == 2 assert [c["model"] for c in gen.calls] == ["gemini-3.1-flash-lite"] * 2 assert gen.calls[0]["repair_hint"] is None and "banned_word" in gen.calls[1]["repair_hint"] assert any("banned_word" in v for v in result.violations) def test_second_failure_escalates_to_the_stronger_model(keyed_settings): svc, gen = service(keyed_settings, [BAD, BAD, good_note()]) result = svc.coach_from_input(make_input()) assert [c["model"] for c in gen.calls] == ["gemini-3.1-flash-lite", "gemini-3.1-flash-lite", "gemini-3.8-flash"] assert result.model == "gemini-3.8-flash" and result.attempts == 3 again = svc.coach_from_input(make_input()) # the escalated answer is cached under the primary model key assert again.cache_hit and len(gen.calls) == 3 def test_everything_failing_falls_back_to_rules(keyed_settings): svc, _gen = service(keyed_settings, [BAD, BAD, BAD]) result = svc.coach_from_input(make_input()) assert result.source == "rules" and result.fallback_reason == "guardrails_failed" and result.attempts == 3 assert result.note.work_on[0].fault_key == "over_stride" and result.usage.cost_usd > 0 # failed calls still cost def test_fallback_notes_are_never_cached_as_successes(keyed_settings): svc, _gen = service(keyed_settings, [BAD, BAD, BAD, good_note()], failure_cache_ttl_s=0) assert svc.coach_from_input(make_input()).source == "rules" assert svc.coach_from_input(make_input()).source == "llm" # with the failure memory off the model is retried def test_fatal_errors_stop_immediately(keyed_settings): svc, gen = service(keyed_settings, [GenerationError("UNAUTHENTICATED", fatal=True)]) result = svc.coach_from_input(make_input()) assert result.source == "rules" and result.fallback_reason == "llm_unavailable" and len(gen.calls) == 1 def test_transport_errors_skip_the_same_model_and_go_to_escalation(keyed_settings): svc, gen = service(keyed_settings, [GenerationError("503"), good_note()]) result = svc.coach_from_input(make_input()) assert [c["model"] for c in gen.calls] == ["gemini-3.1-flash-lite", "gemini-3.8-flash"] assert result.source == "llm" and result.model == "gemini-3.8-flash" and result.attempts == 2 assert any(v.startswith("generation_error[transport]") for v in result.violations) def test_transport_errors_everywhere_fall_back_without_hammering_the_api(keyed_settings): svc, gen = service(keyed_settings, [GenerationError("429"), GenerationError("429")]) result = svc.coach_from_input(make_input()) assert len(gen.calls) == 2 # one per model, never the old six assert result.source == "rules" and result.fallback_reason == "llm_error" def test_unparsable_output_is_billed_recorded_and_repaired_on_the_same_model(keyed_settings): broken = GenerationError( "unparsable output: bad json", kind="unparsable", usage=Usage(input_tokens=2000, output_tokens=700), latency_ms=900, ) svc, gen = service(keyed_settings, [broken, good_note()]) result = svc.coach_from_input(make_input()) assert [c["model"] for c in gen.calls] == ["gemini-3.1-flash-lite"] * 2 and result.source == "llm" assert result.usage.input_tokens == 3000 and result.usage.cost_usd > 0 # the failed call is counted summary = svc.ledger.summary(1) assert summary["model_calls"] == 2 and summary["call_outcomes"] == {"ok": 1, "unparsable_error": 1} def test_every_billed_call_and_every_request_reaches_the_ledger(keyed_settings): svc, _ = service(keyed_settings, [BAD, good_note()]) result = svc.coach_from_input(make_input()) svc.coach_from_input(make_input()) # cache hit summary = svc.ledger.summary(1) assert summary["model_calls"] == 2 and summary["requests"] == 2 and summary["cache_hits"] == 1 assert summary["call_outcomes"] == {"guardrail_failed": 1, "ok": 1} assert summary["cost_usd"] == pytest.approx(result.usage.cost_usd) assert result.request_id and result.latency_ms is not None def test_request_id_reaches_the_model_call_for_trace_correlation(keyed_settings): svc, gen = service(keyed_settings, [good_note()]) result = svc.coach_from_input(make_input()) meta = gen.calls[0]["run_metadata"] assert meta["request_id"] == result.request_id and meta["attempt"] == 1 and meta["discipline"] == "hitting" def test_a_corrupt_cache_row_is_regenerated_not_fatal(keyed_settings): import sqlite3 svc, gen = service(keyed_settings, [good_note(), good_note()]) svc.coach_from_input(make_input()) with sqlite3.connect(keyed_settings.cache_path) as db: db.execute("UPDATE notes SET note = '{broken'") result = svc.coach_from_input(make_input()) assert result.source == "llm" and not result.cache_hit and len(gen.calls) == 2 def test_a_cached_note_that_fails_todays_guardrails_is_rejected(keyed_settings): from ai_coach.cache import cache_key from ai_coach.guardrails import GUARDRAILS_VERSION from ai_coach.input_builder import canonical_json svc, gen = service(keyed_settings, [good_note()]) coach_input = make_input() key = cache_key(f"{svc.prompts.version}+g{GUARDRAILS_VERSION}", keyed_settings.model, canonical_json(coach_input)) svc.cache.put(key, BAD) # a note that passed some older, weaker rules result = svc.coach_from_input(coach_input) assert not result.cache_hit and result.note == good_note() and len(gen.calls) == 1 def test_concurrent_identical_requests_make_one_model_call(keyed_settings): import threading import time gate = threading.Event() class SlowGenerator(FakeGenerator): def generate(self, *args, **kwargs): gate.wait(2) time.sleep(0.05) return super().generate(*args, **kwargs) gen = SlowGenerator([good_note()]) svc = CoachService(keyed_settings, generator=gen) results = [] threads = [threading.Thread(target=lambda: results.append(svc.coach_from_input(make_input()))) for _ in range(6)] for t in threads: t.start() gate.set() for t in threads: t.join(5) assert len(results) == 6 and len(gen.calls) == 1 assert sorted(r.cache_hit for r in results) == [False] + [True] * 5 assert svc._flights == {} # no leaked locks def test_disabling_the_cache_means_no_reads_and_no_writes(keyed_settings): import sqlite3 svc, gen = service(keyed_settings, [good_note(), good_note()], cache_enabled=False) svc.coach_from_input(make_input()) svc.coach_from_input(make_input()) assert len(gen.calls) == 2 with sqlite3.connect(keyed_settings.cache_path) as db: assert db.execute("SELECT COUNT(*) FROM notes").fetchone()[0] == 0 def test_an_unknown_model_cannot_bypass_the_daily_budget(keyed_settings): settings = keyed_settings.model_copy( update={"model": "brand-new-model", "escalation_model": None, "daily_budget_usd": 0.001, "cache_enabled": False} ) svc, gen = service(settings, [good_note(), good_note()]) first = svc.coach_from_input(make_input()) assert first.usage.cost_usd > 0.001 # priced at the most expensive known model, not at zero second = svc.coach_from_input(make_input()) assert second.fallback_reason == "daily_budget_exceeded" and len(gen.calls) == 1 def test_a_broken_ledger_and_cache_never_break_coaching(keyed_settings, tmp_path): blocker = tmp_path / "file" blocker.write_text("x") settings = keyed_settings.model_copy(update={"cache_path": blocker / "c.sqlite3"}) svc, _ = service(settings, [good_note()]) result = svc.coach_from_input(make_input()) assert result.source == "llm" and result.request_id def test_budget_exhaustion_skips_the_model(keyed_settings): svc, gen = service(keyed_settings, [good_note()], daily_budget_usd=0.0) result = svc.coach_from_input(make_input()) assert result.source == "rules" and result.fallback_reason == "daily_budget_exceeded" and not gen.calls def test_spend_is_recorded_in_the_ledger(keyed_settings): svc, _ = service(keyed_settings, [good_note()]) svc.coach_from_input(make_input()) assert svc.ledger.spent_today() == pytest.approx(1000 * 0.25 / 1e6 + 300 * 1.5 / 1e6, rel=1e-3) def test_nothing_to_judge_never_calls_the_model(keyed_settings): svc, gen = service(keyed_settings, [good_note()]) failed = make_input(capture=CaptureInput(ok=False, reasons=["partly_out_of_frame"])) result = svc.coach_from_input(failed) assert result.source == "rules" and result.fallback_reason == "nothing_to_judge" and not gen.calls empty = make_input(metrics=[], problems=[]) assert svc.coach_from_input(empty).fallback_reason == "nothing_to_judge" and not gen.calls def test_without_a_key_the_service_uses_rules_only(settings): result = CoachService(settings).coach_from_input(make_input()) assert result.source == "rules" and result.fallback_reason == "llm_disabled" and result.usage.cost_usd == 0 def test_no_escalation_when_disabled_or_identical(keyed_settings): svc, gen = service(keyed_settings, [BAD, BAD], escalation_model=None, failure_cache_ttl_s=0) assert svc.coach_from_input(make_input()).attempts == 2 and len(gen.calls) == 2 svc2, gen2 = service(keyed_settings, [BAD, BAD], escalation_model="gemini-3.1-flash-lite", failure_cache_ttl_s=0) svc2.coach_from_input(make_input()) assert len(gen2.calls) == 2 def test_prompt_version_is_recorded_and_part_of_the_cache_key(keyed_settings): svc, _ = service(keyed_settings, [good_note(), good_note()]) result = svc.coach_from_input(make_input()) assert result.prompt_version.startswith("coach-v1-") svc.prompts = type(svc.prompts)(svc.prompts.system_text + "x", svc.prompts.user_template, "coach-v1-changed") assert not svc.coach_from_input(make_input()).cache_hit async def test_async_path_matches_sync(keyed_settings): svc, _ = service(keyed_settings, [example_note("hitting_overstride_240fps")]) result = await svc.acoach(load_example("hitting_overstride_240fps")) assert result.source == "llm" def test_every_real_example_yields_a_valid_note_even_when_the_model_misbehaves(settings): for name in ("hitting_ok_240fps", "pitching_short_stride_240fps", "real_hitting_30fps_low_confidence"): result = CoachService(settings).coach(load_example(name)) assert isinstance(result.note, CoachNote) and result.note.headline def test_render_note_is_readable_text(): text = render_note(good_note()) assert "What looks solid" in text and "What to work on" in text and "Drill:" in text and "Keep in mind" in text def test_settings_defaults_match_the_researched_models(): s = Settings(_env_file=None, google_api_key=None) assert s.model == "gemini-3.8-flash" and s.escalation_model == "gemini-3.8-flash" assert s.model in s.prices and s.escalation_model in s.prices and not s.llm_enabled # ----------------------------------------------------------------------------- the agent judges, the baseline is a yardstick def two_problem_input(): from .helpers import second_problem return make_input(problems=[make_input().problems[0], second_problem()]) def head_first_note(): from ai_coach.schemas import DrillNote, WorkOnItem return good_note( work_on=[ WorkOnItem(fault_key="head_drift", evidence=["head_movement_pct_height"], text="Your head moves in 50% of swings."), WorkOnItem(fault_key="over_stride", evidence=["stride_pct_height"], text="Your stride is long in 75% of swings."), ], looks_solid=[], cue="Keep your eyes quiet.", drill=DrillNote(name="Quiet Head Tee", how="Do 3x8 swings."), ) def test_the_model_may_choose_a_different_priority_than_the_baseline(keyed_settings): svc, gen = service(keyed_settings, [head_first_note()]) result = svc.coach_from_input(two_problem_input()) assert result.source == "llm" and result.attempts == 1 and len(gen.calls) == 1 # accepted, not rejected or repaired assert (result.chosen_problem, result.baseline_problem, result.agrees_with_baseline) == ( "head_drift", "over_stride", False, ) def test_agreement_with_the_baseline_is_recorded_everywhere(keyed_settings): svc, _ = service(keyed_settings, [good_note(), head_first_note()]) agree = svc.coach_from_input(make_input()) differ = svc.coach_from_input(two_problem_input()) assert agree.agrees_with_baseline is True and differ.agrees_with_baseline is False summary = svc.ledger.summary(1) assert summary["agreement_with_baseline"] == 0.5 def test_no_problem_means_no_agreement_metric(keyed_settings): svc, _ = service(keyed_settings, [CoachNote(headline="Your head stays quiet.")]) result = svc.coach_from_input(make_input(problems=[])) assert (result.chosen_problem, result.baseline_problem, result.agrees_with_baseline) == (None, None, None) def test_the_rule_based_fallback_follows_the_baseline(keyed_settings): svc, _ = service(keyed_settings, [BAD, BAD, BAD]) result = svc.coach_from_input(two_problem_input()) # rule-based notes follow the baseline by construction: they are not a judgement, so no agreement is recorded assert result.source == "rules" and result.note.work_on[0].fault_key == "over_stride" assert (result.chosen_problem, result.baseline_problem, result.agrees_with_baseline) == (None, None, None) def test_a_note_naming_an_unsupported_problem_is_repaired(keyed_settings): from ai_coach.schemas import WorkOnItem invented = good_note(work_on=[WorkOnItem(fault_key="lunging", evidence=["com_drift_pct_height"], text="Your body slides.")]) svc, gen = service(keyed_settings, [invented, good_note()]) result = svc.coach_from_input(make_input()) assert result.attempts == 2 and any("unknown_fault" in v for v in result.violations) assert "unknown_fault" in gen.calls[1]["repair_hint"] def test_real_measurements_flow_from_session_to_a_guardrail_clean_note(keyed_settings): session = load_example("hitting_stride_and_lunging_240fps") svc, gen = service(keyed_settings, [example_note("hitting_stride_and_lunging_240fps")]) result = svc.coach(session) assert result.source == "llm" and result.chosen_problem == "lunging" sent = gen.calls[0]["session_json"] assert '"problems"' in sent and '"faults"' not in sent and '"focus"' not in sent # ---------------------------------------------------------------------------- review fixes: failures, drills, agreement def test_an_identical_failing_request_is_remembered_and_does_not_repeat_the_whole_chain(keyed_settings): svc, gen = service(keyed_settings, [BAD, BAD, BAD, good_note()]) first = svc.coach_from_input(make_input()) again = svc.coach_from_input(make_input()) assert first.fallback_reason == "guardrails_failed" and len(gen.calls) == 3 assert again.source == "rules" and again.fallback_reason == "cached_failure:guardrails_failed" and len(gen.calls) == 3 assert again.usage.cost_usd == 0 and again.attempts == 0 and again.note == first.note other = svc.coach_from_input(make_input(reps_analyzed=7)) # a different request is not affected assert other.source == "llm" and len(gen.calls) == 4 def test_the_failure_memory_expires_and_can_be_switched_off(keyed_settings, tmp_path): import time as _time svc, gen = service(keyed_settings, [BAD, BAD, BAD, good_note()], failure_cache_ttl_s=0.05) svc.coach_from_input(make_input()) _time.sleep(0.1) assert svc.coach_from_input(make_input()).source == "llm" and len(gen.calls) == 4 off, gen_off = service(keyed_settings, [BAD] * 6, failure_cache_ttl_s=0, cache_path=tmp_path / "other" / "cache.sqlite3") off.coach_from_input(make_input()) off.coach_from_input(make_input()) assert len(gen_off.calls) == 6 def test_budget_exhaustion_is_not_remembered_because_it_can_recover(keyed_settings): svc, gen = service(keyed_settings, [good_note()], daily_budget_usd=0.0) assert svc.coach_from_input(make_input()).fallback_reason == "daily_budget_exceeded" svc.settings = svc.settings.model_copy(update={"daily_budget_usd": 1.0}) svc.ledger.daily_budget_usd = 1.0 assert svc.coach_from_input(make_input()).source == "llm" and len(gen.calls) == 1 def test_waiters_on_a_failing_request_do_not_repeat_the_chain(keyed_settings): import threading import time class Slow(FakeGenerator): def generate(self, *args, **kwargs): time.sleep(0.05) return super().generate(*args, **kwargs) gen = Slow([BAD, BAD, BAD]) svc = CoachService(keyed_settings, generator=gen) results = [] threads = [threading.Thread(target=lambda: results.append(svc.coach_from_input(make_input()))) for _ in range(5)] for t in threads: t.start() for t in threads: t.join(10) assert len(results) == 5 and len(gen.calls) == 3 # one chain, not five assert sorted(r.fallback_reason for r in results).count("cached_failure:guardrails_failed") == 4 def test_a_drill_name_that_differs_only_in_case_or_spacing_is_rewritten_to_the_library_name(keyed_settings): loose = good_note(drill=DrillNote(name=" SHORT step tee", how="Do 3x8 swings with a quiet step.")) svc, _ = service(keyed_settings, [loose]) result = svc.coach_from_input(make_input()) assert result.source == "llm" and result.attempts == 1 and result.note.drill.name == "Short Step Tee" again = svc.coach_from_input(make_input()) assert again.cache_hit and again.note.drill.name == "Short Step Tee" # the canonical note is what gets cached def test_agreement_is_recorded_only_for_fresh_model_notes(keyed_settings): svc, _ = service(keyed_settings, [good_note()]) fresh = svc.coach_from_input(make_input()) cached = svc.coach_from_input(make_input()) assert fresh.agrees_with_baseline is True assert (cached.cache_hit, cached.chosen_problem, cached.baseline_problem, cached.agrees_with_baseline) == ( True, None, None, None, ) rules = CoachService(keyed_settings.model_copy(update={"google_api_key": None})).coach_from_input(make_input()) assert rules.source == "rules" and rules.agrees_with_baseline is None def test_a_failed_capture_has_no_baseline_and_no_agreement(keyed_settings): session = measurements( series={"stride_pct_height": ("%", "high", [60.0] * 6)}, capture={"ok": False, "reasons": ["too_dark"]} ) svc, gen = service(keyed_settings, []) result = svc.coach(session) assert not gen.calls and result.baseline_problem is None and result.agrees_with_baseline is None assert svc.ledger.summary(1)["agreement_with_baseline"] is None def test_the_arm_care_date_and_facts_reach_the_model_input(keyed_settings): import json arm = {"known": True, "pitch_count_today": 40, "daily_max": 95, "next_eligible_date": "2026-10-13", "alerts": []} session = measurements("pitching", series={"stride_pct_height": ("%", "high", [70.0] * 6)}, arm_care=arm) svc, gen = service(keyed_settings, []) svc.settings = keyed_settings note = example_note_for(session) svc, gen = service(keyed_settings, [note]) result = svc.coach(session) sent = json.loads(gen.calls[0]["session_json"]) assert sent["arm_care"]["next_eligible_date"] == "2026-10-13" and sent["arm_care"]["daily_max"] == 95 assert result.source == "llm" and "[removed]" not in gen.calls[0]["session_json"] def example_note_for(session): return build_fallback_note(build_coach_input(session)) def test_malformed_measurements_raise_only_input_error_through_the_service(keyed_settings): from ai_coach.input_builder import InputError svc, gen = service(keyed_settings, [good_note()]) for bad in ({"discipline": "hitting", "reps": [None], "capture": {"ok": True}}, {"discipline": "golf", "reps": []}, None): with pytest.raises(InputError): svc.coach(bad) assert not gen.calls