diff --git a/apps/api/src/modules/competition/domain/series-graph.spec.ts b/apps/api/src/modules/competition/domain/series-graph.spec.ts index 95b0e74f..57e5c34e 100644 --- a/apps/api/src/modules/competition/domain/series-graph.spec.ts +++ b/apps/api/src/modules/competition/domain/series-graph.spec.ts @@ -159,7 +159,13 @@ describe('generateSeriesGraph', () => { }; const first = generateSeriesGraph(input); - const second = generateSeriesGraph(input); + const second = generateSeriesGraph({ + ...input, + format: { + ...input.format, + pairings: [...input.format.pairings].reverse(), + }, + }); expect(second).toEqual(first); expect( @@ -234,6 +240,68 @@ describe('generateSeriesGraph', () => { ])('rejects a duplicate explicit $name', ({ pairings, code }) => { expectGraphError(explicitRoundRobinInput(pairings), code); }); + + it('keeps distinct opponent pairs when opaque TeamIds contain delimiters', () => { + const input = explicitRoundRobinInput([ + pairing(1, 1, 'a', 'b:c'), + pairing(1, 2, 'a:b', 'c'), + ]); + input.format.maxRounds = 1; + input.teams = ['a', 'b:c', 'a:b', 'c'].map((teamId, index) => ({ + teamId, + displayOrder: index + 1, + seedNumber: index + 1, + })); + + expect(generateSeriesGraph(input)).toHaveLength(2); + }); + + it('validates complete odd-team rounds and clamps maxRounds to the full schedule', () => { + const pairings = [ + pairing(1, 1, 'team-2', 'team-5'), + pairing(1, 2, 'team-3', 'team-4'), + pairing(2, 1, 'team-1', 'team-5'), + pairing(2, 2, 'team-2', 'team-3'), + pairing(3, 1, 'team-1', 'team-4'), + pairing(3, 2, 'team-3', 'team-5'), + pairing(4, 1, 'team-1', 'team-3'), + pairing(4, 2, 'team-2', 'team-4'), + pairing(5, 1, 'team-1', 'team-2'), + pairing(5, 2, 'team-4', 'team-5'), + ]; + const input = explicitRoundRobinInput(pairings); + input.teams = Array.from({ length: 5 }, (_, index) => ({ + teamId: `team-${index + 1}`, + displayOrder: index + 1, + seedNumber: index + 1, + })); + input.format.maxRounds = 10; + + expect(generateSeriesGraph(input)).toHaveLength(10); + }); + + it.each([ + { + name: 'an expected round', + pairings: [ + pairing(1, 1, 'team-1', 'team-2'), + pairing(1, 2, 'team-3', 'team-4'), + ], + }, + { + name: 'a match from an expected round', + pairings: [ + pairing(1, 1, 'team-1', 'team-2'), + pairing(1, 2, 'team-3', 'team-4'), + pairing(2, 1, 'team-1', 'team-3'), + ], + }, + ])('rejects explicit pairings missing $name', ({ pairings }) => { + expectGraphError( + explicitRoundRobinInput(pairings), + 'INCOMPLETE_ROUND_ROBIN_PAIRINGS', + ); + }); }); function firstTo(winsRequired: number, maxGames: number) { diff --git a/apps/api/src/modules/competition/domain/series-graph.ts b/apps/api/src/modules/competition/domain/series-graph.ts index 1b72d012..0632dcaf 100644 --- a/apps/api/src/modules/competition/domain/series-graph.ts +++ b/apps/api/src/modules/competition/domain/series-graph.ts @@ -304,7 +304,7 @@ function validateExplicitRoundRobinPairings( } positions.add(position); - const opponents = [pairing.teamAId, pairing.teamBId].sort().join(':'); + const opponents = JSON.stringify([pairing.teamAId, pairing.teamBId].sort()); if (opponentPairs.has(opponents)) { throw graphError( 'DUPLICATE_ROUND_ROBIN_OPPONENTS', @@ -338,6 +338,28 @@ function validateExplicitRoundRobinPairings( ); } } + + const expectedRoundCount = roundRobinRoundCount(teams.length, maxRounds); + const expectedMatchesPerRound = Math.floor(teams.length / 2); + for ( + let roundNumber = 1; + roundNumber <= expectedRoundCount; + roundNumber += 1 + ) { + const matchCount = (teamsByRound.get(roundNumber)?.size ?? 0) / 2; + if (matchCount !== expectedMatchesPerRound) { + throw graphError( + 'INCOMPLETE_ROUND_ROBIN_PAIRINGS', + `Round ${roundNumber} must contain ${expectedMatchesPerRound} Series.`, + ); + } + } + if (teamsByRound.size !== expectedRoundCount) { + throw graphError( + 'INCOMPLETE_ROUND_ROBIN_PAIRINGS', + `Explicit round-robin pairings must contain rounds 1 through ${expectedRoundCount}.`, + ); + } return sorted; } @@ -549,14 +571,7 @@ function roundRobinPairings( const rotating = Array.from({ length: teamCount }, (_, index) => index); if (rotating.length % 2 === 1) rotating.push(bye); - const fullRoundCount = rotating.length - 1; - const requestedRounds = - maxRounds === undefined - ? fullRoundCount - : Number.isFinite(maxRounds) - ? Math.floor(maxRounds) - : fullRoundCount; - const roundCount = Math.max(0, Math.min(fullRoundCount, requestedRounds)); + const roundCount = roundRobinRoundCount(teamCount, maxRounds); const pairings: CanonicalRoundRobinPairing[] = []; for (let roundIndex = 0; roundIndex < roundCount; roundIndex += 1) { @@ -580,6 +595,17 @@ function roundRobinPairings( return pairings; } +function roundRobinRoundCount(teamCount: number, maxRounds?: number): number { + const fullRoundCount = teamCount % 2 === 0 ? teamCount - 1 : teamCount; + const requestedRounds = + maxRounds === undefined + ? fullRoundCount + : Number.isFinite(maxRounds) + ? Math.floor(maxRounds) + : fullRoundCount; + return Math.max(0, Math.min(fullRoundCount, requestedRounds)); +} + function normalizeTeams( teams: readonly CompetitionGraphTeam[], ): CompetitionGraphTeam[] { diff --git a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts index c7df6f59..cd3f7b3e 100644 --- a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts +++ b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts @@ -199,6 +199,387 @@ describe('planCompetitionMigration', () => { ).toHaveLength(12); }); + it('maps a result-less code through an interleaved persisted round-robin schedule', () => { + const legacy = pairedMatch({ + _id: 'match-persisted-round-robin-code', + gameMode: 'round-robin', + gameCount: 2, + roundRobinMaxRounds: 1, + teams: [ + legacyTeam(1, 'One'), + legacyTeam(2, 'Two'), + legacyTeam(3, 'Three'), + legacyTeam(4, 'Four'), + ], + gameSchedule: [ + { gameNumber: 1, roundNumber: 1, teamAIndex: 1, teamBIndex: 3 }, + { gameNumber: 2, roundNumber: 1, teamAIndex: 2, teamBIndex: 4 }, + { gameNumber: 3, roundNumber: 1, teamAIndex: 1, teamBIndex: 3 }, + { gameNumber: 4, roundNumber: 1, teamAIndex: 2, teamBIndex: 4 }, + ], + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'persisted-round-robin-code-game-3', + state: 'reserved', + gameNumber: 3, + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + const expectedSeries = plan.competition.seriesGraph.find( + (series) => series.code === 'RR_R1_M1', + ); + + expect(expectedSeries).toBeDefined(); + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + seriesId: expectedSeries!.id, + gameSlotId: expectedSeries!.gameSlots[1].id, + }), + ); + }); + + it('quarantines an incomplete persisted round-robin schedule', () => { + const legacy = pairedMatch({ + _id: 'match-incomplete-round-robin-schedule', + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 2, + teams: [ + legacyTeam(1, 'One'), + legacyTeam(2, 'Two'), + legacyTeam(3, 'Three'), + legacyTeam(4, 'Four'), + ], + gameSchedule: [ + { gameNumber: 1, roundNumber: 1, teamAIndex: 1, teamBIndex: 2 }, + { gameNumber: 2, roundNumber: 1, teamAIndex: 3, teamBIndex: 4 }, + { gameNumber: 3, roundNumber: 2, teamAIndex: 1, teamBIndex: 3 }, + ], + result: { games: [], seriesResults: [] }, + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'SERIES_GRAPH_GENERATION_FAILED'); + if (plan.status === 'quarantined') { + expect(plan.reasons).toContainEqual( + expect.objectContaining({ + code: 'SERIES_GRAPH_GENERATION_FAILED', + details: { + projectorCode: 'INCOMPLETE_ROUND_ROBIN_PAIRINGS', + }, + }), + ); + } + }); + + it('reconstructs playable rounds for a complete legacy schedule without round numbers', () => { + const schedule = [ + [2, 5], + [1, 2], + [4, 5], + [1, 6], + [5, 6], + [4, 6], + [2, 6], + [3, 5], + [2, 3], + [1, 4], + [3, 6], + [1, 3], + [3, 4], + [1, 5], + [2, 4], + ] as const; + const legacy = pairedMatch({ + _id: 'match-legacy-round-robin-without-rounds', + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: undefined, + teams: Array.from({ length: 6 }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + gameSchedule: schedule.map(([teamAIndex, teamBIndex], index) => ({ + gameNumber: index + 1, + teamAIndex, + teamBIndex, + })), + result: { games: [], seriesResults: [] }, + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.competition.seriesGraph).toHaveLength(15); + expect( + new Set( + plan.competition.seriesGraph.map((series) => series.stage.roundNumber), + ), + ).toHaveProperty('size', 5); + expect(plan.warnings).toContainEqual( + expect.objectContaining({ + code: 'LEGACY_ROUND_ROBIN_ROUNDS_RECONSTRUCTED', + }), + ); + }); + + it('reconstructs a large complete opponent-only schedule without combinatorial search', () => { + const teamCount = 14; + const pairs = Array.from({ length: teamCount }, (_, left) => + Array.from( + { length: teamCount - left - 1 }, + (_, offset) => [left + 1, left + offset + 2] as const, + ), + ).flat(); + const legacy = pairedMatch({ + _id: 'match-large-complete-round-robin-without-rounds', + gameMode: 'round-robin', + gameCount: 1, + teams: Array.from({ length: teamCount }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + gameSchedule: pairs.map(([teamAIndex, teamBIndex], index) => ({ + gameNumber: index + 1, + teamAIndex, + teamBIndex, + })), + result: { games: [], seriesResults: [] }, + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.competition.seriesGraph).toHaveLength(91); + }); + + it('rejects a large infeasible partial opponent schedule during degree preflight', () => { + const teamCount = 14; + const pairs = Array.from({ length: teamCount }, (_, left) => + Array.from( + { length: teamCount - left - 1 }, + (_, offset) => [left + 1, left + offset + 2] as const, + ), + ) + .flat() + .slice(0, 49); + const legacy = pairedMatch({ + _id: 'match-large-infeasible-round-robin-without-rounds', + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 7, + teams: Array.from({ length: teamCount }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + gameSchedule: pairs.map(([teamAIndex, teamBIndex], index) => ({ + gameNumber: index + 1, + teamAIndex, + teamBIndex, + })), + result: { games: [], seriesResults: [] }, + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'INVALID_ROUND_ROBIN_SCHEDULE'); + }); + + it('uses a dedicated quarantine code for unsupported large partial round reconstruction', () => { + const teamCount = 20; + const rotating = Array.from({ length: teamCount }, (_, index) => index + 1); + const pairs: Array = []; + for (let round = 0; round < 10; round += 1) { + for (let index = 0; index < teamCount / 2; index += 1) { + pairs.push([rotating[index], rotating[teamCount - 1 - index]]); + } + const fixed = rotating[0]; + const tail = rotating.slice(1); + tail.unshift(tail.pop()!); + rotating.splice(0, rotating.length, fixed, ...tail); + } + const legacy = pairedMatch({ + _id: 'match-unsupported-large-partial-round-reconstruction', + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 10, + teams: Array.from({ length: teamCount }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + gameSchedule: pairs.reverse().map(([teamAIndex, teamBIndex], index) => ({ + gameNumber: index + 1, + teamAIndex, + teamBIndex, + })), + result: { games: [], seriesResults: [] }, + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason( + plan, + 'ROUND_ROBIN_ROUND_RECONSTRUCTION_UNSUPPORTED', + ); + }); + + it('preserves a sparse global game number as the exact paired-Series slot', () => { + const legacy = pairedMatch({ + _id: 'match-sparse-paired-game-number', + gameCount: 3, + teams: [legacyTeam(1, 'One'), legacyTeam(2, 'Two')], + gameSchedule: undefined, + result: { + games: [ + legacyGame({ + gameNumber: 2, + riotMatchId: 'KR_SPARSE_PAIR_GAME_2', + riotArchivePresent: true, + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'sparse-pair-code-game-2', + state: 'used', + gameNumber: 2, + riotMatchId: 'KR_SPARSE_PAIR_GAME_2', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + const series = plan.competition.seriesGraph[0]; + const gameFact = plan.facts.find((fact) => fact.type === 'game-accepted'); + + expect(gameFact).toMatchObject({ + type: 'game-accepted', + seriesId: series.id, + gameSlotId: series.gameSlots[1].id, + ordinal: 2, + }); + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + seriesId: series.id, + gameSlotId: series.gameSlots[1].id, + }), + ); + }); + + it('preserves a sparse double-elimination global game number and binds its used code to the same slot', () => { + const legacy = sparseDoubleEliminationWbFinalMatch(); + + const plan = requireReady(planCompetitionMigration(legacy)); + const wbFinal = plan.competition.seriesGraph.find( + (series) => series.code === 'WB_FINAL', + ); + + expect(wbFinal).toBeDefined(); + const wbFinalFact = plan.facts.find( + (fact) => fact.type === 'game-accepted' && fact.seriesId === wbFinal!.id, + ); + expect(wbFinalFact).toMatchObject({ + type: 'game-accepted', + seriesId: wbFinal!.id, + gameSlotId: wbFinal!.gameSlots[1].id, + ordinal: 2, + evidence: { + type: 'riot', + riotMatchId: 'KR_SPARSE_WB_FINAL_GAME_2', + }, + }); + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + tournamentCodeId: 'sparse-wb-final-code-game-2', + state: 'used', + seriesId: wbFinal!.id, + gameSlotId: wbFinal!.gameSlots[1].id, + riotMatchId: 'KR_SPARSE_WB_FINAL_GAME_2', + }), + ); + }); + + it('quarantines a used TournamentCode when its slot has no accepted game', () => { + const legacy = pairedMatch({ + _id: 'match-used-code-without-game', + gameCount: 1, + gameSchedule: undefined, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'used-code-without-game', + state: 'used', + gameNumber: 1, + usedAt: '2026-07-02T00:00:00.000Z', + }, + ], + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'USED_CODE_WITHOUT_ACCEPTED_GAME'); + }); + + it('binds a used code without Riot identity to the accepted game in its exact slot', () => { + const legacy = pairedMatch({ + _id: 'match-used-code-by-slot', + gameCount: 1, + gameSchedule: undefined, + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_USED_CODE_BY_SLOT', + riotArchivePresent: true, + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'used-code-by-slot', + state: 'used', + gameNumber: 1, + usedAt: '2026-07-02T00:00:00.000Z', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments).toHaveLength(1); + expect(plan.warnings).toEqual([]); + }); + + it('preserves the actual voided lifecycle timestamp', () => { + const legacy = pairedMatch({ + _id: 'match-voided-code-timestamp', + gameCount: 1, + gameSchedule: undefined, + tournamentCodes: [ + { + _id: 'voided-code-with-timestamp', + state: 'voided', + gameNumber: 1, + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + voidedAt: '2026-07-03T00:00:00.000Z', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + state: 'voided', + voidedAt: '2026-07-03T00:00:00.000Z', + }), + ); + }); + it('maps a result-less reserved TournamentCode by its global game number', () => { const legacy = pairedMatch({ _id: 'match-future-reserved-code', @@ -558,3 +939,91 @@ function dataTxtUpperBracketTopology() { bracketSide: 'winner' as const, })); } + +function sparseDoubleEliminationWbFinalMatch(): LegacyMatchInput { + const completedSeries = [ + ['WB_R1_M1', 1, 2, 1, 8, 1], + ['WB_R1_M2', 4, 5, 4, 5, 4], + ['WB_R1_M3', 7, 8, 2, 7, 2], + ['WB_R1_M4', 10, 11, 3, 6, 3], + ['WB_R2_M1', 13, 14, 1, 4, 1], + ['WB_R2_M2', 16, 17, 2, 3, 2], + ] as const; + const games = completedSeries.flatMap( + ([ + bracketMatchId, + firstGameNumber, + secondGameNumber, + teamA, + teamB, + winner, + ]) => [ + legacyGame({ + bracketMatchId, + gameNumber: firstGameNumber, + riotMatchId: `KR_${bracketMatchId}_1`, + riotArchivePresent: true, + blueTeamIndex: teamA, + redTeamIndex: teamB, + winnerTeamIndex: winner, + gameCreation: 1782864000000 + firstGameNumber * 60_000, + }), + legacyGame({ + bracketMatchId, + gameNumber: secondGameNumber, + riotMatchId: `KR_${bracketMatchId}_2`, + riotArchivePresent: true, + blueTeamIndex: teamB, + redTeamIndex: teamA, + winnerTeamIndex: winner, + gameCreation: 1782864000000 + secondGameNumber * 60_000, + }), + ], + ); + games.push( + legacyGame({ + bracketMatchId: 'WB_FINAL', + gameNumber: 20, + riotMatchId: 'KR_SPARSE_WB_FINAL_GAME_2', + riotArchivePresent: true, + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + gameCreation: 1782864000000 + 20 * 60_000, + }), + ); + + return { + _id: 'match-sparse-double-elimination-game-number', + communityId: 'community-1', + gameMode: 'double-elimination', + gameCount: 3, + status: 'in-progress', + teams: Array.from({ length: 8 }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + doubleElimination: { + teamCount: 8, + resetFinalEnabled: true, + seeds: Array.from({ length: 8 }, (_, index) => ({ + seedNumber: index + 1, + teamIndex: index + 1, + })), + bracketMatches: dataTxtUpperBracketTopology(), + }, + result: { games, seriesResults: [] }, + tournamentCodes: [ + { + _id: 'sparse-wb-final-code-game-2', + state: 'used', + bracketMatchId: 'WB_FINAL', + gameNumber: 20, + riotMatchId: 'KR_SPARSE_WB_FINAL_GAME_2', + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + }, + ], + createdAt: '2026-07-01T00:00:00.000Z', + updatedAt: '2026-07-03T00:00:00.000Z', + }; +} diff --git a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts index c9ba7d56..0bae4bbe 100644 --- a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts +++ b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts @@ -91,6 +91,9 @@ interface LegacyTournamentCodeInput { reservedAt?: Date | string; usedAt?: Date | string; releasedAt?: Date | string; + voidedAt?: Date | string; + createdAt?: Date | string; + updatedAt?: Date | string; } export interface LegacyMatchInput { @@ -226,6 +229,7 @@ export interface CompetitionMigrationAssignment { reservedAt: string; usedAt?: string; releasedAt?: string; + voidedAt?: string; riotMatchId?: string; commandId: string; } @@ -405,7 +409,6 @@ export function planCompetitionMigration( facts, seriesGraph, teamBuild.teamIdByLegacyIndex, - warnings, reasons, ); if (reasons.length > 0) { @@ -614,6 +617,7 @@ function buildFormat( input, teamIds, gameCount, + warnings, reasons, ); if (pairings === null) return undefined; @@ -667,6 +671,7 @@ function normalizeLegacyRoundRobinPairings( input: LegacyMatchInput, teamIds: ReadonlyMap, gameCount: number, + warnings: CompetitionMigrationIssue[], reasons: CompetitionMigrationIssue[], ): RoundRobinPairing[] | undefined | null { const schedule = input.gameSchedule ?? []; @@ -676,30 +681,44 @@ function normalizeLegacyRoundRobinPairings( const groups = new Map< string, { - roundNumber: number; + roundNumber?: number; teamAId: string; teamBId: string; gameNumbers: number[]; } >(); - const gamesPerRound = Math.floor(teamIds.size / 2) * gameCount; + const hasRoundNumbers = schedule.some( + (assignment) => assignment.roundNumber !== undefined, + ); + if ( + hasRoundNumbers && + schedule.some((assignment) => assignment.roundNumber === undefined) + ) { + reasons.push( + issue( + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'Persisted round-robin round numbers must be present for every game or absent from every game.', + ), + ); + return null; + } for (const assignment of schedule) { const teamAId = teamIds.get(assignment.teamAIndex); const teamBId = teamIds.get(assignment.teamBIndex); const roundNumber = - positiveInteger(assignment.roundNumber) ?? - (gamesPerRound > 0 && positiveInteger(assignment.gameNumber) - ? Math.floor((assignment.gameNumber - 1) / gamesPerRound) + 1 - : undefined); + assignment.roundNumber === undefined + ? undefined + : positiveInteger(assignment.roundNumber); if ( !positiveInteger(assignment.gameNumber) || seenGameNumbers.has(assignment.gameNumber) || !teamAId || !teamBId || teamAId === teamBId || - !roundNumber || + (hasRoundNumbers && !roundNumber) || (positiveInteger(input.roundRobinMaxRounds) !== undefined && + roundNumber !== undefined && roundNumber > input.roundRobinMaxRounds!) ) { reasons.push( @@ -714,7 +733,7 @@ function normalizeLegacyRoundRobinPairings( seenGameNumbers.add(assignment.gameNumber); const opponents = [teamAId, teamBId].sort(); - const key = opponents.join(':'); + const key = JSON.stringify(opponents); const existing = groups.get(key); if (existing && existing.roundNumber !== roundNumber) { reasons.push( @@ -734,7 +753,7 @@ function normalizeLegacyRoundRobinPairings( teamBId, gameNumbers: [], } satisfies { - roundNumber: number; + roundNumber?: number; teamAId: string; teamBId: string; gameNumbers: number[]; @@ -743,22 +762,59 @@ function normalizeLegacyRoundRobinPairings( groups.set(key, group); } - const orderedGroups = [...groups.values()].sort( + const groupedSeries = [...groups.values()]; + if (!hasRoundNumbers) { + const reconstruction = assignLegacyRoundRobinRounds( + groupedSeries, + [...teamIds.values()], + input.roundRobinMaxRounds, + ); + if (reconstruction !== 'assigned') { + const [code, message] = + reconstruction === 'unsupported-size' + ? [ + 'ROUND_ROBIN_ROUND_RECONSTRUCTION_UNSUPPORTED', + 'Opponent-only partial round-robin reconstruction supports at most 16 teams.', + ] + : reconstruction === 'search-limit-exceeded' + ? [ + 'ROUND_ROBIN_ROUND_RECONSTRUCTION_LIMIT_EXCEEDED', + 'Opponent-only round-robin reconstruction exceeded its deterministic search limit.', + ] + : [ + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'The persisted round-robin opponent pairs cannot be reconstructed as complete playable rounds.', + ]; + reasons.push(issue(code, message, { teamCount: teamIds.size })); + return null; + } + } + if (!hasRoundNumbers) { + warnings.push( + issue( + 'LEGACY_ROUND_ROBIN_ROUNDS_RECONSTRUCTED', + 'Playable round numbers were reconstructed deterministically from a legacy opponent-only schedule.', + ), + ); + } + + const orderedGroups = groupedSeries.sort( (left, right) => - left.roundNumber - right.roundNumber || + left.roundNumber! - right.roundNumber! || Math.min(...left.gameNumbers) - Math.min(...right.gameNumbers), ); const teamsByRound = new Map>(); const matchNumberByRound = new Map(); const pairings: RoundRobinPairing[] = []; for (const group of orderedGroups) { + const roundNumber = group.roundNumber!; if (group.gameNumbers.length !== gameCount) { reasons.push( issue( 'INVALID_ROUND_ROBIN_SCHEDULE', 'Every persisted round-robin Series must contain exactly gameCount scheduled games.', { - roundNumber: group.roundNumber, + roundNumber, scheduledGameCount: group.gameNumbers.length, expectedGameCount: gameCount, }, @@ -766,25 +822,25 @@ function normalizeLegacyRoundRobinPairings( ); return null; } - const roundTeams = teamsByRound.get(group.roundNumber) ?? new Set(); + const roundTeams = teamsByRound.get(roundNumber) ?? new Set(); if (roundTeams.has(group.teamAId) || roundTeams.has(group.teamBId)) { reasons.push( issue( 'INVALID_ROUND_ROBIN_SCHEDULE', 'A team appears in multiple persisted Series in the same round.', - { roundNumber: group.roundNumber }, + { roundNumber }, ), ); return null; } roundTeams.add(group.teamAId); roundTeams.add(group.teamBId); - teamsByRound.set(group.roundNumber, roundTeams); + teamsByRound.set(roundNumber, roundTeams); - const matchNumber = (matchNumberByRound.get(group.roundNumber) ?? 0) + 1; - matchNumberByRound.set(group.roundNumber, matchNumber); + const matchNumber = (matchNumberByRound.get(roundNumber) ?? 0) + 1; + matchNumberByRound.set(roundNumber, matchNumber); pairings.push({ - roundNumber: group.roundNumber, + roundNumber, matchNumber, teamAId: group.teamAId, teamBId: group.teamBId, @@ -793,6 +849,150 @@ function normalizeLegacyRoundRobinPairings( return pairings; } +function assignLegacyRoundRobinRounds( + groups: Array<{ + roundNumber?: number; + teamAId: string; + teamBId: string; + gameNumbers: number[]; + }>, + teamIds: readonly string[], + maxRounds?: number, +): 'assigned' | 'invalid' | 'unsupported-size' | 'search-limit-exceeded' { + const teamCount = teamIds.length; + const fullRoundCount = teamCount % 2 === 0 ? teamCount - 1 : teamCount; + const roundCount = Math.min( + fullRoundCount, + positiveInteger(maxRounds) ?? fullRoundCount, + ); + const matchesPerRound = Math.floor(teamCount / 2); + if (groups.length !== roundCount * matchesPerRound) return 'invalid'; + + if (roundCount === fullRoundCount) { + return assignCompleteLegacyRoundRobinRounds(groups, teamIds) + ? 'assigned' + : 'invalid'; + } + if (teamCount > 16) return 'unsupported-size'; + + const degreeByTeam = new Map(teamIds.map((teamId) => [teamId, 0])); + for (const group of groups) { + degreeByTeam.set(group.teamAId, degreeByTeam.get(group.teamAId)! + 1); + degreeByTeam.set(group.teamBId, degreeByTeam.get(group.teamBId)! + 1); + } + if ( + [...degreeByTeam.values()].some( + (degree) => + degree > roundCount || (teamCount % 2 === 0 && degree !== roundCount), + ) + ) { + return 'invalid'; + } + + const ordered = [...groups] + .sort( + (left, right) => + Math.min(...left.gameNumbers) - Math.min(...right.gameNumbers), + ) + .map((group, index) => ({ group, index })); + const failedPartitions = new Set(); + let searchBudget = 1_000_000; + + const partition = ( + roundNumber: number, + remaining: typeof ordered, + ): boolean => { + if (roundNumber > roundCount) return remaining.length === 0; + if (remaining.length < matchesPerRound) return false; + const partitionKey = remaining.map(({ index }) => index).join(','); + if (failedPartitions.has(partitionKey) || searchBudget <= 0) return false; + + const selectedIndexes: number[] = [0]; + const usedTeams = new Set([ + remaining[0].group.teamAId, + remaining[0].group.teamBId, + ]); + + const fillRound = (candidateIndex: number): boolean => { + searchBudget -= 1; + if (searchBudget < 0) return false; + if (selectedIndexes.length === matchesPerRound) { + const selected = new Set(selectedIndexes); + const nextRemaining = remaining.filter( + (_group, index) => !selected.has(index), + ); + if (!partition(roundNumber + 1, nextRemaining)) return false; + for (const index of selectedIndexes) { + remaining[index].group.roundNumber = roundNumber; + } + return true; + } + + for (let index = candidateIndex; index < remaining.length; index += 1) { + if (searchBudget <= 0) return false; + const candidate = remaining[index].group; + if ( + usedTeams.has(candidate.teamAId) || + usedTeams.has(candidate.teamBId) + ) { + continue; + } + selectedIndexes.push(index); + usedTeams.add(candidate.teamAId); + usedTeams.add(candidate.teamBId); + if (fillRound(index + 1)) return true; + selectedIndexes.pop(); + usedTeams.delete(candidate.teamAId); + usedTeams.delete(candidate.teamBId); + } + return false; + }; + + const found = fillRound(1); + if (!found) failedPartitions.add(partitionKey); + return found; + }; + + const assigned = partition(1, ordered); + if (assigned) return 'assigned'; + return searchBudget <= 0 ? 'search-limit-exceeded' : 'invalid'; +} + +function assignCompleteLegacyRoundRobinRounds( + groups: Array<{ + roundNumber?: number; + teamAId: string; + teamBId: string; + }>, + teamIds: readonly string[], +): boolean { + const byOpponents = new Map( + groups.map((group) => [ + JSON.stringify([group.teamAId, group.teamBId].sort()), + group, + ]), + ); + const bye = Symbol('round-robin-bye'); + const rotating: Array = [...teamIds].sort(); + if (rotating.length % 2 === 1) rotating.push(bye); + + for (let roundIndex = 0; roundIndex < rotating.length - 1; roundIndex += 1) { + for (let index = 0; index < rotating.length / 2; index += 1) { + const left = rotating[index]; + const right = rotating[rotating.length - 1 - index]; + if (left === bye || right === bye) continue; + const group = byOpponents.get(JSON.stringify([left, right].sort())); + if (!group) return false; + group.roundNumber = roundIndex + 1; + } + const fixed = rotating[0]; + const tail = rotating.slice(1); + tail.unshift(tail.pop()!); + rotating.splice(0, rotating.length, fixed, ...tail); + } + return groups.every((group) => group.roundNumber !== undefined); +} + function fixedFormat(type: 'paired-series', gameCount: number) { return { type, rule: fixedRule(gameCount) } as const; } @@ -832,7 +1032,7 @@ function mapGames( teamIds: Map, reasons: CompetitionMigrationIssue[], ): PlannedGame[] { - const mapped: Array> = []; + const mapped: Array & { ordinal?: number }> = []; const games = input.result?.games ?? []; for (const game of games) { const blueTeamId = teamIds.get(game.blueTeamIndex); @@ -882,10 +1082,14 @@ function mapGames( legacy: game, series: resolution.series, confidence: resolution.confidence, + ...(resolution.ordinal ? { ordinal: resolution.ordinal } : {}), }); } - const grouped = new Map>>(); + const grouped = new Map< + string, + Array & { ordinal?: number }> + >(); for (const game of mapped) { const group = grouped.get(game.series.id) ?? []; group.push(game); @@ -910,9 +1114,42 @@ function mapGames( ); continue; } - seriesGames.forEach((game, index) => - result.push({ ...game, ordinal: index + 1 }), - ); + const occupiedOrdinals = new Set(); + for (const game of seriesGames) { + if (game.ordinal === undefined) continue; + if ( + game.ordinal < 1 || + game.ordinal > series.gameSlots.length || + occupiedOrdinals.has(game.ordinal) + ) { + reasons.push( + issue( + 'AMBIGUOUS_GAME_SLOT_MAPPING', + `Series ${series.code ?? series.id} has conflicting exact GameSlot evidence.`, + { seriesId, ordinal: game.ordinal }, + ), + ); + continue; + } + occupiedOrdinals.add(game.ordinal); + } + const availableOrdinals = series.gameSlots + .map(({ ordinal }) => ordinal) + .filter((ordinal) => !occupiedOrdinals.has(ordinal)); + for (const game of seriesGames) { + const ordinal = game.ordinal ?? availableOrdinals.shift(); + if (ordinal === undefined) { + reasons.push( + issue( + 'GAME_SLOT_MAPPING_NOT_FOUND', + `Series ${series.code ?? series.id} has no remaining stable GameSlot.`, + { seriesId, gameNumber: game.legacy.gameNumber }, + ), + ); + continue; + } + result.push({ ...game, ordinal }); + } } return result.sort( (left, right) => @@ -928,24 +1165,31 @@ function resolveGameSeries( blueTeamId: string, redTeamId: string, ): - | { series: SeriesDefinition; confidence: number } + | { series: SeriesDefinition; confidence: number; ordinal?: number } | { issue: CompetitionMigrationIssue } { if (game.bracketMatchId) { const series = graph.find( (candidate) => candidate.code === game.bracketMatchId, ); - return series - ? { series, confidence: 1 } - : { - issue: issue( - 'GAME_SERIES_MAPPING_NOT_FOUND', - `Legacy bracket code ${game.bracketMatchId} has no Series.`, - { - gameNumber: game.gameNumber, - bracketMatchId: game.bracketMatchId, - }, - ), - }; + if (!series) { + return { + issue: issue( + 'GAME_SERIES_MAPPING_NOT_FOUND', + `Legacy bracket code ${game.bracketMatchId} has no Series.`, + { + gameNumber: game.gameNumber, + bracketMatchId: game.bracketMatchId, + }, + ), + }; + } + const exactSlot = resolveLegacyGameNumberTarget(input, graph, game, series); + if ('issue' in exactSlot) return exactSlot; + return { + series, + confidence: 1, + ...(exactSlot.ordinal ? { ordinal: exactSlot.ordinal } : {}), + }; } const assignments = (input.gameSchedule ?? []).filter( @@ -978,9 +1222,17 @@ function resolveGameSeries( staticSeriesHasTeamSet(series, blueTeamId, redTeamId), ); if (candidates.length === 1) { + const exactSlot = resolveLegacyGameNumberTarget( + input, + graph, + game, + candidates[0], + ); + if ('issue' in exactSlot) return exactSlot; return { series: candidates[0], confidence: assignments.length === 1 ? 0.95 : 0.8, + ...(exactSlot.ordinal ? { ordinal: exactSlot.ordinal } : {}), }; } return { @@ -999,6 +1251,107 @@ function resolveGameSeries( }; } +function resolveLegacyGameNumberTarget( + input: LegacyMatchInput, + graph: SeriesDefinition[], + game: LegacyGameInput, + series: SeriesDefinition, +): { ordinal?: number } | { issue: CompetitionMigrationIssue } { + if (input.gameMode === 'double-elimination') { + if ((input.doubleElimination?.bracketMatches?.length ?? 0) === 0) return {}; + const target = resolvePersistedDoubleEliminationGameNumberTarget( + input, + graph, + game.gameNumber, + ); + if ('error' in target) { + return { + issue: issue('GAME_SLOT_MAPPING_NOT_FOUND', target.error, { + gameNumber: game.gameNumber, + bracketMatchId: game.bracketMatchId, + seriesId: series.id, + }), + }; + } + if (target.series.id !== series.id) { + return { + issue: issue( + 'GAME_SLOT_MAPPING_CONFLICT', + `Legacy game ${game.gameNumber} conflicts with its persisted double-elimination topology.`, + { + gameNumber: game.gameNumber, + bracketMatchId: game.bracketMatchId, + seriesId: series.id, + targetSeriesId: target.series.id, + }, + ), + }; + } + return { ordinal: target.slot.ordinal }; + } + + if ( + input.gameMode === 'round-robin' && + (input.gameSchedule?.length ?? 0) > 0 + ) { + const assignment = input.gameSchedule!.find( + (candidate) => candidate.gameNumber === game.gameNumber, + ); + if (!assignment) { + return { + issue: issue( + 'GAME_SLOT_MAPPING_NOT_FOUND', + `Legacy round-robin game ${game.gameNumber} is absent from its persisted schedule.`, + { gameNumber: game.gameNumber, seriesId: series.id }, + ), + }; + } + const samePair = input + .gameSchedule!.filter( + (candidate) => + unorderedNumberPair(candidate.teamAIndex, candidate.teamBIndex) === + unorderedNumberPair(assignment.teamAIndex, assignment.teamBIndex), + ) + .sort((left, right) => left.gameNumber - right.gameNumber); + const ordinal = + samePair.findIndex( + (candidate) => candidate.gameNumber === game.gameNumber, + ) + 1; + if (!series.gameSlots.some((slot) => slot.ordinal === ordinal)) { + return { + issue: issue( + 'GAME_SLOT_MAPPING_NOT_FOUND', + `Legacy round-robin game ${game.gameNumber} has no stable GameSlot ordinal.`, + { gameNumber: game.gameNumber, seriesId: series.id, ordinal }, + ), + }; + } + return { ordinal }; + } + + const flattened = graph.flatMap((candidateSeries) => + candidateSeries.gameSlots.map((slot) => ({ + series: candidateSeries, + ordinal: slot.ordinal, + })), + ); + const target = flattened[game.gameNumber - 1]; + if (!target || target.series.id !== series.id) { + return { + issue: issue( + 'GAME_SLOT_MAPPING_CONFLICT', + `Legacy game ${game.gameNumber} conflicts with the canonical global GameSlot topology.`, + { + gameNumber: game.gameNumber, + seriesId: series.id, + targetSeriesId: target?.series.id, + }, + ), + }; + } + return { ordinal: target.ordinal }; +} + function staticSeriesHasTeamSet( series: SeriesDefinition, leftTeamId: string, @@ -1492,53 +1845,14 @@ function resolveGlobalGameNumberTarget(params: { params.input.gameMode === 'double-elimination' && bracketMatches.length > 0 ) { - const seenBracketNumbers = new Set(); - const ordered = [...bracketMatches].sort( - (left, right) => - (positiveInteger(left.gameNumber) ?? Number.MAX_SAFE_INTEGER) - - (positiveInteger(right.gameNumber) ?? Number.MAX_SAFE_INTEGER) || - left.bracketMatchId.localeCompare(right.bracketMatchId), - ); - let nextGameNumber = 1; - for (const bracketMatch of ordered) { - const bracketNumber = positiveInteger(bracketMatch.gameNumber); - if ( - !bracketNumber || - seenBracketNumbers.has(bracketNumber) || - bracketNumber !== seenBracketNumbers.size + 1 - ) { - return assignmentMappingNotFound( - params, - 'The persisted double-elimination topology has ambiguous Series numbering.', - ); - } - seenBracketNumbers.add(bracketNumber); - const gameCount = positiveInteger(bracketMatch.gameCount) ?? 1; - if ( - gameNumber >= nextGameNumber && - gameNumber < nextGameNumber + gameCount - ) { - const series = params.graph.find( - (candidate) => candidate.code === bracketMatch.bracketMatchId, - ); - const ordinal = gameNumber - nextGameNumber + 1; - const slot = series?.gameSlots.find( - (candidate) => candidate.ordinal === ordinal, - ); - if (!series || !slot) { - return assignmentMappingNotFound( - params, - 'The persisted double-elimination GameSlot has no Competition target.', - ); - } - return { series, slot }; - } - nextGameNumber += gameCount; - } - return assignmentMappingNotFound( - params, - 'TournamentCode gameNumber is outside the persisted double-elimination topology.', + const target = resolvePersistedDoubleEliminationGameNumberTarget( + params.input, + params.graph, + gameNumber, ); + return 'error' in target + ? assignmentMappingNotFound(params, target.error) + : target; } const schedule = params.input.gameSchedule ?? []; @@ -1608,6 +1922,59 @@ function resolveGlobalGameNumberTarget(params: { ); } +function resolvePersistedDoubleEliminationGameNumberTarget( + input: LegacyMatchInput, + graph: SeriesDefinition[], + gameNumber: number, +): TournamentCodeAssignmentTarget | { error: string } { + const seenBracketNumbers = new Set(); + const ordered = [...(input.doubleElimination?.bracketMatches ?? [])].sort( + (left, right) => + (positiveInteger(left.gameNumber) ?? Number.MAX_SAFE_INTEGER) - + (positiveInteger(right.gameNumber) ?? Number.MAX_SAFE_INTEGER) || + left.bracketMatchId.localeCompare(right.bracketMatchId), + ); + let nextGameNumber = 1; + for (const bracketMatch of ordered) { + const bracketNumber = positiveInteger(bracketMatch.gameNumber); + if ( + !bracketNumber || + seenBracketNumbers.has(bracketNumber) || + bracketNumber !== seenBracketNumbers.size + 1 + ) { + return { + error: + 'The persisted double-elimination topology has ambiguous Series numbering.', + }; + } + seenBracketNumbers.add(bracketNumber); + const gameCount = positiveInteger(bracketMatch.gameCount) ?? 1; + if ( + gameNumber >= nextGameNumber && + gameNumber < nextGameNumber + gameCount + ) { + const series = graph.find( + (candidate) => candidate.code === bracketMatch.bracketMatchId, + ); + const ordinal = gameNumber - nextGameNumber + 1; + const slot = series?.gameSlots.find( + (candidate) => candidate.ordinal === ordinal, + ); + return series && slot + ? { series, slot } + : { + error: + 'The persisted double-elimination GameSlot has no Competition target.', + }; + } + nextGameNumber += gameCount; + } + return { + error: + 'The global game number is outside the persisted double-elimination topology.', + }; +} + function assignmentMappingNotFound( params: { code: LegacyTournamentCodeInput; @@ -1662,7 +2029,6 @@ function buildAssignments( facts: CompetitionMigrationFact[], graph: SeriesDefinition[], teamIds: ReadonlyMap, - warnings: CompetitionMigrationIssue[], reasons: CompetitionMigrationIssue[], ): CompetitionMigrationAssignment[] { const result: CompetitionMigrationAssignment[] = []; @@ -1698,19 +2064,47 @@ function buildAssignments( continue; } const { series, slot } = resolution; - if (code.state === 'used' && !gameFact) { - warnings.push( + const acceptedGame = + gameFact ?? + facts.find( + (fact): fact is MigrationGameAcceptedFact => + fact.type === 'game-accepted' && fact.gameSlotId === slot.id, + ); + if (code.state === 'used' && !acceptedGame) { + reasons.push( issue( 'USED_CODE_WITHOUT_ACCEPTED_GAME', - 'A used TournamentCode has no accepted legacy game evidence.', + 'A used TournamentCode must target an accepted legacy game.', { tournamentCodeId, gameSlotId: slot.id }, ), ); + continue; } - const reservedAt = normalizeDate( - code.reservedAt, - normalizeDate(code.usedAt, sourceFallbackDate(input)), + if ( + code.riotMatchId && + acceptedGame && + !acceptedGameHasRiotIdentity(acceptedGame, code.riotMatchId) + ) { + reasons.push( + issue( + 'TOURNAMENT_CODE_RIOT_EVIDENCE_CONFLICT', + 'TournamentCode Riot identity conflicts with the accepted game in its target slot.', + { + tournamentCodeId, + gameSlotId: slot.id, + riotMatchId: code.riotMatchId, + }, + ), + ); + continue; + } + const timestamps = tournamentCodeTimestamps( + input, + code, + tournamentCodeId, + reasons, ); + if (!timestamps) continue; result.push({ id: stableId( competitionId, @@ -1722,13 +2116,7 @@ function buildAssignments( gameSlotId: slot.id, tournamentCodeId, state: code.state, - reservedAt, - ...(code.usedAt - ? { usedAt: normalizeDate(code.usedAt, reservedAt) } - : {}), - ...(code.releasedAt - ? { releasedAt: normalizeDate(code.releasedAt, reservedAt) } - : {}), + ...timestamps, ...(code.riotMatchId ? { riotMatchId: code.riotMatchId } : {}), commandId: stableId( competitionId, @@ -1764,6 +2152,88 @@ function buildAssignments( return result.sort((left, right) => left.id.localeCompare(right.id)); } +function acceptedGameHasRiotIdentity( + fact: MigrationGameAcceptedFact, + riotMatchId: string, +): boolean { + return ( + (fact.evidence.type === 'riot' && + fact.evidence.riotMatchId === riotMatchId) || + (fact.evidence.type === 'legacy' && + fact.evidence.legacyReference.endsWith(`:${riotMatchId}`)) + ); +} + +function tournamentCodeTimestamps( + input: LegacyMatchInput, + code: LegacyTournamentCodeInput, + tournamentCodeId: string, + reasons: CompetitionMigrationIssue[], +): Pick< + CompetitionMigrationAssignment, + 'reservedAt' | 'usedAt' | 'releasedAt' | 'voidedAt' +> | null { + const raw = { + createdAt: optionalDate(code.createdAt), + reservedAt: optionalDate(code.reservedAt), + usedAt: optionalDate(code.usedAt), + releasedAt: optionalDate(code.releasedAt), + voidedAt: optionalDate(code.voidedAt), + updatedAt: optionalDate(code.updatedAt), + }; + if (Object.values(raw).some((value) => value === null)) { + reasons.push( + issue( + 'INVALID_TOURNAMENT_CODE_TIMELINE', + 'TournamentCode lifecycle contains an invalid timestamp.', + { tournamentCodeId }, + ), + ); + return null; + } + + const reservedAt = + raw.reservedAt ?? + raw.createdAt ?? + raw.usedAt ?? + raw.releasedAt ?? + raw.voidedAt ?? + sourceFallbackDate(input); + const usedAt = raw.usedAt ?? undefined; + const releasedAt = raw.releasedAt ?? undefined; + const voidedAt = + raw.voidedAt ?? + (code.state === 'voided' + ? (raw.updatedAt ?? releasedAt ?? usedAt ?? reservedAt) + : undefined); + const ordered = [reservedAt, usedAt, releasedAt, voidedAt].filter( + (value): value is string => value !== undefined, + ); + if (ordered.some((value, index) => index > 0 && value < ordered[index - 1])) { + reasons.push( + issue( + 'INVALID_TOURNAMENT_CODE_TIMELINE', + 'TournamentCode lifecycle timestamps are not chronological.', + { tournamentCodeId }, + ), + ); + return null; + } + return { + reservedAt, + ...(usedAt ? { usedAt } : {}), + ...(releasedAt ? { releasedAt } : {}), + ...(voidedAt ? { voidedAt } : {}), + }; +} + +function optionalDate(value: unknown): string | undefined | null { + if (value === undefined || value === null || value === '') return undefined; + const date = + value instanceof Date ? value : new Date(value as string | number); + return Number.isNaN(date.getTime()) ? null : date.toISOString(); +} + function seriesCompletionDate(input: LegacyMatchInput, code?: string): string { const completedAt = input.doubleElimination?.bracketMatches?.find( (bracketMatch) => bracketMatch.bracketMatchId === code, diff --git a/apps/api/src/modules/global/database/migrations/competition-domain-runner.spec.ts b/apps/api/src/modules/global/database/migrations/competition-domain-runner.spec.ts index 88e60845..661f692d 100644 --- a/apps/api/src/modules/global/database/migrations/competition-domain-runner.spec.ts +++ b/apps/api/src/modules/global/database/migrations/competition-domain-runner.spec.ts @@ -33,12 +33,73 @@ describe('migrateCompetitionDomain', () => { factCount: 1, assignmentCount: 1, }); + if (result.matches[0].status !== 'ready') { + throw new Error('Expected a ready dry-run result.'); + } + expect(result.matches[0].planHash).toMatch(/^sha256:[a-f0-9]{64}$/); + const repeated = await migrateCompetitionDomain(db); + expect(repeated.matches[0]).toMatchObject({ status: 'ready' }); + if (repeated.matches[0].status !== 'ready') { + throw new Error('Expected a repeated ready dry-run result.'); + } + expect(repeated.matches[0].planHash).toBe(result.matches[0].planHash); expect(startSession).not.toHaveBeenCalled(); expect(db.writeCount).toBe(0); expect(db.docs('competition')).toHaveLength(0); expect(db.createdIndexes).toHaveLength(0); }); + it('reports apply-time global identity conflicts during dry-run without writes', async () => { + const riotMatchId = 'KR_DRY_RUN_GLOBAL_CONFLICT'; + const match = readyMatch(riotMatchId); + const conflictingFactId = objectId(); + const db = new MemoryMigrationDb({ + match: [match], + riotMatch: [riotArchive(riotMatchId)], + tournamentCode: [usedTournamentCode(match, riotMatchId)], + competition_fact: [ + { + _id: conflictingFactId, + competitionId: objectId(), + type: 'game-accepted', + evidence: { type: 'riot', riotMatchId }, + }, + ], + }); + + const dryRun = await migrateCompetitionDomain(db); + + expect(dryRun.summary).toMatchObject({ + scanned: 1, + ready: 0, + applied: 0, + quarantined: 1, + failed: 0, + }); + expect(dryRun.matches[0]).toMatchObject({ status: 'quarantined' }); + if (dryRun.matches[0].status !== 'quarantined') { + throw new Error('Expected a quarantined dry-run result.'); + } + const conflict = dryRun.matches[0].reasons.find( + ({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT', + ); + expect(conflict?.details?.collection).toBe('competition_fact'); + expect(conflict?.details?.indexName).toBe('evidence.riotMatchId_1'); + expect(conflict?.details?.conflictingDocumentId).toBe( + conflictingFactId.toHexString(), + ); + expect(db.writeCount).toBe(0); + expect(db.createdIndexes).toHaveLength(0); + + const applied = await migrateCompetitionDomain(db, { + dryRun: false, + startSession: () => Promise.resolve(new FakeSession()), + }); + + expect(applied.summary).toMatchObject({ applied: 0, quarantined: 1 }); + expect(applied.matches[0]).toEqual(dryRun.matches[0]); + }); + it.each([ ['absent', (match: AnyDoc) => delete match.gameMode], ['null', (match: AnyDoc) => (match.gameMode = null)], @@ -157,6 +218,32 @@ describe('migrateCompetitionDomain', () => { expect(sessions[1]).toMatchObject({ committed: 1, aborted: 0, ended: 1 }); }); + it('persists the source voidedAt timestamp without synthesizing it from usedAt', async () => { + const match = readyMatch('KR_VOIDED_TIMESTAMP'); + const code = usedTournamentCode(match, 'KR_VOIDED_TIMESTAMP'); + code.state = 'voided'; + code.voidedAt = new Date('2026-07-03T00:00:00.000Z'); + const db = new MemoryMigrationDb({ + match: [match], + riotMatch: [riotArchive('KR_VOIDED_TIMESTAMP')], + tournamentCode: [code], + }); + + const result = await migrateCompetitionDomain(db, { + dryRun: false, + startSession: () => Promise.resolve(new FakeSession()), + }); + + expect(result.summary).toMatchObject({ applied: 1, failed: 0 }); + expect(db.docs('tournament_code_assignment')).toContainEqual( + expect.objectContaining({ + state: 'voided', + voidedAt: new Date('2026-07-03T00:00:00.000Z'), + updatedAt: new Date('2026-07-03T00:00:00.000Z'), + }), + ); + }); + it('quarantines an ambiguous Match without changing any legacy Match field', async () => { const match = ambiguousMatch(); const before = canonical(match); @@ -364,6 +451,46 @@ describe('migrateCompetitionDomain', () => { expect(db.docs('competition_migration_quarantine')).toHaveLength(1); }); + it('detects the same global identity collision between dry-run plans as sequential apply', async () => { + const riotMatchId = 'KR_SHARED_DRY_RUN_MIGRATION'; + const firstMatch = readyMatch(riotMatchId); + const secondMatch = readyMatch(riotMatchId); + const db = new MemoryMigrationDb({ + match: [firstMatch, secondMatch], + riotMatch: [riotArchive(riotMatchId)], + tournamentCode: [ + usedTournamentCode(firstMatch, riotMatchId), + usedTournamentCode(secondMatch, riotMatchId), + ], + }); + + const dryRun = await migrateCompetitionDomain(db); + + expect(dryRun.summary).toMatchObject({ ready: 1, quarantined: 1 }); + expect(dryRun.matches.map(({ status }) => status)).toEqual([ + 'ready', + 'quarantined', + ]); + expect(dryRun.matches[1]).toMatchObject({ status: 'quarantined' }); + if (dryRun.matches[1].status !== 'quarantined') { + throw new Error('Expected the second dry-run result to be quarantined.'); + } + expect( + dryRun.matches[1].reasons.some( + ({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT', + ), + ).toBe(true); + expect(db.writeCount).toBe(0); + + const applied = await migrateCompetitionDomain(db, { + dryRun: false, + startSession: () => Promise.resolve(new FakeSession()), + }); + + expect(applied.summary).toMatchObject({ applied: 1, quarantined: 1 }); + expect(applied.matches[1]).toEqual(dryRun.matches[1]); + }); + it('resumes repeated limited apply runs after the durable Match checkpoint', async () => { const firstMatch = readyMatch('KR_BATCH_1'); const secondMatch = readyMatch('KR_BATCH_2'); diff --git a/apps/api/src/modules/global/database/migrations/competition-domain-runner.ts b/apps/api/src/modules/global/database/migrations/competition-domain-runner.ts index 79bf1bac..cdc8cff4 100644 --- a/apps/api/src/modules/global/database/migrations/competition-domain-runner.ts +++ b/apps/api/src/modules/global/database/migrations/competition-domain-runner.ts @@ -98,6 +98,7 @@ export type CompetitionDomainMigrationMatchResult = status: 'ready' | 'applied'; factCount: number; assignmentCount: number; + planHash: string; }) | (CompetitionDomainMigrationMatchBase & { status: 'already-applied'; @@ -206,11 +207,17 @@ export async function migrateCompetitionDomain( resumeStart.startedAfterMatchId, ); const matches: CompetitionDomainMigrationMatchResult[] = []; + const dryRunUniquenessClaims = new Map(); let checkpointAfterMatchId = resumeStart.startedAfterMatchId; let haltedOnFailure = false; for (const [index, scannedMatch] of scan.matches.entries()) { const result = dryRun - ? await inspectMatch(db, scannedMatch, migrationRunId) + ? await inspectMatch( + db, + scannedMatch, + migrationRunId, + dryRunUniquenessClaims, + ) : await applyMatch(db, scannedMatch, migrationRunId, options); matches.push(result); options.onProgress?.({ @@ -433,6 +440,7 @@ async function inspectMatch( db: CompetitionDomainMigrationDb, scannedMatch: AnyDocument, migrationRunId: string, + uniquenessClaims: Map, ): Promise { const matchId = idString(scannedMatch._id); try { @@ -450,6 +458,21 @@ async function inspectMatch( const legacy = await hydrateLegacyMatch(db, scannedMatch); const plan = planCompetitionMigration(legacy, { migrationRunId }); + if (plan.status === 'ready') { + const uniquenessConflicts = await findReadyPlanUniquenessConflicts( + db, + plan, + { claims: uniquenessClaims }, + ); + if (uniquenessConflicts.length > 0) { + return { + status: 'quarantined', + matchId, + warnings: plan.warnings, + reasons: uniquenessConflicts, + }; + } + } return planResult(matchId, plan); } catch (error) { return failedResult(matchId, error); @@ -521,7 +544,7 @@ async function applyMatch( const uniquenessConflicts = await findReadyPlanUniquenessConflicts( db, plan, - session, + { session }, ); if (uniquenessConflicts.length > 0) { await persistQuarantine( @@ -577,6 +600,7 @@ async function applyMatch( competitionId, factCount: plan.facts.length, assignmentCount: plan.assignments.length, + planHash: readyPlanHash(plan), warnings: plan.warnings, }; } catch (error) { @@ -592,12 +616,21 @@ interface UniqueIdentityCheck { indexName: string; filter: Record; expectedDocumentId: string; + expectedCompetitionId?: string; +} + +interface ClaimedUniqueIdentity { + documentId: string; + competitionId?: string; } async function findReadyPlanUniquenessConflicts( db: CompetitionDomainMigrationDb, plan: ReadyCompetitionMigrationPlan, - session: CompetitionDomainMigrationSession, + options: { + session?: CompetitionDomainMigrationSession; + claims?: Map; + } = {}, ): Promise { const checks: UniqueIdentityCheck[] = [ { @@ -619,6 +652,7 @@ async function findReadyPlanUniquenessConflicts( ordinalWithinRevision: fact.ordinalWithinRevision, }, expectedDocumentId: fact.id, + expectedCompetitionId: fact.competitionId, }, { collection: 'competition_fact', @@ -629,6 +663,7 @@ async function findReadyPlanUniquenessConflicts( ordinalWithinRevision: fact.ordinalWithinRevision, }, expectedDocumentId: fact.id, + expectedCompetitionId: fact.competitionId, }, ); if (fact.type === 'game-accepted' && fact.evidence.type === 'riot') { @@ -640,6 +675,7 @@ async function findReadyPlanUniquenessConflicts( 'evidence.riotMatchId': fact.evidence.riotMatchId, }, expectedDocumentId: fact.id, + expectedCompetitionId: fact.competitionId, }); } } @@ -655,6 +691,7 @@ async function findReadyPlanUniquenessConflicts( state: { $in: ['reserved', 'used'] }, }, expectedDocumentId: assignment.id, + expectedCompetitionId: assignment.competitionId, }, { collection: 'tournament_code_assignment', @@ -664,6 +701,7 @@ async function findReadyPlanUniquenessConflicts( state: { $in: ['reserved', 'used'] }, }, expectedDocumentId: assignment.id, + expectedCompetitionId: assignment.competitionId, }, ); } @@ -673,6 +711,7 @@ async function findReadyPlanUniquenessConflicts( indexName: 'riotMatchId_1', filter: { riotMatchId: assignment.riotMatchId }, expectedDocumentId: assignment.id, + expectedCompetitionId: assignment.competitionId, }); } } @@ -680,30 +719,66 @@ async function findReadyPlanUniquenessConflicts( const conflicts: CompetitionMigrationIssue[] = []; // Mongo sessions do not support parallel operations inside one transaction. for (const check of checks) { + const claim = options.claims?.get(uniqueIdentityKey(check)); + if (claim && claim.documentId !== check.expectedDocumentId) { + conflicts.push( + uniqueIdentityConflict(check, { + _id: persistenceId(claim.documentId), + ...(claim.competitionId + ? { competitionId: persistenceId(claim.competitionId) } + : {}), + }), + ); + continue; + } const existing = await db .collection(check.collection) - .findOne(check.filter, { session }); + .findOne( + check.filter, + options.session ? { session: options.session } : undefined, + ); if (!existing || idString(existing._id) === check.expectedDocumentId) { continue; } - conflicts.push({ - code: 'GLOBAL_UNIQUE_INDEX_CONFLICT', - message: `Migration input conflicts with ${check.collection}.${check.indexName}.`, - details: { - collection: check.collection, - indexName: check.indexName, - key: canonicalValue(check.filter) as Record, - expectedDocumentId: check.expectedDocumentId, - conflictingDocumentId: idString(existing._id), - ...(existing.competitionId - ? { conflictingCompetitionId: idString(existing.competitionId) } + conflicts.push(uniqueIdentityConflict(check, existing)); + } + if (conflicts.length === 0 && options.claims) { + for (const check of checks) { + options.claims.set(uniqueIdentityKey(check), { + documentId: check.expectedDocumentId, + ...(check.expectedCompetitionId + ? { competitionId: check.expectedCompetitionId } : {}), - }, - }); + }); + } } return conflicts; } +function uniqueIdentityKey(check: UniqueIdentityCheck): string { + return `${check.collection}:${check.indexName}:${canonicalJson(check.filter)}`; +} + +function uniqueIdentityConflict( + check: UniqueIdentityCheck, + existing: AnyDocument, +): CompetitionMigrationIssue { + return { + code: 'GLOBAL_UNIQUE_INDEX_CONFLICT', + message: `Migration input conflicts with ${check.collection}.${check.indexName}.`, + details: { + collection: check.collection, + indexName: check.indexName, + key: canonicalValue(check.filter) as Record, + expectedDocumentId: check.expectedDocumentId, + conflictingDocumentId: idString(existing._id), + ...(existing.competitionId + ? { conflictingCompetitionId: idString(existing.competitionId) } + : {}), + }, + }; +} + async function hydrateLegacyMatch( db: CompetitionDomainMigrationDb, match: AnyDocument, @@ -1085,12 +1160,18 @@ function assignmentForPersistence( ): AnyDocument { const reservedAt = new Date(assignment.reservedAt); const updatedAt = new Date( - assignment.releasedAt ?? assignment.usedAt ?? assignment.reservedAt, + assignment.voidedAt ?? + assignment.releasedAt ?? + assignment.usedAt ?? + assignment.reservedAt, ); const voidedAt = assignment.state === 'voided' ? new Date( - assignment.releasedAt ?? assignment.usedAt ?? assignment.reservedAt, + assignment.voidedAt ?? + assignment.releasedAt ?? + assignment.usedAt ?? + assignment.reservedAt, ) : undefined; return { @@ -1138,10 +1219,23 @@ function planResult( competitionId: plan.competition.id, factCount: plan.facts.length, assignmentCount: plan.assignments.length, + planHash: readyPlanHash(plan), warnings: plan.warnings, }; } +function readyPlanHash(plan: ReadyCompetitionMigrationPlan): string { + return `sha256:${createHash('sha256') + .update( + canonicalJson({ + competition: plan.competition, + facts: plan.facts, + assignments: plan.assignments, + }), + ) + .digest('hex')}`; +} + function failedResult( matchId: string, error: unknown, diff --git a/docs/specs/competition-result-domain.md b/docs/specs/competition-result-domain.md index e8f725fe..8182fb3f 100644 --- a/docs/specs/competition-result-domain.md +++ b/docs/specs/competition-result-domain.md @@ -276,8 +276,17 @@ Migration builds new collections without dual canonical writes. - A persisted legacy round-robin `gameSchedule` is authoritative. Migration normalizes it into explicit TeamId-based pairings on the Competition format so the immutable Series graph reproduces the historical opponents and rounds instead of - generating a different canonical schedule. Matches without a persisted schedule - continue to use deterministic canonical round-robin generation. + generating a different canonical schedule. The persisted schedule must completely + cover every configured round and every Series in each round; incomplete schedules + are quarantined. If every round number is absent on an older schedule, migration + deterministically partitions its persisted opponent pairs into complete playable + rounds and emits a warning; mixed or unpartitionable schedules are quarantined. + Complete opponent sets use direct canonical factorization at any supported team + count. Partial opponent-only schedules use bounded reconstruction for at most 16 + teams; larger or search-limit-exceeding inputs receive dedicated quarantine codes + instead of being mislabeled as invalid. + Matches without a persisted schedule continue to use deterministic canonical + round-robin generation. - Legacy TournamentCode `gameNumber` is a global GameSlot number, not a Series ordinal. Migration resolves it through accepted Riot evidence first, then the persisted format topology (`gameSchedule` or double-elimination bracket layout), @@ -286,7 +295,9 @@ Migration builds new collections without dual canonical writes. Series/GameSlot must agree. A multi-slot Series is never assigned to its first GameSlot as a fallback; missing, conflicting, duplicated, or out-of-range evidence is quarantined without changing the legacy Match or TournamentCode. -- Dry-run is the default and emits machine-readable and human-readable reports. +- Dry-run is the default and emits machine-readable and human-readable reports. Every + ready/apply result includes a deterministic `planHash` over the graph, facts, and + TournamentCode targets so audits detect target changes even when counts stay equal. - Apply is resumable, idempotent, transactionally scoped per Match, and verifies fact replay equality after every write. - Apply explicitly creates or verifies every Competition unique/partial index before