fix(championship): drop cancelled rounds and declare a clinched title (#110)

* fix(championship): drop cancelled rounds and declare a clinched title

The championship hub counted cancelled meetings (2026 Bahrain/Saudi) as
rounds, reporting 25 total / 6 left instead of 23 / 4. Title math then used
6 x 25 = 150 pts as the ceiling, so a 119-pt gap still looked "alive" after
Antonelli had mathematically clinched the title.

- Skip cancelled meetings and cancelled Race/Sprint sessions in both the
  local (query) and OpenF1 aggregation paths.
- Track pending sprints and return sprints_left + max_points_left
  (25/race + 8/sprint) so title math is sprint-aware.
- Frontend: use max_points_left for alive/out, gap annotations and the
  simulator; show a CHAMPION state, "has clinched" title math, and a
  Champion stat tile once P2 cannot catch the leader.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(championship): resolve ties on countback in title math

Review feedback:
- Local standings broke points ties by driver number, so a season ending
  level could crown the wrong driver. Order ties by FIA countback (most GP
  wins, then P2s, ...) before falling back to driver number.
- An exact-gap lead was always treated as open. It is a clinch when the
  leader still wins the countback even if the rival takes every remaining
  GP. Every rival, not just P2, is now checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aman TahilianiandClaude Opus 5.5 authored and GitHub committed 2026-11-01 18:40:37 -08:00
1 parent 21b29bec6a
commit 09bbccff93
12 files changed
+442 -36

No files matched your search

+67 -19
View File
@@ -697,14 +697,19 @@ type champHubTeam struct {
}
type champHubResponse struct {
Season int `json:"season"`
Round int `json:"round"`
TotalRounds int `json:"total_rounds"`
RoundsLeft int `json:"rounds_left"`
LastRace string `json:"last_race"`
RoundLabels []string `json:"round_labels"`
Drivers []champHubDriver `json:"drivers"`
Teams []champHubTeam `json:"teams"`
Season int `json:"season"`
Round int `json:"round"`
TotalRounds int `json:"total_rounds"`
RoundsLeft int `json:"rounds_left"`
// SprintsLeft counts sprint sessions still to run in the remaining rounds.
SprintsLeft int `json:"sprints_left"`
// MaxPointsLeft is the most points any one driver can still score
// (race wins plus sprint wins). It is the bound for title math.
MaxPointsLeft float64 `json:"max_points_left"`
LastRace string `json:"last_race"`
RoundLabels []string `json:"round_labels"`
Drivers []champHubDriver `json:"drivers"`
Teams []champHubTeam `json:"teams"`
}
// meetingRace bundles a GP meeting with its (already-fetched) race results and grid.
@@ -713,8 +718,17 @@ type meetingRace struct {
RaceSessionKey int
Results []models.SessionResult
Grid []models.StartingGrid
HasSprint bool // meeting has a non-cancelled Sprint session
SprintDone bool // that sprint already has results
}
// Maximum points one driver can score per race / sprint under the current
// (2025+) regulations — no fastest-lap point.
const (
maxRacePoints = 25
maxSprintPoints = 8
)
// champHubWorkers bounds the concurrent per-meeting fetches for the hub.
const champHubWorkers = 5
@@ -880,6 +894,8 @@ func (s *Server) localChampionshipHub(year int) (champHubResponse, bool, error)
RaceSessionKey: race.RaceSessionKey,
Results: race.Results,
Grid: race.Grid,
HasSprint: race.HasSprint,
SprintDone: race.SprintDone,
})
}
return aggregateChampionshipHub(year, races, inputs.Champ, inputs.Teams, inputs.DriverMap), true, nil
@@ -943,6 +959,14 @@ func fetchSeasonRaces(client *api.OpenF1Client, year int) (races []meetingRace,
return nil, false, err
}
sort.Slice(meetings, func(i, j int) bool { return meetings[i].DateStart < meetings[j].DateStart })
active := meetings[:0:0]
for _, m := range meetings {
// Cancelled meetings are not championship rounds.
if !m.IsCancelled {
active = append(active, m)
}
}
meetings = active
var failed atomic.Bool
races = fetchMeetingRaces(meetings, champHubWorkers, func(m models.Meeting) (meetingRace, bool) {
@@ -952,10 +976,15 @@ func fetchSeasonRaces(client *api.OpenF1Client, year int) (races []meetingRace,
return meetingRace{}, false
}
raceKey := 0
sprintKey := 0
for _, sess := range sessions {
if strings.EqualFold(sess.SessionName, "Race") {
if sess.IsCancelled {
continue
}
if strings.EqualFold(sess.SessionName, "Race") && raceKey == 0 {
raceKey = sess.SessionKey
break
} else if strings.EqualFold(sess.SessionName, "Sprint") && sprintKey == 0 {
sprintKey = sess.SessionKey
}
}
if raceKey == 0 {
@@ -973,7 +1002,19 @@ func fetchSeasonRaces(client *api.OpenF1Client, year int) (races []meetingRace,
if rerr != nil || gerr != nil {
failed.Store(true)
}
return meetingRace{Meeting: m, RaceSessionKey: raceKey, Results: results, Grid: grid}, true
mr := meetingRace{Meeting: m, RaceSessionKey: raceKey, Results: results, Grid: grid}
if sprintKey != 0 {
mr.HasSprint = true
if len(results) > 0 {
// The sprint always runs before the race.
mr.SprintDone = true
} else if sprint, serr := client.GetSessionResult(sprintKey); serr == nil {
mr.SprintDone = len(sprint) > 0
}
// On error leave SprintDone false: overstating the points still
// available keeps title math conservative (never a false clinch).
}
return mr, true
})
return races, failed.Load(), nil
}
@@ -1027,11 +1068,15 @@ func aggregateChampionshipHub(
}
completed := 0
sprintsLeft := 0
lastRace := ""
roundPoints := []map[int]float64{} // per completed round: driver -> race points
for _, mr := range races {
if len(mr.Results) == 0 {
if mr.HasSprint && !mr.SprintDone {
sprintsLeft++
}
continue // round not completed yet
}
completed++
@@ -1177,15 +1222,18 @@ func aggregateChampionshipHub(
}
totalRounds := len(races)
roundsLeft := totalRounds - completed
return champHubResponse{
Season: year,
Round: completed,
TotalRounds: totalRounds,
RoundsLeft: totalRounds - completed,
LastRace: lastRace,
RoundLabels: roundLabels,
Drivers: drivers,
Teams: teamsOut,
Season: year,
Round: completed,
TotalRounds: totalRounds,
RoundsLeft: roundsLeft,
SprintsLeft: sprintsLeft,
MaxPointsLeft: float64(maxRacePoints*roundsLeft + maxSprintPoints*sprintsLeft),
LastRace: lastRace,
RoundLabels: roundLabels,
Drivers: drivers,
Teams: teamsOut,
}
}
+72
View File
@@ -406,3 +406,75 @@ func TestChampHubCache(t *testing.T) {
t.Error("incomplete entry should expire after champHubIncompleteTTL")
}
}
func TestFetchSeasonRacesSkipsCancelledMeetings(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/meetings":
_, _ = w.Write([]byte(`[{"meeting_key":1,"meeting_name":"Run GP","date_start":"2026-03-01"},{"meeting_key":2,"meeting_name":"Cancelled GP","date_start":"2026-04-01","is_cancelled":true},{"meeting_key":3,"meeting_name":"Sprint GP","date_start":"2026-05-01"}]`))
case "/v1/sessions":
switch r.URL.Query().Get("meeting_key") {
case "2":
_, _ = w.Write([]byte(`[{"session_key":20,"meeting_key":2,"session_name":"Race","is_cancelled":true}]`))
case "3":
_, _ = w.Write([]byte(`[{"session_key":30,"meeting_key":3,"session_name":"Sprint"},{"session_key":31,"meeting_key":3,"session_name":"Race"}]`))
default:
_, _ = w.Write([]byte(`[{"session_key":10,"meeting_key":1,"session_name":"Race"}]`))
}
case "/v1/session_result":
if r.URL.Query().Get("session_key") == "10" {
_, _ = w.Write([]byte(`[{"driver_number":1,"position":1,"points":25}]`))
return
}
_, _ = w.Write([]byte(`[]`))
case "/v1/starting_grid":
_, _ = w.Write([]byte(`[]`))
default:
http.NotFound(w, r)
}
}))
defer upstream.Close()
client := api.NewOpenF1Client(upstream.URL, 2*time.Second)
defer client.Close()
races, _, err := fetchSeasonRaces(client.Scoped(), 2026)
if err != nil {
t.Fatal(err)
}
if len(races) != 2 {
t.Fatalf("races = %d, want 2 (cancelled meeting must be skipped)", len(races))
}
for _, mr := range races {
if mr.Meeting.MeetingName == "Cancelled GP" {
t.Fatal("cancelled meeting was counted as a round")
}
}
if !races[1].HasSprint || races[1].SprintDone {
t.Fatalf("sprint meeting = HasSprint %v SprintDone %v, want true/false", races[1].HasSprint, races[1].SprintDone)
}
}
func TestAggregateChampionshipHubMaxPointsLeftIncludesSprints(t *testing.T) {
champ := []models.ChampionshipDriver{
{DriverNumber: 12, PointsCurrent: 380, PositionCurrent: 1},
{DriverNumber: 1, PointsCurrent: 261, PositionCurrent: 2},
}
done := []models.SessionResult{raceResult(12, 1, 25), raceResult(1, 2, 18)}
races := []meetingRace{
{Meeting: models.Meeting{MeetingName: "Done GP"}, Results: done, HasSprint: true, SprintDone: true},
{Meeting: models.Meeting{MeetingName: "Sprint Done Race Pending GP"}, HasSprint: true, SprintDone: true},
{Meeting: models.Meeting{MeetingName: "Sprint GP"}, HasSprint: true},
{Meeting: models.Meeting{MeetingName: "Plain GP"}},
}
resp := aggregateChampionshipHub(2026, races, champ, nil, map[int]models.Driver{})
if resp.TotalRounds != 4 || resp.RoundsLeft != 3 {
t.Fatalf("rounds = %d/%d left, want 4 total / 3 left", resp.TotalRounds, resp.RoundsLeft)
}
if resp.SprintsLeft != 1 {
t.Errorf("sprints left = %d, want 1", resp.SprintsLeft)
}
if resp.MaxPointsLeft != 3*25+8 {
t.Errorf("max points left = %v, want %d", resp.MaxPointsLeft, 3*25+8)
}
}