File size: 4,793 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
import json
import logging

import pytest

from ai_coach.config import Settings
from ai_coach.observability import JsonFormatter, configure_logging, log_event, redact
from ai_coach.service import CoachService

from .helpers import FakeGenerator, good_note, make_input


@pytest.fixture(autouse=True)
def clean_logger():
    yield
    logger = logging.getLogger("ai_coach")
    for handler in list(logger.handlers):
        logger.removeHandler(handler)
        handler.close()
    logger.propagate = True


def lines(settings):
    path = settings.log_dir / "coach.jsonl"
    return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []


def logged_settings(tmp_path, **kw):
    options = {"log_dir": tmp_path / "logs", "cache_path": tmp_path / "c.sqlite3", **kw}
    return Settings(_env_file=None, google_api_key="g-secret-key-1", **options)


def test_json_lines_have_the_expected_shape(tmp_path):
    settings = logged_settings(tmp_path)
    configure_logging(settings)
    log_event("llm_call", request_id="r1", model="m", cost_usd=0.001, input_tokens=10)
    (entry,) = lines(settings)
    assert entry["event"] == "llm_call" and entry["request_id"] == "r1" and entry["cost_usd"] == 0.001
    assert entry["level"] == "INFO" and entry["logger"] == "ai_coach.events" and entry["ts"].endswith("+00:00")


def test_nothing_is_written_until_logging_is_configured(tmp_path):
    settings = logged_settings(tmp_path)
    log_event("llm_call", request_id="r1")
    assert lines(settings) == []


def test_configure_logging_is_idempotent(tmp_path):
    settings = logged_settings(tmp_path)
    configure_logging(settings)
    configure_logging(settings)
    logger = logging.getLogger("ai_coach")
    assert len([h for h in logger.handlers if getattr(h, "_ai_coach_handler", False)]) == 1
    log_event("once")
    assert len(lines(settings)) == 1


def test_secrets_and_key_shaped_strings_are_redacted(tmp_path):
    settings = logged_settings(tmp_path)
    configure_logging(settings)
    log_event("oops", detail="failed with g-secret-key-1", other="AIzaSyA1234567890abcdefghijklmnopqrstuv")
    text = (settings.log_dir / "coach.jsonl").read_text()
    assert "g-secret-key-1" not in text and "AIza" not in text and "***" in text
    assert redact("lsv2_pt_abcdefghijklmnop1234 and AIzaSyA1234567890abcdefghijklmnopqrstuv") == "*** and ***"


def test_an_unwritable_log_directory_never_stops_the_app(tmp_path):
    blocker = tmp_path / "file"
    blocker.write_text("x")
    configure_logging(logged_settings(tmp_path, log_dir=blocker / "logs"))
    log_event("still fine")


def test_service_logs_calls_and_requests_without_any_content(tmp_path):
    settings = logged_settings(tmp_path)
    configure_logging(settings)
    svc = CoachService(settings, generator=FakeGenerator([good_note()]))
    result = svc.coach_from_input(make_input())
    svc.coach_from_input(make_input())  # cache hit
    entries = lines(settings)
    calls = [e for e in entries if e["event"] == "llm_call"]
    notes = [e for e in entries if e["event"] == "coach_note"]
    assert len(calls) == 1 and len(notes) == 2
    assert calls[0]["request_id"] == result.request_id and calls[0]["outcome"] == "ok"
    assert calls[0]["input_tokens"] == 1000 and calls[0]["cost_usd"] > 0
    assert notes[0]["source"] == "llm" and notes[1]["cache_hit"] is True and notes[1]["cost_usd"] == 0
    raw = (settings.log_dir / "coach.jsonl").read_text()
    for secret_text in (good_note().headline, "Short Step Tee", "Your front foot lands", "stride_pct_height"):
        assert secret_text not in raw  # no note text, no session content


def test_formatter_serialises_unusual_values():
    record = logging.LogRecord("n", logging.INFO, "f", 1, "evt", (), None)
    record.fields = {"path": __import__("pathlib").Path("/tmp/x"), "n": 1}
    out = json.loads(JsonFormatter().format(record))
    assert out["event"] == "evt" and out["path"] == "/tmp/x" and out["n"] == 1


def test_fields_can_never_overwrite_the_log_envelope(tmp_path):
    settings = logged_settings(tmp_path)
    configure_logging(settings)
    log_event("evt", level="hs_varsity", ts="yesterday", event="spoof")
    (entry,) = lines(settings)
    assert entry["level"] == "INFO" and entry["event"] == "evt" and entry["ts"] != "yesterday"
    assert entry["field_level"] == "hs_varsity" and entry["field_event"] == "spoof"


def test_the_request_event_records_the_player_level_under_its_own_name(tmp_path):
    settings = logged_settings(tmp_path)
    configure_logging(settings)
    CoachService(settings, generator=FakeGenerator([good_note()])).coach_from_input(make_input())
    note = next(e for e in lines(settings) if e["event"] == "coach_note")
    assert note["level"] == "INFO" and note["player_level"] == "hs_varsity"