diff --git a/Game/scripts/ranked_profile_state.gd b/Game/scripts/ranked_profile_state.gd index ea3ae836..dab8b745 100644 --- a/Game/scripts/ranked_profile_state.gd +++ b/Game/scripts/ranked_profile_state.gd @@ -21,7 +21,7 @@ func apply(payload: Dictionary) -> bool: for key in required: if not payload.has(key): return _reject("Profile response is missing " + key) - if not (payload["rating"] is int or payload["rating"] is float) or not (payload["rd"] is int or payload["rd"] is float) or not (payload["volatility"] is int or payload["volatility"] is float) or not payload["ranked_games"] is int or not payload["tier"] is String or not payload["provisional"] is bool: + if not (payload["rating"] is int or payload["rating"] is float) or not (payload["rd"] is int or payload["rd"] is float) or not (payload["volatility"] is int or payload["volatility"] is float) or not (payload["ranked_games"] is int or payload["ranked_games"] is float) or not payload["tier"] is String or not payload["provisional"] is bool: return _reject("Profile response contains invalid types") var next_rating := float(payload["rating"]) var next_rd := float(payload["rd"]) diff --git a/Game/tests/control_plane_smoke.gd b/Game/tests/control_plane_smoke.gd index 274bd241..da6ec0ec 100644 --- a/Game/tests/control_plane_smoke.gd +++ b/Game/tests/control_plane_smoke.gd @@ -25,6 +25,7 @@ var _finished := false var _ticket_id := "" var _assignment_match_id := "" var _steam_ticket := "" +var _ranked_profile_smoke := false func _ready() -> void: @@ -36,6 +37,8 @@ func _ready() -> void: _assignment_match_id = arg.substr("--assignment-match-id=".length()) elif arg.begins_with("--steam-ticket="): _steam_ticket = arg.substr("--steam-ticket=".length()) + elif arg == "--ranked-profile-smoke": + _ranked_profile_smoke = true if control_plane_url.is_empty(): _finish(false, "missing --control-plane-url") return @@ -77,6 +80,12 @@ func _on_request_succeeded(operation: String, payload: Dictionary) -> void: if err != OK: _finish(false, "fetch_assignment() failed to start: %s" % error_string(err)) return + if _ranked_profile_smoke: + print("SMOKE: logged in as %s, fetching populated ranked profile..." % ControlPlaneClient.player_id) + var ranked_err := ControlPlaneClient.fetch_ranked_profile() + if ranked_err != OK: + _finish(false, "fetch_ranked_profile() failed to start: %s" % error_string(ranked_err)) + return print("SMOKE: logged in as %s, fetching ranked profile (expect none yet)..." % ControlPlaneClient.player_id) var err := ControlPlaneClient.fetch_ranked_profile() if err != OK: @@ -87,7 +96,13 @@ func _on_request_succeeded(operation: String, payload: Dictionary) -> void: return _finish(true, "authenticated assignment fetch returned the player-scoped endpoint and join authorisation") "ranked_profile": - _finish(false, "a brand-new testkit identity unexpectedly already has a ranked profile: %s" % payload) + if not _ranked_profile_smoke: + _finish(false, "a brand-new testkit identity unexpectedly already has a ranked profile: %s" % payload) + return + if int(payload.get("rating", -1)) != 1600 or int(payload.get("ranked_games", -1)) != 12 or payload.get("provisional", true) != false or String(payload.get("tier", "")) != "GOLD": + _finish(false, "unexpected populated ranked profile: %s" % payload) + return + _finish(true, "authenticated ranked profile returned the durable rating, games, tier, and provisional state") "queue_create": if payload.get("ticket_id", "") != _ticket_id or payload.get("state", "") != "QUEUED": _finish(false, "unexpected queue_create payload: %s" % payload) diff --git a/multiplayer-next.md b/multiplayer-next.md index 0b2c35c2..0b0e0c2b 100644 --- a/multiplayer-next.md +++ b/multiplayer-next.md @@ -1236,7 +1236,7 @@ the local/CI/community transport, not a silent production fallback. | 8.39 `[D:8.3,8.14,8.17]` | **IN PROGRESS.** `MatchmakingState` now projects queue → proposal → allocation/process-ready/assignment-ready/connect/live plus terminal failure states; autoload `ControlPlaneClient` provides authenticated queue create/recovery/heartbeat/cancel and proposal response requests with idempotency/revision headers; `matchmaking.tscn`/`matchmaking.gd` expose the state and authoritative actions from the main menu; authenticated proposal recovery now reconciles missed proposal events and expires them at read time; the Go API publishes targeted authenticated revisioned queue/proposal/assignment events and the Godot client consumes state/proposal/assignment events, fetching the authoritative assignment after assignment readiness; the API can now use the durable participant-scoped proposal provider for both recovery and accept/decline mutations | `test_matchmaking_state.gd`, `test_control_plane_client.gd`, `test_matchmaking_ui.gd`, `TestProposalRecoveryIsParticipantScopedAndExpiresAtReadBoundary`, `TestAuthenticatedWebSocketDeliversOnlyTargetedRevisionedEvents`, `TestStateChangingAPIActionsPublishTargetedEvents`, `TestProposalRecoveryUsesDurableBackendAndRemainsParticipantScoped` and store proposal SQL tests reject stale/gapped/conflicting updates, validate endpoint/token/payload normalization, preserve idempotent duplicates, and guarantee visible phase/terminal copy; wiring durable allocation events into the outbox, wait/latency explanations and Godot runtime verification remain | | 8.40 `[D:8.3,8.14]` | **IN PROGRESS.** Pure Go revisioned replica reducer rejects gaps for REST resync, makes duplicate/out-of-order events idempotent, and resumes from the authoritative snapshot revision; authenticated queue-ticket recovery now has an owner-checked REST read; Godot client projection persists non-secret ticket/proposal state, forces authoritative recovery after restart, and can replay a lost queue-create response with the original ticket/idempotency key; the Go API now exposes an authenticated `/v1/events` WebSocket with bounded per-player queues, strict upgrade/vocabulary validation and REST-resync-safe slow-client failure; Godot `ControlPlaneClient` can connect to the stream using Godot 4.7's handshake-header API, consume validated events, automatically reconnect with bounded backoff, and trigger REST recovery on projection gaps and stream return, including a deferred recovery when an event arrives during an in-flight HTTP mutation; `OutboxDispatcher` now provides ordered at-least-once delivery after durable commit; assignment recovery events carry the durable assignment revision without leaking it into REST JSON; prediction startup now distinguishes the sequence-0 warm-up acknowledgement from genuine missing/evicted history, preventing a false hard-snap during a live match; proposal creation now writes one durable targeted `proposal_changed` outbox event per proposal aggregate revision, and both production `cmd/control-plane` and the test-only API harness dispatch only that event type to authenticated participants, leaving result events for their separate consumer | `server/domain/sync.go`, `server/api/events.go`, `server/api/outbox.go`, `server/api/service.go`, `server/store/outbox.go`, `server/store/proposal_sql.go`, `server/cmd/control-plane`, `server/cmd/testkit-api`, `service_test.go`, `outbox_test.go`, `matchmaking_state.gd`, `control_plane_client.gd`, `local_prediction_history.gd`, `net_ship_predictor.gd` and tests cover gap, snapshot, replay, same-revision conflict, owner-only ticket recovery, expired-ticket terminal handling, malformed restart snapshots, API-level duplicate-create replay/conflict, authenticated handshake/key rejection, targeted event delivery, exactly-once slow-subscriber closure, invalid-event rejection, delivery-before-ack failure ordering, assignment event/response revision separation, prediction warm-up/hard-resync separation, deferred proposal recovery and proposal outbox filtering/delivery failures; Godot 4.7.1 headless project parse and 150-test unit harness pass with compatibility rendering, and a two-process ENet authoritative match smoke passes spawn, movement, prediction, 0% snapshot loss and 0 hard snaps; `cmd/control-plane` provides a signal-bound API role, `cmd/matcher` now supports casual and explicitly enabled ranked roles with durable identity lookup, and `cmd/maintenance` provides bounded season maintenance. **Live multi-process control-plane/game verification now exists**: `scripts/verify_control_plane_integration.sh` runs a real `postgres:17-alpine`, the real `api.Service` (via the new test-only `server/cmd/testkit-api`, wired identically to `cmd/control-plane` except for a fake Steam login — see §8.7), and a real headless Godot client (`control_plane_smoke.gd`) round-tripping login → `fetch_ranked_profile` (expect 404, §8.22) → `queue_create` → heartbeat → `cancel_queue` over an actual network connection — the first time this boundary was exercised end to end rather than against a mock on either side. **The two-player proposal extension now also passes**: `scripts/verify_control_plane_proposal_integration.sh` starts isolated PostgreSQL, the real matcher and testkit API, launches two headless Godot clients, seeds deterministic RTT projections, observes the real WebSocket `OPEN` proposal, accepts from both clients, and verifies both durable tickets plus the proposal reach `ACCEPTED` (including authoritative recovery when the concurrent revision advances). Allocator and Redis fan-out live verification remain | | 8.41 `[D:7.8,8.9,8.31,8.40]` | **IN PROGRESS.** Authenticated `GET /v1/assignments/{matchId}` now exposes only a validated, player-scoped assignment view including the hosted endpoint; Godot `AssignmentState`/`ControlPlaneClient.fetch_assignment()` bind the response to the authenticated player, recheck expiry, validate and retain the endpoint, and `connect_to_assignment()` now starts only the validated ENet/Steam transport after assignment readiness; the opaque join authorisation is carried in the MatchNet hello payload rather than the endpoint URL; allocated Godot servers now fail closed unless an operator-mounted JSON roster of control-plane signed envelopes and an HMAC-SHA256 key are present, and MatchNet verifies the canonical Go claim bytes, checks exact token membership plus match/server/protocol/slot/expiry claims before admitting a peer, rejects concurrent reuse of an active token, tracks server-owned reconnect generations across the 60-second reclaim window, fences expired reclaims and invalidates old peers; migration 0002 and the Go store adapter now persist/recover the complete player-scoped assignment projection with conflict-safe identical replay; `AssignmentProviderFromStore` wires that durable projection into the API injection point; `SaveAssignments` publishes a complete signed roster atomically instead of allowing partial player visibility; `SaveVerifiedAssignmentRoster` rechecks signed claims before deriving player rows; live authenticated Godot/PostgreSQL assignment verification now exists via `scripts/verify_assignment_integration.sh`, which seeds a durable player-scoped `ASSIGNMENT_READY` row behind the real testkit API and verifies the returned endpoint/join authorisation over HTTP/JSON (including the live numeric-decoding boundary) | `server/api/service.go`, `store_adapters.go`, `service_test.go`, `assignment_state.gd`, `control_plane_client.gd`, `match_net.gd`, `server_boot.gd`, `server_config.gd`, `test_assignment_state.gd`, `test_control_plane_client.gd`, `test_match_net.gd`, `server/contracts/v1/openapi.json`, `server/migrations/0002_assignments.sql` and `server/store/assignment_sql.go` cover participant/identity/expiry/shape/transport/endpoint boundaries, player-scoped schema keys, expiry-filtered reads, assignment upsert conflict handling, atomic batch validation, signed-claim binding, strict endpoint splitting, allowlisted claim rejection, canonical HMAC interoperability, forged-signature rejection, duplicate active-token rejection, reclaim generation/expiry behavior and 150-test Godot compatibility coverage; the three-process disconnect/reclaim smoke passes ship retention, replacement drive and old-peer invalidation; SDR relay-ticket installation and live allocated-token process integration remain | -| 8.42 `[D:8.22,8.23,8.24,8.40]` | **IN PROGRESS.** `RankedProfileState` and `ControlPlaneClient.fetch_ranked_profile()` expose the backend-authoritative rating/RD/volatility/games/tier/provisional/season view; matchmaking UI displays provisional/tier status without client-side rating math | `test_control_plane_client.gd` validates profile shape, numeric safety and provisional display; ranked profile fetch/display, committed revision after reconnect, abandon status and season countdown remain dependent on live auth/backend events and Godot runtime verification | +| 8.42 `[D:8.22,8.23,8.24,8.40]` | **IN PROGRESS.** `RankedProfileState` and `ControlPlaneClient.fetch_ranked_profile()` expose the backend-authoritative rating/RD/volatility/games/tier/provisional/season view; matchmaking UI displays provisional/tier status without client-side rating math; runnable API binaries now wire the backend-owned default tier policy; live authenticated profile verification now exists via `scripts/verify_ranked_profile_integration.sh`, which seeds a durable rating and verifies the populated profile over real PostgreSQL, Go HTTP, and Godot JSON | `test_control_plane_client.gd` validates profile shape, numeric safety and provisional display; the real populated profile path now covers durable rating/games/tier/provisional decoding and caught the missing runtime tier-policy wiring; committed revision after reconnect, abandon status and season countdown remain dependent on live auth/backend events and Godot runtime verification | | 8.43 `[D:8.39,8.40,8.41]` | **IN PROGRESS.** Matchmaking client now distinguishes expired queue recovery, session expiry, missing records and retryable control-plane outages; a 401 clears the in-memory token, emits `session_expired` and disables retry until a new session is configured; terminal messages remain visible and active searches are not falsely failed on transient errors | `MatchmakingState` and `ControlPlaneClient` tests cover explicit expiry and the existing terminal/retry-safe state paths; decline, version mismatch, regional outage retry UI, failed reconnect, duplicate-action recovery and live Godot verification remain | #### 8F — Observability, verification, cost and rollout diff --git a/scripts/verify_control_plane_integration.sh b/scripts/verify_control_plane_integration.sh index 619e9721..5dc49bfc 100755 --- a/scripts/verify_control_plane_integration.sh +++ b/scripts/verify_control_plane_integration.sh @@ -29,6 +29,7 @@ pg_port="55434" api_port="18099" logs_dir="$(mktemp -d "${TMPDIR:-/tmp}/cosmic-clash-control-plane.XXXXXX")" assignment_smoke="${ASSIGNMENT_SMOKE:-0}" +ranked_smoke="${RANKED_SMOKE:-0}" testkit_pid="" cleanup() { @@ -116,6 +117,15 @@ INSERT INTO assignments (match_id, player_id, allocation_id, server_id, slot, re VALUES ('assignment-smoke-match', '$assignment_player_id', 'assignment-smoke-allocation', 'assignment-smoke-server', 0, 'EU', 'smoke-build', 1, 'enet', '127.0.0.1:30001', 'assignment-smoke-join-authorisation', decode('000102030405060708090a0b0c0d0e0f', 'hex'), now() + interval '1 hour', 1) ON CONFLICT (match_id, player_id) DO NOTHING;" godot_args+=(--assignment-match-id="assignment-smoke-match" --steam-ticket="$assignment_ticket") +elif [ "$ranked_smoke" = "1" ]; then + ranked_ticket="ranked-profile-smoke-web-api-ticket" + ranked_player_id="testkit-$(printf '%s' "$ranked_ticket" | shasum -a 256 | awk '{print substr($1,1,16)}')" + docker exec "$container_name" psql -v ON_ERROR_STOP=1 -U "$user" -d "$database" -c " +INSERT INTO identities (player_id, steam_id) VALUES ('$ranked_player_id', 'ranked-profile-smoke-steam') ON CONFLICT (player_id) DO NOTHING; +INSERT INTO ratings (player_id, rating, deviation, volatility, ranked_games, revision) +VALUES ('$ranked_player_id', 1600, 120, 0.05, 12, 3) +ON CONFLICT (player_id) DO NOTHING;" + godot_args+=(--steam-ticket="$ranked_ticket" --ranked-profile-smoke) fi "$godot_bin" --headless --path Game res://tests/control_plane_smoke.tscn -- "${godot_args[@]}" \ diff --git a/scripts/verify_ranked_profile_integration.sh b/scripts/verify_ranked_profile_integration.sh new file mode 100644 index 00000000..c760b917 --- /dev/null +++ b/scripts/verify_ranked_profile_integration.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Real authenticated ranked-profile response verification. The shared gate +# keeps the existing fresh-player 404 path as its default and enables this +# populated durable-rating fixture only for this explicit variant. +root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$root_dir" +RANKED_SMOKE=1 bash scripts/verify_control_plane_integration.sh diff --git a/server/cmd/control-plane/main.go b/server/cmd/control-plane/main.go index 33e363e2..f23a47a5 100644 --- a/server/cmd/control-plane/main.go +++ b/server/cmd/control-plane/main.go @@ -12,6 +12,7 @@ import ( "time" "github.com/cosmic-clash/cosmic-clash/server/api" + "github.com/cosmic-clash/cosmic-clash/server/domain" "github.com/cosmic-clash/cosmic-clash/server/migrations" "github.com/cosmic-clash/cosmic-clash/server/observability" "github.com/cosmic-clash/cosmic-clash/server/store" @@ -100,6 +101,7 @@ func newAPIService(db *sql.DB, workloadSecret string, indexes ...api.CandidateIn ServerRegistrar: api.ServerRegistrarFromStore(db), ResultSubmitter: store.PostgresResults{DB: db}, RankedProfileProvider: store.PostgresRankedProfiles{DB: db}, + TierPolicy: domain.DefaultTierPolicy(), Assignment: api.AssignmentProviderFromStore(db), CandidateIndex: candidateIndex, ProbeRecorder: store.PostgresQueue{DB: db}, diff --git a/server/cmd/testkit-api/main.go b/server/cmd/testkit-api/main.go index ecd510fe..cb285725 100644 --- a/server/cmd/testkit-api/main.go +++ b/server/cmd/testkit-api/main.go @@ -64,6 +64,7 @@ func main() { ServerRegistrar: api.ServerRegistrarFromStore(db), ResultSubmitter: store.PostgresResults{DB: db}, RankedProfileProvider: store.PostgresRankedProfiles{DB: db}, + TierPolicy: domain.DefaultTierPolicy(), Assignment: api.AssignmentProviderFromStore(db), ProbeRecorder: store.PostgresQueue{DB: db}, WorkloadVerify: api.WorkloadVerifierFromSignedToken([]byte(*workloadSecret), db), diff --git a/server/domain/rating.go b/server/domain/rating.go index 250755a7..49d3fe8b 100644 --- a/server/domain/rating.go +++ b/server/domain/rating.go @@ -87,6 +87,19 @@ type TierPolicy struct { bands []TierBand } +// DefaultTierPolicy is the backend-owned launch policy used by runnable API +// binaries. Callers still serialize only the resulting tier; clients never +// receive or reproduce these thresholds. +func DefaultTierPolicy() TierPolicy { + return TierPolicy{bands: []TierBand{ + {Tier: RankTierBronze, MinRating: 0}, + {Tier: RankTierSilver, MinRating: 1200}, + {Tier: RankTierGold, MinRating: 1500}, + {Tier: RankTierPlatinum, MinRating: 1800}, + {Tier: RankTierDiamond, MinRating: 2200}, + }} +} + func NewTierPolicy(bands []TierBand) (TierPolicy, error) { if len(bands) == 0 || bands[0].MinRating > 0 { return TierPolicy{}, fmt.Errorf("tier policy must start at or below zero")