# Monte-Carlo Graph Search for Rigby: research and plan Written 2026-11-16 against `main` at `c8d1ca6` (bench `663779`). Implementation sessions read this file and `docs/mcgs-log.md` first. They do one step from section 5, nothing else. If this plan turns out wrong for a step, that session stops and explains instead of improvising. Contents: 1. Facts about the current code (verified) 2. Research findings, with sources 3. Design 4. Measurement design (step 1) 5. Implementation plan 6. Test reference 7. Open questions for the owner --- ## 1. Facts about the current code (verified on c8d1ca6) Read in full: `src/mcts.h`, `src/mcts.cpp`, `src/uci.cpp`, `src/eval.cpp`, `src/position.h`, `src/types.h`, plus the key and halfmove parts of `src/position.cpp`. - **Value net.** The brief says `(768->128)x2->1`. That is out of date. The Makefile embeds `networks/rigby-value-v2.bin`, which is `(768->1024)x2` SCReLU (PR #22). The README still describes v1. Value = `cp_to_q(quiescence(...))`, with Q = tanh(cp/800). - **`Node` is 20 bytes:** `u32 first_child, u32 visits, float q, u16 move, u16 policy, u8 num_children, u8 state`. It is node and edge at once. Children sit contiguously in `Tree::nodes_`. Index 0 is null and index 1 is always the root (`Tree::root()` is `static constexpr`). - **`q`** is a running mean from the view of the side that moved into the node, updated incrementally: `q += (value - q) / visits`. Selection reads `child.q` directly. The side to move at a node sees `-node.q`. - **Leaf handling.** The first visit of a node only evaluates it (`evaluate_leaf`); the second visit expands it (`expand`: movegen, butterfly bias, policy net). The root is expanded before the first playout and never evaluated, so the root's visits equal the sum of its children's visits. Every other expanded node has at least one visit more. - **`evaluate_leaf`** checks, in this order: no legal moves (mate → `TERMINAL_LOSS`, stalemate → `TERMINAL_DRAW`); then, only at depth > 0, `halfmove >= 100`, insufficient material and `is_repetition`, all stored as `TERMINAL_DRAW`; then a `ValueHash` probe; then `eval::value`. Path-dependent draws therefore live in the node today. That is fine in a tree and wrong in a graph. - **`is_repetition`** is two-fold: any earlier occurrence of the key, same side to move, `back = 4, 6, ... <= halfmove`, over `history_`. `history_` holds the game history up to and including the root, plus the playout path. Two-fold therefore also counts a single earlier occurrence in the game before the root. - **`ValueHash`** takes 1/32 of Hash: 12-byte entries, a 32-bit check, replaced by visits. Backprop stores `-node.q` for every path node except `TERMINAL_DRAW` nodes. `evaluate_leaf` probes it before calling the net. It persists across searches and is cleared on `ucinewgame`. - **`ButterflyHistory`** is updated for every path move with the playout result in cp and biases policy logits at expansion time. - **`Tree::compact`** (used by `reroot` and `collect_garbage`) packs kept child blocks in place. It relies on two things: a child block is allocated after its parent's block, and every node has exactly one parent. `prune_threshold` relies on visits only shrinking going down the tree. All three break on a DAG. - **Root decisions** use child visits: `best_child` (most visits, then Q, then prior), `best_move_settled` (smart pruning with `root_start_visits_`), `principal_variation`, `print_info` and `draw_dashboard`. - **Zobrist key** covers pieces, castling rights, side to move and the ep file only when an ep capture is pseudo-legal. It excludes the halfmove clock, which is good for merging. - **`RIGBY_VERIFY_TREE`** checks, after reroot and after each GC: legality of every child move, `num_children == legal moves`, and visits >= the children's visits sum (+1 for non-root nodes). - **`bench`** runs 16 positions × 5000 playouts, one `Searcher`, Hash 64. Signature = Σ(playouts + depth sum). Each position has history `{key}`, so tree reuse never happens. 5000 expansions are far below 64 MB, so GC never happens either. **Bench therefore does not cover GC or reuse.** Separate checks are needed (section 6). - Baseline on this machine: `663779 nodes 3253818 nps` (bench nps is tree positions per second, not playouts). - The Chess960 perft EPD with node counts was **not in the repo**. The Chess960 session left `fischer.epd` in its scratchpad: 960 positions, D1–D6. It is now copied, untracked, to `tests/fischer.epd`, and step 2 commits it. `perftfile tests/fischer.epd 5` passes on c8d1ca6 (17.6·10⁹ nodes, 52 s). - `cutechess-ob.exe` exists at `C:\Users\rektd\repos\OpenBench\Client\` and can run local smoke matches. ## 2. Research findings "Verified" means I read the source or text myself in this session. Anything else is marked. ### 2.1 KataGo, "Monte-Carlo Graph Search from First Principles" (verified) https://github.com/lightvector/KataGo/blob/master/docs/GraphSearch.md - Naive node sharing is unsound. Child visit counts get inflated by other parents, and parent Q goes stale or drifts. Updating every parent of a node is also wrong. - Derivation: PUCT approximately solves a KL-regularised policy optimisation (Grill et al.). The node value is then the regularised utility of the posterior policy: `Q(n) = (U(n) + Σ_a N(n,a)·Q(n,a)) / N(n)`, with `N(n) = 1 + Σ_a N(n,a)` and `Q(n,a) = Q(child)`. - **Edge visits** N(n,a), meaning how often PUCT at n chose a, are separate from the child's N. PUCT uses edge visits: `Q(n,a) + c·P(n,a)·sqrt(Σ_b N(n,b)) / (1 + N(n,a))`. - Recompute Q idempotently on the playout path. Stale Q off the path is accepted: exploration visits everything eventually, and a recompute makes a node correct once its children are. - **Stop rule:** optionally recurse only if `child.N <= edge visits`. Otherwise increment the edge and recompute upward without a new child visit. KataGo stops by default and has options to always continue or stop "leakily". Convergence needs child visits → ∞ as edge visits → ∞. - An incremental update is equivalent on trees. On graphs it "can be a little tricky" but can be done. KataGo prefers idempotent updates. Tracking N·Q instead of Q can give torn reads under lock-free multithreading. - Game-over nodes: N = 1, U = Q = outcome. - Hashes: 128–192-bit Zobrist is "usually collision-free". Cycle detection guards against collision-induced recursion. - Cycles are mostly ignored in the main text. KataGo (Go) uses a history hash that blocks sharing only when a cycle is possible. The 2024-03-10 addendum links a Google Doc (next item). ### 2.2 lightvector, "Thoughts on Handling N-fold Repetition in MCGS for Chess" (verified) The Google Doc at https://docs.google.com/document/d/1JbxsoMtr7_qAAkfYynAgpvuarMMJycaL5toXdnqVJoo does not render for a fetcher, but its plain-text export (`.../export?format=txt`) was readable. Dated 2024-02-28. The author notes he has no chess implementation experience. Content: - Baseline: put the full history in the hash. That is safe and degenerates to MCTS. Do not XOR position Zobrists together for the history, because XOR commutes and self-cancels; use a non-linear mixer such as splitmix64. - Truncate history at provably irreversible moves (captures, pawn moves, castling-right changes). States that differ only before such a move merge. - Then prune history heuristically with `prune_history_for_hashing(history)`, as KataGo does for Go. Possible rules: drop positions that are too many plies old, or that differ from the current board on many squares, or a learned head predicting whether a history position can recur. - If a cycle still occurs, "terminate a playout if that playout's path ever intersects itself", while still incrementing edge visits and recomputing N and Q on the way back. ### 2.3 Czech, Korus, Kersting, "Monte-Carlo Graph Search for AlphaZero" (2020, verified) https://arxiv.org/abs/2012.11045, CrazyAra (crazyhouse and chess). - Stores visits and Q on **both edges and nodes**. When the next node is a transposition, it computes `δQ = Q(s,a) − V*(s')`. If `|δQ| > ε_Q` (0.01), it stops the playout without a net evaluation and backs up the correction `Q_φ = N(s,a)·δQ + V*(s')`, clipped to `[Vmin, Vmax]`. Otherwise it keeps descending. ε_Q is "the only hyper parameter". - "We incorporate the step counter within the transposition hash key. This way we cannot reach a state with the same key more than once within a trajectory. Therefore, cycles cannot occur." Which counter is meant is **not stated** (probably the ply or move count). Merges then happen only between paths of equal length. - Assumes Markovian states. Using history in the net input "did not result in a major issue". - 30–70 % memory reduction. The gain grows with search size. Chess gains are smaller than crazyhouse gains. ### 2.4 Grill et al., "Monte-Carlo Tree Search as Regularized Policy Optimization" (ICML 2020) https://arxiv.org/abs/2007.12509. I verified only the abstract: AlphaZero's search heuristics approximate the solution of a specific regularised policy optimisation. The form `π̄ = argmax_y [qᵀy − λ_N·KL(π_θ, y)]` with `λ_N = c·sqrt(Σ_b n_b) / (|A| + Σ_b n_b)` is **from memory and not verified**. What matters here is the consequence (verified through the KataGo doc): the regularised target is defined by how often PUCT chose each action at this node, which is the edge visits, not the child's total visits. ### 2.5 Lc0 - **PR #963 is not DAG search.** It is Naphthalin's "Beta-MCTS: a soft hybrid of MCTS and Minimax", opened 2019-10-06, labelled "not for merge" and never merged (verified on the PR page). The TalkChess thread cites it, which is probably where the confusion comes from. - Lc0's DAG search is `src/search/dag_classic`, merged as "dag-preview" in **PR #2155** (borg323, 2025-04, "mostly the work of @Etcaqab"). Follow-ups: #2274 garbage-collection thread (merged 2025-10), #2388 n_in_flight underflow fix (merged 2026-05), #2291 fixed-size TT (open), #2295 TT memory calculation (merged). Source read at master `476a0f7` (2026-10-20). - **Layout** (verified, `node.h`). `LowNode` is the shared position: an `edges_` array (move + policy), N, WL, D, M, number of parents. `Node` is a realised edge with its own N, WL, D, M, `n_in_flight_`, a `sibling_` pointer, a `shared_ptr` to the target `LowNode`, and bit flags including "edge was handled as a repetition at some point". Both are ≤ 64 bytes. **Lc0 keeps Q on the edge** (`Node`) as well as on the node (`LowNode`), like Czech. - **Key** (verified, `PositionHistory::HashLast` and `Position::Hash`): `HashCat` of the last `CacheHistoryLength+1` positions (default 0, so just the last position). Each position's hash includes its repetition count, and the rule-50 ply is mixed in. **Lc0 merges only positions with equal rule-50 ply and equal repetition count**, which is conservative. The TT maps the 64-bit hash to a `weak_ptr` and erases expired entries. The exact container type was not checked. There is no full-position comparison. - **Repetition** (verified, `search.cc`). Three-fold (`repetitions >= 2`) is a pseudo-terminal: the `Node`, i.e. the edge, gets `SetRepetition()` and value 0. A two-fold inside the search tree (`TwoFoldDraws`, default on, depth >= 4 and depth >= plies since the previous occurrence) also marks the edge as a repetition and propagates a draw above it. Fifty-move and insufficient material are made terminal on the `Node` at extension, except at the root. - **Transposition catch-up** (verified). `MaybeAdjustForTerminalOrTransposition` replaces the edge's value by the LowNode's when the edge has fewer visits or the LowNode is a transposition, and propagates the delta upward (`n_to_fix`, `v_delta`). `ShouldStopPickingHere` stops a playout at a transposition whose Node and LowNode differ by ≥ 0.01 WL (and other limits). This is Czech's ε rule. - Multithreaded, with `n_in_flight` on both Node and LowNode and reference counting plus a background GC thread. ### 2.6 Monty (verified, `official-monty/Monty` master `0950aff`, 2026-05-12) - **A tree, not a graph.** Transpositions are handled only by a hash table of Q (`tree/hash.rs`: 32-bit check, q, d, visits). It is probed in place of the network at a node's first visit and written on the way back for every path node. Rigby's `ValueHash` copies this. - Repetition and 50-move are checked by `game_state` with a stack of keys cleared at every zeroing move, set on the node at first visit (`node.set_state`). That is fine in a tree. Note: `halfm == 100` with mate counts as mate. Monty's hash also receives the value of path-dependent draw nodes. I did not check whether that matters. ### 2.7 Ceres (verified, `dje-dev/Ceres` main, `src/Ceres.MCGS`, last change 2026-09-12) - Has a full MCGS implementation (`GNode`, `GEdge`, parent lists, `n_in_flight` per edge). - `PathMode`, default **`PositionEquivalence`**: nodes are coalesced by board position. Alternative: `PositionAndHistoryEquivalence`, which keys on the position plus a 96-bit **multiset** running hash of the positions since the last irreversible move (`PositionWithHistoryHashes`: the running hash resets after an irreversible move). - **Repetition draws live on the edge as a count**, not a flag: `GEdgeStruct` has `N` and `NDrawByRepetition` (both `int`), and `Q = QChild·(N − NDrawByRepetition) / N`, so a draw visit counts as 0. - `ReconcileDrawByRepetitions`: after graph reuse, an edge whose child board is in the game history (graph-root to search-root spine plus prehistory) is reclassified as a full draw (`NDrawByRepetition = N`). That is exact, because that history is common to every path. Purely in-tree repetitions stay path-dependent and are left to live detection. ### 2.8 Graph History Interaction literature - Kishimoto & Müller, "A General Solution to the Graph History Interaction Problem", AAAI-04 (verified, PDF text). GHI was first noted by Palay (1983). Campbell (1985) split it into **draw-first** (a score involving repetition is stored and wrongly reused for a position without repetition) and **draw-last** (the reverse). Breuker et al.'s Base-Twin Algorithm (BTA) uses possible-draw marks with base and twin nodes, needs an explicit graph, and must remove marks every iteration "since marks are path-dependent information". The AAAI paper stores path information for proven results and uses Kawano's simulation, targeting proofs (df-pn, αβ) in checkers and Go. - Campbell 1985 and Breuker, van den Herik, Uiterwijk, Allis 2001 ("A solution to the GHI problem for best-first search", TCS 252) were **not read directly**, only through the AAAI-04 summary. - What carries over to MCGS: MCGS proves nothing, so exact GHI handling is not needed. What is needed is to avoid the draw-first case systematically (never store a path-dependent draw in a shared node) and to keep the draw-last error bounded. ### 2.9 TalkChess, "Move repetitions in tree search + transpositions" (t=72136) Page 1 of 2 was read. Page 2 could not be fetched (connection refused) and is **unread**. - koedem: shared nodes make repetition status path-dependent. He cites lc0 PR #963. - noobpwnftw: only the path with the globally shortest occurrence of a node may expand it. Other occurrences are treated as terminal and rescored locally if the path repeats. - koedem's objections: the shortest path may go through a blunder, the main line can be starved, and his example FEN is `3r2k1/5ppp/8/8/8/8/5PPP/2R3K1 w`. - No resolution on page 1. ### 2.10 Not verified - The exact Grill formula (2.4). - Which "step counter" Czech et al. hash (2.3). - Campbell 1985 and Breuker 2001, read only second-hand (2.8). - TalkChess page 2 (2.9). - Lc0's TT container type (2.5). ## 3. Design ### 3.1 Conventions and invariants - `v` = a value in [-1, 1] **from the side to move** at a position (what `eval::value` returns). - `node.q` and `node.u` are **from the view of the side that moved into the node**: `node.q = −(stm value)`. This keeps Rigby's convention. It is path-independent, because the side to move is part of the position. - Edge `(n, a)` leads to child `c`. `c.q` is from the view of the side to move at n, which is the side choosing a. So the edge value used in PUCT at n is `Q(n,a) = (W(n,a) / N(n,a)) · c.q`, where `N(n,a)` = edge visits, `D(n,a)` = edge visits that ended in a path-dependent draw, and `W = N − D`. Draw visits count as 0. If `N(n,a) = 0`, FPU applies. If `W = 0`, the edge value is 0. - Node visits: `N(n) = base(n) + Σ_a N(n,a)`. A fresh node has `base = 1` and `u = −v_leaf`. A pruned node (3.6) keeps its N in `base` and its Q in `u`. - Recompute in mover view: `n.q = (base·u − Σ_a W(n,a)·c_a.q) / N(n)` Check: the side to move at n sees `−n.q = (base·(−u) + Σ W·c.q) / N`, which is KataGo's formula with draw visits contributing 0. - Terminal nodes (position-intrinsic only: checkmate, stalemate, insufficient material): `u = q = +1` (the stm is mated, so the mover won) or 0. They have no edges. N counts visits. - **Only position-intrinsic facts are ever written into a node.** Repetition and 50-move results exist only as per-edge draw counts and as a playout's value. ### 3.2 Data layout ``` struct Edge { // 16 bytes, contiguous per node, created at expansion u32 child; // node index, 0 = no node yet (lazy creation) u32 visits; // N(n,a): how often PUCT at n chose a u32 draws; // D(n,a): of those, playouts that ended in a path draw u16 move; u16 policy; // prior scaled to 0..65535 }; struct Node { // 32 bytes, created when a position is first reached u64 key; // full Zobrist key u32 first_edge; // 0 = not expanded u32 visits; // N(n) = base + Σ edge visits float q; // mover view, recomputed on the playout path float u; // mover view: own evaluation, or the Q kept by pruning u32 base; // weight of u: 1, or N at the time of pruning u8 num_edges; // ≤ 218 legal moves u8 state; // UNEXPANDED, EXPANDED, TERMINAL_LOSS, TERMINAL_DRAW u16 check; // second fingerprint, see 3.5 }; ``` Why this differs from the brief's 12-byte edge: the draw count must be per edge and 32-bit. A perpetual-check edge in a long analysis can collect more than 65k draw visits, so a u16 would saturate and silently bias Q. A one-bit flag is not enough either (3.5). 16 bytes also keeps 4 edges per cache line. The node is 32 bytes, not 20, because it carries the key (needed to rebuild the table after GC and to verify), `u` and `base` (needed for idempotent recompute and for pruning without losing information) and a 16-bit second check. **Key table:** open addressing with linear probing, power-of-two capacity ≥ 2 × node capacity. 8-byte slots `{u32 key_hi, u32 node}` (`node = 0` is empty). Slot = `key & mask`. A hit needs equal `key_hi`, then the node's full 64-bit `key` and its 16-bit `check`. Nothing is ever deleted except by a rebuild after GC or reroot (3.6), so there are no tombstones. About 16 bytes per node. **Memory and the meaning of Hash.** Hash still means all search memory: ValueHash (1/32, until variant 5c), key table, node arena, edge arena. With r edges per node, a node costs about `32 + 16 + 16r` bytes. Today a node costs 20 bytes for every child, visited or not. The split between the arenas is set in step 3 from the edges-per-node ratio measured in step 1 (`edge_bytes / node_bytes` at the end of 5 s searches). GC runs when either arena or the table (load > 0.5) is full. ### 3.3 Playout (always-descend base, step 3) ``` pos = root_pos; history_ = game history + root; path = [root] loop: n = path.back() if n is TERMINAL: value = stm view of n.u; break if n is UNEXPANDED: expand(n) (fails → playout ends here, value = -n.q, gc_pending) e = select_edge(n) pos.make_move(e.move); history_.push(pos.key); depth++ // Path-dependent draws are decided before the node lookup: if is_repetition(pos) → path draw else if pos.halfmove >= 100 and not checkmated(pos) → path draw if path draw: value = 0; e is marked as a draw edge for backprop; break if e.child == 0: c = table.find(pos) // a transposition into an existing node if !c: c = create_node(pos) // first visit: evaluate (3.1); value = its v e.child = c; path.push(c); break e.child = c path.push(e.child) if depth >= MAX_PLAYOUT_DEPTH (e.g. 512): value = -c.q; break // collision guard ``` - `checkmated(pos)`: if the child node exists, read its state; otherwise use `pos.in_check() && !has_legal_move(pos)`. Mate takes precedence over the 50-move rule, as now. A repeated position cannot be mate, because the game continued from its first occurrence. - `create_node` = today's `evaluate_leaf` minus the path checks: movegen (mate or stalemate → terminal); insufficient material → `TERMINAL_DRAW` (never at the root); then the ValueHash probe; then `eval::value`. - `expand` is unchanged apart from writing edges (`child = 0, visits = draws = 0`). The priors are a snapshot from whichever path expanded the node, the same as today. - The root has no path checks (they apply to children), so it is never declared drawn, as today. The root is created through `create_node` (one evaluation) and expanded before the first playout. ### 3.4 Selection and root decisions - PUCT at n over edges: `Q(n,a)` as in 3.1 for `N(n,a) > 0`, FPU otherwise; exploration `cpuct(N(n)) · sqrt(N(n)) · P / (1 + N(n,a))`, using today's formula with `N(n)` in place of `node.visits`. In a tree `N(n)` equals today's `node.visits`. FPU = `−n.q − fpu_reduction·sqrt(Σ P over edges with N(n,a) > 0)`. Root cpuct is chosen by `idx == root`. - **Everything at the root uses edge visits:** best move (most `N(n,a)`, then edge Q, then prior), smart pruning (`root_start_visits_` = root edge visits at search start), score (`Q` of the best edge), `print_info`, the dashboard rows. - **PV:** follow the best edge from each node. Stop when `child == 0`, `visits == 0`, after 64 plies, or after a move whose position repeats the PV or the history. Cycles make the 64-ply cap necessary, not cosmetic. ### 3.5 Repetition, 50-move and cycles **Decision: key = the position only (today's Zobrist). Detect repetition and 50-move draws on every descent, after `make_move` and before the table lookup. Record them per edge as a draw count `D(n,a)`, never in a node. The reversible-window key with threshold T is variant 5d.** Why counts and not a per-edge flag: an edge belongs to its parent node, and the parent node is shared by every path that reaches it. A move can be a repetition on one path to n and a fresh position on another. A sticky flag, as in Lc0's `Node`, makes every later path see a draw. A count makes the edge value the visit-weighted mixture of what the paths actually produced. Ceres does this with `NDrawByRepetition` and the same formula. Both are approximations. Only the count stays consistent as path frequencies change. Why not put history in the key from the start (Lc0's rule-50 ply plus repetition count, Ceres's history mode, Czech's step counter): 1. **It removes much of the merging.** Two move orders reach the same position with a different halfmove clock whenever their pawn moves fall in a different order. For example, `1.e4 Nc6 2.Nf3` has halfmove 2 and `1.Nf3 Nc6 2.e4` has halfmove 0. A reversible-window key also refuses every transposition between piece manoeuvres, which is where deep transpositions come from. 2. **The pure-position key is the KataGo and Ceres default** (Ceres's `PositionEquivalence`), and every other option is a strict refinement. A threshold variant (5d) can be added later without touching anything else. 3. **The error is bounded.** The value a shared node carries is a mixture over real paths, never a fabricated draw. Repetition-sensitive positions (long reversible sequences, perpetuals, fortresses) are exactly where 5d splits nodes, and 5d's SPRT decides whether that is worth the lost merging. Variant 5d, for comparison: when `halfmove >= T`, the key additionally mixes in a **multiset** hash of the positions in the current reversible window (splitmix64 of each key, summed mod 2^64 so that order does not matter and there is no XOR cancellation; the hash resets at each zeroing move, as in Ceres). Below T the key is the position. Above T, paths with different reversible histories get different nodes, so neither repetition nor the 50-move proximity mixes there. The window multiset fixes its own length, so the halfmove clock is fixed too. T = ∞ is the base. Path detection stays in either case, because repetitions within the window must still score as draws. **Cycles cannot cause infinite descent.** A cycle in the position graph uses only reversible moves: a capture, a pawn move or a lost castling right changes the position for good. So a playout that would re-enter a position already on its path finds that position's key in `history_` within `halfmove` plies, with the same side to move, at distance ≥ 4. `is_repetition` sees it and ends the playout as a draw before the node is entered. A path therefore never contains a node twice, and its length is bounded. `MAX_PLAYOUT_DEPTH` only guards against a hash collision linking unrelated positions (see the next point). **There is no unbounded value feedback.** Nodes can still depend on each other through a cycle: X→Y on one path, Y→X on another. But each recompute is a convex combination: weights `base` and `W(n,a)` over `N(n)`, values in [-1, 1], draw visits at 0. So every Q stays in [-1, 1] and only nodes on the path change. There is no iteration to a fixed point, so nothing can diverge. The remaining error is GHI's draw-last kind: Y's value includes X's value on paths where going back to X would be a draw. The draw counts on that edge pull it towards 0 in proportion to how often that actually happened. **Collisions.** The table compares the full 64-bit key plus a 16-bit `check = u16(mix64(colors[WHITE] ^ rotl(pieces[PAWN], 17) ^ rotl(pieces[KING], 41)))` that is independent of the Zobrist key. That makes about 80 bits. With 2·10^6 nodes the chance of any false merge is about `n²/2^81 ≈ 2·10^-12` per search. Without the check, 64 bits would give about `10^-7` per search, which is fine for games but not for long analysis. The root is additionally re-validated at search start: its edges must equal `generate_legal(root)`, otherwise the graph is cleared. Illegal-move protection inside the graph rests on the 80-bit check. VERIFY builds check legality of every edge (3.8). ### 3.6 Reuse and GC on a DAG **Mark, then slide both arenas, then rebuild the table.** 1. **Mark.** Do a DFS from the root over `edge.child`, with a visited bitmap. Pruning rule with threshold T: a reachable node with `N < T` (other than the root) loses its edges. It keeps `visits`. It sets `u = q` (the current mover-view Q) and `base = visits`, and `state = UNEXPANDED`. Its edges and anything reachable only through them are dropped. `q` is unchanged, so no value is lost, which matches today's behaviour. 2. **Threshold.** Same histogram as today: `kept(T) ≈ Σ over reachable nodes with N ≥ T of (edges + edge targets)`. In a tree this is exact and equals today's rule. In a DAG, reachability through pruned nodes can only lower the real number, so `kept ≤ estimate ≤ target`. The policy therefore does not assume monotone visits for safety, only for tightness. 3. **Forwarding.** `fwd_node[old] → new` for marked nodes, in index order. The edge blocks of kept expanded nodes are sorted by `first_edge` and given new starts in that order. Both arenas then slide toward the front in increasing index order. Every destination is ≤ its source, so memmove in place is safe **regardless of allocation order**. The tree assumption is gone. 4. **Remap.** Remap `node.first_edge` from the block map and `edge.child` from `fwd_node`. A kept node's edges with a child always point to marked nodes, because marking follows exactly those edges. The root becomes `fwd_node[root]`. Make the root index a member, since `root()` can no longer be the constant 1. Null slot 0 stays. 5. **Table.** Clear it and reinsert every surviving node by its own key. This is O(nodes), like the rest of GC, and removes a whole class of remapping bugs. 6. **Reroot** = find the new root (walk the played moves along edges as today, or look its key up in the table; both find the same node in a graph), then mark/compact with T = 0. If the node is terminal, the graph starts fresh. That covers insufficient material, which must not be the root's state. 7. **Root-edge reconciliation** (step 4). After reroot, the game history is common to every path. For each root edge: if its move now gives a two-fold repetition against `history_`, set `D = N`, so the edge becomes a pure draw. If it does not but `D > 0`, those draws belonged to other histories: subtract them (`N −= D`, root `N −= D`, `D = 0`). Root edges are then exact. Ceres goes deeper with a depth-limited walk; that is not planned. ### 3.7 ValueHash and butterfly history - ValueHash stays in step 3, unchanged: it is probed in `create_node` and written for every path node (`−n.q`, visits). Path draws are never nodes, so they are never written. That is cleaner than today's `state != TERMINAL_DRAW` test. In a graph it only helps for positions the graph has dropped (after GC or reroot) or never held. Removing it is variant 5c. - Butterfly history is unchanged and path-based. The playout value is the leaf value, 0 for a path draw, or the stopped node's value (5a). ### 3.8 Debug tooling (`-DRIGBY_VERIFY_TREE`) Each node is visited once, by DFS from the root, carrying the position from the first path that reaches it. Positions are path-independent apart from the clock. The checks: - `node.key == pos.key` and `node.check` matches. `table.find(pos)` returns this node. The number of table entries equals the number of nodes after a rebuild. - Expanded: `num_edges == legal moves`, every `edge.move` legal and distinct, `first_edge + num_edges <= edges_used`. - `edge.draws <= edge.visits`. `edge.visits > edge.draws ⇒ child != 0`. `child < nodes_used`. - `node.visits == base + Σ edge.visits` (expanded nodes, root included from step 3). Terminal nodes have no edges. - **No path state in nodes:** `TERMINAL_LOSS ⇔` checkmate and `TERMINAL_DRAW ⇔` stalemate or insufficient material, recomputed from the position. - `|q| <= 1`, `|u| <= 1`, finite. - Step 2 only (still a tree): the in-degree of every node is exactly 1, the root's is 0. Unit-style checks run as a `verify` UCI command that exists only in VERIFY builds: - (a) Incremental key equals `set_fen(fen()).key` along random games, standard and 960. - (b) GC: snapshot every reachable node by key → (visits, q, edges by move → (visits, draws, child key)), force `collect_garbage`, compare all survivors. Do the same after `reroot`. - (c) Repetition leak: search positions with forced repetitions, then run the node-state check above. - (d) Table consistency after every GC. ### 3.9 Choices that affect later batching or multithreading - Edges have no `n_in_flight`. Virtual loss would need 2 more bytes per edge (20-byte edges), or packing `draws` into fewer bits. - Lazy child creation and table insert would need CAS on `edge.child` and on the table slot, plus per-thread allocation chunks. - `create_node` evaluates synchronously. Batching would need a "pending eval" state that selection treats as in flight. Nothing in this design writes a value that a pending node could not supply later. - Idempotent recompute reads children without locks. Storing a mean `q` (not N·Q) avoids KataGo's torn-read problem. Torn reads of `q` versus `visits` only make a value briefly stale. - GC and reroot are stop-the-world, which is fine with a pause-all-threads barrier. - Path draw detection uses each playout's own `history_` and is naturally per-thread. ### 3.10 Optional variants (each its own branch and SPRT, never bundled) - **5a Stop rule.** After linking or entering an existing child `c` with `c.N > N(n,a)` (before the increment), end the playout: value = `−c.q` (stm view at `c`), increment the edge, and recompute upward. Sub-variants: always stop; leaky (stop with probability p, e.g. 0.5). - **5b Edge-Q cache + incremental sum.** The edge stores the `c.q` it last folded in (+4 bytes, a 20-byte edge). The node stores `S = Σ W·q_seen`. The recompute is O(1): replace the path edge's term. Selection reads only contiguous edges. This trades staleness of off-path children for locality and NPS. - **5c ValueHash removal.** Give its 1/32 to the graph. - **5d Window-hash key for halfmove ≥ T** (3.5). Candidate T from the step-1 halfmove histogram of transposition hits. - Later, not planned: Lc0-style two-fold handling (history two-folds need a third occurrence); path-aware selection that scores an edge as 0 when it repeats on the current path; a deeper reconciliation walk. ## 4. Measurement design (step 1) Goal: bound what MCGS can gain before building it, and size the arenas. All counting is behind `-DRIGBY_STATS` (`make STATS=1`). The normal build is unchanged and bench-identical. **Runner:** a new UCI command `mcgsstats [hash_mb]` searches the 16 bench positions. It uses a fresh `Searcher` per position (no reuse, so results don't depend on order) and prints one row per position plus totals. Run it at **1000 ms and 5000 ms**, Hash 64. Also run 5000 ms at Hash 16 to see GC. **Transposition counters (exact).** These use an instrumentation-only `std::unordered_map` from key to the number of tree nodes with that key, updated at node creation and rebuilt after GC and reroot. A second map from key to the number of expanded nodes is kept the same way. | counter | meaning | what it bounds | | --- | --- | --- | | `leaf_tt` | playouts whose new leaf's key already exists in the tree | the brief's "transposition rate"; value evals MCGS could skip | | `leaf_tt_expanded` | ... and that existing node is expanded | how much subtree would be shared | | `vh_hits` | first visits answered by ValueHash today | what is already saved | | `exp_dup` | `expand()` calls for a key already expanded elsewhere | policy-net calls MCGS saves | | `path_tt` | playouts passing through ≥ 1 node whose key has ≥ 2 tree nodes | how many playouts touch shared structure | | `dup_nodes` | tree nodes / distinct keys, at the end | memory duplication | | `rep_draws`, `r50_draws` | playouts ending in a repetition or 50-move draw | how much the draw-count path is exercised | | `tt_halfmove_hist` | histogram of `pos.halfmove` at `leaf_tt` hits: 0, 1–3, 4–7, 8–15, 16–31, 32–63, ≥64 | upper bound of merges lost by variant 5d for each T | | `visited / allocated` | nodes with visits > 0 / all nodes, at the end | edges-per-node ratio r for the arena split (3.2) | **Time split.** Use `__rdtsc()` on x86 (`std::chrono::steady_clock` elsewhere) around these parts, cumulative per search: value (`eval::value`, i.e. net + qsearch); policy (`eval::policy` inside `expand`); movegen in `evaluate_leaf` and `expand`; `select_child`; backprop loop; ValueHash probe and store; `make_move` in `playout`; total `playout()`. Report each as a share of total playout cycles. The timer overhead (≈ 10 reads × 20–40 cycles) is small against a playout. The shares are from a stats build and labelled as such. **How the numbers bound the gain** (to be filled with measured values in `mcgs-log.md`): - Search time MCGS could free is at most `f_value · max(0, leaf_tt − vh_hits) + f_policy · exp_dup`. `f_*` are the time shares, and the rates are per playout or per expansion. - From the opposite direction, MCGS adds a table lookup per new node plus a recompute over the edges of each path node (about the cost of one more `select_child` per path node). An upper bound for that is `f_select + f_backprop` today. Steps 2 and 3 measure the real NPS cost. - The effect of sharing subtree statistics (deeper effective search, the actual point of MCGS) is not bounded by any of this. Only the SPRT measures it. - Cross-check: the ValueHash comment claims 37–85 % of leaf evaluations repeat a position. `leaf_tt` should land in that range, or the counters are wrong. ## 5. Implementation plan Each step: its own branch from `main` (or from the previous step once merged), small commits, every correctness gate from section 6 passed, `mcgs-log.md` updated (branch, commit, bench; SPRT link and outcome left empty for the owner). No step merges to main by itself. Changes to the brief's suggested order, and why: - **The DAG-capable compaction (forwarding tables, two arenas, no allocation-order assumption) moves into step 2.** It must exist before step 3 can create a graph. Otherwise step 3 would have to disable GC and reuse, and its SPRT would mix MCGS with "no tree reuse". - **Step 4 shrinks** to the DAG-specific reuse behaviour (root-edge reconciliation) plus table and arena sizing. ### Step 1: instrumentation (measurement only) - **Branch:** `mcgs-stats`. - **Files:** `src/mcts.h`, `src/mcts.cpp`, `src/uci.cpp`, `Makefile` (`STATS=1` adds `-DRIGBY_STATS`), and a new `src/stats.h` if that keeps `mcts.cpp` tidy. - **Brief:** Add the counters and timers of section 4, all under `#ifdef RIGBY_STATS`, and the `mcgsstats` command, also stats-only. Do not change search behaviour. - The key→count maps are instrumentation-only and must be rebuilt after `collect_garbage` and `reroot`. Walk the tree from the root and recompute each node's key from its position. - `rep_draws` / `r50_draws` count playouts that end at a `TERMINAL_DRAW` node whose reason was repetition or 50-move. Record the reason in a stats-only side table indexed by node, or recompute it. - Run `mcgsstats 1000`, `mcgsstats 5000`, `mcgsstats 5000 16`. Put the tables and the derived bounds into `mcgs-log.md` under "Step 1 measurements", labelled as stats-build numbers. - **Acceptance:** the normal build is bench-identical (`663779`, or main's current bench if main moved), and the `STATS=1` build is also bench-identical. The stats code must not change search. No new warnings. Cross-check: `leaf_tt` is in the same range as the ValueHash comment's 37–85 %. - **Verification:** build both variants, `bench` on both, `perftsuite`, and one VERIFY build search to make sure nothing broke. - **SPRT:** none. The code is compiled out of the shipped build and the bench is unchanged. - **Merge:** never. The branch stays on its own (owner's decision, 2026-11-16). Later steps branch from `main`, not from `mcgs-stats`. To measure a later branch with the stats build (e.g. when an SPRT disappoints), merge `mcgs-stats` into a throwaway local branch, measure, and delete it. The stats code never enters a step branch. Conflicts are expected once step 2 reshapes `mcts.cpp`, so port the counters by hand on the throwaway branch. ### Step 2: Edge/Node split with tree behaviour preserved - **Branch:** `mcgs-step2-split`. - **Files:** `src/mcts.h`, `src/mcts.cpp`. `src/pretty.*` only if the dashboard rows need new fields (they should not). - **Brief:** 1. Introduce `Edge` (16 B) and the 32-byte `Node` of 3.2, in two arenas. 2. Expansion writes an edge block. A child `Node` is created only when its edge is first selected. 3. Edge visits are kept equal to child visits. In a tree they are identical, and selection, FPU and root decisions switch to reading `edge.visits` (and `edge.policy`) now, with `child.q` for Q. 4. Keep the incremental `q` update and every float operation in the same order. The point is bit-identical search. `u`/`base`/`key`/`check` and `edge.draws` exist but are unused (or set and ignored). 5. Path-dependent draws stay in `node.state` for now. That is still correct in a tree, and it moves in step 3. 6. Make the root index a member. 7. Replace `compact` and `prune_threshold` with the mark → forwarding → slide → remap scheme of 3.6 for two arenas. No table yet. Keep the tree-exact threshold rule. The pruned node keeps visits and q, as today. 8. Extend `verify_tree` per 3.8 (tree subset, in-degree 1) and add the `verify` command with checks (a) and (b). 9. Hash is split between the arenas by the step-1 ratio. Document the split in a comment. 10. In its own commit, add the Chess960 perft suite as `tests/fischer.epd` (960 positions, `;D1`..`;D6`, sha256 `4bc384f273d8ce9312bfde78484dce503c8d1b51b43aacc6352646b3c270b3cd`). An untracked copy is at `tests/fischer.epd` in the main checkout (`C:\Users\rektd\repos\Rigby`). Check the hash before committing it. It enters `main` with this step. - **Acceptance:** - `bench` identical to main. - The reuse sequence from section 6 gives identical `bestmove` and `info` node counts versus main at Hash 256, where no GC happens. - All VERIFY runs clean, including forced-GC runs (Hash 1 and 2). Under GC the output may differ from main, because the bytes per node differ. That is expected; state it. - `perftsuite` and 960 perft clean. No new warnings. - **Report:** NPS (bench nps, and playouts/s at 5 s on the bench positions) versus main, labelled as a local measurement. - **SPRT:** **Non-Regression `[-5.00, 0.00]`, STC 8.0+0.08, Threads=1, Hash=64**, book `UHO_Lichess_4852_v1.epd`, adjudication as in the earlier Rigby tests. It is a hot-path refactor (two arenas, lazy creation, an extra indirection), and GC timing changes with the bytes per node, so play can differ even though bench does not. Non-regression is the right question for a refactor. If NPS drops by more than 3 %, also run LTC 40.0+0.40 Hash=256 Non-Regression, because GC matters more at LTC. ### Step 3: MCGS core (one self-consistent commit series) - **Branch:** `mcgs-step3-core`, from step 2. - **Files:** `src/mcts.h`, `src/mcts.cpp`, `src/movegen.cpp` only if a cheap `checkmated` helper is needed. - **Brief:** Implement 3.1–3.5 and the table rebuild in GC (3.6.5): - The key table with the 80-bit check. - `create_node` (today's `evaluate_leaf` without path checks), with the root created and evaluated through it. - Descent with path draws before the lookup, lazy linking to existing nodes, and `MAX_PLAYOUT_DEPTH`. - Backprop: - for each path node from the leaf's parent up: `edge.visits++` (`edge.draws++` for a path draw), `node.visits++`, recompute `q` by the 3.1 formula (sum in `double`); - the leaf: a new node has `N = base = 1`; a terminal node gets `N++`; - ValueHash store per path node; - the butterfly update as today. - Remove the repetition and 50-move checks from node creation, and the `TERMINAL_DRAW` test in the ValueHash store. - Root decisions, PV, info and dashboard on edges (3.4). - Root edge validation at search start. - VERIFY: the full 3.8 list, including check (c) and the table checks. - Arena and table sizing per 3.2. - No stop rule, no edge Q cache: those are variants. - **Acceptance:** - All gates in section 6. - The bench changes. Explain it in the commit message: the tree becomes a graph (transpositions share nodes, so playout depths and the visited positions change); the root gets an evaluation and `N = 1 + Σ`; and repetitions are now judged per playout instead of once per node. - VERIFY self-play: at least 20 games at a fixed-nodes TC with no abort. - Report labelled numbers: NPS versus step 2, and the measured transposition rate (share of node lookups that hit). - **SPRT:** - **STC 8.0+0.08, `[0.00, 5.00]`, Threads=1, Hash=64**, and **LTC 40.0+0.40, `[0.00, 5.00]`, Threads=1, Hash=256**, both with `UHO_Lichess_4852_v1.epd`. Run both, because the expected gain grows with search size (Czech et al.). LTC gets more Hash because 5× the nodes at 64 MB would GC constantly. 256 MB is roughly the node growth (5×, rounded to a power of two). Eleanor's OpenBench presets scale Hash by 8× from STC to LTC, which would be 512 MB; either is defensible, but keep the same value across all MCGS LTC tests. Both sides always get the same Hash. Rigby has had no LTC test before (the server's index shows only 8.0+0.08), so the LTC preset has to be created. - Suggested merge rule (the owner decides): merge if LTC passes and STC passes, or STC is inconclusive but a follow-up STC Non-Regression `[-5.00, 0.00]` passes. - If both fail or stall, do not tune. Investigate with the stats build: transposition hit rate, NPS loss, depth distribution, draw counts. ### Step 4: DAG-aware reuse polish - **Branch:** `mcgs-step4-reuse`, from step 3. - **Files:** `src/mcts.cpp`. - **Brief:** - Root-edge reconciliation (3.6.7) after every reroot. - Reroot by table lookup, with the move walk kept as a cross-check in VERIFY builds. - Confirm that GC's kept size stays ≤ target on DAGs (log it in VERIFY builds). - Re-measure the arena split at the end of 5 s searches with transpositions and adjust it if one arena fills first. - Add check (b) for a rerooted graph. - **Acceptance:** all gates. Bench unchanged versus step 3, because bench has no reuse; state this. A scripted game sequence shows the reconciled root edges (log the count in `info string`). - **SPRT:** STC `[0.00, 5.00]` Hash=64. If the arena re-split changes memory use noticeably, also LTC `[0.00, 5.00]` Hash=256. ### Step 5: variants (each separate) Each variant gets its own branch from the current MCGS head, a single concern, all gates, and its own SPRT. Never bundle them. | branch | change | SPRT | | --- | --- | --- | | `mcgs-v-stop` | 5a stop rule, always-stop | STC + LTC `[0.00, 5.00]` | | `mcgs-v-stop-leaky` | 5a leaky, p = 0.5 (only after `mcgs-v-stop` has a result) | STC + LTC `[0.00, 5.00]` | | `mcgs-v-edgeq` | 5b edge-Q cache + incremental sum | STC `[0.00, 5.00]` (it is mostly an NPS trade) | | `mcgs-v-novaluehash` | 5c remove ValueHash, memory to the graph | Non-Regression STC `[-5.00, 0.00]` (a simplification) | | `mcgs-v-window-T` | 5d window-hash key for halfmove ≥ T, T from the step-1 histogram | STC + LTC `[0.00, 5.00]` | - Bench changes for every variant except possibly 5c, which changes it only where ValueHash hits mattered. That is almost certainly a change too. Explain each. - **If a variant is inconclusive or negative:** measure before tuning. For example: the stop rule's share of stopped playouts and the change in depth; 5b's NPS gain and how stale the stored Q is (|q_seen − c.q| histogram); 5d's share of node lookups split by the window. ## 6. Test reference (correctness gates) Run them on Windows with the repo Makefile (clang++, MinGW target), from the repo root. ```bash make -j EXE=rigby-dev ``` ```bash make -j EXE=rigby-verify OBJ_DIR=obj-verify CXX="clang++ -DRIGBY_VERIFY_TREE" ``` This works with today's Makefile: command-line variables override `OBJ_DIR`, and `CXX` still contains "clang", so the MinGW target is kept. The separate `OBJ_DIR` keeps the VERIFY objects from mixing with the normal build. Delete `obj-verify/` afterwards, since `.gitignore` does not cover it. A `STATS=1` build (step 1) works the same way with `OBJ_DIR=obj-stats`. Checked in this session: on main, `setoption name Hash value 1`, `go nodes 300000` from startpos runs dozens of collections and every one passes `verify_tree`. UCI searches must be driven so that the next `position` waits for `bestmove`, because `position` stops a running search. Piping all commands at once silently cuts the searches short. Use a small driver that waits for `bestmove` (Python stdlib is enough; keep it outside the repo or under `tools/`). - **Build:** zero new warnings (`-Wall -Wextra`). - **Perft:** `perftsuite` all pass. `perftfile tests/fischer.epd 5` all pass (960 positions, about 52 s on this machine; main at c8d1ca6 passes). - **Bench:** `bench`. Identical for steps 1, 2 and 4 (stated per step). Changed and explained for 3 and 5. - **VERIFY searches**, with a VERIFY build over UCI, `go nodes 200000` unless noted: - `position startpos` and `position startpos moves e2e4 e7e5 g1f3 b8c6 f1c4 g8f6` (transpositions). - `position startpos moves g1f3 g8f6 f3g1 f6g8 g1f3 g8f6` (history repetition at the root's children). - Bench positions 11, 12 and 15 (`8/8/3k4/...`, `8/5pk1/...`, `8/8/8/4k3/8/8/2KR4/8 w - -`), which are endgames with long reversible play. - `8/8/8/4k3/8/8/2KR4/8 w - - 95 100`: 50-move draws at depth 5+ must appear as edge draws, never as node states. - `6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1` (mate in 1, Rd8#). - A Chess960 start, e.g. `bqnb1rkr/pp3ppp/3ppn2/2p5/5P2/P2P4/NPP1P1PP/BQ1BNRKR w HFhf - 2 9` with `UCI_Chess960 true`. - **Tree reuse:** one session with `position startpos`, `go nodes 50000`, then `position startpos moves `, `go nodes 50000`, repeated for 10 moves. - **Forced GC:** `setoption name Hash value 1`, `go nodes 300000` on startpos and on the 960 position (several `tree collected` lines expected). - **`verify` command** (VERIFY builds, from step 2 on): checks (a)–(d) of 3.8. - **Smoke:** `go nodes 1`, `go nodes 2`, and `go depth 1` on the positions above. Then self-play with `C:\Users\rektd\repos\OpenBench\Client\cutechess-ob.exe`: 100 games of dev vs base at 2.0+0.02, Hash 16, which forces GC, and 20 games of the VERIFY build vs itself at `nodes=20000`. Look for illegal moves, disconnects, timeouts and aborts. Results are not strength evidence. ## 7. Questions for the owner Answered on 2026-11-16: 1. **Chess960 perft EPD:** the owner did not know where it was. It was found in the Chess960 session's scratchpad and verified (section 1). Step 2 commits it. 2. **Book and LTC:** use the settings of previous tests. Tests 5307–5309 use `UHO_Lichess_4852_v1.epd`, Threads=1, Hash=64, 8.0+0.08, win adjudication `movecount=3 score=400`, draw adjudication `movenumber=40 movecount=8 score=10`. There was no earlier Rigby LTC, so the plan uses 40.0+0.40 with Hash=256 (section 5, step 3). 3. **Step 1 merge:** the stats code stays on its branch and is never merged. Still open: 4. **Ordering change:** compaction moves into step 2 and step 4 becomes small (section 5). The plan assumes this until the owner says otherwise.