mirror of
https://github.com/AmanTahiliani/box-box.git
synced 2026-12-05 06:44:41 -05:00
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:
1 parent
21b29bec6a
commit
09bbccff93
12 files changed
+442
-36
No files matched your search
@@ -10,6 +10,7 @@ import {
|
||||
projectStandings,
|
||||
} from '../lib/simulator'
|
||||
import type { Scenario } from '../lib/simulator'
|
||||
import { maxPointsLeft } from '../lib/titleMath'
|
||||
|
||||
const STORAGE_PREFIX = 'box-box.champ.sim'
|
||||
|
||||
@@ -60,8 +61,8 @@ export function ChampionshipSimulator({ hub }: { hub: ChampionshipHub }) {
|
||||
}, [hub.season, scenario])
|
||||
|
||||
const projected = useMemo(
|
||||
() => projectStandings(hub.drivers, scenario, hub.rounds_left),
|
||||
[hub.drivers, scenario, hub.rounds_left],
|
||||
() => projectStandings(hub.drivers, scenario, hub.rounds_left, maxPointsLeft(hub)),
|
||||
[hub, scenario],
|
||||
)
|
||||
|
||||
if (hub.rounds_left <= 0 || hub.drivers.length === 0 || scenario.length === 0) {
|
||||
|
||||
@@ -122,11 +122,14 @@ export function pointsGapMeaning(
|
||||
gapToAhead: number | null | undefined,
|
||||
roundsLeft: number,
|
||||
driverAhead?: string | null,
|
||||
maxPointsLeft?: number,
|
||||
): MeaningAnnotation | null {
|
||||
if (gapToAhead == null || !Number.isFinite(gapToAhead) || gapToAhead <= 0) return null
|
||||
if (!Number.isFinite(roundsLeft) || roundsLeft <= 0) return null
|
||||
|
||||
const maxCatchable = roundsLeft * MAX_POINTS_PER_ROUND
|
||||
// Prefer the sprint-aware ceiling when the caller has it.
|
||||
const maxCatchable =
|
||||
maxPointsLeft != null && Number.isFinite(maxPointsLeft) ? maxPointsLeft : roundsLeft * MAX_POINTS_PER_ROUND
|
||||
const ahead = driverAhead?.trim() || 'ahead'
|
||||
|
||||
if (gapToAhead > maxCatchable) {
|
||||
|
||||
@@ -127,6 +127,8 @@ export function projectStandings(
|
||||
drivers: ReadonlyArray<ChampHubDriver>,
|
||||
scenario: Scenario,
|
||||
roundsLeft: number,
|
||||
/** Sprint-aware points ceiling; defaults to race wins only. */
|
||||
maxPointsLeft?: number,
|
||||
): ProjectedDriver[] {
|
||||
if (drivers.length === 0) return []
|
||||
|
||||
@@ -134,7 +136,10 @@ export function projectStandings(
|
||||
const ordered = championshipOrder(drivers)
|
||||
const leader = ordered[0]
|
||||
const leaderProjected = leader.points + (extras.get(leader.driver_number) ?? 0)
|
||||
const maxRemaining = MAX_POINTS_PER_ROUND * Math.max(0, roundsLeft)
|
||||
const maxRemaining =
|
||||
maxPointsLeft != null && Number.isFinite(maxPointsLeft)
|
||||
? Math.max(0, maxPointsLeft)
|
||||
: MAX_POINTS_PER_ROUND * Math.max(0, roundsLeft)
|
||||
|
||||
const rows = ordered.map((driver, i) => {
|
||||
const simPoints = extras.get(driver.driver_number) ?? 0
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// Title math shared by the championship views. Pure functions only.
|
||||
|
||||
import type { ChampHubDriver, ChampionshipHub } from '../types'
|
||||
|
||||
/** Max points one driver can take from a Grand Prix / a Sprint (2025+ rules). */
|
||||
export const MAX_RACE_POINTS = 25
|
||||
export const MAX_SPRINT_POINTS = 8
|
||||
|
||||
/**
|
||||
* Most points any one driver can still score this season. Prefers the
|
||||
* server's sprint-aware `max_points_left`; falls back to race wins only for
|
||||
* older API responses that do not carry it.
|
||||
*/
|
||||
export function maxPointsLeft(hub: Pick<ChampionshipHub, 'rounds_left' | 'max_points_left' | 'sprints_left'>): number {
|
||||
if (typeof hub.max_points_left === 'number' && Number.isFinite(hub.max_points_left)) {
|
||||
return Math.max(0, hub.max_points_left)
|
||||
}
|
||||
const rounds = Math.max(0, hub.rounds_left || 0)
|
||||
const sprints = Math.max(0, hub.sprints_left || 0)
|
||||
return rounds * MAX_RACE_POINTS + sprints * MAX_SPRINT_POINTS
|
||||
}
|
||||
|
||||
/** Grand Prix finishing-position counts (position -> count) from round_positions. */
|
||||
function finishCounts(positions: ReadonlyArray<number> | undefined): Map<number, number> {
|
||||
const counts = new Map<number, number>()
|
||||
for (const p of positions ?? []) {
|
||||
if (p > 0) counts.set(p, (counts.get(p) ?? 0) + 1)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
/**
|
||||
* True only when `leader` is guaranteed to beat `rival` on countback if the
|
||||
* rival wins every remaining Grand Prix and the leader scores nothing (the
|
||||
* only way the two can finish level when the gap equals the points left).
|
||||
* The leader's remaining finishes are unknown but outside the points, so a
|
||||
* countback decided in the leader's favour cannot be overturned by them.
|
||||
*/
|
||||
function leaderWinsWorstCaseCountback(leader: ChampHubDriver, rival: ChampHubDriver, roundsLeft: number): boolean {
|
||||
const lead = finishCounts(leader.round_positions)
|
||||
const riv = finishCounts(rival.round_positions)
|
||||
riv.set(1, (riv.get(1) ?? 0) + Math.max(0, roundsLeft))
|
||||
const maxPos = Math.max(0, ...lead.keys(), ...riv.keys())
|
||||
for (let p = 1; p <= maxPos; p++) {
|
||||
const diff = (lead.get(p) ?? 0) - (riv.get(p) ?? 0)
|
||||
if (diff !== 0) return diff > 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* The champion once the title is mathematically decided, else null.
|
||||
* `drivers` must be in championship order (ties already resolved by the
|
||||
* server's countback). Decided when the season is over, or when no rival can
|
||||
* catch the leader: every rival is further behind than the points left, or
|
||||
* exactly that far behind but certain to lose the countback.
|
||||
*/
|
||||
export function decidedChampion(
|
||||
drivers: ReadonlyArray<ChampHubDriver>,
|
||||
maxLeft: number,
|
||||
roundsLeft = 0,
|
||||
): ChampHubDriver | null {
|
||||
const [leader, ...rivals] = drivers
|
||||
if (!leader) return null
|
||||
if (maxLeft <= 0) return leader
|
||||
if (rivals.length === 0) return null
|
||||
for (const rival of rivals) {
|
||||
const gap = leader.points - rival.points
|
||||
if (gap > maxLeft) continue
|
||||
if (gap === maxLeft && leaderWinsWorstCaseCountback(leader, rival, roundsLeft)) continue
|
||||
return null
|
||||
}
|
||||
return leader
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { Meaning } from '../components/Meaning'
|
||||
import { TeammateH2H } from '../components/TeammateH2H'
|
||||
import { teammatePairs } from '../lib/h2h'
|
||||
import { pointsGapMeaning } from '../lib/meaning'
|
||||
import { decidedChampion, maxPointsLeft } from '../lib/titleMath'
|
||||
|
||||
type View = 'drivers' | 'constructors' | 'progression' | 'rivalry' | 'simulator'
|
||||
|
||||
@@ -130,7 +131,9 @@ interface BodyProps {
|
||||
function ChampionshipBody({ hub, view, setView }: BodyProps) {
|
||||
const { drivers, teams } = hub
|
||||
const leader = drivers[0]
|
||||
const remaining = hub.rounds_left * 25
|
||||
const remaining = maxPointsLeft(hub)
|
||||
const champion = decidedChampion(drivers, remaining, hub.rounds_left)
|
||||
const sprintsLeft = hub.sprints_left ?? 0
|
||||
|
||||
const enriched = useMemo<EnrichedDriver[]>(
|
||||
() =>
|
||||
@@ -149,21 +152,31 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
|
||||
spark: sparkPoints(d.form),
|
||||
h2h: `${d.teammate_wins}–${d.teammate_losses}`,
|
||||
h2hWin: d.teammate_wins >= d.teammate_losses,
|
||||
aliveLabel: i === 0 ? 'LEADS' : alive ? 'ALIVE' : 'OUT',
|
||||
aliveColor: i === 0 ? GOLD : alive ? 'var(--green)' : 'var(--text-3)',
|
||||
aliveLabel: i === 0 ? (champion ? 'CHAMPION' : 'LEADS') : alive && !champion ? 'ALIVE' : 'OUT',
|
||||
aliveColor: i === 0 ? GOLD : alive && !champion ? 'var(--green)' : 'var(--text-3)',
|
||||
}
|
||||
}),
|
||||
[drivers, leader, remaining],
|
||||
[drivers, leader, remaining, champion],
|
||||
)
|
||||
|
||||
const aliveCount = enriched.filter((e) => e.aliveLabel === 'ALIVE' || e.aliveLabel === 'LEADS').length
|
||||
|
||||
const titleMath =
|
||||
`${aliveCount} driver${aliveCount === 1 ? '' : 's'} can still mathematically win the title. ` +
|
||||
`With ${hub.rounds_left} round${hub.rounds_left === 1 ? '' : 's'} left (max ${remaining} pts), ` +
|
||||
`${leader.name_acronym} leads ` +
|
||||
const roundsLeftText = `${hub.rounds_left} round${hub.rounds_left === 1 ? '' : 's'}`
|
||||
const sprintsLeftText = sprintsLeft > 0 ? ` + ${sprintsLeft} sprint${sprintsLeft === 1 ? '' : 's'}` : ''
|
||||
const leadText =
|
||||
(drivers[1] ? `${drivers[1].name_acronym} by ${fmtPts(leader.points - drivers[1].points)}` : 'the field') +
|
||||
(drivers[2] ? ` and ${drivers[2].name_acronym} by ${fmtPts(leader.points - drivers[2].points)}.` : '.')
|
||||
(drivers[2] ? ` and ${drivers[2].name_acronym} by ${fmtPts(leader.points - drivers[2].points)}` : '')
|
||||
|
||||
const titleMath = champion
|
||||
? hub.rounds_left > 0
|
||||
? `${champion.full_name || champion.name_acronym} has clinched the ${hub.season} Drivers' Championship. ` +
|
||||
`${champion.name_acronym} leads ${leadText} with only ${fmtPts(remaining)} pts left ` +
|
||||
`(${roundsLeftText}${sprintsLeftText}).`
|
||||
: `${champion.full_name || champion.name_acronym} is the ${hub.season} World Champion, ` +
|
||||
`finishing ahead of ${leadText}.`
|
||||
: `${aliveCount} driver${aliveCount === 1 ? '' : 's'} can still mathematically win the title. ` +
|
||||
`With ${roundsLeftText}${sprintsLeftText} left (max ${fmtPts(remaining)} pts), ` +
|
||||
`${leader.name_acronym} leads ${leadText}.`
|
||||
|
||||
const topTeam = teams[0]
|
||||
const teamGap = teams[1] ? topTeam.points - teams[1].points : 0
|
||||
@@ -177,7 +190,9 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
|
||||
sub: teams[1] ? `+${fmtPts(teamGap)} ahead` : 'Sole entry',
|
||||
color: '#fff',
|
||||
},
|
||||
{ label: 'Title Fight', value: `${aliveCount} alive`, sub: `${hub.rounds_left} rounds remain`, color: 'var(--red)' },
|
||||
champion
|
||||
? { label: 'Champion', value: champion.name_acronym, sub: hub.rounds_left > 0 ? `Clinched · ${roundsLeftText} to spare` : 'Season complete', color: GOLD }
|
||||
: { label: 'Title Fight', value: `${aliveCount} alive`, sub: `${roundsLeftText} remain`, color: 'var(--red)' },
|
||||
{ label: 'Season Progress', value: `${seasonPct}%`, sub: `Round ${hub.round}/${hub.total_rounds}`, color: '#fff' },
|
||||
]
|
||||
|
||||
@@ -254,6 +269,7 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
|
||||
leaderPoints={leader.points}
|
||||
titleMath={titleMath}
|
||||
roundsLeft={hub.rounds_left}
|
||||
maxPointsLeft={remaining}
|
||||
drivers={drivers}
|
||||
season={hub.season}
|
||||
/>
|
||||
@@ -286,6 +302,7 @@ function DriversView({
|
||||
leaderPoints,
|
||||
titleMath,
|
||||
roundsLeft,
|
||||
maxPointsLeft,
|
||||
drivers,
|
||||
season,
|
||||
}: {
|
||||
@@ -293,6 +310,7 @@ function DriversView({
|
||||
leaderPoints: number
|
||||
titleMath: string
|
||||
roundsLeft: number
|
||||
maxPointsLeft: number
|
||||
drivers: ChampHubDriver[]
|
||||
season: number
|
||||
}) {
|
||||
@@ -423,7 +441,7 @@ function DriversView({
|
||||
<td className="r mono champ-td-muted">{e.gapLeader}</td>
|
||||
<td className="r mono champ-td-dim">
|
||||
{(() => {
|
||||
const gapAnnotation = pointsGapMeaning(e.gapAheadNum, roundsLeft, e.driverAhead)
|
||||
const gapAnnotation = pointsGapMeaning(e.gapAheadNum, roundsLeft, e.driverAhead, maxPointsLeft)
|
||||
return (
|
||||
<Meaning
|
||||
value={e.gapAhead}
|
||||
|
||||
@@ -118,6 +118,31 @@ describe('ChampionshipPage', () => {
|
||||
expect(screen.getAllByText('~10 pts/round').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('declares the champion once the gap exceeds the points left', async () => {
|
||||
// VER leads NOR by 40 with one round (25 pts) left and no sprints.
|
||||
mockFetchHub.mockResolvedValue({ ...hub, round: 9, rounds_left: 1, sprints_left: 0, max_points_left: 25 })
|
||||
renderPage()
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('championship')).toBeInTheDocument())
|
||||
|
||||
const titleMath = screen.getByTestId('champ-titlemath')
|
||||
expect(titleMath).toHaveTextContent('Max Verstappen has clinched the 2025 Drivers\' Championship')
|
||||
expect(titleMath).not.toHaveTextContent('can still mathematically win')
|
||||
expect(screen.getByText('CHAMPION')).toBeInTheDocument()
|
||||
expect(screen.queryByText('ALIVE')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the title open while sprint points can still close the gap', async () => {
|
||||
// 40-pt gap vs two rounds + a sprint (58 pts max): still open.
|
||||
mockFetchHub.mockResolvedValue({ ...hub, round: 8, rounds_left: 2, sprints_left: 1, max_points_left: 58 })
|
||||
renderPage()
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('championship')).toBeInTheDocument())
|
||||
|
||||
expect(screen.getByTestId('champ-titlemath')).toHaveTextContent('2 rounds + 1 sprint left (max 58 pts)')
|
||||
expect(screen.queryByText('CHAMPION')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('switches to constructors and progression views', async () => {
|
||||
renderPage()
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decidedChampion, maxPointsLeft } from '../lib/titleMath'
|
||||
import type { ChampHubDriver } from '../types'
|
||||
|
||||
const d = (driver_number: number, points: number, round_positions: number[] = []) =>
|
||||
({ driver_number, points, round_positions }) as ChampHubDriver
|
||||
|
||||
describe('maxPointsLeft', () => {
|
||||
it('prefers the server ceiling', () => {
|
||||
expect(maxPointsLeft({ rounds_left: 4, sprints_left: 1, max_points_left: 100 })).toBe(100)
|
||||
})
|
||||
it('falls back to races plus sprints for older responses', () => {
|
||||
expect(maxPointsLeft({ rounds_left: 4 })).toBe(100)
|
||||
expect(maxPointsLeft({ rounds_left: 4, sprints_left: 2 })).toBe(116)
|
||||
})
|
||||
})
|
||||
|
||||
describe('decidedChampion', () => {
|
||||
it('clinches when P2 cannot catch the leader', () => {
|
||||
// 2026 after Mexico City: ANT 380, VER 261, 4 rounds / no sprints left.
|
||||
expect(decidedChampion([d(12, 380), d(1, 261)], 100)?.driver_number).toBe(12)
|
||||
})
|
||||
it('stays open when the gap is reachable', () => {
|
||||
expect(decidedChampion([d(12, 380), d(1, 261)], 150)).toBeNull()
|
||||
// P2 is out of reach but P3 is not.
|
||||
expect(decidedChampion([d(12, 380), d(1, 261), d(44, 300)], 100)).toBeNull()
|
||||
})
|
||||
it('clinches on an exact gap when the leader wins the worst-case countback', () => {
|
||||
// 25-pt lead, one race left. Even if the rival wins it (3 wins) the leader has 5.
|
||||
expect(decidedChampion([d(12, 125, [1, 1, 1, 1, 1]), d(1, 100, [1, 1, 2, 2, 2])], 25, 1)?.driver_number).toBe(12)
|
||||
})
|
||||
it('stays open on an exact gap when the rival could win the countback', () => {
|
||||
// Rival would reach 3 wins vs the leader's 2.
|
||||
expect(decidedChampion([d(12, 125, [1, 1, 2, 2, 2]), d(1, 100, [1, 1, 3, 3, 3])], 25, 1)).toBeNull()
|
||||
// Level on wins and every other place: still open.
|
||||
expect(decidedChampion([d(12, 125, [1, 1, 2]), d(1, 100, [1, 2])], 25, 1)).toBeNull()
|
||||
})
|
||||
it('crowns the leader once nothing is left', () => {
|
||||
expect(decidedChampion([d(12, 400), d(1, 400)], 0)?.driver_number).toBe(12)
|
||||
})
|
||||
})
|
||||
@@ -444,6 +444,10 @@ export interface ChampionshipHub {
|
||||
round: number
|
||||
total_rounds: number
|
||||
rounds_left: number
|
||||
/** Sprint sessions still to run (absent on older servers). */
|
||||
sprints_left?: number
|
||||
/** Most points one driver can still score, races + sprints (absent on older servers). */
|
||||
max_points_left?: number
|
||||
last_race: string
|
||||
round_labels: string[]
|
||||
drivers: ChampHubDriver[]
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user