Architecture¶
For the adjudication algorithm itself see
adjudication.md; for the wire/DB shapes seedata_spec.md.
Processes¶
Telegram Bot ──┐
React SPA ─────┼──► FastAPI (port 8000) ──► GameService ──► GameRepo ──► Postgres
DAIDE clients ─┘ │ │
│ └─ (state_json / pending_orders /
│ last_resolution / order_history)
└── engine.Game (pure logic, no I/O) ──► src/rendering (PNG maps)
Five things talk to one Postgres database: the FastAPI HTTP server, the Telegram bot (a
thin HTTP client, never touches the engine or DB directly), the React SPA, DAIDE TCP
clients (a real asyncio listener, src/server/daide/, started alongside the API
process — see "DAIDE protocol support" below), and the deadline scheduler background task
inside the API process. The scheduler's loop sleeps on the event loop but does each 30-second
tick's work (processing due turns, reminders, proposal expiry, housekeeping) on a worker
thread (asyncio.to_thread), so processing a turn never stalls the API or DAIDE clients.
A tick reads every active game once and then works through them, each taking seconds, so
before processing a due game it re-reads it and skips it unless it is still in the phase it
saw with a deadline still due; it passes that phase to GameService.process_turn as
expected_phase_code, which raises StaleGameError if the stored phase has moved on. A
game another path processed meanwhile is never adjudicated again with no orders. The
creator's POST /games/{id}/process_turn pins the same way: it passes the phase it read as
expected_phase_code, and a client may send the phase it saw in the body
({"expected_phase_code": "S1901M"}; the web and the bot's confirm button do). A phase that
has moved on is a 409 with X-Error-Code: phase_moved ("Phase S1901M has already been
processed: the game is now in F1901M. …"), and nothing is processed.
Package boundaries¶
src/engine/ # PURE rules core — stdlib only, no I/O, no DB, no rendering
types.py # frozen dataclasses: Location, Unit, Order variants, GameState,
# Resolution, DislodgedUnit; enums (UnitKind, Season, PhaseType,
# OrderType, ResultCode, GameStatus)
map_loader.py # .map file -> MapData; coasts first-class; topology only
orders/parser.py # order grammar: coasts, VIA convoy, aliases; parse + format
orders/validation.py # the one validation path: validate(order, state, map)
adjudicator/movement.py # Kruijswijk fixed-point resolver — see adjudication.md
adjudicator/retreats.py # retreat legality + phase
adjudicator/adjustments.py # builds/disbands/civil disorder
game.py # phase machine over immutable GameState snapshots
serialization.py # canonical GameState/Order/Resolution <-> JSON (one place)
simple_ai.py # dumb heuristic order generator for demo/AI-filled games
src/persistence/ # SQLAlchemy models + DAL
database.py # ORM models (GameModel, UserModel, PlayerModel, ...)
database_service.py # DatabaseService — CRUD for players/users/messages/channels/
# etc.; game *state* itself is delegated to...
game_repo.py # ...GameRepo: state_json/pending_orders/last_resolution/
# order and resolution histories
src/rendering/ # SVG -> PNG map rendering
board.py, overlays.py, # the board and units, order/outcome symbols, footer key,
arrows.py, tokens.py ... # cache; map.py is the Map namespace over them
view_adapter.py # GameService.view dict -> renderer inputs
order_overlay.py # adapts engine Order/Resolution into the overlay's order dicts
visualization_config.py # colors/sizes/layout config
src/server/ # FastAPI app, CLI Server, DAIDE, Telegram bot
game_service.py # THE single entry point from server code into the engine —
# wraps engine.Game + serialization + parser/validation over
# GameRepo. Routes/CLI/DAIDE never touch engine internals directly.
api/routes/ # games, orders, users, auth, messages, maps, channels, admin,
# waiting_list, bot_outbox, archive, feedback, sandbox
legal_orders.py # pure: every legal order for a power this phase
order_notes.py # pure: why an order is impossible / what it depends on,
# from the board and the power's own orders only
telegram_bot/ # thin HTTP client over the API — see below
daide/ # the DAIDE TCP protocol — see below
server.py # text-command CLI surface (CREATE_GAME, ADD_PLAYER, ...),
# used by tests; independent of the HTTP API
Key discipline: src/engine/ imports nothing but stdlib. Nothing
in it knows about SQLAlchemy, FastAPI, Pillow, or JSON serialization frameworks —
tests/engine/test_purity.py checks every import statement. Everything else
(persistence, rendering, the HTTP/bot/DAIDE surfaces) is an adapter around
GameService, which is the only thing that constructs engine.game.Game instances,
calls adjudicate(), or reaches into orders/parser.py and orders/validation.py.
Two pure server-side modules sit beside GameService and take MapData + GameState
directly: legal_orders.py (what a power may order) and order_notes.py (the order
helper: why an order is impossible, or what it depends on; data_spec.md §Order helper
notes). Both answer from the board and one power's own orders, so every client -- the
web game page, the bot, the sandbox -- shows the same thing. order_notes never receives
another power's pending orders: those are secret until the turn is processed.
Engine design decisions (see adjudication.md for the algorithm)¶
- Immutability. Every engine type is a frozen dataclass, hashable except
GameState(itsownershipis adict). Adjudication is a pure function(map, state, orders) -> (Resolution, new_state).Gamewraps the current state plus a tuple of past snapshots (history); nothing mutates in place. Location = (province, coast|None)everywhere. A fleet in Spain is atLocation("SPA", "SC"). Armies never carry a coast. There are no hardcoded adjacency/coast tables anywhere in the engine —map_loader.pyis the only reader ofmaps/standard.map, which is the sole topology source.- Kruijswijk fixed-point resolver. Per-order state UNRESOLVED/GUESSING/RESOLVED;
recursive resolve with dependency-cycle detection; circular movement succeeds,
convoy-entangled cycles apply the Szykman rule. Full writeup:
adjudication.md. - Phases:
S{y}M -> [S{y}R] -> F{y}M -> [F{y}R] -> [W{y}A] -> S{y+1}M -> ...; a retreat phase is inserted only when the preceding movement dislodged a unit; an adjustment phase only when some power's unit count differs from its supply-center count; SC ownership updates once, after the Fall turn settles; victory at 18 centers.
State persistence¶
A game row (games table) stores the whole GameState as state_json
(engine.serialization.state_to_dict), not a normalized relational breakdown of units
and orders. Alongside it: pending_orders ({power: [order_str]}, submitted but not yet
adjudicated), last_resolution (the most recent Resolution, kept only so the
resolution-map renderer has something to draw arrows from), and order_history
({turn: {power: [order_str]}}, appended on every process_turn, powering the
Telegram bot's order-history view). Player-to-power assignments live in the separate
players table (never engine-coupled). See data_spec.md for the exact column list.
GameService (src/server/game_service.py) is the funnel:
create_game / submit_orders / process_turn / view / last_resolution /
order_history. process_turn loads state_json, parses pending_orders, calls
Game.adjudicate(), and persists the next state_json + last_resolution +
appended order_history, then clears pending_orders. view builds the
GameState-native API response shape consumed by the frontend, the bot, and DAIDE (see
data_spec.md §API view shape).
Rendering¶
src/rendering/ renders PNGs from a GameState-derived unit/ownership view (not from
engine internals) plus, optionally, order or resolution arrows adapted by
order_overlay.py from Order/Resolution objects. Results are cached in-memory and on
disk at /tmp/diplomacy_map_cache. This package has no engine-internal coupling beyond
map_loader topology and the plain-dict view GameService.view already produces.
DAIDE protocol support¶
src/server/daide/ is a real implementation of the DAIDE wire protocol —
interoperability with the external DAIDE bot ecosystem (DumbBot, Albert, and other
standalone Diplomacy AIs). It is started as an asyncio.start_server listener alongside
the deadline scheduler in _api_module.py's lifespan, on port 8432
(DIPLOMACY_DAIDE_PORT).
src/server/daide/
tokens.py # Token: the DAIDE byte-level vocabulary (powers, provinces+coasts, unit
# types, order types, commands, THX/ORD/HLO tokens) as a bidirectional
# registry; province coverage is asserted against
# engine.map_loader.load_standard_map(), never a second hardcoded list
wire.py # DCSP framing: IM/RM/DM/FM/EM message types over asyncio Stream{Reader,
# Writer}; async read_message/write_message
clauses.py # the encode/decode bridge between DAIDE token clauses and engine.types
# (Location, Unit, Order variants); decode reuses
# engine.orders.parser.parse_order rather than a second grammar
session.py # DaideSession: per-connection protocol state machine — the IM/RM
# handshake, then NME/IAM/HLO/MAP/MDF/SCO/NOW/SUB/NOT/GOF/MIS/TME/HST/DRW/
# ADM/SND dispatch (THX is outbound only: the reply to SUB), all routed through GameService (never engine
# internals directly)
server.py # DaideServer: owns the listening socket, the game a connection's NME
# resolves against (created lazily on first successful NME, not at
# listener startup — see its docstring), the power/passcode registry,
# and the notify_game_processed broadcast (NOW/ORD/OUT/SLO) that fires
# whenever GameService.process_turn runs for a game with live sessions,
# and the on_draw_vote hook (_api_module passes api.shared.after_draw_vote,
# so a DRW notifies Telegram without daide/ importing server.api;
# after_draw_vote in turn sends DRW to the sessions for an HTTP draw),
# and the on_orders_changed hook (SUB / NOT (SUB) invalidate the cached
# games/{id} reads, as the HTTP order routes do)
The handshake follows the DAIDE client-server sequence. After IM/RM, a client's
NME ('name') ('version') seats the next free power (or gets REJ (NME ...) when all
seven are taken) and is answered YES (NME ...) followed by MAP ('STANDARD'). The
client may ask MAP and MDF (both served before NME too), then accepts the map with
YES (MAP ('STANDARD')), which the server answers with HLO (power) (passcode) (LVL 0),
SCO and NOW (a repeated YES (MAP ...) gets nothing). REJ (MAP ...) releases the
power, gets OFF, and ends the session. A reconnecting client sends IAM (power)
(passcode), gets YES (IAM ...), and asks for what it needs; a client HLO re-sends its
HLO at any time. HLO comes only after YES (MAP ...) (or a client HLO), never straight after NME. OBS gets REJ:
observers are out of scope. Every other command before a power is held gets REJ.
Retreat and adjustment replies follow the DAIDE message syntax. In a retreat phase
NOW lists each dislodged unit after the units on the board as (power type province MRT
(retreats)), coasts bracketed ((BUL ECS)), and MRT () when it has nowhere to go;
MIS lists the dislodged units of the power that have no order yet in the same form. In
an adjustment phase MIS (n) counts what is still owed after the orders already
submitted: positive is disbands, negative is builds (a WVE counts as a build, since
every unused build must be waived). The build count is capped at the vacant owned home
centres (adjustments_owed), the same number SUB accepts before answering NMB, so a
power with more centres than build sites reaches zero after its last possible build.
When nothing is owed, in any phase, the reply is a bare MIS. An ORD for a unit that was dislodged carries RET: (BNC RET) for a
bounced move, (RET) alone for a hold. A SUB for a unit of another power gets THX
(order) (NYU) and stores nothing.
No client input escapes its session. DaideSession.run answers every framing
violation with the DCSP ErrorMessage for it and then closes the connection, logging a
warning, never a traceback: a token outside the DAIDE vocabulary gets 0x0E, an unknown
frame type 0x08, a DM before the IM 0x02 (IM_NOT_FIRST_MESSAGE), a second IM 0x06, an
RM from the client 0x0D. A client's own ErrorMessage, whatever its code, is logged and
the connection closed without a reply (DCSP: its sender closes). A connection that sends
no IM within IM_TIMEOUT_SECONDS (30 s) gets 0x01 and is closed; a frame whose first
byte arrived but whose remainder did not within FRAME_TIMEOUT_SECONDS (30 s) gets 0x09
and is closed; an idle connection between frames is left open. A connection holds at
most one power: a second NME, or an IAM on a connection that already holds a power,
gets REJ, and a session that ends for any reason releases its power. Every accepted
socket has TCP keepalive on (SO_KEEPALIVE, plus TCP_KEEPIDLE 60 s, TCP_KEEPINTVL 20 s
and TCP_KEEPCNT 6 where the platform has them), so a seated client whose network vanishes
without a FIN or RST is dropped within about three minutes and its power can be reclaimed
by IAM. An OSError while a command is handled ends the session with a logged warning
naming it. Writes to other
sessions (broadcast_admin, relay_press, the notify_game_processed NOW/ORD fan-out)
go through DaideSession.deliver, which treats a closed or closing transport (including
uvloop's RuntimeError) as a dead peer: it is unregistered and closed, and delivery
continues to the rest. DaideServer.stop() sends OFF to every seated session, then
closes every open connection (Server.close_clients), seated or not, so shutdown never
waits on a peer that does not hang up. tests/test_daide_robustness.py covers each case
over a real socket.
Known, permanent limitation: press content is relayed opaquely, not parsed. DAIDE's
press negotiation grammar (PRP/ALY/XDO/... nested inside SND/FRM) is the
deepest part of the spec and the least essential for interoperability. This codebase
syntax-checks press messages only (balanced parens, a valid recipient-power list) and
forwards the token payload opaquely between clients — negotiation content is the
bots' concern, not the server's. Full press-grammar parsing is out of scope by design,
not a temporary gap to be closed later.
End-to-end proof this composes correctly over a real socket (not just each layer's own
unit tests) lives in tests/test_daide_server.py's
TestEndToEndOneFullTurnOverOneSocket — one continuous asyncio TCP connection drives
IM→RM→NME→YES/MAP→MDF→YES(MAP)→HLO/SCO/NOW→SCO→NOW→SUB→THX against a real GameService/Postgres-backed game,
then GameService.process_turn + DaideServer.notify_game_processed (the same calls the
HTTP route/deadline scheduler make) push a real NOW/ORD notification back over that
same socket.
Notifications: who gets told what, when¶
There are three delivery surfaces, and they are not interchangeable:
- Telegram DM —
notify_user(telegram_id, message)andnotify_players(numeric_game_id, message, exclude_telegram_id=None)inapi/shared.py. These write a row to thebot_outboxtable and return; the bot long-pollsGET /bot/outbox?wait=25for undelivered rows and acks them (POST /bot/outbox/ack) once Telegram has accepted the message. Server code never talks to Telegram and never pushes at the bot (see Deployment and message reliability below). Players with a non-numerictelegram_id(test fixtures like"u1") are skipped, not errored. "Except the caller" below means the authenticated user's linkedtelegram_id(the oneresolve_user_or_telegramreturned), never atelegram_idin the request body: a Bearer caller could put anyone's id there. Tests observe notifications throughtests/reliability_helpers.OutboxProbe. A DM may carry inline buttons (buttons=→payload.buttons): turn processed, the 10-minute reminder, "you joined" and "game is full" carrygame_buttons(game_id)— 📝 Enter orders / 🗺 Map / 🎮 Game menu (a turn DM to a player with nothing to order that phase omits 📝 Enter orders), asg|{game_id}|{action}|ncallbacks that the bot's game menu (telegram_bot/hub.py) answers in a new message. - Linked group post — also a
bot_outboxrow, addressed to the group's chat id, fromapi/shared.py(post_to_game_group,_post_turn_to_channel) and the/games/{id}/channel/*routes;telegram_bot/channels.pyonly formats text. Gated by the link's settings (auto_post_notifications,auto_post_maps); a no-op for a game without a group. Achannel_maprow names the image to send bypayload.path, and the bot fetches it at delivery (a turn map it has already uploaded is re-sent by its Telegramfile_id, from a bounded in-memory map, and uploaded again if Telegram refuses the id). After each processed turn k those are/games/{id}/map/turn/{k}/orders(the board as the turn began, every order drawn and coloured by its result, standoffs marked -- skipped when nobody had anything to order) and/games/{id}/map/history/{k+1}(the board it produced, dislodged units included). By turn number, never "the current map": a post delivered late still shows the turn it announces. An image the API refuses is acked as failed rather than retried, so it cannot block the rows behind it. One group post ignores the settings:DELETE /games/{id}/channel/unlinkcalled by anyone but the bot (a web player, an admin) tells the group the game was unlinked from its web page, that it no longer gets maps or reminders, that the game is open to anyone, and how to link it again (/linkgroup <id>). It names nobody, and is queued before the link is cleared. The bot's own unlinks (/unlinkgroup) post nothing: the bot answers in the group.
A group has at most one game (games.channel_id, unique when set). Linking a game to
a group that has one (POST /games/{id}/channel/link: /linkgroup, /newgame) moves
the link: the old game is unlinked in the same transaction and the response's
replaced_game_id names it, which the bot's reply repeats. A move takes the group from a
game — which then turns up in the public list and becomes joinable from the web — so
only a player of the game that loses it may make one: the Telegram user the bot names
in telegram_id, or an admin. Anyone else gets 409, decided on the rows
link_game_to_channel holds locked.
A game is linked to a group only from inside it. POST /games/{id}/channel/link is
bot secret or admin token only (403 for a web login, a player's included), and the bot
sends the id of the chat the command was typed in, after checking the sender plays the
game: /linkgroup (/link_channel is its old name, refused in a private chat), and
/start link_<id>, which Telegram sends to the group the player picks after the web
page's t.me/<bot>?startgroup=link_<id> (in a private chat it links nothing).
That web control (TelegramGroupCard, shown to a player of the game) reads
GET /games/{id}/channel (players, the bot or an admin): linked, the group's
channel_name (its title, sent by the bot when it links), and bot_username
(DIPLOMACY_BOT_USERNAME, default IronChancellorBot) to build that link. A linked
game shows the group and an Unlink button (DELETE /games/{id}/channel/unlink, also
open to a web player of the game), which asks for confirmation first; the group is then
told (see Linked group post above).
/newgame makes one call, POST /games/create with channel_id (bot only): the game
is created linked to the group or, on a 409, deleted again, never left unlinked in the
public list; the bot also checks the rule before it asks. When the group's game is
still being played (GET /channels/{chat_id}/game carries its status and
phase_code), /newgame first posts what would happen with Replace it / Cancel buttons
(ngok|{anon}{random}|{old game}|{asker} / ngno|{asker}, answered in the group, by the
asker only) and creates nothing until the asker confirms; a finished game's link is
replaced without asking. A command typed in a group is about that group's game, never the caller's current game: the bot asks
GET /channels/{chat_id}/game (bot secret only) — /status, /viewmap, /map and
/players answer for it (or say how to link one), through game_context.group_read_game;
a typed id for any other game is refused, not swapped for the group's game. /status
leaves out the caller's power, which would unmask an anonymous game, and ends with the
same seat list /players shows: all seven powers, each with its nickname, "no nickname",
"taken" (anonymous), "open" or "civil disorder" (a private /players adds a line on
/nickname <name> when the caller's own seat has no nickname); a bare
/unlinkgroup detaches it. Every other game command is private (the group guard).
- Web client — pull-only. The SPA polls GET /games/{id}/state; nothing is pushed. Any row
below is therefore "visible on next poll" for the browser, and that is not a gap to close
with websockets unless someone decides it is.
The maintainer (DIPLOMACY_ADMIN_TELEGRAM_ID, optional) gets two kinds of DM: every
player's /feedback (routes/feedback.py, via notify_user), and every error either process
logs (telegram_bot/alerting.py's throttled AdminAlertHandler). The API's alerts are
bot_outbox rows like any DM; the bot sends its own directly, since the bot's errors are
mostly the ones that happen while the API is unreachable. api/error_log.py logs every 5xx
the API returns at ERROR, so a route's own HTTPException(500) alerts too.
(DaideServer.notify_game_processed is a fourth, protocol-level path — NOW/ORD/OUT/SLO
to connected DAIDE bots; a game that ends with no winners (BL6, the last powers conceding
together, or only dummies left) sends a bare DRW once per game, since OFF means the server is shutting down and
a solo SLO needs a winner. It is orthogonal to the table below and fires from both process_turn
call sites already.)
The matrix. Every trigger of an event notifies the same people; this table is the one place the full picture exists.
| Event | Telegram DM | Channel post | Web client | Where |
|---|---|---|---|---|
| Turn processed (deadline) | all players, but a power that is out (eliminated or conceded) is owed no "Orders are due" and its player gets no turn DM; the power a turn eliminates (resolution.eliminated, so never a concession) is announced once, in that turn's DM to every player ("Your power ITALY has been eliminated …" to its own player, "ITALY has been eliminated from game N: it has no units or supply centres left." to the rest) and in the group post |
notification (opening "The turn has been processed because its deadline passed.", where a manual or auto-processed turn reads "The turn has been processed.") + orders map + result map | next poll | notify_turn_processed(trigger="deadline") |
| Turn processed (manual, or auto-processed) | all players except the caller, unless the caller owes orders in a new retreat or adjustment phase | notification + orders map + result map (a turn followed by phases nobody orders in posts once for the chain: see BV2 below) | next poll | notify_turn_processed(trigger="manual") |
| Game ended by a turn (a solo: 18 centres; or the turn left one power or none) | all players (on a manual trigger, all except the caller): "Game N has ended: FRANCE has won with a solo victory."; the winner reads "Game N has ended: you have won with a solo victory." A turn that eliminated the last opponent reads "Game N has ended: FRANCE is the last power standing and wins." (the winner: "you are the last power standing and win"), one that left nobody "Game N has ended: no power is left, so nobody wins.", one that left only dummies "Game N has ended: only civil-disorder powers are left, so nobody wins." (GameService.ending tells them apart). The message is the turn's own DM minus the "Orders are due" and deadline lines and with the ending sentence last: "The turn has been processed for game N[ because its deadline passed].", then that player's results block, centre changes, eliminations and vacant/unordered lines as in any turn DM, then the ending; the buttons are the ended-game ones. Every player's cached game list is invalidated |
"🔔 Turn Processed - Game N" + "The turn has been processed[ because its deadline passed]." + the group's turn lines (disorder, eliminations, vacant/unordered) + "Game N has ended: …" + the final turn's two maps | next poll | notify_turn_processed(game_ended=True) |
| Empty phase could not be processed (BX2: processing a phase that needs nobody raised) | all players: "⚠️ Game N: nobody has anything to order in Spring 1901 retreats, but it could not be processed automatically. The game's creator can move it on with ⚙️ Process turn now in the game menu (or Process turn on the web game page)." and then "Otherwise it is processed at its deadline, …" or "No deadline is set, so until then the game waits." (no fallback deadline is armed); the error is logged at ERROR, which DMs the maintainer (install_admin_alerts). One notice per failure: only a processed turn or a player's change reaches it, never a timer |
the same text | next poll | api.shared.empty_phase_failed |
| Deadline reminder (10 min out) | only the players of powers still owing orders (orders_status.missing; nobody, and so no post, when all have ordered), once per deadline (games.reminded_deadline, claimed by a conditional update, so neither a restart nor a second worker repeats it) |
DM "Reminder: orders for Fall 1903 movement in game N are due in 7 minutes." (the real time left, rounded, at least 1 minute); group "⏰ Game N: orders for Fall 1903 movement are due in 7 minutes (still to come: FRANCE, ITALY; in a public game each power carries its nickname, "ITALY (Zed)"). Orders go to me in private." | — | check_and_send_reminders / _send_deadline_reminder |
| Deadline set or cleared | all players except the setter | the same text, prefixed "⏰ " | next poll | routes/games.py set_deadline |
| Weekly deadline schedule set or removed | all players except the setter | the same text, prefixed "⏰ " | next poll | routes/games.py set_deadline_schedule |
| Player joined | nobody by DM while the table is being seated (seven joins would send 21), but every seated player except the joiner by DM when a vacated seat is taken over mid-game; the joiner's own "You have joined" confirmation, and a group post "X has joined game N as POWER." (a nickname in a public game, "A new player" in an anonymous one) when the game has a group | — | next poll | routes/games.py join |
| Game started (the last seat filled by a join, or the last unseated power made a dummy; DF3) | each seated human, one DM: "Game N has started! You play ITALY. It is Spring 1901 movement: orders are due." plus " First deadline: …" when one is set or a weekly schedule just armed it, with the game's buttons (📝 Enter orders first); dummies get none. Once per game: games.start_announced_at is claimed by one conditional UPDATE (claim_game_start_announcement), so concurrent last-seat requests cannot both announce and a later join, replace or dummy toggle never does. Two paths claim it without sending this DM: a waiting-list fill (its own "Game N created! You've been assigned …" and "now full" messages are that game's announcement) and a saved-game import (a game already under way). Arming a weekly schedule does not wait on the claim: whenever such a write leaves every seat filled and no deadline running (an imported game whose last unlinked seat is then taken), the schedule's next slot is armed whether or not the start is announced |
"🎮 Game N is full -- the game has begun! …" | next poll | api.shared.announce_game_started, from routes/games.py join and set_dummy_power |
| Player quit | the quitter: "You have quit game N." (instead of the general notice); all other players: "POWER has left game N. …" (the vacant-seat hint and "Until then its draw vote is still needed."), or, for an eliminated power, only "POWER (eliminated) has left game N." | — | next poll | routes/games.py quit |
| Player replaced | all players except the replacer: "A new player has taken over Power in game N." (a nickname in a public game) | — | next poll | routes/games.py replace |
| Seat marked inactive (admin) | all players: "{POWER} has been marked inactive by admin and is eligible for replacement." (an eliminated power: "{POWER} (eliminated) has been marked inactive by admin.") | — | next poll | routes/games.py mark_player_inactive |
| Game rolled back (admin) | all players: "Game N has been rolled back by an admin to phase …" (pending orders and draw votes cleared) | — | next poll | routes/games.py restore |
| Game deleted (admin) | all players, sent before the rows go: "Game N has been deleted by an admin." | — | — | routes/admin.py delete game |
| Dummy toggled | all players: "POWER in game N is now played by civil disorder." or "… is open again -- /join N to take it." (when the toggle completes a draw quorum the draw rows apply instead) | — | next poll | routes/games.py set_dummy_power |
Game unlinked from its group by another game taking it (link_or_409: /newgame, /linkgroup, an admin; only when the game is not finished) |
every seated human, one DM: "Game N is no longer linked to group |
— | next poll | routes/channels.py link_or_409 |
| Auto-process toggled | all players except the caller: "Game N now processes each turn as soon as all orders are in. …" or "… no longer processes turns automatically." | — | next poll | routes/games.py auto-process |
| Wait flag raised or lowered | all players except the caller: "POWER asks game N to wait before the turn is processed." or "POWER is ready in game N." | — | next poll | routes/games.py set_wait_flag |
| Deadline proposal made | all players except the proposer and any power that is out: "POWER proposes a 24-hour deadline for game N, counted from when the proposal passes." (or "clearing game N's deadline") + "Needs K yes votes (1/K so far). Vote with the buttons below.", with ✅ Vote yes / ❌ Vote no / 🎮 Game menu buttons; when the proposer is the only active power: "POWER's deadline proposal for game N was accepted immediately (they're the only active power): deadline now …" | — | next poll | routes/games.py deadline propose |
| Deadline proposal expired | all players except powers that are out: "The deadline proposal in game N (from POWER) expired without a majority; nothing changed." (the proposer: "Your deadline proposal in game N expired without a majority; nothing changed.") | — | next poll | deadline scheduler, api.shared |
| Deadline passed with seats unfilled | all players, with the game's buttons: "⏰ Game N: the deadline passed, but the turn waits for a full table. …" + the unseated powers + "The next deadline is …" (a schedule) or "Set a new deadline once the table is full." | the same text | next poll | deadline scheduler, api.shared |
| Deadline proposal vote | all players except the voter and any power that is out: a yes vote that does not decide ("POWER voted yes … (1/4 needed)"), the proposal passing, or its rejection (the proposer reads "Your deadline proposal …"). A "no" vote that does not reject sends nothing | — | next poll | routes/games.py deadline vote |
| Broadcast message | all players except the sender | the broadcast text (when auto_post_broadcasts, default on) |
next poll | routes/messages.py |
| Rumour (anonymous broadcast) | all players, the sender included: "🕵️ Rumour in game {id}: …" | "🕵️ Rumour in game {id}: …" (same setting) | next poll | routes/messages.py |
| Private message | recipient only | — | next poll | routes/messages.py |
| Draw vote cast (not final) | all players except the voter and any power that is out (conceded or eliminated): "FRANCE has voted to end game N in a draw (2/7 agreed). Draw votes last until this phase is processed. Use /draw to agree." (a recipient whose power has already voted reads "You have already voted. Use /nodraw to withdraw." instead), plus the vacant-seat hint when a seat is empty | — | next poll | api.shared.after_draw_vote |
| Draw vote withdrawn | all players except the voter and any power that is out: "FRANCE has withdrawn its vote to end game N in a draw (1/7 agreed).", plus the vacant-seat hint when a seat is empty | — | next poll | api.shared.after_draw_vote |
| Draw vote repeated, or a withdrawal with no vote to withdraw | nobody (GameService.submit_draw_vote returns changed: false) |
— | — | api.shared.after_draw_vote |
| Draw quorum reached → game ends | all players except the voter: "Game N has ended in a draw shared by AUSTRIA, ENGLAND and FRANCE."; a sharer reads itself as "you" ("… shared by you, AUSTRIA and ENGLAND."). When a concession or a new dummy completed the quorum, the cause leads ("ITALY has conceded, and game N has ended in a draw shared by …"; the conceder is left out, a dummy toggle leaves nobody out). Every player's cached game list is invalidated | "🤝 Draw - Game N" + the same sentence; no maps (no turn was processed) | next poll | api.shared.announce_draw → notify_game_drawn |
Draw voted over DAIDE (DRW, NOT (DRW)) |
the three draw rows above, to every Telegram player (a DAIDE voter has no Telegram id to leave out); a completed draw, whichever surface cast the deciding vote, sends one DRW to every DAIDE session (after_draw_vote → broadcast_draw_completion, idempotent per game) |
as above | next poll | DaideServer(on_draw_vote=api.shared.after_draw_vote), wired in _api_module |
| Power conceded | all players except the conceder | "🏳️ POWER has conceded and left game N. …" (the same sentence; none when the concession ended the game: the ending's own post says why) | next poll | routes/games.py concede_game |
| Game ended by a concession or a dummy toggle (last power standing, or nobody left) | all players except the conceder, with the ended-game buttons: "FRANCE has conceded, and game N has ended: ITALY is the last power standing and wins." (the winner: "… you are the last power standing and win."), or "…: no power is left, so nobody wins." / "…: only civil-disorder powers are left, so nobody wins." (the cause may also be "ITALY is now played by civil disorder") | "🏆 Game N has ended" + the same sentence | next poll | api.shared.notify_last_power_standing |
| Password reset requested (web) | the account's linked Telegram user only: "Someone asked to reset the password of your Diplomacy website account (email). If it was you, open this link within an hour …" with the link; email is the fallback for an unlinked account | — | — | routes/auth.py _send_password_reset_link |
| Waiting list filled | all seven placed players, each told their own power ("🎮 Game N created! You've been assigned POWER.", with the game's buttons), then a second DM to every player, "Game N is now full. Good luck to all players.", with the game's buttons | — | — | api/routes/waiting_list.py |
What the turn-processed DM says is per player and names the new phase in words
(api.shared.turn_message, fed by GameService.phase_duties, which uses the same
powers_with_orders_to_give set orders_status waits on, civil-disorder dummies left out):
- movement — "Orders are due for Spring 1902 movement.";
- retreat — to each dislodged power, every dislodged unit with its retreat options as the
adjudicator computed them ("…Fall 1901 retreats: your orders are due.\nYour A BUR was
dislodged: it may retreat to GAS, PIC, RUH, or disband. With no order it is disbanded.", or "…has nowhere to retreat: it
must disband."); a power whose dislodged units all have nowhere to retreat owes no order
(
phase_duties'forced_disbands): its player is told to wait, plus "Your A BUR was dislodged and has nowhere to retreat: it is disbanded, no order needed.", and the channel post does not list it as due; - adjustment — the build count (
adjustments_owed, plus how many more are waived for want of a free home centre) and the free home centres themselves, or the disband count ("You may build 2 units (free home centres: MAR, PAR; 1 more waived: no free home supply centre).", "You must disband 1 unit."); - a power owed builds with no free home centre at all owes nothing, but is told so
(
phase_duties'waived_builds): "Your 2 builds are waived: no free home supply centre." under its wait line (or, if the next phase needs nobody, in the DM that carries the folded lines). The after-phase waived notice (below) does not repeat it; - a player with nothing to order in a retreat or adjustment phase is told so and to wait;
- units an adjustment or retreat phase removed on its own (civil disorder, a bounced or unordered retreat) are told under the power's "Your results for Winter 1901 builds:" block, with the header the ordered results get.
A phase nobody has anything to order in runs at once (BV2): a retreat phase whose only
dislodged units have nowhere to go, or an adjustment phase in which only dummies build or
disband (GameService.phase_needs_nobody: a retreat or adjustment phase whose
powers_with_orders_to_give are all dummies). Every trigger finishes a processed turn
through api.shared.after_turn_processed, which calls finish_processed_turn and then, while
the new phase needs nobody and the table is full, processes it through the same
phase-checked process_turn(expected_phase_code=…), whatever auto_process says (a
StaleGameError means another worker did it). Each processed phase gets its snapshot, but
no player DM and no group post of its own: what that DM would have said about the turn before
it (the results block, a trapped unit's "has nowhere to retreat" notice, units removed) is
folded into the DM for the phase that needs them, after its first line. The group, likewise,
gets one post for the whole chain, as for any turn (FoldCarry): one text naming the phase
that needs orders ("Fall 1901 movement: new orders are due …"), carrying the folded phases'
group lines (each unit disbanded for want of a retreat — "FRANCE: A BEL was dislodged and had
nowhere to retreat: it was disbanded." — the turn's disorder, eliminations, vacant/unordered
lines), then two maps: the orders map of the turn the players ordered, and the board after
the last folded phase (/map/history/{last turn + 1}), both captioned with the ordered phase
("Spring 1901 movement: the result"), since the folded phases had nothing to order. The
ordered phase's deadline is spent with it; the next one is armed once, for the phase that
needs orders, and "No deadline is set for …" goes with it when the ordered phase had one
(process_turn's deadline_spent). If the empty phase cannot be processed
here (another worker got there first, or processing it raised), the folded lines go out on
their own, and so does the group post the fold held back ("Spring 1901 retreats: nobody has
anything to order." with its lines and maps); on an error the game stays in the empty phase,
which gets the deadline any new phase gets (the schedule's next slot, or none), and the turn
before it stands: the route still answers 200 with that turn's resolution, and the scheduler
goes on to the next game. POST /games/{id}/process_turn answers with the phase the game
is in after all this. The DAIDE ORDs for each processed phase carry that phase's
resolution, read when it was processed (not the stored last_resolution, which the empty
phase after it has replaced by the time the broadcast runs). An ORD names the true order: fleets as FLT, a supported or convoyed unit with its real power (both from the resolution's units, the pre-adjudication board), and a convoyed move's VIA (...) lists the fleets that ordered that convoy, in route order. SUB merges per unit (submit_orders(merge=True)): an order replaces only the earlier order for the same unit. A bare SUB is HUH (SUB ERR). In an adjustment phase a build, waive or removal past the power's count is refused (submit_orders(keep_stored=True)) and the orders already submitted stand: NMB for a build or waive, NMR for a removal (the web and bot clients instead let the newest replace the oldest). THX notes: an order of the wrong phase NRS, a retreat or disband for a unit owing none NRN (NSU when the province has no unit at all), a move to the unit's own province FAR.
A phase can also become empty while it stands (BX1): the creator makes the only power
still owing a retreat, build or disband a dummy (POST /games/{id}/dummies), that power
concedes (POST /games/{id}/concede), the seat completing the table is taken
(POST /games/{id}/join) while the phase needs only dummies, or an admin restores a game
from the archive in such a phase (POST /games/import, after everything it restores; its
response's auto_processed counts the phases processed, and its deadline is then the new
phase's). Each of those routes, after its
change is committed and announced, calls api.shared.process_if_phase_needs_nobody, which
processes the phase through the same phase-checked process_turn and after_turn_processed
when it needs nobody and the table is full, whatever auto_process says, so the players
read the change before the turn it caused. A StaleGameError or GameOverError means
another worker (or the game's end) got there first; an error processing it is logged and
leaves the phase under its current deadline, and the route still answers 200 for the change.
Either failure (here or in after_turn_processed) goes through empty_phase_failed, which
tells the players and the group the phase is stuck and how to move it (see the notification
table).
A player quitting is not such a change: the vacated seat's power still owes its orders.
Each player is told what the turn did to their own units (BW1), in a block after those
lines (GameService.turn_outcomes, api.shared.turn_results_lines): "Your results for
Spring 1901 movement:" and then one line per unit, sorted by province, worded like the web's
results list:
- movement — "A PAR - BUR bounced.", "F BRE - MAO succeeded.", "A MUN S A PAR - BUR was
cut.", "A KIE - BUR was invalid, so the unit held.", "A LON - BEL VIA failed: no convoy
route." (or, when a fleet convoying it on a possible route was dislodged, "A LON - NWY VIA failed: the
convoy was broken when F NTH was dislodged."), a support void because it would dislodge the
supporter's own unit (DATC 6.D.10) "A VIE S A VEN - TRI had no effect: it would dislodge your
own F TRI.", a legal support with nothing to support "A GAS S A SPA - MAR had no effect: A SPA did
not move to MAR." (a support to hold of a unit that moved: "… had no effect: A SPA moved."; one
that is out of reach or names no unit stays "was invalid, so the unit held") (all from
GameService.result_reason, which the web shows too), "A BER held.", "A MUN held (no order)."; a dislodged unit names its attacker, power only, never a nickname: "F TRI was dislodged by A TYR (ITALY).", "A VIE - TRI bounced; dislodged by A BOH (RUSSIA)."; a bounced move names who it met (bounce_rivals, from the turn's other results; the web's entries carrybounced_off/bounced_with): "A VIE - GAL bounced off RUSSIA's A GAL." (a unit that kept the province, or swapped with the mover), "A VIE - GAL bounced (RUSSIA's A WAR also moved there)."; a power that ordered none of its several units gets one line: "No orders, so F BRE, A MAR and A PAR held."; - retreat — "F TRI retreated to ALB.", "A BUR was disbanded." (a disband it ordered);
- adjustment — "A PAR was built.", "F KIE was disbanded." (a disband it ordered);
- after the turn that changed centre ownership (a Fall turn), a last line for each power
whose centres changed: "Centres: +BEL, -TRI (now 5)." (from the resolution's
centres).
"Held (no order)" is read from the resolution's unordered mark, so an order refused at
submission shows up here as the unit holding. The block leaves out what the DM's own
notices already say: a trapped unit's disband and waived builds (below). A bounced or
unordered retreat disband and a civil-disorder disband are lines of the same block (under its
header, even when the power has no other result). A player holding several powers gets a
block per power, headed "As FRANCE, your results for …:". The channel post carries no
one's results.
The DM addresses its reader as "you"; only a player owing orders for more than one power
is told which is which ("your orders are due for AUSTRIA and ITALY", "Your F ION (ITALY)
was dislodged…", "As FRANCE, you may build 1 unit."). The DM is plain text (no
parse_mode). The channel post names the phase too, and in a
retreat or adjustment phase the powers that owe orders. The caller of a manual process is
skipped unless they owe orders in a new retreat or adjustment phase, or civil disorder
or a bounced retreat removed one of their units (below): their HTTP response carries the resolution, not
their retreat options or build count, and does not single out a civil-disorder removal.
A civil-disorder removal is announced. When the processed turn was an adjustment in
which a power ordered fewer disbands than it owed, the units the engine removed for it
(the results marked civil_disorder, read by GameService.civil_disorder_disbands) get
one more line, in that power's DM and in the channel post
(api.shared.civil_disorder_line):
- DM — "You were 2 disbands short, so F KIE and A MUN were disbanded (civil disorder)." or "You were 1 disband short, so A SIL was disbanded (civil disorder)." (true whether it sent none, too few, or void ones) ("As GERMANY, you were …" for a player holding more than one such power);
- channel post — the same sentence about the power: "FRANCE was 2 disbands short, so …", "GERMANY was 1 disband short, so …", one line per power, civil-disorder dummies included.
A unit a retreat phase removed without its power choosing it is announced the same
way. GameService.retreat_disbands reads the processed retreat phase's results: a
Retreat that BOUNCEd and a civil_disorder disband carrying retreat_options. Each
gets one line in its owner's DM (prefixed "As FRANCE: " for a player holding more than one
such power) and, prefixed with the power, in the channel post:
- "A MAR's retreat to PIE bounced (FRANCE and ITALY both retreated there): it was disbanded." ("FRANCE retreated 2 units there" when one power bounced its own units);
- "A WAR had no valid retreat order and was disbanded." (no order, or one that was rejected; the line does not say "civil disorder", which a present player did not cause).
A build waived without the power's asking is announced. GameService.waived_builds
reads the processed adjustment's WAIVE results for a power that left builds unused (it sent
no adjustment orders, or ordered fewer builds than it was owed), minus the WAIVE orders it
sent itself, capped at the free home centres it had (a power with no free centre, or a dummy,
is not announced). Its DM gets "Your 2 builds were waived: no orders came in." when it ordered
nothing, or "Your 1 build was waived: it was not ordered." ("they were not ordered" for
several) when it ordered some builds (prefixed "As FRANCE, your " for a player holding more
than one such power), and the channel post "FRANCE: 2 builds were waived: no orders came in."
A build the power waived itself is acknowledged to it alone. GameService.chosen_waives
counts the explicit WAIVE orders in the processed adjustment; the power's results block
(so a power whose only adjustment was a waive still gets its block) ends "1 build was waived."
or "2 builds were waived.". The group post does not mention it: unlike a waive for want of
orders, nothing was missed.
These lines come before "Next deadline: …", which still ends the DM and the post: on the
first line's end when the DM is one line, on its own line otherwise.
When a weekly schedule armed the new phase's deadline, the turn-processed DM and channel
post end with "Next deadline: …", and the game-started DM with "First deadline: …".
When the phase just processed had a deadline and the new one has none, they end with
"No deadline is set for /deadline is refused, says "A player can set one from the game menu in a
private chat with the bot (/game POST /games/{id}/deadline refuses a deadline at or
before now (422, "That deadline has already passed. Choose a time in the future."). After a processed
movement turn, a power whose seat is vacant (its player quit; not a dummy) and which still has units and ordered nothing that turn (orders it sent before quitting stand) adds
"notify_players(..., skip_out=True) leaves out a player whose every power is conceded or eliminated, as the turn DM does. The game-ended announcement still goes to everyone.
How a player is named depends on the game (games.anonymous, fixed at creation).
Every notification that names a power — join, quit, takeover, wait flag, draw vote,
concession, deadline proposals and votes, private messages and broadcasts (DM and group
post) — names it through api.shared.power_label: FRANCE in an anonymous game, FRANCE
(Anna) in a public one (the power alone for a player with no nickname). A join or takeover in an anonymous game says "A new player has
joined … as ITALY". The bot relays every message between players, so in an anonymous game
nobody learns who holds a power except by being told. The same rule holds for API reads
(api.shared.player_rows; docs/specs/data_spec.md §4).
A DM about its reader's own power says "you" instead of naming it: the turn-processed
DM above, the solo winner and the draw's sharers, and the proposer of a deadline proposal
that is voted down ("Your deadline proposal in game N was voted down; nothing changed.")
or expires ("Your deadline proposal in game N expired without a majority; nothing
changed."). Everyone else's DM and the group post keep the power's label.
api.shared.notify_players(own=…) picks the reader's text from the powers they hold.
Events whose actor is the reader skip them altogether (the voter, the proposer, the
conceder: the matrix's "except").
A rumour (POST /games/{id}/broadcast with anonymous: true; the bot's /rumour, or
"🕵️ Rumour (anonymous)" on the game menu's Messages screen) names nobody in any game: not
the power, not the nickname, in the DMs, the group post or GET /games/{id}/messages
(only the sender sees it as theirs). The sender is stored and appears only in the
admin-only export. Unlike a signed broadcast, a rumour's DM goes to every seated player,
the sender included: the same text, queued in the same notify_players loop, with no
"you sent this" marker. Left out, the sender would be the one player without the DM, and
players comparing notes could name them. The sender still gets the bot's "Rumour spread"
reply (or the queue's delivery report) as well.
Message text (routes/messages.py, the same rule for a private message, a broadcast and
a rumour): blank or whitespace-only text is a 400 ("A message cannot be empty."), and so is
text longer than MAX_MESSAGE_LENGTH = 3500 UTF-16 code units ("A message can be at most
3500 characters long (this one is N)."). Telegram counts its 4096-character limit in UTF-16
units, so 3500 leaves room for the longest heading a DM or group post puts in front of the
text; a message that didn't fit would be dropped by the bot as a permanent send error. The
bot shows the 400's reason to the sender; the web composer has maxLength 3500 (a JS
string length counts the same units), shows the characters left from 3000 on, and won't
send blank text. Reading (GET /games/{id}/messages): no credentials reads the
broadcasts only; a valid Bearer token, or telegram_id with the bot secret, adds the
caller's own private messages. On this and every other request, GET or write, the bot sends
the secret only in the X-Bot-Secret header: never in the URL, where it would end up in
access logs and in error text, and never in a JSON body, which its offline queue stores on
disk. A bot_secret query parameter is ignored, so a secret in a URL authenticates
nothing (no credentials leak into logs from a request that works), and so is a bot_secret
in a JSON body: the header is the only place a route reads it. A write the bot queued on disk
under an older release, whose stored body still holds one, delivers anyway, because the bot
drops it and sends the header at delivery time;
credentials that are present but don't check out (an
invalid or expired token, a telegram_id without the secret) are a 401, never a silent
fall-back to the broadcasts-only view.
A draw is announced once. A draw keeps the phase code, so the phase check alone cannot
stop a second request that loaded the board before the draw committed (a double tap, or
the web and the bot at once). GameService.submit_draw_vote passes refuse_completed to
both GameRepo.modify_draw_votes and save_state. The row is locked, a finished game is
refused and the late request gets a 409 that says how the game ended. It is never
recorded as a vote ("(1/7 agreed)") and never announced as a second draw. A concession
is guarded the same way: GameService.concede passes refuse_completed to
GameRepo.modify_state_json, so a concession loaded before a draw committed is a 409 that
says how the game ended, and never writes its still-active board over the finished game.
The concession itself is a locked read-modify-write of state_json: the conceding power's
units, dislodged units and centres are removed from the board read on the locked row, not
from the one the request loaded, so two powers conceding at once both leave the board (a
write of the loaded board put the first one's units and centres back). A concession from a
phase that has since been processed is a 409.
The draw rows need their own call because the game is finalized inline the moment quorum is
reached and the outcome goes to the caller only. GameService._end_if_draw_agreed decides
and writes in one transaction on the game row taken FOR UPDATE (GameRepo.end_game_if):
it reads the board, the votes and the dummies on the locked row, and if every power in the
quorum has voted yes writes Game.draw()'s board as save_state would. refuse_completed
lets only the first of two writes completing the quorum at once end and announce the game.
Every write that can complete a quorum commits its own change and then calls it: a yes vote
(submit_draw_vote), a concession and a seat made a dummy, the last two because they take a
power out of the quorum. Because each decision reads every input under the lock, of two such
writes at once the one deciding second sees both; decided on separate unlocked reads, a vote
and a dummy toggle could each miss the other's write and leave a completed quorum running. A draw completed by
either is announced exactly as a voted one (api.shared.announce_draw: DAIDE DRW, the
deadline cleared, every player's cached game list invalidated, the DM and the group post). The game is then COMPLETED, so the
deadline scheduler skips it (get_games_with_deadlines_and_active_status) and no later
turn-processed fan-out covers for it; without the explicit notification six of seven
players would find out by refreshing. A concession is announced for the same reason.
A non-final draw vote is announced too, deliberately: a draw is the one outcome every power holds
a veto over, so discovering that one is being negotiated should not require running /status.
A turn is processed only at a full table: every power has a seat row (held, or vacated
by a player who quit) or is a dummy (api/shared.py's seats_filled / unseated_powers).
All three triggers check it. The creator's POST /games/{id}/process_turn answers 409
naming the empty seats (3 powers are unseated (Austria, Italy, Turkey): seat players or
mark them as dummies.) with the header X-Error-Code: seats_unfilled, whoever calls it,
bot secret and admin token included. The web switches on the header and shows the
message as is; the bot reads unseated from GET /games/{id}/orders_status, skips its
"process anyway?" confirm when it is not empty, and shows the 409's message. On the opening
phase (S1901M) a non-empty unseated also makes the bot's /status and game menu say "Game N
hasn't started: waiting for K more players (...). Others can join with /join N" instead of the
turn, waiting-on and draw-vote lines, drop the order buttons, and answer a stale order button
(/orderall, /selectunit, the menu's) with that same text.
maybe_auto_process processes nothing. When a deadline passes, the scheduler does not
process the game; it spends the deadline, so it does not find it again every tick (a
weekly schedule moves to its next slot, a one-off deadline is cleared; filling the last
unseated power arms a scheduled one again), and tells the players and the game's group, naming the
empty seats and the next deadline if there is one. It spends the deadline with a compare-and-set (DatabaseService.replace_game_deadline_if_unchanged): only while the game is still in the phase, with the deadline, the scheduler saw. A deadline armed meanwhile (the last seat filling) is kept, and no notice goes out. The bot's demo game is full from the
start: Germany plus six dummies. The DAIDE listener's game (games.daide) is exempt: its
seats are live DAIDE connections held in memory, not seat rows.
A seat its player quits is never unseated: its row stays, so quitting leaves the deadline
as it is, the scheduler processes the turn at it (the vacant power's units hold, as for any
power without orders), and retaking the seat changes no deadline -- there is none to re-arm.
Nothing is played before the game starts. A game has started once its table is full
(as above) or a turn has been processed; a game that has run a turn stays started even if a
dummy seat is reopened later (that holds up only processing). Until then
POST /games/set_orders, POST /games/{id}/draw_vote and POST /games/{id}/concede
answer 409 with the header X-Error-Code: seats_unfilled and the detail
Game 2 hasn't started: 1 power is unseated (Russia): seat players or mark them as dummies.,
naming every open power (api/shared.py's require_started). A power conceding in the
lobby would otherwise be dead once the table filled. Orders a game already holds when it
loses (or never had) a full table stay stored and are adjudicated as usual once it fills;
reading the board, the pending orders and the order status is unaffected. A finished game
is left to the service, which answers with how it ended.
The web game page mirrors this. The API exposes no "started" flag, so the page derives
the lobby: the opening phase (S1901M) with a power that has neither a seat row in
/players nor dummy status. It then shows "Waiting for N more players" naming the open
powers, and hides the turn-status card, the "You still need to submit orders" line and the
order form; messages and the players list stay. Any action refused with seats_unfilled
shows the server's own detail, not the generic stale-write text every other 409 gets.
Deadlines are never imposed by the server. A game has a deadline only when a player
chose one: set explicitly via POST /games/{id}/deadline (the bot's /deadline <game_id>
<hours|clear>, or a majority vote through deadline/propose), or armed from the game's
weekly schedule. A deadline is scoped to its phase: the write that adjudicates the phase
spends it (GameRepo.save_state clears deadline and reminded_deadline on the locked row,
in the same transaction as the phase change, so the deadline scheduler never sees the new
phase with the old phase's deadline past due), finish_processed_turn then arms the new
phase's deadline if a weekly schedule gives it one (and leaves alone one set for the new
phase in between), and an admin restore to a snapshot
(POST /games/{id}/restore/{snapshot_id}) drops the discarded phase's deadline and gives the
restored phase the one a newly entered phase gets. games.deadline is stored as naive UTC; every API field that
carries a deadline (GET/POST /deadline, POST /deadline/schedule, an accepted proposal,
the archive restore) returns it as aware UTC ISO (2026-10-27T18:00:00+00:00, via
shared.utc_iso), so a browser does not read it as local time. The web client also parses a
naive deadline string as UTC (parseUtc).
Weekly schedules (server/deadline_schedule.py, games.deadline_schedule) are a
standing choice such as "Mon, Wed, Fri at 16:00 (Europe/Helsinki)", set by any player via
POST /games/{id}/deadline/schedule (the bot's /deadline <game_id> schedule mon,wed,fri
16:00 [timezone]) or at creation (deadline_schedule/deadline_timezone). While a game
has one, each phase's deadline is armed to the next slot at least an hour away
(MIN_NOTICE, so a turn processed at 15:55 is not given a five-minute phase): when the
game fills, when the schedule is set on a started game, after every processed turn, in
finish_processed_turn (and after a failed deadline run, so it retries at the next slot),
and after an admin restore or an archive import.
Slot times are wall-clock times in the schedule's timezone, so they hold across daylight
saving. Every phase type gets the next slot, retreats and adjustments included. A one-off
POST /deadline (or an accepted proposal) overrides only the current phase; removing the
schedule leaves the current deadline and arms none after it.
Conceding removes the power's units and releases its supply centres (they become
neutral, like the unowned centres at game start), so Game.eliminated_powers() reports it at
once. Ownership otherwise persists until a unit stands there, so a conceded power that kept
its centres would be owed builds at the next Winter and could walk back in. /quit is the
other path: the seat is vacated for a replacement and the board is untouched. A finished game
refuses /quit (409, "Game N is already over; there is no seat to quit."). A vacant seat's draw
vote stays required, since the seat can be refilled: the quit announcement says "Vacant: Germany.
Someone can take the seat with /replace N GERMANY, or the game's creator can make it a dummy with
/dummy N GERMANY. Until then its draw vote is still needed." (with two or more vacant seats the
commands say <power>), and POST .../draw_vote and
GET .../draw_vote_status carry vacant (the vacant powers whose vote is still missing), which
the bot's /draw reply and the vote announcement repeat.
An eliminated power has left the game (it conceded, or lost its last unit and centre;
GameService.is_eliminated, false once the game has ended). While the game goes on it
cannot concede again (409 FRANCE has already conceded, not announced a second time), vote
on a draw (409 ... has been eliminated from game N; it cannot vote on a draw), send
private or broadcast press or a channel broadcast (409 ... it can no longer send
messages), and nobody can take its seat back through /join with that power, /replace
or a random join (409 ... its seat cannot be taken; a random join skips it), or raise a wait
flag (409 ... it cannot ask the table to wait; lowering one is accepted): conceding lowers
the flag it held, and a flag still stored for a power out of the game holds up nothing. The service
refusals are PowerEliminatedError, a GameOverError, so every route already mapping that
to 409 maps them. When a concession or a processed turn leaves one power standing, the game ends with it
as the sole winner; when it leaves none, or leaves only civil-disorder dummies (two or more:
nobody is left to play them), the game ends with no winners (COMPLETED, winners
empty). A seat its player quit is not a dummy: it can be taken again, so it keeps the game
going. Making the last such seat a dummy (POST /games/{id}/dummies) ends the game the same
way. All of these go through GameService._last_standing_end (Game.draw narrowed to the
survivors, or to nobody). It is a server rule, not the engine's: under the rules adjudication alone
can only eliminate every other power by taking all their home centres, which is already
an 18-centre solo, so only after concessions (whose centres turn neutral) can a survivor be
short of 18; and the engine's DATC boards hold only a few powers, which it must not end.
A processed turn applies it before its one save_state, so the end and the turn are
one write and one announcement; its save_state is also guarded by the dummies it was
decided on (expected_dummy_powers), so a seat made a dummy mid-adjudication, whose own check
still saw the board before the turn, makes the turn adjudicate again rather than leave only
dummies playing. After a concession or a dummy toggle it is _end_if_last_standing, decided
and written like a draw on the locked row (end_game_if), so two last powers conceding
together leave no winner rather than crowning one who left. The dummy set itself changes only
through the locked GameRepo.modify_dummy_powers (two seats made dummies at once both stay;
a game that ended meanwhile is a 409), which reads who holds each seat under the same lock; a
join or replace writes its seat (DatabaseService.create_player / claim_vacant_seat with
refuse_dummy) only after taking that lock and finding the power is not a dummy. So a seat
taken and the same seat made a dummy serialize: the second is refused (400 "held by a
player" for the toggle, 409 "played by civil disorder" for the join). Every one of these takes only the game row's lock, one
transaction at a time, so they cannot deadlock with each other or with the other modify_*
paths. Only the concession that ended the game
announces it: one landing at the same moment finds the game ended and returns it as ended,
with no "play on" notice and no auto-processing. The concede response then carries
game_status: "COMPLETED" and winners: ["GERMANY"], and instead of the concession notice
notify_last_power_standing clears the deadline, invalidates every player's cached game
list, tells the players (the winner reads "you are the last power standing and win"; with nobody
left, "no power is left, so nobody wins"; with only dummies left, "only civil-disorder powers
are left, so nobody wins") and posts to the game's group. A dummy toggle that ends the game
is announced the same way, led by "GERMANY is now played by civil disorder", instead of the
plain dummy notice. The conceder, left
out of that, is told by the reply to their concession (the bot: "You have conceded game N,
and it has ended: ...").
A group broadcast (POST /games/{id}/channel/broadcast) is posted as the caller's own
seat. A web user's broadcast carries their seat's power whatever the body's power says;
naming another power is a 403 You do not hold ENGLAND in game N. The bot or an admin may
name a power only if the Telegram user in telegram_id holds it (else the same 403), or
omit it for a public broadcast. A player whose power is eliminated cannot post either way.
Seat writes go through DatabaseService.assign_player_seat, never through attribute
assignment on a row returned by a DAL getter — those rows are detached the moment the
getter's session closes, and DatabaseService.commit() is a no-op, so such writes are
silently discarded. A vacant seat is a row with user_id NULL and is_active False; /join
takes it over the same way /replace does (the web client lists such seats as "Open");
_authorize_power treats it as held by nobody.
Private press belongs to the seat, not the person. routes/messages.py reads private
messages by recipient_power, so whoever takes a seat (/replace, /join on a vacant
seat) reads every message sent to that power before they held it: the newcomer learns what
was promised to the power they now play. This is the maintainer's decision (issue #253).
A COMPLETED game accepts no writes, except press. /message and /broadcast stay open
on purpose: a post-mortem chat is a normal Diplomacy custom (BZ5). GameService.submit_orders, process_turn,
submit_draw_vote and concede all raise GameOverError (a ValueError, deliberately not
an OrderError — routes map that to 404, and a finished game is found) once
state.status is COMPLETED; the routes answer 409 with a message naming the outcome
(Game 12 is drawn between FRANCE, GERMANY; no further orders are accepted, the clause fitted to the action), the bot
shows that detail verbatim, and the DAIDE session answers REJ. orders_status reports no
active or missing powers, legal_orders offers nothing (empty units, orders_by_unit, orders),
and draw_vote_status of a draw-ended game reports the sharers as the votes (quorum reached);
of a game ended any other way it reports no required, voting or missing powers. /replace and
/join answer 409 on a finished game, deadline withdraw likewise, and GET .../deadline shows
no pending proposal for one.
Rules for adding a notification.
- One fan-out per event, shared by every trigger.
notify_turn_processed(called fromfinish_processed_turn, reached throughafter_turn_processed) serves the manual, deadline and auto-processing paths alike. If an event can be reached two ways, the second way calls the same function — do not bolt anotify_playerscall onto the new call site. - Never notify the caller of their own action twice. A player who presses "process turn"
gets the resolution in their HTTP response;
exclude_telegram_idskips their DM. - Every send is best-effort at the call site, durable after it. Wrap and log. A failure to queue (the database is down) must never fail a turn that is already committed to Postgres — the state change is the contract, the notification is not. But once queued, a notification is never dropped: only the bot's ack removes it.
- Update this table in the same commit. It is the only place the full picture exists.
notify_turn_processed is deliberately synchronous so the sync scheduler path
(process_due_deadlines) and the async HTTP route can share it with no bridge; each
notification costs one short database write.
Deployment and message reliability¶
Every service — postgres, diplomacy_api, diplomacy_bot, diplomacy_web (nginx),
caddy, diplomacy_docs — runs from one docker-compose.yml on one VPS; Caddy is the
public entry (80/443). Two other ports are published by compose and bound by env: nginx on
${WEB_BIND:-0.0.0.0}:${WEB_PORT:-80} (ensure_env.sh sets WEB_BIND=127.0.0.1 and
WEB_PORT=8080 once DOMAIN is set, so with HTTPS on only Caddy is reachable; without a
DOMAIN, nginx is the public HTTP entry) and DAIDE on ${DAIDE_BIND:-127.0.0.1}:8432
(loopback unless DAIDE_BIND says otherwise; ensure_env.sh does not set it). The API is
published on 127.0.0.1 only and Postgres not at all. The bot and nginx reach the API by its compose service name
(docs/DEPLOYMENT.md). The images of our four services (API, bot, web, docs) are built
in GitHub Actions and pushed to GHCR tagged with the commit SHA
(ghcr.io/tenderi/diplomacy-<service>:<sha>, .github/workflows/deploy.yml); the host
only pulls them (upgrade.sh), and builds them itself only when the pull fails or with
upgrade.sh --build. A rollback is a deploy of the previous SHA. The deploy reaches the
host through a forced-command SSH key (host/deploy_hook.sh) that deploys only main's
commits and runs only the maintainer-installed copies of the host scripts; a change to
docker-compose.yml or docker/Caddyfile ships only once the maintainer approves it on
the host, so a merged commit changes the containers but never the host
(docs/DEPLOYMENT.md §Hardening). The API is a separate process that is down during every deploy and
after any crash, and a deadline may pass while it is. The contract is that no player
message is ever lost in either direction — only delayed, and always with the original time
preserved.
Player → server (telegram_bot/outbox.py, api_client.api_post_reliable). Orders and
diplomatic messages are written to a SQLite queue (the bot_data volume) before the first
attempt.
Outcomes are delivered / queued / rejected; the handler shows the matching
reply, and a background loop (notifications.outbox_replay_loop) retries queued entries
strictly in id order — stopping at the first that is still unreachable so nothing overtakes
an older write — and DMs each result. A 4xx is a definitive answer (rejected, "The server
refused it: …"). No answer, or a gateway's 502/503/504, is an outage: the entry stays queued
as long as it lasts, with the backoff of outbox.backoff_seconds (5 s doubling to 60 s).
Any other 5xx (500, 501, …) is the API failing on the request — a database blip, a bug — and
is retried the same way, but only api_client.MAX_SERVER_ERRORS (8) times, about four
minutes: the queue is shared by every chat and strictly ordered, so a route that always
answers 500 would otherwise hold back every player's writes behind it. Then the entry is
failed and the player is told "The server kept failing (HTTP 500 on 8 tries), so I
stopped trying. It did not refuse it: please send it again." No answer or a 502/503/504 in
between neither counts nor resets the count, so an outage never makes the bot give up and a
flapping gateway cannot keep a failing route at the head forever. A first attempt answered
with a 5xx is told "I will retry it for a few minutes". An order retried after its phase ended gets the stale-order 409 below and is
rejected. Each request carries:
client_timestamp— when the player composed it (the entry's creation time).api/client_timestamp.pynormalises it to naive UTC, clamps far-future values, refuses ones older than 30 days.MessageModel.timestampstores it; the recipient's notification gains "(sent HH:MM UTC)" when delivery was noticeably late. Order submissions composed beforegames.phase_started_atare refused with 409 (routes/orders.py::_refuse_if_stale) — the turn was adjudicated without them, and applying last phase's orders to this phase's board would be worse than telling the player. Aclient_timestampmore thanFUTURE_TOLERANCE(5 minutes) ahead of the server clock is refused with 422 on the same routes (the clamp above would otherwise turn it into "now" and let it pass as fresh).phase_started_atis stamped byGameRepoon every write that changesphase_code.X-Bot-Secret— the bot secret, added at send time and only in this header: the stored entry never holds it (it would be on disk, and a write queued before a secret rotation would replay with the old one), and abot_secretleft in a stored payload is dropped before sending.Idempotency-Key— a UUID per entry.api/idempotency.pystores the first response (status + JSON) and replays it, withIdempotent-Replayed: true, to any later request with the same key. The key alone identifies the entry:endpointis stored but not compared on replay, so the same key sent to a different route would replay the first response. This does not occur, since only the bot sends keys and it generates one per write. Honoured only withX-Bot-Secret, only for mutating methods, only for responses below 500 (a 5xx should be retried, a 4xx is a definitive answer to relay). The key is reserved before the route runs:DatabaseService.reserve_idempotency_keyinserts a pending row (status_code0) on the key's primary key, so of two concurrent same-key requests, in any worker, exactly one runs the route. The other — a replay of a write the API is still applying — gets 503 withRetry-After: 5, which the bot counts as transient (api_client.TRANSIENT_STATUSES): the entry stays queued with no server error counted, and the next replay gets the stored reply. (Not 409: the bot reports a 4xx as rejected, which would tell the player a write had failed while it was being applied.) A request that stores nothing (a 5xx, a non-JSON body, an exception) releases its reservation so a retry runs the route afresh; a reservation left by a worker that died mid-request is taken over once older thanIDEMPOTENCY_STALE_AFTER(5 minutes, far past any route's run time). The reservation'screated_atis its owner token: the release and the fill both match on it, so a request that ran past the limit can neither free nor fill the reservation of the one that took its key over. Keys expire after 7 days (run_housekeeping).
game_context.fetch_user_games caches each user's games/powers in the same SQLite file and
falls back to the cache when the API is unreachable, which is what lets /order A PAR - BUR
resolve which power you hold and reach the queue while the server is down.
Server → player (bot_outbox table, routes/bot_outbox.py, api/long_poll.py,
notifications.notification_loop). Described in the section above. Delivery is
at-least-once: a row is acked only after Telegram accepts the message, so a crash between
send and ack can repeat a DM. Permanent Telegram failures (user blocked the bot, chat not
found) are acked as failed with the error kept on the row. Delivered rows are purged after
7 days.
The poll is a long-poll. GET /bot/outbox?wait=N (0 ≤ N ≤ 60, default 0 = answer at
once) answers immediately when rows are pending; otherwise it holds the request until a row
is committed or N seconds pass, and then answers with what is there (on timeout {"items": [], "count": 0}; the count is also sent as X-Outbox-Count).
The wait holds no database connection: the request registers an asyncio.Event and queries
only when woken. Two things wake it: DatabaseService.enqueue_bot_notification calls its
bot_outbox listeners after each commit, which wake every waiter in that process; and
every DIPLOMACY_OUTBOX_RECHECK_SECONDS (default 2) the waiter queries anyway, which is how
a row committed by another uvicorn worker is found. Postgres LISTEN/NOTIFY would wake
across workers too, but costs a dedicated listener connection per worker, a thread to poll
it and reconnect handling; one indexed query every two seconds for the one waiting request
is simpler to get right, and its worst case is still faster than the fixed 3 s poll it
replaced. Reading and acking are unchanged: the long-poll only changes when the response
is sent.
The bot asks for wait=DIPLOMACY_NOTIFY_WAIT_SECONDS (default 25) with an HTTP timeout ten
seconds longer, and polls again at once after a poll that handed over rows. A poll that
handed over nothing in less than DIPLOMACY_NOTIFY_POLL_SECONDS (default 3) — an API that
ignores wait, the API unreachable, Telegram refusing — sleeps out the rest of that, so the
loop never spins. Each cycle touches the heartbeat, at most ~35 s apart (the replay loop
touches it every 5 s as well), well inside the healthcheck's 120 s staleness limit.
The access log. api/access_log.py keeps healthy noise out of uvicorn's access log: a
logging.Filter on uvicorn.access (installed by _api_module, so it applies however
uvicorn is started) drops /healthz, /health and empty GET /bot/outbox lines whose
status is below 400. Every error on those paths is still logged, and so is a poll that
handed rows over. uvicorn's access record carries no response body, so the route sets
X-Outbox-Count, and the outermost middleware (QuietAccessLogMiddleware) marks an empty
poll in a context variable for exactly the send that uvicorn logs from.
What the bot needs to run: python-telegram-bot, requests, and a writable
DIPLOMACY_BOT_DATA_DIR. Nothing else — no database URL, no engine, no FastAPI. The Docker
image installs requirements-bot.txt only; tests/test_execution_context.py and the image
build are what keep that boundary honest. The bot starts and stays up whether or not the API
is reachable; that is the whole point.
Frontend¶
React 18 + Vite + TypeScript SPA (frontend/), Tailwind + shadcn/ui. Consumes the
GameState-native GET /games/{id}/state view directly (units_by_power, ownership,
dislodged, contested, phase_type, players, ...). Vite proxies /api to
http://localhost:8000 in dev; in production nginx serves the built app.
The sandbox (/sandbox, /sandbox?game=<id>) is a scratch board on which a player
orders all seven powers and steps through the phases, from a game's current position or the
opening one. It is stateless on the server: the page holds the serialized GameState and
sends it to POST /sandbox/* (data_spec.md §4), which validate, adjudicate and render it
through GameService without touching the database. Leaving the page discards it.
Out of scope for this document¶
Route-by-route API reference, Telegram command list, and DB column-level schema live in
data_spec.md, src/server/README.md and the user-facing docs in docs/. Map variants
beyond standard and a rendering redesign are out of scope (fix_plan.md).