File size: 5,547 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
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()