brackt/app/services/simulations/tennis-simulator.ts

376 lines
15 KiB
TypeScript
Raw Normal View History

/**
* Tennis Grand Slam Simulator
*
* Monte Carlo simulation of the 4 Grand Slam majors using surface-specific Elo
* ratings. Qualifying points (QP) are accumulated across all majors; the final
* QP totals determine fantasy placements (1st8th).
*
* Algorithm:
* 1. Load the 4 Grand Slam scoring events (type = major_tournament).
* 2. For complete majors, read actual qualifyingPointsAwarded from eventResults.
* 3. For incomplete majors, simulate the 128-player seeded bracket.
* 4. Accumulate QP per player across all 4 majors in each simulation.
* 5. Rank players by total QP; tally 1st8th placement counts.
* 6. Return normalized SimulationResult[].
*
* QP per round (tie-splitting pre-applied per the rules):
* Winner 20 QP
* Finalist 14 QP
* SF loser ×2 9 QP each ((10+8)/2)
* QF loser ×4 4 QP each ((5+5+3+3)/4)
* R16 loser ×8 1.5 QP each ((2+2+2+2+1+1+1+1)/8)
* Earlier losers 0 QP
*
* Seeded draw (128 players, top 32 seeded by ATP/WTA world ranking):
* Seed 1 slot 0 (top of top half)
* Seed 2 slot 64 (top of bottom half) can only meet seed 1 in final
* Seeds 34 slots 32, 96 (quarter tops), randomly drawn
* Seeds 58 slots 16, 48, 80, 112 (eighth tops), randomly drawn
* Seeds 916 slots 8, 24, 40, 56, 72, 88, 104, 120 (sixteenth tops), randomly drawn
* Seeds 1732 slots 4, 12, 20, 28, 36, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124, randomly drawn
* Remaining 96 all remaining slots, randomly placed
*
* Surface mapping (matched against scoring event names):
* "Australian Open" hard
* "French Open" / "Roland Garros" clay
* "Wimbledon" grass
* "US Open" hard
*/
import { database } from "~/database/context";
import { eq, and, inArray } from "drizzle-orm";
import * as schema from "~/database/schema";
import { getSurfaceEloMap } from "~/models/surface-elo";
import type { Simulator, SimulationResult } from "./types";
// ─── Simulation parameters ────────────────────────────────────────────────────
const NUM_SIMULATIONS = 10_000;
/**
* Elo divisor for per-match win probability.
* Standard chess Elo uses 400. A single tennis match is modelled as one Elo
* contest (no multi-game Bernoulli model needed), so 400 is appropriate.
* A 200-point Elo gap ~76% win probability; a 400-point gap ~91%.
*/
const ELO_DIVISOR = 400;
/** Fallback Elo for players with no stored surface rating. */
const FALLBACK_ELO = 1500;
// ─── QP constants (tie-splitting pre-applied) ─────────────────────────────────
const QP_WINNER = 20;
const QP_FINALIST = 14;
const QP_SF_LOSER = 9; // (10 + 8) / 2
const QP_QF_LOSER = 4; // (5 + 5 + 3 + 3) / 4
const QP_R16_LOSER = 1.5; // (2 + 2 + 2 + 2 + 1 + 1 + 1 + 1) / 8
// ─── Seeding draw slot positions ──────────────────────────────────────────────
const SEED1_SLOT = 0;
const SEED2_SLOT = 64;
const SEEDS_3_4_SLOTS = [32, 96] as const;
const SEEDS_5_8_SLOTS = [16, 48, 80, 112] as const;
const SEEDS_9_16_SLOTS = [8, 24, 40, 56, 72, 88, 104, 120] as const;
const SEEDS_17_32_SLOTS = [4, 12, 20, 28, 36, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124] as const;
// ─── Surface mapping ──────────────────────────────────────────────────────────
type CourtSurface = "hard" | "clay" | "grass";
const SLAM_SURFACES: Array<{ fragments: string[]; surface: CourtSurface }> = [
{ fragments: ["australian open"], surface: "hard" },
{ fragments: ["french open", "roland garros"], surface: "clay" },
{ fragments: ["wimbledon"], surface: "grass" },
{ fragments: ["us open"], surface: "hard" },
];
function getSurfaceForEvent(eventName: string): CourtSurface {
const lower = eventName.toLowerCase();
for (const { fragments, surface } of SLAM_SURFACES) {
if (fragments.some((f) => lower.includes(f))) return surface;
}
// Default to hard court if the name doesn't match — admin should use standard names.
return "hard";
}
// ─── Math helpers ─────────────────────────────────────────────────────────────
/**
* Per-match win probability for player 1 vs player 2 based on their Elo ratings.
* Uses the standard logistic function: p = 1 / (1 + 10^((R2 - R1) / ELO_DIVISOR))
* Exported for unit testing.
*/
export function eloWinProb(elo1: number, elo2: number): number {
return 1 / (1 + Math.pow(10, (elo2 - elo1) / ELO_DIVISOR));
}
/** Fisher-Yates in-place shuffle. Returns the array for chaining. */
function shuffle<T>(arr: T[]): T[] {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
// ─── Draw builder ─────────────────────────────────────────────────────────────
/**
* Build one seeded 128-slot draw for a major.
*
* Returns an array of 128 participant IDs in bracket order: pairs [0,1],
* [2,3], ... are R1 matches. Consecutive R1 winners form R2 matchups, etc.
* Seeds 132 are determined by ATP/WTA world ranking (ascending, 1 = top seed).
* Players with no world ranking are treated as unseeded (random placement).
* Remaining 96 unseeded players are placed randomly.
* Caller must pass exactly 128 participant IDs.
*/
export function buildDraw(
participantIds: string[],
eloMap: Map<string, { worldRanking: number | null; eloHard: number | null; eloClay: number | null; eloGrass: number | null } | undefined>
): string[] {
// Sort by world ranking ascending (lower number = better seed).
// Players with no ranking sort to the end (unseeded).
const sorted = [...participantIds].toSorted((a, b) => {
const ra = eloMap.get(a)?.worldRanking ?? Infinity;
const rb = eloMap.get(b)?.worldRanking ?? Infinity;
return ra - rb;
});
const seeds = sorted.slice(0, 32);
const unseeded = sorted.slice(32);
const slots: (string | null)[] = Array(128).fill(null);
// Seed 1 and 2 in opposite halves.
slots[SEED1_SLOT] = seeds[0];
slots[SEED2_SLOT] = seeds[1];
// Seeds 34: randomly into the two remaining quarter tops.
const q34 = shuffle([...SEEDS_3_4_SLOTS]);
slots[q34[0]] = seeds[2];
slots[q34[1]] = seeds[3];
// Seeds 58: randomly into the four remaining eighth tops.
const e58 = shuffle([...SEEDS_5_8_SLOTS]);
for (let i = 0; i < 4; i++) slots[e58[i]] = seeds[4 + i];
// Seeds 916: randomly into the eight remaining sixteenth tops.
const s916 = shuffle([...SEEDS_9_16_SLOTS]);
for (let i = 0; i < 8; i++) slots[s916[i]] = seeds[8 + i];
// Seeds 1732: randomly into the 16 remaining 32nd-section tops.
const s1732 = shuffle([...SEEDS_17_32_SLOTS]);
for (let i = 0; i < 16; i++) slots[s1732[i]] = seeds[16 + i];
// Fill remaining 96 slots with the unseeded players in random order.
const openSlots = slots.reduce<number[]>((acc, v, i) => { if (v === null) acc.push(i); return acc; }, []);
const shuffledUnseeded = shuffle([...unseeded]);
shuffledUnseeded.forEach((player, i) => { slots[openSlots[i]] = player; });
return slots as string[];
}
// ─── Single-major bracket simulation ──────────────────────────────────────────
interface QPResult {
participantId: string;
qp: number;
}
/**
* Simulate one Grand Slam major and return QP earned per participant.
* The draw is a pre-shuffled 128-slot array from buildDraw().
* Exported for unit testing.
*/
export function simulateMajor(draw: string[], eloMap: Map<string, { worldRanking: number | null; eloHard: number | null; eloClay: number | null; eloGrass: number | null } | undefined>, surface: CourtSurface): QPResult[] {
const qp = new Map<string, number>(draw.map((id) => [id, 0]));
const getElo = (id: string): number => {
const e = eloMap.get(id);
if (!e) return FALLBACK_ELO;
const v = surface === "hard" ? e.eloHard : surface === "clay" ? e.eloClay : e.eloGrass;
return v ?? FALLBACK_ELO;
};
const simMatch = (p1: string, p2: string): { winner: string; loser: string } => {
const p = eloWinProb(getElo(p1), getElo(p2));
const winner = Math.random() < p ? p1 : p2;
return { winner, loser: winner === p1 ? p2 : p1 };
};
// 7 rounds: R1(64 matches) R2(32) R3(16) R16(8) QF(4) SF(2) Final(1)
let current = [...draw]; // 128 players
// Rounds 13 award 0 QP; just advance winners.
for (let round = 0; round < 3; round++) {
const next: string[] = [];
for (let i = 0; i < current.length; i += 2) {
const { winner } = simMatch(current[i], current[i + 1]);
next.push(winner);
}
current = next;
}
// R16: 8 matches, losers get 1.5 QP each.
{
const next: string[] = [];
for (let i = 0; i < current.length; i += 2) {
const { winner, loser } = simMatch(current[i], current[i + 1]);
qp.set(loser, (qp.get(loser) ?? 0) + QP_R16_LOSER);
next.push(winner);
}
current = next;
}
// QF: 4 matches, losers get 4 QP each.
{
const next: string[] = [];
for (let i = 0; i < current.length; i += 2) {
const { winner, loser } = simMatch(current[i], current[i + 1]);
qp.set(loser, (qp.get(loser) ?? 0) + QP_QF_LOSER);
next.push(winner);
}
current = next;
}
// SF: 2 matches, losers get 9 QP each.
{
const next: string[] = [];
for (let i = 0; i < current.length; i += 2) {
const { winner, loser } = simMatch(current[i], current[i + 1]);
qp.set(loser, (qp.get(loser) ?? 0) + QP_SF_LOSER);
next.push(winner);
}
current = next;
}
// Final: 1 match.
const { winner: champion, loser: finalist } = simMatch(current[0], current[1]);
qp.set(champion, (qp.get(champion) ?? 0) + QP_WINNER);
qp.set(finalist, (qp.get(finalist) ?? 0) + QP_FINALIST);
return Array.from(qp.entries()).map(([participantId, qpVal]) => ({ participantId, qp: qpVal }));
}
// ─── Simulator ────────────────────────────────────────────────────────────────
export class TennisSimulator implements Simulator {
async simulate(sportsSeasonId: string): Promise<SimulationResult[]> {
const db = database();
// 1. Load all participants for this sports season.
const allParticipants = await db
Canonical tournament layer: schema + backfill (1/2) (#365) * refactor(schema): rename per-window tables to season_* prefix Renames participants, participant_expected_values, participant_qualifying_totals, participant_results, participant_surface_elos to season_* prefixed names. Renames event_results.participant_id to season_participant_id. Phase 1a of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: rename participant.ts model file to season-participant.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(models): update model layer to use renamed schema exports Updated all model files to use the renamed schema exports from Task 1: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantQualifyingTotals → seasonParticipantQualifyingTotals - participantResults → seasonParticipantResults - participantSurfaceElos → seasonParticipantSurfaceElos - eventResults.participantId → eventResults.seasonParticipantId - db.query relation accessors updated - Relation field .participant → .seasonParticipant where applicable - Import paths updated: ./participant → ./season-participant Files updated (14 model files + 3 test files): - draft-pick.ts - draft-utils.ts - event-result.ts - group-stage-match.ts - participant-result.ts - qualifying-points.ts - scoring-calculator.ts - scoring-event.ts - sports-season.ts - surface-elo.ts - team-score-events.ts - cs2-major-stage.ts - golf-skills.ts - participant-expected-value.ts - __tests__/sports-season.clone.test.ts - __tests__/auto-pick.test.ts - __tests__/executeAutoPick.timer.test.ts Typecheck errors decreased: 779 → 499 (280 fewer) All model file errors related to renamed schemas resolved. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route layer to use renamed schema exports - Update model import from ~/models/participant to ~/models/season-participant - Rename schema.participants to schema.seasonParticipants - Rename schema.participantResults to schema.seasonParticipantResults - Rename db.query.participants to db.query.seasonParticipants - Update 9 route files and 1 test file Affected files: - admin.sports-seasons.$id.events.$eventId.bracket.server.ts - admin.sports-seasons.$id.participants.tsx - api/draft.force-manual-pick.ts - api/draft.make-pick.ts - api/draft.replace-pick.ts - api/seasons.$seasonId.draft.ts - leagues/$leagueId.draft-board.$seasonId.tsx - leagues/$leagueId.sports-seasons.$sportsSeasonId.server.ts - admin/__tests__/sports-seasons-participants.test.ts Error count reduced from 499 to 453 (46 errors fixed). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route files for schema rename Update route imports from ~/models/participant to ~/models/season-participant and fix references to .participant/.participantId on event results to use .seasonParticipant/.seasonParticipantId after schema rename. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(services): update simulators and services for renamed schema Update all simulators, services, and server files to use renamed schema tables: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantResults → seasonParticipantResults - eventResults.participantId → eventResults.seasonParticipantId Files updated: - 20 sport simulators (NBA, NHL, NFL, MLB, etc.) - probability-updater.ts - standings-sync/index.ts - sports-data-sync.server.ts - server/socket.ts Typecheck errors reduced from 365 to 0. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: rename per-window tables to season_* prefix * fix(tests): update mock query keys after participants table rename Change mock db.query.participants to db.query.seasonParticipants in test files to match the schema rename from commit 66145a9. This fixes "Cannot read properties of undefined (reading 'findFirst'/'findMany')" errors that occurred when production code queries db.query.seasonParticipants but test mocks only defined the old participants key. Files updated: - app/services/simulations/__tests__/world-cup-simulator.test.ts - app/routes/api/__tests__/draft.force-manual-pick.test.ts - app/routes/api/__tests__/draft.force-manual-pick.timer-mode.test.ts - app/routes/api/__tests__/draft.make-pick.timer-mode.test.ts - server/__tests__/timer-autodraft.test.ts - app/models/__tests__/team-score-events.test.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update remaining mock paths and keys after schema rename * fix(tests): final two mock stragglers after schema rename - draft-pick.test.ts: assertion on db.query.participantQualifyingTotals - process-match-result.test.ts: mock key participants → seasonParticipants Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore: add post-phase1a baseline capture (temp, for diff verification) * chore: capture pre-migration baselines * chore: remove post-phase1a capture helper after verification * schema: add canonical tournament & participant tables Adds tournaments, participants (canonical), tournament_results, and participant_surface_elos (canonical). Adds nullable tournament_id to scoring_events and nullable participant_id to season_participants. Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(models): add canonical tournament, participant, result, surface-elo models Adds CRUD modules for the canonical tables created in commit 775b905. Each module mirrors existing app/models conventions (database() from ~/database/context, schema from ~/database/schema, mock-based tests). Key implementation notes: - participant.ts exports use "Canonical" prefix (CanonicalParticipant, createCanonicalParticipant, etc.) to avoid collision with existing season-participant.ts exports - All four models include comprehensive unit tests following the audit-log.test.ts pattern - Tests use mocked db responses (no real database access) - Upsert functions use onConflictDoUpdate for appropriate unique constraints Part of Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: create canonical tables, add nullable FKs * scripts: add extractTournamentIdentity helper for backfill Pure function that derives canonical (name, year) identity from a scoring_events row, stripping trailing 4-digit years from the name or falling back to eventDate. Used by the Phase 2 backfill to group per-window events into canonical tournaments. * scripts: add backfill orchestrator for canonical layer Populates canonical tournaments, participants, tournament_results, and participant_surface_elos from per-window data for qualifying-points sports. Skips already-linked rows, is idempotent, and supports dry-run mode. Critical invariants enforced by the implementation: - qualifying_points_awarded is never copied to tournament_results - season_participant_qualifying_totals is never touched - conflicting surface-Elo values between windows raise a loud error (recorded in report.errors) rather than overwriting * scripts: add backfill CLI with dry-run default Wires backfill-canonical-layer.ts to a CLI entry point exposed as `npm run backfill:canonical`. Defaults to --dry-run; requires --apply to actually write. Supports --sport=<uuid> to limit to a single sport. Exits 2 if the backfill reports errors (e.g., surface-Elo conflicts). * fix(backfill-cli): wrap runBackfill in DatabaseContext.run The orchestrator uses database() from ~/database/context, which requires AsyncLocalStorage to be populated. Wrap the CLI invocation with DatabaseContext.run(db, ...) using server/db's cached connection pool. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(backfill-cli): exit 0 on success so pg pool doesn't block The cached postgres connection pool keeps the Node event loop open after main() returns. Explicit process.exit(0) on success mirrors the pattern in scripts/capture-baseline.ts. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Chris Parsons <chrisp@extrahop.com> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-01 20:13:18 -07:00
.select({ id: schema.seasonParticipants.id })
.from(schema.seasonParticipants)
.where(eq(schema.seasonParticipants.sportsSeasonId, sportsSeasonId));
if (allParticipants.length < 128) {
throw new Error(
`Tennis simulation requires at least 128 participants (got ${allParticipants.length}). ` +
`Ensure all 128 draw entries are added as participants before simulating.`
);
}
const participantIds = allParticipants.map((p) => p.id);
// 2. Load surface Elo ratings.
const surfaceEloMap = await getSurfaceEloMap(sportsSeasonId);
// 3. Load Grand Slam scoring events ordered by date.
const events = await db.query.scoringEvents.findMany({
where: and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
eq(schema.scoringEvents.eventType, "major_tournament")
),
orderBy: (e, { asc }) => [asc(e.eventDate)],
});
if (events.length === 0) {
throw new Error(
`No major_tournament scoring events found for sports season ${sportsSeasonId}. ` +
`Create the 4 Grand Slam events first (e.g., "Australian Open", "French Open", ` +
`"Wimbledon", "US Open").`
);
}
// 4. For complete events, read actual QP from eventResults.
// Map: participantId → totalActualQP (across all completed majors).
const completedEventIds = events
.filter((e) => e.isComplete)
.map((e) => e.id);
const actualQPMap = new Map<string, number>(participantIds.map((id) => [id, 0]));
if (completedEventIds.length > 0) {
const actualResults = await db
.select({
Canonical tournament layer: schema + backfill (1/2) (#365) * refactor(schema): rename per-window tables to season_* prefix Renames participants, participant_expected_values, participant_qualifying_totals, participant_results, participant_surface_elos to season_* prefixed names. Renames event_results.participant_id to season_participant_id. Phase 1a of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: rename participant.ts model file to season-participant.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(models): update model layer to use renamed schema exports Updated all model files to use the renamed schema exports from Task 1: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantQualifyingTotals → seasonParticipantQualifyingTotals - participantResults → seasonParticipantResults - participantSurfaceElos → seasonParticipantSurfaceElos - eventResults.participantId → eventResults.seasonParticipantId - db.query relation accessors updated - Relation field .participant → .seasonParticipant where applicable - Import paths updated: ./participant → ./season-participant Files updated (14 model files + 3 test files): - draft-pick.ts - draft-utils.ts - event-result.ts - group-stage-match.ts - participant-result.ts - qualifying-points.ts - scoring-calculator.ts - scoring-event.ts - sports-season.ts - surface-elo.ts - team-score-events.ts - cs2-major-stage.ts - golf-skills.ts - participant-expected-value.ts - __tests__/sports-season.clone.test.ts - __tests__/auto-pick.test.ts - __tests__/executeAutoPick.timer.test.ts Typecheck errors decreased: 779 → 499 (280 fewer) All model file errors related to renamed schemas resolved. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route layer to use renamed schema exports - Update model import from ~/models/participant to ~/models/season-participant - Rename schema.participants to schema.seasonParticipants - Rename schema.participantResults to schema.seasonParticipantResults - Rename db.query.participants to db.query.seasonParticipants - Update 9 route files and 1 test file Affected files: - admin.sports-seasons.$id.events.$eventId.bracket.server.ts - admin.sports-seasons.$id.participants.tsx - api/draft.force-manual-pick.ts - api/draft.make-pick.ts - api/draft.replace-pick.ts - api/seasons.$seasonId.draft.ts - leagues/$leagueId.draft-board.$seasonId.tsx - leagues/$leagueId.sports-seasons.$sportsSeasonId.server.ts - admin/__tests__/sports-seasons-participants.test.ts Error count reduced from 499 to 453 (46 errors fixed). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route files for schema rename Update route imports from ~/models/participant to ~/models/season-participant and fix references to .participant/.participantId on event results to use .seasonParticipant/.seasonParticipantId after schema rename. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(services): update simulators and services for renamed schema Update all simulators, services, and server files to use renamed schema tables: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantResults → seasonParticipantResults - eventResults.participantId → eventResults.seasonParticipantId Files updated: - 20 sport simulators (NBA, NHL, NFL, MLB, etc.) - probability-updater.ts - standings-sync/index.ts - sports-data-sync.server.ts - server/socket.ts Typecheck errors reduced from 365 to 0. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: rename per-window tables to season_* prefix * fix(tests): update mock query keys after participants table rename Change mock db.query.participants to db.query.seasonParticipants in test files to match the schema rename from commit 66145a9. This fixes "Cannot read properties of undefined (reading 'findFirst'/'findMany')" errors that occurred when production code queries db.query.seasonParticipants but test mocks only defined the old participants key. Files updated: - app/services/simulations/__tests__/world-cup-simulator.test.ts - app/routes/api/__tests__/draft.force-manual-pick.test.ts - app/routes/api/__tests__/draft.force-manual-pick.timer-mode.test.ts - app/routes/api/__tests__/draft.make-pick.timer-mode.test.ts - server/__tests__/timer-autodraft.test.ts - app/models/__tests__/team-score-events.test.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update remaining mock paths and keys after schema rename * fix(tests): final two mock stragglers after schema rename - draft-pick.test.ts: assertion on db.query.participantQualifyingTotals - process-match-result.test.ts: mock key participants → seasonParticipants Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore: add post-phase1a baseline capture (temp, for diff verification) * chore: capture pre-migration baselines * chore: remove post-phase1a capture helper after verification * schema: add canonical tournament & participant tables Adds tournaments, participants (canonical), tournament_results, and participant_surface_elos (canonical). Adds nullable tournament_id to scoring_events and nullable participant_id to season_participants. Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(models): add canonical tournament, participant, result, surface-elo models Adds CRUD modules for the canonical tables created in commit 775b905. Each module mirrors existing app/models conventions (database() from ~/database/context, schema from ~/database/schema, mock-based tests). Key implementation notes: - participant.ts exports use "Canonical" prefix (CanonicalParticipant, createCanonicalParticipant, etc.) to avoid collision with existing season-participant.ts exports - All four models include comprehensive unit tests following the audit-log.test.ts pattern - Tests use mocked db responses (no real database access) - Upsert functions use onConflictDoUpdate for appropriate unique constraints Part of Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: create canonical tables, add nullable FKs * scripts: add extractTournamentIdentity helper for backfill Pure function that derives canonical (name, year) identity from a scoring_events row, stripping trailing 4-digit years from the name or falling back to eventDate. Used by the Phase 2 backfill to group per-window events into canonical tournaments. * scripts: add backfill orchestrator for canonical layer Populates canonical tournaments, participants, tournament_results, and participant_surface_elos from per-window data for qualifying-points sports. Skips already-linked rows, is idempotent, and supports dry-run mode. Critical invariants enforced by the implementation: - qualifying_points_awarded is never copied to tournament_results - season_participant_qualifying_totals is never touched - conflicting surface-Elo values between windows raise a loud error (recorded in report.errors) rather than overwriting * scripts: add backfill CLI with dry-run default Wires backfill-canonical-layer.ts to a CLI entry point exposed as `npm run backfill:canonical`. Defaults to --dry-run; requires --apply to actually write. Supports --sport=<uuid> to limit to a single sport. Exits 2 if the backfill reports errors (e.g., surface-Elo conflicts). * fix(backfill-cli): wrap runBackfill in DatabaseContext.run The orchestrator uses database() from ~/database/context, which requires AsyncLocalStorage to be populated. Wrap the CLI invocation with DatabaseContext.run(db, ...) using server/db's cached connection pool. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(backfill-cli): exit 0 on success so pg pool doesn't block The cached postgres connection pool keeps the Node event loop open after main() returns. Explicit process.exit(0) on success mirrors the pattern in scripts/capture-baseline.ts. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Chris Parsons <chrisp@extrahop.com> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-01 20:13:18 -07:00
participantId: schema.eventResults.seasonParticipantId,
qualifyingPointsAwarded: schema.eventResults.qualifyingPointsAwarded,
})
.from(schema.eventResults)
.where(inArray(schema.eventResults.scoringEventId, completedEventIds));
for (const r of actualResults) {
if (r.qualifyingPointsAwarded !== null) {
const prev = actualQPMap.get(r.participantId) ?? 0;
actualQPMap.set(r.participantId, prev + parseFloat(r.qualifyingPointsAwarded));
}
}
}
// Incomplete majors that need to be simulated.
const incompleteMajors = events.filter((e) => !e.isComplete);
// 5. Monte Carlo loop.
// For each player, count how many times they finish 1st8th by QP rank.
const counts: number[][] = Array.from({ length: participantIds.length }, () => Array.from({ length: 8 }, () => 0));
const idToIndex = new Map<string, number>(participantIds.map((id, i) => [id, i]));
for (let sim = 0; sim < NUM_SIMULATIONS; sim++) {
// Start each simulation from the locked actual QP.
const simQP = new Map<string, number>(actualQPMap);
// Simulate each incomplete major and accumulate QP.
for (const event of incompleteMajors) {
const surface = getSurfaceForEvent(event.name);
const draw = buildDraw(participantIds, surfaceEloMap);
const results = simulateMajor(draw, surfaceEloMap, surface);
for (const { participantId, qp } of results) {
simQP.set(participantId, (simQP.get(participantId) ?? 0) + qp);
}
}
// Rank all participants by total QP descending.
const ranked = [...simQP.entries()].toSorted((a, b) => b[1] - a[1]);
// Award placements 18.
for (let rank = 0; rank < Math.min(8, ranked.length); rank++) {
const [pid] = ranked[rank];
const idx = idToIndex.get(pid);
if (idx !== undefined) {
counts[idx][rank]++;
}
}
}
// 6. Convert counts to probabilities.
// Column sums are naturally 1.0: exactly one player holds each rank per simulation.
return participantIds.map((participantId, i) => ({
participantId,
probabilities: {
probFirst: counts[i][0] / NUM_SIMULATIONS,
probSecond: counts[i][1] / NUM_SIMULATIONS,
probThird: counts[i][2] / NUM_SIMULATIONS,
probFourth: counts[i][3] / NUM_SIMULATIONS,
probFifth: counts[i][4] / NUM_SIMULATIONS,
probSixth: counts[i][5] / NUM_SIMULATIONS,
probSeventh: counts[i][6] / NUM_SIMULATIONS,
probEighth: counts[i][7] / NUM_SIMULATIONS,
},
source: "tennis_grand_slam_monte_carlo",
}));
}
}