diff --git a/multiplayer-next.md b/multiplayer-next.md index 160e8d5a..d63e1eaf 100644 --- a/multiplayer-next.md +++ b/multiplayer-next.md @@ -84,7 +84,9 @@ product policy are in [`docs/MATCHMAKING.md`](docs/MATCHMAKING.md). duplicate-player fencing now exist; durable matcher claims remain. - [ ] **IN PROGRESS:** Send 10 s proposals to every selected human: ranked six, relaxed casual two to six with disclosed bots; enforce exact cooldown and queue-precedence - behavior. + behavior. Playlist-aware proposal preparation now validates casual team humans + and ranked identity/arena metadata before creating proposal state; durable + queue precedence and allocation integration remain. - [ ] **IN PROGRESS:** Fence proposals/participants in a PostgreSQL serializable transaction; prove loss of an acknowledged Redis write cannot split players. - [ ] Casual: target 3v3 humans, after 60 s allow >=2 humans (one/team) plus diff --git a/multiplayer-todo.md b/multiplayer-todo.md index 3beecc93..381184f2 100644 --- a/multiplayer-todo.md +++ b/multiplayer-todo.md @@ -1194,10 +1194,10 @@ the local/CI/community transport, not a silent production fallback. | 8.14 `[D:8.4,8.5,8.8]` | **IN PROGRESS.** Pure Go queue domain enforces one active ticket per verified player under concurrent mutation, 10 s heartbeat/30 s expiry, retry-safe create/heartbeat/cancel, owner-only recovery reads and deterministic candidate projection; store layer adds a rebuildable candidate-cache boundary and authenticated HTTP queue adapter | `server/domain/queue.go`, `server/store/candidates.go` and `server/api/service.go` cover ownership/expiry/idempotency, concurrent create fencing, expired recovery as a terminal error, server-owned candidate resolution, bounded/strict JSON input and cache loss/atomic rebuild; PostgreSQL row adapter, real Redis index/TTLs and restart/failover integration remain | | 8.15 `[D:7.8,8.3]` | **IN PROGRESS.** Pure Go probe validation treats Steam location as opaque, requires nonce/freshness/region and server-computed RTT, and implements discrepancy quarantine/release; authenticated HTTP now accepts only opaque location/nonce input through a server-owned probe provider | `server/domain/probes.go`, adversarial fixtures and `server/api/service.go` cover stale/wrong/forged evidence, the 25 ms/30% threshold, three-sample quarantine, five-clean release, authenticated provider arguments and rejection of client RTT fields; Steam coordinator and regional probe adapters remain | | 8.16 `[D:8.14,8.15]` | **IN PROGRESS.** Pure Go candidate/team selection implements the <=100 ms ceiling, pairwise widening tolerance, anchor inclusion, deterministic set/region scoring and balanced team partitioning; queue-backed formation now consumes the server-owned projection and fences duplicate player identities | `server/domain/matcher.go`, `teams.go` and adversarial fixtures cover no-common-region, tolerance boundaries, lexical ties, mean-rating balance, malformed candidates, duplicate identities and queue-backed oldest-anchor formation; full population fixtures and durable matcher claim integration remain | -| 8.17 `[D:8.14,8.16]` | **IN PROGRESS.** Pure Go proposal policy sends a 10-second response window to every selected human, requires unanimous acceptance, applies exact decline/timeout cooldowns and ranked escalation; authenticated API now exposes revisioned accept/decline mutations | `server/domain/proposal.go` and `server/api/service.go` plus adversarial fixtures cover partial/unanimous response, expiry, replay/conflict, stale API revision and ranked six-player/cooldown rules; casual 6→2 composition, queue precedence and allocation integration remain | +| 8.17 `[D:8.14,8.16]` | **IN PROGRESS.** Pure Go proposal policy sends a 10-second response window to every selected human, requires unanimous acceptance, applies exact decline/timeout cooldowns and ranked escalation; authenticated API exposes revisioned accept/decline mutations; formed matches now pass through a playlist-aware proposal boundary | `server/domain/proposal.go`, `formation.go` and `server/api/service.go` plus adversarial fixtures cover partial/unanimous response, expiry, replay/conflict, stale API revision, casual lineup preparation and ranked metadata validation; queue precedence and allocation integration remain | | 8.18 `[D:8.5,8.14,8.17]` | **IN PROGRESS.** Go store layer defines PostgreSQL SERIALIZABLE whole-transaction retries and queue candidate/proposal claim SQL using `FOR UPDATE SKIP LOCKED` plus durable uniqueness/revision fences | `server/store/serializable.go` and tests cover retry classification and claim-boundary invariants; live PostgreSQL adapter/row decoding, Redis candidate index/repair, worker-failure and concurrent two-matcher integration tests remain | -| 8.19 `[D:8.18]` | **IN PROGRESS.** Pure Go casual lineup requires 2–6 humans with at least one per team, fills missing slots with explicit bots, permits kickoff-only bot-slot backfill and assigns no backfill penalty/rating update | `server/domain/casual.go` covers both-team minimum, bot shape, live-play rejection and zero-penalty backfill; queue candidate selection, opt-in 10 s backfill proposals, reconnect/leave penalties and live integration remain | -| 8.20 `[D:8.18]` | **IN PROGRESS.** Pure Go ranked admission requires six unique verified solo humans, rejects bots/backfill/parties, and allows only random-enabled non-elevated arenas | `server/domain/ranked.go` covers count, identity, party, bot/backfill and arena eligibility rejection; `ArenaRegistry` integration, proposal/allocation wiring and innocent-ticket restoration remain | +| 8.19 `[D:8.18]` | **IN PROGRESS.** Pure Go casual lineup requires 2–6 humans with at least one per team, fills missing slots with explicit bots, permits kickoff-only bot-slot backfill and assigns no backfill penalty/rating update; proposal preparation now derives the lineup from formed teams | `server/domain/casual.go`, `formation.go` cover both-team minimum, bot shape, live-play rejection, zero-penalty backfill and casual proposal composition; queue candidate selection, opt-in 10 s backfill proposals, reconnect/leave penalties and live integration remain | +| 8.20 `[D:8.18]` | **IN PROGRESS.** Pure Go ranked admission requires six unique verified solo humans, rejects bots/backfill/parties, and allows only random-enabled non-elevated arenas; proposal preparation requires matching metadata for every formed player | `server/domain/ranked.go`, `formation.go` cover count, identity, party, bot/backfill, arena eligibility and formed-player metadata rejection; `ArenaRegistry` integration, allocation wiring and innocent-ticket restoration remain | | 8.21 `[D:8.5,8.20]` | **IN PROGRESS.** Pure Go rating core implements canonical Glicko-2, daily inactivity, ranked 1/3 and casual 1/N human-opponent weights, deterministic opponent ordering, and authoritative draw/overtime/abandon scoring | `server/domain/rating.go` has canonical/inactivity/weight/invalid-input plus draw/OT/abandon fixtures; PostgreSQL snapshot locking, rating transaction integration, seasons and concurrent result transaction tests remain | | 8.22 `[D:8.21]` | **IN PROGRESS.** Pure Go ranked profile exposes the first ten games as provisional, derives tiers only through validated backend-owned rating bands, and keeps casual ratings outside the API; authenticated HTTP now returns the authoritative ranked view | `server/domain/rating.go`, `tier_test.go` and `server/api/service.go` cover provisional override, exact band boundaries, malformed policy rejection, session authentication and ranked-only response fields; persisted tier policy, client UI and reconnect transport remain | | 8.23 `[D:8.21]` | **IN PROGRESS.** Pure Go ranked-only season policy compresses 25% toward 1500, clamps RD to 200–350, preserves volatility/history, is idempotent by season ID, and defines exact 12-week windows/due detection | `server/domain/rating.go` and `season_test.go` cover compression, floor/cap, duplicate replay, window boundary and completed-season idempotence; PostgreSQL locking, persisted rollover transaction and maintenance scheduler remain | diff --git a/server/domain/formation.go b/server/domain/formation.go new file mode 100644 index 00000000..68d0c081 --- /dev/null +++ b/server/domain/formation.go @@ -0,0 +1,72 @@ +package domain + +import ( + "fmt" + "time" +) + +type PreparedProposal struct { + Proposal Proposal + CasualLineup []CasualSlot +} + +// PrepareProposal is the boundary between matchmaking and proposal state. It +// never creates a proposal for a casual formation without one human per team, +// or for a ranked formation whose verified identity/arena metadata fails the +// ranked admission policy. +func PrepareProposal(id string, playlist Playlist, formation MatchFormation, rankedParticipants []RankedParticipant, arena RankedArena, now time.Time) (PreparedProposal, error) { + if len(formation.Selection.Players) < 2 || len(formation.Selection.Players) > 6 { + return PreparedProposal{}, fmt.Errorf("invalid formed player count") + } + playerIDs := make([]string, 0, len(formation.Selection.Players)) + seen := make(map[string]bool, len(formation.Selection.Players)) + for _, player := range formation.Selection.Players { + if player.PlayerID == "" || seen[player.PlayerID] { + return PreparedProposal{}, fmt.Errorf("invalid formed player identity") + } + seen[player.PlayerID] = true + playerIDs = append(playerIDs, player.PlayerID) + } + var lineup []CasualSlot + switch playlist { + case Casual: + participants := make([]ConnectParticipant, 0, len(formation.Selection.Players)) + for _, player := range formation.Teams.Team0 { + participants = append(participants, ConnectParticipant{PlayerID: player.PlayerID, Team: 0}) + } + for _, player := range formation.Teams.Team1 { + participants = append(participants, ConnectParticipant{PlayerID: player.PlayerID, Team: 1}) + } + var err error + lineup, err = BuildCasualLineup(participants) + if err != nil { + return PreparedProposal{}, err + } + case Ranked: + if len(rankedParticipants) != len(playerIDs) { + return PreparedProposal{}, fmt.Errorf("ranked metadata does not match formed players") + } + metadata := make(map[string]bool, len(rankedParticipants)) + for _, participant := range rankedParticipants { + metadata[participant.PlayerID] = true + } + if len(metadata) != len(playerIDs) { + return PreparedProposal{}, fmt.Errorf("ranked metadata has duplicate or unknown players") + } + for _, playerID := range playerIDs { + if !metadata[playerID] { + return PreparedProposal{}, fmt.Errorf("ranked metadata missing formed player") + } + } + if err := ValidateRankedAdmission(rankedParticipants, arena); err != nil { + return PreparedProposal{}, err + } + default: + return PreparedProposal{}, fmt.Errorf("unsupported playlist") + } + proposal, err := NewProposal(id, playlist, playerIDs, now) + if err != nil { + return PreparedProposal{}, err + } + return PreparedProposal{Proposal: proposal, CasualLineup: lineup}, nil +} diff --git a/server/domain/formation_test.go b/server/domain/formation_test.go new file mode 100644 index 00000000..e427cb2f --- /dev/null +++ b/server/domain/formation_test.go @@ -0,0 +1,65 @@ +package domain + +import ( + "testing" + "time" +) + +func testFormation(t *testing.T, count int) MatchFormation { + t.Helper() + now := time.Unix(1000, 0) + players := make([]Candidate, count) + for i := range players { + players[i] = Candidate{TicketID: string(rune('a' + i)), PlayerID: string(rune('p' + i)), Rating: 1500, EnqueuedAt: now, PredictedRTT: map[string]float64{"EU": 40}} + } + selection, err := SelectCandidates(players[0], players[1:], count, now) + if err != nil { + t.Fatal(err) + } + teams, err := PartitionTeams(selection.Players) + if err != nil { + t.Fatal(err) + } + return MatchFormation{Selection: selection, Teams: teams} +} + +func TestPrepareProposalBuildsCasualLineupBeforeCreatingProposal(t *testing.T) { + prepared, err := PrepareProposal("proposal-casual-123456", Casual, testFormation(t, 2), nil, RankedArena{}, time.Unix(1000, 0)) + if err != nil { + t.Fatal(err) + } + if prepared.Proposal.Playlist != Casual || len(prepared.Proposal.Participants) != 2 || len(prepared.CasualLineup) != 6 { + t.Fatalf("prepared casual proposal = %+v", prepared) + } + humans := 0 + teams := map[int]bool{} + for _, slot := range prepared.CasualLineup { + if !slot.IsBot { + humans++ + teams[slot.Team] = true + } + } + if humans != 2 || len(teams) != 2 { + t.Fatalf("casual lineup humans/teams = %d/%v", humans, teams) + } +} + +func TestPrepareProposalRejectsInvalidRankedMetadataAndAcceptsVerifiedSix(t *testing.T) { + formation := testFormation(t, 6) + participants := make([]RankedParticipant, 6) + for i, player := range formation.Selection.Players { + participants[i] = RankedParticipant{PlayerID: player.PlayerID, SteamID: "steam-" + player.PlayerID} + } + if _, err := PrepareProposal("proposal-ranked-123456", Ranked, formation, participants, RankedArena{RandomEnabled: true}, time.Unix(1000, 0)); err != nil { + t.Fatal(err) + } + participants[0].IsBot = true + if _, err := PrepareProposal("proposal-ranked-654321", Ranked, formation, participants, RankedArena{RandomEnabled: true}, time.Unix(1000, 0)); err == nil { + t.Fatal("ranked bot metadata accepted") + } + participants[0].IsBot = false + participants[0].PlayerID = "unknown" + if _, err := PrepareProposal("proposal-ranked-000000", Ranked, formation, participants, RankedArena{RandomEnabled: true}, time.Unix(1000, 0)); err == nil { + t.Fatal("ranked unknown player metadata accepted") + } +}