import contextlib from types import SimpleNamespace import langsmith import pytest from ai_coach import tracing from ai_coach.config import Settings from ai_coach.schemas import CoachResult, Usage from ai_coach.tracing import build_client, check, request_trace, violation_codes from .helpers import FakeGenerator, good_note, make_input @pytest.fixture def traced_settings(tmp_path): return Settings( _env_file=None, google_api_key="g-key", langsmith_api_key="lsv2_pt_abcdefghijklmnop1234", tracing=True, langsmith_project="ai-coach-test", environment="test", cache_path=tmp_path / "c.sqlite3", ) class FakeLangSmith: """Stands in for langsmith.tracing_context / langsmith.trace so tests never reach the network.""" def __init__(self, monkeypatch): self.contexts, self.traces, self.runs = [], [], [] monkeypatch.setattr(langsmith, "tracing_context", self._context) monkeypatch.setattr(langsmith, "trace", self._trace) monkeypatch.setattr(tracing, "build_client", lambda settings: "client-object") @contextlib.contextmanager def _context(self, **kwargs): self.contexts.append(kwargs) yield @contextlib.contextmanager def _trace(self, name, run_type, **kwargs): run = SimpleNamespace( metadata={}, outputs={}, add_metadata=lambda m: run.metadata.update(m), add_outputs=lambda o: run.outputs.update(o), ) self.traces.append({"name": name, "run_type": run_type, **kwargs}) self.runs.append(run) yield run def test_tracing_is_off_by_default_and_without_a_key(settings, monkeypatch): monkeypatch.setattr(tracing, "build_client", lambda s: pytest.fail("client must not be built")) assert not settings.tracing_enabled with request_trace(settings, make_input(), "rid", "p1") as recorder: recorder.metadata["x"] = 1 flag_only = settings.model_copy(update={"tracing": True}) assert not flag_only.tracing_enabled # the switch alone is not enough: a key is required with request_trace(flag_only, make_input(), "rid", "p1"): pass def test_enabled_trace_scopes_project_tags_and_numbers_only_inputs(traced_settings, monkeypatch): fake = FakeLangSmith(monkeypatch) with request_trace(traced_settings, make_input(), "req123", "coach-v1-abc") as recorder: recorder.record( CoachResult( note=good_note(), source="llm", model="gemini-3.1-flash-lite", prompt_version="coach-v1-abc", attempts=1, latency_ms=1200, usage=Usage(input_tokens=2000, output_tokens=300, cached_tokens=100, reasoning_tokens=40, cost_usd=0.0009), ) ) ctx, trace, run = fake.contexts[0], fake.traces[0], fake.runs[0] assert ctx["client"] == "client-object" and ctx["project_name"] == "ai-coach-test" and ctx["enabled"] is True assert {"ai-coach", "env:test", "prompt:coach-v1-abc", "hitting"} <= set(trace["tags"]) assert trace["name"] == "coach_request" and trace["metadata"]["request_id"] == "req123" sent = str(trace["inputs"]) assert "video" not in sent and "player" not in sent and "stride_pct_height" in sent assert run.metadata["cost_usd"] == 0.0009 and run.metadata["input_tokens"] == 2000 assert run.metadata["reasoning_tokens"] == 40 and run.metadata["source"] == "llm" and run.metadata["attempts"] == 1 assert run.outputs["source"] == "llm" and run.outputs["note"]["headline"] def test_disabled_flag_per_call_skips_tracing(traced_settings, monkeypatch): fake = FakeLangSmith(monkeypatch) with request_trace(traced_settings, make_input(), "rid", "p", enabled=False): pass assert fake.traces == [] def test_failures_attaching_metadata_never_break_coaching(traced_settings, monkeypatch): fake = FakeLangSmith(monkeypatch) @contextlib.contextmanager def broken_trace(name, run_type, **kwargs): def boom(_): raise RuntimeError("langsmith down") yield SimpleNamespace(add_metadata=boom, add_outputs=boom) monkeypatch.setattr(langsmith, "trace", broken_trace) with request_trace(traced_settings, make_input(), "rid", "p"): pass # must not raise assert fake.contexts def test_only_generation_requests_are_traced_unless_trace_all(traced_settings, monkeypatch): from ai_coach.service import CoachService fake = FakeLangSmith(monkeypatch) svc = CoachService(traced_settings, generator=FakeGenerator([good_note()])) svc.coach_from_input(make_input()) # generates: traced svc.coach_from_input(make_input()) # cache hit: not traced assert len(fake.traces) == 1 and fake.runs[0].metadata["cache_hit"] is False svc_all = CoachService(traced_settings.model_copy(update={"trace_all": True}), generator=FakeGenerator([])) svc_all.coach_from_input(make_input()) # cache hit, but trace_all assert len(fake.traces) == 2 and fake.runs[1].metadata["cache_hit"] is True def test_build_client_uses_explicit_settings_and_is_cached(traced_settings, monkeypatch): seen = [] class StubClient: def __init__(self, **kwargs): seen.append(kwargs) monkeypatch.setattr(langsmith, "Client", StubClient) monkeypatch.setattr(tracing, "_clients", {}) settings = traced_settings.model_copy( update={ "langsmith_endpoint": "https://eu.api.smith.langchain.com", "trace_hide_inputs": True, "trace_sample_rate": 0.5, } ) first = build_client(settings) assert build_client(settings) is first and len(seen) == 1 assert seen[0]["api_key"] == "lsv2_pt_abcdefghijklmnop1234" and seen[0]["api_url"].startswith("https://eu.") assert seen[0]["hide_inputs"] is True and seen[0]["hide_outputs"] is False assert seen[0]["tracing_sampling_rate"] == 0.5 def test_secrets_never_appear_in_repr_or_dumps(traced_settings): text = repr(traced_settings) + str(traced_settings.model_dump()) assert "lsv2_pt_abcdefghijklmnop1234" not in text and "g-key" not in text assert set(traced_settings.secrets) == {"g-key", "lsv2_pt_abcdefghijklmnop1234"} def test_violation_codes_are_extracted_in_order_without_duplicates(): codes = violation_codes( [ "gemini-3.1-flash-lite: banned_word: 'good' in headline", "gemini-3.1-flash-lite: invented_number: 14 in headline is not in the input", "gemini-3.8-flash: banned_word: 'bad' in cue", "generation_error[transport]: 503", ] ) assert codes == ["banned_word", "invented_number", "generation_error"] def test_check_command_requires_tracing_to_be_configured(settings, capsys): assert check(settings) == 2 assert "COACH_TRACING" in capsys.readouterr().err