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

+56 -2
View File
@@ -15,6 +15,11 @@ type ChampionshipRace struct {
RaceSessionKey int
Results []models.SessionResult
Grid []models.StartingGrid
// HasSprint reports whether the meeting has a (non-cancelled) Sprint
// session; SprintDone whether that sprint already has results. Together
// they let the hub count the sprint points still available.
HasSprint bool
SprintDone bool
}
// ChampionshipInputs are local-first inputs for the championship hub aggregation.
@@ -49,11 +54,19 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
}
pointsByDriver := map[int]float64{}
// Grand Prix finishing-position counts per driver, for countback.
finishesByDriver := map[int]map[int]int{}
pointsByTeam := map[string]float64{}
latestSessionKey := 0
latestMeetingKey := 0
for _, meeting := range meetings {
// Cancelled meetings (e.g. 2026 Bahrain/Saudi) are not championship
// rounds: counting them inflates total/remaining rounds and the
// title-math "max points left" bound.
if meeting.IsCancelled {
continue
}
sessions, err := s.ListSessionsByMeeting(int(meeting.MeetingKey))
if err != nil {
return ChampionshipInputs{}, err
@@ -62,6 +75,9 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
raceKey := 0
sprintKey := 0
for _, sess := range sessions {
if sess.IsCancelled {
continue
}
if strings.EqualFold(sess.SessionName, "Race") {
raceKey = sess.SessionKey
} else if strings.EqualFold(sess.SessionName, "Sprint") {
@@ -98,6 +114,14 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
for _, entry := range grid {
race.Grid = append(race.Grid, gridToModel(entry))
}
if sprintKey != 0 {
race.HasSprint = true
sprintResults, err := s.store.ListSessionResults(sprintKey)
if err != nil {
return ChampionshipInputs{}, err
}
race.SprintDone = len(sprintResults) > 0
}
inputs.Races = append(inputs.Races, race)
raceResults = race.Results
@@ -113,6 +137,12 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
}
for _, result := range results {
pointsByDriver[result.DriverNumber] += result.Points
if result.Position > 0 {
if finishesByDriver[result.DriverNumber] == nil {
finishesByDriver[result.DriverNumber] = map[int]int{}
}
finishesByDriver[result.DriverNumber][result.Position]++
}
team := inputs.DriverMap[result.DriverNumber].TeamName
if team != "" {
pointsByTeam[team] += result.Points
@@ -157,7 +187,7 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
_ = raceGrid
}
inputs.Champ = derivedDriverStandings(pointsByDriver, latestMeetingKey, latestSessionKey)
inputs.Champ = derivedDriverStandings(pointsByDriver, finishesByDriver, latestMeetingKey, latestSessionKey)
inputs.Teams = derivedTeamStandings(pointsByTeam, latestMeetingKey, latestSessionKey)
return inputs, nil
}
@@ -182,7 +212,10 @@ func (s *Service) driversForSession(sessionKey int) ([]models.Driver, error) {
return drivers, nil
}
func derivedDriverStandings(points map[int]float64, meetingKey, sessionKey int) []models.ChampionshipDriver {
// derivedDriverStandings orders drivers by points, breaking ties with the
// FIA countback (most Grand Prix wins, then most P2s, and so on), then by
// driver number for a stable order when countback cannot separate them.
func derivedDriverStandings(points map[int]float64, finishes map[int]map[int]int, meetingKey, sessionKey int) []models.ChampionshipDriver {
drivers := make([]models.ChampionshipDriver, 0, len(points))
for num, pts := range points {
drivers = append(drivers, models.ChampionshipDriver{
@@ -194,6 +227,9 @@ func derivedDriverStandings(points map[int]float64, meetingKey, sessionKey int)
}
sort.Slice(drivers, func(i, j int) bool {
if drivers[i].PointsCurrent == drivers[j].PointsCurrent {
if c := countbackCompare(finishes[drivers[i].DriverNumber], finishes[drivers[j].DriverNumber]); c != 0 {
return c > 0
}
return drivers[i].DriverNumber < drivers[j].DriverNumber
}
return drivers[i].PointsCurrent > drivers[j].PointsCurrent
@@ -204,6 +240,24 @@ func derivedDriverStandings(points map[int]float64, meetingKey, sessionKey int)
return drivers
}
// countbackCompare returns >0 if a beats b on countback, <0 if b beats a and
// 0 if their finishing records are identical.
func countbackCompare(a, b map[int]int) int {
maxPos := 0
for p := range a {
maxPos = max(maxPos, p)
}
for p := range b {
maxPos = max(maxPos, p)
}
for p := 1; p <= maxPos; p++ {
if a[p] != b[p] {
return a[p] - b[p]
}
}
return 0
}
func derivedTeamStandings(points map[string]float64, meetingKey, sessionKey int) []models.ChampionshipTeam {
teams := make([]models.ChampionshipTeam, 0, len(points))
for name, pts := range points {
+61
View File
@@ -428,3 +428,64 @@ func TestGetChampionshipInputsIncludesSprintPoints(t *testing.T) {
t.Fatalf("Teams = %+v, want Red Bull 33", inputs.Teams)
}
}
func TestGetChampionshipInputsSkipsCancelledAndFlagsPendingSprint(t *testing.T) {
svc := openTestService(t)
seedRaceHubData(t, svc.store)
upsert := func(m store.Meeting, sessions ...store.Session) {
t.Helper()
if err := svc.store.UpsertMeeting(m); err != nil {
t.Fatalf("UpsertMeeting() error = %v", err)
}
for _, s := range sessions {
if err := svc.store.UpsertSession(s); err != nil {
t.Fatalf("UpsertSession() error = %v", err)
}
}
}
upsert(store.Meeting{MeetingKey: 1230, MeetingName: "Cancelled GP", Year: 2025, DateStart: "2025-06-01T00:00:00+00:00", IsCancelled: true},
store.Session{SessionKey: 9480, MeetingKey: 1230, SessionName: "Race", SessionType: "Race", DateStart: "2025-06-01T13:00:00+00:00", IsCancelled: true})
upsert(store.Meeting{MeetingKey: 1231, MeetingName: "Sprint GP", Year: 2025, DateStart: "2025-07-01T00:00:00+00:00"},
store.Session{SessionKey: 9490, MeetingKey: 1231, SessionName: "Sprint", SessionType: "Race", DateStart: "2025-07-02T13:00:00+00:00"},
store.Session{SessionKey: 9491, MeetingKey: 1231, SessionName: "Race", SessionType: "Race", DateStart: "2025-07-03T13:00:00+00:00"})
inputs, err := svc.GetChampionshipInputs(2025)
if err != nil {
t.Fatalf("GetChampionshipInputs() error = %v", err)
}
if len(inputs.Races) != 2 {
t.Fatalf("Races = %d, want 2 (cancelled meeting skipped)", len(inputs.Races))
}
for _, r := range inputs.Races {
if r.Meeting.IsCancelled {
t.Fatalf("cancelled meeting %q counted as a round", r.Meeting.MeetingName)
}
}
if sprint := inputs.Races[1]; !sprint.HasSprint || sprint.SprintDone {
t.Fatalf("sprint round = HasSprint %v SprintDone %v, want true/false", sprint.HasSprint, sprint.SprintDone)
}
}
func TestDerivedDriverStandingsBreaksTiesOnCountback(t *testing.T) {
// VER #1 and ANT #12 level on points; ANT has more wins, so ANT leads
// despite the higher driver number.
points := map[int]float64{1: 400, 12: 400, 44: 300}
finishes := map[int]map[int]int{
1: {1: 5, 2: 10},
12: {1: 6, 2: 2},
44: {1: 1},
}
got := derivedDriverStandings(points, finishes, 0, 0)
if got[0].DriverNumber != 12 || got[1].DriverNumber != 1 || got[2].DriverNumber != 44 {
t.Fatalf("order = %d,%d,%d, want 12,1,44", got[0].DriverNumber, got[1].DriverNumber, got[2].DriverNumber)
}
if got[0].PositionCurrent != 1 || got[1].PositionCurrent != 2 {
t.Fatalf("positions = %d,%d, want 1,2", got[0].PositionCurrent, got[1].PositionCurrent)
}
// Equal on wins: decided by P2 count.
got = derivedDriverStandings(map[int]float64{1: 50, 12: 50}, map[int]map[int]int{1: {1: 1, 2: 2}, 12: {1: 1, 2: 1}}, 0, 0)
if got[0].DriverNumber != 1 {
t.Fatalf("P2 countback leader = %d, want 1", got[0].DriverNumber)
}
}
+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)
}
}