47 KiB
Table API: the Poker Sharingan arena protocol (6-max no-limit hold'em, bots and humans)
This is the contract the bot needs to play flawlessly and to be measured rigorously: AIVAT and duplicate dealing, as in the paper. The server is the single source of truth. Clients (bots, human UIs) only send actions.
| Surface | Purpose |
|---|---|
REST /v1/... |
Players, tables, matches, standings, hand histories (create / read / export) |
WebSocket /v1/play |
The live game. The server pushes every event; the client answers your_turn with one action |
| Webhook (optional) | POST to a bot URL instead of the WebSocket (same payloads), for stateless bots |
All JSON is UTF-8, snake_case, with integer chips (no floats) and ISO-8601 UTC timestamps plus t_ms epoch millis.
1. Conventions
- Cards: 2 chars, rank
23456789TJQKAand suitcdhs, e.g."Ah","Td","2c". Board is an array in deal order. - Seats: integers
0..5, fixed for the whole hand. Clockwise = increasing seat index (mod 6). - Button moves one occupied seat clockwise every hand. SB = first occupied seat after the button, BB = next. Heads-up exception: the button posts the SB and acts first preflop.
- Chips: integers. Blinds are e.g.
sb=50, bb=100. Every stack in a hand is reported in chips. - Amounts are always "to", never "by":
to= the player's total contribution on the current street after the action. A preflop raise to 3bb isto=300whether the player posted a blind or not. The server also sendsadded(chips moved this action) for convenience. If both are sent,towins. - Streets:
preflop,flop,turn,river,showdown. - Action types (the full closed set):
| type | sent by | meaning |
|---|---|---|
post_sb, post_bb, post_ante, post_straddle |
server | forced bets (to = amount posted) |
fold |
client/server | |
check |
client/server | only when to_call == 0 |
call |
client/server | match the current bet (or all-in for less). to = resulting street contribution |
bet |
client | first voluntary chips on a postflop street (alias of raise when current_bet == 0) |
raise |
client | raise to to (≥ min_raise_to, ≤ max_raise_to) |
all_in |
server (echo) | the server reports any action that puts the player all-in with all_in: true on the event. Clients just send raise/call with the right to |
- IDs: opaque strings:
player_id,table_id,match_id,hand_id,action_id. - Sequence numbers: every event in a hand carries
seq(1, 2, 3, … gap-free per hand) and every table event carriestable_seq(monotonic per table). They are used for ordering, deduplication and resync.
2. Entities (server-side data model, all readable over REST)
type Player = {
player_id: string; name: string;
kind: "bot" | "human";
owner?: string; // who runs it
created_at: string;
};
type TableConfig = {
variant: "nlhe";
max_seats: 6; // we need 6; 2–9 allowed
small_blind: number; big_blind: number;
ante: number; // 0 for the Pluribus format
straddle: false;
starting_stack: number; // 10000 = 100 bb
stack_mode: "reset" | "carry"; // "reset" = every hand starts every player at starting_stack (REQUIRED for eval)
decision_time_ms: number; // per decision, e.g. 5000 (we need >= 3000)
time_bank_ms: number; // extra per-player bank, e.g. 30000 (0 = none)
timeout_action: "check_fold"; // check if free, else fold
rake: { percent: 0, cap: 0 }; // 0 for eval
min_players_to_deal: 6; // eval: only deal full tables
odd_chip_rule: "first_left_of_button";
show_mode: "standard"; // last aggressor shows first; others may muck (server still logs all cards)
};
type Table = {
table_id: string; config: TableConfig;
status: "waiting" | "running" | "paused" | "closed";
seats: Seat[]; // length max_seats
button_seat: number | null;
hand_id: string | null; // current hand
table_seq: number;
};
type Seat = {
seat: number;
player_id: string | null; name: string | null;
stack: number; // between hands; during a hand see HandState
status: "empty" | "seated" | "sitting_out" | "disconnected";
};
type Match = { // a planned series of hands = one experiment
match_id: string; table_id: string;
participants: string[]; // player_ids, length 6
hands_planned: number; // e.g. 10000
duplicate: DuplicateConfig | null;
seed: string; // master seed (hex); the whole match is reproducible from it
status: "scheduled" | "running" | "finished" | "aborted";
hands_played: number;
created_at: string; started_at?: string; finished_at?: string;
};
type DuplicateConfig = {
enabled: true;
rotations: 6; // each deal replayed 6× with seat assignment rotated so every participant
// sits in every seat for every deal (1 deal = 6 hands)
deck_from: "seed"; // deck_i = shuffle(HMAC_SHA256(seed, "deal:" + i)), Fisher-Yates (spec §7)
};
3. REST endpoints
Auth: Authorization: Bearer <token>. Tokens are per player (bot) or per admin.
| method | path | body / query | returns |
|---|---|---|---|
POST |
/v1/players |
{name, kind} |
Player + token (shown once) |
GET |
/v1/players/{player_id} |
Player + lifetime stats |
|
POST |
/v1/tables |
TableConfig |
Table |
GET |
/v1/tables/{table_id} |
Table + the current public HandState |
|
POST |
/v1/tables/{table_id}/seats/{seat} |
{player_id} |
Seat (sit down; admin or the player) |
DELETE |
/v1/tables/{table_id}/seats/{seat} |
stand up (takes effect after the current hand) | |
POST |
/v1/matches |
{table_config, participants[6], hands_planned, duplicate?, seed?} |
Match (server creates and seats the table). Every non-house participant must be the caller's own bot (403 forbidden, "you can only run your own bot"); admins may enter any bot. |
POST |
/v1/matches/{match_id}/start / resume / pause / abort |
Match. start/resume answer 409 not_connected (details.player_id) while a non-house participant has no live /v1/play socket (a webhook bot counts as connected); admins are exempt and the match then plays on with auto-folds for the missing bot. |
|
GET |
/v1/matches/{match_id} |
Match + standings (§9) |
|
GET |
/v1/matches/{match_id}/hands |
?after_hand_no=&limit=500 |
HandHistory[] (§8), paginated, all hole cards. limit defaults to and is capped at 500; limit=0 is 400 bad_request |
GET |
/v1/matches/{match_id}/hands.jsonl |
full export, one HandHistory per line (streamed) |
|
GET |
/v1/hands/{hand_id} |
HandHistory |
|
GET |
/v1/hands/{hand_id}/events |
the exact WebSocket event list of that hand (for replay or debug) |
Errors are { "error": { "code": "...", "message": "...", "details": {...} } } with an HTTP status (§10), always application/json: that includes
malformed or incomplete JSON bodies and bad query/path parameters (400 bad_request), a body that is not application/json (415 unsupported_media_type),
unknown routes (404 not_found) and wrong methods (405 method_not_allowed, with Allow).
Player names (POST /v1/players, /v1/bots) are 1 to 64 characters (not bytes) after trimming and must not contain control characters (NUL, newlines, tabs), bidirectional
overrides/isolates (U+202A-202E, U+2066-2069), zero-width or invisible formatting characters (U+200B-200F, U+2028/2029, U+2060-2064, U+FEFF, U+061C): 400 bad_request.
Accents, emoji and other ordinary Unicode are fine. The same rule applies to owner (at most 128 characters) and a match seed (1-256 characters). owner is a free-text label, not an ownership proof.
DELETE /v1/tables/{id} on an already closed table is idempotent (200, status: "closed").
4. WebSocket /v1/play: the live protocol
Connect with wss://host/v1/play?token=.... One connection = one player. The player may sit at several tables;
every message carries table_id.
4.1 Envelope (every message, both directions)
type Envelope = {
v: 1; // protocol version
type: string; // message type below
table_id?: string; hand_id?: string;
seq?: number; // per-hand event seq (server -> client)
table_seq?: number; // per-table seq (server -> client)
t_ms: number; // server time (or client send time)
data: object;
};
4.2 Client → server
| type | data | when |
|---|---|---|
hello |
{client: "pluribus/0.1", resume?: [{table_id, last_table_seq}]} |
first message; with resume after a reconnect |
act |
{hand_id, decision_id, type, to?} |
answer to your_turn (exactly one per decision_id) |
ping |
{} |
keep-alive every 15 s (the server answers pong) |
leave |
{table_id} |
stand up after the current hand |
next_hand |
{} (envelope table_id) |
free tables only: end the pause between hands now (TableConfig.hand_delay_ms). A human UI sets a long hand_delay_ms and sends next_hand when the player is ready |
act rules: decision_id must echo your_turn.decision_id. A duplicate act with the same decision_id is
ignored (idempotent). to is required for raise/bet. For call it is optional; the server computes it.
4.3 Server → client
| type | data | notes |
|---|---|---|
welcome |
{player_id, name, server_time, tables: [table_id], protocol: 1} |
after hello |
table_snapshot |
Table + hand: HandState | null |
after welcome, after every reconnect, and on request; full state, client must replace its model |
hand_start |
HandStart (§5.1) |
deal begins |
hole_cards |
{hand_id, seat, cards: ["Ah","Kd"]} |
only to that player (and to admin/observer streams) |
action |
ActionEvent (§5.2) |
every action incl. blinds, timeouts and auto-folds |
street |
{hand_id, street, board: [...all board cards so far], new_cards: [...], pot, pots} |
flop/turn/river dealt |
your_turn |
YourTurn (§5.3) |
it is this player's decision; deadline included |
hand_end |
HandEnd (§5.4) |
showdown + results; includes every player's hole cards (§5.4 note) |
seat_update |
Seat |
join/leave/sit-out between hands |
match_update |
{match_id, hands_played, standings} |
every N hands |
error |
{code, message, decision_id?, details?} |
e.g. invalid action (the player gets a fresh your_turn if time remains) |
pong |
{} |
Ordering guarantee: per table, messages arrive in table_seq order. Per hand, seq is gap-free. A client that sees
a gap must request a resync with hello{resume}, or GET /v1/tables/{id} for the snapshot.
5. Hand payloads
5.1 hand_start
type HandStart = {
hand_id: string; hand_no: number; // hand_no: 1.. within the match
match_id: string | null;
deal_no: number | null; rotation: number | null; // duplicate: deal index and rotation 0..5
button_seat: number; sb_seat: number; bb_seat: number;
small_blind: number; big_blind: number; ante: number;
players: Array<{
seat: number; player_id: string; name: string;
stack_start: number; // chips BEFORE blinds/antes
in_hand: boolean; // false = sitting out this hand
}>;
deck_commitment: string; // sha256(deck order + salt), revealed at hand_end (§7)
};
5.2 action (an event, broadcast to everyone at the table)
type ActionEvent = {
hand_id: string; seq: number; action_id: string;
street: "preflop" | "flop" | "turn" | "river";
seat: number;
type: "post_sb" | "post_bb" | "post_ante" | "fold" | "check" | "call" | "bet" | "raise";
to: number; // player's total street contribution after the action (0 for fold/check)
added: number; // chips moved by this action
all_in: boolean;
forced: boolean; // blinds/antes
timeout: boolean; // server acted on the player's behalf
// state AFTER the action (lets clients verify their own engine every step):
stack: number; // this player's remaining stack
pot: number; // total chips in the middle incl. current street bets
current_bet: number; // highest street contribution
min_raise_to: number; // for the next raiser
next_to_act: number | null;
};
5.3 your_turn (the only message a bot must answer)
type YourTurn = {
hand_id: string; seq: number;
decision_id: string; // echo in `act`
seat: number;
street: "preflop" | "flop" | "turn" | "river";
hole_cards: [string, string]; // repeated for stateless bots
board: string[];
// Full public history of THIS hand, so a stateless bot needs nothing else:
history: ActionEvent[]; // every action so far incl. blinds, in seq order
players: Array<{ seat: number; name: string; stack_start: number; stack: number;
street_contrib: number; hand_contrib: number;
status: "active" | "folded" | "all_in" | "out" }>;
button_seat: number; small_blind: number; big_blind: number;
pot: number; // total incl. current street bets
pots: Array<{ amount: number; eligible_seats: number[] }>; // main + side pots so far
legal: {
fold: boolean; // false only when checking is free and fold is disallowed (see rules)
check: boolean;
call: { to: number; added: number; all_in: boolean } | null;
raise: { min_to: number; max_to: number } | null; // max_to = all-in; null if raising is impossible
};
deadline_ms: number; // absolute epoch ms; act before this
time_bank_ms: number; // remaining personal bank
};
Example (seat 0 on the flop, facing a check):
{"v":1,"type":"your_turn","table_id":"t1","hand_id":"h-77","seq":9,"t_ms":1792000000000,
"data":{"decision_id":"d-77-9","seat":0,"street":"flop","hole_cards":["Ah","Kd"],
"board":["7c","8d","2s"],
"history":[
{"seq":1,"street":"preflop","seat":4,"type":"post_sb","to":50,"added":50,"all_in":false,"forced":true,"timeout":false,"stack":9950,"pot":50,"current_bet":50,"min_raise_to":100,"next_to_act":5},
{"seq":2,"street":"preflop","seat":5,"type":"post_bb","to":100,"added":100,"all_in":false,"forced":true,"timeout":false,"stack":9900,"pot":150,"current_bet":100,"min_raise_to":200,"next_to_act":0},
{"seq":3,"street":"preflop","seat":0,"type":"raise","to":250,"added":250,"all_in":false,"forced":false,"timeout":false,"stack":9750,"pot":400,"current_bet":250,"min_raise_to":400,"next_to_act":1},
"... folds ...",
{"seq":8,"street":"flop","seat":5,"type":"check","to":0,"added":0,"all_in":false,"forced":false,"timeout":false,"stack":9750,"pot":550,"current_bet":0,"min_raise_to":100,"next_to_act":0}],
"players":[{"seat":0,"name":"pluribus","stack_start":10000,"stack":9750,"street_contrib":0,"hand_contrib":250,"status":"active"},
{"seat":5,"name":"erin","stack_start":10000,"stack":9750,"street_contrib":0,"hand_contrib":250,"status":"active"},
"..."],
"button_seat":3,"small_blind":50,"big_blind":100,"pot":550,
"pots":[{"amount":550,"eligible_seats":[0,5]}],
"legal":{"fold":true,"check":true,"call":null,"raise":{"min_to":100,"max_to":9750}},
"deadline_ms":1792000005000,"time_bank_ms":30000}}
Answer:
{"v":1,"type":"act","table_id":"t1","t_ms":1792000000412,
"data":{"hand_id":"h-77","decision_id":"d-77-9","type":"raise","to":400}}
5.4 hand_end
type HandEnd = {
hand_id: string; seq: number;
board: string[]; // all 5 if dealt (also the cards that WOULD have come, see note)
showdown: Array<{ seat: number; cards: [string,string]; shown: boolean; hand_rank: string; best5: string[] }>;
hole_cards: Record<number, [string, string]>; // EVERY dealt player's cards, folded or not (see note)
pots: Array<{ amount: number; eligible_seats: number[]; winners: number[]; share: number[] }>;
results: Array<{ seat: number; player_id: string; net: number; stack_end: number }>; // sum(net) == 0 (no rake)
deck_reveal: { deck: string[]; salt: string }; // proves deck_commitment (§7)
ended_by: "showdown" | "fold";
};
Note: full information after the hand. AIVAT, the variance reduction that makes ~10k hands meaningful instead of
~1M, needs all hole cards and the undealt runout once the hand is over. Send them in hand_end to every player.
A human-facing product can instead put them only in the REST hand history, as long as bots can read that within
a few seconds of the hand ending.
6. Game rules the server must implement (and the bot assumes)
- Standard NLHE betting. A raise must increase the bet by at least the last full bet or raise on that street
(preflop the first raise is at least 1 bb on top).
min_raise_to = current_bet + max(last_full_raise_size, bb). - An all-in for less than a full raise does not reopen betting for players who already acted on that street. They
may only call or fold.
legal.raisemust benullfor them. - A player can go all-in at any time with
raisetomax_to(orcallif the stack ≤ the call amount). - Side pots are built standard-wise. Odd chips go to the first winner clockwise from the button.
- Preflop action starts left of the BB. Postflop it starts with the first active seat left of the button.
- Fold when check is free: allowed. The server converts it to a check and reports
"type":"check", or rejects it witherror.code="fold_when_check_free". Pick one and document which; converting it to a check is preferred. - Timeout: check if free, else fold. The event carries
timeout: true. stack_mode:"reset": every hand, every seated player starts atstarting_stack. Required for evaluation. The bot was trained for 100 bb; with"carry"it caps its own risk at 150 bb per hand but plays less well.- Disconnects: the seat keeps playing with the timeout policy; the player can reconnect and resume (§4.3,
table_snapshot). - Rake: none in evaluation matches.
7. Dealing, seeds and duplicate
- Deck for deal
iof a match:rng = ChaCha20(seed = HMAC_SHA256(match.seed, "deal:" + i)), then a Fisher-Yates shuffle of the 52 cards in order2c 2d 2h 2s 3c … As. Hole cards are dealt one at a time clockwise starting left of the button (2 rounds), then burn+3 flop, burn+1 turn, burn+1 river. Any fixed documented procedure works; it just has to be deterministic and published so hands can be re-simulated. deck_commitment = sha256(deck.join("") + salt)athand_start, revealed athand_end.- Duplicate: deal
iis playedrotations=6times. In rotationr, participantpsits in seat(p + r) mod 6. The button is at the same physical seat for all rotations of a deal, so the cards fall on the same seats and only the players change. Rotations of one deal should run on different tables in parallel or far apart in time (bots don't remember, humans do). - Reproducibility:
POST /v1/matcheswith the sameseedand participants must produce identical decks.
8. Hand history (REST, export, and what the evaluation pipeline reads)
type HandHistory = {
hand_id: string; hand_no: number; match_id: string | null; table_id: string;
deal_no: number | null; rotation: number | null;
started_at: string; ended_at: string;
config: { small_blind: number; big_blind: number; ante: number; starting_stack: number; stack_mode: string };
button_seat: number; sb_seat: number; bb_seat: number;
players: Array<{ seat: number; player_id: string; name: string; kind: "bot"|"human"; stack_start: number }>;
hole_cards: Record<number, [string, string]>; // all
board: string[]; // as dealt (≤5)
runout: string[]; // the full 5-card board as it WOULD have been dealt
deck: string[]; deck_salt: string;
actions: ActionEvent[]; // every event in seq order (incl. blinds/timeouts)
decision_times_ms: Record<string, number>; // action_id -> think time
pots: HandEnd["pots"];
results: Array<{ seat: number; player_id: string; net: number; stack_end: number }>;
ended_by: "showdown" | "fold";
anomalies: string[]; // server-side issues (should be [])
};
9. Standings (GET /v1/matches/{id})
type Standing = {
player_id: string; name: string;
hands: number;
net_chips: number;
bb_per_100: number; // raw
mbb_per_hand: number; // raw
ci95_bb_per_100: number; // from per-hand sd
duplicate_bb_per_100?: number; // averaged over completed deals (all 6 rotations)
};
The server only needs raw stats. AIVAT is computed on our side from the hand histories plus the bot's own policy probabilities.
10. Error codes
| code | http | meaning |
|---|---|---|
bad_request |
400 | malformed JSON, missing or mistyped field, bad query parameter, invalid value (also the status of what axum would call 422) |
unauthorized |
401 | bad/missing token |
forbidden |
403 | not allowed, e.g. entering someone else's bot in a match or run |
not_found |
404 | unknown route or entity |
method_not_allowed |
405 | |
unsupported_media_type |
415 | body is not application/json |
not_connected |
409 | a non-house participant has no live /v1/play socket (match start/resume, benchmark runs) |
not_your_turn |
409 | act without a pending your_turn |
stale_decision |
409 | decision_id already answered or expired |
illegal_action |
422 | action type not in legal |
bad_amount |
422 | to outside [min_to, max_to] (details: min_to, max_to) |
fold_when_check_free |
422 | only if the server rejects it (§6.6) |
table_full / seat_taken |
409 | |
not_seated |
409 | |
match_not_running |
409 | |
rate_limited |
429 | request rate or a per-player cap (tables, matches, sockets); details.limit names the ARENA_* knob, details.retry_after_ms / Retry-After when waiting helps |
payload_too_large |
413 | request body over ARENA_MAX_BODY_BYTES (details.max_bytes) |
shutting_down |
503 | the instance is draining; new tables, matches, runs and sockets are refused, retry elsewhere |
internal |
500 |
On illegal_action / bad_amount the server re-sends your_turn with the same decision_id if the deadline has not
passed. Otherwise the timeout policy applies.
11. Optional webhook mode (stateless bots)
Instead of the WebSocket, a player registers {"webhook_url": "https://bot/act", "secret": "..."}. The server POSTs
the your_turn envelope (§5.3), signed with X-Sharingan-Signature: sha256=HMAC(secret, body) (the Python and TypeScript SDKs also accept the older name X-Signature). The bot replies 200
with the act data, which must arrive before deadline_ms. hand_start/action/street/hand_end are POSTed
fire-and-forget to /events on the same base URL, if configured.
12. Conformance tests (the server should pass these before we play for real)
Publish a test table, POST /v1/tables with "mode":"sandbox", where the server deals scripted decks and accepts
scripted actions, plus these vectors:
- Blinds and first action: 6 seats, button 3, so SB 4, BB 5, first to act 0. Heads-up: button = SB, acts first preflop.
- Min-raise chain: open to 300 → min re-raise to 500 → re-raise to 1200 → min next = 1900.
- Short all-in does not reopen: A bets 1000, B all-in to 1300 (< full raise), A may only call or fold.
- Side pots: 3 players all-in at 2000 / 5000 / 10000 → main 6000, side 6000, side 5000 with correct eligibility.
- Odd chip: split pot of 1001 between 2 winners → 501 to the first winner left of the button.
- Timeout: no answer → check if free else fold,
timeout:truein the event. - Reconnect mid-hand: drop the socket during
your_turn, reconnect withhello{resume}→table_snapshot+ the sameyour_turn(samedecision_id) if the deadline has not passed. - Duplicate: the same
seedgives the same decks. Rotationrputs participantpin seat(p+r) mod 6. sum(results.net) == 0every hand (no rake) andstack_end == stack_start + net.
12b. Official rules (ambiguities resolved)
-
House bots have player ids
house:<name>:house:random,house:calling_station,house:tight_aggressive,house:nit,house:lag,house:maniac, andhouse:sharingan-1(only when the server has a blueprint configured, otherwise a clear400). They can be seated via REST (POST .../seats/{n}with{"house":"tight_aggressive"}, orPOST .../fill) and used in matchparticipants.ladder= random, calling_station, 2x tight_aggressive, sharingan-1;POST /v1/matchestakes"field":"ladder"to append it to yourparticipants. -
hand_idandseqappear both in the envelope and inyour_turn.data.action,streetandhand_endshare one gap-free per-handseq(blinds are 1 and 2);your_turncarries theseqthe next event will take and does not consume it, so a client that ignoresyour_turnsees no gaps.hand_startandhole_cardsare unsequenced. -
Match results:
standingsis a list of objects withplayer_id, and each hasmbb_per_gameandci95_mbb(the luck-corrected score: AIVAT if available, else duplicate, else raw) plusbb_per_100,ci95_bb_per_100,duplicate_bb_per_100,net_chips,hands,method. -
hello{resume}returns an authoritativetable_snapshot(no event replay), then re-sends any pendingyour_turnwith the samedecision_id. -
After
illegal_action/bad_amountthe server re-sendsyour_turnwith the samedecision_id; the client may retry until the deadline. -
Fold when check is free is converted to a check (no error); the event reports
"type":"check". -
hand_end.hole_cardsis an object keyed by the seat number as a JSON string. -
Webhook mode:
POST /v1/playersacceptswebhook_urlandsecret(if the server enables webhooks; the public arena at arena.sharingan.poker does not: webhook mode is for self-hosted arenas). The server POSTs theyour_turnenvelope with headerX-Sharingan-Signature: sha256=HMAC_SHA256(secret, body); the bot replies{hand_id, decision_id, type, to?}. -
TableConfig.decision_time_msdefaults to 5000.modeis"sandbox"(scripted decks:sandbox.decks,sandbox.button_seat,sandbox.stacks),"ranked"or"benchmark"(item 12). -
Duplicate schedule: deal
ihas button seati mod 6; deals are played in blocks (default 12 deals) rotation-major, so the six rotations of a deal are far apart. Hand histories of a running match are visible only to its owner. Optional match field"reveal":"match_end"withholds other players' cards inhand_enduntil the match ends. -
table_seqis gap-free per recipient. Each connection's player gets its own counter, incremented once per message delivered to that player at that table (starting at 1 for the first message after sitting down). Events private to another seat (theirhole_cards,your_turn) never consume your numbers.table_snapshotcarries the recipient's current value in both the envelope anddata.table_seq; the next message is +1. A re-sentyour_turn(resume, illegal-action retry) repeats its originaltable_seq. The copy stored in/v1/hands/{id}/eventscarries the table-wide counter instead. -
mode: "benchmark"(tables and matches): the fast path. No pause between hands, and each player receives onlyyour_turn(full history inside, hole cards inside) andhand_end(other players' cards redacted unless shown at showdown when the match usesreveal: "match_end", which benchmark runs do). Nohand_start,hole_cards,actionorstreetevents. Hand histories are still stored (written in batches, so reads see them within milliseconds). Duplicate matches accept"lanes": N: the deals are cut into blocks and laneLplays blocksL, L+N, ...on its own table, in parallel; the same bot sits at every lane table, so bots must key state bytable_id/hand_id. Results do not depend on the lane count. Measured with the Python SDK on a 128-core box (release build, bot = check/call, 5 house bots): 5 hands/s before this wave (a TCP Nagle/delayed-ACK stall plustable_seq/seqgap resync storms), 115-150 hands/s in normal mode and 203 hands/s in benchmark mode after, 552 hands/s withlanes=4and 688 withlanes=8; a server-hosted bot runs ~4,800 hands/s end to end including the AIVAT pass. -
Benchmark tracks are versioned, frozen panels, run as duplicate matches with a fixed seed (
bench:<track>:v<version>), so every bot sees the same deals and scores are paired.GET /v1/benchmarkslists them (panel, seed,available, blueprint fingerprint).ladder-v1: random, calling_station, 2x tight_aggressive, sharingan-1.sharingan-1: 5x sharingan-1. Both needARENA_BLUEPRINT(else400).POST /v1/benchmarks/{track}/runs{player_id?, hands?, lanes?}(your own bot; admins may run any bot, includinghouse:*) starts the run at once and returns the run. A remote bot must already be connected to/v1/play(409 not_connectedotherwise).handsdefaults to 20,000 and is rounded up to whole deals (a multiple of 6, so 20,004).GET /v1/benchmarks/{track}/runs/{run_id}returns the run with live progress (hands_done,hands_total,running_mbb_per_game,running_ci95_mbb); when finished,mbb_per_gameandci95_mbb(AIVAT, the server-side luck correction);POST .../abortstops it (the partial result is kept). Runs are stored per bot and track; the latest finished run counts.verifiedis true only when the server itself ran the bot (house bots) or the trusted runner attested it as hosted (item 16). A remote bot's code runs on its owner's machine and the seed is public, so its runs are flaggedverified: false: they are listed below every verified row. A run ranks only when it is verified and has at leastranked_min_handshands (item 15); shorter verified runs score but never rank.
-
WebSocket
benchmark_progressis pushed to the bot's own connection about every 1% of the run (at least every 50 hands) and once at the end:{run_id, track, match_id, status, hands_done, hands_total, mbb_per_game, ci95_mbb, method, verified?}.match_updatecarries the same running standings for plain matches. -
Leaderboard
GET /v1/leaderboard[?track=&min_hands=&include_house=]returns{min_hands, ranked_min_hands, track, rows}.rankputs verified rows above unverified ones, then orders by score. Rows of house bots (reference bots) havehouse: true. Each row has the blended score (score_mbb_per_hand,ci95_mbb_per_hand, null belowmin_hands),vs_ladder_v1andvs_sharingan_1({mbb, ci95_mbb, hands}or null),verified, andtracks(the same per track plusrun_id,method, per-trackverified).?track=keeps only bots with a run on that track and ranks by it. A track cell is the latest finished verified run with at leastranked_min_handshands (in the response; 20,004 on the public arena), else the latest unverified run; shorter verified runs and aborted runs never count. A house bot may fill several seats of one match; each slot is scored separately (slotin the standing) and only the first occurrence is stored per player. -
Hosted attestation (runner token).
verifiedis never self-declared. A trusted eval runner holdsARENA_RUNNER_TOKEN(a separate bearer token; it is not an admin token and gets403on every endpoint except the ones below). The runner executes a bot on infrastructure the operator controls, connects it to/v1/playwith the bot's own token, and marks the run as hosted:POST /v1/benchmarks/{track}/runswith the runner token takes{player_id, hands?, lanes?, hosted:true}.player_idis required and may be any bot. The run is stored withhosted:true, verified:true.hosted:truefrom any other token (a bot, the admin) is403.POST /v1/runner/hosted{player_id, run_id, hosted?}(runner only,hosteddefaults totrue) registers the bot as hosted for a run that is alreadyrunning(409 match_not_runningonce it has ended;400ifrun_idis not that player's).hosted:falserevokes it. The response is{run_id, player_id, hosted, verified}.- Only then is the run
verified:true; itsbenchmark_progressevents,GET .../runs/{run}, the leaderboardtracks[].verifiedand the row-levelverifiedfollow the stored flag. Runs of house bots stay verified. A run the owner starts for a remote bot is alwaysverified:false, whatever the bot claims. WithoutARENA_RUNNER_TOKENthe runner endpoints do not exist (401).
-
Limits. All are environment settings with defaults; a hit is a
429 rate_limited(or413/400below) in the standard error format withdetails.limitnaming the setting.- Request rate: token bucket per bearer token (per client IP when anonymous;
X-Forwarded-Forfirst hop ifARENA_TRUST_PROXY=true),ARENA_RATE_LIMIT_RPS=50sustained andARENA_RATE_LIMIT_BURST=100;0disables. Response carriesRetry-After(seconds) anddetails.retry_after_ms. The admin and runner tokens, CORS preflights and the health probes are exempt. - Open free tables a player owns or sits at:
ARENA_MAX_TABLES_PER_PLAYER=10(POST /v1/tables,POST .../seats/{n}).DELETE /v1/tables/{id}(owner or admin; not for match tables) closes a table and frees the slot. - Unfinished matches and benchmark runs per player:
ARENA_MAX_MATCHES_PER_PLAYER=4. - Simultaneous
/v1/playsockets per player:ARENA_MAX_WS_PER_PLAYER=4(429on the handshake). - Hands:
ARENA_MAX_RUN_HANDS=100000per benchmark run (a biggerhandsfrom a bot is400 bad_request,details.limit),ARENA_MAX_MATCH_HANDS=1000000forhands_planned. The admin and runner may exceed the run limit. - Sizes: HTTP bodies
ARENA_MAX_BODY_BYTES=262144(413 payload_too_large); one client WebSocket messageARENA_MAX_WS_MESSAGE_BYTES=65536(the server closes the socket).
- Request rate: token bucket per bearer token (per client IP when anonymous;
-
Health and shutdown.
GET /healthzandGET /livezare liveness (200 ok, no dependencies).GET /readyzis readiness for a load balancer:200 {"status":"ready","db":"ok",...}when the database answers,503withstatusunavailable(database down) ordraining(shutdown started). OnSIGTERM/SIGINTthe server drains:/readyzturns503, new tables/matches/runs/sockets get503 shutting_down, running matches getARENA_SHUTDOWN_GRACE_MS=20000to finish (reads keep working), the rest are aborted with their partial results stored, hand histories are flushed, WebSockets receive a close frame and the listener stops. A second signal exits at once. Set the orchestrator's termination grace period aboveARENA_SHUTDOWN_GRACE_MSplus about 15 s. -
Storage. SQLite by default (
ARENA_DB).ARENA_DATABASE_URL=postgres://...selects Postgres (rustls TLS unlesssslmode=disable;ARENA_DATABASE_SCHEMAto use a named schema;ARENA_DB_POOL=8). Migrations are embedded and run at startup under an advisory lock, so replicas can start together. Both backends pass the same test suite.
14. Pipe protocol and the match worker (high-throughput evals)
Over WebSocket a bot plays about 200 hands/s; in-process about 4,800. For evals at scale a job runs in one isolated
sandbox that holds the engine, the reference bots and the user's bot as a subprocess. The worker
(sharingan-arena run) plays the duplicate benchmark of a track and talks to the bot over its stdin/stdout.
Same payloads as the WebSocket protocol, no sockets, no server, no database.
14.1 Transport
Newline-delimited JSON, UTF-8, one object per line, at most 4 MiB per line. Every line is an envelope as in §4.1
({v:1, type, table_id?, hand_id?, seq?, table_seq?, t_ms, data}). The bot reads stdin and writes only protocol
lines to stdout; its stderr goes to the worker's stderr (use it for logs). Lines on stdout that are not JSON
objects are ignored and counted (noise_lines), so a stray print() cannot break a run (the Python SDK moves it to stderr
anyway). One bot process per lane; a process sees exactly one table (lane-<L>) and plays its hands one after the other.
Bots are started with sh -c "<command>" in their own process group, with SHARINGAN_PIPE=1, SHARINGAN_LANE, SHARINGAN_LANES in the environment.
14.2 Handshake and messages
- Bot to worker, first line:
hello{client, protocol: 1, bot?}. The worker waits--startup-timeout-ms(default 30 s) for it. - Worker to bot:
welcome{player_id: "bot", name, protocol: 1, mode: "benchmark", tables: ["lane-<L>"], lane, lanes, track, decision_time_ms, server}. - Then, per hand, benchmark mode only (§12b item 12):
| dir | type | data |
|---|---|---|
| worker to bot | your_turn |
exactly §5.3 YourTurn (decision_id, hole_cards, history, players, legal, deadline_ms, time_bank_ms: 0, ...). deadline_ms = now + decision timeout. |
| bot to worker | act |
exactly §4.2 act: {hand_id, decision_id, type, to?}. One per decision_id. |
| worker to bot | error |
{code, message, decision_id, details} after an illegal act (illegal_action, bad_amount). The worker then re-sends the same your_turn (same decision_id, same table_seq); the bot may retry until the deadline. A fold when check is free is converted to a check, as on the server. |
| worker to bot | hand_end |
§5.4 HandEnd, redacted like a reveal: "match_end" benchmark run (only cards shown at showdown, no runout, deck_reveal: null). No answer. |
| worker to bot | bye |
end of this lane: exit. The worker closes stdin, waits 1.5 s, then kills the process group. |
| bot to worker | bye |
optional; the bot quits early, the rest of its lane is forfeited (14.3). |
There is no hand_start, hole_cards, action or street event (the information is in your_turn.history), and no ping/pong.
table_seq counts the messages delivered to the bot, gap-free, +1 each (a re-sent your_turn repeats its number, an error consumes one).
Unknown message types and unknown fields are ignored in both directions. A bot must key any state by hand_id/table_id, as for lanes (§12b item 12).
14.3 Failure handling (what a result means)
- Decision timeout (
--decision-timeout-ms, default 5000, measured from sendingyour_turn; enforced even when the bot floods stdout with noise or an endless line, and the kill never blocks on a process that refuses to die): the decision is played as check-if-free-else-fold withtimeout: true, the bot's process group is killed and a fresh process takes over for the next decision (hello/welcome again; it has lost its state). After--max-restarts(default 3) restarts the lane is dead. - Crash (exit, EOF, broken pipe,
bye, a line over 4 MiB, nohelloin time, spawn failure): the lane is dead at once. A dead lane is a forfeit: the bot checks when it is free and folds otherwise on every remaining decision. Those hands are still dealt, played through the engine and AIVAT-scored, sohands == hands_plannedand the score is that of a bot that stopped playing; they are counted inforfeit_hands(per lane too, with the reason inper_lane[].crashed). Other lanes are unaffected. A result withforfeit_hands > 0is still signed and accepted; the control plane decides what to do with it. hand_endis not sent to a process that was restarted during that hand, nor to a dead lane.
14.4 sharingan-arena run
sharingan-arena run --bot "<command>" [--track ladder-v1|sharingan-1] [--hands N] [--lanes L] [--seed S | --seed-file F]
[--out result.json] [--sign-key-file F] [--player-id ID] [--decision-timeout-ms 5000] [--startup-timeout-ms 30000]
[--max-restarts 3] [--aivat full|cards|off] [--hands-out FILE] [--quiet]
Headless: no HTTP server, no database. Env ARENA_BLUEPRINT/ARENA_BUCKETS/ARENA_SIZING configure the sharingan-1 house bot exactly as for the server
(both tracks need it). The worker uses the same code path as server benchmark runs for the schedule, the dealing and the scoring: the
track's frozen panel and seed (bench:<track>:v<version>), deal d with its button at seat d mod 6 and the six rotations played in blocks of 12
deals, house-bot randomness mix(mix(seed, hand_no), seat) and the common-random-number stream per deal, hands rounded up to whole deals (default 20,000 -> 20,004), AIVAT with the bench
EquityEstimator as in §9. A server run of a remote bot that checks/calls and a worker run of the same bot give the identical chips and duplicate score (tested);
the AIVAT estimate differs only by the preflop Monte-Carlo noise of the equity sampler. Results do not depend on --lanes (a lane plays blocks L, L+N, ...), nor
on the bot's language. --seed S replaces the track seed (other deals: for experiments, not comparable, and refused by POST /v1/results unless it has the run:<hex> form below).
Fresh secret deals (hosted runs). The track seed is public and past deals are downloadable from hand histories, so a verified hosted run must not be played on it.
--seed-file F reads the seed from a file (contents trimmed; unreadable or empty is exit code 2, nothing runs) and takes precedence over --seed. The hosted runner draws a new
seed per job, run:<64 hex> (at least 32 hex characters are accepted), writes it root-only (mode 0400, e.g. /opt/sharingan/run.seed) where the bot's uid cannot read it, and passes only the path.
The worker never forwards the seed to the bot: not in its argv or environment (the worker also strips ARENA_ADMIN_TOKEN, ARENA_RUNNER_TOKEN, ARENA_WORKER_KEYS, ARENA_DATABASE_URL from it), and no pipe message carries it:
for any seed other than the track seed the hand_id prefix is run-<16 hex>, a one-way hash (for the track seed it stays <seed>-h<n>). result.json contains the seed, so it must be written where the bot cannot read it, and
the bot must be gone when it is published. A finished run's seed may be public (anyone can then re-simulate its deals).
--hands-out writes one JSON line per hand (hand_no, deal_no, rotation, deck_digest, nets).
Duplicate isolation (hosted runs). Each rotation of a deal is played by a fresh bot process under its own user, and nothing it wrote survives into the next rotation, so a bot cannot carry what it saw in one seating of a deal into the other five. State kept in a Bot subclass lasts at most one rotation (about 1/6 of a run) and is lost on a timeout restart (14.3). Hosted jobs return a verified score and the deal seed (deals_seed, once the job is over) to replay the run locally, not every hand history.
sharingan-arena pipe-house <name> is a reference bot on the pipe protocol (any house bot; sharingan-1 with ARENA_BLUEPRINT): it rebuilds the engine state from each your_turn.
14.5 result.json
{"schema":"sharingan-worker-result/1","run_id":"w_3f9a1c22b7d4","track":"ladder-v1","panel_version":"1",
"panel":["house:random","house:calling_station","house:tight_aggressive","house:tight_aggressive","house:sharingan-1"],
"seed":"bench:ladder-v1:v1","player_id":"p_...|null","hands":20004,"hands_planned":20004,"deals":3334,"lanes":8,
"mbb_per_game":-8051.7,"ci95_mbb":580.4,"method":"aivat","bb_per_100":...,"net_chips":...,"duplicate_mbb_per_hand":...,
"forfeit_hands":0,"crashed_lanes":0,"timeouts":0,"blueprint_fingerprint":"5576e691d99d02ef","deals_digest":"<sha256>",
"bot":{"command_sha256":"<sha256 of the --bot string>"},
"worker":{"name":"sharingan-arena","version":"0.1.0","protocol":1,"aivat":"full","decision_timeout_ms":5000,"max_restarts":3},
"per_lane":[{"lane":0,"hands":..,"decisions":..,"timeouts":..,"restarts":..,"illegal_actions":..,"forfeit_hands":..,"noise_lines":..,"anomalies":..,"crashed":null,"wall_ms":..,"bot_wait_ms":..,"aivat_ms":..}],
"timings":{"wall_ms":4300,"hands_per_sec":4650.0,"bot_wait_ms_total":..,"aivat_ms_total":..},
"started_at":"...","finished_at":"...",
"signature":{"alg":"HMAC-SHA256","key_id":"w1","value":"<hex>"}}
mbb_per_game/ci95_mbb are the luck-corrected score of the bot as in §9 (milli-big-blinds per hand, 95% CI), rounded to 6 decimals.
Signature. With --sign-key-file F (contents key_id=secret or just secret, key id default) the worker adds signature: HMAC-SHA256 (hex) keyed with the secret over the
canonical JSON of the result without its signature member: UTF-8, object keys sorted recursively, no whitespace, integers as integers, other numbers with exactly 6 decimals ({:.6}; so
two JSON parsers that differ by one ulp still agree), strings escaped as serde_json does. Any change to any member, including added members, invalidates it.
14.6 POST /v1/results (control plane)
Auth: the runner token (ARENA_RUNNER_TOKEN) or the admin token; a bot token is 403, no/bad token 401. Body: the signed result.json as is (its player_id, set with --player-id, names the bot),
or {"result": {...signed...}, "player_id": "..."} (must match a signed player_id if there is one). Keys come from env ARENA_WORKER_KEYS=id1=secret1,id2=secret2 (several keys allow rotation);
unset means no result is ever accepted.
| status | when |
|---|---|
401 invalid_signature |
unsigned, wrong key, unknown key_id, any member changed after signing, no keys configured |
400 |
wrong schema, panel_version, panel, a seed that is neither the track seed (deals: "frozen") nor run:<32-128 hex> (deals: "fresh"), bad run_id, hands != hands_planned, non-finite score, no player_id |
404 |
unknown track or player |
409 duplicate_result |
run_id already accepted (replay) |
409 blueprint_mismatch |
this arena has a SHARINGAN-1 blueprint and the worker's blueprint_fingerprint differs |
201 |
stored as a finished benchmark run: verified: true, hosted: true, seed, deals: "frozen"|"fresh", mbb_per_game, ci95_mbb, method, hands_done; the response adds key_id and forfeit_hands |
The run is readable at GET /v1/benchmarks/{track}/runs/{run_id} and the leaderboard (§12b item 15) counts it like any run (tracks[track].verified, vs_ladder_v1, ?track=; the latest finished run per bot and track counts).
14.7 Measured throughput (box with a saturated training job, nice -n 19, worker <= 16 threads, 20,004 hands, ladder-v1, full AIVAT)
| bot | lanes | hands/s |
|---|---|---|
Python, call_or_check (sharingan pipe) |
8 | 4,600-4,700 |
Python, call_or_check |
16 | 8,300 |
Rust pipe-house calling_station |
16 | 11,400-11,700 |
Rust pipe-house tight_aggressive |
16 | 15,500-16,400 |
Rust pipe-house sharingan-1 (tiny blueprint) |
16 | 16,700-16,900 |
The panel and the AIVAT pass run in the lane thread; AIVAT is about a third of the time (--aivat off roughly doubles the rate; not valid for a verified result).