docs: specify competition result domain
This commit is contained in:
1 parent
3a76fd8c88
commit
f4ba3d524f
1 file changed
+319
@@ -0,0 +1,319 @@
|
||||
# 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 test -- --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.
|
||||
|
||||
### 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.
|
||||
|
||||
## 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.
|
||||
|
||||
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.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
- Migration dry-run reports zero unclassified documents before apply.
|
||||
- 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.
|
||||
Reference in new issue
Block a user