brackt/app/services/probability-updater.ts
Chris Parsons 2848231235
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

299 lines
8.9 KiB
TypeScript

/**
* Probability Updater Service
*
* Updates probability distributions when real results come in.
*
* Key behaviors:
* - Finished participants: Set to 100% at their placement, 0% elsewhere
* - Unfinished participants: Re-run ICM calculation with remaining participants
* - Handles partial results correctly
*/
import { findParticipantResultsBySportsSeasonId } from "~/models/participant-result";
import {
getAllParticipantEVsForSeason,
upsertParticipantEV,
type ParticipantEV,
} from "~/models/participant-expected-value";
import { calculateICMFromOdds } from "./icm-calculator";
import type { ProbabilityDistribution } from "./ev-calculator";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq } from "drizzle-orm";
/**
* Result of probability update operation
*/
export interface ProbabilityUpdateResult {
finishedParticipants: number;
unfishedParticipants: number;
updated: number;
errors: string[];
}
/**
* Before/after probabilities for display
*/
export interface ProbabilityComparison {
participantId: string;
participantName: string;
before: number[]; // [P(1st), P(2nd), ..., P(8th)]
after: number[]; // [P(1st), P(2nd), ..., P(8th)]
status: 'finished' | 'recalculated' | 'unchanged';
}
/**
* Convert probability array to ProbabilityDistribution
*/
function arrayToProbabilityDistribution(probs: number[]): ProbabilityDistribution {
return {
probFirst: probs[0],
probSecond: probs[1],
probThird: probs[2],
probFourth: probs[3],
probFifth: probs[4],
probSixth: probs[5],
probSeventh: probs[6],
probEighth: probs[7],
};
}
/**
* Convert ParticipantEV to probability array
*/
function evToProbabilityArray(ev: ParticipantEV): number[] {
return [
parseFloat(ev.probFirst),
parseFloat(ev.probSecond),
parseFloat(ev.probThird),
parseFloat(ev.probFourth),
parseFloat(ev.probFifth),
parseFloat(ev.probSixth),
parseFloat(ev.probSeventh),
parseFloat(ev.probEighth),
];
}
/**
* Create a probability distribution where participant finished at a specific position
*
* @param finalPosition The position where participant finished
* - 1-8: 100% at that position, 0% elsewhere
* - 0: Eliminated (didn't make playoffs) - 0% for all positions
* - >8: Finished outside scoring - 0% for all positions
* @returns Array of probabilities with 100% at finalPosition (if 1-8), or all 0%
*/
function createFinishedProbabilities(finalPosition: number): number[] {
const probs = [0, 0, 0, 0, 0, 0, 0, 0];
// Handle positions 1-8
if (finalPosition >= 1 && finalPosition <= 8) {
probs[finalPosition - 1] = 1.0; // 100% at their position
}
// finalPosition = 0 (eliminated) or > 8 (finished outside top 8)
// Keep all probabilities at 0%
return probs;
}
/**
* Update probabilities for a sports season after results come in
*
* Process:
* 1. Get all participant results (finished participants)
* 2. Get all existing participant EVs
* 3. For finished participants: set 100% at their placement
* 4. For unfinished participants: recalculate using ICM with remaining participants
*
* @param sportsSeasonId Sports season to update
* @param recalculateUnfinished Whether to recalculate unfinished participants (default true)
* @returns Update result summary
*/
export async function updateProbabilitiesAfterResult(
sportsSeasonId: string,
recalculateUnfinished = true
): Promise<ProbabilityUpdateResult> {
const errors: string[] = [];
let updated = 0;
try {
// Get all results (finished participants)
const results = await findParticipantResultsBySportsSeasonId(sportsSeasonId);
// Get all existing EVs
const existingEVs = await getAllParticipantEVsForSeason(sportsSeasonId);
// Create map of participantId -> finalPosition
const finishedMap = new Map(
results
.filter(r => r.finalPosition !== null)
.map(r => [r.participantId, r.finalPosition ?? 0])
);
// Update finished participants
// Use default scoring rules (we only care about setting probabilities, not EV for finished)
const defaultScoringRules = {
pointsFor1st: 100,
pointsFor2nd: 70,
pointsFor3rd: 50,
pointsFor4th: 40,
pointsFor5th: 25,
pointsFor6th: 25,
pointsFor7th: 15,
pointsFor8th: 15,
};
for (const [participantId, finalPosition] of finishedMap.entries()) {
try {
const probs = createFinishedProbabilities(finalPosition);
const probabilities = arrayToProbabilityDistribution(probs);
await upsertParticipantEV({
participantId,
sportsSeasonId,
probabilities,
scoringRules: defaultScoringRules,
source: 'manual', // Result is from actual outcome
});
updated++;
} catch (error) {
errors.push(`Failed to update participant ${participantId}: ${error}`);
}
}
// Recalculate unfinished participants if requested
if (recalculateUnfinished) {
const unfinishedEVs = existingEVs.filter(
ev => !finishedMap.has(ev.participantId)
);
if (unfinishedEVs.length > 0) {
// Get their current championship probabilities (use existing P(1st) as proxy)
const unfinishedOdds = unfinishedEVs.map(ev => {
const pFirst = parseFloat(ev.probFirst);
// Convert probability back to odds (approximate)
// probability = 100 / (odds + 100) => odds = (100 / probability) - 100
const odds = pFirst > 0 ? Math.round((100 / pFirst) - 100) : 100000;
return {
participantId: ev.participantId,
odds: odds,
};
});
// Recalculate ICM for unfinished participants
const icmResults = calculateICMFromOdds(unfinishedOdds);
// Update each unfinished participant
for (const [participantId, icmResult] of icmResults.entries()) {
try {
const probs = [
icmResult.probabilities.first,
icmResult.probabilities.second,
icmResult.probabilities.third,
icmResult.probabilities.fourth,
icmResult.probabilities.fifth,
icmResult.probabilities.sixth,
icmResult.probabilities.seventh,
icmResult.probabilities.eighth,
];
const probabilities = arrayToProbabilityDistribution(probs);
await upsertParticipantEV({
participantId,
sportsSeasonId,
probabilities,
scoringRules: defaultScoringRules,
source: 'futures_odds', // Recalculated from remaining odds
});
updated++;
} catch (error) {
errors.push(`Failed to recalculate participant ${participantId}: ${error}`);
}
}
}
}
return {
finishedParticipants: finishedMap.size,
unfishedParticipants: existingEVs.length - finishedMap.size,
updated,
errors,
};
} catch (error) {
errors.push(`Failed to update probabilities: ${error}`);
return {
finishedParticipants: 0,
unfishedParticipants: 0,
updated,
errors,
};
}
}
/**
* Get before/after comparison of probabilities for display
*
* Shows what will change when updateProbabilitiesAfterResult runs.
* Useful for preview before committing changes.
*
* @param sportsSeasonId Sports season to preview
* @returns Array of probability comparisons
*/
export async function previewProbabilityUpdate(
sportsSeasonId: string
): Promise<ProbabilityComparison[]> {
const db = database();
// Get all results (finished participants)
const results = await findParticipantResultsBySportsSeasonId(sportsSeasonId);
// Get all existing EVs with participant names
const existingEVs = await db.query.seasonParticipantExpectedValues.findMany({
where: eq(schema.seasonParticipantExpectedValues.sportsSeasonId, sportsSeasonId),
with: {
participant: true,
},
});
// Create map of participantId -> finalPosition
const finishedMap = new Map(
results
.filter(r => r.finalPosition !== null)
.map(r => [r.participantId, r.finalPosition ?? 0])
);
const comparisons: ProbabilityComparison[] = [];
for (const ev of existingEVs) {
const before = evToProbabilityArray(ev);
const finalPosition = finishedMap.get(ev.participantId);
let after: number[];
let status: 'finished' | 'recalculated' | 'unchanged';
if (finalPosition !== undefined) {
// Finished participant
after = createFinishedProbabilities(finalPosition);
status = 'finished';
} else {
// For preview, we'd need to recalculate - for now just show unchanged
// In a real implementation, we'd run the ICM calculation here too
after = before;
status = 'unchanged';
}
comparisons.push({
participantId: ev.participantId,
participantName: ev.participant?.name || 'Unknown',
before,
after,
status,
});
}
return comparisons;
}