from __future__ import annotations import argparse import asyncio import sys import traceback from typing import Any from app.api.routes_live import build_frontend_snapshot, get_live_runtime from app.services.inference_gateway import get_inference_gateway def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description=( "Observe the existing LiveF1 provider and unchanged production pipeline, " "then print a human-readable backend health report." ) ) parser.add_argument( "--duration", type=int, default=120, help="Seconds to observe the live feed; default 120", ) parser.add_argument( "--interval", type=int, default=5, help="Seconds between progress lines; default 5", ) parser.add_argument("--traceback", action="store_true") return parser def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) if args.duration < 1 or args.interval < 1: print("ERROR: --duration and --interval must be at least 1", file=sys.stderr) return 2 try: return asyncio.run(_run(args.duration, args.interval)) except KeyboardInterrupt: print("\nLive probe cancelled by user.") return 130 except Exception as exc: print("\n" + "=" * 72, file=sys.stderr) print("LIVE BACKEND PROBE FAILED", file=sys.stderr) print(f"{type(exc).__name__}: {exc}", file=sys.stderr) if args.traceback: traceback.print_exc() else: print("Re-run with --traceback for technical details.", file=sys.stderr) print("=" * 72, file=sys.stderr) return 1 async def _run(duration: int, interval: int) -> int: runtime = get_live_runtime() await runtime.pipeline.reset() await get_inference_gateway().startup() print("=" * 72) print("F1 LIVE BACKEND PROBE") print("=" * 72) print(f"Observation window: {duration} seconds") print("Starting the existing LiveF1 provider; production code is unchanged.") await runtime.provider.start() snapshot: dict[str, Any] = {} elapsed = 0 try: while elapsed < duration: wait_for = min(interval, duration - elapsed) await asyncio.sleep(wait_for) elapsed += wait_for snapshot = await build_frontend_snapshot() pipeline = snapshot["pipeline"] counters = pipeline.get("counters", {}) received = sum( int(value) for key, value in counters.items() if str(key).startswith("topic:") ) print( f"[{elapsed:>4}/{duration}s] " f"feed={snapshot['status']:<25} " f"records={received:<7} " f"drivers={pipeline.get('drivers_registered', 0):<3} " f"predictions={counters.get('predictions', 0)}" ) finally: await runtime.provider.stop() await runtime.pipeline.shutdown() if not snapshot: snapshot = await build_frontend_snapshot() return _print_report(snapshot) def _print_report(snapshot: dict[str, Any]) -> int: provider = snapshot.get("provider", {}) pipeline = snapshot.get("pipeline", {}) counters = pipeline.get("counters", {}) prediction = snapshot.get("prediction", {}) race = snapshot.get("race", {}) received = sum( int(value) for key, value in counters.items() if str(key).startswith("topic:") ) checks = [ ( "FAIL" if provider.get("parse_errors", 0) else "PASS", "LiveF1 parser errors", str(provider.get("parse_errors", 0)), ), ( "WARN" if provider.get("is_stale", True) else "PASS", "Feed freshness", str(provider.get("data_age_seconds")), ), ( "FAIL" if prediction.get("prediction_errors", 0) else "PASS", "Prediction errors", str(prediction.get("prediction_errors", 0)), ), ( "WARN" if prediction.get("skipped_predictions", 0) else "PASS", "Skipped predictions", str(prediction.get("skipped_predictions", 0)), ), ( "PASS" if not provider.get("last_error") else "FAIL", "Provider connection", provider.get("last_error") or "no provider error", ), ( "PASS" if received > 0 else "FAIL", "Live records received", str(received), ), ( "PASS" if counters.get("record_errors", 0) == 0 else "FAIL", "Pipeline record errors", str(counters.get("record_errors", 0)), ), ( "PASS" if pipeline.get("drivers_registered", 0) > 0 else "FAIL", "Drivers registered", str(pipeline.get("drivers_registered", 0)), ), ( "PASS" if race.get("driver_count", 0) > 0 else "FAIL", "Frontend race state", f"{race.get('driver_count', 0)} drivers", ), ( "PASS" if counters.get("predictions", 0) > 0 else "WARN", "Model predictions", str(counters.get("predictions", 0)), ), ] print("\n" + "=" * 72) print("LIVE PROBE RESULT") print("=" * 72) for status, label, detail in checks: print(f"[{status:<4}] {label:<28} {detail}") leaderboard = prediction.get("leaderboard", []) if leaderboard: print("\nCURRENT PREDICTION LEADERBOARD") for row in leaderboard[:10]: print( f"{int(row['rank']):>2}. {row['driver']:<4} " f"probability={float(row['normalized_probability']):>7.2%} " f"lap={int(row['lap_number'])}" ) failed = any(status == "FAIL" for status, _, _ in checks) warned = any(status == "WARN" for status, _, _ in checks) overall = "FAIL" if failed else "PASS WITH WARNINGS" if warned else "PASS" print("\n" + "-" * 72) print(f"OVERALL RESULT: {overall}") if counters.get("predictions", 0) == 0: print( "No prediction can be expected when no race is live or no driver has " "completed a lap during the observation window." ) print("=" * 72) return 1 if failed else 0