fix: keep best-of-three grand finals open for results

Allow a separate grand final format and repair prematurely completed finals without dropping accepted games. Replay the correction record alongside subsequent results.
This commit is contained in:
dahyeon committed 2026-11-10 18:49:26 +09:00
1 parent 38a89b5374
commit 7e0cd7cb19
21 files changed
+914 -23

No files matched your search

+1
View File
@@ -9,6 +9,7 @@
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts",
"competition:repair-grand-final": "ts-node src/modules/global/database/migrations/repair-grand-final-bo3.ts",
"auction:indexes": "ts-node src/modules/global/database/migrations/run-auction-cancellation-index.ts",
"seed:dev": "ts-node src/seed.ts",
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
@@ -5,6 +5,7 @@ import {
CompetitionBootstrapService,
type CompetitionBootstrapMatch,
} from './competition-bootstrap.service';
import type { SeriesDefinition } from './domain/series-graph';
describe('CompetitionBootstrapService', () => {
it('creates a deterministic paired-Series Competition and immutable snapshots', async () => {
@@ -210,6 +211,40 @@ describe('CompetitionBootstrapService', () => {
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('gives a configured BO3 grand final three slots without changing the other stage rules', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(harness.connectionService);
const match = matchSnapshot({
gameMode: 'double-elimination',
teamCount: 4,
gameCount: 5,
});
match.doubleElimination = {
teamCount: 4,
resetFinalEnabled: true,
grandFinalGameCount: 3,
seeds: [1, 2, 3, 4].map((teamIndex) => ({
seedNumber: teamIndex,
teamIndex,
})),
};
await service.bootstrap(match);
const { format, seriesGraph } = harness.insertedPayloads[0];
expect(format).toMatchObject({
rules: {
upper: { maxGames: 5, winsRequired: 3 },
lower: { maxGames: 1, winsRequired: 1 },
grandFinal: { maxGames: 3, winsRequired: 2 },
resetFinal: { maxGames: 1, winsRequired: 1 },
},
});
expect(
seriesGraph.find(({ code }) => code === 'GF')?.gameSlots,
).toHaveLength(3);
});
it('rejects incomplete and duplicate team assignments before opening a transaction', async () => {
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
[
@@ -451,7 +486,7 @@ interface InsertPayload {
legacyTeamIndex: number;
seedNumber: number;
}>;
seriesGraph: Array<{ code?: string; rule: unknown }>;
seriesGraph: SeriesDefinition[];
[key: string]: any;
}
@@ -41,6 +41,7 @@ export interface CompetitionBootstrapMatch {
doubleElimination?: {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
grandFinalGameCount?: 1 | 3 | 5;
seeds: Array<{ seedNumber: number; teamIndex: number }>;
};
}
@@ -514,6 +515,8 @@ function mapMatchFormat(
winsRequired: 1,
maxGames: 1,
};
const grandFinalGameCount =
match.doubleElimination?.grandFinalGameCount ?? 1;
return {
type: 'double-elimination',
teamCount: teams.length,
@@ -525,7 +528,11 @@ function mapMatchFormat(
maxGames: match.gameCount,
},
lower: { ...bestOfOne },
grandFinal: { ...bestOfOne },
grandFinal: {
type: 'first-to',
winsRequired: Math.floor(grandFinalGameCount / 2) + 1,
maxGames: grandFinalGameCount,
},
resetFinal: { ...bestOfOne },
},
};
@@ -821,7 +821,7 @@ function buildOutbox(
};
}
function factForProjection(
export function factForProjection(
fact: Readonly<Record<string, unknown>>,
): Readonly<Record<string, unknown>> {
const plain = toPlain(fact) as Readonly<Record<string, unknown>>;
@@ -13,6 +13,7 @@ export const COMPETITION_FACT_TYPES = [
'game-voided',
'series-adjudicated',
'adjudication-reversed',
'grand-final-rule-corrected',
] as const;
export type CompetitionFactType = (typeof COMPETITION_FACT_TYPES)[number];
@@ -200,6 +201,7 @@ export interface CompetitionFact {
adjudicationFactId?: mongoose.Types.ObjectId;
decision?: Record<string, unknown>;
reason?: string;
ruleCorrection?: { previousMaxGames: 1; nextMaxGames: 3 };
createdAt: Date;
updatedAt: Date;
}
@@ -339,6 +341,7 @@ export const CompetitionFactSchema = new Schema<CompetitionFact>(
adjudicationFactId: { type: Schema.Types.ObjectId },
decision: { type: Schema.Types.Mixed },
reason: { type: String },
ruleCorrection: { type: Schema.Types.Mixed },
},
{ timestamps: true, collection: 'competition_fact' },
);
@@ -131,7 +131,12 @@ export interface CompetitionProjection {
export function projectCompetition(
input: ProjectCompetitionInput,
): CompetitionProjection {
assertPrimaryFactTargetsGraph(input.seriesGraph, input.facts);
// The repair commits the corrected graph and its audit fact together. The
// audit fact occupies a revision but is not a game or adjudication.
const resultFacts = input.facts.filter(
(fact) => !isRecord(fact) || fact.type !== 'grand-final-rule-corrected',
);
assertPrimaryFactTargetsGraph(input.seriesGraph, resultFacts);
const teamBySeed = new Map<number, string>();
const knownTeams = new Set<string>();
for (const team of input.teams) {
@@ -169,7 +174,7 @@ export function projectCompetition(
teamBySeed,
projectedById,
),
facts: input.facts,
facts: resultFacts,
active: false,
}),
);
@@ -188,7 +193,7 @@ export function projectCompetition(
projectSeries({
definition: asProjectorDefinition(definition),
participants,
facts: input.facts,
facts: resultFacts,
}),
);
remaining.delete(seriesId);
@@ -211,7 +216,7 @@ export function projectCompetition(
projectSeries({
definition: asProjectorDefinition(definition),
participants,
facts: input.facts,
facts: resultFacts,
...(definition.activation ? { active: false } : {}),
}),
);
@@ -221,7 +226,7 @@ export function projectCompetition(
const gameProjection = projectGamesAndSlots(
input.seriesGraph,
series,
input.facts,
resultFacts,
);
const common = {
competitionId: input.competitionId,
@@ -88,6 +88,7 @@ export interface DoubleEliminationEvent {
export interface DoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
grandFinalGameCount?: 1 | 3 | 5;
resetFinalCreated: boolean;
seeds: DoubleEliminationSeed[];
bracketMatches: DoubleEliminationBracketMatch[];
@@ -98,6 +99,7 @@ export interface DoubleEliminationBracket {
export interface BuildDoubleEliminationBracketOptions {
resetFinalEnabled: boolean;
winnerBracketGameCount?: number;
grandFinalGameCount?: 1 | 3 | 5;
}
export interface DoubleEliminationSeriesRule {
@@ -146,6 +148,9 @@ export function buildDoubleEliminationBracket(
const bracket: DoubleEliminationBracket = {
teamCount: seededTeamIndexes.length,
resetFinalEnabled: options.resetFinalEnabled,
...(options.grandFinalGameCount === undefined
? {}
: { grandFinalGameCount: options.grandFinalGameCount }),
resetFinalCreated: false,
seeds,
bracketMatches:
@@ -171,11 +176,17 @@ export function resolveDoubleEliminationSeriesRule(
bracketMatchId: string;
roundNumber: number;
},
options: { winnerBracketGameCount?: number } = {},
options: Pick<
BuildDoubleEliminationBracketOptions,
'winnerBracketGameCount' | 'grandFinalGameCount'
> = {},
): DoubleEliminationSeriesRule {
if (params.bracketSide === 'winner') {
return seriesRule(options.winnerBracketGameCount ?? 3);
}
if (params.bracketSide === 'grand-final') {
return seriesRule(options.grandFinalGameCount ?? 1);
}
return seriesRule(1);
}
@@ -431,6 +442,7 @@ function rebuildWithSeeds(
): DoubleEliminationBracket {
const next = buildDoubleEliminationBracket(teamIndexes, {
resetFinalEnabled: bracket.resetFinalEnabled,
grandFinalGameCount: bracket.grandFinalGameCount,
});
next.events = [
...bracket.events,
@@ -0,0 +1,293 @@
import mongoose from 'mongoose';
import { projectCompetition } from '../../../competition/domain/competition-projector';
import { generateSeriesGraph } from '../../../competition/domain/series-graph';
import {
parseGrandFinalRepairOptions,
planGrandFinalBo3Repair,
repairGrandFinalBo3,
} from './repair-grand-final-bo3';
describe('grand final BO3 repair', () => {
it.each([false, true])(
'keeps game 28 and finishes only after two wins (split: %s)',
(split) => {
const input = finishedTournament();
const plan = planGrandFinalBo3Repair(input);
expect(plan.before.phase).toBe('completed');
expect(plan.preservedGame).toBe(28);
expect(plan.newGameNumbers).toEqual([29, 30]);
expect(plan.projection.games).toEqual(plan.before.games);
expect(plan.projection).toMatchObject({
phase: 'running',
placements: [],
});
expect(plan.projection).not.toHaveProperty('outcome');
expect(
plan.projection.series.find(
({ seriesId }) => seriesId === plan.seriesId,
),
).toMatchObject({
status: 'in-progress',
entries: [
{ slot: 'A', gameWins: 1 },
{ slot: 'B', gameWins: 0 },
],
});
const facts = [
...input.facts,
{
id: 'rule-audit',
type: 'grand-final-rule-corrected',
seriesId: plan.seriesId,
revision: plan.projection.sourceRevision,
ordinalWithinRevision: 1,
},
];
const replay = () =>
projectCompetition({
...input,
facts,
revision: facts.length,
format: plan.format,
seriesGraph: plan.seriesGraph,
});
expect(replay()).toEqual(plan.projection);
const second = replay().gameSlots.find(
({ displayNumber }) => displayNumber === 29,
)!;
facts.push(acceptedGame(second, facts.length + 1, split ? 'B' : 'A'));
if (split) {
expect(replay().phase).toBe('running');
const third = replay().gameSlots.find(
({ displayNumber }) => displayNumber === 30,
)!;
expect(third.status).toBe('ready');
facts.push(acceptedGame(third, facts.length + 1, 'A'));
}
const completed = replay();
expect(completed.phase).toBe('completed');
expect(
completed.gameSlots.find(({ displayNumber }) => displayNumber === 30)
?.status,
).toBe(split ? 'completed' : 'inactive');
expect(completed.games.at(-1)?.displayNumber).toBe(split ? 30 : 29);
},
);
it('refuses to reopen a bracket that enables a reset final', () => {
const input = finishedTournament();
expect(() =>
planGrandFinalBo3Repair({
...input,
format: { ...input.format, resetFinalEnabled: true },
}),
).toThrow('no reset or later series');
});
it('requires a target and a reviewed revision before applying', () => {
const target = ['--match-id', '000000000000000000000001', '--env', 'prod'];
expect(parseGrandFinalRepairOptions(target)).toMatchObject({
apply: false,
});
expect(() => parseGrandFinalRepairOptions(['--apply', ...target])).toThrow(
'--expected-revision',
);
expect(
parseGrandFinalRepairOptions([
'--apply',
...target,
'--expected-revision',
'23',
]),
).toMatchObject({ apply: true, expectedRevision: 23 });
});
it('previews without writes and applies the graph, match status and audit in one transaction', async () => {
const input = finishedTournament();
const competitionId = new mongoose.Types.ObjectId(input.competitionId);
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
competitionId,
communityId,
gameMode: 'double-elimination',
status: 'finished',
teamBuiltAt: new Date(),
doubleElimination: { resetFinalEnabled: false },
resultPollState: { state: 'complete' },
};
const competition = {
...input,
_id: competitionId,
schemaVersion: 1,
phase: 'completed',
teams: input.teams.map((team) => ({
...team,
teamId: new mongoose.Types.ObjectId(team.teamId),
})),
projection: projectCompetition(input),
};
const query = (value: unknown) => ({
session: jest.fn().mockReturnThis(),
lean: jest.fn().mockReturnThis(),
sort: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue(value),
});
const update = () => jest.fn(() => query({ matchedCount: 1 }));
const models = {
match: { findById: jest.fn(() => query(match)), updateOne: update() },
competition: {
findOne: jest.fn(() => query(competition)),
updateOne: update(),
},
competitionFact: {
find: jest.fn(() => query(input.facts)),
insertMany: jest.fn(),
},
competitionOutbox: { insertMany: jest.fn() },
};
const session = {
withTransaction: jest.fn((run: () => unknown) => run()),
endSession: jest.fn(),
};
const connections = {
getModel: jest.fn((name: keyof typeof models) => models[name]),
createSession: jest.fn().mockResolvedValue(session),
} as never;
const options = { matchId, nodeEnv: 'prod', apply: false };
const preview = await repairGrandFinalBo3(connections, options);
expect(preview).toMatchObject({
mode: 'dry-run',
preservedGame: 28,
newGameNumbers: [29, 30],
});
expect(models.match.updateOne).not.toHaveBeenCalled();
expect(models.competition.updateOne).not.toHaveBeenCalled();
expect(models.competitionFact.insertMany).not.toHaveBeenCalled();
expect(models.competitionOutbox.insertMany).not.toHaveBeenCalled();
await expect(
repairGrandFinalBo3(connections, {
...options,
apply: true,
expectedRevision: preview.revisionBefore,
}),
).resolves.toMatchObject({
mode: 'applied',
phase: 'completed -> running',
});
expect(session.withTransaction).toHaveBeenCalledTimes(1);
expect(models.match.updateOne).toHaveBeenCalledWith(
{ _id: matchId, status: 'finished', competitionId },
{
$set: expect.objectContaining({
status: 'in-progress',
'resultPollState.state': 'polling',
}),
},
{ session, runValidators: true },
);
expect(models.competition.updateOne).toHaveBeenCalledWith(
{ _id: competitionId, revision: preview.revisionBefore },
{
$set: expect.objectContaining({
phase: 'running',
revision: preview.revisionAfter,
}),
},
{ session, runValidators: true },
);
expect(models.competitionFact.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
type: 'grand-final-rule-corrected',
revision: preview.revisionAfter,
}),
],
{ session },
);
expect(models.competitionOutbox.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
type: 'competition.projection-updated',
revision: preview.revisionAfter,
}),
],
{ session },
);
});
});
function finishedTournament() {
const competitionId = '000000000000000000000001';
const teams = Array.from({ length: 8 }, (_, index) => ({
teamId: (index + 1).toString(16).padStart(24, '0'),
displayOrder: index + 1,
seedNumber: index + 1,
}));
const bo1 = { type: 'first-to', maxGames: 1, winsRequired: 1 } as const;
const format = {
type: 'double-elimination' as const,
teamCount: 8 as const,
resetFinalEnabled: false,
rules: {
upper: { ...bo1, maxGames: 3, winsRequired: 2 },
lower: bo1,
grandFinal: bo1,
resetFinal: bo1,
},
};
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
const facts: Record<string, unknown>[] = [];
const input = {
competitionId,
teams,
format,
seriesGraph,
facts,
projectorVersion: 1,
revision: 0,
};
for (let index = 0; index < 28; index += 1) {
const slot = projectCompetition(input).gameSlots.find(
({ status }) => status === 'ready',
);
if (!slot) break;
facts.push(acceptedGame(slot, index + 1, 'A'));
input.revision += 1;
}
return input;
}
function acceptedGame(
slot: ReturnType<typeof projectCompetition>['gameSlots'][number],
revision: number,
winner: 'A' | 'B',
): Record<string, unknown> {
const [a, b] = slot.entries;
const recordedAt = new Date(Date.UTC(2026, 6, 26, 0, revision)).toISOString();
return {
id: `fact-${revision}`,
type: 'game-accepted',
revision,
ordinalWithinRevision: 1,
gameId: `game-${revision}`,
seriesId: slot.seriesId,
gameSlotId: slot.id,
ordinal: slot.ordinal,
recordedAt,
occurredAt: recordedAt,
evidence: { type: 'riot', riotMatchId: `KR_${revision}` },
mapping: {
blueTeamId: a.teamId,
redTeamId: b.teamId,
winnerTeamId: winner === 'A' ? a.teamId : b.teamId,
participantAssignments: [],
},
};
}
@@ -0,0 +1,410 @@
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import mongoose from 'mongoose';
import { createHash } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { factForProjection } from '../../../competition/competition-command.service';
import { projectCompetition } from '../../../competition/domain/competition-projector';
import {
generateSeriesGraph,
type CompetitionGraphFormat,
type CompetitionGraphTeam,
type SeriesDefinition,
} from '../../../competition/domain/series-graph';
import { SecretService } from '../../secret/secret.service';
import { ConnectionService, resolveMongoDbName } from '../connection.service';
const CORRECTION_TYPE = 'grand-final-rule-corrected' as const;
const BO3 = { type: 'first-to', winsRequired: 2, maxGames: 3 } as const;
interface RepairInput {
competitionId: string;
revision: number;
projectorVersion: number;
teams: readonly CompetitionGraphTeam[];
format: CompetitionGraphFormat;
seriesGraph: readonly SeriesDefinition[];
facts: readonly Record<string, unknown>[];
}
export function planGrandFinalBo3Repair(input: RepairInput) {
const { format, seriesGraph, facts } = input;
const final = seriesGraph.find(({ stage }) => stage.type === 'grand-final');
if (
format.type !== 'double-elimination' ||
format.resetFinalEnabled ||
format.rules.grandFinal.type !== 'first-to' ||
format.rules.grandFinal.maxGames !== 1 ||
format.rules.grandFinal.winsRequired !== 1 ||
!final ||
!isDeepStrictEqual(final.rule, format.rules.grandFinal) ||
final.gameSlots.length !== 1 ||
seriesGraph.some(
({ stage }) => stage.displayOrder > final.stage.displayOrder,
)
) {
throw new Error(
'Expected a BO1 grand final with no reset or later series.',
);
}
const before = projectCompetition(input);
const previousFinal = before.series.find(
({ seriesId }) => seriesId === final.id,
);
const finalGames = before.games.filter(
({ seriesId }) => seriesId === final.id,
);
const firstGame = finalGames[0];
if (
before.phase !== 'completed' ||
previousFinal?.status !== 'completed' ||
previousFinal.outcome.type !== 'played' ||
finalGames.length !== 1 ||
firstGame.ordinal !== 1 ||
firstGame.evidence.type !== 'riot' ||
facts.filter((fact) => fact.seriesId === final.id).length !== 1
) {
throw new Error(
'Expected exactly one Riot result and no other final facts.',
);
}
const correctedFormat = {
...format,
rules: { ...format.rules, grandFinal: BO3 },
};
const generatedFinal = generateSeriesGraph({
competitionId: input.competitionId,
teams: input.teams,
format: correctedFormat,
}).find(({ stage }) => stage.type === 'grand-final');
if (
generatedFinal?.id !== final.id ||
!isDeepStrictEqual(generatedFinal.gameSlots[0], final.gameSlots[0])
) {
throw new Error(
'The existing grand final does not match its stable slot identity.',
);
}
const correctedGraph = seriesGraph.map((series) =>
series.id === final.id
? { ...series, rule: BO3, gameSlots: generatedFinal.gameSlots }
: series,
);
const projection = projectCompetition({
...input,
revision: input.revision + 1,
format: correctedFormat,
seriesGraph: correctedGraph,
});
const readySlots = projection.gameSlots.filter(
({ status }) => status === 'ready',
);
if (
projection.phase !== 'running' ||
!isDeepStrictEqual(projection.games, before.games) ||
readySlots.length !== 2 ||
readySlots.some(
(slot, index) =>
slot.seriesId !== final.id ||
slot.ordinal !== index + 2 ||
slot.displayNumber !== firstGame.displayNumber + index + 1,
) ||
!isDeepStrictEqual(
projection.series.filter(({ seriesId }) => seriesId !== final.id),
before.series.filter(({ seriesId }) => seriesId !== final.id),
)
) {
throw new Error(
'Repair would change existing results or fail to reopen the final.',
);
}
return {
before,
format: correctedFormat,
seriesGraph: correctedGraph,
projection,
seriesId: final.id,
preservedGame: firstGame.displayNumber,
newGameNumbers: readySlots.map(({ displayNumber }) => displayNumber),
};
}
interface CliOptions {
matchId: mongoose.Types.ObjectId;
nodeEnv: string;
expectedRevision?: number;
apply: boolean;
}
export function parseGrandFinalRepairOptions(argv: string[]): CliOptions {
let matchId: mongoose.Types.ObjectId | undefined;
let nodeEnv = 'dev';
let expectedRevision: number | undefined;
let apply = false;
for (let index = 0; index < argv.length; index += 1) {
switch (argv[index]) {
case '--':
break;
case '--apply':
apply = true;
break;
case '--match-id': {
const value = argv[++index];
if (!/^[a-f\d]{24}$/i.test(value ?? '')) {
throw new Error('--match-id must be a 24-character ObjectId.');
}
matchId = new mongoose.Types.ObjectId(value);
break;
}
case '--env':
nodeEnv = argv[++index];
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
break;
case '--expected-revision': {
const value = argv[++index];
expectedRevision = Number(value);
if (
!/^\d+$/.test(value ?? '') ||
!Number.isSafeInteger(expectedRevision)
) {
throw new Error('--expected-revision must be a nonnegative integer.');
}
break;
}
default:
throw new Error(`Unknown argument: ${argv[index]}`);
}
}
if (!matchId || (apply && expectedRevision === undefined)) {
throw new Error(
'--match-id is required; --apply also requires --expected-revision from the dry run.',
);
}
return { matchId, nodeEnv, expectedRevision, apply };
}
export async function repairGrandFinalBo3(
connectionService: ConnectionService,
options: CliOptions,
) {
if (options.apply && options.expectedRevision === undefined) {
throw new Error('An expected revision is required to apply the repair.');
}
const [Match, Competition, Fact, Outbox] = await Promise.all([
connectionService.getModel('match'),
connectionService.getModel('competition'),
connectionService.getModel('competitionFact'),
connectionService.getModel('competitionOutbox'),
]);
async function run(session: mongoose.ClientSession | null) {
const match = await Match.findById(options.matchId)
.session(session)
.lean()
.exec();
if (
!match?.competitionId ||
match.gameMode !== 'double-elimination' ||
match.status !== 'finished' ||
!match.teamBuiltAt ||
!match.doubleElimination
) {
throw new Error(
'Expected a finished double-elimination Match with a linked Competition.',
);
}
const competition = await Competition.findOne({
_id: match.competitionId,
matchId: match._id,
communityId: match.communityId,
})
.session(session)
.lean()
.exec();
if (!competition || competition.phase !== 'completed') {
throw new Error('Expected a completed Competition linked to this Match.');
}
if (
options.expectedRevision !== undefined &&
competition.revision !== options.expectedRevision
) {
throw new Error(
`Competition revision is ${competition.revision}; run the preview again.`,
);
}
const facts = await Fact.find({ competitionId: competition._id })
.sort({ revision: 1, ordinalWithinRevision: 1 })
.session(session)
.lean()
.exec();
const plan = planGrandFinalBo3Repair({
competitionId: competition._id.toHexString(),
revision: competition.revision,
projectorVersion: competition.projectorVersion,
teams: competition.teams.map(({ teamId, displayOrder, seedNumber }) => ({
teamId: teamId.toHexString(),
displayOrder,
seedNumber,
})),
format: competition.format as unknown as CompetitionGraphFormat,
seriesGraph: competition.seriesGraph as unknown as SeriesDefinition[],
facts: facts.map((fact) => factForProjection({ ...fact })),
});
if (!isDeepStrictEqual(plan.before, competition.projection)) {
throw new Error(
'The fact ledger does not reproduce the stored projection.',
);
}
const revision = plan.projection.sourceRevision;
if (session) {
const now = new Date();
const idempotencyKey = `repair:grand-final-bo3:${competition._id.toHexString()}`;
const requestHash = createHash('sha256')
.update(idempotencyKey)
.digest('hex');
const commandId = `cmpcmd_${requestHash.slice(0, 32)}`;
const receipt = {
competitionId: competition._id,
revision,
commandId,
idempotencyKey,
requestHash,
};
const factId = new mongoose.Types.ObjectId();
const competitionWrite = await Competition.updateOne(
{ _id: competition._id, revision: competition.revision },
{
$set: {
revision,
format: plan.format,
seriesGraph: plan.seriesGraph,
projection: plan.projection,
phase: plan.projection.phase,
},
},
{ session, runValidators: true },
).exec();
const matchWrite = await Match.updateOne(
{ _id: match._id, status: 'finished', competitionId: competition._id },
{
$set: {
status: 'in-progress',
'doubleElimination.grandFinalGameCount': 3,
...(match.resultPollState
? {
'resultPollState.state': 'polling',
'resultPollState.matchedCount': plan.projection.games.length,
}
: {}),
},
},
{ session, runValidators: true },
).exec();
if (
competitionWrite.matchedCount !== 1 ||
matchWrite.matchedCount !== 1
) {
throw new Error(
'Match or Competition changed during repair; run the preview again.',
);
}
await Fact.insertMany(
[
{
...receipt,
_id: factId,
type: CORRECTION_TYPE,
ordinalWithinRevision: 1,
schemaVersion: competition.schemaVersion,
actor: { type: 'system' },
seriesId: new mongoose.Types.ObjectId(plan.seriesId),
occurredAt: now,
recordedAt: now,
reason:
'Restore the intended BO3 grand final without voiding the first game.',
ruleCorrection: { previousMaxGames: 1, nextMaxGames: 3 },
},
],
{ session },
);
await Outbox.insertMany(
[
{
...receipt,
eventId: `${commandId}:competition-projected`,
type: 'competition.projection-updated',
payload: {
competitionId: competition._id.toHexString(),
sourceRevision: revision,
factIds: [factId.toHexString()],
projection: plan.projection,
phase: plan.projection.phase,
updatedAt: now,
},
state: 'pending',
availableAt: now,
},
],
{ session },
);
}
return {
mode: session ? 'applied' : 'dry-run',
database: resolveMongoDbName(options.nodeEnv),
matchId: match._id.toHexString(),
competitionId: competition._id.toHexString(),
revisionBefore: competition.revision,
revisionAfter: revision,
phase: `${competition.phase} -> ${plan.projection.phase}`,
preservedGame: plan.preservedGame,
totalPreservedGames: plan.projection.games.length,
newGameNumbers: plan.newGameNumbers,
};
}
if (!options.apply) return run(null);
const session = await connectionService.createSession();
if (!session) throw new Error('Repair requires a MongoDB transaction.');
try {
return await session.withTransaction(() => run(session));
} finally {
await session.endSession();
}
}
async function main() {
const args = process.argv.slice(2);
if (args.includes('--help')) {
process.stdout.write(
'Usage: pnpm --filter api competition:repair-grand-final --env <dev|staging|prod> --match-id <id> [--expected-revision <n> --apply]\n',
);
return;
}
const options = parseGrandFinalRepairOptions(args);
process.env.NODE_ENV = options.nodeEnv;
process.env.MONGODB_AUTO_INDEX = 'false';
const connections = new ConnectionService(
new SecretService(new ConfigService()),
);
const connection = await connections.getConnection();
try {
process.stdout.write(
`${JSON.stringify(await repairGrandFinalBo3(connections, options), null, 2)}\n`,
);
} finally {
await connection.close();
}
}
if (require.main === module) {
void main().catch((error: unknown) => {
process.stderr.write(
`${error instanceof Error ? error.message : String(error)}\n`,
);
process.exitCode = 1;
});
}
@@ -644,6 +644,7 @@ export interface DoubleEliminationEvent {
export interface DoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
grandFinalGameCount?: 1 | 3 | 5;
resetFinalCreated: boolean;
seeds: DoubleEliminationSeed[];
bracketMatches: DoubleEliminationBracketMatch[];
@@ -1850,6 +1851,7 @@ const DoubleEliminationBracketSubSchema = new Schema<DoubleEliminationBracket>(
{
teamCount: { type: Number, enum: [4, 8], required: true },
resetFinalEnabled: { type: Boolean, required: true, default: false },
grandFinalGameCount: { type: Number, enum: [1, 3, 5] },
resetFinalCreated: { type: Boolean, required: true, default: false },
seeds: {
type: [DoubleEliminationSeedSubSchema],
@@ -3,7 +3,7 @@ import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import mongoose from 'mongoose';
import { CreateMatchDto, JoinMatchDto } from './create-match.dto';
import { CreateMatchDto, JoinMatchDto, UpdateMatchDto } from './create-match.dto';
describe('CreateMatchDto game mode cutover', () => {
it('rejects the removed live bracket mode', () => {
@@ -61,3 +61,21 @@ describe('JoinMatchDto self-join boundary', () => {
}
});
});
describe('Grand final format validation', () => {
it('allows BO3 on creation and rejects an even game count on update', () => {
const create = plainToInstance(CreateMatchDto, {
title: 'Competition',
scheduledAt: '2026-07-13T10:00:00.000Z',
gameMode: 'double-elimination',
doubleEliminationGrandFinalGameCount: 3,
});
expect(validateSync(create)).toEqual([]);
const update = plainToInstance(UpdateMatchDto, {
doubleEliminationGrandFinalGameCount: 2,
});
expect(validateSync(update)).toEqual([
expect.objectContaining({ property: 'doubleEliminationGrandFinalGameCount' }),
]);
});
});
@@ -1,3 +1,4 @@
import type { GrandFinalGameCount } from '@lolympus/contracts';
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
@@ -119,6 +120,10 @@ export class CreateMatchDto {
@IsBoolean()
doubleEliminationResetFinalEnabled?: boolean;
@IsOptional()
@IsIn([1, 3, 5])
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -183,6 +188,10 @@ export class UpdateMatchDto {
@IsBoolean()
doubleEliminationResetFinalEnabled?: boolean;
@IsOptional()
@IsIn([1, 3, 5])
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -21,7 +21,7 @@ interface PublicMatchSource {
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
doubleElimination?: { resetFinalEnabled?: boolean };
doubleElimination?: { resetFinalEnabled?: boolean; grandFinalGameCount?: 1 | 3 | 5 };
hostUserId?: IdLike;
participants: Array<{
userId: IdLike;
@@ -81,6 +81,8 @@ export function presentPublicMatch(
? {
doubleEliminationResetFinalEnabled:
source.doubleElimination?.resetFinalEnabled ?? false,
doubleEliminationGrandFinalGameCount:
source.doubleElimination?.grandFinalGameCount ?? 1,
}
: {}),
...(source.hostUserId
@@ -60,6 +60,8 @@ export class MatchController {
roundRobinMaxRounds: body.roundRobinMaxRounds,
doubleEliminationResetFinalEnabled:
body.doubleEliminationResetFinalEnabled,
doubleEliminationGrandFinalGameCount:
body.doubleEliminationGrandFinalGameCount,
prizes: body.prizes ?? [],
notices: body.notices ?? [],
schedule: body.schedule ?? [],
@@ -149,7 +151,7 @@ export class MatchController {
const match = await this.matchService.update({
matchId,
communityId,
patch: body,
patch: mongoose.omitUndefined({ ...body }),
});
return this.matchService.serialize(match, {
joined: match.participants.some((participant) =>
@@ -531,6 +531,7 @@ describe('MatchService', () => {
gameCount: 5,
gameMode: 'double-elimination',
doubleEliminationResetFinalEnabled: true,
doubleEliminationGrandFinalGameCount: 3,
},
});
@@ -543,6 +544,7 @@ describe('MatchService', () => {
doubleElimination: {
teamCount: 4,
resetFinalEnabled: true,
grandFinalGameCount: 3,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
@@ -37,6 +37,7 @@ const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3;
interface DoubleEliminationConfigInput {
doubleEliminationResetFinalEnabled?: boolean;
doubleEliminationGrandFinalGameCount?: 1 | 3 | 5;
}
interface CreateMatchParams {
@@ -278,6 +279,14 @@ export class MatchService {
'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
);
}
if (
previousStatus !== 'recruiting' &&
'doubleEliminationGrandFinalGameCount' in params.patch
) {
throw new BadRequestException(
'Grand final game count can only be changed while recruiting.',
);
}
const patchToSet =
previousStatus === 'recruiting'
? this.normalizeMatchConfig({
@@ -292,6 +301,10 @@ export class MatchService {
params.patch.doubleEliminationResetFinalEnabled ??
params.patch.doubleElimination?.resetFinalEnabled ??
match.doubleElimination?.resetFinalEnabled,
doubleEliminationGrandFinalGameCount:
params.patch.doubleEliminationGrandFinalGameCount ??
params.patch.doubleElimination?.grandFinalGameCount ??
match.doubleElimination?.grandFinalGameCount,
})
: this.stripMatchConfigInput(params.patch);
match.set(patchToSet);
@@ -406,6 +419,9 @@ export class MatchService {
input.doubleEliminationResetFinalEnabled ??
input.doubleElimination?.resetFinalEnabled ??
false,
grandFinalGameCount:
input.doubleEliminationGrandFinalGameCount ??
input.doubleElimination?.grandFinalGameCount,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
@@ -427,6 +443,7 @@ export class MatchService {
>(input: T): Partial<Match> {
const patch = { ...input };
delete patch.doubleEliminationResetFinalEnabled;
delete patch.doubleEliminationGrandFinalGameCount;
return patch;
}
@@ -975,6 +975,7 @@ export class TournamentCodeService {
shuffledTeamIndexes,
{
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
grandFinalGameCount: match.doubleElimination?.grandFinalGameCount,
winnerBracketGameCount:
match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
},