import logging import math import time from datetime import date, datetime, timezone from typing import Any, Iterable, Mapping from app.services.raw_schema import LAST_COLUMNS, MAX_COLUMNS, MEAN_COLUMNS, SUM_COLUMNS logger = logging.getLogger(__name__) class LapCompressionError(ValueError): pass class LiveLapCompressor: """Apply high-performance single-pass aggregations to one completed lap.""" def compress(self, samples: Iterable[Mapping[str, Any]]) -> dict[str, Any]: start_time = time.perf_counter() rows = [dict(sample) for sample in samples] if not rows: raise LapCompressionError("Cannot compress an empty lap") # Reverse pass for LAST_COLUMNS (breaks early once all columns found) remaining_last = set(LAST_COLUMNS) last_values: dict[str, Any] = {col: None for col in LAST_COLUMNS} driver = None lap_number = None race_date_val = None for row in reversed(rows): if driver is None: driver_candidate = row.get("Driver") if driver_candidate is not None: driver = driver_candidate if lap_number is None: lap_candidate = row.get("LapNumber") if lap_candidate is not None: lap_number = lap_candidate if race_date_val is None: date_candidate = row.get("Date") if date_candidate is not None: race_date_val = date_candidate if remaining_last: found = [] for col in remaining_last: val = row.get(col) if val is not None: last_values[col] = val found.append(col) for col in found: remaining_last.remove(col) if driver is not None and lap_number is not None and not remaining_last and race_date_val is not None: break if driver is None or lap_number is None: raise LapCompressionError("Driver and LapNumber are required") result: dict[str, Any] = { "_RaceDate": self._format_date(race_date_val), "Driver": str(driver).strip().upper(), "LapNumber": float(lap_number), "TelemetryRecords": len(rows), } # Single forward pass for MEAN, SUM, and MAX columns mean_sums = {col: 0.0 for col in MEAN_COLUMNS} mean_counts = {col: 0 for col in MEAN_COLUMNS} sum_totals = {col: 0.0 for col in SUM_COLUMNS} sum_has_val = {col: False for col in SUM_COLUMNS} max_values = {col: -float("inf") for col in MAX_COLUMNS} max_has_val = {col: False for col in MAX_COLUMNS} for row in rows: # Mean columns for col in MEAN_COLUMNS: val = row.get(col) if val is not None: try: num = float(val) if math.isfinite(num): mean_sums[col] += num mean_counts[col] += 1 except (TypeError, ValueError): pass # Sum columns for col in SUM_COLUMNS: val = row.get(col) if val is not None: try: num = float(val) if math.isfinite(num): sum_totals[col] += num sum_has_val[col] = True except (TypeError, ValueError): pass # Max columns for col in MAX_COLUMNS: val = row.get(col) if val is not None: try: num = float(val) if math.isfinite(num): if num > max_values[col]: max_values[col] = num max_has_val[col] = True except (TypeError, ValueError): pass # Populate final values for col in MEAN_COLUMNS: count = mean_counts[col] result[f"{col}_Mean"] = float(mean_sums[col] / count) if count > 0 else None for col in SUM_COLUMNS: result[f"{col}_Sum"] = float(sum_totals[col]) if sum_has_val[col] else None for col in LAST_COLUMNS: result[f"{col}_Last"] = last_values[col] for col in MAX_COLUMNS: result[f"{col}_Any"] = float(max_values[col]) if max_has_val[col] else None elapsed = time.perf_counter() - start_time if elapsed > 0.5: logger.warning( "[PERF LATENCY WARNING] LiveLapCompressor took %.3fs (> 0.5s threshold) for driver %s lap %s (%d samples)", elapsed, result["Driver"], result["LapNumber"], len(rows), ) return result @staticmethod def _format_date(value: Any) -> str: if isinstance(value, datetime): return value.date().isoformat() if isinstance(value, date): return value.isoformat() if isinstance(value, str) and len(value) >= 10: return value[:10] return datetime.now(timezone.utc).date().isoformat()