Skip to content

Data Model Specification

The engine's types and the persistence layout. Two layers, kept deliberately separate — see architecture.md:

  1. Engine value types (src/engine/types.py) — pure, immutable, no persistence concerns. This is what adjudication actually operates on.
  2. Persistence (src/persistence/) — a game row stores the serialized engine GameState wholesale (state_json), not a normalized relational breakdown. A few peripheral tables (players, users, messages, channels, ...) remain relational because they aren't engine-coupled.

For the algorithm that produces these values, see adjudication.md.

1. Engine value types (src/engine/types.py)

All frozen dataclasses, and all hashable except GameState, whose ownership is a dict (hashing one raises TypeError); no dict-of-dicts, no mutation. Full definitions live in the source — this is the field-level reference.

Location

Location(province: str, coast: Optional[str] = None)

province is always uppercased on construction. coast is one of NC/SC/EC/WC (also uppercased) or None. Armies always have coast=None; fleets in split-coast provinces (BUL, SPA, STP) always name one. str(loc) renders the canonical text form: "PAR" or "SPA/SC" — this is also the JSON encoding (§4).

Unit

Unit(kind: UnitKind, power: str, location: Location)

kind is UnitKind.ARMY ("A") or UnitKind.FLEET ("F"). Raises if an army carries a coast. .province is a convenience property (location.province).

DislodgedUnit

DislodgedUnit(unit: Unit, attacker_origin: Optional[str] = None,
              retreats: tuple[Location, ...] = ())

Carries everything the retreat phase needs precomputed: the province the dislodging attack came from (None if that attack was convoyed — no shared-border block applies), and the full legal retreat set already computed against post-resolution occupancy (see adjudication.md §8). Empty retreats means the unit is trapped and must disband.

Orders

All orders share a power: str field and an order_type: OrderType property. One class per order kind (movement-phase: Hold, Move, SupportHold, SupportMove, Convoy; retreat-phase: Retreat, Disband; adjustment-phase: Build, Disband (shared), Waive):

Class Fields Example order text
Hold unit A PAR H
Move unit, dest, via_convoy A PAR - BUR, A LON - BEL VIA
SupportHold unit, target F BRE S A PAR, F BRE S A PAR H
SupportMove unit, origin, dest F BRE S A PIC - BEL
Convoy unit, origin, dest F NTH C A LON - BEL
Retreat unit, dest A PAR R BUR
Disband unit D A PAR
Build location, kind BUILD A PAR, BUILD F STP/SC
Waive — WAIVE

All Location-typed fields, not strings — there is no separate "target province name" field to keep in sync with a Location. A support-to-hold may end in a hold word (H, HOLD, HOLDS); F BRE S A PAR H parses to the same order as F BRE S A PAR. A coast is written PROV/XX or PROV(XX); on a fleet at or into a split-coast province it must be one of that province's coasts, or the order is a parse error (parse error: XX is not a coast of SPA (SPA/NC or SPA/SC)); an army's coast is ignored and a single-coast province's is dropped. Grammar/parsing lives in orders/parser.py; legality (not just grammar) in orders/validation.py; adjudication semantics for each type in adjudication.md.

OrderResult / Resolution

OrderResult(order: Order, result: ResultCode, dislodged: bool = False,
            retreat_options: tuple[Location, ...] = (), civil_disorder: bool = False)
Resolution(results: tuple[OrderResult, ...] = ())

civil_disorder is true only on a DISBAND the engine made for a power that never ordered it; its order is a synthetic Disband the power never sent. That is either an adjustment's removal for a power that ordered too few disbands (retreat_options empty) or a retreat phase's removal of a dislodged unit left without an order though it could have retreated (retreat_options lists where it could have gone). In a retreat phase, BOUNCE on a Retreat means two or more units retreated into one province and each was disbanded (adjudication.md §8). A stored result without civil_disorder (older rows) reads as false.

ResultCode: OK, BOUNCE, CUT, VOID, NO_CONVOY, DISLODGED, DISBAND, BUILD, WAIVE — see types.py's enum docstring for the precise meaning of each; the convoy-specific distinction between VOID/DISLODGED/NO_CONVOY/OK is covered in adjudication.md §6.

GameState

GameState(
    year: int, season: Season, phase_type: PhaseType,
    units: frozenset[Unit] = frozenset(),
    ownership: dict[str, str] = {},       # supply-center province -> owning power
    dislodged: tuple[DislodgedUnit, ...] = (),
    contested: frozenset[str] = frozenset(),  # standoff provinces (retreat phase only)
    status: GameStatus = GameStatus.ACTIVE,
    winners: Optional[frozenset[str]] = None,  # None until the game is COMPLETED
)

An immutable snapshot of the whole game between phases — not a mutable "current state" object. phase_name derives the canonical code ("S1901M", "F1901R", "W1901A") from season/year/phase_type. Helper queries: units_of(power), unit_at(province), centers_of(power), dislodged_at(province).

Game (src/engine/game.py) wraps a GameState with its map: MapData and a history tuple of past snapshots; Game.adjudicate(orders) is the only way to advance it, and it returns a new Game plus the phase's Resolution — nothing mutates.

2. Serialization (src/engine/serialization.py)

The one place GameState/Order/Resolution cross the pure-engine boundary into JSON. Round-trips exactly (state_from_dict(state_to_dict(s)) == s, Hypothesis-checked).

  • Location -> its canonical string (location_to_str/location_from_str): "PAR" or "SPA/SC".
  • Every enum -> its .value string.
  • frozenset/tuple fields (units, contested) -> JSON arrays (order doesn't matter for round-trip equality — they decode back into sets).
  • state_to_dict(state) -> {year, season, phase_type, units: [unit_dict...], ownership: {province: power}, dislodged: [dislodged_dict...], contested: [province...], status, winners}, winners a sorted list of powers or null (the game has not ended).
  • order_to_dict(order) -> {type, power, ...order-specific Location strings...} (see the field table above — each order type serializes exactly its own fields).
  • resolution_to_dict(resolution) -> {results: [{order, result, dislodged, retreat_options, civil_disorder}, ...]} (a stored result without civil_disorder, written before the field existed, reads back as false). resolution_to_dict writes only that; GameService.process_turn adds the rest before storing. A stored resolution also carries phase (and each result's order_str, via _resolution_dict) and eliminated: the powers that processing turn put out (sorted; absent in older rows), which the turn notification announces; centres, each power whose supply centres the turn changed, {power: {gained: [province...], lost: [...], count}} (count is how many it owns after); and unordered: true on a result whose order the engine made up because the power sent none for that unit (an implicit hold, an unordered retreat or adjustment disband), and on a WAIVE for a build the power left unused rather than waived itself. centres and unordered are absent in rows stored before v3.0.176, and an unused build's unordered before v3.0.327. units is the board the orders were given on (every unit, then the dislodged ones, as {kind, power, location}): DAIDE's ORD needs each ordered or supported unit's kind and power, which the moved board no longer shows; absent in older rows.

to_json()/state_from_json()/order_from_json()/resolution_from_json() are thin json.dumps/json.loads wrappers around the dict functions.

3. Persistence (src/persistence/)

games table (GameModel, src/persistence/database.py)

The columns that matter for game state (all nullable):

Column Type Written by Meaning
state_json JSON GameRepo.create / .save_state The serialized GameState — the authoritative source of truth for a game's board.
pending_orders JSON GameRepo.modify_pending_orders (locked read-modify-write) {power: [order_str, ...]}, submitted but not yet adjudicated; cleared after process_turn. Each is the accepted order re-rendered by format_order with the board's A/F letters and every unit it names on the coast it stands on (F STP - BOT is stored as F STP/SC - BOT), so the resolution's order_str and order_history name it too.
last_resolution JSON GameRepo.save_state / .set_histories (saved-game import) / .restore_state (admin rollback: the restored turn's predecessor's resolution_history entry, or null) The most recent resolution_to_dict() output — what /last_resolution answers and what /generate_map/resolution draws arrows from; not otherwise authoritative (superseded on the next process_turn).
order_history JSON GameRepo.save_state {turn_number_str: {power: [order_str, ...]}}, appended (never overwritten) by each process_turn in which some power ordered (a power with no orders is left out, and a turn where nobody ordered gets no key, unlike resolution_history, which has one for every processed turn) (an admin restore to turn t drops the keys >= t), using the truthful A/F-lettered order text. Powers /orders/history, which also returns phases ({turn_number_str: phase_code}, from each turn's map_snapshots row) so clients label a turn S1901M, not by its counter.
resolution_history JSON GameRepo.save_state (rewound like order_history by .restore_state) {turn_number_str: resolution_dict} — what each turn's orders did; powers /resolutions, /history/{turn} and each turn's orders map.
draw_votes JSON GameRepo.modify_draw_votes {power: "yes"} for this phase's yes votes (withdrawing a vote removes the key); cleared in the same transaction as every phase change (_write_state) and by an admin restore.
pending_deadline_proposal JSON GameRepo (locked read-modify-write) The one open majority vote on a deadline change, with its yes/no votes and optional expiry.
reminded_deadline Timestamp (naive UTC, like deadline) DatabaseService.claim_deadline_reminder The deadline whose 10-minute reminder has been sent. Claimed by one conditional UPDATE ... WHERE deadline = :d AND reminded_deadline IS DISTINCT FROM :d before sending, so a restart or a second worker never sends it twice; every write of deadline clears it, so each new deadline gets its own reminder.
phase_length_seconds Integer create_game, POST /deadline A recurring phase length a caller may arm a deadline from; never armed on its own.
deadline_schedule JSON create_game, POST /deadline/schedule The weekly schedule each phase's deadline is armed from: {"timezone": iana, "slots": [{"day": "MON", "time": "16:00"}]} (server.deadline_schedule). GET /deadline returns it with a readable description. Null = none.
phase_started_at DateTime GameRepo (every phase change) When the current phase began; order submissions composed earlier are refused (409).
dummy_powers JSON GameRepo.create / .modify_dummy_powers (locked) Sorted list of powers played by civil disorder. Never joinable, never waited on (orders_status), excluded from draw quorum and deadline-proposal majorities (GameService.active_powers). Null/[] = none; at most six. In a game whose map_name is "demo" (the bot's solo demo), process_turn gives each dummy with no orders engine.simple_ai orders, seeded by game id and phase, and records them in order_history like anyone's.
auto_process Boolean GameRepo.create / .set_auto_process Process the turn as soon as orders_status has nothing missing and no order incomplete (ready_to_auto_process), no wait flag is up and every power is seated or a dummy. Null/false = manual or deadline only.
wait_flags JSON GameRepo.modify_wait_flags {power: true} for players who asked the table to wait. Cleared in the same transaction as every phase change (GameRepo._write_state, so a processed turn or a game ended outside one) and by an admin restore; never stops a deadline or /processturn. Auto-processing re-checks it on the row it locks to write the turn (save_state(refuse_if_waiting=True), raising WaitFlagRaisedError), so a flag raised after its readiness check still holds the turn and nothing is written. A power that has left the game cannot raise one, conceding lowers its own, and one still stored for a power out of the game (eliminated_powers) is ignored by the readiness check, that locked re-check, orders_status.waiting and the view.
join_password_hash String(100) GameRepo.create / .set_join_password_hash bcrypt hash of a private game's join password; null = open. Never serialized: views and GET /games carry only private, and the saved-game export leaves it out (an imported game comes back open).
anonymous Boolean, not null, default false GameRepo.create Chosen at creation (POST /games/create anonymous, the bot's /newgame anonymous\|public, the web's create form) and never changed. True: players are known only by their power — every announcement and relayed message names the power alone (api.shared.power_label), and no API read says who holds a seat (api.shared.player_rows: user_id, nickname are null; seated says whether the seat is held). False (public): the player's nickname, when they have set one, rides along with the power, FRANCE (Anna). Carried by the saved-game export.
daide Boolean, not null, default false GameRepo.create True for the game the DAIDE listener creates on its first NME (DaideServer.ensure_game_id). Its seats are the listener's live connections, held in memory, never players rows, so the full-table rule does not apply to it (unseated_powers is empty).
random_powers Boolean, not null, default false GameRepo.create Chosen at creation (POST /games/create random_powers, the bot's /newgame … random, the web's create form) and never changed. True: a joining player does not choose a power — POST /games/{id}/join must leave power out, and the server seats them in an open power (no seat held, not a civil-disorder dummy; a vacated seat counts as open) drawn with secrets.SystemRandom, trying the others in turn if it loses a race for one. POST /games/{id}/replace, which names a power, is refused (400). False: the joiner names the power. Either way the join response carries the power taken. Carried by the saved-game export.
channel_id String(255), unique when not null (partial index uq_games_channel_id) DatabaseService.link_game_to_channel / .unlink_game_from_channel The Telegram group (or channel) chat id the game belongs to; channel_settings holds its posting settings and channel_name. A group has at most one game: linking another game to it unlinks the previous one in the same transaction (link_game_to_channel returns that game's id), and only a player of the previous game (displacer_user_id) or an admin may (ChannelTakenError otherwise; see architecture.md §Notifications). Set only by the bot, with the chat a command was typed in, or by an admin (POST /games/{id}/channel/link), or at creation by POST /games/create channel_id (bot only, /newgame), which deletes the new game again if the link is refused. DatabaseService.get_game_by_channel is the reverse lookup behind GET /channels/{chat_id}/game. Null = no group.
created_by_user_id Integer FK users.id, ON DELETE SET NULL GameRepo.create Who created the game (Bearer user, or the bot's telegram_id). Null for waiting-list games. Only the creator (or X-Admin-Token) may change dummy_powers or the join password, or end a turn early.

Plus denormalized convenience columns kept in sync for code that doesn't want to parse state_json (deadline scheduler, game listings, channel posts): map_name, current_turn, current_year, phase_code, status, deadline, channel_settings, created_at, updated_at. current_turn counts processed turns: save_state adds one and keys the turn's order_history/resolution_history entries by the number it leaves behind, and the board it reaches gets the map_snapshots row with the new number. A game ended outside a turn (a draw, a concession, a seat made a dummy: GameRepo.end_game_if) keeps its number, and an admin restore of the snapshot of turn t sets it back to t. phase_code is always state_json's own phase (GameState.phase_name): it is what every phase-checked write compares against (expected_phase_code), so GameService.restore_snapshot refuses a phase_code that differs from the board's (ValueError). A saved-game import (POST /games/import) takes it from the imported board, and refuses with 400, before creating anything, a document whose game.phase_code disagrees with that board, a players entry naming an unknown power or a power twice, a message timestamp that is not ISO 8601 (an aware one is stored as naive UTC), or a snapshot whose state does not parse or whose phase_code is not that state's phase.

There are no relational unit, order or supply-centre tables: state_json holds the board, and map_snapshots one row per turn: the board the turn began on (turn 0, the opening board, is written by GameRepo.create; every later one by GameRepo.save_state, in the transaction that processes the turn before it, under the turn number that write produces; an admin restore of turn t's row deletes the rows after it, boards the restored game never reached, which the replayed turns write afresh). (game_id, turn_number) is unique (uq_map_snapshots_game_turn): every writer goes through persistence.database.upsert_map_snapshot, so a second write of a turn replaces that row's board (keeping its id, created_at and map_image_path) instead of adding a row. POST /games/{id}/snapshot only adds a missing row: it reads the board and the turn number separately, and a turn processed in between would pair the new number with the old board. A saved-game import skips the turns already recorded. /history/{turn}, /map/history/{turn} and /map/turn/{turn}/orders read it, {turn} being a number or a phase code (S1901M, the board that began that phase; 400 for neither, 404 for a phase not reached); for a game created before the turn-0 row existed they fall back to the opening board, which every game starts from.

players table (PlayerModel)

Player-to-power assignment is not an engine concern. Columns: id, game_id (FK, cascade), power_name, user_id (FK to users), is_active, is_eliminated, home_supply_centers (JSON), controlled_supply_centers (JSON), orders_submitted, last_order_time, created_at; (game_id, power_name) is unique. Only user_id and is_active are read for the API view: the board's state_json is the truth for centres, and whether a power is out is not read from is_eliminated either but derived from the board by GameService.eliminated_powers (a power with no units and no centres, which is also what a concession leaves; empty for an ended game), the set behind out in /players (§4) and the powers orders_status leaves out. GameRepo.players(game_id) reads this into {power: {user_id, is_active}} for the API view (§4); in an anonymous game the view nulls user_id and adds seated.

Other tables

users (email + password_hash for web login, telegram_id, and an optional nickname — unique ignoring case, chosen by the player; no real names are stored, nothing is copied from a Telegram profile), link_codes, password_reset_tokens, messages, map_snapshots (the board at the start of each turn, with its state_json), waiting_list, bot_outbox, feedback — see database.py for the full model list. DatabaseService (database_service.py) is the DAL for all of these; only game state lives in GameRepo + GameService.

Table / column Purpose
bot_outbox Everything waiting for the bot to send: kind (dm, channel_text, channel_map, channel_create_thread), telegram_id (a user or a group chat), message, payload (buttons, parse_mode, a map's path, …), created_at, delivered_at (NULL = pending), attempts, last_error. The bot pulls and acks; delivered rows are purged after 7 days.
feedback Player reports (POST /feedback, the bot's /feedback): user_id (FK users, SET NULL), source (telegram/web), game_id (the public id as given; not a FK, so a report outlives its game), phase_code (that game's phase when reported), text (≤ 2000 chars), created_at. At most 10 per player per hour. GET /admin/feedback lists them.
idempotency_keys First response stored per bot-supplied Idempotency-Key: key, endpoint, status_code, response_json, created_at. status_code 0 marks a key reserved by a request still running (no reply yet; response_json NULL); a reservation older than 5 minutes is taken over. Purged after 7 days.
messages.timestamp The time the message was composed when the client sends client_timestamp; otherwise now.
messages.anonymous A rumour: a broadcast (recipient_power NULL) sent with anonymous: true. sender_user_id is still stored, for the record and the admin export, but no player-facing read or notification names the sender. Default false.

4. The HTTP API view shape

GameService.view(game_id) (src/server/game_service.py) is the single place that builds the JSON a client sees for GET /games/{id}/state (and equivalent DAIDE/bot paths) — built directly from GameState:

{
  "game_id": "1",
  "map_name": "standard",
  "phase": "S1901M",                    // GameState.phase_name
  "year": 1901,
  "season": "SPRING",
  "phase_type": "MOVEMENT",             // MOVEMENT | RETREAT | ADJUSTMENT
  "status": "ACTIVE",                   // ACTIVE | COMPLETED (GameStatus also has FORMING, but
                                        // nothing sets it: a game is created ACTIVE)
  "winners": null,                      // null while ACTIVE; once COMPLETED: one power (a solo,
                                        // or the last power standing), several (a draw), or []
                                        // (nobody was left: the last powers conceded together)
  "units": [ {"kind": "F", "power": "FRANCE", "location": "BRE"}, ... ],
  "units_by_power": { "FRANCE": [ ... ], ... },
  "ownership": { "PAR": "FRANCE", ... },
  "supply_centers": { "PAR": "FRANCE", ... },  // == ownership; kept as an alias for callers
  "dislodged": [
    {"unit": {...}, "attacker_origin": "BUR", "retreats": ["PIC", "GAS"]}
  ],
  "contested": ["BUR"],
  "players": { "FRANCE": {"user_id": 42, "is_active": true}, ... },
                                        // anonymous game: {"user_id": null, "is_active": true, "seated": true}
  "dummy_powers": ["TURKEY"],           // played by civil disorder; [] if none
  "auto_process": false,                // turn runs by itself once every unit has an order
  "wait_flags": ["ENGLAND"],            // powers that asked the table to wait
  "private": false,                     // joining needs a password (never the hash)
  "anonymous": false,                   // players known only by their power (games.anonymous)
  "random_powers": false,               // joiners are dealt an open power (games.random_powers)
  "created_by_user_id": 7               // the creator; null when anonymous (the view is public)
}

Who a player is known as. GET /games/{id}/players returns one row per seat: power, seated, is_active, out, user_id, nickname — the last two null in an anonymous game. out is true for a power that conceded or was eliminated (the set orders_status and draw_vote_status leave out); its seat keeps seated. It never carries a Telegram id: the route needs no login, and that id names a real Telegram account. GET /games lists each game's anonymous and random_powers flags and its seats as {power, seated, user_id} (user_id null when anonymous). GET /games/{id}/messages gives each message's sender_power (the seat its sender holds now; null if they left) and, in a public game only, sender_name; an anonymous game nulls sender_user_id. Each message also carries anonymous: for a rumour, sender_user_id, sender_power and sender_name are null for every reader except the sender themself, who sees their own. Without credentials the list holds broadcasts only; with them, also the caller's own private messages; credentials that don't check out are a 401. POST /games/{id}/message and /broadcast refuse blank text and text over 3500 UTF-16 units with a 400 (docs/specs/architecture.md §Notifications, "Message text"). A client finds its own seat in an anonymous game from GET /users/me/games (or /users/{telegram_id}/games). Each row there carries game_id, map_name, power, current_turn, phase_code (the game's phase, e.g. S1901M; the web list shows it as "Spring 1901"), status and is_creator. POST /auth/me/link_code returns {code, expires_in_seconds, expires_at, bot_username}; bot_username is the bot's Telegram username (DIPLOMACY_BOT_USERNAME, default IronChancellorBot), which the /link-telegram page links as t.me/<it>. The player sends the code to the bot (/link <code>), and the bot redeems it with POST /auth/telegram/link {telegram_id, code}, which takes the bot secret only (401 otherwise, and the code stays unused): the body's telegram_id is trusted as the account that sent the code, which only the bot can vouch for. If that Telegram account already exists without a web login, it takes over the code's web login (merged: true).

The view carries no pending orders. It is public (GET /games/{id}/state needs no login, and game ids are sequential), and orders are secret until the turn is processed. A player reads their own from GET /games/{id}/orders/{power} (or GET /games/{id}/orders), which answer only the user holding that power; server code reads them from GameService.pending_orders_view (every power, for trusted callers only). Those lists are re-derived every call via _humanize_orders: stored pending-order strings are reparsed and reformatted against the current board so the A/F unit letter is always correct (a fleet at a non-split-coast province displays F, not the coast-inferred guess format_order would otherwise produce — see orders/parser.py's format_order docstring). This is a display-only correction; adjudication always uses the actual board unit, never the letter in the order string. Once a turn is processed its orders are public: /history/{turn}, /orders/history, /map/turn/{turn}/orders.

Consumers of this exact shape: frontend/src (React SPA — GameView.tsx and friends), the Telegram bot, and src/server/daide/session.py.

Resolution-result shapes: POST .../process_turn and GET .../last_resolution

Who may call it: the game's creator (games.created_by_user_id) — as a Bearer user, or as a Telegram player when the bot passes their telegram_id in the JSON body — plus the bare bot secret and the admin token. Anyone else, seated or not, gets 403; a game nobody created (a waiting-list game) can be ended early only by an admin. The game view carries created_by_user_id so the web shows "Process turn" only to the creator (null in an anonymous game, whose public view must not link a user id to its creator; the web then reads is_creator from GET /users/me/games), and GET /users/{telegram_id}/games marks created games with is_creator: true for the bot. A game with a power that is neither seated nor a dummy is refused with 409, the header X-Error-Code: seats_unfilled (the name a client switches on) and the detail "N powers are unseated (Austria, ...): seat players or mark them as dummies.", whoever calls (see architecture.md, "A turn is processed only at a full table"). Orders, draw votes and concessions get the same 409 and header, the detail prefixed with Game N hasn't started:, until the table is full or a turn has been processed (architecture.md, "Nothing is played before the game starts"); POST /games/{id}/concede returns {status, power, game_status, eliminated, winners, how, auto_processed}, winners naming the last power standing when the concession ended the game (else []; a concession that left nobody, or only dummies, also ends it, game_status: "COMPLETED" with winners: []), or the draw's sharers when it completed the draw votes already cast. how is null while the game goes on, else GameService.ending's: "last_standing", "no_winner", "only_dummies" or "draw". POST /games/{id}/dummies returns {status, dummy_powers, ended, winners}: ended is that same how when making the seat a dummy ended the game (the draw votes already cast were complete, or only dummies are left), else null, and winners is then the draw's sharers ([] otherwise).

POST /games/{id}/process_turn (api/routes/games.py) returns, additively (the pre-existing status: "ok" key is unchanged so existing clients keep working):

{
  "status": "ok",
  "phase": "F1901M",           // the phase the game is in once the call returns: the phase
                                // adjudication reached, or a later one when phases that needed
                                // nobody were run (BV2) or auto-processing ran the next turn
  "game_status": "ACTIVE",     // the game's status at that same point -- "status" was already
                                // taken by the pre-existing "ok" key above
  "resolution": {              // the stored resolution of the turn just adjudicated
    "phase": "S1901M",         // the phase it adjudicated
    "eliminated": [],          // powers this turn put out (not an earlier concession), sorted
    "centres": {"FRANCE": {"gained": ["BEL"], "lost": [], "count": 6}},  // per power whose centres changed (Fall only)
    "units": [{"kind": "A", "power": "FRANCE", "location": "PAR"}, ...],  // the board the orders were given on
    "results": [ ... ]         // per-result shape below, without `power`, `reason`,
                                // `bounced_off` or `bounced_with`
  },
  "results": ["Your results for Winter 1901 builds:", "F MAR was built."]
                                // the caller's own turn-DM results lines, only when the caller was
                                // left out of the DMs (they get none) and the DM would have carried
                                // them; otherwise []. The bot shows them in its reply.
}

That is the dict GameService.process_turn stores (and resolution_history keeps): the engine's resolution_to_dict (results, §2) plus fields GameService adds, not the serializer: phase and each result's order_str (_resolution_dict), then eliminated, centres, units (the pre-adjudication board, §1 above) and, on a result for a unit the power gave no order (the engine made one up), unordered: true. A result's power, reason, bounced_off and bounced_with are not stored: reads derive them.

GET /games/{id}/resolutions is {"game_id", "resolutions": {turn: resolution}}, every stored turn with the stored phase and its results decorated exactly as /last_resolution's (GameService.resolution_history_view: power, order_str, reason, bounced_off, bounced_with). Like /last_resolution it needs no auth and hides nothing: adjudicated outcomes are public. The web's "Previous turns" selector reads it (the newest turn is the "last turn" section above it).

GET /games/{id}/last_resolution (added so a client can re-fetch this after a page reload, since the inline process_turn response above isn't persisted client-side) returns 404 when the game doesn't exist, {"results": []} when it exists but no turn has been processed yet, else GameService.last_resolution_view: only results (and movement, below), decorated, and not the stored dict: no phase, eliminated or centres. Each result is the stored one plus power and, where they apply, reason, bounced_off and bounced_with:

{
  "results": [
    {
      "order": {"type": "MOVE", "power": "FRANCE", "unit": "PAR", "dest": "BUR", "via_convoy": false},
      "result": "BOUNCE",       // engine.types.ResultCode -- OK/BOUNCE/CUT/VOID/NO_CONVOY/DISLODGED/DISBAND/BUILD/WAIVE
      "dislodged": false,
      "retreat_options": [],
      "civil_disorder": false,  // true: a DISBAND made for the power, which never ordered it
      "order_str": "A PAR - BUR", // format_order(order), stored by process_turn against the
                                   // pre-adjudication board; a resolution stored before that
                                   // falls back to format_order without the board's
                                   // kind_by_province, so a fleet at a non-split-coast
                                   // province may print as "A"
      "unordered": true,        // only when set: the power gave this unit no order
      "power": "FRANCE",        // convenience: same as order.power, flattened
      "reason": "it would dislodge your own F TRI", // only when set, see below
      "bounced_off": "GERMANY's A MUN",  // only on a BOUNCE move: the unit that kept the
                                          // destination (held, failed to leave, or swapped)
      "bounced_with": ["GERMANY's A RUH"] // only on a BOUNCE move: the other units that moved
                                          // there (GameService.bounce_rivals); either key is
                                          // absent when no such rival is found
    },
    ...
  ]
}

When the last resolution is a retreat phase's (each stored resolution carries a top-level "phase", the code of the phase it adjudicated, e.g. "F1901R"; rows stored before that fall back to a RETREAT order among its results) and the turn before it is a movement phase's, the response also carries "movement": {"results": [...]}, that movement phase's results in the same shape, so a client can show why a power has builds or disbands after the retreat (GameService._movement_before_retreat).

In both responses order and the bare result/dislodged/retreat_options/civil_disorder fields are exactly engine.serialization.resolution_to_dict()'s canonical per-OrderResult shape (§2), passed through unchanged; /last_resolution adds power on top, and reason where the code alone would mislead (GameService.result_reason, read from the same resolution's other results): a VOID support of a move onto a unit of the supporter's own power that stayed, "it would dislodge your own F TRI", and a NO_CONVOY move or convoy whose convoying fleet was dislodged, "F NTH was dislodged" (GameService.last_resolution_view). This is what a client uses to answer "what happened to my orders?" without re-deriving adjudication itself. The web results list (OrderEntry.tsx ResultList, text from lib/resultText.ts describeResult) shows an adjustment's civil_disorder result as "Disbanded by civil disorder: too few disbands were ordered, so the unit farthest from its home centres was removed.", a retreat phase's (one with retreat_options) as "Disbanded by civil disorder: no retreat was ordered.", a bounced retreat as "Retreat bounced: another unit retreated to the same province, and the unit was disbanded.", a DISBAND on a Retreat order as "The retreat was not legal — the unit was disbanded." and an ordered disband as "Unit was disbanded."; a result with a reason reads "Had no effect: it would dislodge your own F TRI." (VOID) or "Convoy failed — F NTH was dislodged, so the move did not happen." (NO_CONVOY).

Order/resolution overlay maps: GET .../map/orders, GET .../map/resolution

GET /games/{id}/map streams the current board as PNG bytes. Two more GET routes mirror it with overlay arrows drawn on top, so a browser can render them directly (the older POST .../generate_map/orders and .../generate_map/resolution return {"map_path": "/tmp/diplomacy_maps/..."} — a server-filesystem path, unreachable from a browser; both routes are kept for existing server-side callers):

  • GET /games/{id}/map/orders — the board plus arrows for the caller's own pending orders (plain board if none submitted yet). Players in the game only (Bearer, or a telegram_id query parameter with the bot secret in the X-Bot-Secret header); anyone else gets 403, since pending orders are secret. The web client fetches it with its token and shows it from a blob URL, as an <img src> sends no credentials. POST .../generate_map/orders draws every power's pending orders and so takes the bot secret only; POST .../generate_map and .../generate_map/resolution (like POST .../snapshot) take the bot secret or a signed-in user seated in or creator of the game (require_bot_or_game_member), 403 for anyone else.
  • GET /games/{id}/map/resolution — the board plus arrows for the last processed turn's orders, coloured by ResultCode, plus standoff markers (plain board if no turn has been processed yet).

Both return image/png bytes with the same 404-on-missing-game behavior as GET .../map, and lean on Map.render_board_png*'s own disk-backed byte cache rather than a second caching layer (see get_map_preview_png's docstring in maps.py).

The sandbox: POST /sandbox/*

The web sandbox (routes/sandbox.py) lets a player order every power on a scratch board and step it through movement, retreat and adjustment phases. It stores nothing: the client holds the board as a serialized GameState (state_to_dict, §2) and sends it with every request. Because it is client-supplied, GameService.sandbox_state validates it before use (400 Invalid sandbox board: ...): known powers and provinces only, each unit where its kind can stand (a fleet on a named coast of a split-coast province), one unit per province, ownership of supply centres only, dislodged units only in a retreat phase. All four routes need a signed-in caller (require_bot_or_user: the bot secret, or the access token of a user who exists and is active; otherwise 401).

Route Body Returns
POST /sandbox/start {game_id?} {source_game_id, state, view}: that game's current board (404 if unknown), or the opening position
POST /sandbox/legal_orders {state, power} legal_orders_for_power, the shape of GET /games/{id}/legal_orders/{power}
POST /sandbox/adjudicate {state, orders: {power: [order_str]}} {order_results: {power: [{order, ok, reason}]}, resolution, state, view}; 409 once the board's game is over
POST /sandbox/map {state, orders, overlay} (board, orders or resolution) image/png: the board, the orders as pending arrows, or the orders adjudicated on this board and coloured by result

view is GameService.sandbox_view: the board fields of §4 (phase, phase_type, units_by_power, ownership, dislodged, contested, status, winners, ...) plus powers_to_order (powers_with_orders_to_give). Orders are validated exactly as submit_orders validates them; a refused order is reported and left out, so its unit holds. resolution results carry power and a truthful order_str, as last_resolution does. At most 40 orders per power are accepted.

5. Validation

Order legality (not grammar — grammar is orders/parser.py's job) is centralized in orders/validation.py's validate(order, state, map) -> ValidationResult, the one path used by GameService.submit_orders (pre-check before an order is accepted into pending_orders) and by adjudicator/adjustments.py (build legality). There is no second, divergent validation path anywhere in the codebase.

The first check is the phase: an order whose kind has no meaning in state.phase_type is refused before any unit or topology check, with a reason that names the phase (a move order is not accepted during the retreat phase (S1901R); only retreat and disband (for dislodged units) orders are). Movement takes Hold / Move / SupportHold / SupportMove / Convoy; Retreat takes Retreat / Disband; Adjustment takes Build / Disband / Waive. The adjudicators already ignore orders from the wrong phase, so without this gate a build typed during a movement phase, or a move typed during a retreat or build phase, was accepted with ok=True, stored, shown as pending, and then dropped without a word — which for an adjustment phase meant a player's build was silently waived. Interactive menus never offered such orders (legal_orders.py is phase-aware); the gate covers free-text input from every client. One case gets a hint instead of the list: a move by a unit that is dislodged in this retreat phase is a retreat written as a move, so it is refused with the retreat spelling (a move order is not accepted during the retreat phase (S1901R); to retreat, write A BUR R RUH). It is refused rather than read as a retreat so that each order string has one meaning in every phase and what is stored is what the player wrote. If the move is written with the wrong unit letter (F WAR - LVN for an army), the kind check wins: the unit in WAR is an army, not a fleet, as for every other order.

Moves and convoys. A non-adjacent army move between two coastal provinces is a convoyed move, written with or without VIA (the rulebook writes A Lon-Bel); it is accepted like A LON - BEL VIA, and adjudication treats it as convoyed (adjudication.md §6). The submission result carries the order helper's convoy note (below) as its note: the fleets that could carry it ("A LON - NWY needs a convoy: it can succeed only if F NTH convoys it"), or that none can this turn; none when the player's own convoy orders already carry it. A support of a move onto the supporter's own unit is accepted (it is legal) with the note "your own F TRI is there: this support has no effect unless it moves away" (DATC 6.D.10). Any other non-adjacent move is refused (BEL is not adjacent to MUN). A move into a province that borders the unit's but that the unit cannot enter says why instead, through retreats.unreachable_reason (topology from MapData only): A MAR cannot reach LYO: an army cannot enter a sea, F MAR cannot reach BUR: a fleet cannot enter an inland province, F LYO cannot reach SPA/NC: a fleet in LYO can reach only SPA/SC, F SPA/NC cannot reach MAR: MAR borders SPA only from SPA/SC, or F ROM cannot reach VEN: ROM and VEN share no coastline, so a fleet cannot move between them. A move to the unit's own province is refused as well (LON cannot move to its own province); a support of a move into the supporter's own province is refused as such (VEN cannot support a move into its own province), not as out of reach. A support or convoy of a move from a province into itself is refused, since no such move exists and the adjudicator voids it: A PAR S A BUR - BUR says BUR cannot move to its own province, so there is no move to support, F NTH C A LON - LON the same ending to convoy; provinces are compared, so S F SPA/NC - SPA/SC is refused too. A unit supporting itself, to hold or to move (A WAR S A WAR - UKR), is refused (a unit cannot support itself). A fleet moving to a split-coast province (BUL, SPA, STP) without naming a coast is accepted when exactly one coast is reachable from where it stands (F BLA - BUL arrives on BUL/EC; the adjudicator infers it), refused as ambiguous when both are (fleet move into split-coast BUL must name a coast (BUL/EC or BUL/SC)), and refused as not adjacent when neither is (BUL is not adjacent to ANK). A Convoy is refused unless an army stands at its origin (no army at ALB to convoy, the unit at ALB is a fleet; only an army can be convoyed). submit_orders stores each accepted order as format_order writes it with the board's real unit letters, and refuses (as one ok=False entry, parse error: ...) any order whose stored form would not parse back, so a single bad order can never fail the batch.

Retreats. A Retreat is legal iff its destination is in the dislodged unit's precomputed retreats (adjudication.md §8); a fleet naming no coast gets the sole legal coast, as a move does, and must name one when two are legal. A refusal says why, through retreats.retreat_refusal (the same rules as compute_retreat_options): BUR is not a legal retreat for A PAR: followed by the unit that dislodged it attacked from there, another unit stands there, a standoff left it empty this turn, and no unit may retreat there, or it is not adjacent to PAR (or, when the provinces border, the same clause as a move's: an army cannot enter a sea, ...).

In an adjustment phase an order must also be on the right side of the power's delta (centres minus units): a Build or Waive needs a positive delta and a Disband a negative one (FRANCE has no unit to disband (3 supply centres, 1 unit); it may build 2 units). For a power that owes the other way this is checked before the order's own checks, so BUILD A BER from a power owing disbands says it must disband, not that BER is occupied; at a zero delta the order's own reason comes first (no unit to disband at PIC). The adjudicator voids anything else. The count is a whole-submission rule and lives in GameService._check_orders: a submission may hold at most adjustments_owed builds/waives (the delta, capped at the vacant owned home centres — the adjustment.slots of legal_orders, which also carries the centers and units the delta is made of) or disbands; the later ones beyond it are refused (ENGLAND has 1 build; 2 builds/waives submitted). When orders are merged (merge=true, every bot path) the stored ones are trimmed to make room for the new ones — stored waives first, then the oldest — so the stored list never exceeds the count: a WAIVE sent after BUILD F KIE replaces it, as a build sent after a waive does. The player is told (POST /games/set_orders with no order in it is a 400; GET /games/{id}/legal_orders/{power} for a name that is not a power is a 400 naming the powers): each POST /games/set_orders result is {order, success, error, replaced, note, superseded_by, stored, notes}, where stored is the canonical form kept for an accepted order (F SPA R POR -> F SPA/SC R POR; null when refused or superseded) and the bot echoes it in place of the typed text, and replaced lists the stored orders that accepted order pushed out (stored form, oldest first; [] when none) and note says so (replaced BUILD F BRE (you may build 1), or you must disband N for disbands; null when nothing was replaced). The pushed-out orders go to the submission's accepted orders in turn. The bot appends the note to the order's line (✅ BUILD A PAR replaced BUILD F BRE (you may build 1)), in the immediate reply and in the delivery DM of a queued submission; the interactive pick adds ↩️ This replaced BUILD F BRE (you may build 1). The web client sends merge=false, which replaces the power's stored orders. A request in which none of the submitted orders is accepted changes nothing: the power keeps the orders it had, and the first result carries a note (none of these orders was accepted, so nothing was changed. Your earlier orders stand: BUILD F BRE; replaced stays empty); the web client appends it to its "Not accepted" message. An accepted full set reports no replacement.

An army build names no coast: BUILD A STP/NC is refused at parse time (parse error: an army build may not specify a coast), like the validator's refusal of an army build with a coast; it used to be stored as BUILD A STP.

Two orders for one unit (or build site) in a single request: the later one stands. The earlier is not a failure -- the request did store an order for that unit -- so its result is success: true, error: null, superseded_by the later order's text as sent, and note replaced by a later order in this submission: <later>; every other result has superseded_by: null. Clients that count success: false as refused therefore never show such a unit as unordered; the bot prints the note after the ✅.

GameService.orders_status (and so GET /games/{id}/orders_status and process_turn?require_all=true) counts only the powers that have a decision to make this phase, via server.legal_orders.powers_with_orders_to_give: every power with a unit in a movement phase, only powers with a dislodged unit that has at least one retreat option (DislodgedUnit.retreats, from compute_retreat_options) in a retreat phase, and in an adjustment phase only powers that must disband or that are owed a build and have a vacant owned home centre to put it on. A power legal_orders_for_power would offer nothing but WAIVE, or nothing but disbands of units with nowhere to retreat, is not waited on: the adjudicator waives or disbands for it anyway, so it is in nothing_to_do. A power with one unit that can retreat is waited on, and owes an order for that unit only (a trapped unit needs none to make it complete).

Those powers (civil-disorder dummies left out) are active_powers, and each of them is in exactly one of submitted — it has at least one stored order this phase — and missing. An empty stored list (what a submission whose every order was refused leaves) is missing, not submitted. incomplete is the part of submitted that has not yet ordered everything that must act. nothing_to_do lists every other non-dummy power still in the game (a unit or a centre): no order is due from it, so it is neither submitted nor waited on. The bot's /status and the web turn-status card show the three groups separately; the card also names the incomplete powers, since auto-processing waits for them. The web order panel, which tells the player "a unit with no order holds" (in a retreat phase, "is disbanded"), sends that default explicitly for every unit left blank (A PAR H, D A PAR), so a power submitting from the panel is never incomplete; orders typed into the text fallback are sent as written. The route adds unseated: the powers with neither a seat nor dummy status, while which no turn is processed (empty for the DAIDE listener's game, games.daide).

Order helper notes

server/order_notes.py (pure, beside legal_orders.py) explains orders as the player gives them: order_notes(map, state, power, orders) takes the board and the power's own order set (a later valid order for a unit replaces an earlier one) and returns {orders: [{order, ok, notes}], notes}. Each note is {kind, code, text}:

  • kind: "impossible" -- refused, or accepted but unable to succeed whatever anyone orders, with what would work: an army move across water names the fleet chains that could convoy it (needs_convoy, alternatives joined by "or if"; no_convoy_route when no chain of fleets at sea links the two coasts; inland_army, inland_destination), fleet_inland, army_to_sea, not_an_army (a fleet moving VIA), name_coast / wrong_coast (the coasts the fleet can reach), support_out_of_reach (and the player's units that could give it), convoy_from_coast, convoy_by_army, convoy_no_army, convoy_of_fleet, convoy_inland, convoy_off_route (no possible route passes the fleet), retreat_refused (why, from retreat_refusal, and the retreats there are), no_build_due, build_site, build_wrong_unit (the builds there are).
  • kind: "warning" -- accepted, but it depends on something: needs_convoy when no route is carried by the player's own convoy orders (foreign fleets are named with their power, France's F ENG), support_mismatch / support_moving_unit / convoy_mismatch (the player's own supported or convoyed unit is ordered otherwise, or has no order), same_destination (two own units into one province), own_unit_support (a support for an attack on the player's own unit, DATC 6.D.10). Set notes: unordered (a unit with no order holds; a dislodged one is disbanded), builds_left, disbands_left.

Nothing may reveal another power's pending orders: the function has no input for them, and GameService.order_notes reads only the requesting power's stored orders. A note may name a foreign unit on the board (every player sees it), never what it was told to do. POST /games/set_orders gives each result its notes, computed against the power's whole stored set after the write, and a top-level notes for the set; POST /games/{id}/orders/{power}/notes ({orders, merge}, only the power's own player) explains a draft before submitting it -- the whole set, the stored set (orders: null), or picks laid over the stored orders (merge: true, as the bot submits). It stores nothing. The sandbox's order_results carry the same notes.

Where players see them: the web game page lists the draft's notes under the order form as it changes (components/OrderNotes.tsx, the read route, debounced; nothing when the draft is empty or the helper is unreachable). The bot shows a result's notes as 💡 lines under its ✅/❌ line (format_order_results, every submission path and the queued delivery report), on a single pick's reply, and on the /orderall summary before Submit (the read route with the picks, merge as the walk will submit). A note the result's note already says is not repeated.

6. Out of scope here

Full DB migration history: alembic/versions/. Route-by-route request/response models: the route modules themselves, or the generated OpenAPI schema at /docs. The adjudication algorithm that produces Resolution/next-GameState: adjudication.md.