brackt/app/lib/__tests__/corona-states.test.ts
Claude 75960a8826
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 3m5s
🚀 Deploy / ʦ🔍 Typecheck & Lint (pull_request) Successful in 1m20s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
Fix review findings in the tie-split ledger and backfill
A review of the previous two commits found five defects in the new ledger
writer and backfill, plus one pre-existing scoring bug the refactor
exposed.

season_standings ties were never split. processSeasonStandings
deliberately writes the same finalPosition to every driver in a tied group
-- its comment says "the scoring system will handle averaging" -- but no
path ever did, so two drivers tied for 3rd each banked the full 50 instead
of the published 45. This predates the tie-split work; the original
cascade had only bracket and qualifying_points arms. Introduce
usesSharedPlacementSplit as the single definition of which patterns record
ties as a repeated placement, and route both calculatePickPoints and every
caller-side gate through it. The caller gates matter as much as the
helper: a gate left hardcoded to qualifying_points silently passes a tie
count of 1, which reads as "no tie" and makes the fix inert.

The ledger anchor picked the wrong event. Ordering on completedAt with no
isComplete filter ranked never-completed events first, because drizzle's
desc() emits a bare desc and Postgres orders DESC as NULLS FIRST.
Restrict to completed events and order explicitly with NULLS LAST plus a
stable tiebreak. The anchor is also no longer load-bearing for
idempotence: stale event-level rows for the sports season are cleared
before writing, so a re-run whose anchor moved replaces rather than
duplicates.

A ledger failure could abort finalization. The call sat unguarded after
the season was already marked completed, so a throw in any of its queries
would skip the standings recalculation and the Discord notification. Guard
both call sites the way the probability refresh directly below already is.

Rows could be mislabelled permanently. The backfill passed no eventName,
and the upsert never rewrote scoringEventName. Derive the label from the
scoring pattern inside the writer so omitting it is impossible, and
refresh it on conflict so existing rows can be repaired.

The backfill damaged unrelated leagues. recalculateStandings rewrites
previousRank, so sweeping every season wiped rank-movement arrows league
wide, including leagues holding no tie at all. Scope it to seasons
drafting from a sports season that actually contains a tied placement, and
correct the docblock that called it a pure recompute.

Also drops the inert Number.EPSILON guard from calculateAveragedPoints
(EPSILON is below the ULP for any value >= 2, and integer averages landing
on .5 are exactly representable) and extracts countSharedPlacements so the
ledger writer stops re-querying rows it already holds.

Every fix is covered by a test confirmed to fail when that fix alone is
reverted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019LZLF1PAfeKdpYog3NKtyz
2026-08-23 01:57:54 +00:00

135 lines
4 KiB
TypeScript

import { describe, it, expect } from "vitest";
import { computeCoronaStates } from "../corona-states";
const RULES = {
pointsFor1st: 100, pointsFor2nd: 70, pointsFor3rd: 50, pointsFor4th: 40,
pointsFor5th: 25, pointsFor6th: 25, pointsFor7th: 15, pointsFor8th: 15,
};
function pick(id: string, scoringPattern: string | null, sportsSeasonId = "ss-1") {
return { participant: { id, sportsSeasonId }, scoringPattern };
}
function results(
rows: Array<{ participantId: string; finalPosition: number | null; isPartialScore?: boolean }>
) {
return new Map(
rows.map((r) => [r.participantId, { isPartialScore: false, ...r }])
);
}
describe("computeCoronaStates", () => {
const noTies = new Map<string, Map<number, number>>();
it("splits points for a tied qualifying_points pick", () => {
// Rahm tied for 8th. 9th is outside the scoring range and contributes 0,
// so (15 + 0) / 2 = 7.5 → 8. Before the shared helper this path awarded the
// full 15 while the standings awarded the split — the reported bug.
const states = computeCoronaStates(
[pick("rahm", "qualifying_points")],
results([{ participantId: "rahm", finalPosition: 8 }]),
new Map(),
RULES,
RULES.pointsFor1st,
new Map([["ss-1", new Map([[8, 2]])]])
);
expect(states.rahm).toEqual({
type: "scored",
points: 8,
brightness: 8 / 100,
});
});
it("awards the full value when the placement is untied", () => {
const states = computeCoronaStates(
[pick("rahm", "qualifying_points")],
results([{ participantId: "rahm", finalPosition: 8 }]),
new Map(),
RULES,
RULES.pointsFor1st,
noTies
);
expect(states.rahm).toMatchObject({ type: "scored", points: 15 });
});
it("still averages bracket tiers via the bracket template", () => {
const states = computeCoronaStates(
[pick("team-a", "playoff_bracket")],
results([{ participantId: "team-a", finalPosition: 5 }]),
new Map([["ss-1", null]]),
RULES,
RULES.pointsFor1st,
noTies
);
// Four QF losers share 5th-8th: (25 + 25 + 15 + 15) / 4 = 20
expect(states["team-a"]).toMatchObject({ type: "scored", points: 20 });
});
it("scores other patterns straight off the placement", () => {
const states = computeCoronaStates(
[pick("driver", "season_standings")],
results([{ participantId: "driver", finalPosition: 2 }]),
new Map(),
RULES,
RULES.pointsFor1st,
noTies
);
expect(states.driver).toMatchObject({ type: "scored", points: 70 });
});
it("splits a tied season_standings placement", () => {
const states = computeCoronaStates(
[pick("driver", "season_standings")],
results([{ participantId: "driver", finalPosition: 3 }]),
new Map(),
RULES,
RULES.pointsFor1st,
new Map([["ss-1", new Map([[3, 2]])]])
);
expect(states.driver).toMatchObject({ type: "scored", points: 45 });
});
it("marks picks with no result as pending", () => {
const states = computeCoronaStates(
[pick("rahm", "qualifying_points")],
results([]),
new Map(),
RULES,
RULES.pointsFor1st,
noTies
);
expect(states.rahm).toEqual({ type: "pending" });
});
it("marks a finalized zero placement as eliminated", () => {
const states = computeCoronaStates(
[pick("rahm", "qualifying_points")],
results([{ participantId: "rahm", finalPosition: 0 }]),
new Map(),
RULES,
RULES.pointsFor1st,
noTies
);
expect(states.rahm).toEqual({ type: "eliminated", points: 0 });
});
it("keeps brightness within range when a tier exceeds maxPoints", () => {
const states = computeCoronaStates(
[pick("champ", "season_standings")],
results([{ participantId: "champ", finalPosition: 1 }]),
new Map(),
RULES,
10, // deliberately below the 1st-place award
noTies
);
expect(states.champ).toMatchObject({ brightness: 1 });
});
});