import { projectCompetition } from '../../../competition/domain/competition-projector'; import { planCompetitionMigration, type LegacyMatchInput, type ReadyCompetitionMigrationPlan, } from './20260712-competition-domain'; describe('planCompetitionMigration', () => { it('produces deterministic, idempotent identities and maps legacy bracket mode explicitly', () => { const legacy = pairedMatch({ gameMode: 'bracket' }); const first = planCompetitionMigration(legacy); const second = planCompetitionMigration(structuredClone(legacy)); expect(first).toEqual(second); const plan = requireReady(first); expect(plan.competition.id).toMatch(/^[a-f0-9]{24}$/); expect(plan.competition.teams.map((team) => team.teamId)).toEqual( expect.arrayContaining([ expect.stringMatching(/^[a-f0-9]{24}$/), expect.stringMatching(/^[a-f0-9]{24}$/), ]), ); expect(plan.competition.format).toMatchObject({ type: 'paired-series' }); expect(plan.warnings).toContainEqual( expect.objectContaining({ code: 'LEGACY_BRACKET_MAPPED_TO_PAIRED_SERIES', }), ); }); it('preserves Riot-backed and normalized-only games as different evidence kinds', () => { const legacy = pairedMatch({ gameCount: 2 }); legacy.result = { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_WITH_ARCHIVE', blueTeamIndex: 1, redTeamIndex: 2, winnerTeamIndex: 1, riotArchivePresent: true, }), legacyGame({ gameNumber: 2, riotMatchId: 'KR_NORMALIZED_ONLY', blueTeamIndex: 2, redTeamIndex: 1, winnerTeamIndex: 2, riotArchivePresent: false, }), ], seriesResults: [], }; const plan = requireReady(planCompetitionMigration(legacy)); const games = plan.facts.filter((fact) => fact.type === 'game-accepted'); expect(games).toHaveLength(2); expect(games[0]).toMatchObject({ evidence: { type: 'riot', riotMatchId: 'KR_WITH_ARCHIVE', }, }); expect(games[1].evidence.type).toBe('legacy'); if (games[1].evidence.type !== 'legacy') { throw new Error('Expected normalized-only legacy evidence.'); } expect(games[1].evidence.legacyReference).toContain('KR_NORMALIZED_ONLY'); }); it('turns a winner-only Series into an adjudication without fabricating games', () => { const legacy = pairedMatch({ gameCount: 3 }); legacy.result = { games: [], seriesResults: [ { teamAIndex: 1, teamBIndex: 2, teamAWins: 0, teamBWins: 0, winnerTeamIndex: 2, }, ], }; const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.facts).toHaveLength(1); expect(plan.facts[0]).toMatchObject({ type: 'series-adjudicated', decision: { type: 'administrative', winnerTeamId: plan.competition.teams[1].teamId, }, reason: 'legacy-winner-only-result', }); expect(plan.facts).not.toContainEqual( expect.objectContaining({ type: 'game-accepted' }), ); }); it('quarantines an ambiguous legacy game assignment instead of guessing', () => { const legacy = pairedMatch({ teams: [ legacyTeam(1, 'One'), legacyTeam(2, 'Two'), legacyTeam(3, 'Three'), legacyTeam(4, 'Four'), ], }); legacy.gameSchedule = [ { gameNumber: 7, teamAIndex: 1, teamBIndex: 2 }, { gameNumber: 7, teamAIndex: 3, teamBIndex: 4 }, ]; legacy.result = { games: [ legacyGame({ gameNumber: 7, riotMatchId: 'KR_AMBIGUOUS', blueTeamIndex: 1, redTeamIndex: 2, winnerTeamIndex: 1, riotArchivePresent: true, }), ], seriesResults: [], }; const plan = planCompetitionMigration(legacy); expectQuarantineReason(plan, 'AMBIGUOUS_GAME_ASSIGNMENT'); }); it('preserves a persisted non-canonical round-robin schedule', () => { const schedule = [ [1, 1, 1, 2], [2, 1, 3, 4], [3, 1, 5, 6], [4, 1, 7, 8], [5, 2, 1, 3], [6, 2, 2, 4], [7, 2, 5, 7], [8, 2, 6, 8], [9, 3, 1, 4], [10, 3, 2, 3], [11, 3, 5, 8], [12, 3, 6, 7], ] as const; const legacy = pairedMatch({ _id: 'match-persisted-round-robin-schedule', gameMode: 'round-robin', gameCount: 1, roundRobinMaxRounds: 3, teams: Array.from({ length: 8 }, (_, index) => legacyTeam(index + 1, `${index + 1}팀`), ), gameSchedule: schedule.map( ([gameNumber, roundNumber, teamAIndex, teamBIndex]) => ({ gameNumber, roundNumber, teamAIndex, teamBIndex, }), ), result: { games: schedule.map(([gameNumber, , teamAIndex, teamBIndex]) => legacyGame({ gameNumber, riotMatchId: `KR_PERSISTED_RR_${gameNumber}`, blueTeamIndex: teamAIndex, redTeamIndex: teamBIndex, winnerTeamIndex: teamAIndex, riotArchivePresent: true, }), ), seriesResults: [], }, }); const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.competition.format.type).toBe('round-robin'); if (plan.competition.format.type !== 'round-robin') { throw new Error('Expected a round-robin format.'); } expect( plan.competition.format.pairings?.some( (pairing) => pairing.roundNumber === 3 && pairing.matchNumber === 4 && pairing.teamAId === plan.competition.teams[5].teamId && pairing.teamBId === plan.competition.teams[6].teamId, ), ).toBe(true); expect( plan.facts.filter(({ type }) => type === 'game-accepted'), ).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, reservedAt: '2026-07-01T00:00:00.000Z', usedAt: '2026-07-02T00:00:00.000Z', releasedAt: '2026-07-01T12:00:00.000Z', voidedAt: '2026-07-01T18:00:00.000Z', }, ], }); const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.assignments).toHaveLength(1); expect(plan.assignments[0]).toMatchObject({ state: 'used', usedAt: '2026-07-02T00:00:00.000Z', }); expect(plan.assignments[0]).not.toHaveProperty('releasedAt'); expect(plan.assignments[0]).not.toHaveProperty('voidedAt'); 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', releasedAt: '2026-07-04T00: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', }), ); expect(plan.assignments[0]).not.toHaveProperty('releasedAt'); }); it('ignores stale terminal timestamps from an earlier lifecycle when a code is reserved again', () => { const legacy = pairedMatch({ _id: 'match-reused-reserved-code-timeline', gameCount: 1, gameSchedule: undefined, result: { games: [], seriesResults: [] }, tournamentCodes: [ { _id: 'reused-reserved-code', state: 'reserved', gameNumber: 1, reservedAt: '2026-07-03T00:00:00.000Z', usedAt: '2026-07-01T00:00:00.000Z', releasedAt: '2026-07-02T00:00:00.000Z', voidedAt: '2026-07-02T00:00:00.000Z', riotMatchId: 'KR_STALE_RESERVED_LIFECYCLE', }, ], }); const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.assignments).toContainEqual( expect.objectContaining({ state: 'reserved', reservedAt: '2026-07-03T00:00:00.000Z', }), ); expect(plan.assignments[0]).not.toHaveProperty('usedAt'); expect(plan.assignments[0]).not.toHaveProperty('releasedAt'); expect(plan.assignments[0]).not.toHaveProperty('voidedAt'); expect(plan.assignments[0]).not.toHaveProperty('riotMatchId'); }); it('preserves only the applicable lifecycle for a released code', () => { const legacy = pairedMatch({ _id: 'match-released-code-timeline', gameCount: 1, gameSchedule: undefined, result: { games: [], seriesResults: [] }, tournamentCodes: [ { _id: 'released-code-with-stale-terminal-fields', state: 'released', gameNumber: 1, reservedAt: '2026-07-03T00:00:00.000Z', usedAt: '2026-07-01T00:00:00.000Z', releasedAt: '2026-07-04T00:00:00.000Z', voidedAt: '2026-07-02T00:00:00.000Z', riotMatchId: 'KR_STALE_RELEASED_LIFECYCLE', }, ], }); const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.assignments[0]).toMatchObject({ state: 'released', reservedAt: '2026-07-03T00:00:00.000Z', releasedAt: '2026-07-04T00:00:00.000Z', }); expect(plan.assignments[0]).not.toHaveProperty('usedAt'); expect(plan.assignments[0]).not.toHaveProperty('voidedAt'); expect(plan.assignments[0]).not.toHaveProperty('riotMatchId'); }); it('uses updatedAt as voidedAt for the production reversal document shape', () => { const legacy = pairedMatch({ _id: 'match-voided-code-updated-at-fallback', gameCount: 1, gameSchedule: undefined, result: { games: [], seriesResults: [] }, tournamentCodes: [ { _id: 'voided-code-updated-at-fallback', state: 'voided', gameNumber: 1, reservedAt: '2026-07-01T00:00:00.000Z', usedAt: '2026-07-02T00:00:00.000Z', updatedAt: '2026-07-03T00:00:00.000Z', }, ], }); const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.assignments[0]).toMatchObject({ state: 'voided', voidedAt: '2026-07-03T00:00:00.000Z', }); }); it('normalizes a post-game reservation timestamp for an accepted used code', () => { const legacy = pairedMatch({ _id: 'match-post-game-used-code-reservation', gameCount: 1, gameSchedule: undefined, updatedAt: '2026-07-03T00:06:00.000Z', result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_POST_GAME_CODE_RESERVATION', riotArchivePresent: true, riotGameEndedAt: '2026-07-02T00:00:00.000Z', riotGameEndedAtSource: 'gameEndTimestamp', }), ], seriesResults: [], }, tournamentCodes: [ { _id: 'used-code-reserved-after-game', state: 'used', gameNumber: 1, reservedAt: '2026-07-03T00:00:00.000Z', usedAt: '2026-07-02T00:00:00.000Z', updatedAt: '2026-07-03T00:05:00.000Z', riotMatchId: 'KR_POST_GAME_CODE_RESERVATION', }, ], }); const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.assignments[0]).toMatchObject({ state: 'used', reservedAt: '2026-07-03T00:00:00.000Z', usedAt: '2026-07-03T00:05:00.000Z', }); expect(plan.warnings).toContainEqual({ code: 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', message: 'Legacy used TournamentCode usedAt represented Riot game time and was normalized to its persisted transition time.', details: { tournamentCodeId: 'used-code-reserved-after-game', originalReservedAt: '2026-07-03T00:00:00.000Z', originalUsedAt: '2026-07-02T00:00:00.000Z', sourceUpdatedAt: '2026-07-03T00:05:00.000Z', normalizedUsedAt: '2026-07-03T00:05:00.000Z', factRecordedAt: '2026-07-03T00:06:00.000Z', legacyOccurrenceSource: 'riot-archive-gameEndTimestamp', riotMatchId: 'KR_POST_GAME_CODE_RESERVATION', gameSlotId: plan.assignments[0].gameSlotId, strategy: 'use-persisted-transition-time', }, }); }); it('normalizes a chronological legacy Riot occurrence to the persisted used transition', () => { const legacy = pairedMatch({ _id: 'match-chronological-legacy-used-occurrence', gameCount: 1, gameSchedule: undefined, updatedAt: '2026-07-02T00:06:00.000Z', result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_CHRONOLOGICAL_LEGACY_USED_OCCURRENCE', riotArchivePresent: true, riotGameEndedAt: '2026-07-02T00:00:00.000Z', riotGameEndedAtSource: 'gameEndTimestamp', }), ], seriesResults: [], }, tournamentCodes: [ { _id: 'chronological-legacy-used-occurrence', state: 'used', gameNumber: 1, reservedAt: '2026-07-01T00:00:00.000Z', usedAt: '2026-07-02T00:00:00.000Z', updatedAt: '2026-07-02T00:05:00.000Z', riotMatchId: 'KR_CHRONOLOGICAL_LEGACY_USED_OCCURRENCE', }, ], }); const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.assignments[0]).toMatchObject({ reservedAt: '2026-07-01T00:00:00.000Z', usedAt: '2026-07-02T00:05:00.000Z', }); expect(plan.warnings).toContainEqual( expect.objectContaining({ code: 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', }), ); }); it('recognizes the legacy Riot gameCreation fallback occurrence path', () => { const legacy = pairedMatch({ _id: 'match-legacy-game-creation-used-occurrence', gameCount: 1, gameSchedule: undefined, updatedAt: '2026-07-02T00:06:00.000Z', result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_LEGACY_GAME_CREATION_USED_OCCURRENCE', riotArchivePresent: true, riotGameEndedAt: '2026-07-02T00:00:00.000Z', riotGameEndedAtSource: 'gameCreation', }), ], seriesResults: [], }, tournamentCodes: [ { _id: 'legacy-game-creation-used-occurrence', state: 'used', gameNumber: 1, reservedAt: '2026-07-01T00:00:00.000Z', usedAt: '2026-07-02T00:00:00.000Z', updatedAt: '2026-07-02T00:05:00.000Z', riotMatchId: 'KR_LEGACY_GAME_CREATION_USED_OCCURRENCE', }, ], }); const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.assignments[0].usedAt).toBe('2026-07-02T00:05:00.000Z'); const warning = plan.warnings.find( ({ code }) => code === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', ); expect(warning?.details).toMatchObject({ legacyOccurrenceSource: 'riot-archive-gameCreation', }); }); it('recognizes the legacy repair gameCreation plus duration occurrence path', () => { const legacy = pairedMatch({ _id: 'match-repaired-legacy-used-occurrence', gameCount: 1, gameSchedule: undefined, updatedAt: '2026-07-03T00:06:00.000Z', result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_REPAIRED_LEGACY_USED_OCCURRENCE', riotArchivePresent: true, gameCreation: '2026-07-02T00:00:00.000Z', gameDuration: 1800, riotGameEndedAt: '2026-07-02T00:30:17.000Z', riotGameEndedAtSource: 'gameEndTimestamp', }), ], seriesResults: [], }, tournamentCodes: [ { _id: 'repaired-legacy-used-occurrence', state: 'used', gameNumber: 1, reservedAt: '2026-07-01T00:00:00.000Z', usedAt: '2026-07-02T00:30:00.000Z', updatedAt: '2026-07-03T00:05:00.000Z', riotMatchId: 'KR_REPAIRED_LEGACY_USED_OCCURRENCE', }, ], }); const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.assignments[0]).toMatchObject({ reservedAt: '2026-07-01T00:00:00.000Z', usedAt: '2026-07-03T00:05:00.000Z', }); const warning = plan.warnings.find( ({ code }) => code === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', ); expect(warning?.details).toMatchObject({ legacyOccurrenceSource: 'legacy-gameCreation-plus-duration', }); }); it('does not normalize an inverted used-code lifecycle without Riot archive evidence', () => { const legacy = pairedMatch({ _id: 'match-unverified-used-code-transition', gameCount: 1, gameSchedule: undefined, updatedAt: '2026-07-03T00:06:00.000Z', result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_UNVERIFIED_USED_CODE_TRANSITION', riotArchivePresent: false, }), ], seriesResults: [], }, tournamentCodes: [ { _id: 'unverified-used-code-transition', state: 'used', gameNumber: 1, reservedAt: '2026-07-03T00:00:00.000Z', usedAt: '2026-07-02T00:00:00.000Z', updatedAt: '2026-07-03T00:05:00.000Z', riotMatchId: 'KR_UNVERIFIED_USED_CODE_TRANSITION', }, ], }); const plan = planCompetitionMigration(legacy); expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); }); it('preserves a chronological usedAt that does not match a known occurrence encoding', () => { const legacy = pairedMatch({ _id: 'match-current-used-transition-semantics', gameCount: 1, gameSchedule: undefined, updatedAt: '2026-07-02T00:10:00.000Z', result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_CURRENT_USED_TRANSITION_SEMANTICS', riotArchivePresent: true, riotGameEndedAt: '2026-07-02T00:00:00.000Z', riotGameEndedAtSource: 'gameEndTimestamp', }), ], seriesResults: [], }, tournamentCodes: [ { _id: 'current-used-transition-semantics', state: 'used', gameNumber: 1, reservedAt: '2026-07-01T00:00:00.000Z', usedAt: '2026-07-02T00:10:00.000Z', updatedAt: '2026-07-02T00:10:00.000Z', riotMatchId: 'KR_CURRENT_USED_TRANSITION_SEMANTICS', }, ], }); const plan = requireReady(planCompetitionMigration(legacy)); expect(plan.assignments[0].usedAt).toBe('2026-07-02T00:10:00.000Z'); expect( plan.warnings.some( ({ code }) => code === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', ), ).toBe(false); }); it('quarantines an inverted used timeline with an out-of-range legacy duration without throwing', () => { const legacy = pairedMatch({ _id: 'match-out-of-range-legacy-duration', gameCount: 1, gameSchedule: undefined, updatedAt: '2026-07-03T00:06:00.000Z', result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_OUT_OF_RANGE_LEGACY_DURATION', riotArchivePresent: true, gameCreation: '2026-07-02T00:00:00.000Z', gameDuration: Number.MAX_VALUE, }), ], seriesResults: [], }, tournamentCodes: [ { _id: 'out-of-range-legacy-duration', state: 'used', gameNumber: 1, reservedAt: '2026-07-03T00:00:00.000Z', usedAt: '2026-07-02T00:00:00.000Z', updatedAt: '2026-07-03T00:05:00.000Z', riotMatchId: 'KR_OUT_OF_RANGE_LEGACY_DURATION', }, ], }); const plan = planCompetitionMigration(legacy); expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); }); it('does not normalize an inverted used-code lifecycle with an invalid transition time', () => { const legacy = pairedMatch({ _id: 'match-invalid-used-code-transition-time', gameCount: 1, gameSchedule: undefined, updatedAt: '2026-07-03T00:06:00.000Z', result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_INVALID_USED_CODE_TRANSITION_TIME', riotArchivePresent: true, riotGameEndedAt: '2026-07-02T00:00:00.000Z', riotGameEndedAtSource: 'gameEndTimestamp', }), ], seriesResults: [], }, tournamentCodes: [ { _id: 'invalid-used-code-transition-time', state: 'used', gameNumber: 1, reservedAt: '2026-07-03T00:00:00.000Z', usedAt: '2026-07-02T00:00:00.000Z', updatedAt: '2026-07-02T12:00:00.000Z', riotMatchId: 'KR_INVALID_USED_CODE_TRANSITION_TIME', }, ], }); const plan = planCompetitionMigration(legacy); expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); }); it.each<[string, string | undefined]>([ ['missing', undefined], ['earlier than the Riot occurrence', '2026-07-01T12:00:00.000Z'], ])( 'quarantines a recognized legacy occurrence when persisted transition time is %s', (_label, updatedAt) => { const legacy = pairedMatch({ _id: `match-invalid-persisted-transition-${_label}`, gameCount: 1, gameSchedule: undefined, updatedAt: '2026-07-03T00:06:00.000Z', result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_INVALID_PERSISTED_TRANSITION', riotArchivePresent: true, riotGameEndedAt: '2026-07-02T00:00:00.000Z', riotGameEndedAtSource: 'gameEndTimestamp', }), ], seriesResults: [], }, tournamentCodes: [ { _id: `invalid-persisted-transition-${_label}`, state: 'used', gameNumber: 1, reservedAt: '2026-07-01T00:00:00.000Z', usedAt: '2026-07-02T00:00:00.000Z', ...(updatedAt ? { updatedAt } : {}), riotMatchId: 'KR_INVALID_PERSISTED_TRANSITION', }, ], }); const plan = planCompetitionMigration(legacy); expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); }, ); it('does not normalize a used-code transition recorded after the accepted fact', () => { const legacy = pairedMatch({ _id: 'match-used-code-transition-after-fact', gameCount: 1, gameSchedule: undefined, updatedAt: '2026-07-03T00:04:00.000Z', result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_USED_CODE_TRANSITION_AFTER_FACT', riotArchivePresent: true, riotGameEndedAt: '2026-07-02T00:00:00.000Z', riotGameEndedAtSource: 'gameEndTimestamp', }), ], seriesResults: [], }, tournamentCodes: [ { _id: 'used-code-transition-after-fact', state: 'used', gameNumber: 1, reservedAt: '2026-07-03T00:00:00.000Z', usedAt: '2026-07-02T00:00:00.000Z', updatedAt: '2026-07-03T00:05:00.000Z', riotMatchId: 'KR_USED_CODE_TRANSITION_AFTER_FACT', }, ], }); const plan = planCompetitionMigration(legacy); expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); }); it('still quarantines an inverted released-code lifecycle', () => { const legacy = pairedMatch({ _id: 'match-inverted-released-code-timeline', gameCount: 1, gameSchedule: undefined, result: { games: [], seriesResults: [] }, tournamentCodes: [ { _id: 'released-code-inverted-current-timeline', state: 'released', gameNumber: 1, reservedAt: '2026-07-03T00:00:00.000Z', releasedAt: '2026-07-02T00:00:00.000Z', }, ], }); const plan = planCompetitionMigration(legacy); expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); }); it('maps a result-less reserved TournamentCode by its global game number', () => { const legacy = pairedMatch({ _id: 'match-future-reserved-code', gameCount: 2, teams: [ legacyTeam(1, 'One'), legacyTeam(2, 'Two'), legacyTeam(3, 'Three'), legacyTeam(4, 'Four'), ], gameSchedule: undefined, result: { games: [], seriesResults: [] }, tournamentCodes: [ { _id: 'future-code-for-global-game-3', state: 'reserved', gameNumber: 3, }, ], }); const plan = requireReady(planCompetitionMigration(legacy)); const expectedSeries = plan.competition.seriesGraph.find( (series) => series.code === 'PAIR_M2', ); expect(expectedSeries).toBeDefined(); expect(plan.assignments).toContainEqual( expect.objectContaining({ tournamentCodeId: 'future-code-for-global-game-3', seriesId: expectedSeries!.id, gameSlotId: expectedSeries!.gameSlots[0].id, }), ); }); it('maps persisted WB_FINAL global game numbers to distinct stable slots', () => { const legacy = loadDataTxtFixture(); legacy.result = { games: [], seriesResults: [] }; legacy.doubleElimination!.bracketMatches = dataTxtUpperBracketTopology(); legacy.tournamentCodes = [19, 20, 21].map((gameNumber, index) => ({ _id: `wb-final-code-${index + 1}`, state: 'reserved' as const, bracketMatchId: 'WB_FINAL', gameNumber, })); const plan = requireReady(planCompetitionMigration(legacy)); const wbFinal = plan.competition.seriesGraph.find( (series) => series.code === 'WB_FINAL', ); expect(wbFinal).toBeDefined(); expect(wbFinal!.gameSlots).toHaveLength(3); expect(plan.assignments).toHaveLength(3); for (const [index, slot] of wbFinal!.gameSlots.entries()) { expect(plan.assignments).toContainEqual( expect.objectContaining({ tournamentCodeId: `wb-final-code-${index + 1}`, seriesId: wbFinal!.id, gameSlotId: slot.id, }), ); } }); it('quarantines a TournamentCode whose bracket identity conflicts with its global game number', () => { const legacy = loadDataTxtFixture(); legacy.result = { games: [], seriesResults: [] }; legacy.doubleElimination!.bracketMatches = dataTxtUpperBracketTopology(); legacy.tournamentCodes = [ { _id: 'conflicting-wb-final-code', state: 'reserved', bracketMatchId: 'WB_FINAL', gameNumber: 1, }, ]; const plan = planCompetitionMigration(legacy); expectQuarantineReason(plan, 'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT'); }); it('quarantines conflicting Riot evidence and global game number', () => { const legacy = pairedMatch({ _id: 'match-conflicting-code-evidence', gameCount: 2, gameSchedule: undefined, result: { games: [ legacyGame({ gameNumber: 1, riotMatchId: 'KR_CONFLICTING_CODE_EVIDENCE', blueTeamIndex: 1, redTeamIndex: 2, winnerTeamIndex: 1, riotArchivePresent: true, }), ], seriesResults: [], }, tournamentCodes: [ { _id: 'code-with-conflicting-evidence', state: 'used', gameNumber: 2, riotMatchId: 'KR_CONFLICTING_CODE_EVIDENCE', }, ], }); expectQuarantineReason( planCompetitionMigration(legacy), 'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT', ); }); it('quarantines a TournamentCode game number outside the Competition topology', () => { const legacy = pairedMatch({ _id: 'match-out-of-range-code', gameSchedule: undefined, result: { games: [], seriesResults: [] }, tournamentCodes: [ { _id: 'out-of-range-code', state: 'reserved', gameNumber: 99, }, ], }); expectQuarantineReason( planCompetitionMigration(legacy), 'TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', ); }); it('does not guess the first slot of a multi-slot Series without exact slot evidence', () => { const legacy = pairedMatch({ _id: 'match-multi-slot-code-without-evidence', gameCount: 3, result: { games: [], seriesResults: [] }, tournamentCodes: [ { _id: 'code-with-series-only', state: 'reserved', bracketMatchId: 'PAIR_M1', }, ], }); const plan = planCompetitionMigration(legacy); expectQuarantineReason( plan, 'TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', ); }); it('repairs the data.txt WB_R2_M2 positional bug from accepted game evidence', () => { const legacy = loadDataTxtFixture(); const plan = requireReady(planCompetitionMigration(legacy)); const projection = projectCompetition({ competitionId: plan.competition.id, revision: plan.competition.revision, projectorVersion: plan.competition.projectorVersion, teams: plan.competition.teams, format: plan.competition.format, seriesGraph: plan.competition.seriesGraph, facts: plan.facts, }); const team3 = plan.competition.teams.find( (team) => team.legacyTeamIndex === 3, ); const team8 = plan.competition.teams.find( (team) => team.legacyTeamIndex === 8, ); const series = (code: string) => projection.series.find((candidate) => candidate.code === code); expect(team3).toBeDefined(); expect(team8).toBeDefined(); expect(series('WB_R2_M2')).toMatchObject({ status: 'completed', entries: [ { slot: 'A', teamId: team8!.teamId, gameWins: 2 }, { slot: 'B', teamId: team3!.teamId, gameWins: 1 }, ], outcome: { type: 'played', winnerTeamId: team8!.teamId, loserTeamId: team3!.teamId, }, }); expect( series('WB_FINAL')?.entries.some( (entry) => entry.slot === 'B' && entry.teamId === team8!.teamId && entry.gameWins === 0, ), ).toBe(true); expect( series('LB_R2_M1')?.entries.some( (entry) => entry.slot === 'B' && entry.teamId === team3!.teamId && entry.gameWins === 0, ), ).toBe(true); }); }); function pairedMatch( overrides: Partial = {}, ): LegacyMatchInput { return { _id: 'match-legacy-paired', communityId: 'community-1', gameMode: 'pair', gameCount: 1, status: 'in-progress', teams: [legacyTeam(1, 'One'), legacyTeam(2, 'Two')], gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }], createdAt: '2026-07-01T00:00:00.000Z', updatedAt: '2026-07-02T00:00:00.000Z', ...overrides, }; } function legacyTeam(teamIndex: number, name: string) { return { teamIndex, name, captainUserId: `captain-${teamIndex}`, members: [], }; } function legacyGame( overrides: Partial['games'][number]>, ): NonNullable['games'][number] { return { gameNumber: 1, riotMatchId: 'KR_DEFAULT', blueTeamIndex: 1, redTeamIndex: 2, winnerTeamIndex: 1, gameCreation: 1782864000000, gameDuration: 1800, participants: [], ...overrides, }; } function requireReady( plan: ReturnType, ): ReadyCompetitionMigrationPlan { if (plan.status !== 'ready') { throw new Error( `Expected ready migration plan: ${JSON.stringify(plan.reasons)}`, ); } return plan; } function expectQuarantineReason( plan: ReturnType, code: string, ): void { expect(plan.status).toBe('quarantined'); if (plan.status !== 'quarantined') { throw new Error( `Expected a quarantined migration plan, got ${plan.status}.`, ); } expect(plan.reasons.some((reason) => reason.code === code)).toBe(true); } function loadDataTxtFixture(): LegacyMatchInput { const seededTeamIndexes = [1, 8, 3, 4, 5, 6, 7, 2]; const games = [ ['WB_R1_M3', 8, 7, 8], ['WB_R1_M3', 7, 8, 8], ['WB_R1_M4', 3, 6, 3], ['WB_R1_M4', 6, 3, 3], ['WB_R2_M2', 3, 8, 8], ['WB_R2_M2', 8, 3, 3], ['WB_R2_M2', 3, 8, 8], ] as const; return { _id: '6a3e0c2c8ade90b14b72f335', communityId: '69ebe0adf627c11be2f020a1', gameMode: 'double-elimination', gameCount: 3, status: 'in-progress', teams: Array.from({ length: 8 }, (_, index) => legacyTeam( index + 1, index + 1 === 3 ? '해온해줘' : index + 1 === 8 ? '똥칼라파워' : `${index + 1}팀`, ), ), doubleElimination: { teamCount: 8, resetFinalEnabled: true, seeds: seededTeamIndexes.map((teamIndex, index) => ({ seedNumber: index + 1, teamIndex, })), bracketMatches: [], }, result: { games: games.map( ( [bracketMatchId, blueTeamIndex, redTeamIndex, winnerTeamIndex], index, ) => legacyGame({ gameNumber: index + 1, bracketMatchId, riotMatchId: `KR_DATA_TXT_${index + 1}`, riotArchivePresent: true, blueTeamIndex, redTeamIndex, winnerTeamIndex, gameCreation: 1782864000000 + index * 60_000, }), ), seriesResults: [], }, createdAt: '2026-06-27T05:18:00.000Z', updatedAt: '2026-07-12T17:17:00.000Z', }; } function dataTxtUpperBracketTopology() { return [ 'WB_R1_M1', 'WB_R1_M2', 'WB_R1_M3', 'WB_R1_M4', 'WB_R2_M1', 'WB_R2_M2', 'WB_FINAL', ].map((bracketMatchId, index) => ({ bracketMatchId, gameNumber: index + 1, gameCount: 3, requiredWins: 2, 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', }; }