From e64dcdb0a07bae5f336c9da155f3116a3bef8e51 Mon Sep 17 00:00:00 2001 From: Kalle <38327916+Sendouc@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:42:35 +0200 Subject: [PATCH] Superjump bracket progression hotfixes --- .../tournament-bracket/core/Bracket.test.ts | 136 +++++++++++++++++- .../core/Bracket/Bracket.ts | 85 +++++++++-- ...bracket-advancement-preview-wrong-teams.md | 5 + ...026-11-14-start-follow-up-bracket-early.md | 5 + code-review-findings.md | 29 ++++ .../docs/guides/tournament-creation.mdx | 2 + 6 files changed, 251 insertions(+), 11 deletions(-) create mode 100644 changelog/2026-11-14-bracket-advancement-preview-wrong-teams.md create mode 100644 changelog/2026-11-14-start-follow-up-bracket-early.md create mode 100644 code-review-findings.md diff --git a/app/features/tournament-bracket/core/Bracket.test.ts b/app/features/tournament-bracket/core/Bracket.test.ts index 8aae16d61..85790ae73 100644 --- a/app/features/tournament-bracket/core/Bracket.test.ts +++ b/app/features/tournament-bracket/core/Bracket.test.ts @@ -1733,10 +1733,10 @@ describe("single elimination sourcing - placements are tiers", () => { .bracketByIdx(1)! .previewSeeding!.toSorted((a, b) => a - b); - test("sources only the semifinal losers while the final is unplayed", () => { + test("sources the semifinal and quarterfinal losers by their tiers while the final is unplayed", () => { const beforeFinal = playOut(14); - expect(top4Seeding(beforeFinal)).toEqual([3, 4]); + expect(top4Seeding(beforeFinal)).toEqual([3, 4, 5, 6, 7, 8]); }); // without a third place match the placements are 1, 2, 3, 3, 5, 5, 5, 5, 9... @@ -2163,6 +2163,138 @@ describe("grouped elimination - edge cases", () => { }); }); +// pools of 10 and 9 teams leave raw placement gaps (1, 2, 3, 4, 5, 7, 9) until every team is placed +describe("grouped double elimination - sourcing while underway", () => { + const TEAM_IDS = Array.from({ length: 19 }, (_, index) => index + 1); + const PROGRESSION: TournamentSettings["bracketProgression"] = [ + { + type: "double_elimination", + name: "Pools", + requiresCheckIn: false, + settings: { + groupCount: 2, + skippedRounds: ["LB_FINALS", "GRAND_FINALS", "BRACKET_RESET"], + }, + }, + { + type: "double_elimination", + name: "Delta", + requiresCheckIn: false, + settings: {}, + sources: [{ bracketIdx: 0, placements: [6] }], + }, + { + type: "round_robin", + name: "Epsilon Seeding", + requiresCheckIn: false, + settings: { teamsPerGroup: 4 }, + sources: [{ bracketIdx: 0, placements: [7] }], + }, + ]; + + const startedPools = () => + createResolved({ + type: "double_elimination", + seeding: TEAM_IDS, + settings: PROGRESSION[0].settings, + }); + + /** Winners rounds 1-2 and the losers rounds up to `lastLosersRound` played, the later rounds of both groups unplayed. Losers round 1 is only BYEs. */ + const poolsPlayedUpTo = (lastLosersRound: number) => { + let data = startedPools(); + const rounds = data.round; + const isPlayed = (match: MatchData) => { + const round = rounds.find((candidate) => candidate.id === match.roundId)!; + + return ( + round.number <= (round.section === "winners" ? 2 : lastLosersRound) + ); + }; + + let ready = readyMatches(data, isPlayed); + while (ready.length) { + for (const match of ready) { + data = reportLowerIdWinner(data, match.id); + } + ready = readyMatches(data, isPlayed); + } + + return data; + }; + + /** Played up to and including the losers round knocking out the 1-2 teams. */ + const underwayPools = () => poolsPlayedUpTo(3); + + const tournamentOf = (pools: BracketData) => + testTournament({ + ctx: { + settings: { bracketProgression: PROGRESSION }, + teams: TEAM_IDS.map((id) => tournamentCtxTeam(id, { seed: id })), + }, + data: pools, + }); + + const sortedIds = (ids: number[] | undefined) => + (ids ?? []).toSorted((a, b) => a - b); + + test("advances the losers of the first losers round to the bracket sourcing their tier", () => { + const tournament = tournamentOf(underwayPools()); + const firstLosersRoundLosers = tournament + .bracketByIdx(0)! + .source({ placements: [-1] }).teams; + + expect(firstLosersRoundLosers).toHaveLength(3); + expect(sortedIds(tournament.bracketByIdx(2)!.previewSeeding)).toEqual( + sortedIds(firstLosersRoundLosers), + ); + }); + + test("advances the losers of the second losers round to the bracket sourcing their tier", () => { + const tournament = tournamentOf(underwayPools()); + const pools = tournament.bracketByIdx(0)!; + const firstLosersRoundLosers = pools.source({ placements: [-1] }).teams; + const secondLosersRoundLosers = pools + .source({ placements: [-2] }) + .teams.filter((teamId) => !firstLosersRoundLosers.includes(teamId)); + + expect(secondLosersRoundLosers).toHaveLength(4); + expect(sortedIds(tournament.bracketByIdx(1)!.previewSeeding)).toEqual( + sortedIds(secondLosersRoundLosers), + ); + }); + + test("advances the same teams while underway as once the pools are played out", () => { + const underway = tournamentOf(underwayPools()); + const finished = tournamentOf(playedOut(startedPools())); + + expect(finished.bracketByIdx(0)!.everyMatchOver).toBe(true); + for (const bracketIdx of [1, 2]) { + expect( + sortedIds(finished.bracketByIdx(bracketIdx)!.previewSeeding), + ).toEqual(sortedIds(underway.bracketByIdx(bracketIdx)!.previewSeeding)); + } + }); + + test("a follow-up can be started once the matches its teams leave the pools from are decided", () => { + const tournament = tournamentOf(poolsPlayedUpTo(2)); + + expect(tournament.bracketByIdx(0)!.everyMatchOver).toBe(false); + expect(tournament.bracketByIdx(2)!.canBeStarted).toBe(true); + }); + + test("a follow-up can't be started while a match its teams leave the pools from is undecided", () => { + const tournament = tournamentOf(poolsPlayedUpTo(2)); + + expect(tournament.bracketByIdx(1)!.canBeStarted).toBe(false); + }); + + test("a follow-up can't be started before any of its teams have left the pools", () => { + const tournament = tournamentOf(poolsPlayedUpTo(1)); + + expect(tournament.bracketByIdx(2)!.canBeStarted).toBe(false); + }); +}); + describe("follow-up seeding through a redemption bracket", () => { const TEAM_IDS = Array.from({ length: 32 }, (_, index) => index + 1); const PROGRESSION: TournamentSettings["bracketProgression"] = [ diff --git a/app/features/tournament-bracket/core/Bracket/Bracket.ts b/app/features/tournament-bracket/core/Bracket/Bracket.ts index 16bcb78e6..15eeea8b4 100644 --- a/app/features/tournament-bracket/core/Bracket/Bracket.ts +++ b/app/features/tournament-bracket/core/Bracket/Bracket.ts @@ -3,7 +3,10 @@ import type { Tables } from "~/db/tables"; import type { TournamentStageSettings } from "~/db/tables-json"; import * as Standings from "~/features/tournament/core/Standings"; import { TOURNAMENT } from "~/features/tournament/tournament-constants"; -import type { BracketData } from "~/features/tournament-bracket/core/engine/types"; +import type { + BracketData, + MatchData, +} from "~/features/tournament-bracket/core/engine/types"; import { invariant } from "~/utils/invariant"; import { logger } from "~/utils/logger"; import { showsOneGroupAtATime } from "../../tournament-bracket-utils"; @@ -717,12 +720,17 @@ export abstract class Bracket { }; /** - * Only settled teams appear in the standings, so placements are matched raw until the full - * standings resolve and only then normalized (1,3,5 -> 1,2,3) the way group brackets source. + * Settled teams are matched by the tier of the match they left the bracket from, the same tier the + * bracket shows as the match's destination. Raw placements leave gaps (1,3,5) until every team is placed, + * so matching them before that would advance the wrong teams. Teams without an exit fall back to their + * placement, normalized (1,3,5 -> 1,2,3) once the full standings resolve. + * + * Finished as soon as every match teams leave with a sourced tier from is decided, so the follow-up + * can start while the rest of the bracket is still played. */ protected sourceByStandings(placements: number[], rest: boolean) { const standings = this.standings; - const relevantMatchesFinished = + const everyTeamPlaced = standings.length === this.participantTournamentTeamIds.length && this.participantTournamentTeamIds.length > 0; @@ -732,18 +740,56 @@ export abstract class Bracket { const uniquePlacements = R.unique(standings.map((s) => s.placement)); const placementNormalized = (placement: number) => - relevantMatchesFinished - ? uniquePlacements.indexOf(placement) + 1 - : placement; + everyTeamPlaced ? uniquePlacements.indexOf(placement) + 1 : placement; + + const exits = this.matchExits(); + const exitTierByTeamId = this.exitTierByTeamId(exits); + const tierOf = (standing: Standing) => + exitTierByTeamId.get(standing.team.id) ?? + placementNormalized(standing.placement); + + const sourcedExitMatches = this.data.match.filter((match) => { + const exit = exits.get(match.id); + + return [exit?.winnerTier, exit?.loserTier].some( + (tier) => typeof tier === "number" && matchesPlacement(tier), + ); + }); + const everySourcedExitDecided = + sourcedExitMatches.length > 0 && sourcedExitMatches.every(isDecided); return { - relevantMatchesFinished, + relevantMatchesFinished: everyTeamPlaced || everySourcedExitDecided, teams: standings - .filter((s) => matchesPlacement(placementNormalized(s.placement))) + .filter((s) => matchesPlacement(tierOf(s))) .map((s) => s.team.id), }; } + /** Tier of the decided match each team left the bracket from, keyed by tournament team id. */ + private exitTierByTeamId(exits: Map) { + const result = new Map(); + + for (const match of this.data.match) { + const exit = exits.get(match.id); + const winnerSide = winnerSideOf(match); + if (!exit || !winnerSide) continue; + + const winnerId = match[winnerSide]?.id; + const loserId = + match[winnerSide === "opponent1" ? "opponent2" : "opponent1"]?.id; + + if (typeof winnerId === "number" && typeof exit.winnerTier === "number") { + result.set(winnerId, exit.winnerTier); + } + if (typeof loserId === "number" && typeof exit.loserTier === "number") { + result.set(loserId, exit.loserTier); + } + } + + return result; + } + /** Statuses of every match of the bracket, keyed by match id. */ matchStatuses() { if (!this._matchStatuses) { @@ -763,3 +809,24 @@ export abstract class Bracket { abstract defaultRoundBestOfs(data: BracketData): BracketMapCounts; } + +/** The side that won, or the side advancing past a BYE once its team is known. Null while undecided. */ +function winnerSideOf(match: MatchData) { + if (match.winnerSide) return match.winnerSide; + if (match.opponent1 && match.opponent2) return null; + + const advancingSide = match.opponent1 + ? "opponent1" + : match.opponent2 + ? "opponent2" + : null; + if (!advancingSide) return null; + + return typeof match[advancingSide]?.id === "number" ? advancingSide : null; +} + +function isDecided(match: MatchData) { + if (!match.opponent1 && !match.opponent2) return true; + + return winnerSideOf(match) !== null; +} diff --git a/changelog/2026-11-14-bracket-advancement-preview-wrong-teams.md b/changelog/2026-11-14-bracket-advancement-preview-wrong-teams.md new file mode 100644 index 000000000..cb1eba334 --- /dev/null +++ b/changelog/2026-11-14-bracket-advancement-preview-wrong-teams.md @@ -0,0 +1,5 @@ +--- +navItem: medal +type: bug +--- +Fixed a follow-up bracket showing the wrong teams as advanced while a grouped elimination bracket was still being played diff --git a/changelog/2026-11-14-start-follow-up-bracket-early.md b/changelog/2026-11-14-start-follow-up-bracket-early.md new file mode 100644 index 000000000..1b9adae42 --- /dev/null +++ b/changelog/2026-11-14-start-follow-up-bracket-early.md @@ -0,0 +1,5 @@ +--- +navItem: medal +type: feature +--- +A follow-up bracket can be started as soon as every team going to it from an elimination bracket is decided, without waiting for the rest of that bracket to be played diff --git a/code-review-findings.md b/code-review-findings.md new file mode 100644 index 000000000..3b52b9bda --- /dev/null +++ b/code-review-findings.md @@ -0,0 +1,29 @@ +# Code Review + +_uncommitted changes on main — 2026-11-14_ + +**3 issues found** + +## 1. [test-coverage] No test notices a BYE-vs-TBD sourced match counted as decided + +`app/features/tournament-bracket/core/Bracket/Bracket.ts:814` — warning + +Mutation run: 14 of 15 mutants in `winnerSideOf` and 5 of 7 in `isDecided` (lines 814–832) survive. One example: `return true ? advancingSide : null` at line 825, or `!match.opponent1 || !match.opponent2` at line 829. Either one makes a match where a BYE waits on a still-unknown team (BYE vs TBD) count as decided. If that shipped, an organizer could start the follow-up bracket before a team going to it is known, and that team would be missing from the follow-up's seeding. + +**Suggestion**: In `Bracket.test.ts`, add a grouped elimination case where a sourced-tier match is BYE vs TBD because its feeder match is unplayed. Assert that `canBeStarted` / `relevantMatchesFinished` is false there, and true once the feeder is reported. Also add a BYE-vs-BYE sourced match that does not block an early start. + +## 2. [test-coverage] Early start with exactly one sourced match is untested + +`app/features/tournament-bracket/core/Bracket/Bracket.ts:759` — warning + +Mutation `sourcedExitMatches.length > 0` → `> 1` survives. Every new test sources tiers that span several matches. Take a follow-up that takes the exits of a single match, such as the loser of losers finals in a non-grouped double elimination bracket: with this mutant it could never start early, and the new feature would silently not work for it. + +**Suggestion**: Add a test in which the follow-up sources a tier that only one match produces. Decide that match while the rest of the bracket (e.g. grand finals) is still unplayed, and assert that the follow-up can be started. + +## 3. [abstraction] `isDecided` reimplements the engine's `isMatchCompleted` + +`app/features/tournament-bracket/core/Bracket/Bracket.ts:828` — info + +`isMatchCompleted` in `app/features/tournament-bracket/core/engine/status.ts:46` (`isMatchByeCompleted(match) || Boolean(match.winnerSide)`) treats every case the same way as `isDecided`: BYE vs team, BYE vs BYE, BYE vs TBD and a set `winnerSide`. `MatchData` extends `MatchResults`, so it type-checks. Keeping two definitions of "decided match" lets them drift apart. + +**Suggestion**: Delete `isDecided` and use `sourcedExitMatches.every(isMatchCompleted)`. Keep `winnerSideOf` only for `exitTierByTeamId`, which needs the winning side. This also removes the `isDecided` survivors from finding 1. diff --git a/docs/site/src/content/docs/guides/tournament-creation.mdx b/docs/site/src/content/docs/guides/tournament-creation.mdx index 85932bcd1..18befc22e 100644 --- a/docs/site/src/content/docs/guides/tournament-creation.mdx +++ b/docs/site/src/content/docs/guides/tournament-creation.mdx @@ -188,6 +188,8 @@ Placements are relative in the sense that the amount of teams that sign up don't For example in a round robin bracket with two groups of four teams each, placement `1` is both groups' winners and placement `4` both groups' last placed teams. +From a single or double elimination bracket the placement is decided by the round a team gets knocked out in, the same for every group. A follow-up bracket taking those teams can be started as soon as all of them are decided, even while the rest of the elimination bracket is still being played. + ### Start time Whether to start the bracket right after the previous one concludes or at some other time. This can be useful for two day tournaments. Note that it's not really meant to organize an event that spans many weeks, use a [league](#leagues) for that instead. Only available for brackets that take their teams from another bracket.