From 87ea9ecbc820dd79b4713b42d37cc80c5e0cfe31 Mon Sep 17 00:00:00 2001 From: Jon Lazarowicz Date: Wed, 4 Nov 2026 11:55:15 -0500 Subject: [PATCH 1/2] feat: remove car telemetry client surface (API removed in racehooks#5025) Drops TelemetryNamespace / client.telemetry, data.get_race_summary and data.get_race_telemetry_{laps,stints,aggression}, RaceSummaryEvent and its type-discriminator dispatch. Removal is breaking for callers of those methods; on 0.x this should be a minor bump. --- AGENTS.md | 6 ++-- CHANGELOG.md | 11 ++++++ README.md | 7 ++-- racehooks/__init__.py | 2 -- racehooks/client.py | 3 -- racehooks/models/__init__.py | 2 -- racehooks/models/events.py | 34 +----------------- racehooks/namespaces.py | 70 ++---------------------------------- tests/test_models.py | 20 ----------- tests/test_surface.py | 6 ---- 10 files changed, 19 insertions(+), 142 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3c74255..bdf0911 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ this package is the idiomatic answer. Data covers Formula 1 and other series. RaceHooks provides **predictive models and analytics for motorsport — race intelligence delivered to your endpoint.** You subscribe to feeds; RaceHooks **pushes signed JSON to your webhook URL** (no polling), or you can read an SSE stream. A REST API serves post-race model -outputs, telemetry analytics, and historical results from 1950 to present. This SDK gives you a +outputs and historical results from 1950 to present. This SDK gives you a typed REST client, HMAC webhook verification, Pydantic event models, and an optional gRPC streaming client. @@ -83,7 +83,7 @@ rh.webhooks.deliveries(); rh.webhooks.rotate_secret(webhook_id); rh.webhooks.del # Model outputs, data and history (decoded JSON `data`; plan-gated by the API) rh.insights.get_race("2026-bahrain-r1"); rh.models.manifest(); rh.lines.get(race_id) -rh.data.get_race(race_id); rh.historical.results(2021, 22); rh.telemetry.get_race_summary(race_id) +rh.data.get_race(race_id); rh.historical.results(2021, 22) rh.usage.current(); rh.usage.subscription() for feed, payload in rh.stream(["events.race"]): # SSE, no webhook server @@ -91,7 +91,7 @@ for feed, payload in rh.stream(["events.race"]): # SSE, no webhook server ``` Fantasy, replay and webhook methods return typed Pydantic models; the data/insights/historical/ -telemetry/models/lines/analytics/preview/strategy/usage namespaces return the decoded JSON `data`. On a non-2xx response the client raises +models/lines/analytics/preview/strategy/usage namespaces return the decoded JSON `data`. On a non-2xx response the client raises `RaceHooksAPIError` (with `status_code` and `body`); auth failures raise `RaceHooksAuthError`. ## Verify every incoming payload (do NOT skip this) diff --git a/CHANGELOG.md b/CHANGELOG.md index 15d48de..453263b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ +## Unreleased + +### Breaking Changes + +- Remove car telemetry client surface, following the API removal of `/v1/telemetry/*`, + `/v1/data/races/{raceId}/telemetry/*`, `/v1/data/races/{raceId}/summary` and the + `results.race-summary` webhook feed (racehooks#5025). Removed: `TelemetryNamespace` and + `client.telemetry`; `data.get_race_summary`, `data.get_race_telemetry_laps`, + `data.get_race_telemetry_stints`, `data.get_race_telemetry_aggression`; `RaceSummaryEvent` and + its `type == "race.summary.complete"` dispatch in `parse_event`. + ## v0.7.0 (2026-10-29) ### Features diff --git a/README.md b/README.md index c9d81e5..ca7e7f4 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ enforced by the API: a call above your plan raises `RaceHooksAPIError` with status 402 or 403. The fantasy, session-replay and webhook methods return typed Pydantic models. -The data, historical, insights, telemetry, models, lines, analytics, preview, +The data, historical, insights, models, lines, analytics, preview, strategy and usage namespaces return the decoded JSON `data` payload (`dict` or `list`); field names are listed in the [OpenAPI spec](https://api.racehooks.io/openapi.json). @@ -94,17 +94,15 @@ rh.preview.upcoming() # next-session preview (detail depen rh.strategy.preview_next(); rh.strategy.recap("2026-monaco-r5") ``` -### Data, historical and telemetry +### Data and historical ```python rh.data.list_drivers(search="ver", active=True) rh.data.get_race("2026-bahrain-r1") -rh.data.get_race_telemetry_laps("2026-bahrain-r1", driver_id="max_verstappen", lap=12) rh.data.get_season_standings(2026) rh.historical.results(2021, 22) # 1950 to present rh.historical.driver_career("lewis_hamilton") -rh.telemetry.get_lap_comparison("2026-bahrain-r1", 20) rh.indycar.standings() ``` @@ -282,7 +280,6 @@ The `feed` discriminator is the canonical, hyphenated feed id: | `events.race` | `RaceEvent` | `event`, `lap`, `utc` | | `events.qualifying` | `QualifyingEvent` | `event`, `lap`, `utc` | | `session.timing` | `SessionTimingEvent` | `utc`, `lap`, `total_laps`, `track_status` | -| `results.race-summary` | `RaceSummaryEvent` | `type`, `race_id`, telemetry summary fields | | `analytics.*` | `AnalyticsStrategy`, `AnalyticsRaceOdds`, `AnalyticsTruePace`, `AnalyticsGapProjection`, `AnalyticsWinningMargin`, `AnalyticsRaceDuration`, `AnalyticsRacePreview`, `AnalyticsTireStrategy`, `AnalyticsTeamPoints`, `AnalyticsChampionshipProbability`, `AnalyticsQualifying`, `AnalyticsSectorPace`, `AnalyticsBattle`, `AnalyticsPitWindow`, `AnalyticsTrackConditions`, `AnalyticsPitQuality` | per-feed (see `racehooks.models.feeds`) | | `weather.*` | `WeatherRainEvent` (rain-onset + rain-cleared), `WeatherForecastUpdate`, `WeatherTireMismatch`, `WeatherStrategyDivergence`, `WeatherCompoundCrossover` | per-feed | | anything else | `WebhookEvent` | — | diff --git a/racehooks/__init__.py b/racehooks/__init__.py index 7932e59..ad199af 100644 --- a/racehooks/__init__.py +++ b/racehooks/__init__.py @@ -69,7 +69,6 @@ RaceControlMessages, RaceEvent, RaceScores, - RaceSummaryEvent, ReplayMeta, SessionPitTimes, SessionScores, @@ -137,7 +136,6 @@ "RaceEvent", "QualifyingEvent", "SessionTimingEvent", - "RaceSummaryEvent", "AnyEvent", # shared "DriverRef", diff --git a/racehooks/client.py b/racehooks/client.py index 9911e94..c8519de 100644 --- a/racehooks/client.py +++ b/racehooks/client.py @@ -60,7 +60,6 @@ ModelsNamespace, PreviewNamespace, StrategyNamespace, - TelemetryNamespace, UsageNamespace, _data, _q, @@ -148,7 +147,6 @@ def __init__( self.historical = HistoricalNamespace(self) self.indycar = IndyCarNamespace(self) self.insights = InsightsNamespace(self) - self.telemetry = TelemetryNamespace(self) self.models = ModelsNamespace(self) self.lines = LinesNamespace(self) self.analytics = AnalyticsNamespace(self) @@ -713,7 +711,6 @@ def status(self, session_id: str) -> SimulateArtifact: "HistoricalNamespace", "IndyCarNamespace", "InsightsNamespace", - "TelemetryNamespace", "ModelsNamespace", "LinesNamespace", "AnalyticsNamespace", diff --git a/racehooks/models/__init__.py b/racehooks/models/__init__.py index 8b5d28d..349d615 100644 --- a/racehooks/models/__init__.py +++ b/racehooks/models/__init__.py @@ -21,7 +21,6 @@ AnyEvent, QualifyingEvent, RaceEvent, - RaceSummaryEvent, SessionTimingEvent, WebhookEvent, WeatherCompoundCrossover, @@ -88,7 +87,6 @@ "AnyEvent", "RaceEvent", "QualifyingEvent", - "RaceSummaryEvent", "SessionTimingEvent", "WebhookEvent", "parse_event", diff --git a/racehooks/models/events.py b/racehooks/models/events.py index b82e4ab..99a6bbb 100644 --- a/racehooks/models/events.py +++ b/racehooks/models/events.py @@ -11,8 +11,6 @@ ``{ feed, sessionId, event, lap, utc, data }`` — a discriminated union keyed on ``event`` (e.g. ``"overtake"``, ``"safety.car.deployed"``). * ``session.timing``: ``{ feed, sessionId, utc, ...trackerFields }`` -* ``results.race-summary``: predates the ``feed`` envelope; carries a ``type`` - discriminator (``"race.summary.complete"``). * Derived analytics + weather feeds: see :mod:`racehooks.models.feeds`. :func:`parse_event` deserializes a raw payload into the most specific model, @@ -114,35 +112,12 @@ class SessionTimingEvent(WebhookEvent): track_status: Optional[str] = Field(default=None, alias="trackStatus") -class RaceSummaryEvent(WebhookEvent): - """``results.race-summary`` — post-race telemetry summary (once, after CarData). - - This delivery predates the standard ``feed`` envelope and instead carries a - ``type`` discriminator (``"race.summary.complete"``). Top-level fields mirror - the canonical ``RaceSummaryPayload``. - """ - - feed: str = "results.race-summary" - type: Optional[str] = None - race_id: Optional[str] = Field(default=None, alias="raceId") - race_name: Optional[str] = Field(default=None, alias="raceName") - processed_at: Optional[str] = Field(default=None, alias="processedAt") - total_samples: Optional[int] = Field(default=None, alias="totalSamples") - max_speed_kph: Optional[float] = Field(default=None, alias="maxSpeedKph") - max_speed_driver: Optional[DriverRef] = Field(default=None, alias="maxSpeedDriver") - avg_throttle_pct: Optional[float] = Field(default=None, alias="avgThrottlePct") - avg_brake_pct: Optional[float] = Field(default=None, alias="avgBrakePct") - top_aggression_driver: Optional[DriverRef] = Field(default=None, alias="topAggressionDriver") - top_aggression_score: Optional[float] = Field(default=None, alias="topAggressionScore") - - # Canonical feed ids that get a dedicated envelope model. Everything else is # parsed as the generic :class:`WebhookEvent`. _EVENT_MODELS: Dict[str, Any] = { "events.race": RaceEvent, "events.qualifying": QualifyingEvent, "session.timing": SessionTimingEvent, - "results.race-summary": RaceSummaryEvent, "analytics.strategy": AnalyticsStrategy, "analytics.race-odds": AnalyticsRaceOdds, "analytics.true-pace": AnalyticsTruePace, @@ -171,7 +146,6 @@ class RaceSummaryEvent(WebhookEvent): RaceEvent, QualifyingEvent, SessionTimingEvent, - RaceSummaryEvent, AnalyticsStrategy, AnalyticsRaceOdds, AnalyticsTruePace, @@ -200,9 +174,7 @@ class RaceSummaryEvent(WebhookEvent): def parse_event(payload: Union[str, bytes, bytearray, Dict[str, Any]]) -> AnyEvent: """Parse a raw webhook payload into the most specific event model. - Dispatch is on the canonical ``feed`` discriminator. The - ``results.race-summary`` delivery predates the ``feed`` envelope and instead - carries ``type == "race.summary.complete"``; that shape is recognised too. + Dispatch is on the canonical ``feed`` discriminator. :param payload: Raw JSON ``str``/``bytes`` or an already-decoded ``dict``. :returns: The most specific :class:`AnyEvent` member, or generic @@ -217,9 +189,6 @@ def parse_event(payload: Union[str, bytes, bytearray, Dict[str, Any]]) -> AnyEve raise ValueError("Webhook payload must be a JSON object") feed = data.get("feed") - if not feed and data.get("type") == "race.summary.complete": - return RaceSummaryEvent.model_validate(data) - model = _EVENT_MODELS.get(feed or "", WebhookEvent) return model.model_validate(data) @@ -229,7 +198,6 @@ def parse_event(payload: Union[str, bytes, bytearray, Dict[str, Any]]) -> AnyEve "RaceEvent", "QualifyingEvent", "SessionTimingEvent", - "RaceSummaryEvent", "AnyEvent", "parse_event", "DriverRef", diff --git a/racehooks/namespaces.py b/racehooks/namespaces.py index f21144c..f324f61 100644 --- a/racehooks/namespaces.py +++ b/racehooks/namespaces.py @@ -38,9 +38,8 @@ def _get(self, path: str, **params: Any) -> Any: class DataNamespace(_Namespace): - """Drivers, constructors, circuits, seasons, races and post-race telemetry - analytics (``/v1/data/*``). Available on every plan; timing fields and some - telemetry are gated by plan.""" + """Drivers, constructors, circuits, seasons and races (``/v1/data/*``). + Available on every plan; timing fields are gated by plan.""" def list_drivers( self, @@ -196,9 +195,6 @@ def get_race_tyres(self, race_id: str) -> Any: def get_race_weather(self, race_id: str) -> Any: return self._get(f"/data/races/{race_id}/weather") - def get_race_summary(self, race_id: str) -> Any: - return self._get(f"/data/races/{race_id}/summary") - def get_race_laps( self, race_id: str, @@ -220,41 +216,6 @@ def get_driver_race_laps(self, race_id: str, driver_id: str) -> Any: """Every lap of one driver in one race (``/v1/data/races/{raceId}/laps/{driverId}``).""" return self._get(f"/data/races/{race_id}/laps/{driver_id}") - def get_race_telemetry_laps( - self, - race_id: str, - *, - series: Optional[str] = None, - driver_id: Optional[str] = None, - lap: Optional[int] = None, - limit: Optional[int] = None, - offset: Optional[int] = None, - ) -> Any: - return self._get( - f"/data/races/{race_id}/telemetry/laps", - series=series, - driverId=driver_id, - lap=lap, - limit=limit, - offset=offset, - ) - - def get_race_telemetry_stints( - self, - race_id: str, - *, - series: Optional[str] = None, - driver_id: Optional[str] = None, - ) -> Any: - return self._get( - f"/data/races/{race_id}/telemetry/stints", - series=series, - driverId=driver_id, - ) - - def get_race_telemetry_aggression(self, race_id: str) -> Any: - return self._get(f"/data/races/{race_id}/telemetry/aggression") - def get_session_analytics( self, session_id: str, @@ -480,33 +441,6 @@ def get_model_meta(self) -> Any: return self._get("/insights/model-meta") -class TelemetryNamespace(_Namespace): - """Post-session per-lap telemetry analytics (``/v1/telemetry/*``).""" - - def get_race_laps( - self, - race_id: str, - *, - driver_id: Optional[str] = None, - lap_number: Optional[int] = None, - ) -> Any: - return self._get( - f"/telemetry/races/{race_id}/laps", - driverId=driver_id, - lapNumber=lap_number, - ) - - def get_driver_laps(self, race_id: str, driver_id: str) -> Any: - return self._get(f"/telemetry/races/{race_id}/drivers/{driver_id}/laps") - - def get_lap_comparison(self, race_id: str, lap_number: int) -> Any: - """All drivers for one lap, for cross-driver comparison.""" - return self._get(f"/telemetry/races/{race_id}/laps/{lap_number}") - - def get_race_summary(self, race_id: str) -> Any: - return self._get(f"/telemetry/races/{race_id}/summary") - - class ModelsNamespace(_Namespace): """Public model manifest and scorecards (``/v1/models/*``).""" diff --git a/tests/test_models.py b/tests/test_models.py index 6d843ea..9dd7aff 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -10,7 +10,6 @@ LapCount, QualifyingEvent, RaceEvent, - RaceSummaryEvent, SessionTimingEvent, TrackStatus, WeatherData, @@ -97,25 +96,6 @@ def test_parse_session_timing_specializes(): assert event.remaining == "01:28:00" -def test_parse_results_race_summary_by_type_discriminator(): - # results.race-summary predates the feed envelope — dispatched on `type`. - payload = { - "type": "race.summary.complete", - "raceId": "2026-bahrain-r1", - "raceName": "Bahrain Grand Prix", - "processedAt": "2026-03-16T17:30:00Z", - "totalSamples": 123456, - "maxSpeedKph": 342.1, - "maxSpeedDriver": _driver_ref("1"), - } - event = parse_event(payload) - assert isinstance(event, RaceSummaryEvent) - assert event.feed == "results.race-summary" - assert event.race_id == "2026-bahrain-r1" - assert event.total_samples == 123456 - assert event.max_speed_driver.tla == "VER" - - def test_parse_event_accepts_bytes(): event = parse_event(b'{"feed":"session.track-status","sessionId":null,"data":{"Status":"1"}}') assert event.feed == "session.track-status" diff --git a/tests/test_surface.py b/tests/test_surface.py index fc468e6..386f9f4 100644 --- a/tests/test_surface.py +++ b/tests/test_surface.py @@ -46,11 +46,6 @@ def handler(request: httpx.Request) -> httpx.Response: "/v1/data/drivers", {"search": "ver", "active": "true", "limit": "5"}, ), - ( - lambda rh: rh.data.get_race_telemetry_laps("r1", driver_id="d", lap=3), - "/v1/data/races/r1/telemetry/laps", - {"driverId": "d", "lap": "3"}, - ), (lambda rh: rh.historical.results(2021, 22), "/v1/historical/2021/22/results", {}), ( lambda rh: rh.historical.driver_standings(2021, 5), @@ -60,7 +55,6 @@ def handler(request: httpx.Request) -> httpx.Response: (lambda rh: rh.historical.driver_standings(2021), "/v1/historical/2021/driverStandings", {}), (lambda rh: rh.insights.get_race("r1"), "/v1/insights/races/r1", {}), (lambda rh: rh.insights.get_model_meta(), "/v1/insights/model-meta", {}), - (lambda rh: rh.telemetry.get_lap_comparison("r1", 20), "/v1/telemetry/races/r1/laps/20", {}), (lambda rh: rh.models.manifest(), "/v1/models/manifest", {}), ( lambda rh: rh.lines.get("r1", checkpoint="q_end", market="winner"), From f06073684d7b104872abc0dcc4df1df2b47300c9 Mon Sep 17 00:00:00 2001 From: Jon Lazarowicz Date: Wed, 4 Nov 2026 15:25:25 -0500 Subject: [PATCH 2/2] feat: generate FeedId, FeedAvailability and FEED_CATALOG from the vendored feed catalog Vendor the RaceHooks feed catalog as catalog/feed-catalog.json and generate racehooks/models/_feed_catalog.py from it (scripts/gen_feed_catalog.py). CI re-runs the generator and fails on diff. - New FeedId, FeedAvailability (free | live | analytics | lap), FeedFamily literals and the FEED_CATALOG / FEED_CATALOG_HASH constants, exported from racehooks. Feed.availability stays a plain str (documented as the feed tier, not the account plan) so a new tier never breaks parsing. - New event models where the catalog publishes a real sample: pit.stops, session.clock, session.info, telemetry.track-position. All other feeds without a model, including the seven with no sample (fantasy.scores, lite.race-odds, radio.transcript, strategy.recommendation, race.grid-penalty, regulatory.stewards-decision, analytics.ml-result), parse as the generic WebhookEvent. --- .github/workflows/ci.yml | 16 + catalog/feed-catalog.json | 1000 +++++++++++++++++++++++++++++ racehooks/__init__.py | 20 + racehooks/models/__init__.py | 22 + racehooks/models/_feed_catalog.py | 157 +++++ racehooks/models/events.py | 50 +- racehooks/models/resources.py | 2 + scripts/gen_feed_catalog.py | 72 +++ tests/test_models.py | 27 + 9 files changed, 1365 insertions(+), 1 deletion(-) create mode 100644 catalog/feed-catalog.json create mode 100644 racehooks/models/_feed_catalog.py create mode 100644 scripts/gen_feed_catalog.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c94041c..a3ffc6a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,3 +52,19 @@ jobs: bash scripts/gen_proto.sh git diff --exit-code -- racehooks/grpc/_gen \ || (echo "stubs out of date: run scripts/gen_proto.sh" && exit 1) + + feed-catalog: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Verify generated feed catalog is up to date + run: | + python scripts/gen_feed_catalog.py + git diff --exit-code -- racehooks/models/_feed_catalog.py \ + || (echo "feed catalog out of date: run scripts/gen_feed_catalog.py" && exit 1) + # TODO: also compare catalog/feed-catalog.json contentHash against the monorepo's published + # catalog. No public URL serves it yet (GET /v1/feeds requires auth), so this check is not + # possible until one exists. diff --git a/catalog/feed-catalog.json b/catalog/feed-catalog.json new file mode 100644 index 0000000..9ff4099 --- /dev/null +++ b/catalog/feed-catalog.json @@ -0,0 +1,1000 @@ +{ + "schema": "racehooks.feed-catalog/1", + "contentHash": "e573a0c1b84e09386053de7d77b5edca38fab0bd2ac8aba5afe48f476cd1daf9", + "families": [ + { + "category": "analytics", + "slug": "analytics", + "label": "Models & Predictions", + "desc": "ML model outputs, per driver", + "order": 1 + }, + { + "category": "timing", + "slug": "timing", + "label": "Timing & Laps", + "desc": "Lap times, sectors, gaps, positions", + "order": 2 + }, + { + "category": "strategy", + "slug": "strategy", + "label": "Strategy & Tyres", + "desc": "Tyre stints, pit times, compounds", + "order": 3 + }, + { + "category": "race-control", + "slug": "race-control", + "label": "Race Control", + "desc": "FIA messages, flags, team radio", + "order": 4 + }, + { + "category": "race-events", + "slug": "race-events", + "label": "Race Events", + "desc": "Computed events, session timing, qualifying", + "order": 5 + }, + { + "category": "results", + "slug": "results", + "label": "Results & Standings", + "desc": "Classified results and championship projections", + "order": 6 + }, + { + "category": "weather", + "slug": "weather", + "label": "Weather", + "desc": "Conditions and predictive alerts", + "order": 7 + }, + { + "category": "telemetry", + "slug": "telemetry", + "label": "Telemetry", + "desc": "Live position and driver tracking", + "order": 8 + }, + { + "category": "core", + "slug": "session-core", + "label": "Session & Core", + "desc": "Status, clock, lap count, drivers", + "order": 9 + } + ], + "feeds": [ + { + "feedId": "analytics.strategy", + "name": "Race Strategy Analytics", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Per-driver decision surfaces: pit (probability, window, plan, call), threat (undercut/overcut/overtake), pace (LTOE, clean pace, tyre health), reliability (DNF risk); plus session-level raceState (safety car probability, strategy leverage, pit-cycle openness T(L)).", + "cadence": "Per lap", + "sessionContext": "Race, Sprint", + "sample": { + "payload": { + "feed": "analytics.strategy", + "sessionId": "2026-canada_r", + "lap": 18, + "drivers": [ + { + "number": "12", + "tla": "ANT", + "pit": { + "pNextLap": 0.09, + "pWithin3Laps": 0.248 + } + } + ] + }, + "source": { + "kind": "production-export", + "session": "2026-canada_r", + "utc": null, + "note": "recorded production pit-model output for lap 18 (company/marketing/evidence/export_canada_tiles.py), one driver row" + } + } + }, + { + "feedId": "strategy.recommendation", + "name": "Strategy Recommendation", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Prescriptive counterfactual strategy ranking for the front-runners: candidate pit-and-compound schedules simulated under common random numbers and ranked by outcome distribution — P(win), P(podium), expected finish, expected championship points, p10–p90 robustness spread — with the emergent-strategy baseline for honest comparison.", + "cadence": "Per lap", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.race-odds", + "name": "Race Outcome Probabilities", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Monte Carlo position distribution, podium/points odds, expected points, fastest-lap probability, H2H vs teammate, and same-team pairs — plus, during the opening laps, the glass-box combined win-prob line (model prior pooled with the pre-race market line) that anchors the early race.", + "cadence": "Per lap", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "lite.race-odds", + "name": "In-race Chances", + "family": "analytics", + "tier": "lap", + "shortDesc": "In-race win, podium and points chance for every driver plus safety-car chance for the rest of the race, rounded to 5% and released one lap behind (Developer Live+).", + "cadence": "Per lap, one lap behind", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.true-pace", + "name": "True Pace Ranking", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Who's genuinely fastest: each car's session pace stripped of fuel load, tyre age, and traffic (dirty air), ranked — the public-data proxy for hidden long-run pace.", + "cadence": "Per lap", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.gap-projection", + "name": "Gap to Leader Projection", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Projected gap to the race leader at race end for every driver: five percentile bands (p10–p90) plus P(lapped) from Monte Carlo simulation.", + "cadence": "Per lap", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.winning-margin", + "name": "Winning Margin Projection", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Session-level race outlook: projected winning margin (P1–P2) with percentile bands, the probability the margin lands above 5s / 10s / below 3s, and the safety-car collapse risk that resets the lead.", + "cadence": "Per lap", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.race-preview", + "name": "Pre-Race Preview", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Pre-race projections in two stages: post-final-practice (long-run pace ranking, circuit strategy priors, weather outlook) and post-qualifying (classification with measured pole margin, pace-vs-grid deltas, derived race distance, pre-race pit-stop-count distributions, and — when a market line is available — the glass-box combined win-prob line pooling the model prior with the market).", + "cadence": "Twice per race weekend (post-final-practice, post-qualifying)", + "sessionContext": "Practice, Qualifying", + "sample": null + }, + { + "feedId": "analytics.ml-result", + "name": "ML Results", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Every ML model result as its own update the moment it lands: per model stream, ordered and gapless, with the per-driver predictions exactly as the inference server returned them (no coalescing).", + "cadence": "Per inference result (about every 1-2 s in a race, per model stream)", + "sample": null + }, + { + "feedId": "analytics.race-duration", + "name": "Race Duration Projection", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Projected total race time with p10/p90 bands, expected winner lap time, red-flag probability, and P(race exceeds the 2-hour FIA limit).", + "cadence": "Per lap", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.tire-strategy", + "name": "Tyre Strategy Probability", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Next-compound probabilities for drivers approaching a pit window (pitStopProbabilityNext3Laps > 0.25 — the within-3 scale, not the per-lap pitStopProbability). Sparse — fires only when relevant.", + "cadence": "Per pit approach", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.team-points", + "name": "Team Points Analytics", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Constructor-level expected points from discrete joint position-distribution convolution, with P(both drivers score) and full points distribution.", + "cadence": "Per lap", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.championship-probability", + "name": "Championship Win Probability", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Post-race championship win probability for every driver (WDC) and constructor (WCC). afterRaceId identifies which race the data reflects.", + "cadence": "Once, post-race", + "sessionContext": "Season", + "sample": null + }, + { + "feedId": "analytics.qualifying", + "name": "Qualifying Analytics", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Per-sector fastest probabilities and per-driver pace deltas during qualifying, with pole-margin probability. Fires after each personal best.", + "cadence": "Per lap improvement", + "sessionContext": "Qualifying", + "sample": null + }, + { + "feedId": "analytics.sector-pace", + "name": "Sector Pace Analytics", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Per-sector pace deltas with anomaly detection; fires when a sector-pace anomaly is detected.", + "cadence": "On sector anomaly", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.battle", + "name": "Strategy Battle Alert", + "family": "analytics", + "tier": "analytics", + "shortDesc": "On-track battle status between a driver and the car directly ahead (closing, holding, defending).", + "cadence": "On battle state change", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.pit-window", + "name": "Pit Window Alert", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Pit-window status (OPEN / URGENT) combining pit probability, undercut viability, tyre cliff risk, and gap context.", + "cadence": "On window open/urgent", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.track-conditions", + "name": "Track Conditions Analytics", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Track evolution and grip-condition analytics derived from field pace trends.", + "cadence": "Per lap", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "analytics.pit-quality", + "name": "Pit Quality Alert", + "family": "analytics", + "tier": "analytics", + "shortDesc": "Pit-stop execution quality assessment (stationary time vs. expected) after a stop completes.", + "cadence": "On pit completion", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "timing.data", + "name": "Live Timing", + "family": "timing", + "tier": "live", + "shortDesc": "Per-driver position, gaps (leader + interval), lap/sector times, speed traps, pit status.", + "sample": { + "payload": { + "feed": "timing.data", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:21:14.005Z", + "drivers": [ + { + "driverId": "norris-lando", + "constructorId": "mclaren", + "number": "1", + "tla": "NOR", + "name": "Lando Norris", + "team": "McLaren", + "gapToLeader": { + "display": "+29.517", + "seconds": 29.517 + }, + "lastLapTime": { + "display": "1:18.079", + "ms": 78079 + }, + "bestLapTime": { + "display": "1:18.079", + "ms": 78079 + }, + "sectors": [ + null, + null, + { + "display": "30.774", + "ms": 30774 + } + ], + "speeds": { + "fl": 293 + } + }, + { + "driverId": "hadjar-isack", + "constructorId": "red-bull-racing", + "number": "6", + "tla": "HAD", + "name": "Isack Hadjar", + "team": "Red Bull Racing", + "gapToLeader": { + "display": "+7.292", + "seconds": 7.292 + }, + "lastLapTime": null, + "sectors": [ + { + "display": "21.828", + "ms": 21828 + }, + null, + null + ], + "speeds": { + "i1": 240 + } + }, + { + "driverId": "leclerc-charles", + "constructorId": "ferrari", + "number": "16", + "tla": "LEC", + "name": "Charles Leclerc", + "team": "Ferrari", + "gapToLeader": { + "display": "+5.314", + "seconds": 5.314 + }, + "lastLapTime": null, + "sectors": [ + null, + null, + null + ] + } + ] + }, + "source": { + "kind": "capture-normalised", + "session": "2026-canada_r", + "utc": "2026-10-05T18:21:14.005Z", + "note": "recorded frame; driver identity fields completed from the driver registry, timing.data trimmed to 3 rows" + } + } + }, + { + "feedId": "timing.stats", + "name": "Timing Stats", + "family": "timing", + "tier": "live", + "shortDesc": "Personal best lap, best sectors, speed trap rankings.", + "sample": null + }, + { + "feedId": "timing.lap-history", + "name": "Lap History", + "family": "timing", + "tier": "live", + "shortDesc": "Accumulated per-driver lap data series.", + "sample": null + }, + { + "feedId": "timing.top-three", + "name": "Top Three", + "family": "timing", + "tier": "live", + "shortDesc": "Simplified live leaderboard for the top three cars — position, driver, lap time, and gap. Zero-dependency feed for tickers and score overlays.", + "sample": null + }, + { + "feedId": "timing.mini-sectors", + "name": "Mini-Sector Timing", + "family": "timing", + "tier": "analytics", + "shortDesc": "High-granularity timing companion: mini-sector progress ticks, speed-trap readings (I1, I2, FL, ST), and live pit/retirement flags.", + "sample": null + }, + { + "feedId": "tire.current", + "name": "Current Tyres", + "family": "strategy", + "tier": "live", + "shortDesc": "Current compound per driver with age and new-set flag.", + "sample": null + }, + { + "feedId": "tire.history", + "name": "Tyre History", + "family": "strategy", + "tier": "live", + "shortDesc": "Full stint history: compound, start lap, laps on tyre.", + "sample": null + }, + { + "feedId": "tire.stints", + "name": "Stint Data", + "family": "strategy", + "tier": "live", + "shortDesc": "Each driver's complete stint list: compound, new set, tyre age, laps, best lap; plus grid slot.", + "sample": null + }, + { + "feedId": "pit.lane-times", + "name": "Pit Lane Times", + "family": "strategy", + "tier": "live", + "shortDesc": "Pit stop durations in milliseconds with pit-in/out laps.", + "sample": null + }, + { + "feedId": "pit.stops", + "name": "Pit Stop", + "family": "strategy", + "tier": "live", + "shortDesc": "Official F1 single pit-stop record (authoritative, arrives after the live stop).", + "sample": { + "payload": { + "feed": "pit.stops", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:51:14.806Z", + "data": { + "driver": { + "driverId": "colapinto-franco", + "constructorId": "alpine", + "number": "43", + "tla": "COL", + "name": "Franco Colapinto", + "team": "Alpine" + }, + "lap": 30, + "pitStopTimeMs": 3800, + "pitLaneTimeMs": 25640 + } + }, + "source": { + "kind": "capture-normalised", + "session": "2026-canada_r", + "utc": "2026-10-05T18:51:14.806Z", + "note": "recorded frame; driver identity fields completed from the driver registry, timing.data trimmed to 3 rows" + } + } + }, + { + "feedId": "pit.stop-series", + "name": "Pit Stop Series", + "family": "strategy", + "tier": "live", + "shortDesc": "Full pit-stop history per driver.", + "sample": null + }, + { + "feedId": "session.track-status", + "name": "Track Status", + "family": "race-control", + "tier": "free", + "shortDesc": "Track flag code: 1=Clear, 2=Yellow, 4=SC, 5=Red, 6=VSC, 7=VSC Ending.", + "sample": { + "payload": { + "feed": "session.track-status", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:49:34.525Z", + "data": { + "status": "yellow", + "message": "Yellow" + } + }, + "source": { + "kind": "capture", + "session": "2026-canada_r", + "utc": "2026-10-05T18:49:34.525Z", + "capture": "sc", + "seq": 47632 + } + } + }, + { + "feedId": "race-control.messages", + "name": "Race Control Messages", + "family": "race-control", + "tier": "live", + "shortDesc": "Raw FIA race control messages: safety car, VSC, red flag, penalties, investigations.", + "sample": { + "payload": { + "feed": "race-control.messages", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:48:39.015Z", + "data": { + "messages": [ + { + "utc": "2026-05-24T20:46:58", + "category": "Flag", + "message": "WAVED BLUE FLAG FOR CAR 18 (STR) TIMED AT 16:46:58", + "flag": "BLUE", + "lap": 29, + "scope": "Driver" + } + ] + } + }, + "source": { + "kind": "capture", + "session": "2026-canada_r", + "utc": "2026-10-05T18:48:39.015Z", + "capture": "sc", + "seq": 46669 + } + } + }, + { + "feedId": "radio.transcript", + "name": "Team Radio Transcript", + "family": "race-control", + "tier": "analytics", + "shortDesc": "Team radio speech, transcribed: what the driver and pit wall actually said, with a confidence score.", + "cadence": "per radio clip, seconds after the broadcast", + "sample": null + }, + { + "feedId": "regulatory.stewards-decision", + "name": "Stewards Decisions", + "family": "race-control", + "tier": "live", + "shortDesc": "Parsed FIA stewards decisions: penalty type, driver, session, infringement, grid places / seconds / fine, raw decision text.", + "cadence": "on publication (FIA decision documents, ~3 min poll)", + "sample": null + }, + { + "feedId": "race.grid-penalty", + "name": "Grid Penalties", + "family": "race-control", + "tier": "live", + "shortDesc": "Grid-affecting stewards decisions only (grid drop, back of grid, pit-lane start), with the number of grid places.", + "cadence": "on publication (FIA decision documents, ~3 min poll)", + "sample": null + }, + { + "feedId": "events.race", + "name": "Race Events", + "family": "race-events", + "tier": "live", + "shortDesc": "RaceHooks-computed synthetic events: overtakes, pit stops, safety cars, fastest laps, retirements, penalties, and more (40+ event types).", + "cadence": "On state transition", + "sample": { + "payload": { + "feed": "events.race", + "sessionId": "2026-canada_r", + "event": "overtake", + "lap": 30, + "utc": "2026-10-05T18:49:20.412Z", + "data": { + "overtakingDriver": { + "driverId": "antonelli-kimi", + "constructorId": "mercedes", + "number": "12", + "tla": "ANT", + "name": "Kimi Antonelli", + "team": "Mercedes", + "newPosition": 1, + "prevPosition": 2 + }, + "overtakenDriver": { + "driverId": "russell-george", + "constructorId": "mercedes", + "number": "63", + "tla": "RUS", + "name": "George Russell", + "team": "Mercedes", + "newPosition": 2, + "prevPosition": 1 + } + } + }, + "source": { + "kind": "capture-normalised", + "session": "2026-canada_r", + "utc": "2026-10-05T18:49:20.412Z", + "note": "recorded overtake event (docsDemoFixture DEMO_RACE_EVENTS); driver identity fields completed from the driver registry" + } + } + }, + { + "feedId": "session.timing", + "name": "Session Timing Milestones", + "family": "race-events", + "tier": "live", + "shortDesc": "Aggregated session timing state: flag, lap, clock, qualifying segment, resume time.", + "cadence": "On timing-relevant state change", + "sample": { + "payload": { + "feed": "session.timing", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:48:39.843Z", + "state": "racing", + "flag": "green", + "lap": 30, + "totalLaps": 68, + "sessionType": "Race", + "clock": { + "remaining": "01:59:59", + "extrapolating": true, + "utc": "2026-05-24T20:09:48.004Z" + }, + "resumeAt": null, + "resumeAtUtc": null, + "qualifyingSegment": null + }, + "source": { + "kind": "capture", + "session": "2026-canada_r", + "utc": "2026-10-05T18:48:39.843Z", + "capture": "sc", + "seq": 46684 + } + } + }, + { + "feedId": "events.qualifying", + "name": "Qualifying Events", + "family": "race-events", + "tier": "live", + "shortDesc": "Qualifying-specific synthetic events: lap improvements, eliminations, pole position, front row, session complete.", + "cadence": "On qualifying state change", + "sessionContext": "Qualifying", + "sample": null + }, + { + "feedId": "fantasy.scores", + "name": "Fantasy Scores", + "family": "race-events", + "tier": "live", + "shortDesc": "Provisional fantasy points per driver with the full component breakdown, pushed when a score changes. Same computation as the fantasy REST routes.", + "cadence": "On scoring change", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "standings.projection", + "name": "Live Championship Projection", + "family": "results", + "tier": "analytics", + "shortDesc": "Live championship points simulation: projected standings if the current race order holds.", + "sample": null + }, + { + "feedId": "results.classification", + "name": "Classified Results", + "family": "results", + "tier": "analytics", + "shortDesc": "Post-race classified positions (fires once after race end).", + "sample": null + }, + { + "feedId": "weather.data", + "name": "Weather Data", + "family": "weather", + "tier": "free", + "shortDesc": "Air/track temp, humidity, pressure, wind, rainfall.", + "sample": { + "payload": { + "feed": "weather.data", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:48:27.593Z", + "data": { + "airTempC": 13.4, + "trackTempC": 18.1, + "humidity": 67.5, + "pressure": 1024, + "windSpeed": 4.5, + "windDirection": 188, + "rainfall": false + } + }, + "source": { + "kind": "capture", + "session": "2026-canada_r", + "utc": "2026-10-05T18:48:27.593Z", + "capture": "sc", + "seq": 46478 + } + } + }, + { + "feedId": "weather.data-series", + "name": "Weather Data Series", + "family": "weather", + "tier": "live", + "shortDesc": "Time-series history of weather data.", + "sample": null + }, + { + "feedId": "weather.rain-onset", + "name": "Rain Onset", + "family": "weather", + "tier": "live", + "shortDesc": "Fires when rainfall begins at the circuit.", + "cadence": "On rain start", + "sample": null + }, + { + "feedId": "weather.rain-cleared", + "name": "Rain Cleared", + "family": "weather", + "tier": "live", + "shortDesc": "Fires when rainfall stops at the circuit.", + "cadence": "On rain stop", + "sample": null + }, + { + "feedId": "weather.strategy-divergence", + "name": "Weather Strategy Divergence", + "family": "weather", + "tier": "analytics", + "shortDesc": "Fires during active rain when the field splits between wet and dry compound strategies.", + "cadence": "During rain", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "weather.compound-crossover", + "name": "Compound Crossover Alert", + "family": "weather", + "tier": "analytics", + "shortDesc": "Fires when forecast conditions cross the threshold where a different compound becomes optimal.", + "cadence": "On crossover", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "weather.forecast-update", + "name": "Weather Forecast Update", + "family": "weather", + "tier": "analytics", + "shortDesc": "Fires when precipitation forecast changes by more than 0.5 mm/hr.", + "cadence": "On forecast change", + "sample": null + }, + { + "feedId": "weather.tire-mismatch", + "name": "Tyre Mismatch Alert", + "family": "weather", + "tier": "analytics", + "shortDesc": "Per-driver alert when a car is on slicks with rain falling or imminent — the wrong tyre for the conditions.", + "cadence": "On wet-tyre mismatch", + "sessionContext": "Race, Sprint", + "sample": null + }, + { + "feedId": "telemetry.driver-tracker", + "name": "Driver Tracker", + "family": "telemetry", + "tier": "live", + "shortDesc": "Low-resolution live position (x/y/z).", + "sample": null + }, + { + "feedId": "telemetry.track-position", + "name": "Virtual Track Position", + "family": "telemetry", + "tier": "live", + "shortDesc": "Every car's live position on the circuit — lap fraction plus x/y track coordinates — reconstructed each second from timing.", + "cadence": "~1/sec", + "sample": { + "payload": { + "feed": "telemetry.track-position", + "sessionId": "2026-canada_r", + "lap": 29, + "utc": "2026-10-05T18:48:29.984Z", + "estimates": [ + { + "driver": "1", + "lap": 28, + "arc": 3415.9225076124335, + "lapFraction": 0.7832888116515555, + "x": 163.35373540548088, + "y": 1007.3523059663565, + "v": 89.27185775464518, + "stdM": 25, + "regime": "track", + "ageMs": 0 + }, + { + "driver": "3", + "lap": 29, + "arc": 3102.9423574228254, + "lapFraction": 0.7115208340799875, + "x": 79.11032229002551, + "y": 1310.7302642025743, + "v": 87.34141667585854, + "stdM": 25, + "regime": "track", + "ageMs": 0 + }, + { + "driver": "5", + "lap": 28, + "arc": 1173.9516315859835, + "lapFraction": 0.26919321980875566, + "x": -92.57296325412047, + "y": 344.01358097584034, + "v": 41.81418690725663, + "stdM": 25, + "regime": "track", + "ageMs": 0 + } + ] + }, + "source": { + "kind": "capture", + "session": "2026-canada_r", + "utc": "2026-10-05T18:48:29.984Z", + "capture": "sc", + "seq": 46525, + "note": "trimmed to the first 3 of the frame's car estimates" + } + } + }, + { + "feedId": "session.status", + "name": "Session Status", + "family": "core", + "tier": "free", + "shortDesc": "Session lifecycle: Started, Aborted, Finished, Finalised, Ends.", + "sample": { + "payload": { + "feed": "session.status", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:11:28.392Z", + "data": { + "status": "started" + } + }, + "source": { + "kind": "capture", + "session": "2026-canada_r", + "utc": "2026-10-05T18:11:28.392Z", + "capture": "start", + "seq": 3748 + } + } + }, + { + "feedId": "session.lap-count", + "name": "Lap Count", + "family": "core", + "tier": "free", + "shortDesc": "Current lap and total laps remaining.", + "sample": { + "payload": { + "feed": "session.lap-count", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:09:44.695Z", + "data": { + "currentLap": 0, + "totalLaps": 68 + } + }, + "source": { + "kind": "capture", + "session": "2026-canada_r", + "utc": "2026-10-05T18:09:44.695Z", + "capture": "start", + "seq": 3511 + } + } + }, + { + "feedId": "driver.list", + "name": "Driver List", + "family": "core", + "tier": "free", + "shortDesc": "Driver number, TLA, full name, team name, team colour.", + "sample": { + "payload": { + "feed": "driver.list", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:49:56.756Z", + "drivers": [ + { + "driverId": "antonelli-kimi", + "constructorId": "mercedes", + "number": "12", + "tla": "ANT", + "name": "Kimi Antonelli", + "team": "Mercedes" + }, + { + "driverId": "russell-george", + "constructorId": "mercedes", + "number": "63", + "tla": "RUS", + "name": "George Russell", + "team": "Mercedes" + } + ] + }, + "source": { + "kind": "capture-normalised", + "session": "2026-canada_r", + "utc": "2026-10-05T18:49:56.756Z", + "note": "recorded frame; driver identity fields completed from the driver registry, timing.data trimmed to 3 rows" + } + } + }, + { + "feedId": "session.clock", + "name": "Extrapolated Clock", + "family": "core", + "tier": "live", + "shortDesc": "Session countdown clock with remaining time and extrapolating flag.", + "sample": { + "payload": { + "feed": "session.clock", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:11:28.642Z", + "data": { + "clockUtc": "2026-05-24T20:09:48.004Z", + "remaining": "01:59:59", + "extrapolating": true + } + }, + "source": { + "kind": "capture", + "session": "2026-canada_r", + "utc": "2026-10-05T18:11:28.642Z", + "capture": "start", + "seq": 3755 + } + } + }, + { + "feedId": "session.info", + "name": "Session Info", + "family": "core", + "tier": "live", + "shortDesc": "Session metadata: circuit, event, type, start/end dates, GMT offset.", + "sample": { + "payload": { + "feed": "session.info", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:11:28.392Z", + "data": { + "sessionType": "Race", + "sessionName": "Race", + "startDate": "2026-05-24T16:00:00", + "endDate": "2026-05-24T18:00:00", + "gmtOffset": "-04:00:00", + "eventName": "Canadian Grand Prix", + "officialName": "FORMULA 1 LENOVO GRAND PRIX DU CANADA 2026", + "location": "Montréal", + "country": { + "code": "CAN", + "name": "Canada" + }, + "circuit": { + "id": "montreal", + "name": "Montreal" + } + } + }, + "source": { + "kind": "capture", + "session": "2026-canada_r", + "utc": "2026-10-05T18:11:28.392Z", + "capture": "start", + "seq": 3747 + } + } + } + ] +} diff --git a/racehooks/__init__.py b/racehooks/__init__.py index ad199af..ad4a915 100644 --- a/racehooks/__init__.py +++ b/racehooks/__init__.py @@ -26,6 +26,12 @@ RaceHooksError, ) from .models import ( + FEED_CATALOG, + FEED_CATALOG_HASH, + FeedAvailability, + FeedCatalogEntry, + FeedFamily, + FeedId, DemoSession, ReplayQuota, ReplayableSession, @@ -74,6 +80,10 @@ SessionScores, SessionStatus, SessionTimingEvent, + PitStopEvent, + SessionClockEvent, + SessionInfoEvent, + TrackPositionEvent, Simulation, SubscriptionData, TimingData, @@ -136,6 +146,16 @@ "RaceEvent", "QualifyingEvent", "SessionTimingEvent", + "PitStopEvent", + "SessionClockEvent", + "SessionInfoEvent", + "TrackPositionEvent", + "FEED_CATALOG", + "FEED_CATALOG_HASH", + "FeedAvailability", + "FeedCatalogEntry", + "FeedFamily", + "FeedId", "AnyEvent", # shared "DriverRef", diff --git a/racehooks/models/__init__.py b/racehooks/models/__init__.py index 349d615..0656c03 100644 --- a/racehooks/models/__init__.py +++ b/racehooks/models/__init__.py @@ -1,5 +1,13 @@ """RaceHooks Pydantic models.""" +from ._feed_catalog import ( + FEED_CATALOG, + FEED_CATALOG_HASH, + FeedAvailability, + FeedCatalogEntry, + FeedFamily, + FeedId, +) from .common import DriverRef, ReplayMeta from .events import ( AnalyticsBattle, @@ -22,6 +30,10 @@ QualifyingEvent, RaceEvent, SessionTimingEvent, + PitStopEvent, + SessionClockEvent, + SessionInfoEvent, + TrackPositionEvent, WebhookEvent, WeatherCompoundCrossover, WeatherForecastUpdate, @@ -88,6 +100,16 @@ "RaceEvent", "QualifyingEvent", "SessionTimingEvent", + "PitStopEvent", + "SessionClockEvent", + "SessionInfoEvent", + "TrackPositionEvent", + "FEED_CATALOG", + "FEED_CATALOG_HASH", + "FeedAvailability", + "FeedCatalogEntry", + "FeedFamily", + "FeedId", "WebhookEvent", "parse_event", # raw feed data models diff --git a/racehooks/models/_feed_catalog.py b/racehooks/models/_feed_catalog.py new file mode 100644 index 0000000..2549a52 --- /dev/null +++ b/racehooks/models/_feed_catalog.py @@ -0,0 +1,157 @@ +"""GENERATED by scripts/gen_feed_catalog.py from catalog/feed-catalog.json. Do not edit.""" + +from __future__ import annotations + +from typing import Literal, NamedTuple, Optional, Tuple + +# Feed availability tier as published in the feed catalog. Not the account plan. +FeedAvailability = Literal[ + "analytics", + "lap", + "live", + "free", +] + +# Feed family (catalog category). +FeedFamily = Literal[ + "analytics", + "timing", + "strategy", + "race-control", + "race-events", + "results", + "weather", + "telemetry", + "core", +] + +# Canonical feed ids (the `feed` discriminator on every delivery). +FeedId = Literal[ + "analytics.strategy", + "strategy.recommendation", + "analytics.race-odds", + "lite.race-odds", + "analytics.true-pace", + "analytics.gap-projection", + "analytics.winning-margin", + "analytics.race-preview", + "analytics.ml-result", + "analytics.race-duration", + "analytics.tire-strategy", + "analytics.team-points", + "analytics.championship-probability", + "analytics.qualifying", + "analytics.sector-pace", + "analytics.battle", + "analytics.pit-window", + "analytics.track-conditions", + "analytics.pit-quality", + "timing.data", + "timing.stats", + "timing.lap-history", + "timing.top-three", + "timing.mini-sectors", + "tire.current", + "tire.history", + "tire.stints", + "pit.lane-times", + "pit.stops", + "pit.stop-series", + "session.track-status", + "race-control.messages", + "radio.transcript", + "regulatory.stewards-decision", + "race.grid-penalty", + "events.race", + "session.timing", + "events.qualifying", + "fantasy.scores", + "standings.projection", + "results.classification", + "weather.data", + "weather.data-series", + "weather.rain-onset", + "weather.rain-cleared", + "weather.strategy-divergence", + "weather.compound-crossover", + "weather.forecast-update", + "weather.tire-mismatch", + "telemetry.driver-tracker", + "telemetry.track-position", + "session.status", + "session.lap-count", + "driver.list", + "session.clock", + "session.info", +] + + +class FeedCatalogEntry(NamedTuple): + id: str + name: str + family: str + tier: str + description: str + cadence: Optional[str] + + +FEED_CATALOG_HASH = "e573a0c1b84e09386053de7d77b5edca38fab0bd2ac8aba5afe48f476cd1daf9" + +FEED_CATALOG: Tuple[FeedCatalogEntry, ...] = ( + FeedCatalogEntry(id="analytics.strategy", name="Race Strategy Analytics", family="analytics", tier="analytics", description="Per-driver decision surfaces: pit (probability, window, plan, call), threat (undercut/overcut/overtake), pace (LTOE, clean pace, tyre health), reliability (DNF risk); plus session-level raceState (safety car probability, strategy leverage, pit-cycle openness T(L)).", cadence='Per lap'), + FeedCatalogEntry(id="strategy.recommendation", name="Strategy Recommendation", family="analytics", tier="analytics", description="Prescriptive counterfactual strategy ranking for the front-runners: candidate pit-and-compound schedules simulated under common random numbers and ranked by outcome distribution — P(win), P(podium), expected finish, expected championship points, p10–p90 robustness spread — with the emergent-strategy baseline for honest comparison.", cadence='Per lap'), + FeedCatalogEntry(id="analytics.race-odds", name="Race Outcome Probabilities", family="analytics", tier="analytics", description="Monte Carlo position distribution, podium/points odds, expected points, fastest-lap probability, H2H vs teammate, and same-team pairs — plus, during the opening laps, the glass-box combined win-prob line (model prior pooled with the pre-race market line) that anchors the early race.", cadence='Per lap'), + FeedCatalogEntry(id="lite.race-odds", name="In-race Chances", family="analytics", tier="lap", description="In-race win, podium and points chance for every driver plus safety-car chance for the rest of the race, rounded to 5% and released one lap behind (Developer Live+).", cadence='Per lap, one lap behind'), + FeedCatalogEntry(id="analytics.true-pace", name="True Pace Ranking", family="analytics", tier="analytics", description="Who's genuinely fastest: each car's session pace stripped of fuel load, tyre age, and traffic (dirty air), ranked — the public-data proxy for hidden long-run pace.", cadence='Per lap'), + FeedCatalogEntry(id="analytics.gap-projection", name="Gap to Leader Projection", family="analytics", tier="analytics", description="Projected gap to the race leader at race end for every driver: five percentile bands (p10–p90) plus P(lapped) from Monte Carlo simulation.", cadence='Per lap'), + FeedCatalogEntry(id="analytics.winning-margin", name="Winning Margin Projection", family="analytics", tier="analytics", description="Session-level race outlook: projected winning margin (P1–P2) with percentile bands, the probability the margin lands above 5s / 10s / below 3s, and the safety-car collapse risk that resets the lead.", cadence='Per lap'), + FeedCatalogEntry(id="analytics.race-preview", name="Pre-Race Preview", family="analytics", tier="analytics", description="Pre-race projections in two stages: post-final-practice (long-run pace ranking, circuit strategy priors, weather outlook) and post-qualifying (classification with measured pole margin, pace-vs-grid deltas, derived race distance, pre-race pit-stop-count distributions, and — when a market line is available — the glass-box combined win-prob line pooling the model prior with the market).", cadence='Twice per race weekend (post-final-practice, post-qualifying)'), + FeedCatalogEntry(id="analytics.ml-result", name="ML Results", family="analytics", tier="analytics", description="Every ML model result as its own update the moment it lands: per model stream, ordered and gapless, with the per-driver predictions exactly as the inference server returned them (no coalescing).", cadence='Per inference result (about every 1-2 s in a race, per model stream)'), + FeedCatalogEntry(id="analytics.race-duration", name="Race Duration Projection", family="analytics", tier="analytics", description="Projected total race time with p10/p90 bands, expected winner lap time, red-flag probability, and P(race exceeds the 2-hour FIA limit).", cadence='Per lap'), + FeedCatalogEntry(id="analytics.tire-strategy", name="Tyre Strategy Probability", family="analytics", tier="analytics", description="Next-compound probabilities for drivers approaching a pit window (pitStopProbabilityNext3Laps > 0.25 — the within-3 scale, not the per-lap pitStopProbability). Sparse — fires only when relevant.", cadence='Per pit approach'), + FeedCatalogEntry(id="analytics.team-points", name="Team Points Analytics", family="analytics", tier="analytics", description="Constructor-level expected points from discrete joint position-distribution convolution, with P(both drivers score) and full points distribution.", cadence='Per lap'), + FeedCatalogEntry(id="analytics.championship-probability", name="Championship Win Probability", family="analytics", tier="analytics", description="Post-race championship win probability for every driver (WDC) and constructor (WCC). afterRaceId identifies which race the data reflects.", cadence='Once, post-race'), + FeedCatalogEntry(id="analytics.qualifying", name="Qualifying Analytics", family="analytics", tier="analytics", description="Per-sector fastest probabilities and per-driver pace deltas during qualifying, with pole-margin probability. Fires after each personal best.", cadence='Per lap improvement'), + FeedCatalogEntry(id="analytics.sector-pace", name="Sector Pace Analytics", family="analytics", tier="analytics", description="Per-sector pace deltas with anomaly detection; fires when a sector-pace anomaly is detected.", cadence='On sector anomaly'), + FeedCatalogEntry(id="analytics.battle", name="Strategy Battle Alert", family="analytics", tier="analytics", description="On-track battle status between a driver and the car directly ahead (closing, holding, defending).", cadence='On battle state change'), + FeedCatalogEntry(id="analytics.pit-window", name="Pit Window Alert", family="analytics", tier="analytics", description="Pit-window status (OPEN / URGENT) combining pit probability, undercut viability, tyre cliff risk, and gap context.", cadence='On window open/urgent'), + FeedCatalogEntry(id="analytics.track-conditions", name="Track Conditions Analytics", family="analytics", tier="analytics", description="Track evolution and grip-condition analytics derived from field pace trends.", cadence='Per lap'), + FeedCatalogEntry(id="analytics.pit-quality", name="Pit Quality Alert", family="analytics", tier="analytics", description="Pit-stop execution quality assessment (stationary time vs. expected) after a stop completes.", cadence='On pit completion'), + FeedCatalogEntry(id="timing.data", name="Live Timing", family="timing", tier="live", description="Per-driver position, gaps (leader + interval), lap/sector times, speed traps, pit status.", cadence=None), + FeedCatalogEntry(id="timing.stats", name="Timing Stats", family="timing", tier="live", description="Personal best lap, best sectors, speed trap rankings.", cadence=None), + FeedCatalogEntry(id="timing.lap-history", name="Lap History", family="timing", tier="live", description="Accumulated per-driver lap data series.", cadence=None), + FeedCatalogEntry(id="timing.top-three", name="Top Three", family="timing", tier="live", description="Simplified live leaderboard for the top three cars — position, driver, lap time, and gap. Zero-dependency feed for tickers and score overlays.", cadence=None), + FeedCatalogEntry(id="timing.mini-sectors", name="Mini-Sector Timing", family="timing", tier="analytics", description="High-granularity timing companion: mini-sector progress ticks, speed-trap readings (I1, I2, FL, ST), and live pit/retirement flags.", cadence=None), + FeedCatalogEntry(id="tire.current", name="Current Tyres", family="strategy", tier="live", description="Current compound per driver with age and new-set flag.", cadence=None), + FeedCatalogEntry(id="tire.history", name="Tyre History", family="strategy", tier="live", description="Full stint history: compound, start lap, laps on tyre.", cadence=None), + FeedCatalogEntry(id="tire.stints", name="Stint Data", family="strategy", tier="live", description="Each driver's complete stint list: compound, new set, tyre age, laps, best lap; plus grid slot.", cadence=None), + FeedCatalogEntry(id="pit.lane-times", name="Pit Lane Times", family="strategy", tier="live", description="Pit stop durations in milliseconds with pit-in/out laps.", cadence=None), + FeedCatalogEntry(id="pit.stops", name="Pit Stop", family="strategy", tier="live", description="Official F1 single pit-stop record (authoritative, arrives after the live stop).", cadence=None), + FeedCatalogEntry(id="pit.stop-series", name="Pit Stop Series", family="strategy", tier="live", description="Full pit-stop history per driver.", cadence=None), + FeedCatalogEntry(id="session.track-status", name="Track Status", family="race-control", tier="free", description="Track flag code: 1=Clear, 2=Yellow, 4=SC, 5=Red, 6=VSC, 7=VSC Ending.", cadence=None), + FeedCatalogEntry(id="race-control.messages", name="Race Control Messages", family="race-control", tier="live", description="Raw FIA race control messages: safety car, VSC, red flag, penalties, investigations.", cadence=None), + FeedCatalogEntry(id="radio.transcript", name="Team Radio Transcript", family="race-control", tier="analytics", description="Team radio speech, transcribed: what the driver and pit wall actually said, with a confidence score.", cadence='per radio clip, seconds after the broadcast'), + FeedCatalogEntry(id="regulatory.stewards-decision", name="Stewards Decisions", family="race-control", tier="live", description="Parsed FIA stewards decisions: penalty type, driver, session, infringement, grid places / seconds / fine, raw decision text.", cadence='on publication (FIA decision documents, ~3 min poll)'), + FeedCatalogEntry(id="race.grid-penalty", name="Grid Penalties", family="race-control", tier="live", description="Grid-affecting stewards decisions only (grid drop, back of grid, pit-lane start), with the number of grid places.", cadence='on publication (FIA decision documents, ~3 min poll)'), + FeedCatalogEntry(id="events.race", name="Race Events", family="race-events", tier="live", description="RaceHooks-computed synthetic events: overtakes, pit stops, safety cars, fastest laps, retirements, penalties, and more (40+ event types).", cadence='On state transition'), + FeedCatalogEntry(id="session.timing", name="Session Timing Milestones", family="race-events", tier="live", description="Aggregated session timing state: flag, lap, clock, qualifying segment, resume time.", cadence='On timing-relevant state change'), + FeedCatalogEntry(id="events.qualifying", name="Qualifying Events", family="race-events", tier="live", description="Qualifying-specific synthetic events: lap improvements, eliminations, pole position, front row, session complete.", cadence='On qualifying state change'), + FeedCatalogEntry(id="fantasy.scores", name="Fantasy Scores", family="race-events", tier="live", description="Provisional fantasy points per driver with the full component breakdown, pushed when a score changes. Same computation as the fantasy REST routes.", cadence='On scoring change'), + FeedCatalogEntry(id="standings.projection", name="Live Championship Projection", family="results", tier="analytics", description="Live championship points simulation: projected standings if the current race order holds.", cadence=None), + FeedCatalogEntry(id="results.classification", name="Classified Results", family="results", tier="analytics", description="Post-race classified positions (fires once after race end).", cadence=None), + FeedCatalogEntry(id="weather.data", name="Weather Data", family="weather", tier="free", description="Air/track temp, humidity, pressure, wind, rainfall.", cadence=None), + FeedCatalogEntry(id="weather.data-series", name="Weather Data Series", family="weather", tier="live", description="Time-series history of weather data.", cadence=None), + FeedCatalogEntry(id="weather.rain-onset", name="Rain Onset", family="weather", tier="live", description="Fires when rainfall begins at the circuit.", cadence='On rain start'), + FeedCatalogEntry(id="weather.rain-cleared", name="Rain Cleared", family="weather", tier="live", description="Fires when rainfall stops at the circuit.", cadence='On rain stop'), + FeedCatalogEntry(id="weather.strategy-divergence", name="Weather Strategy Divergence", family="weather", tier="analytics", description="Fires during active rain when the field splits between wet and dry compound strategies.", cadence='During rain'), + FeedCatalogEntry(id="weather.compound-crossover", name="Compound Crossover Alert", family="weather", tier="analytics", description="Fires when forecast conditions cross the threshold where a different compound becomes optimal.", cadence='On crossover'), + FeedCatalogEntry(id="weather.forecast-update", name="Weather Forecast Update", family="weather", tier="analytics", description="Fires when precipitation forecast changes by more than 0.5 mm/hr.", cadence='On forecast change'), + FeedCatalogEntry(id="weather.tire-mismatch", name="Tyre Mismatch Alert", family="weather", tier="analytics", description="Per-driver alert when a car is on slicks with rain falling or imminent — the wrong tyre for the conditions.", cadence='On wet-tyre mismatch'), + FeedCatalogEntry(id="telemetry.driver-tracker", name="Driver Tracker", family="telemetry", tier="live", description="Low-resolution live position (x/y/z).", cadence=None), + FeedCatalogEntry(id="telemetry.track-position", name="Virtual Track Position", family="telemetry", tier="live", description="Every car's live position on the circuit — lap fraction plus x/y track coordinates — reconstructed each second from timing.", cadence='~1/sec'), + FeedCatalogEntry(id="session.status", name="Session Status", family="core", tier="free", description="Session lifecycle: Started, Aborted, Finished, Finalised, Ends.", cadence=None), + FeedCatalogEntry(id="session.lap-count", name="Lap Count", family="core", tier="free", description="Current lap and total laps remaining.", cadence=None), + FeedCatalogEntry(id="driver.list", name="Driver List", family="core", tier="free", description="Driver number, TLA, full name, team name, team colour.", cadence=None), + FeedCatalogEntry(id="session.clock", name="Extrapolated Clock", family="core", tier="live", description="Session countdown clock with remaining time and extrapolating flag.", cadence=None), + FeedCatalogEntry(id="session.info", name="Session Info", family="core", tier="live", description="Session metadata: circuit, event, type, start/end dates, GMT offset.", cadence=None), +) diff --git a/racehooks/models/events.py b/racehooks/models/events.py index 99a6bbb..7e931e6 100644 --- a/racehooks/models/events.py +++ b/racehooks/models/events.py @@ -20,7 +20,7 @@ from __future__ import annotations import json -from typing import Any, Dict, Optional, Union +from typing import Any, Dict, List, Optional, Union from pydantic import BaseModel, ConfigDict, Field @@ -112,12 +112,52 @@ class SessionTimingEvent(WebhookEvent): track_status: Optional[str] = Field(default=None, alias="trackStatus") +class PitStopEvent(WebhookEvent): + """``pit.stops`` — one completed pit stop: ``data`` carries ``driver`` + (:class:`DriverRef`), ``lap``, ``pitStopTimeMs`` and ``pitLaneTimeMs``.""" + + feed: str = "pit.stops" + utc: Optional[str] = None + + +class SessionClockEvent(WebhookEvent): + """``session.clock`` — ``data`` carries ``clockUtc``, ``remaining`` and ``extrapolating``.""" + + feed: str = "session.clock" + utc: Optional[str] = None + + +class SessionInfoEvent(WebhookEvent): + """``session.info`` — ``data`` carries ``sessionType``, ``sessionName``, ``startDate``, + ``endDate``, ``gmtOffset``, ``eventName``, ``officialName``, ``location``, ``country`` and ``circuit``.""" + + feed: str = "session.info" + utc: Optional[str] = None + + +class TrackPositionEvent(WebhookEvent): + """``telemetry.track-position`` — ``{ feed, sessionId, lap, utc, estimates }``. + + Each estimate is a per-driver dict (``driver``, ``lap``, ``arc``, ``lapFraction``, + ``x``, ``y``, ``v``, ``stdM``, ``regime``, ``ageMs``), kept raw. + """ + + feed: str = "telemetry.track-position" + utc: Optional[str] = None + lap: Optional[int] = None + estimates: List[Dict[str, Any]] = Field(default_factory=list) + + # Canonical feed ids that get a dedicated envelope model. Everything else is # parsed as the generic :class:`WebhookEvent`. _EVENT_MODELS: Dict[str, Any] = { "events.race": RaceEvent, "events.qualifying": QualifyingEvent, "session.timing": SessionTimingEvent, + "pit.stops": PitStopEvent, + "session.clock": SessionClockEvent, + "session.info": SessionInfoEvent, + "telemetry.track-position": TrackPositionEvent, "analytics.strategy": AnalyticsStrategy, "analytics.race-odds": AnalyticsRaceOdds, "analytics.true-pace": AnalyticsTruePace, @@ -146,6 +186,10 @@ class SessionTimingEvent(WebhookEvent): RaceEvent, QualifyingEvent, SessionTimingEvent, + PitStopEvent, + SessionClockEvent, + SessionInfoEvent, + TrackPositionEvent, AnalyticsStrategy, AnalyticsRaceOdds, AnalyticsTruePace, @@ -198,6 +242,10 @@ def parse_event(payload: Union[str, bytes, bytearray, Dict[str, Any]]) -> AnyEve "RaceEvent", "QualifyingEvent", "SessionTimingEvent", + "PitStopEvent", + "SessionClockEvent", + "SessionInfoEvent", + "TrackPositionEvent", "AnyEvent", "parse_event", "DriverRef", diff --git a/racehooks/models/resources.py b/racehooks/models/resources.py index 4ef84cd..822774f 100644 --- a/racehooks/models/resources.py +++ b/racehooks/models/resources.py @@ -54,6 +54,8 @@ class Feed(_Resource): feed_id: Optional[str] = Field(default=None, alias="feedId") name: Optional[str] = None path: Optional[str] = None + #: Feed availability tier (see ``racehooks.FeedAvailability``: free, live, analytics, lap). + #: This is the feed tier, not your account plan. Kept as ``str`` so new tiers never break parsing. availability: Optional[str] = None diff --git a/scripts/gen_feed_catalog.py b/scripts/gen_feed_catalog.py new file mode 100644 index 0000000..ec5aa2f --- /dev/null +++ b/scripts/gen_feed_catalog.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Generate racehooks/models/_feed_catalog.py from catalog/feed-catalog.json. + +The JSON is the vendored copy of the RaceHooks feed catalog (schema +``racehooks.feed-catalog/1``). Usage: ``python scripts/gen_feed_catalog.py``. +""" + +import hashlib +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SRC = ROOT / "catalog" / "feed-catalog.json" +OUT = ROOT / "racehooks" / "models" / "_feed_catalog.py" + + +def literal(name: str, values: list) -> str: + body = ",\n".join(f" {json.dumps(v)}" for v in values) + return f"{name} = Literal[\n{body},\n]\n" + + +def main() -> None: + cat = json.loads(SRC.read_text(encoding="utf-8")) + if cat["schema"] != "racehooks.feed-catalog/1": + raise SystemExit(f"unsupported catalog schema: {cat['schema']}") + # Same canonicalisation as the monorepo generator (JS JSON.stringify: no spaces, raw unicode). + canon = json.dumps( + {"families": cat["families"], "feeds": cat["feeds"]}, + separators=(",", ":"), + ensure_ascii=False, + ) + digest = hashlib.sha256(canon.encode("utf-8")).hexdigest() + if digest != cat["contentHash"]: + raise SystemExit( + f"{SRC} is corrupt or hand-edited: contentHash {cat['contentHash']} != computed {digest}" + ) + + feeds = cat["feeds"] + tiers = list(dict.fromkeys(f["tier"] for f in feeds)) + families = [f["category"] for f in cat["families"]] + rows = "\n".join( + " FeedCatalogEntry(" + f"id={json.dumps(f['feedId'])}, name={json.dumps(f['name'], ensure_ascii=False)}, " + f"family={json.dumps(f['family'])}, tier={json.dumps(f['tier'])}, " + f"description={json.dumps(f['shortDesc'], ensure_ascii=False)}, " + f"cadence={f.get('cadence')!r})," + for f in feeds + ) + out = ( + '"""GENERATED by scripts/gen_feed_catalog.py from catalog/feed-catalog.json. Do not edit."""\n\n' + "from __future__ import annotations\n\n" + "from typing import Literal, NamedTuple, Optional, Tuple\n\n" + "# Feed availability tier as published in the feed catalog. Not the account plan.\n" + + literal("FeedAvailability", tiers) + + "\n# Feed family (catalog category).\n" + + literal("FeedFamily", families) + + "\n# Canonical feed ids (the `feed` discriminator on every delivery).\n" + + literal("FeedId", [f["feedId"] for f in feeds]) + + "\n\nclass FeedCatalogEntry(NamedTuple):\n" + " id: str\n name: str\n family: str\n tier: str\n description: str\n" + " cadence: Optional[str]\n\n\n" + f'FEED_CATALOG_HASH = "{cat["contentHash"]}"\n\n' + "FEED_CATALOG: Tuple[FeedCatalogEntry, ...] = (\n" + rows + "\n)\n" + ) + OUT.write_text(out, encoding="utf-8") + print( + f"wrote {OUT.relative_to(ROOT)} ({len(feeds)} feeds, hash {cat['contentHash'][:12]})" + ) + + +if __name__ == "__main__": + main() diff --git a/tests/test_models.py b/tests/test_models.py index 9dd7aff..9db0f41 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -455,3 +455,30 @@ def test_rest_resource_models(): assert event.official_name.startswith("Formula 1") assert event.sessions[0].session_id == "2026-bahrain-r1_Race" assert event.sessions[0].gmt_offset == "+03:00" + + +def test_feed_catalog_is_consistent(): + from typing import get_args + + from racehooks import FEED_CATALOG, FeedAvailability, FeedId + + ids = [f.id for f in FEED_CATALOG] + assert len(ids) == len(set(ids)) == len(get_args(FeedId)) + assert set(ids) == set(get_args(FeedId)) + assert {f.tier for f in FEED_CATALOG} <= set(get_args(FeedAvailability)) + + +def test_parse_event_catalog_sample_feeds(): + from racehooks import parse_event + + clock = parse_event( + { + "feed": "session.clock", + "sessionId": "2026-canada_r", + "utc": "2026-10-05T18:11:28.642Z", + "data": {"clockUtc": "2026-05-24T20:09:48.004Z", "remaining": "01:59:59", "extrapolating": True}, + } + ) + assert type(clock).__name__ == "SessionClockEvent" and clock.data["remaining"] == "01:59:59" + pos = parse_event({"feed": "telemetry.track-position", "sessionId": "s", "lap": 29, "estimates": [{"driver": "1"}]}) + assert type(pos).__name__ == "TrackPositionEvent" and pos.lap == 29