392 lines
17 KiB
Markdown
392 lines
17 KiB
Markdown
# Spec: Competition Result Domain
|
|
|
|
## Objective
|
|
|
|
Replace the positional, duplicated tournament result state currently stored across
|
|
`Match.result`, `Match.doubleElimination`, and `TournamentCode` with a dedicated
|
|
Competition aggregate.
|
|
|
|
The replacement must make accepted game evidence and explicit administrative
|
|
adjudications the durable facts. A single deterministic projector derives every
|
|
score, leader, series outcome, bracket participant, standing, placement, and
|
|
competition outcome.
|
|
|
|
The change fixes the production failure where `WB_R2_M2` was stored with bracket
|
|
slots `A=8, B=3`, while the independently sorted series score used `A=3, B=8`,
|
|
causing team 3 to advance despite team 8 winning two games.
|
|
|
|
## Approved Product Decisions
|
|
|
|
- Recruitment and team building remain on `Match`; competitive play is a separate
|
|
one-to-one `Competition` aggregate.
|
|
- Team identity is an opaque string/ObjectId and is independent from display order
|
|
and seed number.
|
|
- The API and web app switch to the new contract together. No legacy result response
|
|
adapter or dual canonical write path remains after cutover.
|
|
- The unused `bracket` mode is removed. Legacy documents using it migrate to
|
|
`paired-series`, matching their actual historical execution path.
|
|
- Round-robin ranking uses series wins, game differential, and a tied-group
|
|
head-to-head mini-table. Remaining ties share the same rank.
|
|
- Parent-result reversal is strict by default. Administrators can request an impact
|
|
preview and execute an explicit, hash-confirmed cascade reversal.
|
|
- Full event sourcing is out of scope. Competition configuration is a state snapshot;
|
|
accepted results, adjudications, and reversals form an append-only fact ledger.
|
|
|
|
## Tech Stack
|
|
|
|
- NestJS 11 and Mongoose 9 in `apps/api`
|
|
- React 19, TypeScript, and Vite in `apps/web`
|
|
- pnpm workspace with shared wire contracts under `packages/contracts`
|
|
- MongoDB transactions for command atomicity
|
|
- Redis locks only as duplicate-work optimization
|
|
- Jest for API/domain tests
|
|
|
|
## Commands
|
|
|
|
- API unit/integration tests: `pnpm --filter api test`
|
|
- Focused API test: `pnpm --filter api exec jest --runInBand <test-path>`
|
|
- API build: `pnpm --filter api build`
|
|
- Web build/typecheck: `pnpm --filter web build`
|
|
- Migration dry-run: `pnpm --filter api competition:migrate -- --dry-run`
|
|
- Migration apply: `pnpm --filter api competition:migrate -- --apply`
|
|
|
|
## Project Structure
|
|
|
|
- `packages/contracts/` owns public Competition/Series/Game DTOs and branded wire IDs.
|
|
- `apps/api/src/modules/competition/domain/` owns format definitions, graph generation,
|
|
invariant validation, and pure projectors.
|
|
- `apps/api/src/modules/competition/` owns persistence, commands, presenters, and HTTP
|
|
integration.
|
|
- `apps/api/src/modules/global/database/migrations/` owns pure migration planning and
|
|
database application.
|
|
- Existing `riot_match` remains the immutable external evidence archive.
|
|
- Existing `match_stats` remains a rebuildable read model and gains source revision
|
|
checks.
|
|
|
|
## Domain Model
|
|
|
|
### Match and Competition
|
|
|
|
`Match` continues to own recruiting, participants, team building, notices, prizes,
|
|
and scheduling metadata. It receives a unique optional `competitionId`.
|
|
|
|
`Competition` owns:
|
|
|
|
- immutable team snapshots after the first accepted result;
|
|
- a format-specific, versioned Series graph;
|
|
- a monotonic revision;
|
|
- a projector version;
|
|
- a rebuildable current projection cache.
|
|
|
|
Exactly one Competition may reference a Match.
|
|
|
|
Competition creation is an explicit side effect of the finalized team-building
|
|
workflow. Read endpoints never create state. If a finalized Match is observed before
|
|
its Competition has been linked, the API reports that initialization is still in
|
|
progress instead of attempting a lazy bootstrap.
|
|
|
|
After `competitionId` is linked, the Match cannot return to recruiting, change its
|
|
game count, reset or undo its auction, or be hard-deleted through ordinary Match
|
|
operations. Corrections happen through Competition facts and reversals; replacing the
|
|
event requires a new Match. The legacy-import bulk-delete operation is the one
|
|
explicit destructive exception and removes the whole aggregate and its dependent
|
|
read models transactionally.
|
|
|
|
Joining a Match is an authenticated self-service action. The normal participant
|
|
endpoint always derives the participant from the authenticated user; only the
|
|
administrator endpoint may add another community member.
|
|
|
|
### Identifiers
|
|
|
|
- `CompetitionId`, `TeamId`, `SeriesId`, `GameSlotId`, `GameId`, and `FactId` are
|
|
opaque strings on the wire and ObjectIds in MongoDB.
|
|
- Display order, seed, round, ordinal, and global display number are never identities.
|
|
- `WB_R2_M2` is an optional diagnostic/display code, never a parsed control key.
|
|
- Migration identifiers are deterministic from the Match ID, entity kind, and legacy
|
|
key so migration is idempotent.
|
|
|
|
### Formats
|
|
|
|
Supported formats are:
|
|
|
|
- `paired-series`: independent fixed-game Series with no overall champion;
|
|
- `round-robin`: fixed-game Series with shared-rank standings;
|
|
- `double-elimination`: first-to rules per upper, lower, grand-final, and reset-final
|
|
stage.
|
|
|
|
Fixed-game Series complete only after all configured GameSlots are filled and may
|
|
draw. First-to Series complete as soon as a team reaches the threshold and cannot
|
|
draw.
|
|
|
|
The legacy double-elimination defaults remain upper=`Match.gameCount`, lower=BO1,
|
|
grand final=BO1, reset final=BO1.
|
|
|
|
### Series Graph
|
|
|
|
Every Series has:
|
|
|
|
- an opaque ID and optional display code;
|
|
- explicit stage, round, and display order;
|
|
- exactly two local slots named A and B;
|
|
- exactly one source per target slot;
|
|
- a Series rule;
|
|
- stable GameSlots identified by Series ID and ordinal;
|
|
- optional activation rules.
|
|
|
|
Only incoming slot sources are stored. Reverse winner/loser destinations are derived.
|
|
The graph must be acyclic. GF_RESET is created as a stable inactive conditional node,
|
|
not appended at runtime.
|
|
|
|
### Durable Facts
|
|
|
|
`competition_fact` is append-only and supports:
|
|
|
|
- `game-accepted`;
|
|
- `game-voided`;
|
|
- `series-adjudicated`;
|
|
- `adjudication-reversed`.
|
|
|
|
Every fact carries competition ID, command ID, revision, ordinal within revision,
|
|
schema version, actor, occurrence/record timestamps, and optional causation ID.
|
|
|
|
An accepted game records its stable Series/GameSlot, Riot evidence ID and payload
|
|
hash, mapping algorithm version and confidence, blue/red/winner team IDs, the mapping
|
|
snapshot used at acceptance time, and a normalized legacy evidence fallback.
|
|
|
|
Facts are never updated or deleted. Reversal facts reference the exact fact they
|
|
invalidate.
|
|
|
|
### Administrative Adjudication
|
|
|
|
- Walkover requires no active games.
|
|
- Forfeit may retain partial played-game scores.
|
|
- Administrative outcome requires a reason and an explicit winner or draw.
|
|
- At most one active adjudication exists per Series.
|
|
- Administrative outcome determines the official result while played scores remain
|
|
visible.
|
|
- Draw adjudication is invalid for elimination formats.
|
|
|
|
### Projection
|
|
|
|
The projector is pure, deterministic, versioned, and free of implicit time or random
|
|
inputs. It derives:
|
|
|
|
- actual team in each Series slot;
|
|
- score entries shaped as `{ slot, teamId, gameWins }`;
|
|
- Series state;
|
|
- `leaderTeamId` only for an in-progress Series;
|
|
- `winnerTeamId` only in a completed outcome;
|
|
- bracket progression and connectors;
|
|
- active GameSlots;
|
|
- round-robin standings and shared ranks;
|
|
- double-elimination placements and champion;
|
|
- overall Competition phase/outcome.
|
|
|
|
The projector rejects inconsistent evidence rather than guessing. In particular, an
|
|
accepted game's team set must equal the projected Series team set, ordinals and Riot
|
|
claims must be unique, and no game may be accepted after completion.
|
|
|
|
Round-robin tie order is:
|
|
|
|
1. overall series wins;
|
|
2. overall game differential;
|
|
3. tied-group mini-table series wins;
|
|
4. tied-group mini-table game differential;
|
|
5. shared rank.
|
|
|
|
### Tournament Code Assignment
|
|
|
|
`TournamentCode` remains the pool resource. Assignment history moves to a separate
|
|
`tournament_code_assignment` collection keyed by Competition, Series, and GameSlot.
|
|
Assignments transition through reserved, used, released, or voided without deleting
|
|
history. Active code and active GameSlot assignments are uniquely indexed.
|
|
|
|
Accepting a code-backed Riot game atomically commits the accepted fact, assignment
|
|
use, code consumption, Competition revision/projection, and outbox events.
|
|
|
|
Reversal releases only codes that are in a releasable terminal state and removes all
|
|
obsolete Match code bindings in the same transaction. Public/team reads validate the
|
|
active assignment, code state, and Match binding instead of returning stale codes.
|
|
Expired reserved codes also terminate their active assignment and Match binding
|
|
atomically so the slot can be provisioned again without an administrative replacement
|
|
endpoint.
|
|
|
|
## Command Semantics
|
|
|
|
All Competition mutations require an idempotency key and expected revision.
|
|
|
|
Within a MongoDB transaction, the shared command runner:
|
|
|
|
1. verifies revision and idempotency;
|
|
2. appends fact(s);
|
|
3. runs the projector;
|
|
4. persists revision and projection;
|
|
5. updates TournamentCodeAssignment where applicable;
|
|
6. inserts outbox records;
|
|
7. commits atomically.
|
|
|
|
Transient transaction/write-conflict failures use a bounded retry. Idempotency is
|
|
rechecked on every attempt, so a concurrent successful command is replayed rather
|
|
than duplicated. Outbox delivery uses bounded attempts and moves permanently failing
|
|
events to an explicit `dead-letter` state for operator recovery.
|
|
|
|
External Riot fetches occur before the transaction. A stale revision returns HTTP 412,
|
|
a valid-state conflict returns 409, and invalid input returns 422.
|
|
|
|
Strict reversal rejects any descendant accepted game, adjudication, or used code.
|
|
Reserved descendant codes may be released atomically. Cascade reversal requires a
|
|
preview generated at the same source revision and an unchanged impact hash. It emits
|
|
individual reversal facts joined by one causation ID.
|
|
|
|
## Public API
|
|
|
|
- Public Match and Competition responses are explicit DTOs, never spread Mongoose
|
|
documents.
|
|
- The shared Match contract is the single wire definition used by API presenters and
|
|
web consumers. Authentication is optional on public Match reads solely to compute
|
|
the required `joined` flag; anonymous reads receive `joined: false`.
|
|
- Public responses exclude tournament codes, audit actors, and internal fact payloads.
|
|
- Team view exposes only the authenticated user's team slots and code assignments.
|
|
- Administrator fact view exposes the audit ledger.
|
|
- GET responses expose revision/ETag; commands require `If-Match` and
|
|
`Idempotency-Key`.
|
|
- The web client never parses Series codes or recomputes official winners/standings.
|
|
- Storage, domain, and wire types remain separate.
|
|
|
|
## Migration
|
|
|
|
Migration builds new collections without dual canonical writes.
|
|
|
|
- Team, Series, and GameSlot IDs are deterministic.
|
|
- Riot-backed legacy games become accepted-game facts.
|
|
- Normalized games without raw archives use explicit legacy evidence.
|
|
- Winner-only records with no games become administrative adjudications; games are
|
|
never fabricated.
|
|
- Active walkovers become walkover adjudications.
|
|
- Legacy `seriesResults`, bracket winners, and placements are diagnostic only and are
|
|
not trusted as source facts.
|
|
- The known A/B positional bug is repaired by projecting accepted games.
|
|
- Ambiguous mappings, evidence conflicts, or already-played invalid descendants are
|
|
quarantined.
|
|
- Legacy `bracket` format becomes `paired-series` with a warning.
|
|
- Native Mongo migration reads do not receive Mongoose defaults. The hydration
|
|
boundary restores the historical Match default only when `gameMode` is absent or
|
|
`null`, mapping it to `pair`; an explicitly stored unknown mode remains
|
|
quarantined instead of being guessed.
|
|
- A persisted legacy round-robin `gameSchedule` is authoritative. Migration
|
|
normalizes it into explicit seed-based pairings on the Competition format so the
|
|
immutable Series graph reproduces the historical opponents and rounds instead of
|
|
generating a different canonical schedule. Matches without a persisted schedule
|
|
continue to use deterministic canonical round-robin generation.
|
|
- Legacy TournamentCode `gameNumber` is a global GameSlot number, not a Series
|
|
ordinal. Migration resolves it through accepted Riot evidence first, then the
|
|
persisted format topology (`gameSchedule` or double-elimination bracket layout),
|
|
and only uses canonical flattened graph order when no persisted topology exists.
|
|
- TournamentCode `bracketMatchId`, global `gameNumber`, Riot evidence, and resolved
|
|
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
|
|
is quarantined without changing the legacy Match or TournamentCode.
|
|
- Dry-run is the default and emits machine-readable and human-readable reports.
|
|
- Apply is resumable, idempotent, transactionally scoped per Match, and verifies fact
|
|
replay equality after every write.
|
|
- Apply explicitly creates or verifies every Competition unique/partial index before
|
|
migrating a Match. Existing target-data/index-definition conflicts block apply with
|
|
a machine-readable preflight report; source Matches that collide with an already
|
|
accepted global identity are quarantined rather than guessed or partially written.
|
|
- Limited apply runs persist the last terminal Match `_id` in a migration checkpoint.
|
|
The next run resumes strictly after that cursor; a failed Match does not advance the
|
|
cursor, and an explicit `--after` cursor may override the checkpoint for recovery.
|
|
- An explicit limited-apply `--after` cursor durably replaces an older checkpoint
|
|
before scanning, so a failure on the first overridden Match is retried by the next
|
|
ordinary limited apply.
|
|
- Dry-run never creates indexes, uses a persisted resume checkpoint, or updates
|
|
checkpoints; it always audits the requested source range from the beginning unless
|
|
an explicit `--after` cursor is supplied.
|
|
|
|
Legacy Match fields remain untouched for rollback until the new runtime is verified,
|
|
then a separate cleanup migration removes them.
|
|
|
|
## Testing Strategy
|
|
|
|
- TDD for graph generation, Series projection, Competition projection, commands, and
|
|
migration planning.
|
|
- Unit tests dominate and use pure fixtures.
|
|
- Integration tests cover Mongo transactions, revision races, idempotency, assignments,
|
|
and API presenters.
|
|
- Migration fixtures cover the supplied `data.txt` failure and all ambiguous legacy
|
|
categories.
|
|
- API and web production builds are required.
|
|
- Staging smoke verification covers recruiting through completion and reversal.
|
|
|
|
## Code Style
|
|
|
|
Prefer explicit discriminated unions and pure functions:
|
|
|
|
```ts
|
|
switch (series.rule.type) {
|
|
case "first-to":
|
|
return projectFirstToSeries(series, facts);
|
|
case "fixed-games":
|
|
return projectFixedGamesSeries(series, facts);
|
|
}
|
|
```
|
|
|
|
Never infer identity from ordering and never use a positional score without carrying
|
|
its `teamId` in the same object.
|
|
|
|
## Boundaries
|
|
|
|
### Always
|
|
|
|
- Write a failing test before behavioral code.
|
|
- Rebuild official state with the one Competition projector.
|
|
- Use transactions and expected revisions for mutations.
|
|
- Preserve accepted evidence and reversal history.
|
|
- Keep every increment buildable and commit verified slices atomically.
|
|
|
|
### Ask First
|
|
|
|
- Adding runtime dependencies.
|
|
- Changing authentication/authorization policy outside Competition endpoints.
|
|
- Broadening supported team counts or tournament formats.
|
|
- Applying a migration to a non-test database.
|
|
|
|
### Never
|
|
|
|
- Treat Redis locks as the correctness boundary.
|
|
- Dual-write old and new canonical result models.
|
|
- Parse `WB_*`/`LB_*` codes for control flow.
|
|
- Delete facts to implement correction.
|
|
- Fabricate Riot evidence for legacy results.
|
|
- Expose tournament codes on a public endpoint.
|
|
- Reintroduce legacy seed reshuffling, positional bracket mutation, or unauthenticated
|
|
tournament-code replacement endpoints.
|
|
|
|
## Success Criteria
|
|
|
|
- The supplied `WB_R2_M2` fixture projects team 8 as winner, team 8 into WB_FINAL,
|
|
and team 3 into LB_R2_M1.
|
|
- No persisted positional `teamAWins/teamBWins` projection is a source of truth.
|
|
- In-progress Series cannot expose a winner in TypeScript or API output.
|
|
- Result, code assignment, projection, and outbox transitions are atomic and
|
|
idempotent.
|
|
- Pair, round-robin, and double-elimination flows complete end to end.
|
|
- Reversal preview/cascade is revision- and hash-protected.
|
|
- Statistics cannot regress to an older source revision.
|
|
- A legacy stats builder cannot overwrite a Competition-backed fragment, and a late
|
|
builder cannot resurrect stats after its Match/Competition has been deleted.
|
|
- Double-elimination seeds are persisted before the finalized team-build timestamp is
|
|
exposed, and an expired reserved code can be provisioned again automatically.
|
|
- Migration dry-run reports zero unclassified documents before apply.
|
|
- Historical Matches without a persisted `gameMode` plan as `paired-series`, while
|
|
an explicitly invalid legacy mode is still reported as
|
|
`UNSUPPORTED_LEGACY_GAME_MODE`.
|
|
- Competition unique/partial indexes are verified before the first apply write, and
|
|
repeated limited apply runs advance without rescanning the first page.
|
|
- API tests and API/web production builds pass.
|
|
- Legacy result writers, serializers, and frontend code are removed after cutover.
|
|
|
|
## Open Questions
|
|
|
|
None. Product and architecture decisions were approved before implementation.
|