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

@@ -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],