Compare commits

..
Author SHA1 Message Date
AmanTahilianiandCursor c736f8d353 fix(chapters): sync race-story titles after conflict trim
resolveConflicts already clips a still-open safety car so finish can
keep the last laps, but Title and EndTime stayed on the pre-trim
range. Rebuild range-bearing titles from the final laps and point
EndTime at the trimmed lap-index end.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 15:38:29 -04:00
14 changed files with 105 additions and 447 deletions

No files matched your search

@@ -10,7 +10,6 @@ import {
projectStandings,
} from '../lib/simulator'
import type { Scenario } from '../lib/simulator'
import { maxPointsLeft } from '../lib/titleMath'
const STORAGE_PREFIX = 'box-box.champ.sim'
@@ -61,8 +60,8 @@ export function ChampionshipSimulator({ hub }: { hub: ChampionshipHub }) {
}, [hub.season, scenario])
const projected = useMemo(
() => projectStandings(hub.drivers, scenario, hub.rounds_left, maxPointsLeft(hub)),
[hub, scenario],
() => projectStandings(hub.drivers, scenario, hub.rounds_left),
[hub.drivers, scenario, hub.rounds_left],
)
if (hub.rounds_left <= 0 || hub.drivers.length === 0 || scenario.length === 0) {
+1 -4
View File
@@ -122,14 +122,11 @@ 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
// Prefer the sprint-aware ceiling when the caller has it.
const maxCatchable =
maxPointsLeft != null && Number.isFinite(maxPointsLeft) ? maxPointsLeft : roundsLeft * MAX_POINTS_PER_ROUND
const maxCatchable = roundsLeft * MAX_POINTS_PER_ROUND
const ahead = driverAhead?.trim() || 'ahead'
if (gapToAhead > maxCatchable) {
+1 -6
View File
@@ -127,8 +127,6 @@ 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 []
@@ -136,10 +134,7 @@ export function projectStandings(
const ordered = championshipOrder(drivers)
const leader = ordered[0]
const leaderProjected = leader.points + (extras.get(leader.driver_number) ?? 0)
const maxRemaining =
maxPointsLeft != null && Number.isFinite(maxPointsLeft)
? Math.max(0, maxPointsLeft)
: MAX_POINTS_PER_ROUND * Math.max(0, roundsLeft)
const maxRemaining = MAX_POINTS_PER_ROUND * Math.max(0, roundsLeft)
const rows = ordered.map((driver, i) => {
const simPoints = extras.get(driver.driver_number) ?? 0
-74
View File
@@ -1,74 +0,0 @@
// 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
}
+11 -29
View File
@@ -10,7 +10,6 @@ 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'
@@ -131,9 +130,7 @@ interface BodyProps {
function ChampionshipBody({ hub, view, setView }: BodyProps) {
const { drivers, teams } = hub
const leader = drivers[0]
const remaining = maxPointsLeft(hub)
const champion = decidedChampion(drivers, remaining, hub.rounds_left)
const sprintsLeft = hub.sprints_left ?? 0
const remaining = hub.rounds_left * 25
const enriched = useMemo<EnrichedDriver[]>(
() =>
@@ -152,31 +149,21 @@ 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 ? (champion ? 'CHAMPION' : 'LEADS') : alive && !champion ? 'ALIVE' : 'OUT',
aliveColor: i === 0 ? GOLD : alive && !champion ? 'var(--green)' : 'var(--text-3)',
aliveLabel: i === 0 ? 'LEADS' : alive ? 'ALIVE' : 'OUT',
aliveColor: i === 0 ? GOLD : alive ? 'var(--green)' : 'var(--text-3)',
}
}),
[drivers, leader, remaining, champion],
[drivers, leader, remaining],
)
const aliveCount = enriched.filter((e) => e.aliveLabel === 'ALIVE' || e.aliveLabel === 'LEADS').length
const roundsLeftText = `${hub.rounds_left} round${hub.rounds_left === 1 ? '' : 's'}`
const sprintsLeftText = sprintsLeft > 0 ? ` + ${sprintsLeft} sprint${sprintsLeft === 1 ? '' : 's'}` : ''
const leadText =
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 ` +
(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)}` : '')
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}.`
(drivers[2] ? ` and ${drivers[2].name_acronym} by ${fmtPts(leader.points - drivers[2].points)}.` : '.')
const topTeam = teams[0]
const teamGap = teams[1] ? topTeam.points - teams[1].points : 0
@@ -190,9 +177,7 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
sub: teams[1] ? `+${fmtPts(teamGap)} ahead` : 'Sole entry',
color: '#fff',
},
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: 'Title Fight', value: `${aliveCount} alive`, sub: `${hub.rounds_left} rounds remain`, color: 'var(--red)' },
{ label: 'Season Progress', value: `${seasonPct}%`, sub: `Round ${hub.round}/${hub.total_rounds}`, color: '#fff' },
]
@@ -269,7 +254,6 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
leaderPoints={leader.points}
titleMath={titleMath}
roundsLeft={hub.rounds_left}
maxPointsLeft={remaining}
drivers={drivers}
season={hub.season}
/>
@@ -302,7 +286,6 @@ function DriversView({
leaderPoints,
titleMath,
roundsLeft,
maxPointsLeft,
drivers,
season,
}: {
@@ -310,7 +293,6 @@ function DriversView({
leaderPoints: number
titleMath: string
roundsLeft: number
maxPointsLeft: number
drivers: ChampHubDriver[]
season: number
}) {
@@ -441,7 +423,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, maxPointsLeft)
const gapAnnotation = pointsGapMeaning(e.gapAheadNum, roundsLeft, e.driverAhead)
return (
<Meaning
value={e.gapAhead}
@@ -118,31 +118,6 @@ 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()
-41
View File
@@ -1,41 +0,0 @@
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)
})
})
-4
View File
@@ -444,10 +444,6 @@ 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[]
+33 -5
View File
@@ -72,7 +72,7 @@ func Detect(rc []RaceControl, positions []PositionSample, laps []Lap, totalLaps
chapters = append(chapters, detectDecisiveSwings(positions, lapIndex, totalLaps)...)
chapters = append(chapters, detectFinish(rc, lapIndex, totalLaps))
return resolveConflicts(chapters)
return resolveConflicts(chapters, lapIndex)
}
func normalizeTotalLaps(totalLaps int, laps []Lap, rc []RaceControl) int {
@@ -321,7 +321,7 @@ func detectPitPhases(laps []Lap, idx lapIndex) []Chapter {
}
ch := Chapter{
Kind: KindPitPhase,
Title: fmt.Sprintf("Pit phase (L%d-L%d)", start, end),
Title: pitPhaseTitle(start, end),
StartLap: start,
EndLap: end,
StartTime: idx.lapStart(start),
@@ -339,7 +339,7 @@ func detectPitPhases(laps []Lap, idx lapIndex) []Chapter {
drivers[driver] = true
}
last.DriverNumbers = sortedDriverNumbers(drivers)
last.Title = fmt.Sprintf("Pit phase (L%d-L%d)", last.StartLap, last.EndLap)
last.Title = pitPhaseTitle(last.StartLap, last.EndLap)
continue
}
windows = append(windows, ch)
@@ -479,7 +479,7 @@ func detectFinish(rc []RaceControl, idx lapIndex, totalLaps int) Chapter {
}
return Chapter{
Kind: KindFinish,
Title: fmt.Sprintf("Finish (L%d-L%d)", startLap, finishLap),
Title: finishTitle(startLap, finishLap),
StartLap: startLap,
EndLap: finishLap,
StartTime: idx.lapStart(startLap),
@@ -487,7 +487,31 @@ func detectFinish(rc []RaceControl, idx lapIndex, totalLaps int) Chapter {
}
}
func resolveConflicts(chapters []Chapter) []Chapter {
func pitPhaseTitle(startLap, endLap int) string {
return fmt.Sprintf("Pit phase (L%d-L%d)", startLap, endLap)
}
func finishTitle(startLap, endLap int) string {
return fmt.Sprintf("Finish (L%d-L%d)", startLap, endLap)
}
// titleForResolved rebuilds range-bearing titles from the final StartLap/EndLap
// after conflict resolution. Flag and pit-phase formatters are reused so stale
// pre-trim strings are never parsed.
func titleForResolved(ch Chapter) string {
switch ch.Kind {
case KindSafetyCar, KindVirtualSafetyCar, KindRedFlag:
return flagTitle(ch.Kind, ch.StartLap, ch.EndLap)
case KindPitPhase:
return pitPhaseTitle(ch.StartLap, ch.EndLap)
case KindFinish:
return finishTitle(ch.StartLap, ch.EndLap)
default:
return ch.Title
}
}
func resolveConflicts(chapters []Chapter, idx lapIndex) []Chapter {
normalized := make([]Chapter, 0, len(chapters))
for _, ch := range chapters {
if ch.StartLap <= 0 {
@@ -528,6 +552,7 @@ func resolveConflicts(chapters []Chapter) []Chapter {
if priority(ch.Kind) > priority(last.Kind) {
if last.StartLap < ch.StartLap {
last.EndLap = ch.StartLap - 1
last.EndTime = idx.lapEnd(last.EndLap)
out = append(out, ch)
} else {
*last = ch
@@ -541,6 +566,9 @@ func resolveConflicts(chapters []Chapter) []Chapter {
}
}
}
for i := range out {
out[i].Title = titleForResolved(out[i])
}
return out
}
+36
View File
@@ -125,6 +125,42 @@ func TestDetectDecisiveSwingPersistsToFinish(t *testing.T) {
}
}
func TestDetectSafetyCarTrimmedForFinishRewritesTitle(t *testing.T) {
rcs := []RaceControl{
rc(3, models.CategorySafetyCar, "", "SAFETY CAR DEPLOYED"),
rc(72, models.CategoryFlag, models.FlagChequered, "CHEQUERED FLAG"),
}
got := Detect(rcs, nil, testLaps(72, nil), 72)
sc := findKind(got, KindSafetyCar)
if sc == nil {
t.Fatalf("chapters = %+v, want safety car", got)
}
if sc.StartLap != 3 || sc.EndLap != 70 || sc.Title != "Safety Car (L3-L70)" {
t.Fatalf("safety car = %+v, want StartLap=3 EndLap=70 Title=%q", *sc, "Safety Car (L3-L70)")
}
if wantEnd := lapTime(71); sc.EndTime != wantEnd {
t.Fatalf("safety car EndTime = %q, want lap-index end of L70 (%q)", sc.EndTime, wantEnd)
}
fin := findKind(got, KindFinish)
if fin == nil || fin.StartLap != 71 || fin.EndLap != 72 {
t.Fatalf("finish = %+v, want L71-L72", got)
}
for i := 1; i < len(got); i++ {
if got[i].StartLap <= got[i-1].EndLap {
t.Fatalf("chapters overlap at %d: %+v then %+v", i, got[i-1], got[i])
}
}
headed := ApplyHeadlines(got, nil, rcs, 0)
if scH := findKind(headed, KindSafetyCar); scH == nil || scH.Headline != "Safety Car (L3-L70)" {
t.Fatalf("headline = %+v, want fallback to resolved title Safety Car (L3-L70)", headed)
}
}
func TestDetectFlagPeriodsWinOverConflictingChapters(t *testing.T) {
pitOuts := map[int][]int{
12: {1, 2},
+2 -56
View File
@@ -15,11 +15,6 @@ 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.
@@ -54,19 +49,11 @@ 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
@@ -75,9 +62,6 @@ 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") {
@@ -114,14 +98,6 @@ 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
@@ -137,12 +113,6 @@ 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
@@ -187,7 +157,7 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
_ = raceGrid
}
inputs.Champ = derivedDriverStandings(pointsByDriver, finishesByDriver, latestMeetingKey, latestSessionKey)
inputs.Champ = derivedDriverStandings(pointsByDriver, latestMeetingKey, latestSessionKey)
inputs.Teams = derivedTeamStandings(pointsByTeam, latestMeetingKey, latestSessionKey)
return inputs, nil
}
@@ -212,10 +182,7 @@ func (s *Service) driversForSession(sessionKey int) ([]models.Driver, error) {
return drivers, nil
}
// 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 {
func derivedDriverStandings(points map[int]float64, meetingKey, sessionKey int) []models.ChampionshipDriver {
drivers := make([]models.ChampionshipDriver, 0, len(points))
for num, pts := range points {
drivers = append(drivers, models.ChampionshipDriver{
@@ -227,9 +194,6 @@ func derivedDriverStandings(points map[int]float64, finishes map[int]map[int]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
@@ -240,24 +204,6 @@ func derivedDriverStandings(points map[int]float64, finishes map[int]map[int]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,64 +428,3 @@ 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)
}
}
+19 -67
View File
@@ -697,19 +697,14 @@ type champHubTeam struct {
}
type champHubResponse struct {
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"`
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"`
}
// meetingRace bundles a GP meeting with its (already-fetched) race results and grid.
@@ -718,17 +713,8 @@ 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
@@ -894,8 +880,6 @@ 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
@@ -959,14 +943,6 @@ 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) {
@@ -976,15 +952,10 @@ func fetchSeasonRaces(client *api.OpenF1Client, year int) (races []meetingRace,
return meetingRace{}, false
}
raceKey := 0
sprintKey := 0
for _, sess := range sessions {
if sess.IsCancelled {
continue
}
if strings.EqualFold(sess.SessionName, "Race") && raceKey == 0 {
if strings.EqualFold(sess.SessionName, "Race") {
raceKey = sess.SessionKey
} else if strings.EqualFold(sess.SessionName, "Sprint") && sprintKey == 0 {
sprintKey = sess.SessionKey
break
}
}
if raceKey == 0 {
@@ -1002,19 +973,7 @@ func fetchSeasonRaces(client *api.OpenF1Client, year int) (races []meetingRace,
if rerr != nil || gerr != nil {
failed.Store(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 meetingRace{Meeting: m, RaceSessionKey: raceKey, Results: results, Grid: grid}, true
})
return races, failed.Load(), nil
}
@@ -1068,15 +1027,11 @@ 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++
@@ -1222,18 +1177,15 @@ func aggregateChampionshipHub(
}
totalRounds := len(races)
roundsLeft := totalRounds - completed
return champHubResponse{
Season: year,
Round: completed,
TotalRounds: totalRounds,
RoundsLeft: roundsLeft,
SprintsLeft: sprintsLeft,
MaxPointsLeft: float64(maxRacePoints*roundsLeft + maxSprintPoints*sprintsLeft),
LastRace: lastRace,
RoundLabels: roundLabels,
Drivers: drivers,
Teams: teamsOut,
Season: year,
Round: completed,
TotalRounds: totalRounds,
RoundsLeft: totalRounds - completed,
LastRace: lastRace,
RoundLabels: roundLabels,
Drivers: drivers,
Teams: teamsOut,
}
}
-72
View File
@@ -406,75 +406,3 @@ 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)
}
}