brackt/app/services/probability-updater.ts

384 lines
15 KiB
TypeScript
Raw Normal View History

/**
* 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";
Fix EV reporting 20 pts for both LLWS 5-6 and 7-8 locked tiers After an LLWS simulation, a team locked into the 5th-6th tier and one locked into the 7th-8th tier both showed 20 points EV. They should show 25 and 15. The simulator and calculateEV were both right. A team locked into the 5-6 tier comes out of llws-simulator at probFifth = probSixth = 0.5, and against DEFAULT_SCORING_RULES (100/70/50/40/25/25/15/15) that is 25 — matching calculateBracketPoints, which already knows llws_20 splits 5-8 into two tiers. The Admin -> Expected Values page just wasn't using that table. It hardcoded its own stale copy: const SCORING = [100, 70, 45, 45, 20, 20, 20, 20] as const; 0.5*20 + 0.5*20 = 20 for either tier. It is not LLWS-specific. Four places carried that same stale table, and it stayed invisible because a standard single-elimination bracket puts all four quarterfinal losers in one tier worth avg(25,25,15,15) = 20 — the same number. It only diverges for the templates that split 5-8 (llws_20, afl_10) and those with a distinct 3rd/4th (llws_20, fifa_48, where 45/45 should be 50/40). Two of the four *persist* EVs computed that way, so the wrong values reached the database: - expected-values.tsx displayed EV, the total, and the sort order - expected-values.server manual EV entry, written to expected_value - golf-skills.tsx simulation EVs + snapshots, written - surface-elo.tsx simulation EVs + snapshots, written All four now use the shared DEFAULT_SCORING_RULES. probability-updater had a fourth inline copy with the right values; it is folded in too so there is one table left. The page's 340 total-EV invariant is unchanged — both tables sum to 340. A second path collapses the same two tiers, this time in real fantasy points. calculateBracketPoints falls back to the flat avg([5,6,7,8]) when bracketTemplateId is null, and four call sites resolved the template by taking an arbitrary scoringEvents row for the sports season — unordered, and not filtered to rows that actually carry a template. A season can own several events (a bracket plus schedule events, or a re-created bracket beside a stale one), so a null row wins at random and llws_20 is lost. New getBracketTemplateIdsForSportsSeasons in models/bracket-template.ts filters to events with a template and takes the most recent, the same rule llws-simulator uses to pick its bracket event; standings, calculateTeamScore, calculateTeamProjectedScore and getDraftedParticipantsWithPoints all go through it. Tests: evFromProbs pinned to 25 / 15 / 20-for-a-single-5-8-tier and the 340 invariant; the new lookup against a mixed set of events; and two llws-simulator tests that play out a full U.S. side so a team really is locked into each tier and must come out at exactly 50/50 across it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EmUdy42Rpgx9qZTnpQwirz
2026-08-27 16:11:59 +00:00
import { DEFAULT_SCORING_RULES } from "~/lib/scoring-types";
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
import { getSportsSeasonSimulatorConfig } from "~/models/simulator";
Stop the simulator re-run from trampling its caller's side effects A review of this branch found four problems, all downstream of one decision: calling runSportsSeasonSimulation from inside the result path. That function does three jobs — recompute probabilities, recalculate standings, write the daily EV snapshot — and the result path wants only the first. 1. The Discord standings post was silently suppressed on every scored match, for all 13 bracket-aware sports. recalculateAffectedLeagues detects change by snapshotting teamStandings, recalculating, then diffing; changedTeamIds gates the notification. But processMatchResult runs updateProbabilitiesAfterResult first, which now reached the runner's own recalculateStandings. The new totals were therefore already written when the "before" snapshot was taken, the diff came back empty, and the post never fired. previousRank went the same way: recalculateStandings rolls it forward on every call, so the extra one erased rank movement. runSportsSeasonSimulation now takes skipStandingsRecalc / skipSnapshots and the probability updater passes both. The snapshot is skipped because it is a per-day series keyed by snapshotDate — writing it per match result just overwrites the day's row with intra-day values. 2. finalizeQualifyingPoints marks the season completed immediately before calling the updater, and the runner rejects a completed season outright. With the ICM fallback gone that failed every time, stranding anyone still in the unfinished set on permanently stale probabilities — reachable for cs2_major_qualifying_points, the one bracket-aware qualifying-points sport. A completed season is not this branch's case rather than a failure: every placement is final and the floor it protects can no longer be contradicted. shouldRerunSimulator now excludes it and it falls through to ICM as before. The genuine failure modes still leave probabilities alone rather than falling back to the path being replaced. 3. match-sync calls processMatchResult in a per-match loop with no skipSideEffects, so each synced match ran a full Monte Carlo plus EV rewrite, snapshot and standings recalc. processMatchResult gains skipProbabilities — mirroring the option processPlayoffEvent already takes, and narrower than skipSideEffects — which match-sync passes in the loop before refreshing once at the end. Per-match standings and Discord posts are unchanged. 4. A partially-seeded afl_10 bracket now throws from inside the result path. The throw is correct and stays; the concern was that it was silent, which the error surfacing in 2 covers. Two claims from the review did not hold up and were left alone: the batch bracket route already passes skipSideEffects per match and refreshes once after the loop, and autoCompleteRoundIfDone already passes skipProbabilities, so there is no double run per round completion. Tests: the runner honors both skip flags and still writes EVs; the updater asks for probabilities only; a completed season takes the ICM path without erroring; processMatchResult skips the refresh but still announces. The two behavioral ones were confirmed to fail against the previous behavior. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 03:46:12 +00:00
import { findSportsSeasonById } from "~/models/sports-season";
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
import { getManifestSimulatorProfile } from "~/services/simulations/manifest";
import { logger } from "~/lib/logger";
/**
* 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;
}
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
/**
Route every bracket-aware sport away from ICM, not just AFL The previous commit gated the simulator re-run on a `bracketAware` flag set only on afl_bracket and llws_bracket, on the claim that every other simulator was bracket-blind and would resurrect eliminated teams if re-run. That claim was wrong. Eleven more read playoff_matches and honor isComplete/winnerId already: ucl, ncaam, ncaaw (both via ncaa-basketball), nba, nhl, snooker, world_cup, darts, cs2_major, college_hockey and nll. All thirteen are now flagged, so any sport with a bracket the simulator can read absorbs a result by re-running that simulator rather than through ICM. Two simulators are deliberately left off. playoff_bracket and ncaa_football_bracket declare a "bracket" setup section but never read playoff_matches, so re-running them really would re-draw the field. That mismatch runs the other way too — world_cup, darts_bracket and cs2_major_qualifying_points read the bracket without declaring the section — so setupSections is not a usable signal here and the flag stays separate from it, with both facts written down on the flag. The EV-source condition is also gone. It only asked whether the existing EVs came from a simulation, which protected nothing: the alternative to re-running was never leaving them alone, it was the ICM branch overwriting them anyway. Given two overwrites, the bracket-aware one wins regardless of what wrote them. Tests: a bracket-blind simulator still goes through ICM, futures-odds EVs no longer divert a bracket-aware season away from the re-run, and the bracket-aware set is pinned in the manifest test so a new simulator is an explicit decision rather than a default. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:49:17 +00:00
* Whether this season's still-alive participants should be refreshed by re-running its
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
* simulator instead of by the ICM recalculation below.
*
Route every bracket-aware sport away from ICM, not just AFL The previous commit gated the simulator re-run on a `bracketAware` flag set only on afl_bracket and llws_bracket, on the claim that every other simulator was bracket-blind and would resurrect eliminated teams if re-run. That claim was wrong. Eleven more read playoff_matches and honor isComplete/winnerId already: ucl, ncaam, ncaaw (both via ncaa-basketball), nba, nhl, snooker, world_cup, darts, cs2_major, college_hockey and nll. All thirteen are now flagged, so any sport with a bracket the simulator can read absorbs a result by re-running that simulator rather than through ICM. Two simulators are deliberately left off. playoff_bracket and ncaa_football_bracket declare a "bracket" setup section but never read playoff_matches, so re-running them really would re-draw the field. That mismatch runs the other way too — world_cup, darts_bracket and cs2_major_qualifying_points read the bracket without declaring the section — so setupSections is not a usable signal here and the flag stays separate from it, with both facts written down on the flag. The EV-source condition is also gone. It only asked whether the existing EVs came from a simulation, which protected nothing: the alternative to re-running was never leaving them alone, it was the ICM branch overwriting them anyway. Given two overwrites, the bracket-aware one wins regardless of what wrote them. Tests: a bracket-blind simulator still goes through ICM, futures-odds EVs no longer divert a bracket-aware season away from the re-run, and the bracket-aware set is pinned in the manifest test so a new simulator is an explicit decision rather than a default. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:49:17 +00:00
* If the season has a simulator that reads its bracket, that simulator is simply a better
* answer than ICM to "what happens from here": it seeds from the real draw and replays every
* completed match, where ICM re-derives a whole distribution from P(1st) alone and knows
* nothing about who is playing whom or what has already been decided. That blindness is what
* makes ICM report a placement floor the league has already paid out as worth less than its
* awarded points.
*
* Where the EVs originally came from is not consulted, because the alternative here is not
* leaving them alone the ICM branch overwrites them either way. Given the choice between
* two overwrites, the bracket-aware one wins.
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
*
Route every bracket-aware sport away from ICM, not just AFL The previous commit gated the simulator re-run on a `bracketAware` flag set only on afl_bracket and llws_bracket, on the claim that every other simulator was bracket-blind and would resurrect eliminated teams if re-run. That claim was wrong. Eleven more read playoff_matches and honor isComplete/winnerId already: ucl, ncaam, ncaaw (both via ncaa-basketball), nba, nhl, snooker, world_cup, darts, cs2_major, college_hockey and nll. All thirteen are now flagged, so any sport with a bracket the simulator can read absorbs a result by re-running that simulator rather than through ICM. Two simulators are deliberately left off. playoff_bracket and ncaa_football_bracket declare a "bracket" setup section but never read playoff_matches, so re-running them really would re-draw the field. That mismatch runs the other way too — world_cup, darts_bracket and cs2_major_qualifying_points read the bracket without declaring the section — so setupSections is not a usable signal here and the flag stays separate from it, with both facts written down on the flag. The EV-source condition is also gone. It only asked whether the existing EVs came from a simulation, which protected nothing: the alternative to re-running was never leaving them alone, it was the ICM branch overwriting them anyway. Given two overwrites, the bracket-aware one wins regardless of what wrote them. Tests: a bracket-blind simulator still goes through ICM, futures-odds EVs no longer divert a bracket-aware season away from the re-run, and the bracket-aware set is pinned in the manifest test so a new simulator is an explicit decision rather than a default. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:49:17 +00:00
* The gate is `bracketAware`, not merely "has a simulator": re-running a bracket-blind
* simulator would re-draw the field and hand equity back to teams already knocked out.
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
*/
Route every bracket-aware sport away from ICM, not just AFL The previous commit gated the simulator re-run on a `bracketAware` flag set only on afl_bracket and llws_bracket, on the claim that every other simulator was bracket-blind and would resurrect eliminated teams if re-run. That claim was wrong. Eleven more read playoff_matches and honor isComplete/winnerId already: ucl, ncaam, ncaaw (both via ncaa-basketball), nba, nhl, snooker, world_cup, darts, cs2_major, college_hockey and nll. All thirteen are now flagged, so any sport with a bracket the simulator can read absorbs a result by re-running that simulator rather than through ICM. Two simulators are deliberately left off. playoff_bracket and ncaa_football_bracket declare a "bracket" setup section but never read playoff_matches, so re-running them really would re-draw the field. That mismatch runs the other way too — world_cup, darts_bracket and cs2_major_qualifying_points read the bracket without declaring the section — so setupSections is not a usable signal here and the flag stays separate from it, with both facts written down on the flag. The EV-source condition is also gone. It only asked whether the existing EVs came from a simulation, which protected nothing: the alternative to re-running was never leaving them alone, it was the ICM branch overwriting them anyway. Given two overwrites, the bracket-aware one wins regardless of what wrote them. Tests: a bracket-blind simulator still goes through ICM, futures-odds EVs no longer divert a bracket-aware season away from the re-run, and the bracket-aware set is pinned in the manifest test so a new simulator is an explicit decision rather than a default. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:49:17 +00:00
async function shouldRerunSimulator(sportsSeasonId: string): Promise<boolean> {
Stop the simulator re-run from trampling its caller's side effects A review of this branch found four problems, all downstream of one decision: calling runSportsSeasonSimulation from inside the result path. That function does three jobs — recompute probabilities, recalculate standings, write the daily EV snapshot — and the result path wants only the first. 1. The Discord standings post was silently suppressed on every scored match, for all 13 bracket-aware sports. recalculateAffectedLeagues detects change by snapshotting teamStandings, recalculating, then diffing; changedTeamIds gates the notification. But processMatchResult runs updateProbabilitiesAfterResult first, which now reached the runner's own recalculateStandings. The new totals were therefore already written when the "before" snapshot was taken, the diff came back empty, and the post never fired. previousRank went the same way: recalculateStandings rolls it forward on every call, so the extra one erased rank movement. runSportsSeasonSimulation now takes skipStandingsRecalc / skipSnapshots and the probability updater passes both. The snapshot is skipped because it is a per-day series keyed by snapshotDate — writing it per match result just overwrites the day's row with intra-day values. 2. finalizeQualifyingPoints marks the season completed immediately before calling the updater, and the runner rejects a completed season outright. With the ICM fallback gone that failed every time, stranding anyone still in the unfinished set on permanently stale probabilities — reachable for cs2_major_qualifying_points, the one bracket-aware qualifying-points sport. A completed season is not this branch's case rather than a failure: every placement is final and the floor it protects can no longer be contradicted. shouldRerunSimulator now excludes it and it falls through to ICM as before. The genuine failure modes still leave probabilities alone rather than falling back to the path being replaced. 3. match-sync calls processMatchResult in a per-match loop with no skipSideEffects, so each synced match ran a full Monte Carlo plus EV rewrite, snapshot and standings recalc. processMatchResult gains skipProbabilities — mirroring the option processPlayoffEvent already takes, and narrower than skipSideEffects — which match-sync passes in the loop before refreshing once at the end. Per-match standings and Discord posts are unchanged. 4. A partially-seeded afl_10 bracket now throws from inside the result path. The throw is correct and stays; the concern was that it was silent, which the error surfacing in 2 covers. Two claims from the review did not hold up and were left alone: the batch bracket route already passes skipSideEffects per match and refreshes once after the loop, and autoCompleteRoundIfDone already passes skipProbabilities, so there is no double run per round completion. Tests: the runner honors both skip flags and still writes EVs; the updater asks for probabilities only; a completed season takes the ICM path without erroring; processMatchResult skips the refresh but still announces. The two behavioral ones were confirmed to fail against the previous behavior. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 03:46:12 +00:00
// A completed season cannot be simulated — runSportsSeasonSimulation rejects it outright —
// and finalizeQualifyingPoints marks the season completed immediately before calling here,
// so taking this branch there would fail every single time and leave anyone still in the
// unfinished set on permanently stale probabilities. It is not a failure, it is not this
// branch's case: the season is over, every placement is final, and the floor this branch
// exists to protect can no longer be contradicted. Fall through to ICM as before.
const sportsSeason = await findSportsSeasonById(sportsSeasonId);
if (sportsSeason?.status === "completed") return false;
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
const simulatorConfig = await getSportsSeasonSimulatorConfig(sportsSeasonId);
if (!simulatorConfig) return false;
return getManifestSimulatorProfile(simulatorConfig.simulatorType)?.bracketAware === true;
}
/**
* 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
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
* 4. For unfinished participants: re-run the season's bracket-aware simulator if it has one,
* otherwise 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);
Fix four issues found reviewing the entry-floor change - Provisional rows were being treated as finished by updateProbabilitiesAfterResult, whose finishedMap filtered on finalPosition alone. Entry floors made that fire for the whole seeded field: on the first match result, AFL seeds 1-6 would each be pinned to 100% at their floor position and dropped from the ICM recalc, zeroing the championship odds of six teams that had not played. Filter partial rows out of finishedMap so they stay in the unfinished set. Finalized 0-position eliminations still finalize as before. - generate-bracket recalculated standings only inside markEliminatedAndAnnounce, which no-ops when nothing was eliminated. A season whose participants exactly equal the bracket field would never surface the floors in teamStandings.totalPoints. Recalculate explicitly in that case (skipDiscord: seeding is not a result). - applyBracketEntryFloors upserted unconditionally, so regenerating a bracket mid-tournament could downgrade a team already sitting on a better placement. Read existing placements first and only write when the floor improves on what a participant already has; position 0 is eliminated, not a placement, so it never blocks a floor. - Relaxing the reprocess guard to matches.length made the season-wide deleteParticipantResultsBySportsSeasonId reachable with zero completed matches, wiping other events' placements with no replay able to rebuild them. Skip the wipe when there is nothing to replay; entry floors and elimination marking are additive and need no wipe. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JkhdcbUCvramxJdVdoBsKd
2026-08-24 17:13:45 +00:00
// Create map of participantId -> finalPosition.
//
// Provisional rows (isPartialScore) are NOT finished: they are the guaranteed
// minimum for someone still alive — a bracket entry floor, or the floor banked
// by winning a round. Treating them as finished pins the participant to 100% at
// that floor and drops them from the ICM recalculation below, which would zero
// the championship odds of every team still playing. They belong in the
// unfinished set until a real result lands.
const finishedMap = new Map(
results
Fix four issues found reviewing the entry-floor change - Provisional rows were being treated as finished by updateProbabilitiesAfterResult, whose finishedMap filtered on finalPosition alone. Entry floors made that fire for the whole seeded field: on the first match result, AFL seeds 1-6 would each be pinned to 100% at their floor position and dropped from the ICM recalc, zeroing the championship odds of six teams that had not played. Filter partial rows out of finishedMap so they stay in the unfinished set. Finalized 0-position eliminations still finalize as before. - generate-bracket recalculated standings only inside markEliminatedAndAnnounce, which no-ops when nothing was eliminated. A season whose participants exactly equal the bracket field would never surface the floors in teamStandings.totalPoints. Recalculate explicitly in that case (skipDiscord: seeding is not a result). - applyBracketEntryFloors upserted unconditionally, so regenerating a bracket mid-tournament could downgrade a team already sitting on a better placement. Read existing placements first and only write when the floor improves on what a participant already has; position 0 is eliminated, not a placement, so it never blocks a floor. - Relaxing the reprocess guard to matches.length made the season-wide deleteParticipantResultsBySportsSeasonId reachable with zero completed matches, wiping other events' placements with no replay able to rebuild them. Skip the wipe when there is nothing to replay; entry floors and elimination marking are additive and need no wipe. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JkhdcbUCvramxJdVdoBsKd
2026-08-24 17:13:45 +00:00
.filter(r => r.finalPosition !== null && !r.isPartialScore)
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196) * Fix no-shadow and consistent-function-scoping lint violations Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint warnings and promotes both rules to errors in .oxlintrc.json. no-shadow: renamed Drizzle callback params (sports→s, matches→m, seasons→s) to avoid shadowing outer imports; removed shadowed destructures (eq, inArray) from where callbacks; renamed inner template→bracketTemplate, prev→currentTimers, season→ss, name→teamName (with name: teamName fix to preserve semantics). consistent-function-scoping: moved formatDate, getRankBadge, getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr, elo (×2), weightedPick, sortByMatchNumber (×2) to module scope; moved formatTime (×2), isValidLeagueName, getDraftTimes, makeSeasonQueues to file scope in test files. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-non-null-assertion lint violations and promote to error Eliminates all 208 no-non-null-assertion warnings across 38 files. Promotes typescript/no-non-null-assertion from warn to error in .oxlintrc.json. Fix patterns applied: - Map.get(key)! after .has() check → extract with get() + null guard - Map.get(key)! on pre-populated count maps → ?? 0 default - .set(id, map.get(id)! + 1) increment → ?? 0 before adding - participant1Id!/participant2Id! on DB matches → ?? "" fallback - array.find()! in tests → guard + throw or expect().toBeDefined() - bracketTemplateCache.get(id)! → null guard extract - Various nullable field accesses → optional chain or ?? default Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers Resolves all 9 remaining non-console lint warnings and promotes all three rules to errors in .oxlintrc.json. - prefer-add-event-listener: converted onchange/onclick/onload assignments to addEventListener in useDraftNotifications.ts and admin.data-sync.tsx; stored changeHandler ref for proper cleanup with removeEventListener - no-unassigned-import: configured rule with allow list for legitimate side-effect imports (*.css, @testing-library/jest-dom, @testing-library/cypress/add-commands) - require-module-specifiers: removed redundant `export {}` from cypress/support/e2e.ts (file already has an import) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix TypeScript errors from no-non-null-assertion fixes Two fixes introduced by the non-null assertion cleanup produced type errors: - scoring-event.ts: `?? ""` was wrong type for a participant object map; restructured to explicit null guards so TypeScript can narrow correctly - standings-sync/index.ts: `?? null` after name-match lookup lost the truthy guarantee, causing TS18047 on the write-back block; added `participant &&` guard before accessing its properties Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Add npm run typecheck as Stop hook in Claude settings Runs a full project typecheck at the end of each Claude turn so type errors surface as feedback before the next message. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
.map(r => [r.participantId, r.finalPosition ?? 0])
);
// Recalculate unfinished participants if requested
if (recalculateUnfinished) {
const unfinishedEVs = existingEVs.filter(
ev => !finishedMap.has(ev.participantId)
);
Route every bracket-aware sport away from ICM, not just AFL The previous commit gated the simulator re-run on a `bracketAware` flag set only on afl_bracket and llws_bracket, on the claim that every other simulator was bracket-blind and would resurrect eliminated teams if re-run. That claim was wrong. Eleven more read playoff_matches and honor isComplete/winnerId already: ucl, ncaam, ncaaw (both via ncaa-basketball), nba, nhl, snooker, world_cup, darts, cs2_major, college_hockey and nll. All thirteen are now flagged, so any sport with a bracket the simulator can read absorbs a result by re-running that simulator rather than through ICM. Two simulators are deliberately left off. playoff_bracket and ncaa_football_bracket declare a "bracket" setup section but never read playoff_matches, so re-running them really would re-draw the field. That mismatch runs the other way too — world_cup, darts_bracket and cs2_major_qualifying_points read the bracket without declaring the section — so setupSections is not a usable signal here and the flag stays separate from it, with both facts written down on the flag. The EV-source condition is also gone. It only asked whether the existing EVs came from a simulation, which protected nothing: the alternative to re-running was never leaving them alone, it was the ICM branch overwriting them anyway. Given two overwrites, the bracket-aware one wins regardless of what wrote them. Tests: a bracket-blind simulator still goes through ICM, futures-odds EVs no longer divert a bracket-aware season away from the re-run, and the bracket-aware set is pinned in the manifest test so a new simulator is an explicit decision rather than a default. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:49:17 +00:00
if (unfinishedEVs.length > 0 && (await shouldRerunSimulator(sportsSeasonId))) {
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
// The simulator reads the bracket, so it already knows this result: it seeds from the
// real draw and replays every completed match. Re-running it keeps each participant's
// distribution consistent with the games actually played — including the placement
// floors a bracket entry or a non-scoring-round win has already banked, which the ICM
// branch below cannot see and would value below points the league has paid out.
//
// Imported lazily: probability-updater → runner → scoring-calculator →
// probability-updater is a module cycle, and a static import leaves the binding
// undefined at module-init time.
try {
const { runSportsSeasonSimulation } = await import("~/services/simulations/runner");
Stop the simulator re-run from trampling its caller's side effects A review of this branch found four problems, all downstream of one decision: calling runSportsSeasonSimulation from inside the result path. That function does three jobs — recompute probabilities, recalculate standings, write the daily EV snapshot — and the result path wants only the first. 1. The Discord standings post was silently suppressed on every scored match, for all 13 bracket-aware sports. recalculateAffectedLeagues detects change by snapshotting teamStandings, recalculating, then diffing; changedTeamIds gates the notification. But processMatchResult runs updateProbabilitiesAfterResult first, which now reached the runner's own recalculateStandings. The new totals were therefore already written when the "before" snapshot was taken, the diff came back empty, and the post never fired. previousRank went the same way: recalculateStandings rolls it forward on every call, so the extra one erased rank movement. runSportsSeasonSimulation now takes skipStandingsRecalc / skipSnapshots and the probability updater passes both. The snapshot is skipped because it is a per-day series keyed by snapshotDate — writing it per match result just overwrites the day's row with intra-day values. 2. finalizeQualifyingPoints marks the season completed immediately before calling the updater, and the runner rejects a completed season outright. With the ICM fallback gone that failed every time, stranding anyone still in the unfinished set on permanently stale probabilities — reachable for cs2_major_qualifying_points, the one bracket-aware qualifying-points sport. A completed season is not this branch's case rather than a failure: every placement is final and the floor it protects can no longer be contradicted. shouldRerunSimulator now excludes it and it falls through to ICM as before. The genuine failure modes still leave probabilities alone rather than falling back to the path being replaced. 3. match-sync calls processMatchResult in a per-match loop with no skipSideEffects, so each synced match ran a full Monte Carlo plus EV rewrite, snapshot and standings recalc. processMatchResult gains skipProbabilities — mirroring the option processPlayoffEvent already takes, and narrower than skipSideEffects — which match-sync passes in the loop before refreshing once at the end. Per-match standings and Discord posts are unchanged. 4. A partially-seeded afl_10 bracket now throws from inside the result path. The throw is correct and stays; the concern was that it was silent, which the error surfacing in 2 covers. Two claims from the review did not hold up and were left alone: the batch bracket route already passes skipSideEffects per match and refreshes once after the loop, and autoCompleteRoundIfDone already passes skipProbabilities, so there is no double run per round completion. Tests: the runner honors both skip flags and still writes EVs; the updater asks for probabilities only; a completed season takes the ICM path without erroring; processMatchResult skips the refresh but still announces. The two behavioral ones were confirmed to fail against the previous behavior. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 03:46:12 +00:00
// Probabilities only. Our callers recalculate standings themselves right after this,
// and recalculateAffectedLeagues detects change by diffing teamStandings across its
// own recalculation — a recalculation slipped in here empties that diff and silently
// suppresses the Discord standings post, and rolls previousRank forward a second time
// so rank movement disappears. The daily EV snapshot is not ours to write either: it
// is keyed by date, so writing it per result overwrites the day with intra-day values.
await runSportsSeasonSimulation(sportsSeasonId, {
skipStandingsRecalc: true,
skipSnapshots: true,
});
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
updated += unfinishedEVs.length;
} catch (error) {
Stop the simulator re-run from trampling its caller's side effects A review of this branch found four problems, all downstream of one decision: calling runSportsSeasonSimulation from inside the result path. That function does three jobs — recompute probabilities, recalculate standings, write the daily EV snapshot — and the result path wants only the first. 1. The Discord standings post was silently suppressed on every scored match, for all 13 bracket-aware sports. recalculateAffectedLeagues detects change by snapshotting teamStandings, recalculating, then diffing; changedTeamIds gates the notification. But processMatchResult runs updateProbabilitiesAfterResult first, which now reached the runner's own recalculateStandings. The new totals were therefore already written when the "before" snapshot was taken, the diff came back empty, and the post never fired. previousRank went the same way: recalculateStandings rolls it forward on every call, so the extra one erased rank movement. runSportsSeasonSimulation now takes skipStandingsRecalc / skipSnapshots and the probability updater passes both. The snapshot is skipped because it is a per-day series keyed by snapshotDate — writing it per match result just overwrites the day's row with intra-day values. 2. finalizeQualifyingPoints marks the season completed immediately before calling the updater, and the runner rejects a completed season outright. With the ICM fallback gone that failed every time, stranding anyone still in the unfinished set on permanently stale probabilities — reachable for cs2_major_qualifying_points, the one bracket-aware qualifying-points sport. A completed season is not this branch's case rather than a failure: every placement is final and the floor it protects can no longer be contradicted. shouldRerunSimulator now excludes it and it falls through to ICM as before. The genuine failure modes still leave probabilities alone rather than falling back to the path being replaced. 3. match-sync calls processMatchResult in a per-match loop with no skipSideEffects, so each synced match ran a full Monte Carlo plus EV rewrite, snapshot and standings recalc. processMatchResult gains skipProbabilities — mirroring the option processPlayoffEvent already takes, and narrower than skipSideEffects — which match-sync passes in the loop before refreshing once at the end. Per-match standings and Discord posts are unchanged. 4. A partially-seeded afl_10 bracket now throws from inside the result path. The throw is correct and stays; the concern was that it was silent, which the error surfacing in 2 covers. Two claims from the review did not hold up and were left alone: the batch bracket route already passes skipSideEffects per match and refreshes once after the loop, and autoCompleteRoundIfDone already passes skipProbabilities, so there is no double run per round completion. Tests: the runner honors both skip flags and still writes EVs; the updater asks for probabilities only; a completed season takes the ICM path without erroring; processMatchResult skips the refresh but still announces. The two behavioral ones were confirmed to fail against the previous behavior. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 03:46:12 +00:00
// A run already in flight, failed readiness, or a bracket the simulator refuses to
// read (afl_10 seeded into only some of its slots). Leave the existing probabilities
// alone rather than falling back to ICM — for these seasons ICM is precisely the
// thing being replaced, and reintroducing it here would reintroduce sub-floor EVs.
// Completed seasons never reach this: shouldRerunSimulator excludes them.
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
logger.error(
`[ProbabilityUpdater] Failed to re-run simulator for sports season ${sportsSeasonId}; ` +
`leaving existing probabilities in place:`,
error
);
errors.push(`Failed to re-run simulator for sports season ${sportsSeasonId}: ${error}`);
}
} else 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);
// Sequential for the same reason as the finished loop above:
// upsertParticipantEV rewrites shared per-season state via syncVorpForSeason.
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,
Fix EV reporting 20 pts for both LLWS 5-6 and 7-8 locked tiers After an LLWS simulation, a team locked into the 5th-6th tier and one locked into the 7th-8th tier both showed 20 points EV. They should show 25 and 15. The simulator and calculateEV were both right. A team locked into the 5-6 tier comes out of llws-simulator at probFifth = probSixth = 0.5, and against DEFAULT_SCORING_RULES (100/70/50/40/25/25/15/15) that is 25 — matching calculateBracketPoints, which already knows llws_20 splits 5-8 into two tiers. The Admin -> Expected Values page just wasn't using that table. It hardcoded its own stale copy: const SCORING = [100, 70, 45, 45, 20, 20, 20, 20] as const; 0.5*20 + 0.5*20 = 20 for either tier. It is not LLWS-specific. Four places carried that same stale table, and it stayed invisible because a standard single-elimination bracket puts all four quarterfinal losers in one tier worth avg(25,25,15,15) = 20 — the same number. It only diverges for the templates that split 5-8 (llws_20, afl_10) and those with a distinct 3rd/4th (llws_20, fifa_48, where 45/45 should be 50/40). Two of the four *persist* EVs computed that way, so the wrong values reached the database: - expected-values.tsx displayed EV, the total, and the sort order - expected-values.server manual EV entry, written to expected_value - golf-skills.tsx simulation EVs + snapshots, written - surface-elo.tsx simulation EVs + snapshots, written All four now use the shared DEFAULT_SCORING_RULES. probability-updater had a fourth inline copy with the right values; it is folded in too so there is one table left. The page's 340 total-EV invariant is unchanged — both tables sum to 340. A second path collapses the same two tiers, this time in real fantasy points. calculateBracketPoints falls back to the flat avg([5,6,7,8]) when bracketTemplateId is null, and four call sites resolved the template by taking an arbitrary scoringEvents row for the sports season — unordered, and not filtered to rows that actually carry a template. A season can own several events (a bracket plus schedule events, or a re-created bracket beside a stale one), so a null row wins at random and llws_20 is lost. New getBracketTemplateIdsForSportsSeasons in models/bracket-template.ts filters to events with a template and takes the most recent, the same rule llws-simulator uses to pick its bracket event; standings, calculateTeamScore, calculateTeamProjectedScore and getDraftedParticipantsWithPoints all go through it. Tests: evFromProbs pinned to 25 / 15 / 20-for-a-single-5-8-tier and the 340 invariant; the new lookup against a mixed set of events; and two llws-simulator tests that play out a full U.S. side so a team really is locked into each tier and must come out at exactly 50/50 across it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EmUdy42Rpgx9qZTnpQwirz
2026-08-27 16:11:59 +00:00
scoringRules: DEFAULT_SCORING_RULES,
source: 'futures_odds', // Recalculated from remaining odds
});
updated++;
} catch (error) {
errors.push(`Failed to recalculate participant ${participantId}: ${error}`);
}
}
}
}
Make the AFL simulator read the bracket that was actually drawn An AFL club seeded into an Elimination Final is awarded 15 fantasy points the moment the bracket is generated — afl_10's entryFloor: 7 — and cannot finish worse than the 7th-8th tier. Its EV still read 13. AFLSimulator was stateless with respect to the live bracket. It read only participants, sourceElo and the regular-season standings, then re-projected the whole ladder and re-seeded 1-10 from Elo on every one of its 10,000 iterations. So a team with a locked Elimination Final berth was re-drawn into the Wildcard Round, or out of the finals entirely, in a slice of them — and there it scores 0. Even with the ladder complete the Math.random() tiebreaker reshuffled every club tied on ladder points, which in the AFL is most of the middle of the table. Games already played were re-played the same way, so a completed Wildcard win was worth 50% of nothing. Mixing zeroes into a distribution whose floor is 15 is what produced 13. afl_10 is the only template that defines entryFloor at all, which is why this surfaced here and not on LLWS, whose floors only exist once a team has won something. The simulator now mirrors llws-simulator's bracket-aware mode: - readAflBracketSeeds reads the 10 seeds from the slots generateAFL10Bracket writes them into. The two Elimination Final participant2 slots are TBD by design and are never read as seeds, leaving exactly 10 named slots. No draw at all falls back to the ladder projection; a partially seeded, duplicated or unknown draw throws rather than silently discarding the draw and every recorded result with it. - makePlayGame replays a completed match from its recorded result whenever both recorded teams are the two the simulation routed into that game, so an already-played result sticks across all iterations. - simAFLFinals labels each game with the round and match number generateAFL10Bracket and advanceAFLWinner use, so a result is looked up against the game it was played in. Its routing was already correct. EV >= the banked floor now holds by construction, with no clamping: a team seeded into an Elimination Final is in that game in every iteration. Column sums stay exactly 1.0 and the 340-point total-EV invariant is unchanged, since teams outside the bracket simply score nothing. Fixing the simulator alone would not have held. processMatchResult calls updateProbabilitiesAfterResult on every result, and its ICM branch re-derives each still-alive participant's whole distribution from P(1st) alone, knowing nothing about the bracket — so the next finals result would have put the EV straight back under the floor. That branch was built for futures-odds seasons. It now runs only when the season's EVs did not come from a bracket-aware simulator; when they did, that simulator is re-run instead, since it already knows the completed matches. Both conditions matter: re-running a bracket-blind simulator would re-draw the field and hand equity back to knocked-out teams, so a new manifest `bracketAware` flag limits this to AFL and LLWS. A failed re-run leaves probabilities untouched rather than falling back to the ICM path that is being replaced. The finalized-participant pinning loop now runs after that recalculation rather than before. A simulation run rewrites every participant in the season, the finalized ones included; a finalized placement is a fact, not a projection, so it is written last and wins. Tests: seeds clear the entry floors their seeding banked, a Qualifying Final entrant is structurally absent from the 7th-8th tier, the bracket's draw beats Elo (the weakest club seeded 1, the strongest seeded 10), completed Wildcard and Qualifying Finals are replayed with the winner banking its floor, teams outside the bracket are zeroed, and the column sums and 340 total survive. The bracket fixtures deliberately seed the ten weakest clubs, because seeding the strongest ten lets the ladder projection reproduce much the same field by accident. Six of the seven were confirmed to fail against the previous behavior. Plus the probability-updater branch in each direction, its failure path, and the pin ordering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxDnSEKVoKx9HFcQ6gmcS
2026-08-29 02:42:31 +00:00
// Update finished participants. The shared default table is used because we only
// care about setting probabilities here, not the EV — each league re-derives its own
// EV from the stored probabilities in calculateTeamProjectedScore.
//
// This runs *after* the recalculation above, not before, because re-running a simulator
// rewrites every participant in the season — the finalized ones included. A finalized
// placement is a fact, not a projection, so it is written last and wins: if a simulator
// ever puts a knocked-out team back in contention (a bracket-aware one whose bracket has
// since been cleared and not re-seeded, say), the pin still zeroes them.
// Sequential: upsertParticipantEV calls syncVorpForSeason internally, which
// reads and rewrites every seasonParticipants row for this sportsSeasonId.
// Running these in parallel would race on that shared state.
for (const [participantId, finalPosition] of finishedMap.entries()) {
try {
const probs = createFinishedProbabilities(finalPosition);
const probabilities = arrayToProbabilityDistribution(probs);
await upsertParticipantEV({
participantId,
sportsSeasonId,
probabilities,
scoringRules: DEFAULT_SCORING_RULES,
source: 'manual', // Result is from actual outcome
});
updated++;
} catch (error) {
errors.push(`Failed to update 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
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
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)
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196) * Fix no-shadow and consistent-function-scoping lint violations Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint warnings and promotes both rules to errors in .oxlintrc.json. no-shadow: renamed Drizzle callback params (sports→s, matches→m, seasons→s) to avoid shadowing outer imports; removed shadowed destructures (eq, inArray) from where callbacks; renamed inner template→bracketTemplate, prev→currentTimers, season→ss, name→teamName (with name: teamName fix to preserve semantics). consistent-function-scoping: moved formatDate, getRankBadge, getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr, elo (×2), weightedPick, sortByMatchNumber (×2) to module scope; moved formatTime (×2), isValidLeagueName, getDraftTimes, makeSeasonQueues to file scope in test files. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-non-null-assertion lint violations and promote to error Eliminates all 208 no-non-null-assertion warnings across 38 files. Promotes typescript/no-non-null-assertion from warn to error in .oxlintrc.json. Fix patterns applied: - Map.get(key)! after .has() check → extract with get() + null guard - Map.get(key)! on pre-populated count maps → ?? 0 default - .set(id, map.get(id)! + 1) increment → ?? 0 before adding - participant1Id!/participant2Id! on DB matches → ?? "" fallback - array.find()! in tests → guard + throw or expect().toBeDefined() - bracketTemplateCache.get(id)! → null guard extract - Various nullable field accesses → optional chain or ?? default Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers Resolves all 9 remaining non-console lint warnings and promotes all three rules to errors in .oxlintrc.json. - prefer-add-event-listener: converted onchange/onclick/onload assignments to addEventListener in useDraftNotifications.ts and admin.data-sync.tsx; stored changeHandler ref for proper cleanup with removeEventListener - no-unassigned-import: configured rule with allow list for legitimate side-effect imports (*.css, @testing-library/jest-dom, @testing-library/cypress/add-commands) - require-module-specifiers: removed redundant `export {}` from cypress/support/e2e.ts (file already has an import) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix TypeScript errors from no-non-null-assertion fixes Two fixes introduced by the non-null assertion cleanup produced type errors: - scoring-event.ts: `?? ""` was wrong type for a participant object map; restructured to explicit null guards so TypeScript can narrow correctly - standings-sync/index.ts: `?? null` after name-match lookup lost the truthy guarantee, causing TS18047 on the write-back block; added `participant &&` guard before accessing its properties Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Add npm run typecheck as Stop hook in Claude settings Runs a full project typecheck at the end of each Claude turn so type errors surface as feedback before the next message. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
.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;
}