Headless mode (server)
Note
This section describes an advanced, optional mode of blunderDB, intended for server deployments, multi-user setups and automation. The normal and recommended use of blunderDB remains the desktop application described in the previous chapters. If you use blunderDB on your own, on your computer, you do not need this mode: you can skip this chapter without losing any of the analysis features.
Overview
In addition to the desktop application and the command-line commands (see Command Line Interface (CLI)), the same blunderdb binary can run in headless mode: without a graphical interface, driven entirely from the command line or over the network. This mode covers three use cases:
the
servedaemon — exposes the blunderDB engine as an HTTP + JSON service, to run a shared database on a server and access it from several clients;the generic
calldispatcher — calls any storage operation directly, locally, for scripting and testing;the
migratecommand — transfers a single-user SQLite database to a multi-user PostgreSQL backend.
These three use cases rely on a shared storage layer that can talk to two backends: SQLite (the usual .db file format of the desktop application) and PostgreSQL (for multi-user server deployments).
The serve daemon
blunderdb serve runs the engine as an HTTP service that responds in JSON. It lets you host a position database on one machine and access it from several clients.
# sqlite
blunderdb serve --db database.db --addr 127.0.0.1:8080
# postgres
blunderdb serve --backend postgres \
--dsn "postgres://user:pass@host:5432/blunderdb?sslmode=disable" \
--addr 127.0.0.1:8080
Note
sslmode=disable is only suitable for a trusted private network — a database in a neighbouring container, on a network with no route to either the host or the Internet. For a remote database, sslmode=require encrypts the link, and verify-full also checks the server’s certificate and hostname. The other connection strings on this page carry sslmode=disable for the same reason: they all describe a private network.
Warning
The daemon performs no authentication. It trusts the X-Tenant-ID request header and must run behind a reverse proxy (nginx, Caddy…) responsible for authentication. Never expose it directly to the public Internet.
X-Tenant-ID is the tenant’s integer (1, 2, 42…): it is the reverse-proxy’s job to map the authenticated account to that integer. A name (alice) is refused with 400 invalid, never converted.
The optional X-User-Name header names the person behind the request: it signs the comments they write (comments.add, the MCP tool comment_position), and the daemon trusts it without checking, like X-Tenant-ID. Without it, the comment has no author — never the tenant, which would leave with an export. An import does not sign in the name of whoever imports: the notes of an XG file are signed “XG”, those of another file by its transcriber, those of a .db database by their original author.
Options:
Option |
Default |
Meaning |
|---|---|---|
|
– |
SQLite file (shorthand for |
|
|
storage backend: |
|
|
backend connection string |
|
|
listen address |
|
|
log level: |
|
|
exposes |
|
|
serves the read-mostly web page under |
|
|
serves the tournament and event direction gestures; off by default, see Direction gestures |
|
|
offers the write tools of |
|
|
serves the transcription moves ( |
|
|
serves the gestures of a Duel ( |
|
|
closes a transcription session that has been idle for longer than this |
|
– |
enable CORS for this origin, a comma-separated list of origins, or |
|
|
requests per second per tenant limit (0 = disabled); enabled by default at a generous value rather than opt-in, so a compose file that only thinks about the database does not end up inheriting a daemon with no limit at all |
|
|
token-bucket size for request bursts |
|
|
positions a tenant may store, checked at the start of an import: once the limit is reached, the import is refused (413, |
|
|
bytes a tenant may occupy on disk (tables and indexes), checked at the start of an import like |
|
|
CPU seconds of engine computation per tenant and per UTC day (429, |
|
|
imports of a single tenant running at the same time (429, |
|
|
disk space that the imports in progress occupy together, all tenants combined (429 beyond it): an upload reserves twice its declared size, a batch what its archive announces; 0 = four times the largest upload allowed |
|
|
engine workers shared by the sweeps and evaluations of all tenants; a search spreads over the idle workers; 0 = one per core |
|
|
reads of the whole library served at once (see below); 0 = one per pair of cores on SQLite, unbounded on PostgreSQL; -1 = unbounded |
|
(empty) |
|
|
|
PostgreSQL: enables per-tenant Row-Level Security (defence in depth, opt-in) |
|
|
honors the |
|
– |
optional two-sided bearoff database ( |
|
– |
directory for the daemon’s signing identity (created on first use); needed for |
|
– |
name carried by this identity: the one read by the recipient of a watermarked export and of each signed comment; when empty, the recorded name is kept ( |
|
– |
directory on the daemon’s machine that |
|
– |
serves the |
|
– |
exposes |
All options except --db and --transcription-ttl can also be given through an environment variable (BLUNDERDB_BACKEND, BLUNDERDB_DSN, BLUNDERDB_ADDR, BLUNDERDB_LOG_LEVEL, BLUNDERDB_METRICS, BLUNDERDB_WEB, BLUNDERDB_DIRECTION, BLUNDERDB_MCP_WRITE, BLUNDERDB_TRANSCRIPTION, BLUNDERDB_DUEL, BLUNDERDB_CORS_ALLOW_ORIGIN, BLUNDERDB_RATE_LIMIT_RPS, BLUNDERDB_RATE_LIMIT_BURST, BLUNDERDB_QUOTA_POSITIONS, BLUNDERDB_QUOTA_BYTES, BLUNDERDB_QUOTA_ANALYSIS_SECONDS, BLUNDERDB_QUOTA_IMPORTS, BLUNDERDB_ANALYSIS_WORKERS, BLUNDERDB_HEAVY_SLOTS, BLUNDERDB_ANALYSIS_WEIGHTS, BLUNDERDB_RLS, BLUNDERDB_READ_TENANTS, BLUNDERDB_TS_PATH, BLUNDERDB_IDENTITY_DIR, BLUNDERDB_IDENTITY_NAME, BLUNDERDB_IMPORT_DIR, BLUNDERDB_OPS_ADDR, BLUNDERDB_PPROF_ADDR): an explicit flag still wins over the matching variable.
The daemon has no data-directory option: it writes its bearoff tables to $XDG_DATA_HOME/blunderdb, or ~/.local/share/blunderdb otherwise. So it is XDG_DATA_HOME that moves them — see The bearoff databases.
The rate limiter’s own bucket table carries a hard cap (10,000 distinct tenants): beyond it, each new tenant evicts the least-recently-used bucket rather than letting the table grow without bound — useful if a client sends many distinct X-Tenant-ID values, whether by accident or not, between two periodic sweeps of idle buckets.
blunderdb serve rejects any unexpected positional argument (beyond the single leading serve that an ENTRYPOINT already reduced to the bare binary lets through): without this check, a flag placed after such an argument was silently ignored — docker run image serve --addr :9090, a natural reflex since the image’s ENTRYPOINT is already serve, used to start on :8080 without a word.
Endpoints
The service exposes operational endpoints, always present:
GET /healthz— liveness (the process is running);GET /readyz— readiness (storage responds and its schema is at the expected version);GET /metrics— Prometheus metrics (if--metricsis enabled);GET /app/— the read-mostly web page (if--webis enabled).
The web page
blunderdb serve --web serves a page under /app/: a library you can consult from a tablet or a phone, with nothing to install.
It can do four things, and that list is the decision, not a stage:
consult a position, its analysis and its board;
search, with the same token grammar as the application’s command line;
review an Anki deck — answer revealed and grade given;
display a tournament, read-only: the Tournoi tab shows a Direction’s display page (bracket, pairings, results, standings), the same one the desktop writes to its display folder, and refreshes it every ten seconds by conditional read (
If-None-Match: a 304 as long as nothing has changed)./app/?tournoi=<id>shows only that tournament, with no menu — the address to project or share.
It cannot edit a position, import, delete, manage collections, matches or the configuration, nor enter anything into a tournament, and it will not learn to. A feature missing here is not a gap: it is the perimeter.
It is off by default, and that default is the decision. The daemon authenticates nobody: it trusts the X-Tenant-ID header and must run behind a proxy that authenticates. Shipping a browser-reachable interface switched on out of the box would invite exactly the deployment that rule forbids.
The desktop itself serves a tournament’s display on the local network, without serve: the Direction starts on demand a server that exposes only the web page and directions.pageHtml for the single chosen tournament — any other address of the page redirects to that tournament’s display, never to the full application —, sets the tenant itself, and shows the address’s QR code (see the manual, Displaying a tournament). It authenticates no one either: anyone on the local network reads the page.
The page sends no tenant: the proxy sets the header, as for any other client. In local development, and there only, /app/?tenant=1 names one — which changes nothing about the safety of a daemon that already accepts that header from anyone. Opened without a proxy, the page loads, but its data calls are refused: it says so in plain words (“cette page se sert derrière un mandataire…”) rather than staying blank, and the daemon recalls it in its log at startup.
The page’s files are served without a tenant, deliberately: a browser must be able to load the page before the proxy assigns it anything, and a page holds no data.
Liveness and readiness answer two different questions. /healthz always answers 200 as soon as the process serves requests, without ever querying the storage: an orchestrator restarts a container whose liveness fails, and a briefly unreachable database must not restart a healthy daemon in a loop. /readyz answers 503 (with status set to down or version_mismatch) as long as the database does not answer or its schema is not the binary’s: traffic is simply routed away until it comes back.
The blunderdb healthcheck subcommand (also present in the serve binary of the container image) performs a GET /readyz request on the local daemon and returns 0 when it is ready, 1 otherwise; the address is that of --addr or BLUNDERDB_ADDR, :8080 by default. It is the Docker image’s HEALTHCHECK, and it works just as well from a script or a systemd unit:
blunderdb healthcheck --addr 127.0.0.1:8080 && echo ready
The business surface follows the POST /v1/<family>.<method> shape (for example /v1/positions.save, /v1/matches.get). The families cover positions, analyses, matches, comments, collections, tournaments, Anki cards, filters, sessions, history (search and commands), search, metadata, library settings, statistics, import and export. Listing endpoints return an NDJSON stream (one JSON object per line). The server shuts down cleanly on SIGINT / SIGTERM.
An error returns the envelope {"error":{"code":…,"message":…}}. The code not_found says a named resource does not exist; unknown_route, also a 404, says the daemon does not serve the method called: a client and a daemon of different versions, or a family the daemon only serves behind a flag. A client concludes that data is missing only on not_found.
positions.save returns {"id":…,"created":…}. created is true for the one call that inserted the position, and the write itself says so: a client that copies a position then its analysis, and must undo the copy after a failure, deletes the position only if it created it, without the race of a prior positions.exists.
What /v1 promises
A client written against /v1 must keep working. The rule fits in three lines, and it is more useful written down than guessed:
What exists does not change meaning. A
/v1route is never renamed, removed or re-purposed. A request or response field is never renamed, dropped or retyped.What is added is added. A new route, an optional request field, a new field in a response: a client that ignores them keeps working — that is the definition of “compatible” taken here. A client must therefore ignore the fields it does not know rather than refuse them.
Everything else is
/v2. Making a field mandatory that was not, changing a unit, changing the meaning of an error code: those are breaks, and they live under another prefix, beside/v1, for as long as clients need to cross over.
Two clarifications that matter. The /ops/ routes are not covered: they operate a deployment, change with it, and are not an API for third-party programs. And the contract itself is generated from the daemon’s route table (openapi.yaml, API contract): it cannot describe anything other than what the server serves.
Lessons
Lessons (Lessons) are read and written under the caller’s tenant through fourteen routes: /v1/lessons.list, lessons.get (the lesson and its steps, in order), lessons.create, lessons.update, lessons.delete, lessons.addStep, lessons.updateStep, lessons.removeStep, lessons.reorderSteps, lessons.setStepDone ({"id": <step>, "done": true|false}, the reader’s “step done” gesture, written under their own tenant) and lessons.doneSteps (the date of that gesture per step). lessons.html ({"id": <lesson>, "language": "en"}) renders the lesson as one self-contained HTML page, boards included; lessons.markdown and lessons.importMarkdown exchange Markdown (see below). Deleting a lesson is permanent and leaves the collections and positions that its steps showed. The MCP tools list_lessons and lesson read them.
lessons.markdown ({"ids": [<leçon>, …]}) renders lessons as one Markdown text (markdown): # nom, the description, then one ## titre section per step; an article is a lesson with no step. lessons.importMarkdown ({"markdown": "…"}) creates one lesson per document, in a single transaction, and returns their ids. The Markdown carries text only: an imported step shows neither board nor collection. A code block that no fence closes is refused.
Transcribing through the API
The transcriptions.* family lets an external client transcribe a match move by move, with the same logic as the desktop. The reads (list, get, exportMat, losses) are always served. The moves (create, open, editMatch, apply, undo, redo, candidates, close, finish, abandon, materialize, import) are served only with serve --transcription (Config.Transcription for a host that embeds the engine): without this flag, these routes answer 404.
create and open return the draft’s state, its revision and a sessionId. apply, undo, redo, close and finish name that sessionId: missing → 400, expired or unknown session → 410; the client then reopens the draft (open), cursor at the end of the document. abandon names no session: it deletes the draft under the If-Match revision alone. Every move that writes carries the last revision seen in the If-Match header and returns the next one:
If-Matchmissing → 428;stale revision → 409; the error envelope gives the current revision (
details.revision) and the draft’s fresh state (details.state: document, revision, session and cursor), which the client displays before replaying its move if it still applies.
The revision advances only when the document changes (header and actions): moving the cursor or entering a die of the action in progress writes nothing and returns the same revision. A session belongs to the draft, not to a client: open returns the live session when there is one, and the tabs or workstations that share it also share the cursor and the undo stack.
The session keeps only the undo stack, the cursor and the entry in progress: the draft is written after every move that changes it, so a lost session (inactivity, restart, another instance) loses no move. transcriptions.get returns the revision as an ETag and answers 304 to an If-None-Match that names it.
The state returns the video tracking as the desktop shows it, with no recomputation on the client side: annotated.document.header.video_source is the video the markers refer to; each annotated.actions[i] carries its markers (roll_tick_ms, tick_ms, in milliseconds from the start of the video) and the durations they give (decision_ms, cube_decision_ms), with decision_estimated when a play’s duration is an upper bound estimated up to the next action. An unknown key is absent.
candidates (id, sessionId) returns the legal plays of the roll being entered, both dice typed (otherwise 400): all of them, with no cap, ranked at 0-ply without pruning, from best to worst, as in the desktop’s transcription panel. Each play carries index (the one select_candidate names), its notation, its steps, its rank and its evaluation (analysis). If the ranking fails (score outside the match equity table), unranked is true and the plays follow the generator’s order. This ranking neither counts against nor checks the analysis quota; it goes through the same workers as evaluations, taking its turn among tenants, and is not subject to the heavy-read gate (--heavy-slots).
finish saves the Match and deletes the draft, abandon deletes it without a Match, close only releases the session. editMatch opens a draft on an existing Match and, for an imported match, returns the count of analyses and comments that the transcription does not keep (losses.lossy). The analysis of the saved match is started with gammonnet.analyzeMissing.
materialize writes a Match in a single call from an actions document (header and actions, dice included), without a draft or a session, under Idempotency-Key. It applies the rules machine like the Duel referee: the first refused action stops everything, nothing is written, and the error (400) gives its rank from 0 (details.rank, -1 for the header), its kind (details.kind) and its reason (details.detail). The Match is the one that create, one apply per action and then finish would give: same fingerprints, no “played here” origin. The decision duration of an action (decision_ms, cube_decision_ms) is carried over onto its move; when absent, it stays unknown. The response is that of finish.
import opens a new draft on a document written elsewhere, under Idempotency-Key: either the text of a .mat file (mat) or the actions of a transcription document (actions, with optionally header, format_version and next_score: a draft’s document is sent as it is) — one of the two, otherwise 400. Unlike materialize, nothing is refused for an inconsistency: it is kept and marked, and the client corrects it before finish. Only what no replay can read is refused (400, nothing is written): a .mat without a game, a newer document format, an unknown action kind, a player, die or point off the board; details.rank then gives the rank of the faulty action (-1 for the header). A document without format_version is read in the current format. The response is that of create: the draft’s state, its revision and its sessionId.
Warning
The daemon authenticates nobody: opening writes means entrusting them to the proxy (Deployment behind an authenticating proxy). A “transcriber” role is a proxy rule on the /v1/transcriptions. prefix, not a notion of the daemon.
Playing a Duel through the API
The duels.* family drives a Duel one Action at a time, with the same logic as the desktop. The reads (list, get) are always served. The gestures (create, open, act, flag, suspend, stop, forfeit, discard) are served only with serve --duel: without this flag, these routes answer 404.
create receives the match length (or a money session), the Start position, the two Sides ({"kind": "external"}, or {"kind": "bot", "level": "instant"} — normal and thorough exist too; an unknown Side or level is refused with a 400), the Cadence and the names. Two Bots play the whole match in the call that creates the Duel; a money session between two Bots, which would never end, is refused with a 400. act plays an Action — roll, double, take, pass, move or resign — and names its Side (play.side, 0 or 1, mandatory: absent → 400): the daemon authenticates no one, so the client answers for who plays for whom. The response returns the state of the Duel at the next point where an external Side decides, with the Actions that happened in between (rolls, forced moves, Actions of a Bot). An Action the rules refuse is a 400 and writes nothing.
An external Side may declare the Bot that plays behind it, a gammonNet Bot the client runs itself: {"kind": "external", "declared": {"configuration": "normal", "engine": "v1.6.0"}}, two texts of at most 64 bytes. Without a given name, the player takes the Bot’s (gammonNet normal). The Arbiter treats this Side as any external Side. The Match’s origin (matches.origin) carries the declaration apart, in declared_bots, as declared by the client and not attested: bot_level and bot_engine only name the Bot the Arbiter played itself.
With "combinedSeed": true, create publishes the fingerprint and does no more: the Duel awaits each external Side’s contribution to its seed (awaitingContribution), with no roll and no clock, and a game Action before them is refused with 400. duels.contribute (id, side 0 or 1, contribution, 1 to 64 bytes) brings it once per Side; a second contribution, one from a delegated Side or one without a combined seed are refused with 400, and the last contribution starts the dice. The rolls then come from the effective seed, the HMAC-SHA256 of the sealed seed over each Side’s contribution, in player order, preceded by its length as 4 big-endian bytes. The Match’s origin carries the contributions (contributions) and the effective seed (roll_seed): everything is recomputed from the revealed seed.
Every gesture on an existing Duel carries the revision last seen in If-Match: absent → 428, stale → 409, including for a second client that read the same revision as a first one that already got through. A tenant can have several open Duels at a time, each with its clocks running: opening one suspends none of the others, and a Bot’s computation holds up its own Duel only. A gesture on a suspended Duel opens it in the same write. “Open” is written in the draft: list reads it there, an open Duel stays open after a daemon restart, and two daemons on the same database see the same open Duels, the revision settling their gestures. get returns the revision as an ETag and answers 304 to an If-None-Match that names it.
The dice seed leaves through no route before the end: the state carries its fingerprint, and the seed is revealed only with the Match that the end of the Duel writes (ended.diceSeed). discard throws the Duel away: nothing of it is written. The gestures are announced on /v1/events (duel filter). Under blunderdb call, a Duel has no Cadence and no decision time: each call is its own process.
forfeit gives the match up for a Side (side, 0 or 1, required): the game in progress goes to the other Side for the points that bring them to the match length — at money play, a single at the cube’s value — and the Match is written won by them. stop with keep true writes a money session’s Match as it stands, the game in progress without a winner; on an unfinished match in points it is refused with 400 and the Duel stays open: the Match is written whole only, and the Duel is suspended, forfeited, or stopped with keep false, which throws it away. Stopping is not forfeiting. Under a Cadence whose overrun loses the match (timeOut set to lose_match), losing on time counts as a forfeit by the Side whose time ran out: in points, the Match is written won by the other at the length.
Export is no exception: exports.sqlite carries no suspended Duel, even when it covers the whole tenant, since its seed is every roll to come. The Match of a finished Duel travels with its origin, seed revealed. Only migrate carries the suspended Duels with their seed, so that they resume on PostgreSQL with the same dice.
Warning
The daemon authenticates no one: whoever reaches these routes plays for either Side. A proxy rule on the /v1/duels. prefix decides who may (Deployment behind an authenticating proxy).
A Python client
clients/python/ holds a minimal client with no dependency beyond the standard library — the daemon speaks POST and JSON, which urllib and json cover entirely:
from blunderdb import Client
api = Client("http://127.0.0.1:8080", tenant=1)
print(api.metadata_counts())
for position in api.positions_list({"limit": 10}):
print(position["id"])
It comes in two halves, on purpose. _generated.py carries one method per route, generated from the daemon’s route table by go run ./cmd/openapi-gen: a hand-written surface would drift the day a route is added, and nobody would notice before a user did. client.py carries the transport — the session, the tenant header, the error envelope, the NDJSON decode — and is written by hand. What changes with the API is generated; what changes with judgement is not.
Method names are family_operation in snake_case: /v1/positions.loadByIds becomes positions_load_by_ids(). The family is kept because several families share an operation name (list, delete), and a bare list() would collide.
events() follows /v1/events and returns one dictionary per message (see Being notified of gestures: /v1/events).
A failure raises APIError, carrying the daemon’s envelope as it is: the code (what a program branches on), the message (what a person reads), the HTTP status and the details.
Embedding the engine in a Go program
pkg/blunderdb/server.Bootstrap opens the storage and returns a set of handlers in the calling process, without listening on a port. It is the way in for a trusted parent — gammonGo — that wants the position library without running a daemon beside it or speaking HTTP to itself.
What that assumes is explicit: the parent is trusted. There is no tenant to verify, no header to validate, no rate limiter — those belong to the daemon because it faces a network, and ADR-0005 says why. A program that embeds the engine chooses its own tenant and answers for its calls.
Config.EnableDirection opens the tournament direction gestures in the embedded engine, as serve --direction does for the daemon; they are closed by default.
Tournament direction and events
Tournaments directed at the workstation and the events that group them (rencontre in the API and its /v1/rencontres.* routes) are read through the API, under the caller’s tenant, with the same code as the workstation. Reading is always served; the gestures (entering a result, pairing, creating an event) are served only under serve --direction (Direction gestures).
directions.listanddirections.directoryread the whole tenant: the list of directed tournaments, the player directory.The other
directions.*take{"tournamentId": N}:directions.get(the full view: proposals, standings, matches in progress),directions.participants,directions.freeParticipants,directions.tableGrid,directions.freeSlots(the bye slots a latecomer can still take),directions.brackets,directions.standings,directions.standingsCsv,directions.history(optionalplayerandmatchfilters),directions.clock,directions.slots,directions.lastDecision,directions.pageHtmlanddirections.pairingSheetHtml(withround).directions.statuses(tournamentId, andidsto read only some registrants) answers “am I playing?”: for each registrant,kind(playing,bye,qualified,undecided,eliminated,winner,withdrawnornot_entered), the phase, the section, the round and alabelin codes, never in sentences, the remaining lives (lives) and, when a match is in progress,matchId,tableandopponent. An identifier that is not registered is omitted.rencontres.list, thenrencontres.getandrencontres.pageHtmlwith{"id": N}.rencontres.pageHtmlrenders the room’s wall page, a self-contained HTML document in thehtmlfield: a wall screen displays it and reloads it periodically.rencontres.rankingreturns the season ranking, likeblunderdb tournament ranking --season:rencontreId,from,to,points,participationandelo, all optional; withoutrencontreIdor a period, all the tenant’s directed tournaments count.
Pages are rendered in French, the language of the direction engine. A tournament that is not directed, or that belongs to another tenant, answers 404.
Conditional reads. Each of these routes returns an ETag header. Sent back in If-None-Match, it gets 304 with no body as long as nothing the route reads has changed. Any write changes the ETag at once: a gesture in the tournament or in a tournament of the same event, the attachment of a match, a draft started from a slot, the renaming of a tournament, a change to the event. Answering 304 replays no tournament, which makes a wall page that polls every few seconds inexpensive. Only what depends on the time is an exception: proposals, the clock and pages are computed at the moment of the read, so an ETag is valid for one minute at most. A client that reloads thus sees a deadline or a pause go by within the minute.
These routes are POST. For this verb, RFC 9110 (§13.1.2) answers 412 to a matching If-None-Match. The daemon answers 304 nonetheless: the request body carries only the parameters of a read with no effect, which behaves like a GET. The If-None-Match: * form is refused (400), because it designates no response the client would already have. An invalid request (a negative round, for example) is refused before any condition.
curl -si -X POST http://127.0.0.1:8080/v1/rencontres.pageHtml \
-H 'X-Tenant-ID: 1' -d '{"id":1}' | grep -i '^etag'
curl -si -X POST http://127.0.0.1:8080/v1/rencontres.pageHtml \
-H 'X-Tenant-ID: 1' -H 'If-None-Match: W/"…"' -d '{"id":1}'
# HTTP/1.1 304 Not Modified
Like the rest of /v1, these routes authenticate no one: behind the proxy (Deployment behind an authenticating proxy), anyone who reaches a tenant’s /v1/directions. prefix reads its tournaments, player names included. A proxy that reserves these reads for certain users does so with a rule on that prefix and on /v1/rencontres..
Direction gestures
blunderdb serve --direction opens the gestures the workstation performs on a directed tournament and on an event. Without this flag, these routes answer 404, as if absent. call always serves them.
directions.create(tournamentId,config,seed),directions.setConfiganddirections.previewConfig(config, the configuration in the engine’s JSON format);registrations:
directions.enterParticipants(players),directions.addParticipant(name,club,rating; withsectionandkey, a latecomer takes a bye slot; withid, the registration keeps the given identifier, refused if it is already taken),directions.updateParticipant,directions.withdraw,directions.reinstate,directions.makeAbsent,directions.makeAvailable,directions.addPair,directions.updatePair,directions.replaceParticipant(id, the player replaced, who has not played a match yet;name,club,ratingandnewIdfor the newcomer; a doubles pair is refused),directions.replacePair(id, the pair replaced;membersandratingfor the new pair, whose two persons replace the former ones in the directory),directions.swapParticipants(a,b: two players who have not played a match yet exchange places);the course of play:
directions.confirmProposal(action, as proposed bydirections.get),directions.confirmAllProposals,directions.startMatch,directions.enterResult,directions.enterForfeit,directions.moveMatchToTable,directions.cancelMatch,directions.correctResult,directions.close,directions.reopen,directions.addNote,directions.attachMatch,directions.detachMatch;confirming a list:
directions.confirmProposals(actions, the proposals asdirections.getshows them) records all of them at the same instant, so that the matches launched together form a single batch, or records none. A proposal held back (reasonequal towaiting_table,player_unavailableorplayer_busy) cannot be confirmed: a list containing one is refused. What the list brings about, the queue after a repechage or the draw of the next phase, is proposed in the response and is never confirmed automatically;the reason for a refusal: the 400 of a refused gesture carries, when the cause is one of these, a stable code in
details.reason:table_taken(the table is occupied, in this tournament or in another one sharing its room),player_busy(a player is in a match of another tournament of the room),no_such_table,table_outside(the table is in none of the tournament’s rooms),table_closed(table reserved or kept for someone else),proposal_heldandproposal_changed(a proposal of the list is held back, or is no longer proposed as listed). The message remains meant for reading, the code for deciding;the other reasons:
repechage_pending(a draw or a passage to the next phase is listed while a repechage between tied candidates awaits the director’s choice),empty_list(empty list),invalid_action(a proposal sent back cannot be read) andengine_refused(the engine’s rules refuse the event, the message says which);the rounds of the current phase: in a manually paired phase (
manual), the director places each match withdirections.startMatchandround(0: the latest round; the next one opens it) and each bye withdirections.placeBye(id,round), withdrawn withdirections.cancelBye; any other phase refusesround. In a Swiss by rounds (swiss_rounds),directions.giveHalfBye(id,round, required) records that a player will not play that round and takes half a point there, anddirections.cancelHalfByewithdraws it while the round is not open;the event:
rencontres.create,rencontres.update,rencontres.attach,rencontres.detach,rencontres.trash,rencontres.setTableOutOfService,rencontres.setBreaks;the table properties:
rencontres.setTables(id,tableSettings, one entry per table that carries any: number, name, room, reserved, assigned to),rencontres.setEventRooms(id,tournamentId,rooms, the rooms the competition plays in; none means all tables) anddirections.setTables(tournamentId,tableSettings) for a competition that plays alone.
A tournament gesture returns the full view of the tournament, like directions.get; an event gesture returns the event. The service then rewrites the display pages in the folder the database designates, as at the workstation. A page that cannot be written (folder gone, disk full) does not cancel the gesture: the response carries a Direction-Page-Warning header for each page not written (tournament 3, rencontre 2), without the server path, and the workstation shows it in its status bar.
A gesture that the rules refuse (empty name, occupied table, tournament that has not started, configuration rejected by the engine) returns 400 with the reason. A failure of the daemon or its database returns 500, without detail: the reason stays in the daemon’s log.
Simulating a format. directions.simulate plays a format through without a tournament or a database: config (the engine configuration), players (a head count, from 2 to 512, or a list of entrants with id and rating), tables, start, runs (30 by default, 200 at most) and seed. The response returns runs, matches, minutesP10, minutesP50, minutesP90, estimatedEnd, peakTables, matchesPerPlayerMin, matchesPerPlayerMax and warnings, a list of codes. The same request returns the same response. The simulation starts each match as soon as it is paired: peakTables is the number of tables needed so that nobody waits, and the code tables_exceeded flags a smaller room, whose returned durations are then a minimum. No version and no If-Match.
The first run, played with the seed of the request, decides: its work is counted, not timed, and a format of which this tournament requires more than an ordinary processor computes in three tenths of a second is refused with 503, code unavailable, details.reason too_heavy, without Retry-After, as soon as the count exceeds that threshold. The same request gets the same verdict on any machine, whatever runs is. It is well formed but too heavy: reduce the field, the pools, the lives, the rounds or the format. An admitted format always returns this first run; the following ones stop two seconds after the computation starts, and the response is then partial: it carries the code time_budget and relies on the runs played, whose number depends on the machine. A run that the engine does not bring to its end is discarded under the code run_failed: the figures rely on the others. A malformed or out-of-bounds request returns 400, whatever the load.
The bounds of a simulation are refusals, stated before any computing: 512 players, 200 runs, 16 phases, matches to 99 points, 100 lives, 4096 tables, 4096 matches drawn at once by a phase (the pools of a round_robin as the engine draws them, the field split equally: a single pool of 91 players at most, two pools of 50 for 100 players in pools of 91, pools of 17 for 512 players) and a body of 1 MiB (413 beyond). directions.create bounds neither the field, nor the lives, nor the pools; the simulation does: nothing in it is sized by the request, and the draw of a large pool, which cannot be interrupted, would hold the processor and the memory outside the budget. Under these bounds, the work decides: a single pool of 40 players, a bracket of 512 or a double elimination of 256 return too_heavy; a single pool of 30 players, a double elimination of 128, a bracket of 256 or 200 players in pools of 4 are admitted. The durations follow the min_per_point of the configuration (8 minutes by default) and, with a start, skip its breaks (breaks) as directions.clock does; without a start, a break, which is a date, is not counted. Also refused (400): a format that plays no match with this field, a simulated tournament longer than a year, and a start whose end falls off the calendar.
The count includes the pairing search of a swiss_rounds, which the engine counts in steps: a large Swiss whose rounds approach its field, or a club holding more than half the field with avoid_clubs, searches long for a round without rematch, and returns too_heavy on that count, with no bound on the number of rounds.
The two computing slots belong to the process, all tenants together: a tenant holding one takes a second only if no other tenant is waiting, and a tenant holding none waits for the next one, three seconds at most. With no slot, the response is 503, code unavailable, details.reason simulation_busy, with Retry-After: the same request can be replayed as is. This wait adds to the computation budget: end to end a simulation can take up to five seconds, and the host sets its timeout above that. A caller who gives up during the wait is not a failure: nothing is written, and the log carries 499.
While the tournament is not finished, directions.clock returns, alongside estimatedEnd, estimatedEndEarly and estimatedEndLate: the 10th and 90th percentiles of the same forecast.
Version required. Every read of a tournament or an event returns a Direction-Version header, and every gesture sends it back in If-Match:
without
If-Match(or with*), the gesture is refused:428;if someone has written since that read, the gesture is refused:
409. The error’sdetailsfield carries the fresh state and itsversion: the client re-reads, then replays its gesture if it is still valid;otherwise the gesture is applied and returns the new version in
Direction-Version.
The comparison is made in the gesture’s transaction, under a database lock (PostgreSQL advisory lock per tournament or per event, SQLite write lock): of two gestures sent on the same read, only one is applied, whether they go through the same daemon, through two daemons on the same PostgreSQL database, or through the workstation and call on the same file. The gesture is written all or nothing. A tournament played in an event has its event’s version, so a gesture in a sibling competition changes it too. directions.create and rencontres.create target nothing existing and take no version.
Idempotence. A gesture that carries an Idempotency-Key header is applied only once: sent again with the same key, it returns the first response, with its headers (Direction-Version included) and Idempotency-Replayed: true. A double click or a network retry does not enter two results; two simultaneous sends of the same key run the gesture only once. Only a successful response is kept.
The key is bound to the request body: the same key with another body returns
422.The replay comes before the version check: it returns the kept response without
428or409, even if the version has moved since.Keys live in memory, in each instance of the daemon, for 24 hours, at most 1,000 per tenant: a restart forgets them, and another instance does not know them.
curl -si -X POST http://127.0.0.1:8080/v1/directions.get \
-H 'X-Tenant-ID: 1' -d '{"tournamentId":3}' | grep -i '^direction-version'
curl -s -X POST http://127.0.0.1:8080/v1/directions.enterResult \
-H 'X-Tenant-ID: 1' -H 'If-Match: "…"' -H 'Idempotency-Key: t4-r2' \
-d '{"tournamentId":3,"matchId":"m7","winner":"aa","scoreA":7,"scoreB":3}'
Warning
The daemon authenticates no one (ADR-0005). With --direction, anyone the proxy lets through enters results. The engine knows no role (director, referee, reader): a role is a proxy rule, which reserves /v1/directions. and /v1/rencontres. for directors, or lets only reads through. Never run --direction on a reachable daemon without that proxy, even on a club’s Wi-Fi.
Being notified of gestures: /v1/events
GET /v1/events is a Server-Sent Events stream (text/event-stream): one message per validated gesture of the tenant, published after the database write, never for a refused or cancelled gesture. The message says what changed and its new version, not the state: the client re-reads what it displays, with If-None-Match.
event: rencontre—rencontreId,tournamentIds(the event’s competitions, before and after the gesture) andversion;event: direction—tournamentIdandversion, for a tournament played outside any event;event: transcription—transcriptionIdandrevision; an abandoned or finished draft carriesremoved(andmatchIdfor Finish).
removed: true signals what no longer exists. The route is served only with --direction, --transcription or --duel: without them, the daemon writes nothing it would have to announce, and /v1/events answers 404. Like every /v1/ route, it requires X-Tenant-ID: a subscriber hears only its own tenant. A tenant holds at most 16 open streams at a time; beyond that, 429. The workstation uses the same service but plugs no bus into it: its gestures are not announced.
The tournament, rencontre, transcription and duel parameters (comma-separated or repeated identifiers) narrow the subscription: a message passes if it names one of them. A tournament of an event receives the messages of its event. An unknown parameter or an invalid identifier returns 400.
curl -N http://127.0.0.1:8080/v1/events?rencontre=2 -H 'X-Tenant-ID: 1'
No history. The daemon keeps no message. Every stream opens with event: resync, carrying an id: the client may have missed gestures before connecting, or between two connections, and re-reads everything it displays. The reason is reconnected when the request carries Last-Event-ID, subscribed otherwise. A subscriber that is too slow, whose queue of 64 messages is full, is disconnected after the same resync: it never delays a gesture. The stream announces a reconnection delay of 3 seconds.
Through a proxy. A : ping comment is sent every 25 seconds so that a proxy does not cut a silent stream; X-Accel-Buffering: no asks nginx not to buffer it. The stream is not compressed, escapes the timeout of ordinary requests and counts as only one request for rate limiting. Stopping the daemon closes all streams; a subscription requested during shutdown receives 503.
Multiple instances. On SQLite, a single instance holds the database: the in-memory bus is enough. On PostgreSQL, as soon as --direction or --transcription is active, each instance relays its actions to the others through LISTEN/NOTIFY, on the blunderdb_events channel: a subscriber attached to one instance hears an action validated on another, or issued through call on the same database. The tenant travels in the notification and the instance that receives it delivers it only to that tenant’s subscribers. Each instance opens two more connections (application_name blunderdb-events-… for listening, blunderdb-notify-… for sending); an instance that cannot listen at startup refuses to start. call announces without listening, and serves its request even if it cannot announce.
Any role allowed to connect can emit on this channel, under --rls too. A received notification is trusted only if its tenant is valid and its kind known; the rest is logged and ignored. At worst, a forged notification can make a tenant’s subscribers re-read their data.
The notification is sent after the database write, like the local message. Two losses remain without
resync: an instance killed between the write and the notification, and a shutdown that cannot send in 2 seconds what is left in the queue. The action is validated, but the streams already open on the other instances only learn of it when their client reconnects.A lost listening connection is re-established, with a growing delay from 250 ms to 30 s. Actions from other instances that happened during the outage are lost: on recovery, each subscriber of the instance receives a
resyncwith the reasonmissed. A notification too long for PostgreSQL (8,000 bytes), or that an instance could not send, reaches the others as this sameresyncfor the tenant concerned.The stream
idvalues are specific to each instance. A client that a load balancer sends to another instance gains nothing from them: theresyncthat opens every stream makes it re-read what it displays.
The bearoff databases
The daemon computes its two default tables at start-up, in the background (TS-06-06 for the cube verdict, OS-06 for the EPC): about six seconds of one core, once, in its data directory — $XDG_DATA_HOME/blunderdb, or ~/.local/share/blunderdb otherwise. Nothing is downloaded and nothing is embedded in the binary (ADR-0027). If that directory is read-only, the tables are held in memory for the life of the process: the service starts, it simply pays for the computation at every restart.
A wider domain is not computed at start-up — TS-06-11 weighs 1.2 GB and takes minutes, which is not something a service decides on its own. It is up to the operator to make it, with the CLI, in the volume the daemon will read:
# generate
blunderdb bearoff generate --ts 6x11 --data-dir /srv/data/blunderdb
# serve
XDG_DATA_HOME=/srv/data blunderdb serve --db database.db
blunderdb serve --db database.db \
--bearoff-ts /srv/data/blunderdb/gnubg_ts6x11.bd
The first launch lets the daemon find the table on its own in its data directory; the second points to it by path, wherever it is. --data-dir is an option of the bearoff subcommands, never of serve.
blunderdb bearoff list --data-dir /srv/data/blunderdb says what the volume holds and what each domain would cost; blunderdb bearoff verify exits with an error on a corrupt table, which makes it a start-up probe usable as is. See Command Line Interface (CLI) for the details.
The operator routes
Two calls do not stop at the tenant making them, and therefore live under a prefix of their own, POST /ops/<family>.<method>:
/ops/maintenance.vacuum(SQLite backend) rewrites the whole file, every tenant’s data included, and holds a write lock for the duration;/ops/tenant.purge(PostgreSQL backend) destroys a tenant’s data, and the tenant it destroys is the one named in the header the caller controls.
The daemon authenticates nobody (see below): a route reachable by one tenant is a route every tenant may call. The prefix exists so the proxy can refuse both with a single rule. Never expose /ops/ through the public proxy. Under nginx, the rule fits in one line of the server block; under Caddy, in two lines of the site:
location /ops/ { return 403; }
location /metrics { return 403; }
@closed path /ops/* /metrics
respond @closed 403
The --ops-addr <host:port> option goes further: the two routes then leave the --addr address and are served only on that second listener, to be bound on an administration interface. Without the option they stay on the main listener, and blocking them is the proxy’s business.
These routes require the X-Tenant-ID header like every other one — a purge names the tenant it destroys, and needs that header more than anything else. Only the probes (/healthz, /readyz) and /metrics go without.
This is why the denial rule above also covers /metrics: requiring no tenant, it is readable by anyone who reaches the daemon, and it publishes the database size and the work in flight, across every tenant. It is meant to be consulted from the daemon’s own machine, or through a path the proxy reserves for operations. The third thing that must never be exposed is not a route but a listener: the one for --pprof-addr, which has no notion of tenant and hands out a profile of the whole process. It should bind to an administration interface, never published by the proxy.
What did not move under /ops/: /v1/gammonnet.sweepStale. The catch-up is expensive but it is scoped to the calling tenant; what bounds it is the rate limit and the in-flight gauges, not a trust boundary.
The complete contract — every method, its request and its response — is generated from the source and versioned: openapi.yaml at the repository root (OpenAPI format, schemas included) and its readable annex, API contract (one table per family). Both are regenerated by go run ./cmd/openapi-gen, and a dedicated test fails if either falls behind the routes actually registered.
Every /v1 request accepts a JSON body (Content-Type: application/json, or no header at all — a body of another type is refused with 400 invalid rather than failing on a confusing JSON parse error); a known method called with the wrong HTTP verb answers 405, the Allow header naming the one verb it accepts. Listing methods that take a limit refuse anything past 1000 rows per page (400 invalid) rather than honouring an unbounded value.
Every listing family accepts limit and offset: positions.list, positions.listIds, matches.list, search.find, anki.reviewLog, comments.listAll, tournaments.list and collections.positions. Both default to zero, which means what it has always meant: everything. There is no implicit cap — a stream is not held in memory, so an unbounded list costs time and bandwidth but never the daemon’s footing, whereas a silent default limit would have a client read a truncated list believing it complete. What the two parameters buy is the ability to page, for whoever wants to.
Every TCP connection is bounded in read/write time per request — a generous budget for ordinary calls, a far larger one for streaming routes (NDJSON lists, imports/exports, the gammonNet catch-up sweep) — and the number of them open at once is capped: past that many, a further connection waits for one of the existing ones to free up rather than every connection unconditionally getting its own thread of execution. A graceful shutdown (SIGINT/SIGTERM) first cancels every in-flight import and gammonNet catch-up — each answers with a trailing {"event":"cancelled"} event instead of having its connection cut with no explanation — before closing the server within the usual grace period. An uploaded import’s temporary file keeps only the extensions the daemon recognises from the original one (.xg, .xgp, .sgf, .mat, .bgf, .ogxm, .txt, .db, .dbx), and every import in flight — across every tenant — shares one global quota of bytes spooled to disk: past it, a new import is refused (too many requests) rather than letting $TMPDIR usage grow without bound.
/v1/imports.json reads back a blunderDB JSON export by filling gaps: the analysis it carries is written only on a position that has none yet, never replacing an existing analysis, and the rollouts on both sides are kept.
The search family offers three doors onto the same search. search.find takes the complete filter object, field by field. search.query takes a query written in the language of the application’s command bar (s cube p>30 E>50, described in List of commands) and streams the same positions; it is the only way to reach, over the network, the filters that have no obvious field — move pattern, comment text, player, date, excluded dice, zones and blots. search.parse searches nothing: it answers what a query means — the filters it denotes, its canonical form (two equivalent queries share it, which makes a saved search comparable) and its diagnostics.
A query carrying a token nothing recognises is refused (400 invalid, naming the token) rather than run while narrowing the search in silence. A token that is understood but has no effect here — x, which switches on the exclusion structure, itself a board rather than text — travels in the X-BlunderDB-Query-Diagnostics header, so that the body stays NDJSON positions for every existing client.
positions.listFields returns, for a page of ids, what a table of positions shows beside the board: analysed, playedErrorMp (the played error, in millipoints), date and matchDated, then two lists of {id, name} — collections, in the library’s order, and decks, the study decks holding a card of the position, in the order they were created. An empty list is [], never null. search.page returns the same rows when asked for listFields. The cost is a fixed number of queries per page, whatever its length.
Two methods in the positions family decode a position without storing it: positions.fromXGID rebuilds a position from an XGID string, and positions.fromXGP from a single-position .xgp file.
POST /v1/exports.sqlite exports the whole current tenant — positions, collections, matches, tournaments (with their Direction and Encounter), lessons, transcriptions, aliases, analyses, comments, played moves, filter library and Anki decks — into a SQLite file that the desktop workstation can open as is. The JSON request body is optional; it carries the export options of the export window and of blunderdb export, under the same names and read the same way, so that the same set of options writes the same file through all three routes. An absent field keeps its default value, that of the whole library: wholeLibrary, each include… and includeAnkiHistory are true. An include… option set to false removes its family (includeMatches, includeCollections, includeTournaments, includeLessons, includeAnkiDecks, includeFilterLibrary, includeTranscriptions, includeAliases, includeAnalysis, includeComments, includePlayedMoves); a list of identifiers restricts it to those items (matchIDs, collectionIDs, tournamentIDs, lessonIDs, deckIDs). With "wholeLibrary": false, only the positions named by positionIDs (or all of them with allPositions), the matches in which they were played, and what the identifier lists designate are exported; includeCollectionPositions adds the positions of the chosen collections, and an include… option left true without a list still carries its whole family when it needs no named positions (lessons, filter library). watermark / watermarkNote apply a watermark signed with the daemon’s own identity (--identity-dir) — without these fields, the export carries no watermark; requesting them without a configured identity fails with the code invalid, like a password: the daemon does not return an encrypted container. A watermarked export also signs every comment written in the tenant and not yet signed, with the same identity: it is one for all tenants, so the signature attests that the comment comes from this server, not from which tenant or which person (name adjustable with --identity-name). positions supplies whole positions, saved or not, in place of positionIDs. metadata is refused: the daemon writes into the file only its creation date and the watermark. "incremental": true exports only what has entered the tenant since the last incremental export under the same syncCursor (default if absent), and advances that marker in the tenant when the file is built (see Synchronising two machines). The marker advances before the client has received the file: an interrupted download cannot be replayed by sending the same request, which would no longer carry those rows. To catch up, request a full export (without incremental), or an incremental export under a new syncCursor, which starts from zero; since the import is idempotent, this overlap creates no duplicates. On PostgreSQL, a concurrent import can make rows numbered below the marker visible after the fact: a marker is therefore held as safe only once every transaction of the database that was running when it was read has ended, however long it lasts, and each incremental export also returns what the previous one carried. The report header carries "syncHeld": true when rows were set aside: the marker has then not advanced. exportPath is ignored. A key that the options do not know, or written with another case (collectionIds), is refused with the code invalid, which names it. The response carries, in the X-Blunderdb-Export-Report header, the JSON count of what the file contains, family by family. POST /v1/exports.plan takes the same body and returns these counts before any export, with the live collections that would be frozen and the “search” decks whose source would lose a part; it writes nothing. POST /v1/exports.planIds returns a page of the identifiers behind one of these counts: export carries the body of exports.sqlite, family the family, offset and limit the page (1000 identifiers at most).
"omitProvenance": true (--provenance=false on the command line, for export and transfer alike) removes what names the original match: analyses leave without players or played moves and cube decisions, no match, tournament, transcription or alias leaves, and naming a match or a tournament is refused (invalid).
Without provenance, a saved query never leaves as written: it leaves rewritten by the query parser — only the tokens it read travel, in their canonical form (c becomes cube) — or it does not leave. The living collection then leaves frozen on the positions it selects at the source, the saved filter stays behind, and the search deck keeps its positions without its query.
A query that reads what stays at the source does not leave: the match (pl, op, tn, au, ma, rd:, ml, md, pr, n, i), a free text (t"…"), the move played and its time (E, tm, mg, dr, dd: without the moves played, the query would select other positions on arrival) or, when comments do not leave, a comment (co, xco, co:, #tag). Neither does one that carries an unknown or ignored token (a second m"…"), or a value outside the expected form: a word in place of a number, an engine after ad:.
A ranking against a stored position (like<n>) does not leave either: it names a row of this database, which designates nothing at the destination; like alone, on a drawn board, reads only that board and leaves. With the comments, a #tag leaves only when a comment that is sent bears it, and an id list holds numbers only. The source of a search deck keeps, in every export, only ids, command, position (the drawn board, without the identifier of the position it comes from), library and, with the provenance, payload.
The file carries neither the producer’s user nor its description. Comments are free text: they leave only when asked for by name ("includeComments": true, --comments). The name and description of a collection, like the name of a filter or a deck, are also free text and leave as they are: do not write there what the transfer must keep quiet. export --type matches and --type mat refuse --provenance=false: a match is the provenance.
Importing a folder or a corpus is done with imports.batch, which goes through the same pipeline as blunderdb import --type batch: same matches, same canonical_hash fingerprints, a duplicate is written only once. The call returns {"importId": …, "files": N} at once and the import carries on in the background for as long as it takes. The batch comes in one of two forms:
an archive,
.zipor.tar, sent as multipart (filefield); only the importable files are extracted from it; the archive is bounded byImportMaxBodyBytes(512 MiB by default), its unpacked content at twice that;a path local to the daemon,
{"path": "corpus", "recursive": true}, read in the directory the operator opened with--import-dir. Without that option every path is refused (codeinvalid); with it, a path that leaves the directory, symbolic links included, is refused too. The daemon authenticates nobody: naming a directory lets any caller read match files from it. This is the way for large corpora, which are not pushed over HTTP.
A match already in the database is not rewritten, but its analyses deeper than the stored ones replace them; ?skip_duplicates=true, accepted by imports.batch as well as by a file import, ignores it without taking anything from it except the marks, like --skip-duplicates on the command line.
Idempotency-Key is accepted: replaying the call with the same key returns the same importId (header Idempotency-Replayed: true) without restarting the import. For a batch received as an archive, the key names the batch, not the archive’s content.
Two limits come from PostgreSQL. A batch archive is counted at the logical size of its entries (holes of sparse archives included): a sum that overflows, or bytes written beyond what the batch reserved, makes it refused (400) and erases what had been written. The database role must own the tables, or hold MAINTAIN (PostgreSQL 17): otherwise the statistics of a tenant’s first import are not computed, which the server logs once per process (import statistics skipped) and which the import measures as slower plans until autovacuum has run. Finally, an imports.db that analyses more already-present positions without analysis than the lock table holds (max_locks_per_transaction × max_connections, about 6,400 at the default settings) fails as a whole with an error that says so (out of shared memory, SQLSTATE 53200): raise max_locks_per_transaction or import smaller files.
Each refused file carries a stable code in addition to its text, in the status as in the report (the import of a single file returns it as import_code in its error event): unknown_format, truncated, corrupt, too_large, empty or internal. A duplicate is not an error: the report counts it separately. The import of a single file accepts ?report=deferred: its last event then omits the report, which imports.report returns on demand.
imports.batch.status ({"importId": …}) returns the state (receiving, running, done, cancelled or failed) and the progress measured by the pipeline: files processed, matches imported, duplicates, files in error, positions, bytes read, rate, estimated time remaining. The first hundred errors are listed with their file, the total is exact. A finished batch stays readable for an hour. imports.batch.cancel stops it: the groups of files already committed stay in the database, the group in progress is rolled back. imports.report returns, from the status’s batchId, the end-of-import report. imports.files ({"batchId": …}) returns the batch log: for each file, its path, size, date, SHA-256 fingerprint and the result (new, duplicate, enriched or error) with the resulting match or the message. To continue an interrupted batch, imports.batch accepts "resume": <batchId> (resume field of a multipart upload): files already logged with the same path, size and date are skipped without being read; those with the same content are read but not analysed.
curl -X POST http://127.0.0.1:8080/v1/imports.batch \
-H 'X-Tenant-ID: 7' -F file=@corpus.zip
curl -X POST http://127.0.0.1:8080/v1/imports.batch.status \
-H 'X-Tenant-ID: 7' -H 'Content-Type: application/json' \
-d '{"importId":"3f9c…"}'
Copying a collection from one tenant to another goes through the client (reading it in place, without a copy, is the job of across.collectionsList, Reading several tenants): the giving tenant calls exports.sqlite with "wholeLibrary": false and collectionIDs, includeCollectionPositions to take their positions along, without lessons, filters or Anki history (and a watermark, so that the receiver knows where the file comes from); the receiving tenant sends the file to imports.db. Each request carries its own X-Tenant-ID; the proxy decides who is allowed to do either. On import, a collection joins the receiver’s collection of the same name, or is created; its positions are appended to it, without duplicates. A living collection of the receiver gets no position: its query makes its content. An Anki deck is shared the same way, with deckIDs: the receiver studies it from scratch, its cards all new; a deck whose name the receiver already holds is left as it is, cards and schedule included, so importing the same file twice changes nothing. Importing a database in the desktop application follows the same rules.
imports.db also reads back matches with their games and moves (a match the recipient already holds, same fingerprint, is not copied again), tournaments (by name), transcription drafts and aliases, with the dates they bore in the source. A living collection’s query is renumbered onto the recipient’s rows, or frozen when a row it names is missing; arriving on a manual list of the same name, it leaves that list as it is and is reported. The response counts each family: matches, skippedDuplicates, tournaments, transcriptions, aliases, livingCollectionsFrozen, livingCollectionsOnManual, and unreadable when the received database is too old to carry a family.
The first progress event of imports.db arrives before any write and carries total_positions, the number of positions the import will process; each following event repeats it, enough to show n / N and a remaining time. The max_positions parameter (/v1/imports.db?max_positions=5000) brings in at most that number of positions, taken among the first of the file in the order of their original identifier. A match, a collection, a lesson or an Anki deck that touches a position left out is left out entirely, as is a position that nothing would hold after the import; a later import without a cap therefore brings in complete what was missing. The done event counts what was left out: positions_left_out, matches_left_out, collections_left_out, lessons_left_out, decks_left_out. Cancelled (imports.cancel) or on error, the import writes no row: the whole merge fits in one transaction. imports.dbAnalyze receives the same file and returns, without importing anything, what it would bring: positions and positionsHeld (those the tenant already holds), matches and matchesKnown, collections, lessons, decks, sourceVersion and unreadable; an unreadable file, or one the import would refuse, is refused there (400), like import --type database --analyze on the command line.
curl -X POST http://127.0.0.1:8080/v1/exports.sqlite \
-H 'X-Tenant-ID: 7' -H 'Content-Type: application/json' \
-d '{"wholeLibrary":false,"collectionIDs":[4],"includeCollectionPositions":true,
"includeLessons":false,"includeFilterLibrary":false,"includeAnkiHistory":false,
"watermark":"Club de Lyon"}' -o ouvertures.db
curl -X POST http://127.0.0.1:8080/v1/imports.dbAnalyze \
-H 'X-Tenant-ID: 2' -F file=@ouvertures.db
curl -X POST http://127.0.0.1:8080/v1/imports.db \
-H 'X-Tenant-ID: 2' -F file=@ouvertures.db
The training family keeps the log of the Training tab: training.save adds a session (exercise, seedSource, counts, items) and returns its id (Idempotency-Key accepted); training.sessions reads the sessions back, most recent first (exercise and limit optional); training.numberStats aggregates an exercise’s items by number type; training.missed returns the missed positions, each once, most recently missed first (exercise, sessionId and limit optional). A Decision item carries its position (positionId), the answer given (answer) and its cost in millipoints (errorMp, absent when timed out). The questions themselves are drawn by the client.
training.generateBearoff and training.generateEvaluation draw questions of the Bearoff and Evaluation exercises, with their truth, for a client that has someone work in front of their own board: nothing is kept, the clock and the marking stay with the client. The body is source ("pool", the canonical shapes; "board", the neighbourhood of position, which is the seed; "library", the tenant’s positions listed in positionIds, taken as they stand, one question each), count (1 by default, at most 50 for Bearoff and 10 for Evaluation, ignored for "library" which returns one per identifier) and seed (seed + count - 1 at most 2^52). Question i is drawn from seed + i: the same request and the same seed return the same questions, and question i alone is replayed with count 1 and the seed it carries; seed at 0 draws one, returned in each question. The answer is {"questions": [...]}, each question carrying seed, positionId (source "library"), generated, refusal (a seed outside the domain is a named refusal in the answer, not an error: notBearoff, tooFewCheckers, emptyBoard, noTable, notAGame, notMoneyCubeDecision, notEvaluable), source, plies, position and the truth: epc for Bearoff; winChance (in percent), cubeVerdict, cubeAnswer (nd, dt or dp), regime, depth and epc for Evaluation. The "library" source reads the tenant (an unknown identifier answers 404); "pool" reads nothing. Bearoff is a table walk of a few microseconds, run on the request. Each Evaluation question, whose truth is computed at 2 plies, is a unit of the shared analysis workers: it waits for its tenant turn and is counted in the analysis quota (which, once exhausted, refuses the call with 429, or cuts short an answer in progress, which then returns fewer questions than count).
The openingbook family serves the Opening exercise of the Training panel: an opening roll, or a reply, to play at a given score, judged against the book embedded in the binary and computed by blunderDB. The book belongs to no tenant: all draw from the same one and are judged against it, with nothing read from or written to the database. openingbook.status (body {}) returns the number of lines in the book (lines) and the scores it holds (scores, in grid order, "money" for money play). openingbook.question draws a question; roll ("first", the opening move, by default, or "second", the reply after an opening move tied with the best at that score), scores, openings ("31"), replies ("52", for "second") and seed are optional, an empty list allowing everything and a seed of 0 drawing from the clock. It returns roll, opening, score, position (the board to play), xgid and candidates (the number of plays the book ranks), plus openingPlay and reply for a reply. On an empty book, or a restriction that leaves nothing, the response is a success carrying {"empty": true}, not an error. openingbook.grade judges an answer: opening, score and, for a reply, openingPlay and reply from the question, plus the play made (board, the board left, or notation, board winning when both are given); an empty openingPlay judges the opening play. With neither board nor notation (out of time), the verdict is reduced to the correction. It carries legal, notation, played (the index in ranked, -1 when the book does not rank that play), right (the play is tied with the best), ranked (each candidate against the best), signature and games (the rollout’s settings and number of games). A line the book does not hold answers 400. The client logs the session through training.save like the other exercises, with exercise equal to opening.
gammonnet.evaluate evaluates a bare position (position or xgid), without reading or writing anything in the tenant: with dice, the best moves (candidates, 5 by default, at most 20); without dice, the cube decision. ply ranges from 0 to 2 (2 by default); a deeper search is the job of analyzeMissing.
The anki family gains six methods that extend the spaced-repetition scheduler (FSRS): anki.reviewLog (a log of every review — rating and FSRS outcome — powering retention statistics and a faithful history), anki.forecast (a projection of the number of cards due over the coming days, including overdue cards), anki.suspendCard / anki.buryCard / anki.removeCard (remove a card from the review queue temporarily or permanently) and anki.retention (the pass rate measured over a deck’s reviews, read against the target its owner set).
anki.undoReview (cardId) reverts a card’s last review: the card gets back exactly its state from before that rating (due date, interval, stability, difficulty, counters), the rating leaves the log, and the response is the restored card, with its position. Called again, it goes back one more rating. With no review to undo — card never rated, all its ratings already undone, or a rating recorded before schema 2.42.0 —, it refuses with a 409 whose message contains “the card has no review to undo”; a card from another tenant is a 404. Like anki.reviewCard, it accepts an Idempotency-Key: replayed, it does not undo one rating too many.
Note
anki.retention replaces anki.optimizeParams, which nudged the target toward the observed rate and could write it. The retention target is a choice about the load/quality trade-off, the measured rate is its outcome, and coupling one to the other is exactly the mechanism FSRS’s authors reject. The method only measures, and never writes.
The stats family provides stats.playerTable, which returns one row of statistics per player (matches, wins/losses, counted decisions, overall / checker / cube PR, Snowie Error Rate, errors, blunders and luck) over the matches the given filter retains. As in the graphical interface, this table honours only the filter’s date range, tournaments and match lengths: the player selection and the decision type are ignored, since the table covers every player and already splits checker and cube into separate columns. The luck_known field says whether luck was measured for that player; luck_rate_mp must not be read when it is false, unknown luck not being zero luck.
stats.report returns in the html field the standalone HTML report for the filter passed (filter), the one from the graphical interface and blunderdb stats report; language chooses its language (English by default).
The filter passed to the stats methods accepts, alongside PlayerName, a PlayerAliases field: the other spellings the same person signed under. Since a player’s name is typed by hand into every file, one person routinely appears under several spellings, and a filter that keeps only one computes on part of the matches without anything looking wrong. The field is purely additive: the decisions of any of the names are kept. Merging the names in place (MergePlayers) is the other answer, to be reserved for databases you did not receive from someone else — it rewrites everybody’s matches.
Two methods complete parity with the graphical interface: stats.tournamentBadges returns, for each tournament in the database, the indicator shown on its thumbnail (PR of the reference player), and matches.findByHash indicates whether a given match is already present, from the two duplicate-detection fingerprints — enough to avoid a redundant import before committing to it. matches.duplicates lists the pairs of matches that the dice say are identical — same dice under other names, or a truncated then completed version — like repair --duplicates, without merging anything; a pair with the same dice carries its pairings, the aliases to pass to players.alias.set for each reading of who is who.
Other spellings of a player or an event are managed by players.alias.list, players.alias.set ({"alias": …, "canonical": …}), players.alias.remove ({"alias": …}, returns removed) and players.alias.suggest (the names that differ only by case, accents, punctuation or word order, recording nothing); the same under events.alias.* for events. matches.mergePlayers creates these aliases rather than rewriting the matches. An import records the canonical name (the fingerprints keep the names of the file), and stats.compute, stats.playerTable, stats.playerNames and the player search read all the spellings as a single person. players.main.get returns the main player, players.main.plan ({"name": …}) the matches that designating it would swap (swap) and those it would leave (refused), players.main.set designates it and swaps them in one transaction, players.main.clear removes it without swapping anything; a later import places it as player 1. players.matchIds returns the matches of a player under all of their spellings.
The winner field of a game, received by matches.createGame and returned by matches.games, has a single encoding: 1 for player 1, -1 for player 2, 0 for an unfinished game. A client that still sends 0, 1 or -1 in gnubg’s sense (0 for player 1, 1 for player 2) records the opposite winner.
analyses.repair recomputes an analysis’s denormalised columns (cube_error among them) from its full analysis, and returns how many rows were actually corrected. Those columns are only a projection: a faulty projection therefore repairs without re-importing the source files. The operation is explicit and never triggered on its own — neither when a database is opened nor by a migration, the schema not being at fault. An unreadable analysis is left as it is rather than reset to zero. The known case: the non-doubles labelled “Double No” by gnuBG, misread before version 0.33.0, which carried the error of a double that never took place.
The met family manages the tenant’s match equity tables: met.list lists them; met.import saves one from a gnuBG XML file, either as text (source, already decoded: a file declared ISO-8859-1 is re-read byte by byte) or as raw bytes (source_base64, to be preferred for any file that is not UTF-8); name is used when the file names none. A table whose values are already held is returned as held, with already_held true. Only UTF-8, US-ASCII and ISO-8859-1 are read; any other encoding is refused with a message that names it; met.setCurrent ({"id": N}) makes it the current table, 0 returning the built-in Kazaross-XG2 table; met.ofAnalysis ({"position_id": N}) returns the table with which the position’s analysis was valued, the current table and different, true when a match analysis was valued with a table other than the current one — it is then left out of comparisons.
The trash has its trash family. trash.deletePosition, trash.deleteCollection, trash.deleteComment and trash.deleteMatch delete while keeping what is needed to restore, and return the id of the trash entry; positions.delete, matches.delete and the other deletions remain permanent. trash.list (kind, limit, offset) and trash.count read it, trash.restore ({"id": N}) puts an entry back and returns the id of what comes back, with warnings: what a successful restore could not put back, each with a stable code (direction_slot_taken, direction_slot_gone, tournament_gone) and a message in English. trash.discard erases one, and trash.empty erases the entries older than olderThanDays days (0 empties everything) and returns their number (purged).
The changeset family synchronises two libraries through their journal. changeset.export (cursor, limit) returns a page: records, the cursor to give back as is, and more as long as the exchange is not finished; a page never separates an object from what it refers to. An empty cursor starts over. A 410 response says that this journal cannot continue from that cursor (a backup restored elsewhere, a cursor taken before a family was added to the journal): start again from an empty cursor, the import absorbs the repetition. changeset.import (records) merges, the latest write winning, and returns the report: added, modified, removed, older, conflicts, and missing for a reference that could not be placed. A note overwritten by the import stays in the trash. The journal carries positions (with their analysis), matches, collections, notes, lessons, transcriptions, tournaments and Anki decks with their cards and schedule. A tournament travels with its header, its note and its dates; a match’s attachment to a tournament and its place in the list stay specific to each library. The families without a trash (lessons, transcriptions, tournaments, decks, cards) are deleted when a peer trashes them. On a tie in date, each family merges the two contents the same way on both sides and erases nothing the other keeps: the note or description that one side lacks is taken over, two notes are kept together, the furthest review wins. skipped, in the exported page, counts the journal objects whose content could not be read; a collection whose query designates rows by number (id12, ma3) does not carry it.
Synchronization server. The Synchronization tab of the settings (see Synchronization) keeps the open library in the same state as a remote server, whichever it is, provided it answers the same two calls as blunderdb serve, under the address the user pastes (its <base> may carry a prefix, for example https://host/api):
POST <base>/v1/changeset.exportwith{"cursor": {…}, "limit": N}returns200and{"cursor": {…}, "more": bool, "records": […]}. The cursor is opaque,{}starts over from the beginning;limitdoes not exceed 1000 (the application asks for 500). A record is{"seq", "uuid", "family", "op", "changed_at", "payload"?}. The server must be able to resume from a cursor it issued, and answer410when it can no longer resume one. A server that does not want to carry a record that is too large returns an empty page whose cursor goes past it and which names it:"skipped": [{"family", "uuid", "size"}]. Without this, a single-record page is served whatever its size.POST <base>/v1/changeset.importwith{"records": […]}(at most 500 records, those of achangeset.export) merges, the last write winning, and returns200and the report (applied,added,modified,removed,older,conflicts,missing,unsupported). A repeated record changes nothing.Every request carries
Authorization: Bearer <token>andContent-Type: application/json. The token never appears in the address.401or403: token refused;413with the codepayload_too_largeorrecord_too_large: upload too large for the server (any other413, from a proxy for example, stops the run without skipping anything);400with codeinvalid_body: body cut off or too slow;429: rate limit reached;410on export: stale cursor; any other failure carries the{"error": {"code", "message"}}envelope of the calls above.
The application sends first, then receives, one page at a time. It keeps two cursors per server and per library: the local journal’s (what the server already has) and the server’s (what is already merged here), each advanced once its page is settled. A cursor refused by a journal (410, or stale locally) starts over from the beginning, the import absorbing the repetition. Records received come back on the next upload, which the server absorbs the same way.
On 413 payload_too_large or a cut during upload, the application halves the page down to a single record. A single record that the server refuses for its size (explicit code), or that does not go through, is set aside: it is kept with its type and identifier in the synchronization state, retried on every run and listed in the synchronization screen. The same goes for a record that the server declares skipped on export. The server must therefore read a slowly sent body: the read timeout renews as long as the upload progresses.
Three marks can be added to a position: changeset.export carries all three, export and transfer the drawing and the origin link, but not the label. positions.drawing and positions.setDrawing ({"id": N, "marks": […]}) read and replace its drawing: arrows and squares, 40 at most; an empty list erases it. positions.setDerivedFrom ({"id": N, "derivedFrom": {"fromId": <origine>, "move": "13/7"}}, null to erase) declares it a variant of another position; positions.derivedFrom reads that link and positions.variants lists its variants. A loop or a missing origin is refused. positions.publicId and positions.setPublicId read and set a label that blunderDB keeps without ever interpreting it.
gammonnet.analyzeMissing triggers the gammonNet catch-up of the current tenant: write an analysis for every position that has none (ADR-0013, ADR-0015). It is a library operation — it reads and writes stored positions and analyses — never a bare evaluator: blunderdb serve operates on a library, gammonnet serve evaluates a position. The response is an NDJSON stream (started, progress, then done or error/cancelled), on the same model as the import endpoints; gammonnet.analyzeMissing.cancel (with the job_id received in the started event) cancels a running catch-up and serves either sweep indifferently — a catch-up or a re-analysis (below). It is the same operation as the automatic run after an import and the explicit gesture of the graphical interface, and as the blunderdb analyze subcommand (see Command Line Interface (CLI)) — three forms, one logic.
gammonnet.sweepStale is analyzeMissing’s counterpart for re-analysis rather than gap-filling: every position whose analysis is entirely gammonNet’s own but stale — an engine version older than the one currently running, or a depth different from ply — is re-evaluated at the requested depth. The staleness predicate is shared with the same batch in the graphical interface and in blunderdb analyze --stale (no duplicated logic across the three modes); a position carrying an XG, GNUbg or BGBlitz analysis is never touched, whatever its gammonNet content — ADR-0013’s protection remains unconditional. Same NDJSON shape as analyzeMissing, and the final event of each of the two routes carries the evaluated/refused/failed breakdown: a position gammonNet declines to evaluate (a match score beyond its table’s range, a cube decision the model refuses) counts as refused, not failed — it is never retried in vain on the next pass, unlike a position that genuinely failed.
rollout.position plays a library position (positionId) by a rollout and returns, for each candidate, the equity, its 95% interval and the JSD; rollout carries the settings (fast, standard or standard,ply=1…), store records the finished rollout as a second analysis, beside the one the position carries, which it never replaces. A bare position (an XGID) is refused: the daemon operates on a library. rollout.filter is the batch form of blunderdb analyze --rollout: the positions chosen by query (the search language) that do not yet carry a rollout with the same settings are played one after the other and recorded as they go, as an NDJSON stream (started, progress after each series of games, then done, cancelled or quota_exceeded); rollout.filter.cancel cancels it with its job_id. A tenant runs only one batch at a time, rollout or gammonNet. rollout.list reads the recorded rollouts of a position.
Correlation and business metrics
Every request gets a correlation identifier: the one the client (or a reverse proxy) sends in the X-Request-Id header, otherwise a generated one — either way returned on the same header of the response and added to the request’s closing log line (field request_id). A traceparent (W3C Trace Context), when present, is relayed as-is into that same log line — the daemon neither parses nor validates it, and embeds no tracing library: it is a bridge for correlating these logs with a tracing pipeline running upstream, nothing more.
Beyond request volume and latency, /metrics publishes gauges on the work in flight, otherwise invisible for a stuck import or gammonNet batch (one very long request, not many requests):
blunderdb_imports_inflight— imports under way, across all tenants;blunderdb_import_spool_bytes— bytes currently reserved against the import spool quota (see--rate-limit-*above for the requests-per-second counterpart);blunderdb_gammonnet_sweep_inflight— gammonNet catch-up sweeps under way, across all tenants;blunderdb_database_size_bytes— size of the main SQLite file, orpg_database_sizeunder PostgreSQL (the whole database, not per tenant, like the connection-pool gauges below); absent until a first measurement has been published.
A memory or CPU profile of the process is available by starting with --pprof-addr <host:port> (net/http/pprof): off by default, and deliberately on an address separate from --addr, since these endpoints have no notion of tenant.
Stream compression
NDJSON listings repeat the same field names on every line. The daemon compresses them when the client accepts it: send Accept-Encoding: gzip and the response comes back as Content-Encoding: gzip. Measured on a match listing: 13.5% of the original size over a thousand lines, 14.6% over a hundred.
Compression changes nothing about the stream being incremental — each record is pushed to the client as before, only compressed on the way. It applies to NDJSON, JSON and text responses only: a database export or a .dbx container is already compressed, and re-gzipping it would only make it bigger. Accept-Encoding: gzip;q=0 refuses it explicitly.
A single tenant on SQLite
The SQLite backend has no tenant column: all the data sits in the same tables, with no partition. On that backend the daemon therefore refuses any X-Tenant-ID other than 1 — accepting the others would mean serving everyone everybody’s rows behind a header claiming otherwise. A deployment that genuinely has several tenants needs the PostgreSQL backend.
Reading several tenants
A coach who reads their students’ matches, a club that shares a library: the relationship between these accounts lives with the host that authenticates them, never in the daemon. The proxy expresses it with the X-Read-Tenants header, a comma-separated list of tenants (X-Read-Tenants: 2, 3), which it sets next to X-Tenant-ID. The daemon trusts it as it trusts X-Tenant-ID and authorizes nothing itself (ADR-0063).
The feature is disabled by default, and disabled means refused: until the daemon is started with --read-tenants (or BLUNDERDB_READ_TENANTS=true; Config.TrustReadTenants for a host that embeds the engine), any request carrying a non-empty X-Read-Tenants is refused (400), whatever the route. Enable it only once the proxy is configured to strip any client-sent value and to set the list itself.
Only the /v1/across.* reads look at this header. The full list: across.searchFind, across.matchesList, across.statsCompute and across.playerTable; they read X-Tenant-ID first, then each tenant listed in header order, at most 64 distinct tenants in all. On a tenant from the list, named with the id: across.matchesGet, across.matchMovePositions (the positions of a match, move by move, in pages of limit / offset) and across.analysesLoadByIds; a tenant absent from the list is refused there. Each result carries its tenant of origin ("tenant": "2"), because an id is unique only within its tenant; a position also carries its Zobrist hash ("zobrist"), which designates the same board in every tenant. limit applies to each tenant; 0 means 1000, and a larger value is refused. In an NDJSON stream, an error on a late tenant arrives as the last line, after the results of the tenants already read: the whole stream then fails.
curl -s http://127.0.0.1:8080/v1/across.matchesList \
-H 'Content-Type: application/json' \
-H 'X-Tenant-ID: 1' -H 'X-Read-Tenants: 2, 3' -d '{"limit":20}'
Every write stays in X-Tenant-ID: no route outside across.* reads X-Read-Tenants, and the only one in this family that writes, across.transferPull (Pulling a copy from a read tenant), writes into X-Tenant-ID. Without the header, an across.* read covers only X-Tenant-ID. A malformed header (a name, an empty element, more than 64 tenants) or one sent on several lines refuses the whole request, whatever the route. On SQLite, which has a single tenant, the list can only contain 1: the header widens nothing there. These routes are specific to the server: the desktop app and call have a single tenant.
An across.* request costs up to 64 storage reads, but the rate limit (--rate-limit-rps) counts it only once, for X-Tenant-ID: size the database and this limit accordingly, or have the proxy bound the list. The access log of an across.* route carries the list received (read_tenants field). The header is not among the allowed CORS headers: only the proxy writes it, never a browser.
Five reads serve the club and the coach, on the same list (ADR-0065):
coach comments: the coach stores a student’s position in their own tenant (
positions.saveunder their ownX-Tenant-ID, same hash) and comments on it (comments.add); nothing is written to the student’s tenant.across.commentsByZobrist({"zobrists": [...]}, at most 1000 hashes) returns the comments that each tenant read has written on these boards, each with its tenant, the position id in that tenant and its origin;elsewhere:
across.positionElsewhere({"zobrist": H}or{"position": {...}},neighbours,maxDistance) returns, for each tenant read other thanX-Tenant-ID, what it knows about this board: the id of its copy, its analysis, its comments, the matches where it was played and its neighbouring boards. Moves are judged with the thresholds ofX-Tenant-ID; an analysis made with another equity table is flagged (otherMet).blunderdb elsewhereperforms the same lookup on files;across.objectElsewhere({"kind": "match", "id": N}, ortournament,collection,lesson) says whether each of these tenants holds that object ofX-Tenant-ID, under the key a copy would merge it on (the match fingerprint, the name otherwise), with its id and what it contains;shared library:
across.collectionsListlists the collections of the tenants read,across.collectionPositions(tenant,collectionId) the positions of one of them, each with its hash. The library is read in place, never copied: sharing a collection by file (export then import), by contrast, gives the recipient a copy;club ranking:
across.clubRankingmerges the player tables of the tenants read into a single ranking, best PR first, on the given statistics filter (filter.DateFromandfilter.DateTofor a period). Each row carries its tenant; a name is never merged from one tenant to another.players(tenant,namepairs) keeps only those players,minDecisionsdrops those with fewer counted decisions; at equal PR the rank is shared, and a row with no counted decision has rank 0.filter.TournamentIDsis refused there (400): a tournament id is valid only within its own tenant. The response is a page (limit, 100 by default, 1000 at most;offset) withtotal, the number of rows of the whole ranking. This is not the season ranking of directed tournaments.
Pulling a copy from a read tenant
across.transferPull copies part of a tenant from the X-Read-Tenants list into X-Tenant-ID: it is the command-line transfer command (transfer — Copy from one library to another), between two tenants. The body names the source tenant (tenant, which must appear in the list) and, under export, the selection, with the keys of the exports.sqlite body (includeMatches, collectionIDs…); without export, the whole tenant is copied. The copy is merged like the import of a .db database: a position already present is recognised by its hash, and a match, collection or lesson already present is not duplicated, so pulling from 2 into 1 and then from 1 into 2 creates no duplicate. The response counts what was read (exported) and what the tenant took from it (imported). The positions follow the rules of transfer: as soon as a list of IDs is given, only those reached by the retained families are sent; a collection goes with its members; a named match carries the record of its tournament, not its other matches. An ID that the source tenant does not contain is refused (400). To copy collection 3 and its positions, nothing else is needed:
curl -s http://127.0.0.1:8080/v1/across.transferPull \
-H 'Content-Type: application/json' \
-H 'X-Tenant-ID: 1' -H 'X-Read-Tenants: 2' \
-d '{"tenant":"2","export":{"collectionIDs":[3],"includeMatches":false,"includeTournaments":false,"includeLessons":false,"includeAnkiDecks":false}}'
The transfer is always pulled by the receiving tenant, never pushed into another: reads go across tenants and writes only go to one’s own (ADR-0102). Nothing is written that says where the copy comes from, in either tenant: watermark, password, incremental and metadata are rejected (400), as is a tenant absent from the list or the tenant itself. A transfer counts as an import of the receiving tenant (--quota-imports, --quota-positions, --quota-bytes) and is interrupted when the daemon stops.
Backup and restore
Four gestures, depending on what is to be recovered.
Everything, under PostgreSQL — pg_dump is the tool, and blunderDB has nothing to add:
pg_dump --format=custom --file=blunderdb.dump "postgres://…"
pg_restore --dbname="postgres://…" blunderdb.dump
Everything, under SQLite in a container — the file is opened in WAL mode (the daemon encodes journal_mode(WAL) in its connection string, for every connection in the pool): alongside blunderdb.db live a -wal and a -shm, and the most recent writes are in the -wal. Copying the .db alone from a running daemon therefore gives an incomplete file, with nothing to signal it. Two safe ways:
stop the daemon, then copy the whole volume — once stopped, the three files are consistent, and it is the volume, not the
.dbalone, that is the unit to back up;do not copy the file at all:
/v1/exports.sqlite(below) writes a complete.dbwhile the daemon is running, and it is the only gesture that requires no interruption.
/ops/maintenance.vacuum does fold the WAL back into the main file before rewriting it, but it does not freeze the database: the next write starts a new WAL. It is a compaction command, not a backup method.
One tenant alone — /v1/exports.sqlite writes a tenant’s database into an ordinary .db file, the one the desktop application opens:
curl -X POST http://127.0.0.1:8080/v1/exports.sqlite \
-H "X-Tenant-ID: 42" -o tenant-42.db
This command runs on the daemon’s own machine: it targets the local listener, bypasses the proxy, and therefore sets the tenant header itself. From outside, it is the proxy that is queried, and the tenant is that of the authenticated account — the header is not to be supplied, the proxy strips the client’s before injecting its own:
curl -u alice:… -X POST \
https://blunderdb.example.com/v1/exports.sqlite -o tenant-alice.db
Putting that file back — migrate copies it under the tenant you name:
./blunderdb migrate --from tenant-42.db --to "postgres://…" --tenant-id 42
migrate refuses to write into a tenant that already holds something, and says what (“128 positions, 3 matches”); --on-conflict skip goes ahead anyway and lets Zobrist de-duplication merge the positions.
migrate also copies lessons, with their steps in order; a step points to the collections and positions that were moved.
What migrate does not copy, and announces at the end with the exact count: the Anki decks and their cards, the filter library, the search and command histories, and the session state. These are the desktop application’s usage data; the positions they refer to have indeed been moved.
The error and blunder thresholds, for their part, are copied: they are not usage data but the reading habit the counts depend on, and a tenant that counted differently from the file it came from would make the migration a silent change of meaning.
A tenant sets its own through POST /v1/librarySettings.load and /v1/librarySettings.save. Unlike metadata, which is global infrastructure exposed read-only, the settings table carries a tenant_id and lives under Row-Level Security: a tenant writing its thresholds reaches nothing but its own rows.
The desktop and the server
The desktop application opens .db files, not URLs: it never connects to any serve daemon, and there is nowhere a field to type an address. The server and the desktop exchange files, in two symmetric gestures:
from the server to the desktop —
POST /v1/exports.sqlitewrites the whole current tenant into a.dbthe desktop application opens as-is (see Backup and restore);from the desktop to the server —
blunderdb migratecopies a.dbunder the intended tenant (see Migrating a SQLite database to PostgreSQL).
Nothing a tenant stores is visible to another, except through the across.* reads, and only on the tenants the proxy lists in X-Read-Tenants under serve --read-tenants (Reading several tenants). Any other request knows only the tenant the proxy set for it. A coach who wants to see their students’ matches therefore has three paths, all explicit:
read their matches through
across.*, the proxy listing the students’ tenants;open an additional account for them in the proxy, associated with the student’s tenant: it is the proxy’s mapping table, never the daemon, that decides which tenant a session sees;
ask them for an export — the
.dbproduced byexports.sqliteor by the desktop application’s export window — and open it on their own desktop.
Deployment with Docker
The repository provides a Dockerfile.serve that builds a minimal container image of the daemon: only the serve binary is compiled (pure Go, with no graphical interface and no CGO, therefore statically linked), then placed into a distroless image.
# build
docker build -f Dockerfile.serve -t blunderdb-serve .
# run
docker run --rm -p 127.0.0.1:8080:8080 \
-e BLUNDERDB_DSN="postgres://user:pass@host:5432/blunderdb?sslmode=disable" \
blunderdb-serve
The build is run from the repository root, and the image’s default backend is postgres.
The image listens on port 8080 and is configured through environment variables (BLUNDERDB_BACKEND, BLUNDERDB_DSN, BLUNDERDB_ADDR, BLUNDERDB_RLS). It declares a HEALTHCHECK that runs blunderdb healthcheck every 30 seconds (a request on /readyz — the distroless image has neither curl nor a shell): docker ps shows the container as healthy or unhealthy, and Compose or an orchestrator can wait for the daemon to be ready before starting what depends on it.
Published image
There is no need to build the image yourself: every published blunderDB release pushes its own to the GitHub registry (GHCR), under the name ghcr.io/kevung/blunderdb-serve. Two tags are available: the version number, frozen forever on that image, and latest, which follows the most recently published version. All the documentation writes them as ghcr.io/kevung/blunderdb-serve:<version>: it is a published version number that takes the place of <version>, and it is that form, never latest, that a production deployment pins. The image is provided for linux/amd64 and linux/arm64; Docker picks the host architecture.
# pull
docker pull ghcr.io/kevung/blunderdb-serve:<version>
# postgres
docker run --rm -p 127.0.0.1:8080:8080 \
-e BLUNDERDB_DSN="postgres://user:pass@host:5432/blunderdb?sslmode=disable" \
ghcr.io/kevung/blunderdb-serve:<version>
# sqlite
docker run --rm -p 127.0.0.1:8080:8080 \
-v blunderdb-data:/data \
-e BLUNDERDB_BACKEND=sqlite -e BLUNDERDB_DSN=/data/blunderdb.db \
ghcr.io/kevung/blunderdb-serve:<version>
/data is the mount point the image prepares, with its unprivileged user’s permissions, and its XDG_DATA_HOME: the volume mounted there is not only for the database — the bearoff tables are computed there once, in /data/blunderdb, and found again on later startups. Without a volume, they are recomputed on every container start — a few seconds — and the daemon says so at startup if it cannot write them (could not prepare the bearoff tables; the exact regime will be unavailable), in which case it serves normally, with only the estimated regime on bearoff positions.
The image carries the usual OCI labels (org.opencontainers.image.source, .version, .revision, .licenses): docker inspect tells which commit and which version it comes from. It is built by continuous integration from the repo’s Dockerfile.serve, exactly as above; building locally or pulling the published image gives the same binary.
Warning
Like the daemon itself, the container performs no authentication (ADR-0005): it trusts the X-Tenant-ID header exactly as it receives it. It must be placed behind a reverse proxy responsible for authentication, which sets that header itself, and must never be exposed directly to the public Internet. The examples above publish the port on 127.0.0.1 only for this reason, and --addr likewise binds to 127.0.0.1: the proxy is on the same machine.
Deployment behind an authenticating proxy
ADR-0005 makes the reverse proxy the whole of the daemon’s security boundary: it alone authenticates the caller, it alone is allowed to set the X-Tenant-ID header, and it must strip any value sent by the client before injecting the authenticated tenant — otherwise anyone can impersonate any tenant simply by naming it. The threat model fits in one sentence: the daemon assumes a trusted internal network, and whoever reaches it directly is, as far as it is concerned, the tenant it claims to be. The repository ships a complete, ready-to-run example in the deploy/ directory. It lives in the git repository, not in the container image: so clone the repository, or download the two files reproduced below together with deploy/.env.example into the same directory.
The Compose file puts Caddy — demonstration HTTP Basic authentication — in front of blunderdb-serve and PostgreSQL, with Row-Level Security enabled. Only Caddy publishes a port: the other two services live on a Docker network declared internal: true, which has no route to either the host or the Internet, whatever ports: a later change might add to them.
# Example deployment of `blunderdb serve` behind an authenticating reverse
# proxy — the security model ADR-0005 requires and, until now, that no example
# in this repository actually showed. See deploy/README.md for the threat
# model and doc/source/mode_headless.rst for the full walkthrough.
#
# Try it from the repository root:
# POSTGRES_PASSWORD=changeme docker compose -f deploy/docker-compose.yml up -d --build
# curl -u alice:demo-password http://localhost:8080/v1/metadata.counts -d '{}'
# docker compose -f deploy/docker-compose.yml down -v
services:
# Caddy is the ENTIRE security boundary (ADR-0005): it is the only service
# with a published port, it authenticates every request, and it is the
# only thing allowed to set X-Tenant-ID — see Caddyfile. Any reverse proxy
# capable of stripping and re-setting a header works equally well; Caddy is
# used here for its one-file config and built-in Basic Auth with no extra
# modules. deploy/nginx-tenant-proxy.conf shows the equivalent nginx
# snippet for an existing nginx deployment.
caddy:
image: caddy:2-alpine
restart: unless-stopped
ports:
- "8080:80" # the ONLY port this compose project exposes to the host
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy-data:/data
- caddy-config:/config
networks:
- edge # the published port lives here — "backend" is internal-only
- backend
depends_on:
blunderdb-serve:
condition: service_healthy
# No `ports:` here — on purpose (ADR-0005). The daemon performs no
# authentication of its own, so it must be reachable only from Caddy, over
# the "backend" network, and never published to the host.
blunderdb-serve:
build:
context: ..
dockerfile: Dockerfile.serve
restart: unless-stopped
environment:
BLUNDERDB_BACKEND: postgres
BLUNDERDB_DSN: "postgres://blunderdb:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD, see deploy/.env.example}@postgres:5432/blunderdb?sslmode=disable"
BLUNDERDB_ADDR: ":8080"
# Row-Level Security: defence-in-depth *inside* the trust boundary
# Caddy draws above — it does not replace the proxy (ADR-0005).
BLUNDERDB_RLS: "true"
volumes:
# The bearoff tables are computed on first start and kept under
# $XDG_DATA_HOME/blunderdb, which the image sets to /data: without a
# volume they are recomputed at every restart of the container.
- blunderdb-data:/data
networks:
- backend
depends_on:
postgres:
condition: service_healthy
postgres:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_DB: blunderdb
POSTGRES_USER: blunderdb
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD, see deploy/.env.example}
volumes:
- postgres-data:/var/lib/postgresql/data
networks:
- backend
healthcheck:
test: ["CMD-SHELL", "pg_isready -U blunderdb -d blunderdb"]
interval: 5s
timeout: 3s
retries: 10
volumes:
postgres-data:
# Bearoff tables computed by blunderdb-serve on first start (see
# XDG_DATA_HOME above): a few megabytes, worth keeping across restarts.
blunderdb-data:
caddy-data:
caddy-config:
networks:
# Caddy's own network, carrying the one published port. A container on
# "backend" alone (blunderdb-serve, postgres) is never reachable through it.
edge: {}
# internal: true means this network has no route to the outside world and
# accepts no published ports — blunderdb-serve and postgres can only ever
# be reached by another container attached to it (here, only Caddy),
# never from the host or the public internet, regardless of what `ports:`
# a future edit might add to either service.
backend:
internal: true
The Caddyfile authenticates, maps the authenticated account to the tenant’s integer (map), then injects it into X-Tenant-ID after explicitly clearing any value received from the client: the header_up X-Tenant-ID "" guard precedes the injection, so that a header sent by the client can never reach the daemon, whatever later changes are made to the file.
The same goes for X-Read-Tenants (Reading several tenants): the proxy removes the client’s one, and sets it only if it knows the relationship between the accounts; the repository’s examples know none and always remove it.
# Demonstration reverse-proxy for `blunderdb serve` (ADR-0005).
#
# This is the WHOLE security boundary of the daemon: it authenticates the
# caller (here, HTTP Basic Auth — swap for forward_auth to a real identity
# provider, or an OIDC plugin, in production) and is the only thing allowed
# to set X-Tenant-ID. blunderdb-serve trusts that header completely and
# performs no authentication of its own.
#
# Demo credentials — CHANGE THESE before using this anywhere but a laptop:
# alice / demo-password
# bob / demo-password
# Generate a real hash with:
# docker run --rm caddy:2-alpine caddy hash-password --plaintext '<password>'
{
# This demo terminates plain HTTP on a fixed port instead of Caddy's
# automatic HTTPS, which needs a real public domain name to obtain a
# certificate for. Point a domain at this host, replace ":80" below with
# that domain, and delete these two lines to get HTTPS for free.
auto_https off
admin off
}
:80 {
basic_auth {
alice $2a$14$7yGnM3/IY8G/.mcBHMbDveecDQbnJnvHPcJQZcbWqn.H.mpttw9/.
bob $2a$14$7yGnM3/IY8G/.mcBHMbDveecDQbnJnvHPcJQZcbWqn.H.mpttw9/.
}
# Map the authenticated login (Caddy sets {http.auth.user.id} once
# basic_auth succeeds) to the tenant's positive integer — the only
# spelling of X-Tenant-ID the daemon accepts (ADR-0005, amendment
# 2026-09-03). This is the identity-to-tenant mapping ADR-0005 says is
# the proxy's job: the daemon never sees "alice", only "1".
map {http.auth.user.id} {tenant_id} {
alice 1
bob 2
default 0
}
# Never reach the daemon's operator routes or its metrics through the
# public proxy: /ops/ (vacuum, tenant purge) acts beyond the calling
# tenant, /metrics needs no X-Tenant-ID and describes the whole daemon.
@private path /ops/* /metrics
respond @private 403
reverse_proxy blunderdb-serve:8080 {
# Guard, then inject: clear whatever the client sent BEFORE setting
# the authenticated value, so a client-supplied X-Tenant-ID can never
# reach the daemon no matter how this file is edited later — the
# second line is the only one that can still be in effect once both
# have run.
header_up X-Tenant-ID ""
header_up X-Tenant-ID {tenant_id}
# X-Read-Tenants widens a read to other tenants (ADR-0063): only a
# proxy that knows the relation (coach, club) may set it. This demo
# knows none, so it drops whatever the client sent.
header_up -X-Read-Tenants
}
}
Two more files round out the directory: deploy/nginx-tenant-proxy.conf carries the same scheme as an nginx snippet (proxy_set_header X-Tenant-ID "" then proxy_set_header X-Tenant-ID $tenant_id, with the map $remote_user $tenant_id block), for anyone who already has an nginx in place; deploy/README.md states the threat model and what must never be done.
The Caddyfile’s HTTP Basic authentication is a demonstration, not a production recommendation: replace it with forward_auth to a real identity provider (OIDC, enterprise SSO…), which authenticates and then hands off the identity at the same spot in the file. The two passwords and the two accounts in the mapping table are to be replaced the same way.
deploy/Caddyfile.oidc is the OpenID Connect recipe: Caddy queries oauth2-proxy (forward_auth on /oauth2/auth), which answers 202 with the signed-in account’s address in X-Auth-Request-Email, or redirects to the provider’s sign-in page. The map block maps that address to the tenant’s integer, and the same header_up X-Tenant-ID "" guard precedes the injection. The oauth2-proxy service to add to the Compose file is at the top of the file.
Per-tenant quotas
A shared instance bounds what each tenant takes from it with --quota-positions, --quota-bytes, --quota-analysis-seconds and --quota-imports (without an option, nothing is bounded). Computation time counts every engine computation requested by the tenant: gammonnet.analyzeMissing, gammonnet.sweepStale, gammonnet.compare, gammonnet.cubeMatrix, gammonnet.evaluate, rollout.position and rollout.filter. It is counted in CPU seconds: the elapsed time of each computation, plus that of the idle workers over which its search spread, so a computation spread over all cores costs as much as the same work done position by position. Once the day’s time is used up, these routes answer 429 with the quota_exceeded code. A sweep or a rollout.filter in progress keeps what it has recorded and ends on the quota_exceeded event instead of done; an interrupted rollout.position answers 429 and records nothing; an interrupted comparison returns what it has folded with quotaExceeded: true and, in gathered, the number of positions it had to examine. The count resets to zero at midnight UTC and lives in memory: restarting the daemon resets it. The positions quota is checked at the start of an import, which is not interrupted midway: a tenant can exceed it by as much as its imports in progress add. positions.save and the other single writes do not check it. The bytes quota is checked at the same moment and with the same latitude. Under SQLite, a database holds only one library: the tenant occupies the live pages of the file. Under PostgreSQL, tenants share the tables and no row carries its size: the space of each table (indexes included) is distributed in proportion to the rows, so a tenant holding a third of a table’s rows is counted a third of its space. This is an estimate, which follows the planner’s statistics. Each refusal carries in details the limit (quota, limit) and the usage (used). tenants.quota returns to the calling tenant its limits and its usage: stored positions, bytes occupied (storedBytes), computation seconds of the day, imports in progress.
Quotas are the daemon’s bookkeeping, not a boundary: they apply to the tenant that the proxy has set in X-Tenant-ID.
Every engine computation goes through a single analysis queue: sweeps (gammonnet.analyzeMissing, gammonnet.sweepStale), evaluations (gammonnet.evaluate), comparisons (gammonnet.compare), cube matrices (gammonnet.cubeMatrix) and rollouts (rollout.position, rollout.filter). It is a set of engine workers (--analysis-workers), each with its own reused searcher, which take positions one by one, going round the tenants that have work. Two tenants sweeping at the same time share the cores instead of each claiming them; an evaluation requested during another tenant’s sweep waits for one position, not for the whole sweep. A search run while workers are idle (a lone evaluation, the end of a sweep) spreads over them, never exceeding --analysis-workers cores; its result does not change by a single bit. With --analysis-weights 7=3, tenant 7 receives three positions per turn when another receives one. The jobs of a single tenant run in the order they arrived. A rollout takes its turn game by game: one tenant’s long rollout does not keep another tenant’s short request from being served before it ends, and its results do not change (they depend only on the settings and the seed). Every position, cell or game computed is charged to its tenant’s quota of computing seconds. While the daemon is shutting down, an evaluation, a cube matrix or a rollout.position rollout still in the queue answers 503 (code unavailable), recording nothing.
Full scenario, from nothing to a daemon that answers:
git clone https://github.com/kevung/blunderDB.git
cd blunderDB/deploy
cp .env.example .env # POSTGRES_PASSWORD
docker compose up -d --build
# 401
curl -i http://localhost:8080/v1/metadata.counts -d '{}'
# 200
curl -u alice:demo-password http://localhost:8080/v1/metadata.counts -d '{}'
curl -u alice:demo-password -H "X-Tenant-ID: 999" \
http://localhost:8080/v1/metadata.counts -d '{}'
docker compose logs blunderdb-serve
docker compose down -v
The first request is rejected by Caddy, before it even reaches the daemon. The next two are authenticated as “alice”, whom the mapping table associates with tenant 1: they return the same body ({"positions":0,"analyses":0,"matches":0,…}) and the daemon’s log carries tenant=1 for both — the value 999 sent by the client did not survive the Caddyfile’s guard. This scenario has been replayed as written.
To pull the published image instead of building it, replace the three build: lines of the blunderdb-serve service in docker-compose.yml with a single image: line, then run docker compose up -d without --build:
blunderdb-serve:
image: ghcr.io/kevung/blunderdb-serve:<version>
restart: unless-stopped
The Compose file publishes Caddy’s port on every interface (8080:80): that is what one expects from a proxy, which is there to be reached. What must never be published is the daemon — and it is not, it has no ports: at all.
Updating a deployment
The schema is migrated automatically at startup, and this migration is one-way: a database migrated to a recent schema is no longer readable by an earlier version of blunderDB (see Annex: Database Schema). The order of the steps therefore matters.
Back up first, before anything else: it is the only way back (see Backup and restore).
Pull the tag of the intended version, never
latestin production.latestfollows the most recently published version: a deployment that pins it changes version at the whim of restarts, without anyone deciding to, and without the backup from step 1 necessarily being recent.Restart the daemon on the new image. It migrates the schema before serving a single request; if the migration fails, it stops on the error rather than serve a half-migrated database.
Check the readiness probe.
GET /readyzanswers200and{"status":"ready","version":"…"}when storage responds and its schema matches the binary’s;503and{"status":"down"}when the database is unreachable;503and{"status":"version_mismatch","version":"…","expected":"…"}when the two schemas differ — the response names the database’s and the one the binary expects.blunderdb healthcheckreturns the same verdict as an exit code.
Under row-level security (--rls), the first start of a version that adds a derivation computed by the daemon, such as the provenance of analyses, walks once through the rows of every tenant: each batch briefly locks the tables it touches, and tenant requests wait for the batch to finish. If a table stays busy for more than five seconds, the daemon starts anyway and resumes the walk at the next start; once the walk is complete, later starts lock nothing.
A version_mismatch that persists after the restart means a rollback: an older binary facing an already-migrated database. There is no downward migration; it is the backup from step 1 that must be restored.
Important
Before enabling --read-tenants on an existing deployment, update the proxy: a proxy configured before this header existed strips only X-Tenant-ID and would forward as is an X-Read-Tenants sent by the client, which would then read other tenants. Without the option, the daemon refuses this header: a proxy that lets it through shows up in its 400 responses.
PostgreSQL backend and multi-user
For a shared deployment, blunderDB can store data in PostgreSQL rather than in a SQLite file. The backend is selected with --backend postgres and the --dsn connection string. The schema is created and migrated automatically at startup.
Data is partitioned per tenant: each request carries its tenant’s identifier (the X-Tenant-ID header, a positive decimal integer such as 1 or 42), which lets several users share the same instance without seeing each other’s data. An identifier that is not such an integer — a name like alice or default, 0, 007 — is refused with 400 invalid: the reverse-proxy maps an account to its integer, the daemon never guesses.
Row-Level Security
The --rls option additionally enables PostgreSQL’s Row-Level Security. At every startup, the daemon installs on every table carrying a tenant_id a tenant_isolation policy that lets through only the rows of the tenant named by the session parameter current_setting('app.tenant_id'), and enforces it down to the table’s owner (FORCE ROW LEVEL SECURITY). This parameter is set on the connection when it leaves the pool and reset when it returns; a connection with no tenant sees no row and inserts none. This is an optional defence in depth, disabled by default: the application code’s tenant filtering stays in place either way.
The connection role must be ordinary: neither superuser nor
BYPASSRLS. PostgreSQL lets both of those sail through every policy without a word, and isolation falls back to the application code alone. That same role must, on the other hand, own the tables, since it is the one that runs theALTER TABLEandCREATE POLICYstatements.On an already-populated database, there is nothing to migrate: applying the policies is idempotent DDL, replayed at every startup after the schema migration. No data is moved, no row rewritten; turning
--rlson or off is just a restart.The cost is measured: on reading a position, 101.8 µs without, 177.0 µs with, i.e. +73.8 % — same container, same rows, two pools differing only by this flag. It is paid on every connection borrowed from the pool (setting then resetting the parameter) and on the predicate every query crosses in addition, never on the volume of data.
Opening and closing a tenant
There is nothing to create on the server side: a tenant is not a record, it is the integer its rows carry. The database has no table of tenants and the daemon keeps no list of them — opening an account means adding an entry to the proxy’s mapping table, and the member’s first write is what makes their tenant exist.
An empty tenant answers like an empty database, with no error: metadata.counts returns zeros and the lists return nothing.
When a tenant is decommissioned, POST /ops/tenant.purge permanently deletes all its data (positions, matches, collections, history, etc.) for the current tenant (the one carried by X-Tenant-ID), as well as its session state (last search, last position, open tabs — the rows of the session_state table carrying that tenant): the operation runs in a single transaction, is idempotent (no error purging an already-empty tenant or repeating the call), and does not affect any other tenant. It erases this tenant’s rows in every table that carries one, leaving only what belongs to no one: the metadata table, including the global schema-version row, and the migration log. The purged tenant therefore becomes exactly an empty tenant again, and its integer can be reassigned. It is only available with the PostgreSQL backend — it returns an invalid error on a SQLite backend, which has no notion of tenant.
Compaction and connection pool
POST /ops/maintenance.vacuum compacts the daemon’s SQLite file — the counterpart of the “Reclaimable space” line of the Maintenance tab of the graphical interface and of the blunderdb vacuum command (see Command Line Interface (CLI)), with the same disk-space guard — and returns the sizes before and after (sizeBefore, sizeAfter, in bytes). It is only available with the SQLite backend; on PostgreSQL, which has no file to compact, it returns an invalid error.
The PostgreSQL connection pool is tuned via environment variable: BLUNDERDB_POSTGRES_MAX_CONNS (50 by default), BLUNDERDB_POSTGRES_MIN_CONNS (5), BLUNDERDB_POSTGRES_MAX_CONN_LIFETIME (1h), BLUNDERDB_POSTGRES_HEALTH_CHECK_PERIOD (30s), BLUNDERDB_POSTGRES_CONNECT_TIMEOUT (5s — past it, an unreachable database fails fast instead of hanging on the operating system’s TCP timeout) and BLUNDERDB_POSTGRES_MAX_CONN_IDLE_TIME (30m — a connection opened for a burst of traffic does not sit in the pool forever once the burst is over). Each value is a Go-formatted duration (5s, 30m, 1h); absent or malformed, it falls back to its default. When --metrics is on, the pool’s state is continuously exposed on /metrics: blunderdb_pg_pool_acquired (connections currently in use), _idle (available ones), _max (the configured ceiling) and _wait_count (the cumulative count of Acquire calls that had to wait for a free connection).
BLUNDERDB_POSTGRES_QUERY_EXEC_MODE selects the pool’s query execution mode: cache_describe (the default), cache_statement, describe_exec, exec or simple_protocol (pgx’s names). By default the engine does not prepare named plans on the server: with cache_statement, every distinct SQL text (variable-length IN lists and multi-row inserts) leaves a plan in memory on the connection until it closes. An unknown value makes startup fail; a default_query_exec_mode given in the connection URL takes precedence over the variable.
With the SQLite backend, the daemon opens one connection per core, ten at least (the desktop keeps ten). Requests that scan the whole library (stats.*, search.count, search.find, search.ids, search.query, search.indexOf, matches.list) run at most one per pair of cores, two at least, so that connections stay free for single-row reads; the next ones wait their turn, at most 20 s and eight per slot, then receive 503 (code unavailable) with a Retry-After header. A write that cannot get the database, held by another writer beyond its wait, receives the same answer: nothing was written, and the request can be retried as is. --heavy-slots sets another number; on PostgreSQL these reads are bounded only when it is given.
At startup, a SQLite daemon computes in the background the missing per-match statistics (the stats.matches line of the maintenance); a statistics read arriving during this computation waits for it, then reads the result.
Migrating a SQLite database to PostgreSQL
blunderdb migrate copies a single-user SQLite database to a PostgreSQL backend, under a chosen tenant — the integer the reverse-proxy will send in X-Tenant-ID for that user — this is the path to “upload” a desktop library to a server deployment.
blunderdb migrate \
--from sqlite:///path/to/database.db \
--to "postgres://user:pass@host:5432/db?sslmode=disable" \
--tenant-id 42
# --dry-run
blunderdb migrate --from sqlite:///path/to/database.db \
--tenant-id 42 --dry-run
The migration copies the positions, their analyses and comments, the matches (games + moves), the tournaments (with their match links) and the collections (with their composition), as well as the match equity tables (the current one and the one with which each analysis was valued), reassigning primary and foreign keys, all within a single transaction on the destination side: the operation is atomic (a failure leaves the destination intact, just run it again). Positions, their analyses and moves are written in batches. Progress and the final summary are emitted as NDJSON on standard output; each copied family also leaves one line in the log (standard error) with its row count and duration. If the source database is old enough to need its own in-place schema upgrade, that runs first and emits its own "schema-migration" events (phase/done/total) before the copy begins.
During the copy, the transaction holds a SHARE UPDATE EXCLUSIVE lock on the position, analysis, match, game and move tables: two simultaneous migrate runs, even to different tenants, run one after the other and autovacuum skips those tables; the daemon’s reads and writes are not blocked. The DSN’s role must be allowed to run ANALYZE on these tables — own them, be superuser or, from PostgreSQL 17, hold the MAINTAIN privilege — otherwise migrate stops before copying anything.
Option |
Default |
Meaning |
|---|---|---|
|
– |
source SQLite database ( |
|
– |
destination PostgreSQL DSN ( |
|
– |
destination tenant, a positive decimal integer (required except in |
|
– |
counts what would be copied without writing anything |
|
|
|
Note
Application states are not migrated: Anki decks/cards, the filter library, search and command history, and session metadata; migrate announces their count at the end. The error and blunder thresholds, however, are copied (see Backup and restore).
The generic call dispatcher
In addition to the historical subcommands (Command Line Interface (CLI)), blunderdb call exposes all storage operations directly, locally. It goes through the same handlers as the serve daemon: the behaviour is therefore identical to POST /v1/<family>.<method>. This is useful for scripting and integration testing.
# --list
blunderdb call --list
# read
blunderdb call metadata.counts --db database.db
blunderdb call positions.list --db database.db --json '{"limit":10}'
blunderdb call matches.get --db database.db --json '{"id":1}'
# write
blunderdb call positions.save --db database.db --json '{"position":{...}}'
blunderdb call matches.delete --db database.db --json '{"id":42}'
# a gesture of a tournament Direction, with the version a read printed
blunderdb call directions.enterResult --db database.db --if-match '…' \
--json '{"tournamentId":3,"matchId":"m7","winner":"aa"}'
Options:
Option |
Default |
Meaning |
|---|---|---|
|
– |
SQLite file (shorthand for |
|
|
|
|
|
backend connection string; with |
|
– |
with |
|
|
with |
|
|
tenant, a positive decimal integer (sent as |
|
|
request body in JSON format |
|
– |
reads the request body from a file |
|
– |
lists all |
|
– |
version sent in |
With --backend remote, call reads no database: its handlers go through the /v1 API of the daemon named by --dsn (an http://host:port or https://… URL), with the tenant of --scope and the headers of --header (X-Tenant-ID is refused there: the tenant is --scope). --db and --backend remote exclude each other. The daemon does not authenticate; the proxy in front of it decides: a refusal by the proxy (HTTP 401 or 403) reads “refused” and points to --header, a limit (HTTP 429, rate_limited) reads as such, and only a daemon that is unreachable or silent beyond --timeout reads “daemon unavailable”. A daemon older than withPlayed ignores it and returns the analysis without the moves played: the answer is printed as is and call reports it on standard error.
A method whose storage has no /v1 route (a transaction, a Direction, Rencontre, Duel, match equity table or transcription service) does not go through --backend remote: the error says so, the process exits non-zero, and call prints on standard error the request to send to the daemon (POST <dsn>/v1/<method>). The same holds for exports (exports.sqlite, exports.json, exports.plan, incremental ones included): call the daemon directly.
call serves the transcription moves without any flag: it works on a local file, like the CLI. Every call is a fresh process, hence its own session: sessionId can be omitted, and there is no undo from one call to the next.
The JSON response (or the NDJSON stream for *.list endpoints) is written to standard output. On error, the process exits with a non-zero code and the {"error":{…}} envelope is printed to standard output so it stays parseable (for example with jq); so is an error that occurs in the middle of a stream. A response carrying a Direction-Version header prints it on standard error: that is the value the next gesture passes to --if-match. call serves direction gestures without a flag, like the CLI, since it runs locally.
Tools for an AI assistant (MCP)
blunderDB embeds no language model: it offers its tools to the assistant you already use (Claude Code, Claude Desktop, a local client), through the Model Context Protocol. The assistant searches, reads and explains; blunderDB answers with its own figures.
The tools go through the same handlers as /v1 and call:
Tool |
What it returns |
|---|---|
|
counts, period covered by the matches, schema version, frequent players |
|
positions found by a search in the command-bar grammar (described in the tool), with its canonical form |
|
comments containing given words; all the comments of a position, each with its author; saved searches |
|
a position, its analysis (best moves or cube), the move played and the comment |
|
the theme of the error, its cost in millipoints and the best decision |
|
neighbouring positions; reading of an XGID; legal moves; race EPC |
|
players; their aliases and the suggested spellings; global PR, checkers, cube, by phase; recurring errors; quiz PR and Anki retention against the real PR; positions missed in the quiz |
|
head-to-head of two players; PR by calendar window; ranking by PR |
|
matches, detail of a match, tournaments |
|
collections and their positions; study decks |
|
lessons; the steps of a lesson, in order |
|
draws a position without its answer, then grades the answer given |
|
gammonNet evaluation of a position given as text, without saving it: best moves or cube decision |
|
the next due card of a review deck |
|
match transcriptions; detail of a transcription; its |
|
directed tournaments; standings of a tournament; season ranking |
|
rollout of a library position: equity, 95% interval and JSD per candidate |
|
reads across the tenants that the proxy lists (Reading several tenants): the students’ matches, the positions of a match with their hash, comments written on these boards, shared library, club ranking; without |
Only these tools write — save_position, comment_position (which signs with the author argument, otherwise with the X-User-Name header), create_collection, add_to_collection, anki_review, which grades a card drawn by anki_next, and the transcription gestures transcribe_create, transcribe_open, transcribe_apply, transcribe_undo, transcribe_redo and transcribe_finish, served only by a daemon launched with --transcription; each gesture that changes the draft names its session and the last revision seen, and a stale revision is refused as for a direct client — and they are offered only on request: --write locally, --mcp-write on the daemon. All the others only read; rollout nevertheless gains, when writing is offered, the store argument, which records the rollout beside the position’s analysis. No tool deletes anything.
Locally, the assistant launches blunderdb mcp on a file (see Command Line Interface (CLI)). For Claude Code:
claude mcp add blunderdb -- blunderdb mcp --db /chemin/vers/base.db
On the daemon, the same tools answer over HTTP on POST /mcp (streamable HTTP transport, sessionless). Like /v1, /mcp requires X-Tenant-ID and each tool works in that tenant; a program that embeds pkg/blunderdb/server serves it too. The daemon authenticates nobody (ADR-0005): /mcp is protected at the proxy like /v1, and --mcp-write is decided there like --direction. Every /v1 call a tool makes goes through the daemon’s whole chain again: it is logged, counted in the metrics and charged to the tenant’s rate limit, on top of the /mcp request that carries it. A tool call therefore costs several requests; none is exempted.
Like call, blunderdb mcp migrates an older database’s schema when it opens it, even without --write.