diff --git a/multiplayer-next.md b/multiplayer-next.md index d59e5842..ce8305a7 100644 --- a/multiplayer-next.md +++ b/multiplayer-next.md @@ -63,8 +63,10 @@ product policy are in [`docs/MATCHMAKING.md`](docs/MATCHMAKING.md). down gracefully; optional `--redis-addr` publishes queue mutations to a TTL-bound best-effort candidate projection without making Redis authoritative; a runnable casual `cmd/matcher` role now polls PostgreSQL and delegates - proposal claims to the durable transaction; allocator/maintenance roles, - ranked provider wiring, Redis worker wiring and live service checks remain. + proposal claims to the durable transaction; `cmd/maintenance` now runs + bounded ranked-season rollover batches with signal-bound shutdown; + provider-backed allocation, ranked provider wiring, Redis worker wiring and + live service checks remain. - [ ] **IN PROGRESS:** Define assignment compatibility and opt-in `ServerConfig` flags whose defaults reproduce the community-server path. Allocation manifest validation now covers client build and future expiry; allocated servers now diff --git a/multiplayer-todo.md b/multiplayer-todo.md index c3e34887..82597a13 100644 --- a/multiplayer-todo.md +++ b/multiplayer-todo.md @@ -1201,7 +1201,7 @@ the local/CI/community transport, not a silent production fallback. | 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; migration and Go store now persist a per-player/per-season marker and rating update atomically | `server/domain/rating.go`, `season_test.go`, `server/migrations/0001_initial.sql` and `server/store/season_sql.go` cover compression, floor/cap, duplicate replay, window boundary, completed-season idempotence, row locking and conflict-safe rollover markers; opt-in PostgreSQL execution now covers the durable rating update, marker creation and duplicate replay without a second compression; maintenance scheduler remains | +| 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; migration and Go store now persist a per-player/per-season marker and rating update atomically; `cmd/maintenance` runs bounded due-season batches with signal-bound shutdown | `server/domain/rating.go`, `season_test.go`, `server/migrations/0001_initial.sql` and `server/store/maintenance_sql.go` cover compression, floor/cap, duplicate replay, window boundary, completed-season idempotence, bounded enumeration, row locking and conflict-safe rollover markers; opt-in PostgreSQL execution now covers the durable rating update, marker creation and duplicate replay without a second compression; live maintenance/DB execution remains | | 8.24 `[D:8.9,8.20,8.21]` | **IN PROGRESS.** Pure Go ranked connection policy binds match/server/player/team/slot/protocol, supports 60 s reclaim with server-owned generations, fences old connections, and applies the rolling 7-day 5 m/15 m/1 h/24 h abandon ladder; canonical signed authorisation issuance/verification now gates admission | `server/domain/reconnect.go`, `join_auth.go` and adversarial fixtures cover repeated backend-independent reclaim, all signed claim binding, tampering, failed verification, old-generation fencing, grace boundary and deterministic cooldown audit ordering; persistent lease fencing, join transport and full match/result integration remain | | 8.25 `[D:8.10,8.24]` | **IN PROGRESS.** Pure Go result policy binds match/server/workload identity, hashes canonical payloads, makes identical retries idempotent, leaves conflicts inert, separates integrity eligibility, classifies roster/simulation/result/fairness evidence, validates annotation signatures/digests, and exposes 5 m alert/30 m review delivery thresholds; Go store SQL now executes the receipt → match lock → completion → receipt acknowledgment → outbox boundary atomically, and exposes bounded ordered outbox reads plus publish acknowledgements for replayable fan-out; `OutboxDispatcher` now delivers in order and acknowledges only after successful fan-out | `server/domain/result.go`, `workload.go`, `server/store/result_sql.go` and `outbox.go` plus adversarial fixtures cover credential binding, duplicate/conflict, annotation forgery, delivery-outage-versus-integrity classification, commit ordering, idempotent SQL reconciliation, unpublished-event replay/ack boundaries and delivery-before-ack failure ordering; opt-in PostgreSQL execution now covers result-pending completion, durable receipt/outbox publication, ack removal, identical replay and conflicting replay rejection; production credential verification, Agones annotation persistence/reconciliation, rating-lock integration and integrity evidence adapters remain | diff --git a/server/cmd/maintenance/main.go b/server/cmd/maintenance/main.go new file mode 100644 index 00000000..8fcaf861 --- /dev/null +++ b/server/cmd/maintenance/main.go @@ -0,0 +1,67 @@ +package main + +import ( + "context" + "database/sql" + "flag" + "fmt" + "log" + "os" + "os/signal" + "syscall" + "time" + + "github.com/cosmic-clash/cosmic-clash/server/migrations" + "github.com/cosmic-clash/cosmic-clash/server/store" + _ "github.com/jackc/pgx/v5/stdlib" +) + +func main() { + dsn := flag.String("dsn", os.Getenv("COSMIC_CLASH_POSTGRES_DSN"), "PostgreSQL connection string") + migrationDir := flag.String("migrations", "migrations", "directory containing numbered SQL migrations") + interval := flag.Duration("interval", time.Minute, "maintenance poll interval") + batch := flag.Int("batch", 100, "maximum player rollovers per pass") + flag.Parse() + if *dsn == "" { + fatalf("--dsn or COSMIC_CLASH_POSTGRES_DSN is required") + } + if *interval <= 0 || *batch < 1 || *batch > 1000 { + fatalf("invalid interval or batch") + } + db, err := sql.Open("pgx", *dsn) + if err != nil { + fatalf("open PostgreSQL: %v", err) + } + defer db.Close() + startupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if err := db.PingContext(startupCtx); err != nil { + fatalf("ping PostgreSQL: %v", err) + } + if err := migrations.Apply(startupCtx, db, *migrationDir); err != nil { + fatalf("apply migrations: %v", err) + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + for { + count, err := store.RolloverDueSeasons(ctx, db, time.Now().UTC(), *batch) + if err != nil { + fatalf("season maintenance: %v", err) + } + if count > 0 { + log.Printf("applied %d ranked season rollovers", count) + } + timer := time.NewTimer(*interval) + select { + case <-ctx.Done(): + timer.Stop() + return + case <-timer.C: + } + } +} + +func fatalf(format string, args ...any) { + fmt.Fprintf(os.Stderr, "maintenance: "+format+"\n", args...) + os.Exit(1) +} diff --git a/server/store/maintenance_sql.go b/server/store/maintenance_sql.go new file mode 100644 index 00000000..c5ef1fcc --- /dev/null +++ b/server/store/maintenance_sql.go @@ -0,0 +1,67 @@ +package store + +import ( + "context" + "database/sql" + "fmt" + "time" + + "github.com/cosmic-clash/cosmic-clash/server/domain" +) + +const DueSeasonRolloversSQL = `SELECT s.season_id, r.player_id, r.rating, r.deviation, + r.volatility, r.ranked_games +FROM seasons s +CROSS JOIN ratings r +LEFT JOIN ranked_season_rollovers rr ON rr.season_id = s.season_id AND rr.player_id = r.player_id +WHERE s.playlist = 'ranked' AND s.ends_at <= $1 AND rr.player_id IS NULL +ORDER BY s.ends_at, s.season_id, r.player_id +LIMIT $2` + +const MarkSeasonRolledOverSQL = `UPDATE seasons SET rolled_over_at = $2 +WHERE season_id = $1 AND rolled_over_at IS NULL + AND NOT EXISTS (SELECT 1 FROM ratings r + LEFT JOIN ranked_season_rollovers rr ON rr.season_id = $1 AND rr.player_id = r.player_id + WHERE rr.player_id IS NULL)` + +type dueSeasonRollover struct { + seasonID string + playerID string + profile domain.RankedProfile +} + +// RolloverDueSeasons processes a bounded batch. Each player update is its own +// exactly-once SERIALIZABLE transaction, so a worker crash can safely resume. +func RolloverDueSeasons(ctx context.Context, db *sql.DB, now time.Time, limit int) (int, error) { + if db == nil || now.IsZero() || limit < 1 || limit > 1000 { + return 0, fmt.Errorf("invalid season maintenance arguments") + } + rows, err := db.QueryContext(ctx, DueSeasonRolloversSQL, now, limit) + if err != nil { + return 0, err + } + defer rows.Close() + var due []dueSeasonRollover + for rows.Next() { + var item dueSeasonRollover + if err := rows.Scan(&item.seasonID, &item.playerID, &item.profile.Value, &item.profile.RD, &item.profile.Volatility, &item.profile.RankedGames); err != nil { + return 0, err + } + due = append(due, item) + } + if err := rows.Err(); err != nil { + return 0, err + } + count := 0 + for _, item := range due { + if _, applied, err := ApplyRankedSeasonRollover(ctx, db, item.playerID, item.seasonID, item.profile, now); err != nil { + return count, err + } else if applied { + count++ + } + if _, err := db.ExecContext(ctx, MarkSeasonRolledOverSQL, item.seasonID, now); err != nil { + return count, err + } + } + return count, nil +} diff --git a/server/store/maintenance_sql_test.go b/server/store/maintenance_sql_test.go new file mode 100644 index 00000000..e563a7a4 --- /dev/null +++ b/server/store/maintenance_sql_test.go @@ -0,0 +1,28 @@ +package store + +import ( + "testing" + "time" +) + +func TestMaintenanceSQLEnumeratesOnlyUnrolledRankedPlayers(t *testing.T) { + for _, fragment := range []string{"s.playlist = 'ranked'", "ends_at <= $1", "rr.player_id IS NULL", "ORDER BY s.ends_at", "LIMIT $2"} { + if !contains(DueSeasonRolloversSQL, fragment) { + t.Fatalf("due query missing %q", fragment) + } + } + for _, fragment := range []string{"rolled_over_at IS NULL", "NOT EXISTS", "ranked_season_rollovers"} { + if !contains(MarkSeasonRolledOverSQL, fragment) { + t.Fatalf("mark query missing %q", fragment) + } + } +} + +func TestRolloverDueSeasonsRejectsUnboundedMaintenance(t *testing.T) { + if _, err := RolloverDueSeasons(nil, nil, time.Unix(1000, 0), 0); err == nil { + t.Fatal("zero batch accepted") + } + if _, err := RolloverDueSeasons(nil, nil, time.Unix(1000, 0), 1001); err == nil { + t.Fatal("oversized batch accepted") + } +}