From 4dcf98cbb05e754385f882bc442b5f1f90f7324e Mon Sep 17 00:00:00 2001 From: Josh Creek <8179928+jcreek@users.noreply.github.com> Date: Mon, 31 Aug 2026 21:36:00 +0100 Subject: [PATCH] feat: form matches from queue projections --- multiplayer-next.md | 3 +++ multiplayer-todo.md | 2 +- server/domain/matcher.go | 44 ++++++++++++++++++++++++++++++++++- server/domain/matcher_test.go | 35 ++++++++++++++++++++++++++++ 4 files changed, 82 insertions(+), 2 deletions(-) diff --git a/multiplayer-next.md b/multiplayer-next.md index 95c84112..160e8d5a 100644 --- a/multiplayer-next.md +++ b/multiplayer-next.md @@ -79,6 +79,9 @@ product policy are in [`docs/MATCHMAKING.md`](docs/MATCHMAKING.md). region/team tie-break rules. Authenticated probe transport now routes opaque location/nonce data through a server-owned evidence provider and refuses client RTT values; Steam/coordinator adapters remain. +- [ ] **IN PROGRESS:** Form deterministic candidate sets and balanced teams from + the server-owned queue projection. Queue-backed oldest-anchor formation and + 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. diff --git a/multiplayer-todo.md b/multiplayer-todo.md index d759239f..3beecc93 100644 --- a/multiplayer-todo.md +++ b/multiplayer-todo.md @@ -1193,7 +1193,7 @@ 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 | `server/domain/matcher.go`, `teams.go` and adversarial fixtures cover no-common-region, tolerance boundaries, lexical ties, mean-rating balance and input-order independence; queue-backed candidate loading and full population fixtures 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.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 | diff --git a/server/domain/matcher.go b/server/domain/matcher.go index 6a22172a..571a82eb 100644 --- a/server/domain/matcher.go +++ b/server/domain/matcher.go @@ -2,6 +2,7 @@ package domain import ( "fmt" + "math" "sort" "time" ) @@ -33,6 +34,33 @@ type Selection struct { TotalWaitSeconds float64 } +type MatchFormation struct { + Selection Selection + Teams Teams +} + +// FormFromQueue is the queue-backed matcher boundary. Queue.Candidates owns +// expiry and ordering; this method chooses the oldest projected candidate as +// the anchor, then forms and partitions one deterministic match. +func FormFromQueue(queue *Queue, size int, now time.Time) (MatchFormation, error) { + if queue == nil { + return MatchFormation{}, fmt.Errorf("queue is required") + } + candidates := queue.Candidates(now) + if len(candidates) == 0 { + return MatchFormation{}, fmt.Errorf("queue is empty") + } + selection, err := SelectCandidates(candidates[0], candidates[1:], size, now) + if err != nil { + return MatchFormation{}, err + } + teams, err := PartitionTeams(selection.Players) + if err != nil { + return MatchFormation{}, err + } + return MatchFormation{Selection: selection, Teams: teams}, nil +} + func RatingTolerance(waitSeconds float64) float64 { if waitSeconds < 0 { waitSeconds = 0 @@ -50,9 +78,11 @@ func SelectCandidates(anchor Candidate, candidates []Candidate, size int, now ti } pool := make([]Candidate, 0, len(candidates)+1) seen := map[string]bool{} + seenPlayers := map[string]bool{} add := func(candidate Candidate) { - if candidate.TicketID != "" && !seen[candidate.TicketID] { + if validCandidate(candidate) && !seen[candidate.TicketID] && !seenPlayers[candidate.PlayerID] { seen[candidate.TicketID] = true + seenPlayers[candidate.PlayerID] = true pool = append(pool, candidate) } } @@ -97,6 +127,18 @@ func SelectCandidates(anchor Candidate, candidates []Candidate, size int, now ti return best, nil } +func validCandidate(candidate Candidate) bool { + if candidate.TicketID == "" || candidate.PlayerID == "" || candidate.EnqueuedAt.IsZero() || math.IsNaN(candidate.Rating) || math.IsInf(candidate.Rating, 0) { + return false + } + for region, rtt := range candidate.PredictedRTT { + if region != "EU" && region != "NA" || math.IsNaN(rtt) || math.IsInf(rtt, 0) || rtt < 0 { + return false + } + } + return len(candidate.PredictedRTT) > 0 +} + func compatibleSet(players []Candidate, now time.Time) bool { regions := commonRegions(players) if len(regions) == 0 { diff --git a/server/domain/matcher_test.go b/server/domain/matcher_test.go index 1d92ef38..af2237c7 100644 --- a/server/domain/matcher_test.go +++ b/server/domain/matcher_test.go @@ -66,3 +66,38 @@ func TestSelectCandidatesRejectsNoCommonRegion(t *testing.T) { t.Fatal("selected players without a common <=100ms region") } } + +func TestFormFromQueueUsesServerProjectionAndBalancesTeams(t *testing.T) { + now := time.Unix(100000, 0) + queue := NewQueue() + for _, id := range []string{"c", "a", "b", "d"} { + candidate := candidate(id, 1500, time.Second, 40, 45, now) + if _, err := queue.Create(candidate.PlayerID, candidate.TicketID, "create-key-"+id+"-123456", candidate, now.Add(-time.Duration(len(id))*time.Millisecond)); err != nil { + t.Fatal(err) + } + } + formation, err := FormFromQueue(queue, 4, now) + if err != nil { + t.Fatal(err) + } + if formation.Selection.Players[0].TicketID != "a" || formation.Selection.Region != "EU" || len(formation.Teams.Team0) != 2 || len(formation.Teams.Team1) != 2 { + t.Fatalf("formation = %+v", formation) + } + seen := map[string]bool{} + for _, player := range append(formation.Teams.Team0, formation.Teams.Team1...) { + if seen[player.PlayerID] { + t.Fatalf("duplicate player in teams: %s", player.PlayerID) + } + seen[player.PlayerID] = true + } +} + +func TestSelectCandidatesRejectsMalformedCandidateInsteadOfTrustingIt(t *testing.T) { + now := time.Unix(100000, 0) + anchor := candidate("a", 1500, 0, 40, 40, now) + malformed := candidate("b", 1500, 0, 40, 40, now) + malformed.PlayerID = anchor.PlayerID + if _, err := SelectCandidates(anchor, []Candidate{malformed}, 2, now); err == nil { + t.Fatal("duplicate player candidate accepted") + } +}