File size: 5,569 Bytes
267266e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import math
from dataclasses import dataclass
from typing import Any

from app.services.live_pipeline import LivePipeline
from app.services.model_service import ModelService
from app.services.prediction_service import PredictionService
from testing_pipeline.fastf1_replay import ReplayResult


@dataclass(frozen=True, slots=True)
class Check:
    status: str
    label: str
    detail: str


def build_checks(

    result: ReplayResult,

    pipeline: LivePipeline,

    predictions: PredictionService,

    model: ModelService,

    leaderboard: list[dict[str, Any]],

) -> list[Check]:
    counters = pipeline.status()["counters"]
    probabilities = [row.get("raw_probability") for row in leaderboard]
    valid_probabilities = bool(probabilities) and all(
        isinstance(value, (int, float)) and math.isfinite(value) and 0 <= value <= 1
        for value in probabilities
    )
    avg_feature_coverage = (
        sum(float(row.get("feature_coverage", 0)) for row in leaderboard)
        / len(leaderboard)
        if leaderboard
        else 0.0
    )
    predicted = leaderboard[0]["driver"] if leaderboard else None

    return [
        Check("PASS", "FastF1 session", f"{result.year} {result.event_name}"),
        _boolean_check(
            result.drivers_loaded > 0,
            "Driver registry input",
            f"{result.drivers_loaded} drivers loaded",
        ),
        _boolean_check(
            result.telemetry_samples > 0,
            "Telemetry replay",
            f"{result.telemetry_samples:,} samples across {result.laps_replayed} laps",
        ),
        _boolean_check(
            model.loaded and model.metadata.feature_count == 39,
            "Model contract",
            f"{model.metadata.feature_count if model.loaded else 0}/39 features",
        ),
        _boolean_check(
            counters.get("record_errors", 0) == 0,
            "Pipeline processing",
            f"{counters.get('record_errors', 0)} record errors",
        ),
        _boolean_check(
            counters.get("predictions", 0) > 0,
            "Predictions generated",
            str(counters.get("predictions", 0)),
        ),
        _boolean_check(
            valid_probabilities,
            "Probability sanity",
            f"{len(probabilities)} finite values in [0, 1]",
        ),
        Check(
            "PASS" if avg_feature_coverage >= 0.75 else "WARN",
            "Average feature coverage",
            f"{avg_feature_coverage:.1%}",
        ),
        Check(
            "PASS" if not result.skipped_laps else "WARN",
            "Skipped FastF1 laps",
            str(len(result.skipped_laps)),
        ),
        Check(
            "PASS" if predicted and predicted == result.actual_winner else "WARN",
            "Historical winner comparison",
            f"predicted={predicted or '-'}, actual={result.actual_winner or '-'}",
        ),
    ]


def print_report(

    result: ReplayResult,

    pipeline: LivePipeline,

    predictions: PredictionService,

    model: ModelService,

    leaderboard: list[dict[str, Any]],

) -> bool:
    checks = build_checks(result, pipeline, predictions, model, leaderboard)
    width = 72
    print("\n" + "=" * width)
    print("F1 BACKEND END-TO-END HISTORICAL REPLAY")
    print("=" * width)
    print(f"Race       : {result.year} {result.event_name}")
    print(f"Session    : {result.session_name}")
    print(f"Race laps  : {result.total_laps}")
    print(f"Model mode : local saved production artifact")

    print("\nCHECKS")
    for check in checks:
        print(f"[{check.status:<4}] {check.label:<30} {check.detail}")

    print("\nFINAL LEADERBOARD")
    if not leaderboard:
        print("No predictions were generated.")
    for row in leaderboard[:10]:
        print(
            f"{int(row['rank']):>2}. {str(row['driver']):<4} "
            f"normalized={float(row['normalized_probability']):>7.2%}  "
            f"raw={float(row['raw_probability']):.6f}  "
            f"lap={int(row['lap_number']):>2}  "
            f"coverage={float(row['feature_coverage']):.1%}"
        )

    if result.prediction_checkpoints:
        print("\nPREDICTION CHECKPOINTS")
        for lap_number, rows in sorted(result.prediction_checkpoints.items()):
            summary = ", ".join(
                f"{row['driver']} {float(row['normalized_probability']):.1%}"
                for row in rows
            ) or "waiting for predictions"
            print(f"Lap {lap_number:>2}: {summary}")

    print("\nRAW FIELD COVERAGE (lowest 10)")
    for name, coverage in sorted(result.raw_coverage().items(), key=lambda item: item[1])[:10]:
        print(f"{name:<32} {coverage:>7.1%}")

    if result.skipped_laps:
        print("\nSKIPPED LAP EXAMPLES")
        for detail in result.skipped_laps[:8]:
            print(f"- {detail}")

    has_failures = any(check.status == "FAIL" for check in checks)
    has_warnings = any(check.status == "WARN" for check in checks)
    overall = "FAIL" if has_failures else "PASS WITH WARNINGS" if has_warnings else "PASS"
    print("\n" + "-" * width)
    print(f"OVERALL RESULT: {overall}")
    print("Note: winner mismatch is a model-quality warning, not a pipeline failure.")
    print("=" * width)
    return not has_failures


def _boolean_check(condition: bool, label: str, detail: str) -> Check:
    return Check("PASS" if condition else "FAIL", label, detail)