From 97b187fc408082e1a3e29589448c20249ef43397 Mon Sep 17 00:00:00 2001 From: Leo-Galli Date: Wed, 25 Nov 2026 17:25:04 +0100 Subject: [PATCH] feat(game): atomic apply_move via Redis Lua CAS (CV-171) Concurrent apply cannot append two plies on the same position. Flag meta writes use length-CAS so they cannot overwrite a winning ply. --- README.md | 13 +-- scripts/verify-readme.mjs | 2 +- src/game/apply.rs | 163 +++++++++++++++++++++++++------- src/game/mod.rs | 6 +- src/game/store.rs | 179 ++++++++++++++++++++++++++++++++++- tests/atomic_apply.rs | 192 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 508 insertions(+), 47 deletions(-) create mode 100644 tests/atomic_apply.rs diff --git a/README.md b/README.md index ef202dc..2c29951 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@
-Rust Axum game server for Corvin. Ships a bindable binary with `GET /health`, WebSocket `GET /ws` play wire (`Hello` / `Welcome` / `Ping` / `Pong`, cookie or `AuthTicket`, `QuickPair`, `Move`, offers, `Resign` / `Abort`, `ClaimDraw`, `Flag`, `ResumeGame` → `GameSnapshot` + `Replay`, and `GameEnd` with persist plus Glicko-2), reversible Postgres migrations for `users`, `sessions`, `passkeys`, `email_otps`, `challenges`, `ratings`, `rating_updates`, `games`, and `game_events`, Redis presence keys, Redis append-only live game event logs that replay to FEN via [chess-core](https://github.com/corvin-chess/chess-core), legal `apply_move` with PROTOCOL `MoveApplied` / `MoveRejected` (`ILLEGAL_MOVE`, `NOT_YOUR_TURN`, `GAME_GONE`, `AUTH`), server-authoritative clocks with Fischer increment and flag verification (`ClockSync` / `GameEnd` reason `flag`), lag compensation quota from server-measured RTT (`lag_comp_ms` on apply; never trusts client send time), draw / takeback / resign / abort helpers (`OfferState`, `OFFER_INVALID`, `ABORT_DENIED`, `GameEnd` reasons `agreement` / `resign` / `abort`), threefold / fifty-move `claim_draw` plus automatic fivefold / seventy-five draws (`CLAIM_DENIED`, `GameEnd` reasons `threefold` / `fifty` / `fivefold` / `seventy_five`), Redis quick pair pools plus Postgres challenge links that seat two players and emit PROTOCOL `GameStart`, Glicko-2 `apply_rated_finish` that updates per-time-class rating rows exactly once per `game_id` (PROTOCOL `rating_diff` `{w,b}`; skips casual and abort), once-only `persist_finished_game` into Postgres with `export_pgn` / `GET /api/v1/games/{id}/pgn` whose movetext matches chess-core `encode_movetext`, PROTOCOL contract fixtures under `tests/fixtures/protocol/` exercised by `tests/protocol_contract.rs`, HTTP auth under `/api/v1/auth` (WebAuthn passkeys plus email OTP), HttpOnly session cookies, CSRF-bound logout, and age-appropriate messaging defaults (`dm_enabled` / `public_chat_enabled`, minors stay off). Lobby seeks UI, tournaments, multi-instance hub fan-out, and the wider HTTP API remain Planned. +Rust Axum game server for Corvin. Ships a bindable binary with `GET /health`, WebSocket `GET /ws` play wire (`Hello` / `Welcome` / `Ping` / `Pong`, cookie or `AuthTicket`, `QuickPair`, `Move`, offers, `Resign` / `Abort`, `ClaimDraw`, `Flag`, `ResumeGame` → `GameSnapshot` + `Replay`, and `GameEnd` with persist plus Glicko-2), reversible Postgres migrations for `users`, `sessions`, `passkeys`, `email_otps`, `challenges`, `ratings`, `rating_updates`, `games`, and `game_events`, Redis presence keys, Redis append-only live game event logs that replay to FEN via [chess-core](https://github.com/corvin-chess/chess-core), legal `apply_move` (Redis Lua CAS on event length) with PROTOCOL `MoveApplied` / `MoveRejected` (`ILLEGAL_MOVE`, `NOT_YOUR_TURN`, `GAME_GONE`, `AUTH`), server-authoritative clocks with Fischer increment and flag verification (`ClockSync` / `GameEnd` reason `flag`), lag compensation quota from server-measured RTT (`lag_comp_ms` on apply; never trusts client send time), draw / takeback / resign / abort helpers (`OfferState`, `OFFER_INVALID`, `ABORT_DENIED`, `GameEnd` reasons `agreement` / `resign` / `abort`), threefold / fifty-move `claim_draw` plus automatic fivefold / seventy-five draws (`CLAIM_DENIED`, `GameEnd` reasons `threefold` / `fifty` / `fivefold` / `seventy_five`), Redis quick pair pools plus Postgres challenge links that seat two players and emit PROTOCOL `GameStart`, Glicko-2 `apply_rated_finish` that updates per-time-class rating rows exactly once per `game_id` (PROTOCOL `rating_diff` `{w,b}`; skips casual and abort), once-only `persist_finished_game` into Postgres with `export_pgn` / `GET /api/v1/games/{id}/pgn` whose movetext matches chess-core `encode_movetext`, PROTOCOL contract fixtures under `tests/fixtures/protocol/` exercised by `tests/protocol_contract.rs`, HTTP auth under `/api/v1/auth` (WebAuthn passkeys plus email OTP), HttpOnly session cookies, CSRF-bound logout, and age-appropriate messaging defaults (`dm_enabled` / `public_chat_enabled`, minors stay off). Lobby seeks UI, tournaments, multi-instance hub fan-out, and the wider HTTP API remain Planned. @@ -21,7 +21,7 @@ Rust Axum game server for Corvin. Ships a bindable binary with `GET /health`, We

Overview

-Rust Axum server for Corvin. Current surface: `GET /health` returns HTTP 200 with plain body `ok` plus a trailing newline for Compose probes; `GET /ws` upgrades to the JSON play protocol v1 handshake (`Hello` with `client` `web|mobile|bot` and `locale` yields `Welcome` with ULID `session_id`, unix-ms `server_time`, and empty `features`, then a server `Ping` for RTT sampling; client `Ping`/`Pong` echo `nonce`; unsupported `v` returns `Error` `PROTO_VERSION`); reversible SQL migrations under `migrations/` create `users`, `sessions`, `passkeys`, `email_otps`, `challenges`, `ratings`, `rating_updates`, `games`, and `game_events`, and add `dm_enabled` / `public_chat_enabled` on `users` (ULID account ids, opaque sessions with CSRF secret material, WebAuthn credential JSON, hashed email OTP challenges; challenge rows hold open link tokens with expiry; ratings hold Glicko-2 `rating` / `rd` / `volatility` per time class; `rating_updates` audits one finish per `game_id`; `games` stores finished-game snapshots with username labels and `game_events` keeps the append-only JSONB audit log); Redis helpers under `src/redis_store.rs` connect via `REDIS_URL` and maintain short-TTL presence keys `corvin:presence:{user_id}`; game helpers under `src/game/` store live append-only logs at `corvin:game:{id}:meta` (initial FEN, seat ids, clocks with Fischer `increment_ms` and `active_started_ms`, `initial_ms` for PGN TimeControl, per-seat `lag_quota_*_ms`, `time_class`, `rated`, optional `pending_offer`, prev-clock snapshot for takeback) and `corvin:game:{id}:events` (JSON Move / Offer / OfferResponse / Resign / Abort / Takeback / ClaimDraw / AutoDraw / ServerNote entries with monotonic `seq`), reconstruct position FEN by replaying net Move UCIs through [chess-core](https://github.com/corvin-chess/chess-core) (Takeback pops the last net ply), apply seated legal moves via `apply_move` / `apply_move_with_rtt` (SAN + FEN + PROTOCOL reject codes; deducts effective elapsed after lag credit then adds increment; flags before increment; optional `lag_comp_ms`; clears pending offers; may set `AppliedMove.auto_draw` for fivefold or seventy-five), and verify flag claims via `claim_flag` / `check_flag` (timeout draw when the opponent has no mating potential); offer helpers under `src/game/offers.rs` implement `offer_draw` / `offer_takeback` / `respond_offer` / `resign` / `abort` with PROTOCOL `OfferState` and `GameEnd` (`agreement`, `resign`, `abort`), reject codes `OFFER_INVALID` / `ABORT_DENIED`, ADR-005 first-move abort windows (bullet 15s / blitz 20s / rapid+ 60s), and counter-offer-as-accept; claim helpers under `src/game/claims.rs` implement `claim_draw` for side-to-move threefold or fifty-move claims (`CLAIM_DENIED` otherwise) and automatic fivefold / seventy-five ends after apply; lag helpers under `src/game/lag.rs` publish interim quota `clamp((initial+40×inc)/60, 200, 1000)` ms from server RTT EWMA one-way estimates (remeasure CV-305; never trust client send time); matchmaking helpers under `src/matchmaking/` implement Redis `quick_pair` / `quick_pair_cancel` / `take_pair_result` (exact-config pools `corvin:pair:pool:{time_class}:{rated|casual}:{initial_ms}:{increment_ms}`) and Postgres `challenge_create_link` / `challenge_accept` / `challenge_decline` / `challenge_cancel` that create seated live games (meta `rated` and `initial_ms` from config) and PROTOCOL `GameStart` JSON for both seats; rating helpers under `src/rating/` implement Glicko-2 (ADR-007: initial 1500/350/0.06, τ=0.75, provisional RD≥110) via `apply_rated_finish` / `game_end_with_rating_diff` (once-only via `rating_updates.game_id`; skip casual and abort; PROTOCOL `rating_diff` `{w,b}` integers; color weighting stays CV-221); persist helpers under `src/game/persist.rs` and `src/game/pgn.rs` implement once-only `persist_finished_game` / `persist_finished_from_redis` into `games` + `game_events`, plus `export_pgn` / `render_pgn` whose movetext matches chess-core `encode_movetext` of net Moves; PROTOCOL message shapes for built helpers are locked by golden fixtures under `tests/fixtures/protocol/` (`tests/protocol_contract.rs`); `GET /api/v1/games/{id}` and `GET /api/v1/games/{id}/pgn` serve the durable summary and PGN (`application/x-chess-pgn`); auth routes under `/api/v1/auth/email/otp/*` and `/api/v1/auth/passkey/*` mint HttpOnly `corvin_session` cookies (`SameSite=Lax`, `Secure` on https) and return a synchronizer `csrf_token` plus messaging flags (prior sessions for that user are revoked); `GET /api/v1/auth/session` resolves the cookie to `{user_id,username,csrf_token,dm_enabled,public_chat_enabled}`; `POST /api/v1/auth/logout` requires matching `X-CSRF-Token` and clears the cookie; `GET|PATCH /api/v1/account/messaging` reads or updates those flags (CSRF on PATCH; estimated age under 18 or missing `birth_year` cannot enable DMs or public chat). `GET /ws` on the full app authenticates via session cookie or `AuthTicket`, registers the seat on an in-process `PlayHub`, dispatches `QuickPair` / `QuickPairCancel`, `Move` (with Ping RTT into `LagTracker`), offer / resign / abort / claim / flag messages, and `ResumeGame` (`GameSnapshot` + `Replay`), and on terminal ends calls `persist_finished_from_redis` then `apply_rated_finish` before broadcasting `GameEnd`. Planned surfaces: expanding rating windows (CV-210), τ calibration (CV-220), tournaments, DM delivery (CV-281 uses `assert_can_send_dm`), mid-game Postgres flush (CV-180), multi-instance hub fan-out, and the wider HTTP API. Intended dependencies: PostgreSQL for durable data, Redis for live games and presence, chess-core for legality, and optional analysis via [engine](https://github.com/corvin-chess/engine). Fair-play review hooks are planned to consume the public [fairplay](https://github.com/corvin-chess/fairplay) library; private thresholds stay out of this repository. Outbound SMTP is not wired yet; OTP delivery uses a log sink unless tests inject a capture mailer. +Rust Axum server for Corvin. Current surface: `GET /health` returns HTTP 200 with plain body `ok` plus a trailing newline for Compose probes; `GET /ws` upgrades to the JSON play protocol v1 handshake (`Hello` with `client` `web|mobile|bot` and `locale` yields `Welcome` with ULID `session_id`, unix-ms `server_time`, and empty `features`, then a server `Ping` for RTT sampling; client `Ping`/`Pong` echo `nonce`; unsupported `v` returns `Error` `PROTO_VERSION`); reversible SQL migrations under `migrations/` create `users`, `sessions`, `passkeys`, `email_otps`, `challenges`, `ratings`, `rating_updates`, `games`, and `game_events`, and add `dm_enabled` / `public_chat_enabled` on `users` (ULID account ids, opaque sessions with CSRF secret material, WebAuthn credential JSON, hashed email OTP challenges; challenge rows hold open link tokens with expiry; ratings hold Glicko-2 `rating` / `rd` / `volatility` per time class; `rating_updates` audits one finish per `game_id`; `games` stores finished-game snapshots with username labels and `game_events` keeps the append-only JSONB audit log); Redis helpers under `src/redis_store.rs` connect via `REDIS_URL` and maintain short-TTL presence keys `corvin:presence:{user_id}`; game helpers under `src/game/` store live append-only logs at `corvin:game:{id}:meta` (initial FEN, seat ids, clocks with Fischer `increment_ms` and `active_started_ms`, `initial_ms` for PGN TimeControl, per-seat `lag_quota_*_ms`, `time_class`, `rated`, optional `pending_offer`, prev-clock snapshot for takeback) and `corvin:game:{id}:events` (JSON Move / Offer / OfferResponse / Resign / Abort / Takeback / ClaimDraw / AutoDraw / ServerNote entries with monotonic `seq`), reconstruct position FEN by replaying net Move UCIs through [chess-core](https://github.com/corvin-chess/chess-core) (Takeback pops the last net ply), apply seated legal moves via `apply_move` / `apply_move_with_rtt` (SAN + FEN + PROTOCOL reject codes; Redis Lua CAS on event list length so concurrent apply cannot double-append; deducts effective elapsed after lag credit then adds increment; flags before increment; optional `lag_comp_ms`; clears pending offers; may set `AppliedMove.auto_draw` for fivefold or seventy-five), and verify flag claims via `claim_flag` / `check_flag` (timeout draw when the opponent has no mating potential); offer helpers under `src/game/offers.rs` implement `offer_draw` / `offer_takeback` / `respond_offer` / `resign` / `abort` with PROTOCOL `OfferState` and `GameEnd` (`agreement`, `resign`, `abort`), reject codes `OFFER_INVALID` / `ABORT_DENIED`, ADR-005 first-move abort windows (bullet 15s / blitz 20s / rapid+ 60s), and counter-offer-as-accept; claim helpers under `src/game/claims.rs` implement `claim_draw` for side-to-move threefold or fifty-move claims (`CLAIM_DENIED` otherwise) and automatic fivefold / seventy-five ends after apply; lag helpers under `src/game/lag.rs` publish interim quota `clamp((initial+40×inc)/60, 200, 1000)` ms from server RTT EWMA one-way estimates (remeasure CV-305; never trust client send time); matchmaking helpers under `src/matchmaking/` implement Redis `quick_pair` / `quick_pair_cancel` / `take_pair_result` (exact-config pools `corvin:pair:pool:{time_class}:{rated|casual}:{initial_ms}:{increment_ms}`) and Postgres `challenge_create_link` / `challenge_accept` / `challenge_decline` / `challenge_cancel` that create seated live games (meta `rated` and `initial_ms` from config) and PROTOCOL `GameStart` JSON for both seats; rating helpers under `src/rating/` implement Glicko-2 (ADR-007: initial 1500/350/0.06, τ=0.75, provisional RD≥110) via `apply_rated_finish` / `game_end_with_rating_diff` (once-only via `rating_updates.game_id`; skip casual and abort; PROTOCOL `rating_diff` `{w,b}` integers; color weighting stays CV-221); persist helpers under `src/game/persist.rs` and `src/game/pgn.rs` implement once-only `persist_finished_game` / `persist_finished_from_redis` into `games` + `game_events`, plus `export_pgn` / `render_pgn` whose movetext matches chess-core `encode_movetext` of net Moves; PROTOCOL message shapes for built helpers are locked by golden fixtures under `tests/fixtures/protocol/` (`tests/protocol_contract.rs`); `GET /api/v1/games/{id}` and `GET /api/v1/games/{id}/pgn` serve the durable summary and PGN (`application/x-chess-pgn`); auth routes under `/api/v1/auth/email/otp/*` and `/api/v1/auth/passkey/*` mint HttpOnly `corvin_session` cookies (`SameSite=Lax`, `Secure` on https) and return a synchronizer `csrf_token` plus messaging flags (prior sessions for that user are revoked); `GET /api/v1/auth/session` resolves the cookie to `{user_id,username,csrf_token,dm_enabled,public_chat_enabled}`; `POST /api/v1/auth/logout` requires matching `X-CSRF-Token` and clears the cookie; `GET|PATCH /api/v1/account/messaging` reads or updates those flags (CSRF on PATCH; estimated age under 18 or missing `birth_year` cannot enable DMs or public chat). `GET /ws` on the full app authenticates via session cookie or `AuthTicket`, registers the seat on an in-process `PlayHub`, dispatches `QuickPair` / `QuickPairCancel`, `Move` (with Ping RTT into `LagTracker`), offer / resign / abort / claim / flag messages, and `ResumeGame` (`GameSnapshot` + `Replay`), and on terminal ends calls `persist_finished_from_redis` then `apply_rated_finish` before broadcasting `GameEnd`. Planned surfaces: expanding rating windows (CV-210), τ calibration (CV-220), tournaments, DM delivery (CV-281 uses `assert_can_send_dm`), mid-game Postgres flush (CV-180), multi-instance hub fan-out, and the wider HTTP API. Intended dependencies: PostgreSQL for durable data, Redis for live games and presence, chess-core for legality, and optional analysis via [engine](https://github.com/corvin-chess/engine). Fair-play review hooks are planned to consume the public [fairplay](https://github.com/corvin-chess/fairplay) library; private thresholds stay out of this repository. Outbound SMTP is not wired yet; OTP delivery uses a log sink unless tests inject a capture mailer. @@ -61,7 +61,7 @@ Redis presence (requires `REDIS_URL` from the same Compose stack): export REDIS_URL=redis://127.0.0.1:6379/0 ``` -Library helpers `touch_presence` / `is_online` / `clear_presence` use keys `corvin:presence:{user_id}` with a short TTL. Live game helpers `create_game` / `append_move_event` / `apply_move` / `apply_move_with_rtt` / `reconstruct_fen` / `claim_flag` / `check_flag` / `seed_lag_quotas` / `offer_draw` / `offer_takeback` / `respond_offer` / `resign` / `abort` / `claim_draw` use `corvin:game:{id}:meta` and `corvin:game:{id}:events` (replay reconstructs FEN; `apply_move` rejects illegal and wrong-turn moves and ticks clocks with injectable server `ts`; `apply_move_with_rtt` credits lag from a fake or measured RTT; `claim_flag` verifies PROTOCOL flag claims; offer helpers return `OfferState` or `GameEnd` and map rejects to `OFFER_INVALID` / `ABORT_DENIED`; `claim_draw` ends with `threefold` or `fifty` or rejects with `CLAIM_DENIED`; successful apply may auto-end with `fivefold` or `seventy_five`). Matchmaking helpers `quick_pair` / `quick_pair_cancel` / `take_pair_result` / `challenge_create_link` / `challenge_accept` / `challenge_decline` / `challenge_cancel` pair two players into a seated live game and return PROTOCOL `GameStart` (waiting peer notified via `corvin:pair:notify:{player_id}`; open links need `link_token` on accept). Rating helpers `apply_rated_finish` / `ensure_rating` / `get_rating` / `game_end_with_rating_diff` update Postgres `ratings` once per finished rated `game_id` (audit in `rating_updates`; casual and abort skip). Persist helpers `persist_finished_game` / `persist_finished_from_redis` / `export_pgn` / `render_pgn` write `games` + `game_events` once and rebuild standard tag-pair PGN (movetext matches chess-core `encode_movetext`). +Library helpers `touch_presence` / `is_online` / `clear_presence` use keys `corvin:presence:{user_id}` with a short TTL. Live game helpers `create_game` / `append_move_event` / `commit_apply_cas` / `apply_move` / `apply_move_with_rtt` / `reconstruct_fen` / `claim_flag` / `check_flag` / `seed_lag_quotas` / `offer_draw` / `offer_takeback` / `respond_offer` / `resign` / `abort` / `claim_draw` use `corvin:game:{id}:meta` and `corvin:game:{id}:events` (replay reconstructs FEN; `apply_move` rejects illegal and wrong-turn moves, ticks clocks with injectable server `ts`, and commits meta+Move via Lua CAS; `apply_move_with_rtt` credits lag from a fake or measured RTT; `claim_flag` verifies PROTOCOL flag claims; offer helpers return `OfferState` or `GameEnd` and map rejects to `OFFER_INVALID` / `ABORT_DENIED`; `claim_draw` ends with `threefold` or `fifty` or rejects with `CLAIM_DENIED`; successful apply may auto-end with `fivefold` or `seventy_five`). Matchmaking helpers `quick_pair` / `quick_pair_cancel` / `take_pair_result` / `challenge_create_link` / `challenge_accept` / `challenge_decline` / `challenge_cancel` pair two players into a seated live game and return PROTOCOL `GameStart` (waiting peer notified via `corvin:pair:notify:{player_id}`; open links need `link_token` on accept). Rating helpers `apply_rated_finish` / `ensure_rating` / `get_rating` / `game_end_with_rating_diff` update Postgres `ratings` once per finished rated `game_id` (audit in `rating_updates`; casual and abort skip). Persist helpers `persist_finished_game` / `persist_finished_from_redis` / `export_pgn` / `render_pgn` write `games` + `game_events` once and rebuild standard tag-pair PGN (movetext matches chess-core `encode_movetext`). WebSocket handshake (no Postgres required for the socket itself): @@ -77,7 +77,7 @@ WebSocket handshake (no Postgres required for the socket itself):

Development

-Edit `src/lib.rs` (router and `AppState`), `src/ws/` (PROTOCOL Hello/Welcome/Ping), `src/auth/` (email OTP, passkeys, sessions, mailer), `src/safety/` (age defaults and DM gate), `src/account/` (messaging prefs), `src/api/` (finished-game HTTP), `src/db.rs` (pool and migrate up/down), `src/redis_store.rs` (Redis connect and presence keys), `src/game/` (append-only game event log, FEN replay, legal `apply_move`, clocks with Fischer increment and flag, lag quota, draw/takeback/resign/abort offers, threefold/fifty claims and fivefold/seventy-five auto draws, Postgres persist and PGN export), `src/matchmaking/` (quick pair Redis pools, challenge links, `GameStart`), `src/rating/` (Glicko-2 math, Postgres ratings, once-only `apply_rated_finish`), `src/main.rs` (bind, graceful shutdown, migrate CLI), and SQL under `migrations/`. Local Postgres and Redis from [infra](https://github.com/corvin-chess/infra) supply `DATABASE_URL` / `REDIS_URL`. Secrets and fair-play private configuration never live in this repository. +Edit `src/lib.rs` (router and `AppState`), `src/ws/` (PROTOCOL Hello/Welcome/Ping), `src/auth/` (email OTP, passkeys, sessions, mailer), `src/safety/` (age defaults and DM gate), `src/account/` (messaging prefs), `src/api/` (finished-game HTTP), `src/db.rs` (pool and migrate up/down), `src/redis_store.rs` (Redis connect and presence keys), `src/game/` (append-only game event log, FEN replay, legal `apply_move` with Lua/CAS commit, clocks with Fischer increment and flag, lag quota, draw/takeback/resign/abort offers, threefold/fifty claims and fivefold/seventy-five auto draws, Postgres persist and PGN export), `src/matchmaking/` (quick pair Redis pools, challenge links, `GameStart`), `src/rating/` (Glicko-2 math, Postgres ratings, once-only `apply_rated_finish`), `src/main.rs` (bind, graceful shutdown, migrate CLI), and SQL under `migrations/`. Local Postgres and Redis from [infra](https://github.com/corvin-chess/infra) supply `DATABASE_URL` / `REDIS_URL`. Secrets and fair-play private configuration never live in this repository. @@ -96,7 +96,7 @@ node scripts/verify-dockerfile.mjs Compose builds this image from the repository root `Dockerfile` (migrate-on-start entrypoint, `GET /health` on port 3000). -`tests/protocol_contract.rs` loads golden JSON under `tests/fixtures/protocol/` (manifest + Hello/Welcome/Ping/Pong/Error, MoveApplied, MoveRejected, ClockSync, OfferState, GameEnd, GameStart, Challenge), asserts required keys and the PROTOCOL.md error-code set, and compares public JSON builders to fixture shapes (handshake wire behavior stays covered by `tests/ws_hello.rs`; always-on; no Redis/Postgres). `tests/health.rs` asserts `/health` returns 200 with body `ok\n` and unknown paths return 404. `tests/ws_hello.rs` binds a local listener and contracts `Hello`/`Welcome`/`Ping`/`Pong` plus `PROTO_VERSION` against PROTOCOL.md (no Postgres). `tests/ws_play.rs` asserts `GameSnapshot` shape always-on and, when `DATABASE_URL` and `REDIS_URL` are set, two authenticated sockets quick-pair, play `e2e4`, and resign to a PROTOCOL `GameEnd`. `tests/migrations.rs` asserts paired up/down SQL and, when `DATABASE_URL` is set, applies migrate up/down against Postgres including `passkeys` / `email_otps` and messaging flags (CI runs Postgres 16). `tests/presence.rs` asserts presence key shape and, when `REDIS_URL` is set, PING plus touch/clear/TTL expiry against Redis (CI runs Redis 7). `tests/game_event_log.rs` asserts FEN replay for a known opening line always-on and, when `REDIS_URL` is set, create/append/reconstruct against Redis. `tests/move_apply.rs` asserts PROTOCOL `MoveApplied` / `MoveRejected` JSON shapes always-on and, when `REDIS_URL` is set, legal apply plus `ILLEGAL_MOVE` / `NOT_YOUR_TURN` / `AUTH` / `GAME_GONE` rejects. `tests/clocks.rs` asserts injectable clock math (deduct then Fischer increment; flag before increment), PROTOCOL `ClockSync` / `GameEnd` shapes, and when `REDIS_URL` is set, persisted tick on `apply_move`, flag-on-apply, and `claim_flag` verification. `tests/lag_quota.rs` asserts interim quota bounds, EWMA one-way math, PROTOCOL optional `lag_comp_ms`, and when `REDIS_URL` is set, fake-RTT credit/deplete plus lag preventing a false flag. `tests/offers.rs` asserts ADR-005 abort windows, PROTOCOL `OfferState` / `GameEnd` / `OFFER_INVALID` / `ABORT_DENIED` shapes, and when `REDIS_URL` is set, draw accept/decline/withdraw/counter-offer, resign, abort (0–1 ply window), takeback FEN+clock restore, and auth rejects. `tests/draw_claims.rs` asserts PROTOCOL `GameEnd` reasons `threefold` / `fifty` / `fivefold` / `seventy_five` and `CLAIM_DENIED`, and when `REDIS_URL` is set, fifty and threefold claims by side to move, deny paths, and fivefold / seventy-five auto ends on apply. `tests/matchmaking.rs` asserts PROTOCOL `GameStart` / `Challenge` shapes always-on and, when `REDIS_URL` / `DATABASE_URL` are set, two-client quick pair, cancel, challenge link accept, decline/cancel, and self-accept reject. `tests/glicko2.rs` asserts the Glickman paper worked example (τ=0.5) plus ADR-007 defaults and provisional RD. `tests/ratings.rs` asserts PROTOCOL `rating_diff` shape always-on and, when `DATABASE_URL` is set, rated finish changes both rating rows once, returns `AlreadyApplied` on repeat, and skips casual/abort. `tests/persist_game.rs` asserts PGN movetext matches chess-core `encode_movetext` always-on and, when `DATABASE_URL` is set, once-only `persist_finished_game`, `export_pgn` parity, and `GET /api/v1/games/{id}/pgn` (Redis path when `REDIS_URL` is set). `tests/auth_email_otp.rs` and `tests/auth_passkey.rs` exercise register/login e2e when `DATABASE_URL` is set (capture mailer; SoftPasskey). `tests/session_csrf.rs` asserts cookie attribute matrix always-on and, when `DATABASE_URL` is set, CSRF-bound logout plus session probe security tests. `tests/age_defaults.rs` asserts under-18 / missing birth year default DMs off, adults can toggle via `/api/v1/account/messaging`, and minors cannot enable messaging. Compose stack image wiring and multi-instance hub fan-out land with later tasks. +`tests/protocol_contract.rs` loads golden JSON under `tests/fixtures/protocol/` (manifest + Hello/Welcome/Ping/Pong/Error, MoveApplied, MoveRejected, ClockSync, OfferState, GameEnd, GameStart, Challenge), asserts required keys and the PROTOCOL.md error-code set, and compares public JSON builders to fixture shapes (handshake wire behavior stays covered by `tests/ws_hello.rs`; always-on; no Redis/Postgres). `tests/health.rs` asserts `/health` returns 200 with body `ok\n` and unknown paths return 404. `tests/ws_hello.rs` binds a local listener and contracts `Hello`/`Welcome`/`Ping`/`Pong` plus `PROTO_VERSION` against PROTOCOL.md (no Postgres). `tests/ws_play.rs` asserts `GameSnapshot` shape always-on and, when `DATABASE_URL` and `REDIS_URL` are set, two authenticated sockets quick-pair, play `e2e4`, and resign to a PROTOCOL `GameEnd`. `tests/migrations.rs` asserts paired up/down SQL and, when `DATABASE_URL` is set, applies migrate up/down against Postgres including `passkeys` / `email_otps` and messaging flags (CI runs Postgres 16). `tests/presence.rs` asserts presence key shape and, when `REDIS_URL` is set, PING plus touch/clear/TTL expiry against Redis (CI runs Redis 7). `tests/game_event_log.rs` asserts FEN replay for a known opening line always-on and, when `REDIS_URL` is set, create/append/reconstruct against Redis. `tests/move_apply.rs` asserts PROTOCOL `MoveApplied` / `MoveRejected` JSON shapes always-on and, when `REDIS_URL` is set, legal apply plus `ILLEGAL_MOVE` / `NOT_YOUR_TURN` / `AUTH` / `GAME_GONE` rejects. `tests/atomic_apply.rs` asserts Lua CAS reply parsing always-on and, when `REDIS_URL` is set, concurrent identical or racing white UCIs leave exactly one Move event. `tests/clocks.rs` asserts injectable clock math (deduct then Fischer increment; flag before increment), PROTOCOL `ClockSync` / `GameEnd` shapes, and when `REDIS_URL` is set, persisted tick on `apply_move`, flag-on-apply, and `claim_flag` verification. `tests/lag_quota.rs` asserts interim quota bounds, EWMA one-way math, PROTOCOL optional `lag_comp_ms`, and when `REDIS_URL` is set, fake-RTT credit/deplete plus lag preventing a false flag. `tests/offers.rs` asserts ADR-005 abort windows, PROTOCOL `OfferState` / `GameEnd` / `OFFER_INVALID` / `ABORT_DENIED` shapes, and when `REDIS_URL` is set, draw accept/decline/withdraw/counter-offer, resign, abort (0–1 ply window), takeback FEN+clock restore, and auth rejects. `tests/draw_claims.rs` asserts PROTOCOL `GameEnd` reasons `threefold` / `fifty` / `fivefold` / `seventy_five` and `CLAIM_DENIED`, and when `REDIS_URL` is set, fifty and threefold claims by side to move, deny paths, and fivefold / seventy-five auto ends on apply. `tests/matchmaking.rs` asserts PROTOCOL `GameStart` / `Challenge` shapes always-on and, when `REDIS_URL` / `DATABASE_URL` are set, two-client quick pair, cancel, challenge link accept, decline/cancel, and self-accept reject. `tests/glicko2.rs` asserts the Glickman paper worked example (τ=0.5) plus ADR-007 defaults and provisional RD. `tests/ratings.rs` asserts PROTOCOL `rating_diff` shape always-on and, when `DATABASE_URL` is set, rated finish changes both rating rows once, returns `AlreadyApplied` on repeat, and skips casual/abort. `tests/persist_game.rs` asserts PGN movetext matches chess-core `encode_movetext` always-on and, when `DATABASE_URL` is set, once-only `persist_finished_game`, `export_pgn` parity, and `GET /api/v1/games/{id}/pgn` (Redis path when `REDIS_URL` is set). `tests/auth_email_otp.rs` and `tests/auth_passkey.rs` exercise register/login e2e when `DATABASE_URL` is set (capture mailer; SoftPasskey). `tests/session_csrf.rs` asserts cookie attribute matrix always-on and, when `DATABASE_URL` is set, CSRF-bound logout plus session probe security tests. `tests/age_defaults.rs` asserts under-18 / missing birth year default DMs off, adults can toggle via `/api/v1/account/messaging`, and minors cannot enable messaging. Compose stack image wiring and multi-instance hub fan-out land with later tasks. @@ -104,7 +104,7 @@ Compose builds this image from the repository root `Dockerfile` (migrate-on-star

Architecture

-Binary crate `corvin-server`: `src/lib.rs` owns the Axum router and `AppState` (Postgres, optional Redis, `PlayHub`); `src/ws/` implements PROTOCOL connection lifecycle plus play dispatch on `/ws` (`Hello`/`Welcome`/`Ping`/`Pong`, cookie/`AuthTicket`, `QuickPair`, `Move`, offers, resign/abort/claim/flag, `ResumeGame` → `GameSnapshot`/`Replay`, hub fan-out, finish persist + rating); `src/auth/` implements PROTOCOL auth paths with `webauthn-rs` and hashed email OTPs; `src/safety/` owns age-based messaging defaults and `assert_can_send_dm`; `src/account/` serves messaging preference GET/PATCH; `src/api/` serves finished-game `GET /api/v1/games/{id}` and `GET /api/v1/games/{id}/pgn`; `src/db.rs` embeds reversible sqlx migrations and exposes `migrate_up` / `migrate_down`; `src/redis_store.rs` opens a Redis connection manager from `REDIS_URL` and owns presence key helpers; `src/game/` owns live game meta, append-only event lists in Redis, FEN reconstruction, legal `apply_move` (PROTOCOL `MoveApplied` / `MoveRejected`), clocks (`src/game/clock.rs`: Fischer tick, `claim_flag`, `ClockSync` / `GameEnd`), lag compensation (`src/game/lag.rs`: EWMA RTT, quota, credit), offers (`src/game/offers.rs`: draw/takeback/resign/abort state machine), draw claims (`src/game/claims.rs`: threefold/fifty claim + fivefold/seventy-five auto), and durable persist/PGN (`src/game/persist.rs`, `src/game/pgn.rs`) via `corvin-chess-core`; `src/matchmaking/` owns Redis quick-pair pools and Postgres challenge links that create seated games and PROTOCOL `GameStart`; `src/rating/` owns Glicko-2 math (`glicko2.rs`) and once-only Postgres finish updates (`apply_rated_finish`); `src/main.rs` binds `HOST`/`PORT`, requires `DATABASE_URL` and `REDIS_URL`, and serves with graceful shutdown, or runs `migrate up|down` when those args are passed. Planned: multi-instance hub fan-out, expanding rating windows, tournaments. Server is authoritative for game state and clocks; clients reconcile to protocol events. See organization ADRs and [website](https://github.com/corvin-chess/website) once docs are published. +Binary crate `corvin-server`: `src/lib.rs` owns the Axum router and `AppState` (Postgres, optional Redis, `PlayHub`); `src/ws/` implements PROTOCOL connection lifecycle plus play dispatch on `/ws` (`Hello`/`Welcome`/`Ping`/`Pong`, cookie/`AuthTicket`, `QuickPair`, `Move`, offers, resign/abort/claim/flag, `ResumeGame` → `GameSnapshot`/`Replay`, hub fan-out, finish persist + rating); `src/auth/` implements PROTOCOL auth paths with `webauthn-rs` and hashed email OTPs; `src/safety/` owns age-based messaging defaults and `assert_can_send_dm`; `src/account/` serves messaging preference GET/PATCH; `src/api/` serves finished-game `GET /api/v1/games/{id}` and `GET /api/v1/games/{id}/pgn`; `src/db.rs` embeds reversible sqlx migrations and exposes `migrate_up` / `migrate_down`; `src/redis_store.rs` opens a Redis connection manager from `REDIS_URL` and owns presence key helpers; `src/game/` owns live game meta, append-only event lists in Redis, FEN reconstruction, legal `apply_move` with Lua/CAS commit (PROTOCOL `MoveApplied` / `MoveRejected`), clocks (`src/game/clock.rs`: Fischer tick, `claim_flag`, `ClockSync` / `GameEnd`), lag compensation (`src/game/lag.rs`: EWMA RTT, quota, credit), offers (`src/game/offers.rs`: draw/takeback/resign/abort state machine), draw claims (`src/game/claims.rs`: threefold/fifty claim + fivefold/seventy-five auto), and durable persist/PGN (`src/game/persist.rs`, `src/game/pgn.rs`) via `corvin-chess-core`; `src/matchmaking/` owns Redis quick-pair pools and Postgres challenge links that create seated games and PROTOCOL `GameStart`; `src/rating/` owns Glicko-2 math (`glicko2.rs`) and once-only Postgres finish updates (`apply_rated_finish`); `src/main.rs` binds `HOST`/`PORT`, requires `DATABASE_URL` and `REDIS_URL`, and serves with graceful shutdown, or runs `migrate up|down` when those args are passed. Planned: multi-instance hub fan-out, expanding rating windows, tournaments. Server is authoritative for game state and clocks; clients reconcile to protocol events. See organization ADRs and [website](https://github.com/corvin-chess/website) once docs are published. @@ -124,6 +124,7 @@ Binary crate `corvin-server`: `src/lib.rs` owns the Axum router and `AppState` ( | WS Hello/Welcome/Ping | Built | | Game event log | Built | | Move apply | Built | +| Atomic apply | Built | | Clocks | Built | | Lag compensation | Built | | Offers | Built | diff --git a/scripts/verify-readme.mjs b/scripts/verify-readme.mjs index a6906e9..57ac743 100644 --- a/scripts/verify-readme.mjs +++ b/scripts/verify-readme.mjs @@ -23,7 +23,7 @@ const CLOSING = const PLANNED_AREAS = /^(Implementation)$/i const BUILT_AREAS = - /^(README|Axum scaffold|Postgres migrations|Redis presence|Auth|Session cookies \/ CSRF|Age-appropriate defaults|WS Hello\/Welcome\/Ping|Game event log|Move apply|Clocks|Lag compensation|Offers|Draw claims|Matchmaking|Ratings|Finished game persist|Protocol contract fixtures|Play protocol \/ WS|Docker image)$/i + /^(README|Axum scaffold|Postgres migrations|Redis presence|Auth|Session cookies \/ CSRF|Age-appropriate defaults|WS Hello\/Welcome\/Ping|Game event log|Move apply|Atomic apply|Clocks|Lag compensation|Offers|Draw claims|Matchmaking|Ratings|Finished game persist|Protocol contract fixtures|Play protocol \/ WS|Docker image)$/i const fail = (msg) => { console.error(`FAIL: ${msg}`) diff --git a/src/game/apply.rs b/src/game/apply.rs index 0bd11f1..8f62b92 100644 --- a/src/game/apply.rs +++ b/src/game/apply.rs @@ -2,6 +2,7 @@ //! Clocks tick + Fischer increment + flag-before-increment (CV-163 / ADR-005). //! Lag compensation from server-measured RTT (CV-164); never trusts client send time. //! Fivefold / seventy-five auto draws after a successful ply (CV-166). +//! Redis Lua CAS commit so concurrent apply cannot double-append (CV-171). use std::fmt; @@ -9,19 +10,22 @@ use corvin_chess_core::{Color, Move, UciError}; use redis::aio::ConnectionManager; use serde_json::{json, Value}; -use super::claims::{auto_draw_reason, position_with_prior_keys, record_auto_draw}; +use super::claims::{auto_draw_reason, position_with_prior_keys}; use super::clock::{ flag_outcome_for_position, is_flagged_at_compensated, tick_meta_on_move_compensated, write_flag_to_meta, write_tick_to_meta, ClockPair, ClockTick, FlagOutcome, }; +use super::events::GameEvent; use super::lag::{credit_lag, LagCredit}; use super::offers::GameEndOut; use super::store::{ - append_move_event, load_events, load_meta, save_meta, GameLogError, MAX_PLAYER_ID_LEN, - MAX_UCI_LEN, + commit_apply_cas, commit_meta_cas, load_events, load_meta, CasCommitResult, GameLogError, + MAX_PLAYER_ID_LEN, MAX_UCI_LEN, }; const PROTOCOL_V: u32 = 1; +/// Bounded CAS retries when another writer wins the event-length race. +const MAX_CAS_RETRIES: u32 = 8; /// Successful apply payload fields (PROTOCOL `MoveApplied` body). #[derive(Clone, Debug, PartialEq, Eq)] @@ -71,6 +75,8 @@ pub enum ApplyError { Flagged { outcome: FlagOutcome, }, + /// CAS lost the event-length race; apply retries internally before surfacing. + Conflict, InvalidUci(UciError), Corrupt(String), TooManyEvents, @@ -86,7 +92,11 @@ impl ApplyError { Self::GameGone => Some(MoveRejectCode::GameGone), Self::Auth => Some(MoveRejectCode::Auth), // Flag mid-apply is GameEnd, not MoveRejected. Storage faults → Error INTERNAL. - Self::Flagged { .. } | Self::Corrupt(_) | Self::TooManyEvents | Self::Redis(_) => None, + Self::Flagged { .. } + | Self::Conflict + | Self::Corrupt(_) + | Self::TooManyEvents + | Self::Redis(_) => None, } } } @@ -99,6 +109,7 @@ impl fmt::Display for ApplyError { Self::GameGone => write!(f, "game not found"), Self::Auth => write!(f, "not a player in this game"), Self::Flagged { outcome } => write!(f, "flagged: {}", outcome.flagged), + Self::Conflict => write!(f, "apply conflict (CAS)"), Self::InvalidUci(err) => write!(f, "invalid UCI: {err}"), Self::Corrupt(detail) => write!(f, "corrupt game state: {detail}"), Self::TooManyEvents => write!(f, "game event log exceeds max length"), @@ -190,7 +201,7 @@ pub fn move_rejected_json(id: &str, code: MoveRejectCode, message: &str) -> Valu /// /// Deducts elapsed think time from the mover, adds Fischer `increment_ms`, then /// starts the opponent clock at `ts`. Flags before increment (ADR-005). -/// Single-writer per game is assumed; concurrent apply needs Lua/CAS (CV-171). +/// Commits via Redis Lua CAS on event length (CV-171). pub async fn apply_move( conn: &mut ConnectionManager, game_id: &str, @@ -219,6 +230,53 @@ pub async fn apply_move_with_rtt( return Err(ApplyError::InvalidUci(UciError::Invalid)); } + for attempt in 0..MAX_CAS_RETRIES { + match try_apply_once(conn, game_id, player_id, uci, ts, rtt_ms).await { + Ok(applied) => return Ok(applied), + Err(ApplyError::Conflict) if attempt + 1 < MAX_CAS_RETRIES => continue, + Err(ApplyError::Conflict) => { + // Last resort: map exhausted CAS races to a client reject, not INTERNAL. + return resolve_exhausted_conflict(conn, game_id, player_id).await; + } + Err(err) => return Err(err), + } + } + resolve_exhausted_conflict(conn, game_id, player_id).await +} + +async fn resolve_exhausted_conflict( + conn: &mut ConnectionManager, + game_id: &str, + player_id: &str, +) -> Result { + let meta = load_meta(conn, game_id).await?; + if meta.ended { + return Err(ApplyError::GameGone); + } + let events = load_events(conn, game_id).await?; + let (pos, _) = position_with_prior_keys(&meta.initial_fen, &events) + .map_err(|err| ApplyError::Corrupt(err.to_string()))?; + let seat = if player_id == meta.white_id { + Color::White + } else if player_id == meta.black_id { + Color::Black + } else { + return Err(ApplyError::Auth); + }; + if pos.side_to_move() != seat { + return Err(ApplyError::NotYourTurn); + } + Err(ApplyError::Conflict) +} + +async fn try_apply_once( + conn: &mut ConnectionManager, + game_id: &str, + player_id: &str, + uci: &str, + ts: u64, + rtt_ms: Option, +) -> Result { let mut meta = load_meta(conn, game_id).await?; if meta.ended { return Err(ApplyError::GameGone); @@ -236,6 +294,7 @@ pub async fn apply_move_with_rtt( }; let events = load_events(conn, game_id).await?; + let expected_len = events.len() as u64; // Same walk as FEN replay, but keep prior repetition keys for post-ply auto draws. let (pos, prior) = position_with_prior_keys(&meta.initial_fen, &events) .map_err(|err| ApplyError::Corrupt(err.to_string()))?; @@ -283,8 +342,14 @@ pub async fn apply_move_with_rtt( write_flag_to_meta(&mut meta, color, &zeroed); meta.pending_offer = None; meta.ended_reason = Some(format!("flag:{}", outcome.result)); - save_meta(conn, game_id, &meta).await?; - return Err(ApplyError::Flagged { outcome }); + // CAS meta-only so a concurrent ply cannot be overwritten by stale flag meta. + match commit_meta_cas(conn, game_id, expected_len, &meta).await? { + CasCommitResult::Ok { .. } => return Err(ApplyError::Flagged { outcome }), + CasCommitResult::Conflict { .. } => return Err(ApplyError::Conflict), + CasCommitResult::Gone => return Err(ApplyError::GameGone), + CasCommitResult::TooManyEvents => return Err(ApplyError::TooManyEvents), + CasCommitResult::Corrupt(detail) => return Err(ApplyError::Corrupt(detail)), + } } // Legality before clock commit so illegal attempts do not mutate Redis clocks. @@ -318,8 +383,13 @@ pub async fn apply_move_with_rtt( write_flag_to_meta(&mut meta, color, &clocks); meta.pending_offer = None; meta.ended_reason = Some(format!("flag:{}", outcome.result)); - save_meta(conn, game_id, &meta).await?; - return Err(ApplyError::Flagged { outcome }); + match commit_meta_cas(conn, game_id, expected_len, &meta).await? { + CasCommitResult::Ok { .. } => return Err(ApplyError::Flagged { outcome }), + CasCommitResult::Conflict { .. } => return Err(ApplyError::Conflict), + CasCommitResult::Gone => return Err(ApplyError::GameGone), + CasCommitResult::TooManyEvents => return Err(ApplyError::TooManyEvents), + CasCommitResult::Corrupt(detail) => return Err(ApplyError::Corrupt(detail)), + } } ClockTick::Applied(pair) => { write_tick_to_meta(&mut meta, &pair); @@ -346,8 +416,8 @@ pub async fn apply_move_with_rtt( let mut prior_for_next = prior; prior_for_next.push(pos.repetition_key()); - // Detect auto-draw before Redis writes so meta.ended is set with the clock save - // (a failed AutoDraw append must not leave a live fivefold/seventy-five game). + // Detect auto-draw before Redis writes so meta.ended is set with the Move CAS + // (Move + AutoDraw share one Lua script; no live fivefold/seventy-five gap). let auto_reason = auto_draw_reason(&next, &prior_for_next); if let Some(reason) = auto_reason { meta.pending_offer = None; @@ -356,30 +426,51 @@ pub async fn apply_move_with_rtt( meta.active_started_ms = 0; } - // Persist clocks before the ply so a failed RPUSH does not leave an orphan move - // with stale clocks; a failed append after save leaves clocks ahead of the board - // (recoverable by CV-171 atomic apply). Prefer that over move-without-clocks. - save_meta(conn, game_id, &meta).await?; - let seq = append_move_event(conn, game_id, uci, ts).await?; - - let auto_draw = match auto_reason { - Some(reason) => Some( - record_auto_draw(conn, game_id, reason, ts) - .await - .map_err(|err| ApplyError::Corrupt(err.to_string()))?, - ), - None => None, - }; + let move_seq = expected_len + 1; + let move_event = GameEvent::move_uci(move_seq, uci, ts); + let auto_event = auto_reason.map(|reason| GameEvent::AutoDraw { + seq: move_seq + 1, + kind: reason.to_owned(), + ts, + }); - Ok(AppliedMove { - uci: uci.to_owned(), - san, - fen: next_fen, - clock_w_ms: meta.clock_w_ms, - clock_b_ms: meta.clock_b_ms, - active: color_active(next.side_to_move()), - seq, - lag_comp_ms: if lag_comp > 0 { Some(lag_comp) } else { None }, - auto_draw, - }) + // Atomic SET meta + RPUSH Move (+ AutoDraw): concurrent apply loses CAS, retries. + let cas = commit_apply_cas( + conn, + game_id, + expected_len, + &meta, + &move_event, + auto_event.as_ref(), + ) + .await?; + + match cas { + CasCommitResult::Ok { + move_seq: seq, + last_seq, + } => { + let auto_draw = auto_reason.map(|reason| GameEndOut { + result: "1/2-1/2", + winner: None, + reason, + seq: last_seq, + }); + Ok(AppliedMove { + uci: uci.to_owned(), + san, + fen: next_fen, + clock_w_ms: meta.clock_w_ms, + clock_b_ms: meta.clock_b_ms, + active: color_active(next.side_to_move()), + seq, + lag_comp_ms: if lag_comp > 0 { Some(lag_comp) } else { None }, + auto_draw, + }) + } + CasCommitResult::Conflict { .. } => Err(ApplyError::Conflict), + CasCommitResult::Gone => Err(ApplyError::GameGone), + CasCommitResult::TooManyEvents => Err(ApplyError::TooManyEvents), + CasCommitResult::Corrupt(detail) => Err(ApplyError::Corrupt(detail)), + } } diff --git a/src/game/mod.rs b/src/game/mod.rs index 0e4fc9d..944c889 100644 --- a/src/game/mod.rs +++ b/src/game/mod.rs @@ -7,6 +7,7 @@ //! Draw / takeback / resign / abort: CV-165. //! Threefold / fifty claims + fivefold / seventy-five auto: CV-166. //! Finished-game Postgres persist + PGN export: CV-169. +//! Atomic apply_move Lua/CAS: CV-171. mod apply; mod claims; @@ -50,7 +51,8 @@ pub use persist::{ pub use pgn::{movetext_from_events, render_pgn, PgnExportError}; pub use replay::{net_move_events, replay_fen}; pub use store::{ - append_game_event, append_move_event, create_game, delete_game, game_events_key, game_meta_key, - load_events, load_meta, reconstruct_fen, save_meta, GameLogError, GAME_KEY_PREFIX, MAX_EVENTS, + append_game_event, append_move_event, commit_apply_cas, commit_meta_cas, create_game, + delete_game, game_events_key, game_meta_key, load_events, load_meta, parse_cas_commit_reply, + reconstruct_fen, save_meta, CasCommitResult, GameLogError, GAME_KEY_PREFIX, MAX_EVENTS, MAX_EVENT_BYTES, MAX_FEN_LEN, MAX_GAME_ID_LEN, MAX_META_BYTES, MAX_PLAYER_ID_LEN, MAX_UCI_LEN, }; diff --git a/src/game/store.rs b/src/game/store.rs index 84762f4..da48c39 100644 --- a/src/game/store.rs +++ b/src/game/store.rs @@ -208,11 +208,186 @@ pub async fn save_meta( Ok(()) } +/// Outcome of the apply CAS Lua script (CV-171). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CasCommitResult { + Ok { move_seq: u64, last_seq: u64 }, + Conflict { actual_len: u64 }, + Gone, + TooManyEvents, + Corrupt(String), +} + +/// Parse the integer vector returned by `commit_apply_cas` Lua. +pub fn parse_cas_commit_reply(reply: &[i64]) -> CasCommitResult { + match reply { + // move_seq may be 0 for meta-only CAS when the event list is still empty. + [1, move_seq, last_seq] if *move_seq >= 0 && *last_seq >= *move_seq => { + CasCommitResult::Ok { + move_seq: *move_seq as u64, + last_seq: *last_seq as u64, + } + } + [0, actual] if *actual >= 0 => CasCommitResult::Conflict { + actual_len: *actual as u64, + }, + [-1] => CasCommitResult::Gone, + [-2] => CasCommitResult::TooManyEvents, + _ => CasCommitResult::Corrupt("unexpected CAS reply".into()), + } +} + +/// Lua: CAS on event list length, then SET meta + RPUSH move (+ optional auto-draw). +/// +/// KEYS[1]=meta KEYS[2]=events +/// ARGV[1]=expected_len ARGV[2]=max_events ARGV[3]=meta_json ARGV[4]=move_json +/// ARGV[5]=auto_json or empty +const COMMIT_APPLY_CAS_LUA: &str = r#" +local expected = tonumber(ARGV[1]) +local max_events = tonumber(ARGV[2]) +if redis.call('EXISTS', KEYS[1]) == 0 then + return {-1} +end +local len = redis.call('LLEN', KEYS[2]) +if len ~= expected then + return {0, len} +end +local add = 1 +if ARGV[5] ~= '' then + add = 2 +end +if len + add > max_events then + return {-2} +end +redis.call('SET', KEYS[1], ARGV[3]) +redis.call('RPUSH', KEYS[2], ARGV[4]) +local move_seq = len + 1 +local last_seq = move_seq +if ARGV[5] ~= '' then + redis.call('RPUSH', KEYS[2], ARGV[5]) + last_seq = move_seq + 1 +end +return {1, move_seq, last_seq} +"#; + +/// Atomically commit an applied ply: meta + Move event (+ optional AutoDraw). +/// +/// Fails with `CasCommitResult::Conflict` when another writer already appended +/// since `expected_len` was observed (callers retry after re-validation). +pub async fn commit_apply_cas( + conn: &mut ConnectionManager, + game_id: &str, + expected_len: u64, + meta: &GameMeta, + move_event: &GameEvent, + auto_event: Option<&GameEvent>, +) -> Result { + let (meta_key, events_key) = require_keys(game_id)?; + if meta.initial_fen.len() > MAX_FEN_LEN || meta.initial_fen.is_empty() { + return Err(GameLogError::CorruptEvent( + "meta initial_fen out of bounds".into(), + )); + } + if meta.white_id.len() > MAX_PLAYER_ID_LEN || meta.black_id.len() > MAX_PLAYER_ID_LEN { + return Err(GameLogError::CorruptEvent( + "seat id exceeds max length".into(), + )); + } + let meta_payload = + serde_json::to_string(meta).map_err(|err| GameLogError::CorruptEvent(err.to_string()))?; + if meta_payload.len() > MAX_META_BYTES { + return Err(GameLogError::CorruptEvent("meta payload too large".into())); + } + let move_payload = serde_json::to_string(move_event) + .map_err(|err| GameLogError::CorruptEvent(err.to_string()))?; + if move_payload.len() > MAX_EVENT_BYTES { + return Err(GameLogError::CorruptEvent("event payload too large".into())); + } + let auto_payload = match auto_event { + Some(ev) => { + let raw = serde_json::to_string(ev) + .map_err(|err| GameLogError::CorruptEvent(err.to_string()))?; + if raw.len() > MAX_EVENT_BYTES { + return Err(GameLogError::CorruptEvent("event payload too large".into())); + } + raw + } + None => String::new(), + }; + + let reply: Vec = redis::Script::new(COMMIT_APPLY_CAS_LUA) + .key(meta_key) + .key(events_key) + .arg(expected_len) + .arg(MAX_EVENTS as u64) + .arg(meta_payload) + .arg(move_payload) + .arg(auto_payload) + .invoke_async(conn) + .await?; + + Ok(parse_cas_commit_reply(&reply)) +} + +/// Lua: CAS on event list length, then SET meta only (flag / terminal without a ply). +/// +/// KEYS[1]=meta KEYS[2]=events +/// ARGV[1]=expected_len ARGV[2]=meta_json +const COMMIT_META_CAS_LUA: &str = r#" +local expected = tonumber(ARGV[1]) +if redis.call('EXISTS', KEYS[1]) == 0 then + return {-1} +end +local len = redis.call('LLEN', KEYS[2]) +if len ~= expected then + return {0, len} +end +redis.call('SET', KEYS[1], ARGV[2]) +return {1, len, len} +"#; + +/// Atomically write meta only when the event list length still matches `expected_len`. +/// +/// Used for flag termination so a concurrent move CAS cannot be overwritten by a +/// stale `save_meta` after the ply already committed. +pub async fn commit_meta_cas( + conn: &mut ConnectionManager, + game_id: &str, + expected_len: u64, + meta: &GameMeta, +) -> Result { + let (meta_key, events_key) = require_keys(game_id)?; + if meta.initial_fen.len() > MAX_FEN_LEN || meta.initial_fen.is_empty() { + return Err(GameLogError::CorruptEvent( + "meta initial_fen out of bounds".into(), + )); + } + if meta.white_id.len() > MAX_PLAYER_ID_LEN || meta.black_id.len() > MAX_PLAYER_ID_LEN { + return Err(GameLogError::CorruptEvent( + "seat id exceeds max length".into(), + )); + } + let meta_payload = + serde_json::to_string(meta).map_err(|err| GameLogError::CorruptEvent(err.to_string()))?; + if meta_payload.len() > MAX_META_BYTES { + return Err(GameLogError::CorruptEvent("meta payload too large".into())); + } + + let reply: Vec = redis::Script::new(COMMIT_META_CAS_LUA) + .key(meta_key) + .key(events_key) + .arg(expected_len) + .arg(meta_payload) + .invoke_async(conn) + .await?; + + Ok(parse_cas_commit_reply(&reply)) +} + /// Append any game event; assigns monotonic `seq` (1-based list length) and returns it. /// /// Pass `seq: 0` on the event; the stored value is overwritten with the list length. -/// Assumes single-writer ownership per game (live match node). Concurrent -/// appenders can race LLEN/RPUSH; CV-171 can tighten with a Lua script. +/// Non-apply paths still use LLEN then RPUSH; move apply uses `commit_apply_cas` (CV-171). pub async fn append_game_event( conn: &mut ConnectionManager, game_id: &str, diff --git a/tests/atomic_apply.rs b/tests/atomic_apply.rs new file mode 100644 index 0000000..03658c7 --- /dev/null +++ b/tests/atomic_apply.rs @@ -0,0 +1,192 @@ +//! CV-171: Atomic apply_move Lua/CAS — concurrent apply cannot double-append. + +use std::env; +use std::sync::Arc; + +use corvin_server::game::{ + apply_move, create_game, delete_game, load_events, parse_cas_commit_reply, reconstruct_fen, + ApplyError, CasCommitResult, GameMeta, START_FEN, +}; +use corvin_server::redis_store::connect; +use redis::aio::ConnectionManager; +use tokio::sync::Barrier; + +const AFTER_E4: &str = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1"; +const AFTER_D4: &str = "rnbqkbnr/pppppppp/8/8/3P4/8/PPP1PPPP/RNBQKBNR b KQkq d3 0 1"; +const WHITE: &str = "player-white-ulid-cv171-0001"; +const BLACK: &str = "player-black-ulid-cv171-0001"; + +fn redis_url() -> Option { + env::var("REDIS_URL") + .ok() + .map(|value| value.trim().to_owned()) + .filter(|value| !value.is_empty()) +} + +fn seated_meta() -> GameMeta { + GameMeta { + initial_fen: START_FEN.to_owned(), + created_ms: 1_730_000_000_000, + white_id: WHITE.to_owned(), + black_id: BLACK.to_owned(), + clock_w_ms: 300_000, + clock_b_ms: 300_000, + ..GameMeta::default() + } +} + +#[test] +fn cas_commit_reply_parsing() { + assert_eq!( + parse_cas_commit_reply(&[1, 0, 0]), + CasCommitResult::Ok { + move_seq: 0, + last_seq: 0 + } + ); + assert_eq!( + parse_cas_commit_reply(&[1, 5, 5]), + CasCommitResult::Ok { + move_seq: 5, + last_seq: 5 + } + ); + assert_eq!( + parse_cas_commit_reply(&[1, 3, 4]), + CasCommitResult::Ok { + move_seq: 3, + last_seq: 4 + } + ); + assert_eq!( + parse_cas_commit_reply(&[0, 2]), + CasCommitResult::Conflict { actual_len: 2 } + ); + assert_eq!(parse_cas_commit_reply(&[-1]), CasCommitResult::Gone); + assert_eq!( + parse_cas_commit_reply(&[-2]), + CasCommitResult::TooManyEvents + ); + assert_eq!( + parse_cas_commit_reply(&[9]), + CasCommitResult::Corrupt("unexpected CAS reply".into()) + ); +} + +#[test] +fn apply_error_conflict_is_not_move_rejected() { + assert_eq!(ApplyError::Conflict.reject_code(), None); +} + +#[tokio::test] +async fn redis_concurrent_identical_uci_one_ply() { + let Some(url) = redis_url() else { + eprintln!("skip redis_concurrent_identical_uci_one_ply: REDIS_URL unset"); + return; + }; + + let mut setup = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV171CONCURRENTE2E4000001"; + let _ = delete_game(&mut setup, game_id).await; + create_game(&mut setup, game_id, &seated_meta()) + .await + .expect("create"); + + let barrier = Arc::new(Barrier::new(2)); + let url = Arc::new(url); + let game = Arc::new(game_id.to_owned()); + + let run = |uci: &'static str, ts: u64| { + let barrier = Arc::clone(&barrier); + let url = Arc::clone(&url); + let game = Arc::clone(&game); + async move { + let mut conn = connect(url.as_str()).await.expect("conn"); + barrier.wait().await; + apply_move(&mut conn, game.as_str(), WHITE, uci, ts).await + } + }; + + let (a, b) = tokio::join!(run("e2e4", 10), run("e2e4", 11)); + let oks = [&a, &b].iter().filter(|r| r.is_ok()).count(); + let errs = [&a, &b].iter().filter(|r| r.is_err()).count(); + assert_eq!(oks, 1, "exactly one apply must win: {a:?} {b:?}"); + assert_eq!(errs, 1, "loser must fail: {a:?} {b:?}"); + + let loser = if a.is_err() { &a } else { &b }; + assert!( + matches!(loser, Err(ApplyError::NotYourTurn)), + "loser after CAS retry should be NOT_YOUR_TURN: {loser:?}" + ); + + let events = load_events(&mut setup, game_id).await.expect("events"); + assert_eq!(events.len(), 1, "one Move event only"); + assert_eq!( + reconstruct_fen(&mut setup, game_id).await.expect("fen"), + AFTER_E4 + ); + + delete_game(&mut setup, game_id).await.expect("cleanup"); +} + +#[tokio::test] +async fn redis_concurrent_racing_white_ucis_one_ply() { + let Some(url) = redis_url() else { + eprintln!("skip redis_concurrent_racing_white_ucis_one_ply: REDIS_URL unset"); + return; + }; + + let mut setup = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV171CONCURRENTD2D4000001"; + let _ = delete_game(&mut setup, game_id).await; + create_game(&mut setup, game_id, &seated_meta()) + .await + .expect("create"); + + let barrier = Arc::new(Barrier::new(2)); + let url = Arc::new(url); + let game = Arc::new(game_id.to_owned()); + + let left = { + let barrier = Arc::clone(&barrier); + let url = Arc::clone(&url); + let game = Arc::clone(&game); + async move { + let mut conn: ConnectionManager = connect(url.as_str()).await.expect("conn"); + barrier.wait().await; + apply_move(&mut conn, game.as_str(), WHITE, "e2e4", 20).await + } + }; + let right = { + let barrier = Arc::clone(&barrier); + let url = Arc::clone(&url); + let game = Arc::clone(&game); + async move { + let mut conn: ConnectionManager = connect(url.as_str()).await.expect("conn"); + barrier.wait().await; + apply_move(&mut conn, game.as_str(), WHITE, "d2d4", 21).await + } + }; + + let (a, b) = tokio::join!(left, right); + let oks: Vec<_> = [a, b].into_iter().filter_map(Result::ok).collect(); + assert_eq!(oks.len(), 1, "exactly one white ply may commit"); + let fen = reconstruct_fen(&mut setup, game_id).await.expect("fen"); + assert!( + fen == AFTER_E4 || fen == AFTER_D4, + "winner FEN must be e4 or d4, got {fen}" + ); + assert_eq!( + load_events(&mut setup, game_id) + .await + .expect("events") + .len(), + 1 + ); + + delete_game(&mut setup, game_id).await.expect("cleanup"); +}