ADR-R2-10. Opening explorer build: one parallel pass, verified before activation
Source:
docs/decisions/ADR-R2-10-opening-explorer-build.md. Generated at build time; edit the source file.
Date: 2026-11-22 Status: Accepted. This is a placeholder number; the controller renumbers R2 ADRs before merging. It builds on ADR-R2-9 (the streamed, verified, never-stored dump) and ADR-R2-23 (reference build storage), and carries TS M2 ADR 0035’s parameters into the Rust backend.
Context
Section titled “Context”The repertoire’s “in theory” test (≥ 50 games and a ≥ 5 % share) and its opening verdicts need an opening explorer for each rating band and time class. That data comes from the Lichess monthly dump. A month is about 31 GB compressed and about 95M games, in time order. TS M2 (ADR 0035) read the dump in a single thread, after downloading it. R2 streams the dump instead (ADR-R2-9). Every byte must still be hashed before the result is trusted, so a build is one long transfer, and the parser has to keep up with it.
Decision
Section titled “Decision”Parameters (from TS M2 ADR 0035)
Section titled “Parameters (from TS M2 ADR 0035)”- One month per build, built quarterly by the operator CLI (
lichess-db build --month M --explorer). - Sample size about 2M games (
max_games). Each game counts only its first 30 plies (max_ply). The replay goes throughPosition::play_san, and the parser never replays the full PGN. - Prune rows whose total is below 3 (
min_row_count) before activation. - Bands by the mean rating of the two players:
explorer_band = band_of((white + black) / 2). - Four time classes: bullet, blitz, rapid and classical. Correspondence (
TimeControl "-") is excluded. - Each row’s key is
fen_key | band | time_class | uci, and it holds White wins, draws and Black wins. Unfinished games (*) count nothing.
Sampling across the whole month (T19 review ruling)
Section titled “Sampling across the whole month (T19 review ruling)”- The dump is in time order. Taking the first 2M games would sample only the first hours of the month, so the build samples by rate:
sample_rate = min(1, max_games / expected_games).- The sample uses the deterministic FNV hash of
Siteand the seed (ADR-R2-9). expected_gamescomes from--expected-gamesif given. Otherwise it is thegames_scannedof the newest active or superseded build that was not capped. With neither, it isDEFAULT_EXPECTED_GAMES= 100M, a rough 2026 figure.
- The sample uses the deterministic FNV hash of
max_gamesis an upper target. The rate divides by every game in the month, but the filters (BOT, correspondence, abandoned, missing ratings) also drop games, so the sample lands a little belowmax_games(kept ≈ target × eligible share). That makes the sample smaller, not biased.- A build that reaches the safety cap logs a warning, since the explorer then lacks the end of the month. It still activates, and is recorded as capped.
- The estimate comes from the newest uncapped build before the month being built, so rebuilding an older month never uses a later month’s count.
- The pipeline stops only at a safety cap of
max_games × 1.25.- A build that reaches the cap is recorded with
params.capped = true. Its count is never used as the next month’s estimate. - With a correct estimate, the binomial spread at 2M is about ±0.1 %, so the cap is not reached.
- A build that reaches the cap is recorded with
- BOT games are excluded: either side has
WhiteTitleorBlackTitle"BOT". - Provisional-looking games are not excluded (fix round 1, controller ruling). The dump has no provisional flag.
headers::looks_provisionalflags a side when|RatingDiff| ≥ 25in that game, andBuildOptions::exclude_provisional/SampleFilter::exclude_provisional(both off by default) can drop such games. The option stays off for the explorer, for two reasons:- The threshold is an unverified estimate. It comes from Glicko-2 arithmetic: at RD ≈ 60 an even game moves a rating by about 10 points and a large upset by about 20, and at RD ≥ 110 (the Lichess provisional threshold) an even game moves it by about 30. It has not been checked against Lichess data, and its drop rate is unknown.
- It filters partly by result. A rating change scales with how surprising the result was, so a raw threshold drops upsets more often than other games. It also flags established but inactive players (RD 80-110) in ordinary decisive games, and misses provisional players who draw an equal opponent. Those results are exactly what the explorer counts (White wins, draws, Black wins), so turning it on would bias the counts by an unknown amount.
- A result-independent rule, such as an RD estimate normalised by
|score − expected|, is left to Task 21, which owns reference-player selection. Until then, a game’s band can be off when one side is provisional. That error does not select games by their result, so it is preferred to a filter that does.
Single-pass parallel pipeline
Section titled “Single-pass parallel pipeline”run_pipeline (pipeline.rs) works in these steps:
- The async reader pulls games from the dump stream. The network, SHA-256, zstd and the splitter all run on that one task.
- It fills
Vec<String>batches ofbatch_gamesgames (2,000) into a bounded channel ofchannel_batchesbatches (2 × threads). - Each batch goes to a rayon pool of
threadsthreads (default: every core). The pool runspar_iterover the batch: headers, thenkeep, thenGameSink::observe, which for the explorer is the SAN replay into(fen_key, uci)pairs. - At most two batches are in flight. Their results come back in batch order, through
buffered, notbuffer_unordered. GameSink::mergeruns on the async side, one batch after another.
Memory is bounded by channel_batches + 2 batches plus one flush interval of explorer keys. The channel scales with the thread count: at 24 threads, 48 + 2 batches of 2,000 games is about 100,000 games, or roughly 100-150 MB of PGN. That is bounded but not small; lower --threads (or channel_batches) on a small host.
Deterministic merges
Section titled “Deterministic merges”- Batches merge in source order, and the cap is applied in that order. So the kept games, the
games_seencount at the cap and every explorer count are the same at any thread count. pipeline_is_deterministic_across_thread_countscompares 1 thread with 4, with 9-game batches and a flush every 37 games, and gets identical rows. Mutation check: withbuffer_unordered, three ordering and cap tests fail.- A panic in
observeis caught and becomes an error; it does not abort the process.
Activation only after verification (R-9)
Section titled “Activation only after verification (R-9)”The build runs in this order:
- Fetch
sha256sums.txt. - Create the
buildingrow, with its parameters inparams. - Run the pipeline. Flush every
flush_every_games(50,000) games, and once more at the end. - Drain the rest of the body through the hasher without decompressing it.
ShaHandle::verifychecks the digest.finishis never used.- On a match:
- record
params.capped; set_source_sha, withgames_scanned= games seen;prune_explorer;activate_build, which supersedes the previous build and deletes its rows.
- record
Any error after step 2 calls fail_build. That deletes the build’s rows and leaves the previous active build untouched. Such errors include a transport error that could not be resumed, a checksum mismatch, a store error, and a month that is not newer.
--verify none skips steps 1, 4 and 5. It prunes and marks the build unverified, which is never served.
A build records one job_metrics row: kind = "lichess-db:build", total_ms, and the stages read_ms, parse_ms, aggregate_ms, flush_ms, drain_ms, prune_ms and activate_ms.
Flushes are not retried
Section titled “Flushes are not retried”flush_explorer adds counts, so retrying a chunk that may already have committed would count it twice (T17 review). The build never retries a flush. A failed flush fails the whole build, and since the stream cannot be replayed, the operator reruns the month. A double-counted chunk can therefore never reach an active build. Making chunks idempotent with a chunk marker would need a migration, and it would only pay off with in-process flush retries, which this design does not have.
Transfer robustness (T19 review ruling)
Section titled “Transfer robustness (T19 review ruling)”- Before the body starts, a connect error, a timeout, a 5xx or a 429 is retried: 3 tries in total, with a doubling backoff from 2 s. A 4xx such as 404 is not retried.
- A transport error mid-body is resumed in-process. The resume is a GET with
Range: bytes=<read>-andIf-Range: <strong ETag>, and the answer must be a206whoseContent-Rangestarts exactly at the offset. The resumed bytes go into the same hashing stream. - The budget is 5 resumes. Every ranged request uses one, with a backoff of
2 s × nbefore the n-th. A ranged request that fails to connect, times out, or gets a 5xx or 429 is tried again while the budget lasts (fix round 1), so a short mirror outage does not abort a 2.5-hour transfer. A200(the file changed, soIf-Rangefailed), another status or a wrongContent-Rangeis final at once. - Without a strong ETag, or with a
200, the error is final, and the hash stays incomplete, soverifycan never pass. - The zstd window is capped at 2^24 (
window_log_max; Lichess uses 2^23), so a hostile frame cannot force a large allocation.
Throughput
Section titled “Throughput”The measurements are in docs/research/r2-lichess-db-benchmark.md, taken on a 24-thread Ryzen 9 9900X:
- On synthetic data, games/s scales 5.9× from 1 to 24 threads, and parsing is the bound.
- On the real 2026-10 dump, the run is network-bound at 3.5 MB/s, about 10.8k games/s.
A full month is therefore set by its transfer, about 2.5 hours at that rate, not by the CPU. lichess-db bench is a CLI subcommand only. It is never part of the gate.
Alternatives considered
Section titled “Alternatives considered”- Multiple passes, or a pre-scan to count the month. That would download 31 GB twice. We use the last build’s count instead.
- First-N sampling. It is biased to the start of the month (rejected by the T19 review).
buffer_unorderedmerges. They are faster on a skewed batch, but the cap would no longer be deterministic, and nor would the results under a cap.- Bottom-k by hash (R-10) gives an exact sample size without an estimate. It was kept for the reference-player selection (Task 21). For the explorer, a ±25 % miss on the sample size is harmless.
- Idempotent flush chunks (chunk ids, or a marker written in the same transaction) were the T17 review’s wording. The controller accepted “never retry, fail the build” instead (fix round 1), as safe: an ambiguous commit leads to
fail_build, which deletes the rows, so a double-counted chunk can never be activated. Chunk markers would need a migration, and they pay off only if flushes are retried in-process.
Consequences
Section titled “Consequences”- An explorer build takes as long as its transfer. If a resume is impossible, a late network failure means a rerun of the month.
- The CLI
builduses a 6-hour statement timeout, because the prune and the activation delete millions of rows. --band-referenceis refused with aConfigerror until Task 21 wires it intobuild.DumpErrorgainsStore(Postgres) andConfig(invalid options).