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