import { createHash } from 'node:crypto'; import { projectCompetition } from '../../../competition/domain/competition-projector'; import { generateSeriesGraph, type CompetitionGraphFormat, type RoundRobinPairing, type SeriesDefinition, } from '../../../competition/domain/series-graph'; const MIGRATION_RUN_ID = '20260712-competition-domain'; const SCHEMA_VERSION = 1; const PROJECTOR_VERSION = 1; const EPOCH = '1970-01-01T00:00:00.000Z'; type LegacyGameMode = 'pair' | 'bracket' | 'round-robin' | 'double-elimination'; interface LegacyTeamMemberInput { userId: unknown; assignedPosition?: string; cost?: number; } interface LegacyTeamInput { teamIndex: number; name?: string; captainUserId?: unknown; members?: LegacyTeamMemberInput[]; } interface LegacyParticipantInput { userId: unknown; gameName?: string; tagLine?: string; profileIconId?: number; } interface LegacyGameInput { gameNumber: number; bracketMatchId?: string; riotMatchId?: string; riotArchivePresent?: boolean; payloadHash?: string; blueTeamIndex: number; redTeamIndex: number; winnerTeamIndex: number; winnerSide?: 'blue' | 'red'; gameCreation?: number | string | Date; gameDuration?: number; riotGameEndedAt?: number | string | Date; riotGameEndedAtSource?: 'gameEndTimestamp' | 'gameCreation'; participants?: Array<{ userId?: unknown; teamIndex?: number; side?: 'blue' | 'red'; [key: string]: unknown; }>; } type LegacyUsedOccurrenceSource = | 'riot-archive-gameEndTimestamp' | 'riot-archive-gameCreation' | 'legacy-gameCreation-plus-duration'; interface LegacyUsedOccurrenceEvidence { at: string; source: LegacyUsedOccurrenceSource; } interface LegacySeriesResultInput { bracketMatchId?: string; teamAIndex: number; teamBIndex: number; teamAWins?: number; teamBWins?: number; winnerTeamIndex?: number; } interface LegacyBracketMatchInput { bracketMatchId: string; gameNumber?: number; gameCount?: number; requiredWins?: number; bracketSide?: 'winner' | 'loser' | 'grand-final' | 'reset-final'; state?: 'pending' | 'ready' | 'completed'; winnerTeamIndex?: number; completedAt?: Date | string; completedBy?: 'riot-result' | 'walkover'; walkover?: { winnerTeamIndex: number; reason?: string; awardedBy?: unknown; awardedAt?: Date | string; active: boolean; }; } interface LegacyTournamentCodeInput { _id: unknown; state?: 'available' | 'reserved' | 'used' | 'expired' | 'released' | 'voided'; gameNumber?: number; bracketMatchId?: string; riotMatchId?: string; reservedAt?: Date | string; usedAt?: Date | string; releasedAt?: Date | string; voidedAt?: Date | string; createdAt?: Date | string; updatedAt?: Date | string; } export interface LegacyMatchInput { _id: unknown; communityId: unknown; gameMode: LegacyGameMode; gameCount: number; roundRobinMaxRounds?: number; status?: string; participants?: LegacyParticipantInput[]; teams: LegacyTeamInput[]; gameSchedule?: Array<{ gameNumber: number; roundNumber?: number; teamAIndex: number; teamBIndex: number; }>; result?: { winnerTeamIndex?: number; riotMatchIds?: string[]; games: LegacyGameInput[]; seriesResults?: LegacySeriesResultInput[]; }; doubleElimination?: { teamCount?: 4 | 8; resetFinalEnabled?: boolean; seeds?: Array<{ seedNumber: number; teamIndex: number }>; bracketMatches?: LegacyBracketMatchInput[]; }; tournamentCodes?: LegacyTournamentCodeInput[]; riotMatchArchiveIds?: string[]; createdAt?: Date | string; updatedAt?: Date | string; } export interface CompetitionMigrationIssue { code: string; message: string; details?: Record; } export interface CompetitionMigrationTeamSnapshot { teamId: string; legacyTeamIndex: number; displayOrder: number; seedNumber: number; name: string; captainUserId?: string; members: Array<{ userId: string; displayName: string; gameName?: string; tagLine?: string; profileIconId?: number; assignedPosition?: string; cost?: number; }>; } interface MigrationFactBase { id: string; competitionId: string; revision: number; ordinalWithinRevision: 1; commandId: string; idempotencyKey: string; requestHash: string; schemaVersion: 1; actor: { type: 'migration'; migrationRunId: string }; occurredAt: string; recordedAt: string; } export interface MigrationGameAcceptedFact extends MigrationFactBase { type: 'game-accepted'; gameId: string; seriesId: string; gameSlotId: string; ordinal: number; startedAt: string; durationSeconds: number; participants: Array<{ userId: string; teamId: string; side: 'blue' | 'red'; summonerName: string; tagLine: string; championId: number; kills: number; deaths: number; assists: number; }>; evidence: | { type: 'riot'; riotMatchId: string; payloadHash: string } | { type: 'legacy'; legacyReference: string }; mapping: { mappingVersion: 1; confidence: number; blueTeamId: string; redTeamId: string; winnerTeamId: string; participantAssignments: Array<{ userId: string; teamId: string; side: 'blue' | 'red'; }>; }; } export interface MigrationSeriesAdjudicatedFact extends MigrationFactBase { type: 'series-adjudicated'; seriesId: string; decision: | { type: 'walkover' | 'administrative'; winnerTeamId: string; } | { type: 'administrative-draw' }; reason: string; } export type CompetitionMigrationFact = | MigrationGameAcceptedFact | MigrationSeriesAdjudicatedFact; export interface CompetitionMigrationAssignment { id: string; competitionId: string; seriesId: string; gameSlotId: string; tournamentCodeId: string; state: 'reserved' | 'used' | 'released' | 'voided'; reservedAt: string; usedAt?: string; releasedAt?: string; voidedAt?: string; riotMatchId?: string; commandId: string; } export interface CompetitionMigrationSnapshot { id: string; matchId: string; communityId: string; schemaVersion: 1; projectorVersion: 1; revision: number; phase: 'ready' | 'running' | 'completed' | 'cancelled'; teams: CompetitionMigrationTeamSnapshot[]; format: CompetitionGraphFormat; seriesGraph: SeriesDefinition[]; projection: ReturnType; createdAt: string; updatedAt: string; } export interface ReadyCompetitionMigrationPlan { status: 'ready'; competition: CompetitionMigrationSnapshot; facts: CompetitionMigrationFact[]; assignments: CompetitionMigrationAssignment[]; warnings: CompetitionMigrationIssue[]; } export interface QuarantinedCompetitionMigrationPlan { status: 'quarantined'; matchId: string; reasons: CompetitionMigrationIssue[]; warnings: CompetitionMigrationIssue[]; } export type CompetitionMigrationPlan = | ReadyCompetitionMigrationPlan | QuarantinedCompetitionMigrationPlan; interface PlannedGame { legacy: LegacyGameInput; series: SeriesDefinition; confidence: number; ordinal: number; } interface PendingFact { kind: CompetitionMigrationFact['type']; seriesOrder: number; occurredAt: string; logicalKey: string; build(base: MigrationFactBase): CompetitionMigrationFact; } /** * Builds an entirely deterministic write plan from one legacy Match snapshot. * It performs no I/O and deliberately quarantines uncertainty instead of * guessing a Series or team identity. */ export function planCompetitionMigration( input: LegacyMatchInput, options: { migrationRunId?: string } = {}, ): CompetitionMigrationPlan { const migrationRunId = options.migrationRunId ?? MIGRATION_RUN_ID; const warnings: CompetitionMigrationIssue[] = []; const reasons: CompetitionMigrationIssue[] = []; const matchId = opaqueString(input?._id); const communityId = opaqueString(input?.communityId); if (!matchId) { reasons.push( issue('MATCH_ID_MISSING', 'The legacy Match has no identity.'), ); } if (!communityId) { reasons.push( issue( 'COMMUNITY_ID_MISSING', 'The legacy Match has no Community identity.', ), ); } const competitionId = stableId(matchId || 'missing-match', 'competition'); const teamBuild = buildTeamSnapshots(input, competitionId, reasons); if (reasons.length > 0) { return quarantined(matchId, reasons, warnings); } const format = buildFormat( input, teamBuild.teamIdByLegacyIndex, warnings, reasons, ); if (!format) return quarantined(matchId, reasons, warnings); let seriesGraph: SeriesDefinition[]; try { seriesGraph = generateSeriesGraph({ competitionId, teams: teamBuild.teams, format, }); } catch (error) { reasons.push( issue( 'SERIES_GRAPH_GENERATION_FAILED', errorMessage(error), errorCodeDetails(error), ), ); return quarantined(matchId, reasons, warnings); } const plannedGames = mapGames( input, seriesGraph, teamBuild.teamIdByLegacyIndex, reasons, ); const pendingFacts: PendingFact[] = []; addGameFacts( input, competitionId, plannedGames, teamBuild.teamIdByLegacyIndex, seriesGraph, pendingFacts, reasons, ); addAdjudicationFacts( input, competitionId, plannedGames, teamBuild.teamIdByLegacyIndex, seriesGraph, pendingFacts, reasons, ); if (reasons.length > 0) { return quarantined(matchId, reasons, warnings); } const facts = materializeFacts( competitionId, migrationRunId, normalizeDate(input.updatedAt, normalizeDate(input.createdAt, EPOCH)), pendingFacts, ); let projection: ReturnType; try { projection = projectCompetition({ competitionId, revision: facts.length, projectorVersion: PROJECTOR_VERSION, teams: teamBuild.teams, format, seriesGraph, facts, }); } catch (error) { reasons.push( issue( 'MIGRATION_PROJECTION_REJECTED', errorMessage(error), errorCodeDetails(error), ), ); return quarantined(matchId, reasons, warnings); } const assignments = buildAssignments( input, competitionId, facts, seriesGraph, teamBuild.teamIdByLegacyIndex, reasons, warnings, ); if (reasons.length > 0) { return quarantined(matchId, reasons, warnings); } const createdAt = normalizeDate(input.createdAt, EPOCH); const updatedAt = normalizeDate(input.updatedAt, createdAt); return { status: 'ready', competition: { id: competitionId, matchId, communityId, schemaVersion: SCHEMA_VERSION, projectorVersion: PROJECTOR_VERSION, revision: facts.length, phase: projection.phase, teams: teamBuild.teams, format, seriesGraph, projection, createdAt, updatedAt, }, facts, assignments, warnings: sortedIssues(warnings), }; } function buildTeamSnapshots( input: LegacyMatchInput, competitionId: string, reasons: CompetitionMigrationIssue[], ): { teams: CompetitionMigrationTeamSnapshot[]; teamIdByLegacyIndex: Map; } { const legacyTeams = Array.isArray(input?.teams) ? input.teams : []; if (legacyTeams.length < 2) { reasons.push( issue('TEAMS_MISSING', 'At least two legacy teams are required.'), ); } const indexes = new Set(); for (const team of legacyTeams) { if (!Number.isInteger(team.teamIndex) || team.teamIndex < 1) { reasons.push( issue('INVALID_LEGACY_TEAM_INDEX', 'A legacy team index is invalid.', { teamIndex: team.teamIndex, }), ); continue; } if (indexes.has(team.teamIndex)) { reasons.push( issue( 'DUPLICATE_LEGACY_TEAM_INDEX', `Legacy team index ${team.teamIndex} occurs more than once.`, { teamIndex: team.teamIndex }, ), ); } indexes.add(team.teamIndex); } const sorted = [...legacyTeams].sort( (left, right) => left.teamIndex - right.teamIndex, ); const displayOrderByIndex = new Map( sorted.map((team, index) => [team.teamIndex, index + 1]), ); const seedByTeamIndex = seedMap(input, sorted, reasons); const participantByUserId = new Map( (input.participants ?? []).map((participant) => [ opaqueString(participant.userId), participant, ]), ); const teamIdByLegacyIndex = new Map(); const teams = sorted.map((team) => { const teamId = stableId(competitionId, 'team', team.teamIndex); teamIdByLegacyIndex.set(team.teamIndex, teamId); const members = (team.members ?? []).map((member) => { const userId = opaqueString(member.userId); const participant = participantByUserId.get(userId); return { userId, displayName: participant?.gameName || (userId ? `legacy-user:${userId}` : 'legacy-user'), ...(participant?.gameName ? { gameName: participant.gameName } : {}), ...(participant?.tagLine ? { tagLine: participant.tagLine } : {}), ...(typeof participant?.profileIconId === 'number' ? { profileIconId: participant.profileIconId } : {}), ...(member.assignedPosition ? { assignedPosition: member.assignedPosition } : {}), ...(typeof member.cost === 'number' ? { cost: member.cost } : {}), }; }); const captainUserId = opaqueString(team.captainUserId); return { teamId, legacyTeamIndex: team.teamIndex, displayOrder: displayOrderByIndex.get(team.teamIndex)!, seedNumber: seedByTeamIndex.get(team.teamIndex)!, name: team.name?.trim() || `${team.teamIndex}팀`, ...(captainUserId ? { captainUserId } : {}), members, }; }); return { teams, teamIdByLegacyIndex }; } function seedMap( input: LegacyMatchInput, sortedTeams: LegacyTeamInput[], reasons: CompetitionMigrationIssue[], ): Map { if (input.gameMode !== 'double-elimination') { return new Map( sortedTeams.map((team, index) => [team.teamIndex, index + 1]), ); } const seeds = input.doubleElimination?.seeds ?? []; if (seeds.length !== sortedTeams.length) { reasons.push( issue( 'INVALID_DOUBLE_ELIMINATION_SEEDS', 'Every double-elimination team must have exactly one seed.', ), ); } const result = new Map(); const seenSeeds = new Set(); for (const seed of seeds) { if ( !Number.isInteger(seed.seedNumber) || seed.seedNumber < 1 || seenSeeds.has(seed.seedNumber) || !sortedTeams.some((team) => team.teamIndex === seed.teamIndex) || result.has(seed.teamIndex) ) { reasons.push( issue( 'INVALID_DOUBLE_ELIMINATION_SEEDS', 'Double-elimination seeds are duplicate, non-contiguous, or reference an unknown team.', { seedNumber: seed.seedNumber, teamIndex: seed.teamIndex }, ), ); continue; } seenSeeds.add(seed.seedNumber); result.set(seed.teamIndex, seed.seedNumber); } for (let seedNumber = 1; seedNumber <= sortedTeams.length; seedNumber += 1) { if (!seenSeeds.has(seedNumber)) { reasons.push( issue( 'INVALID_DOUBLE_ELIMINATION_SEEDS', 'Double-elimination seeds must be contiguous from one.', { missingSeedNumber: seedNumber }, ), ); } } return result; } function buildFormat( input: LegacyMatchInput, teamIds: Map, warnings: CompetitionMigrationIssue[], reasons: CompetitionMigrationIssue[], ): CompetitionGraphFormat | undefined { const gameCount = positiveInteger(input.gameCount); if (!gameCount) { reasons.push( issue( 'INVALID_GAME_COUNT', 'Legacy gameCount must be a positive integer.', ), ); return undefined; } switch (input.gameMode) { case 'pair': return fixedFormat('paired-series', gameCount); case 'bracket': warnings.push( issue( 'LEGACY_BRACKET_MAPPED_TO_PAIRED_SERIES', 'The unused legacy bracket mode was executed as paired Series and is migrated accordingly.', ), ); return fixedFormat('paired-series', gameCount); case 'round-robin': { const pairings = normalizeLegacyRoundRobinPairings( input, teamIds, gameCount, warnings, reasons, ); if (pairings === null) return undefined; return { type: 'round-robin', rule: fixedRule(gameCount), ...(positiveInteger(input.roundRobinMaxRounds) ? { maxRounds: input.roundRobinMaxRounds } : {}), ...(pairings ? { pairings } : {}), tieBreakers: ['series-wins', 'game-diff', 'head-to-head'], }; } case 'double-elimination': { const teamCount = input.teams.length; if (teamCount !== 4 && teamCount !== 8) { reasons.push( issue( 'UNSUPPORTED_DOUBLE_ELIMINATION_TEAM_COUNT', 'Only four- and eight-team double elimination can be migrated.', { teamCount }, ), ); return undefined; } const bracketMatches = input.doubleElimination?.bracketMatches ?? []; return { type: 'double-elimination', teamCount, resetFinalEnabled: input.doubleElimination?.resetFinalEnabled ?? false, rules: { upper: legacyFirstToRule(bracketMatches, 'winner', gameCount), lower: legacyFirstToRule(bracketMatches, 'loser', 1), grandFinal: legacyFirstToRule(bracketMatches, 'grand-final', 1), resetFinal: legacyFirstToRule(bracketMatches, 'reset-final', 1), }, }; } default: reasons.push( issue( 'UNSUPPORTED_LEGACY_GAME_MODE', `Unsupported legacy game mode: ${String(input.gameMode)}`, ), ); return undefined; } } function normalizeLegacyRoundRobinPairings( input: LegacyMatchInput, teamIds: ReadonlyMap, gameCount: number, warnings: CompetitionMigrationIssue[], reasons: CompetitionMigrationIssue[], ): RoundRobinPairing[] | undefined | null { const schedule = input.gameSchedule ?? []; if (schedule.length === 0) return undefined; const seenGameNumbers = new Set(); const groups = new Map< string, { roundNumber?: number; teamAId: string; teamBId: string; gameNumbers: number[]; } >(); 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 = assignment.roundNumber === undefined ? undefined : positiveInteger(assignment.roundNumber); if ( !positiveInteger(assignment.gameNumber) || seenGameNumbers.has(assignment.gameNumber) || !teamAId || !teamBId || teamAId === teamBId || (hasRoundNumbers && !roundNumber) || (positiveInteger(input.roundRobinMaxRounds) !== undefined && roundNumber !== undefined && roundNumber > input.roundRobinMaxRounds!) ) { reasons.push( issue( 'INVALID_ROUND_ROBIN_SCHEDULE', 'The persisted round-robin schedule has an invalid game, round, or team identity.', { gameNumber: assignment.gameNumber }, ), ); return null; } seenGameNumbers.add(assignment.gameNumber); const opponents = [teamAId, teamBId].sort(); const key = JSON.stringify(opponents); const existing = groups.get(key); if (existing && existing.roundNumber !== roundNumber) { reasons.push( issue( 'INVALID_ROUND_ROBIN_SCHEDULE', 'A persisted round-robin opponent pair occurs in multiple rounds.', { gameNumber: assignment.gameNumber }, ), ); return null; } const group = existing ?? ({ roundNumber, teamAId, teamBId, gameNumbers: [], } satisfies { roundNumber?: number; teamAId: string; teamBId: string; gameNumbers: number[]; }); group.gameNumbers.push(assignment.gameNumber); groups.set(key, group); } 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! || 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, scheduledGameCount: group.gameNumbers.length, expectedGameCount: gameCount, }, ), ); return null; } 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 }, ), ); return null; } roundTeams.add(group.teamAId); roundTeams.add(group.teamBId); teamsByRound.set(roundNumber, roundTeams); const matchNumber = (matchNumberByRound.get(roundNumber) ?? 0) + 1; matchNumberByRound.set(roundNumber, matchNumber); pairings.push({ roundNumber, matchNumber, teamAId: group.teamAId, teamBId: group.teamBId, }); } 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; } function fixedRule(gameCount: number) { return { type: 'fixed-games' as const, gameCount, drawPolicy: 'allow' as const, }; } function legacyFirstToRule( bracketMatches: LegacyBracketMatchInput[], bracketSide: NonNullable, fallbackGameCount: number, ) { const matching = bracketMatches.filter( (bracketMatch) => bracketMatch.bracketSide === bracketSide, ); const maxGames = Math.max( ...matching.map( (bracketMatch) => positiveInteger(bracketMatch.gameCount) ?? 0, ), fallbackGameCount, ); const configuredWins = matching .map((bracketMatch) => positiveInteger(bracketMatch.requiredWins)) .filter((value): value is number => value !== undefined); const winsRequired = configuredWins[0] ?? Math.floor(maxGames / 2) + 1; return { type: 'first-to' as const, winsRequired, maxGames }; } function mapGames( input: LegacyMatchInput, graph: SeriesDefinition[], teamIds: Map, reasons: CompetitionMigrationIssue[], ): PlannedGame[] { const mapped: Array & { ordinal?: number }> = []; const games = input.result?.games ?? []; for (const game of games) { const blueTeamId = teamIds.get(game.blueTeamIndex); const redTeamId = teamIds.get(game.redTeamIndex); const winnerTeamId = teamIds.get(game.winnerTeamIndex); if (!blueTeamId || !redTeamId || !winnerTeamId) { reasons.push( issue( 'GAME_REFERENCES_UNKNOWN_TEAM', `Legacy game ${game.gameNumber} references an unknown team.`, { gameNumber: game.gameNumber, blueTeamIndex: game.blueTeamIndex, redTeamIndex: game.redTeamIndex, winnerTeamIndex: game.winnerTeamIndex, }, ), ); continue; } if ( blueTeamId === redTeamId || (winnerTeamId !== blueTeamId && winnerTeamId !== redTeamId) ) { reasons.push( issue( 'INCONSISTENT_GAME_TEAM_EVIDENCE', `Legacy game ${game.gameNumber} has an invalid team or winner set.`, { gameNumber: game.gameNumber }, ), ); continue; } const resolution = resolveGameSeries( input, graph, game, blueTeamId, redTeamId, ); if ('issue' in resolution) { reasons.push(resolution.issue); continue; } mapped.push({ legacy: game, series: resolution.series, confidence: resolution.confidence, ...(resolution.ordinal ? { ordinal: resolution.ordinal } : {}), }); } const grouped = new Map< string, Array & { ordinal?: number }> >(); for (const game of mapped) { const group = grouped.get(game.series.id) ?? []; group.push(game); grouped.set(game.series.id, group); } const result: PlannedGame[] = []; for (const [seriesId, seriesGames] of grouped) { seriesGames.sort(compareLegacyGames); const series = graph.find((candidate) => candidate.id === seriesId)!; if (seriesGames.length > series.gameSlots.length) { reasons.push( issue( 'TOO_MANY_GAMES_FOR_SERIES', `Series ${series.code ?? series.id} has more legacy games than stable slots.`, { seriesId, gameCount: seriesGames.length, slotCount: series.gameSlots.length, }, ), ); continue; } 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) => graph.indexOf(left.series) - graph.indexOf(right.series) || left.ordinal - right.ordinal, ); } function resolveGameSeries( input: LegacyMatchInput, graph: SeriesDefinition[], game: LegacyGameInput, blueTeamId: string, redTeamId: string, ): | { series: SeriesDefinition; confidence: number; ordinal?: number } | { issue: CompetitionMigrationIssue } { if (game.bracketMatchId) { const series = graph.find( (candidate) => candidate.code === 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( (assignment) => assignment.gameNumber === game.gameNumber, ); if (assignments.length > 1) { return { issue: issue( 'AMBIGUOUS_GAME_ASSIGNMENT', `Legacy game number ${game.gameNumber} maps to multiple schedule entries.`, { gameNumber: game.gameNumber, assignmentCount: assignments.length }, ), }; } if (assignments.length === 1) { const assignment = assignments[0]; const expected = new Set([assignment.teamAIndex, assignment.teamBIndex]); if (!expected.has(game.blueTeamIndex) || !expected.has(game.redTeamIndex)) { return { issue: issue( 'GAME_ASSIGNMENT_TEAM_MISMATCH', `Legacy game ${game.gameNumber} conflicts with its schedule entry.`, { gameNumber: game.gameNumber }, ), }; } } const candidates = graph.filter((series) => 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 { issue: issue( candidates.length > 1 ? 'AMBIGUOUS_GAME_SERIES_MAPPING' : 'GAME_SERIES_MAPPING_NOT_FOUND', candidates.length > 1 ? `Legacy game ${game.gameNumber} matches multiple Series.` : `Legacy game ${game.gameNumber} cannot be mapped to a Series.`, { gameNumber: game.gameNumber, candidateSeriesIds: candidates.map((series) => series.id), }, ), }; } 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, rightTeamId: string, ): boolean { const sourceTeamIds = series.slots.map((slot) => slot.source.type === 'team' ? slot.source.teamId : undefined, ); return ( sourceTeamIds.every((teamId) => teamId !== undefined) && new Set(sourceTeamIds).size === 2 && sourceTeamIds.includes(leftTeamId) && sourceTeamIds.includes(rightTeamId) ); } function addGameFacts( input: LegacyMatchInput, competitionId: string, plannedGames: PlannedGame[], teamIds: Map, graph: SeriesDefinition[], pending: PendingFact[], reasons: CompetitionMigrationIssue[], ): void { const riotIds = new Set(); for (const planned of plannedGames) { const game = planned.legacy; const riotMatchId = game.riotMatchId?.trim(); if (riotMatchId && riotIds.has(riotMatchId)) { reasons.push( issue( 'DUPLICATE_RIOT_MATCH_EVIDENCE', `Riot match ${riotMatchId} appears more than once.`, { riotMatchId }, ), ); continue; } if (riotMatchId) riotIds.add(riotMatchId); const slot = planned.series.gameSlots.find( (candidate) => candidate.ordinal === planned.ordinal, )!; const blueTeamId = teamIds.get(game.blueTeamIndex)!; const redTeamId = teamIds.get(game.redTeamIndex)!; const winnerTeamId = teamIds.get(game.winnerTeamIndex)!; const occurredAt = gameOccurrence(game, input); const evidence = gameEvidence(input, competitionId, planned); const logicalKey = `game:${planned.series.id}:${planned.ordinal}:${riotMatchId ?? game.gameNumber}`; pending.push({ kind: 'game-accepted', seriesOrder: graph.indexOf(planned.series), occurredAt, logicalKey, build: (base) => ({ ...base, type: 'game-accepted', gameId: stableId( competitionId, 'game', planned.series.id, planned.ordinal, riotMatchId ?? game.gameNumber, ), seriesId: planned.series.id, gameSlotId: slot.id, ordinal: planned.ordinal, startedAt: occurredAt, durationSeconds: typeof game.gameDuration === 'number' ? game.gameDuration : 0, participants: (game.participants ?? []).flatMap((participant) => { const userId = opaqueString(participant.userId); const teamId = teamIds.get(participant.teamIndex ?? -1); if ( !userId || !teamId || (participant.side !== 'blue' && participant.side !== 'red') ) { return []; } return [ { userId, teamId, side: participant.side, summonerName: typeof participant.summonerName === 'string' ? participant.summonerName : '', tagLine: typeof participant.tagLine === 'string' ? participant.tagLine : '', championId: numericValue(participant.championId), kills: numericValue(participant.kills), deaths: numericValue(participant.deaths), assists: numericValue(participant.assists), }, ]; }), evidence, mapping: { mappingVersion: 1, confidence: planned.confidence, blueTeamId, redTeamId, winnerTeamId, participantAssignments: (game.participants ?? []) .filter( (participant) => opaqueString(participant.userId) && (participant.side === 'blue' || participant.side === 'red') && teamIds.has(participant.teamIndex ?? -1), ) .map((participant) => ({ userId: opaqueString(participant.userId), teamId: teamIds.get(participant.teamIndex!)!, side: participant.side!, })), }, }), }); } } function gameEvidence( input: LegacyMatchInput, competitionId: string, planned: PlannedGame, ): MigrationGameAcceptedFact['evidence'] { const game = planned.legacy; const riotMatchId = game.riotMatchId?.trim(); const archiveKnown = game.riotArchivePresent === true || (riotMatchId !== undefined && input.riotMatchArchiveIds?.includes(riotMatchId)); if (riotMatchId && archiveKnown) { return { type: 'riot', riotMatchId, payloadHash: game.payloadHash ?? `sha256:${stableHash(canonicalize(game))}`, }; } return { type: 'legacy', legacyReference: [ 'match', opaqueString(input._id), 'result.games', String(game.gameNumber), riotMatchId ?? stableId( competitionId, 'legacy-game', planned.series.id, planned.ordinal, ), ].join(':'), }; } function addAdjudicationFacts( input: LegacyMatchInput, competitionId: string, plannedGames: PlannedGame[], teamIds: Map, graph: SeriesDefinition[], pending: PendingFact[], reasons: CompetitionMigrationIssue[], ): void { const gameSeriesIds = new Set(plannedGames.map((game) => game.series.id)); const adjudicatedSeriesIds = new Set(); for (const bracketMatch of input.doubleElimination?.bracketMatches ?? []) { const walkover = bracketMatch.walkover; if (!walkover?.active) continue; const series = graph.find( (candidate) => candidate.code === bracketMatch.bracketMatchId, ); const winnerTeamId = teamIds.get(walkover.winnerTeamIndex); if (!series || !winnerTeamId) { reasons.push( issue( 'WALKOVER_MAPPING_NOT_FOUND', `Active walkover ${bracketMatch.bracketMatchId} cannot be mapped.`, { bracketMatchId: bracketMatch.bracketMatchId }, ), ); continue; } if (gameSeriesIds.has(series.id)) { reasons.push( issue( 'WALKOVER_CONFLICTS_WITH_GAMES', `Series ${bracketMatch.bracketMatchId} has both active games and a walkover.`, { seriesId: series.id }, ), ); continue; } addAdjudication({ competitionId, series, winnerTeamId, decisionType: 'walkover', reason: walkover.reason?.trim() || 'legacy-walkover', occurredAt: normalizeDate(walkover.awardedAt, sourceFallbackDate(input)), graph, pending, logicalSuffix: 'walkover', }); adjudicatedSeriesIds.add(series.id); } for (const result of input.result?.seriesResults ?? []) { if (!result.winnerTeamIndex) continue; const resolution = resolveSeriesResult(graph, result, teamIds); if ('issue' in resolution) { reasons.push(resolution.issue); continue; } const { series } = resolution; if (gameSeriesIds.has(series.id) || adjudicatedSeriesIds.has(series.id)) continue; const winnerTeamId = teamIds.get(result.winnerTeamIndex); if (!winnerTeamId) { reasons.push( issue( 'WINNER_ONLY_RESULT_REFERENCES_UNKNOWN_TEAM', 'A winner-only Series references an unknown team.', { winnerTeamIndex: result.winnerTeamIndex, seriesId: series.id }, ), ); continue; } addAdjudication({ competitionId, series, winnerTeamId, decisionType: 'administrative', reason: 'legacy-winner-only-result', occurredAt: seriesCompletionDate(input, series.code), graph, pending, logicalSuffix: 'winner-only', }); adjudicatedSeriesIds.add(series.id); } if ( input.result?.winnerTeamIndex && graph.length === 1 && !gameSeriesIds.has(graph[0].id) && !adjudicatedSeriesIds.has(graph[0].id) ) { const winnerTeamId = teamIds.get(input.result.winnerTeamIndex); if (!winnerTeamId) { reasons.push( issue( 'WINNER_ONLY_RESULT_REFERENCES_UNKNOWN_TEAM', 'The Match winner references an unknown team.', { winnerTeamIndex: input.result.winnerTeamIndex }, ), ); } else { addAdjudication({ competitionId, series: graph[0], winnerTeamId, decisionType: 'administrative', reason: 'legacy-winner-only-result', occurredAt: sourceFallbackDate(input), graph, pending, logicalSuffix: 'match-winner-only', }); } } } function resolveSeriesResult( graph: SeriesDefinition[], result: LegacySeriesResultInput, teamIds: Map, ): { series: SeriesDefinition } | { issue: CompetitionMigrationIssue } { if (result.bracketMatchId) { const series = graph.find( (candidate) => candidate.code === result.bracketMatchId, ); return series ? { series } : { issue: issue( 'WINNER_ONLY_SERIES_MAPPING_NOT_FOUND', `Winner-only bracket code ${result.bracketMatchId} has no Series.`, ), }; } const left = teamIds.get(result.teamAIndex); const right = teamIds.get(result.teamBIndex); if (!left || !right) { return { issue: issue( 'WINNER_ONLY_RESULT_REFERENCES_UNKNOWN_TEAM', 'A winner-only Series references an unknown team.', ), }; } const candidates = graph.filter((series) => staticSeriesHasTeamSet(series, left, right), ); if (candidates.length !== 1) { return { issue: issue( candidates.length > 1 ? 'AMBIGUOUS_WINNER_ONLY_SERIES_MAPPING' : 'WINNER_ONLY_SERIES_MAPPING_NOT_FOUND', 'A winner-only Series cannot be mapped without guessing.', { candidateSeriesIds: candidates.map((series) => series.id) }, ), }; } return { series: candidates[0] }; } function addAdjudication(params: { competitionId: string; series: SeriesDefinition; winnerTeamId: string; decisionType: 'walkover' | 'administrative'; reason: string; occurredAt: string; graph: SeriesDefinition[]; pending: PendingFact[]; logicalSuffix: string; }): void { params.pending.push({ kind: 'series-adjudicated', seriesOrder: params.graph.indexOf(params.series), occurredAt: params.occurredAt, logicalKey: `adjudication:${params.series.id}:${params.logicalSuffix}`, build: (base) => ({ ...base, type: 'series-adjudicated', seriesId: params.series.id, decision: { type: params.decisionType, winnerTeamId: params.winnerTeamId, }, reason: params.reason, }), }); } function materializeFacts( competitionId: string, migrationRunId: string, recordedAt: string, pending: PendingFact[], ): CompetitionMigrationFact[] { const sorted = [...pending].sort( (left, right) => left.occurredAt.localeCompare(right.occurredAt) || left.seriesOrder - right.seriesOrder || left.logicalKey.localeCompare(right.logicalKey), ); return sorted.map((fact, index) => { const revision = index + 1; const id = stableId(competitionId, 'fact', fact.logicalKey); const commandId = stableId( competitionId, 'migration-command', fact.logicalKey, ); const base: MigrationFactBase = { id, competitionId, revision, ordinalWithinRevision: 1, commandId, idempotencyKey: `${migrationRunId}:${fact.logicalKey}`, requestHash: `sha256:${stableHash(fact.logicalKey)}`, schemaVersion: SCHEMA_VERSION, actor: { type: 'migration', migrationRunId }, occurredAt: fact.occurredAt, recordedAt, }; return fact.build(base); }); } interface TournamentCodeAssignmentTarget { series: SeriesDefinition; slot: SeriesDefinition['gameSlots'][number]; } function resolveTournamentCodeAssignmentTarget(params: { input: LegacyMatchInput; code: LegacyTournamentCodeInput; tournamentCodeId: string; gameFact: MigrationGameAcceptedFact | undefined; graph: SeriesDefinition[]; teamIds: ReadonlyMap; }): TournamentCodeAssignmentTarget | { issue: CompetitionMigrationIssue } { let target: TournamentCodeAssignmentTarget | undefined; if (params.gameFact) { const series = params.graph.find( (candidate) => candidate.id === params.gameFact!.seriesId, ); const slot = series?.gameSlots.find( (candidate) => candidate.id === params.gameFact!.gameSlotId, ); if (!series || !slot) { return assignmentMappingNotFound( params, 'Accepted TournamentCode evidence does not target a stable GameSlot.', ); } target = { series, slot }; } if (params.code.gameNumber !== undefined) { const numbered = resolveGlobalGameNumberTarget(params); if ('issue' in numbered) return numbered; if (target && !sameAssignmentTarget(target, numbered)) { return assignmentConflict( params, [target, numbered], 'TournamentCode Riot evidence conflicts with its global game number.', ); } target = numbered; } if (params.code.bracketMatchId) { const bracketSeries = params.graph.find( (candidate) => candidate.code === params.code.bracketMatchId, ); if (!bracketSeries) { return assignmentMappingNotFound( params, 'The TournamentCode bracket identity has no stable Series.', ); } if (target && target.series.id !== bracketSeries.id) { return assignmentConflict( params, [target], 'TournamentCode bracket identity conflicts with its exact GameSlot evidence.', ); } if (!target) { if (bracketSeries.gameSlots.length !== 1) { return assignmentMappingNotFound( params, 'A multi-slot TournamentCode Series needs exact GameSlot evidence.', ); } target = { series: bracketSeries, slot: bracketSeries.gameSlots[0] }; } } return ( target ?? assignmentMappingNotFound( params, 'A non-available TournamentCode cannot be mapped to a stable GameSlot.', ) ); } function resolveGlobalGameNumberTarget(params: { input: LegacyMatchInput; code: LegacyTournamentCodeInput; tournamentCodeId: string; graph: SeriesDefinition[]; teamIds: ReadonlyMap; }): TournamentCodeAssignmentTarget | { issue: CompetitionMigrationIssue } { const gameNumber = positiveInteger(params.code.gameNumber); if (!gameNumber) { return assignmentMappingNotFound( params, 'TournamentCode gameNumber must be a positive integer.', ); } const bracketMatches = params.input.doubleElimination?.bracketMatches ?? []; if ( params.input.gameMode === 'double-elimination' && bracketMatches.length > 0 ) { const target = resolvePersistedDoubleEliminationGameNumberTarget( params.input, params.graph, gameNumber, ); return 'error' in target ? assignmentMappingNotFound(params, target.error) : target; } const schedule = params.input.gameSchedule ?? []; if (schedule.length > 0) { const matches = schedule.filter( (assignment) => assignment.gameNumber === gameNumber, ); if (matches.length !== 1) { return assignmentMappingNotFound( params, matches.length > 1 ? 'TournamentCode gameNumber maps to multiple persisted schedule entries.' : 'TournamentCode gameNumber is absent from the persisted schedule.', ); } const [assignment] = matches; const teamAId = params.teamIds.get(assignment.teamAIndex); const teamBId = params.teamIds.get(assignment.teamBIndex); if (!teamAId || !teamBId || teamAId === teamBId) { return assignmentMappingNotFound( params, 'TournamentCode schedule entry references an invalid team set.', ); } const candidates = params.graph.filter((series) => staticSeriesHasTeamSet(series, teamAId, teamBId), ); if (candidates.length !== 1) { return assignmentMappingNotFound( params, 'TournamentCode schedule entry does not identify one stable Series.', ); } const samePair = schedule .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 === gameNumber, ); const series = candidates[0]; const slot = series.gameSlots.find( (candidate) => candidate.ordinal === ordinal + 1, ); if (!slot) { return assignmentMappingNotFound( params, 'TournamentCode schedule ordinal has no stable GameSlot.', ); } return { series, slot }; } const flattened = params.graph.flatMap((series) => series.gameSlots.map((slot) => ({ series, slot })), ); const target = flattened[gameNumber - 1]; return ( target ?? assignmentMappingNotFound( params, 'TournamentCode gameNumber is outside the canonical Competition topology.', ) ); } 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; tournamentCodeId: string; }, message: string, ): { issue: CompetitionMigrationIssue } { return { issue: issue('TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', message, { tournamentCodeId: params.tournamentCodeId, bracketMatchId: params.code.bracketMatchId, gameNumber: params.code.gameNumber, }), }; } function assignmentConflict( params: { code: LegacyTournamentCodeInput; tournamentCodeId: string; }, targets: TournamentCodeAssignmentTarget[], message: string, ): { issue: CompetitionMigrationIssue } { return { issue: issue('TOURNAMENT_CODE_ASSIGNMENT_CONFLICT', message, { tournamentCodeId: params.tournamentCodeId, bracketMatchId: params.code.bracketMatchId, gameNumber: params.code.gameNumber, targets: targets.map(({ series, slot }) => ({ seriesId: series.id, gameSlotId: slot.id, })), }), }; } function sameAssignmentTarget( left: TournamentCodeAssignmentTarget, right: TournamentCodeAssignmentTarget, ): boolean { return left.series.id === right.series.id && left.slot.id === right.slot.id; } function unorderedNumberPair(left: number, right: number): string { return left < right ? `${left}:${right}` : `${right}:${left}`; } function buildAssignments( input: LegacyMatchInput, competitionId: string, facts: CompetitionMigrationFact[], graph: SeriesDefinition[], teamIds: ReadonlyMap, reasons: CompetitionMigrationIssue[], warnings: CompetitionMigrationIssue[], ): CompetitionMigrationAssignment[] { const result: CompetitionMigrationAssignment[] = []; for (const code of input.tournamentCodes ?? []) { if ( code.state !== 'reserved' && code.state !== 'used' && code.state !== 'released' && code.state !== 'voided' ) { continue; } const tournamentCodeId = opaqueString(code._id); const riotMatchId = code.state === 'used' || code.state === 'voided' ? code.riotMatchId : undefined; const gameFact = facts.find( (fact): fact is MigrationGameAcceptedFact => fact.type === 'game-accepted' && riotMatchId !== undefined && ((fact.evidence.type === 'riot' && fact.evidence.riotMatchId === riotMatchId) || (fact.evidence.type === 'legacy' && fact.evidence.legacyReference.endsWith(`:${riotMatchId}`))), ); const resolution = resolveTournamentCodeAssignmentTarget({ input, code, tournamentCodeId, gameFact, graph, teamIds, }); if ('issue' in resolution) { reasons.push(resolution.issue); continue; } const { series, slot } = resolution; 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 must target an accepted legacy game.', { tournamentCodeId, gameSlotId: slot.id }, ), ); continue; } if ( riotMatchId && acceptedGame && !acceptedGameHasRiotIdentity(acceptedGame, 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, }, ), ); continue; } const legacyGame = riotMatchId ? input.result?.games.find( (game) => game.riotMatchId?.trim() === riotMatchId, ) : undefined; const timestamps = tournamentCodeTimestamps( input, code, tournamentCodeId, reasons, warnings, riotMatchId && acceptedGame?.evidence.type === 'riot' && acceptedGame.evidence.riotMatchId === riotMatchId && legacyGame ? { riotMatchId, gameSlotId: slot.id, factRecordedAt: acceptedGame.recordedAt, legacyOccurrences: legacyUsedOccurrenceEvidence(legacyGame), } : undefined, ); if (!timestamps) continue; result.push({ id: stableId( competitionId, 'tournament-code-assignment', tournamentCodeId, ), competitionId, seriesId: series.id, gameSlotId: slot.id, tournamentCodeId, state: code.state, ...timestamps, ...(riotMatchId ? { riotMatchId } : {}), commandId: stableId( competitionId, 'migration-code-command', tournamentCodeId, ), }); } const activeSlots = new Set(); const activeCodes = new Set(); for (const assignment of result) { if (assignment.state !== 'reserved' && assignment.state !== 'used') continue; if ( activeSlots.has(assignment.gameSlotId) || activeCodes.has(assignment.tournamentCodeId) ) { reasons.push( issue( 'AMBIGUOUS_TOURNAMENT_CODE_ASSIGNMENT', 'Active TournamentCode assignments collide on identity or GameSlot.', { tournamentCodeId: assignment.tournamentCodeId, gameSlotId: assignment.gameSlotId, }, ), ); } activeSlots.add(assignment.gameSlotId); activeCodes.add(assignment.tournamentCodeId); } 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[], warnings: CompetitionMigrationIssue[], corroboratedRiotTransition?: { riotMatchId: string; gameSlotId: string; factRecordedAt: string; legacyOccurrences: LegacyUsedOccurrenceEvidence[]; }, ): Pick< CompetitionMigrationAssignment, 'reservedAt' | 'usedAt' | 'releasedAt' | 'voidedAt' > | null { const raw = { createdAt: optionalDate(code.createdAt), reservedAt: optionalDate(code.reservedAt), usedAt: code.state === 'used' || code.state === 'voided' ? optionalDate(code.usedAt) : undefined, releasedAt: code.state === 'released' ? optionalDate(code.releasedAt) : undefined, voidedAt: code.state === 'voided' ? optionalDate(code.voidedAt) : undefined, updatedAt: code.state === 'voided' && code.voidedAt == null ? optionalDate(code.updatedAt) : undefined, }; if (Object.values(raw).some((value) => value === null)) { reasons.push( issue( 'INVALID_TOURNAMENT_CODE_TIMELINE', 'TournamentCode lifecycle contains an invalid timestamp.', { tournamentCodeId }, ), ); return null; } // TournamentCode pool documents can be restored and reserved again while // terminal timestamps from a previous binding remain on the document. A // Competition assignment represents only the current binding, so preserve // the lifecycle fields that are reachable for its current state. const reservedAt = raw.reservedAt ?? raw.createdAt ?? (code.state === 'used' || code.state === 'voided' ? raw.usedAt : undefined) ?? (code.state === 'released' ? raw.releasedAt : undefined) ?? (code.state === 'voided' ? raw.voidedAt : undefined) ?? sourceFallbackDate(input); let usedAt = code.state === 'used' || code.state === 'voided' ? (raw.usedAt ?? undefined) : undefined; const releasedAt = code.state === 'released' ? (raw.releasedAt ?? undefined) : undefined; const voidedAt = code.state === 'voided' ? (raw.voidedAt ?? raw.updatedAt ?? usedAt ?? reservedAt) : undefined; // Legacy result collection and repair paths recorded usedAt from Riot game // occurrence, while updatedAt captured the persisted state transition. Keep // target lifecycle meaning uniform by using that transition only when an // archived Riot fact, exact identity, and source occurrence all corroborate. const occurrenceEvidence = corroboratedRiotTransition?.legacyOccurrences.find( (candidate) => candidate.at === raw.usedAt, ); if ( code.state === 'used' && raw.reservedAt && raw.usedAt && occurrenceEvidence && corroboratedRiotTransition ) { const persistedTransitionAt = optionalDate(code.updatedAt); if ( !persistedTransitionAt || persistedTransitionAt < reservedAt || persistedTransitionAt < raw.usedAt || persistedTransitionAt > corroboratedRiotTransition.factRecordedAt ) { reasons.push( issue( 'INVALID_TOURNAMENT_CODE_TIMELINE', 'Legacy used TournamentCode has no valid persisted transition time.', { tournamentCodeId, state: code.state, reservedAt, originalUsedAt: raw.usedAt, sourceUpdatedAt: persistedTransitionAt, factRecordedAt: corroboratedRiotTransition.factRecordedAt, }, ), ); return null; } const originalUsedAt = raw.usedAt; usedAt = persistedTransitionAt; if (originalUsedAt !== usedAt) { warnings.push( issue( 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', 'Legacy used TournamentCode usedAt represented Riot game time and was normalized to its persisted transition time.', { tournamentCodeId, originalReservedAt: reservedAt, originalUsedAt, sourceUpdatedAt: persistedTransitionAt, normalizedUsedAt: usedAt, factRecordedAt: corroboratedRiotTransition.factRecordedAt, legacyOccurrenceSource: occurrenceEvidence.source, riotMatchId: corroboratedRiotTransition.riotMatchId, gameSlotId: corroboratedRiotTransition.gameSlotId, strategy: 'use-persisted-transition-time', }, ), ); } } 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, state: code.state, reservedAt, ...(usedAt ? { usedAt } : {}), ...(releasedAt ? { releasedAt } : {}), ...(voidedAt ? { voidedAt } : {}), }, ), ); 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, )?.completedAt; return normalizeDate(completedAt, sourceFallbackDate(input)); } function gameOccurrence( game: LegacyGameInput, input: LegacyMatchInput, ): string { if (typeof game.gameCreation === 'number') { const milliseconds = game.gameCreation < 10_000_000_000 ? game.gameCreation * 1000 : game.gameCreation; return normalizeDate(milliseconds, sourceFallbackDate(input)); } return normalizeDate(game.gameCreation, sourceFallbackDate(input)); } function legacyUsedOccurrenceEvidence( game: LegacyGameInput, ): LegacyUsedOccurrenceEvidence[] { const candidates: LegacyUsedOccurrenceEvidence[] = []; const archivedGameEnd = optionalRiotDate(game.riotGameEndedAt); if (archivedGameEnd && game.riotGameEndedAtSource) { candidates.push({ at: archivedGameEnd, source: game.riotGameEndedAtSource === 'gameEndTimestamp' ? 'riot-archive-gameEndTimestamp' : 'riot-archive-gameCreation', }); } const gameCreation = optionalRiotDate(game.gameCreation); if ( gameCreation && typeof game.gameDuration === 'number' && Number.isFinite(game.gameDuration) && game.gameDuration >= 0 ) { const computedGameEnd = optionalDate( Date.parse(gameCreation) + game.gameDuration * 1000, ); if (computedGameEnd) { candidates.push({ at: computedGameEnd, source: 'legacy-gameCreation-plus-duration', }); } } return candidates.filter( (candidate, index) => candidates.findIndex((other) => other.at === candidate.at) === index, ); } function optionalRiotDate(value: unknown): string | null | undefined { if (typeof value !== 'number') return optionalDate(value); return optionalDate(value < 10_000_000_000 ? value * 1000 : value); } function compareLegacyGames( left: Omit, right: Omit, ) { return ( gameOccurrence(left.legacy, { createdAt: EPOCH, } as LegacyMatchInput).localeCompare( gameOccurrence(right.legacy, { createdAt: EPOCH } as LegacyMatchInput), ) || left.legacy.gameNumber - right.legacy.gameNumber || (left.legacy.riotMatchId ?? '').localeCompare( right.legacy.riotMatchId ?? '', ) ); } function sourceFallbackDate(input: LegacyMatchInput): string { return normalizeDate(input.updatedAt, normalizeDate(input.createdAt, EPOCH)); } function normalizeDate(value: unknown, fallback: string): string { if (value === undefined || value === null || value === '') return fallback; const date = value instanceof Date ? value : new Date(value as string | number); return Number.isNaN(date.getTime()) ? fallback : date.toISOString(); } function stableId(...parts: Array): string { return createHash('sha256') .update(JSON.stringify(parts)) .digest('hex') .slice(0, 24); } function stableHash(value: string): string { return createHash('sha256').update(value).digest('hex'); } function canonicalize(value: unknown): string { if (Array.isArray(value)) { return `[${value.map(canonicalize).join(',')}]`; } if (value instanceof Date) return JSON.stringify(value.toISOString()); if (value && typeof value === 'object') { const record = value as Record; return `{${Object.keys(record) .sort() .map((key) => `${JSON.stringify(key)}:${canonicalize(record[key])}`) .join(',')}}`; } return JSON.stringify(value); } function opaqueString(value: unknown): string { if (typeof value === 'string') return value.trim(); if (hasHexString(value)) { const rendered = value.toHexString(); if (typeof rendered === 'string') return rendered.trim(); } if (typeof value === 'number' || typeof value === 'boolean') { return String(value); } if (value === undefined || value === null) return ''; return ''; } function hasHexString(value: unknown): value is { toHexString(): unknown } { return ( value !== null && typeof value === 'object' && 'toHexString' in value && typeof value.toHexString === 'function' ); } function positiveInteger(value: unknown): number | undefined { return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined; } function numericValue(value: unknown): number { return typeof value === 'number' && Number.isFinite(value) ? value : 0; } function issue( code: string, message: string, details?: Record, ): CompetitionMigrationIssue { return { code, message, ...(details && Object.keys(details).length > 0 ? { details } : {}), }; } function quarantined( matchId: string, reasons: CompetitionMigrationIssue[], warnings: CompetitionMigrationIssue[], ): QuarantinedCompetitionMigrationPlan { return { status: 'quarantined', matchId, reasons: sortedIssues(reasons), warnings: sortedIssues(warnings), }; } function sortedIssues( issues: CompetitionMigrationIssue[], ): CompetitionMigrationIssue[] { return [...issues].sort( (left, right) => left.code.localeCompare(right.code) || canonicalize(left.details).localeCompare(canonicalize(right.details)), ); } function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } function errorCodeDetails(error: unknown): Record | undefined { if (!error || typeof error !== 'object' || !('code' in error)) return undefined; return { projectorCode: String((error as { code: unknown }).code) }; }