Interact-ai's picture
Upload folder using huggingface_hub
267266e verified
Raw History Blame Contribute Delete
5.57 kB
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)