From 49b675eebc5bde7fe71f7d2b72a30428d0927942 Mon Sep 17 00:00:00 2001 From: cjus Date: Sun, 1 Nov 2026 16:33:43 -0700 Subject: [PATCH 1/3] CNP: search trees (engine/tree, engine/treeNode, capability tree) cb2026's node keeps search trees for Solrac's Engine Mind (Solrac Chess AI #350), as the Chess Node Protocol's new section 7.8 defines them. - A tree is recorded by Engine::search_tree on a fresh engine and a thread of its own (its own table, one thread, the switches at their defaults), so it is answered while a search runs and is the same tree every time. One at a time; a cancel stops it and keeps nothing; the node's maxTimeMs bounds it. - cb2026_engine::tree folds the log into nodes. Each node is its last search (window, score, children, decisions), after the decisions that say how it came to be searched that way; verification searches (null move, singular) and attempts that decided nothing are left out; each decision goes to the node it is about, so the singular, double and negative extensions move from the parent to the child. - The node says each note in alpha-beta's terms (cutoff, table, tablebase, nullMove, nodePruned, movePruned, reduced, extended, research), naming the switch behind it, with mates counted from the node and each score's bound read against the window of its last search. - Trees are kept five minutes after their last use, eight and 2,000,000 nodes and decisions at most, the one unused longest dropped first; up to depth 24 and six plies, 500,000 events a recording. - search_tree takes a stop flag, and a recorded tree brackets the root's searches (not counted in the statistics), so an aspiration re-search shows. - The cnp pin moves to cjus/chess-node-protocol#22's branch (68cf80d), whose six new sessions cb2026 passes. No functional change. Bench: 767812 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 4 +- Cargo.toml | 4 +- crates/cli/tests/cnp.rs | 7 +- crates/cnp/src/lib.rs | 263 +++++++++++- crates/cnp/src/tree.rs | 834 ++++++++++++++++++++++++++++++++++++ crates/engine/src/lib.rs | 16 +- crates/engine/src/search.rs | 26 +- crates/engine/src/stats.rs | 4 +- crates/engine/src/tree.rs | 572 +++++++++++++++++++++++++ crates/shell/src/explain.rs | 1 + docs/PRD.md | 7 +- docs/status.md | 17 +- 12 files changed, 1731 insertions(+), 24 deletions(-) create mode 100644 crates/cnp/src/tree.rs create mode 100644 crates/engine/src/tree.rs diff --git a/Cargo.lock b/Cargo.lock index 596fa47..43265f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -214,7 +214,7 @@ checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "cnp" version = "0.1.0" -source = "git+https://github.com/cjus/chess-node-protocol?rev=3791c23d98303a5f541171fa6d23af5a6bb53b1b#3791c23d98303a5f541171fa6d23af5a6bb53b1b" +source = "git+https://github.com/cjus/chess-node-protocol?rev=68cf80d917066de0e366952b334eb82a65fa42d6#68cf80d917066de0e366952b334eb82a65fa42d6" dependencies = [ "serde", "serde_json", @@ -223,7 +223,7 @@ dependencies = [ [[package]] name = "cnp-conformance" version = "0.1.0" -source = "git+https://github.com/cjus/chess-node-protocol?rev=3791c23d98303a5f541171fa6d23af5a6bb53b1b#3791c23d98303a5f541171fa6d23af5a6bb53b1b" +source = "git+https://github.com/cjus/chess-node-protocol?rev=68cf80d917066de0e366952b334eb82a65fa42d6#68cf80d917066de0e366952b334eb82a65fa42d6" dependencies = [ "cnp", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 3c584b8..d2910ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,8 +41,8 @@ cb2026-tools = { path = "crates/tools" } cb2026-trainer = { path = "crates/trainer" } # The Chess Node Protocol, how Solrac talks to cb2026 (`crates/cnp`), and its conformance # sessions (Solrac Chess AI #98). Pinned to a commit; bump both together. -cnp = { git = "https://github.com/cjus/chess-node-protocol", rev = "3791c23d98303a5f541171fa6d23af5a6bb53b1b" } -cnp-conformance = { git = "https://github.com/cjus/chess-node-protocol", rev = "3791c23d98303a5f541171fa6d23af5a6bb53b1b" } +cnp = { git = "https://github.com/cjus/chess-node-protocol", rev = "68cf80d917066de0e366952b334eb82a65fa42d6" } +cnp-conformance = { git = "https://github.com/cjus/chess-node-protocol", rev = "68cf80d917066de0e366952b334eb82a65fa42d6" } # Lints shared by every crate (each crate opts in with `[lints] workspace = true`). [workspace.lints.rust] diff --git a/crates/cli/tests/cnp.rs b/crates/cli/tests/cnp.rs index 1d49008..aeaf124 100644 --- a/crates/cli/tests/cnp.rs +++ b/crates/cli/tests/cnp.rs @@ -4,7 +4,7 @@ //! The sessions come with the `cnp-conformance` crate ([`cnp_conformance::SESSIONS`]), so a //! new session there is checked here as soon as the protocol's pin is bumped. Sessions that need //! an engine capability cb2026 doesn't offer (a search window), or that are for a node without -//! one it does (pondering), are skipped, and the test says which. +//! one it does (pondering, the search tree), are skipped, and the test says which. use std::path::PathBuf; use std::time::Duration; @@ -69,13 +69,14 @@ fn cb2026_passes_every_conformance_session_that_applies() { let (failed, skipped) = run_all(&node(&["--cnp"])); assert!(failed.is_empty(), "failed:\n{}", failed.join("\n\n")); // Of the engine's sessions, only the window's needs a capability cb2026 doesn't offer, and - // two are for nodes without capabilities it has: pondering, and an evaluation's quiet line - // and piece values. + // three are for nodes without capabilities it has: pondering, an evaluation's quiet line + // and piece values, and the search tree. assert_eq!( skipped, vec![ "evaluate-quiet-pieces-unsupported (needs !engine.quiet, !engine.pieces)".to_string(), "ponder-unsupported (needs !engine.ponder)".to_string(), + "tree-unsupported (needs !engine.tree)".to_string(), "window (needs engine.window)".to_string(), ] ); diff --git a/crates/cnp/src/lib.rs b/crates/cnp/src/lib.rs index 9a1b873..e8579c1 100644 --- a/crates/cnp/src/lib.rs +++ b/crates/cnp/src/lib.rs @@ -9,7 +9,9 @@ //! version with the commit it was built from ([`build_version`], `1.0.0+f1638bcb6851`), so a //! client that keeps what the engine said, as Solrac's game review does, can tell builds apart. //! It ponders: a search with `"ponder": true` runs on the opponent's time until -//! `engine/ponderHit` (spec 7.7). +//! `engine/ponderHit` (spec 7.7). And it keeps search trees (spec 7.8): `engine/tree` records a +//! search's decisions near the root and `engine/treeNode` reads them a node at a time, so +//! Solrac's Engine Mind can say why cb2026 set a move aside (the `tree` module). //! `cb2026 --cnp` speaks it, and so does a plain `cb2026` whose first input line is JSON. //! //! ```text @@ -49,11 +51,16 @@ //! the same search throughout, so it keeps its tree, and its answer says how long it pondered //! (`ponderMs`). On a miss the client cancels it, and the next search is taken at once, as //! after any cancel. UCI's `go ponder` and `ponderhit` work the same way (`cb2026-protocol`). +//! - **A tree has an engine and a thread of its own** (the `tree` module), so it is answered while a +//! search runs, and is the same tree each time it is asked for. One at a time +//! (`maxConcurrentTrees` 1). The trees are kept for [`TREE_EXPIRY_MS`] after their last use, +//! at most [`MAX_TREES_KEPT`] of them, and `engine/treeNode` is answered in the loop, at once. //! //! ## What it offers //! //! Every engine capability except `window`: cb2026's search always starts with an open window -//! at the root. Pondering included. None of the other domains: voice, and the games, preferences +//! at the root. Pondering and the search tree included, the tree to [`MAX_TREE_DEPTH`] and +//! [`MAX_TREE_PLIES`]. None of the other domains: voice, and the games, preferences //! and backups that Solrac's own node keeps. Its techniques are the shell's switches //! ([`cb2026_shell::SWITCHES`]), by the names the shell's `set` uses. Its levels are [`RATINGS`], //! whole numbers only, since a level's settings are whole steps. A rating within [`ELO_RANGE`] @@ -96,6 +103,8 @@ #![forbid(unsafe_code)] +mod tree; + use std::collections::BTreeMap; use std::io::{self, BufRead, Read, Write}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -114,7 +123,7 @@ use cb2026_shell::SWITCHES; use cnp::engine::{ EloRange, EngineCapabilities, EngineProgress, Evaluate, EvaluateParams, EvaluateResult, Level, Levels, LevelsResult, Line, PieceValue, PonderHit, Progress, Search, SearchParams, SearchStats, - Stop, Technique, Techniques, TechniquesResult, Term, + Stop, Technique, Techniques, TechniquesResult, Term, Tree, TreeNodePage, }; use cnp::lifecycle::{ CancelRequest, Capabilities, IncompatibleVersionData, Initialize, InitializeResult, @@ -123,6 +132,11 @@ use cnp::lifecycle::{ use cnp::stdio::{ReadError, read_message, write_message}; use cnp::{Id, Message, Notification, Request, RequestMethod, Response, ResponseError, code}; +pub use tree::{ + MAX_TREE_DEPTH, MAX_TREE_ENTRIES_KEPT, MAX_TREE_PLIES, MAX_TREES_KEPT, TREE_EXPIRY_MS, + TREE_HASH_MB, TREE_MAX_EVENTS, +}; + /// The longest search the node runs, infinite ones included: an hour. pub const MAX_TIME_MS: u64 = 60 * 60 * 1000; @@ -298,6 +312,12 @@ struct Node { search: Option, /// The `game` hint of the last search, whose hash table the engine still holds. last_game: Option, + /// What each tree's engine is made from. + tree_setup: tree::TreeSetup, + /// The tree being recorded, if any. + recording: Option, + /// The trees kept for `engine/treeNode`, shared with the recording thread. + trees: Arc>, } /// A search request, checked and turned into the engine's terms. @@ -320,7 +340,8 @@ struct Prepared { impl Node { fn new(output: Output, engine: Engine, config: Config) -> Node { let mut fresh = Engine::new(); - let defaults = SWITCHES.iter().map(|s| *(s.flag)(&mut fresh)).collect(); + let defaults: Vec = SWITCHES.iter().map(|s| *(s.flag)(&mut fresh)).collect(); + let tree_setup = tree::TreeSetup::new(&engine, &defaults); let mut evaluator = fresh; evaluator.set_hash_size(EVALUATOR_HASH_MB); evaluator.params = engine.params.clone(); @@ -337,6 +358,9 @@ impl Node { defaults, search: None, last_game: None, + tree_setup, + recording: None, + trees: Arc::default(), } } @@ -389,6 +413,17 @@ impl Node { Ok(result) => Response::ok::(id, &result), Err(e) => Response::error(Some(id), e), }, + (State::Running, Tree::NAME) => match self.start_tree(&request) { + Ok(()) => return, + Err(e) => Response::error(Some(id), e), + }, + (State::Running, TreeNodePage::NAME) => match request + .params::() + .and_then(|params| tree::node_page(&self.trees, ¶ms)) + { + Ok(result) => Response::ok::(id, &result), + Err(e) => Response::error(Some(id), e), + }, (State::Running, method) => error( code::METHOD_NOT_FOUND, &format!("cb2026 has no method {method}"), @@ -409,6 +444,10 @@ impl Node { running.cancelled.store(true, Ordering::Relaxed); running.stop.store(true, Ordering::Relaxed); } + if let Some(recording) = self.recording.as_ref().filter(|r| r.id == params.id) { + recording.cancelled.store(true, Ordering::Relaxed); + recording.stop.store(true, Ordering::Relaxed); + } } fn initialize(&mut self, request: &Request) -> Response { @@ -453,6 +492,7 @@ impl Node { quiet: true, pieces: true, ponder: true, + tree: true, }), voice: None, preferences: None, @@ -466,6 +506,9 @@ impl Node { max_multipv: Some(MAX_MULTIPV), max_concurrent_searches: Some(1), max_message_bytes: None, + max_tree_depth: Some(MAX_TREE_DEPTH), + max_tree_plies: Some(MAX_TREE_PLIES), + max_concurrent_trees: Some(1), }, }; Response::ok::(id, &result) @@ -592,13 +635,46 @@ impl Node { } } - /// Cancels the running search, if any, and waits for it to answer. + /// Checks a tree request and starts recording it on its own thread, or says why not. + fn start_tree(&mut self, request: &Request) -> Result<(), ResponseError> { + let params = request.params::()?; + let prepared = tree::prepare(¶ms)?; + if let Some(recording) = self.recording.take() { + if recording.ending() { + // Answered and ending, or winding down after a cancel: a few milliseconds. + recording.join(&self.output); + } else { + self.recording = Some(recording); + return Err(ResponseError::new( + code::BUSY, + "cb2026 records one tree at a time", + )); + } + } + self.recording = Some(tree::start( + &self.tree_setup, + prepared, + request.id.clone(), + &self.output, + &self.trees, + )); + Ok(()) + } + + /// Cancels the running search and the tree being recorded, if any, waits for them to + /// answer, and forgets the kept trees. fn finish(&mut self) { if let Some(running) = self.search.take() { running.cancelled.store(true, Ordering::Relaxed); running.stop.store(true, Ordering::Relaxed); self.reclaim(running); } + if let Some(recording) = self.recording.take() { + recording.cancelled.store(true, Ordering::Relaxed); + recording.stop.store(true, Ordering::Relaxed); + recording.join(&self.output); + } + tree::lock(&self.trees).clear(); } /// The switchable techniques: the shell's switches, under the names `set` uses. @@ -1064,7 +1140,7 @@ mod tests { use cb2026_engine::time::TimeParams; use cnp::engine::{ Clock, PonderHitParams, Position as CnpPosition, SearchLimits, SideClock, StopParams, - Strength, Window, + Strength, TreeNodeParams, TreeParams, Window, }; fn search(fen: &str) -> SearchParams { @@ -1493,6 +1569,181 @@ mod tests { node.finish(); } + /// A tree request of the start position after `moves`. + fn tree_of(moves: &[&str], depth: u32, plies: u32) -> TreeParams { + TreeParams { + plies: Some(plies), + ..TreeParams::new( + CnpPosition::start().with_moves(moves.iter().copied()), + depth, + ) + } + } + + /// The error code of request `id`'s response. + fn error_code(capture: &Capture, id: i64) -> i64 { + capture.response(id).unwrap().outcome.unwrap_err().code + } + + #[test] + fn a_tree_is_answered_while_a_search_runs_and_read_a_node_at_a_time() { + let capture = Capture::default(); + let mut node = running_node(&capture); + let mut infinite = start(); + infinite.limits = SearchLimits::infinite(); + node.request(Request::new::(1, &infinite)); + let params = TreeParams { + limit: Some(3), + ..tree_of(&["e2e4", "e7e5"], 6, 2) + }; + node.request(Request::new::(2, ¶ms)); + let result = capture + .wait_for(2, Duration::from_secs(60)) + .expect("the tree answers while the search runs") + .result::() + .unwrap(); + assert!(capture.response(1).is_none(), "the search still runs"); + assert_eq!((result.depth, result.recorded.plies), (6, 2)); + assert!(!result.recorded.truncated); + assert_eq!(result.pv.first(), result.best_move.as_ref()); + // The root: every legal move entered, and the result's score, exact. + assert_eq!(result.root.mv, None); + assert_eq!(result.root.child_count, 29); + assert_eq!(result.root.score, result.score); + assert_eq!(result.root.score.unwrap().bound, cnp::engine::Bound::Exact); + assert_eq!(result.recorded.nodes, result.root.subtree + 1); + assert_eq!(result.children.len(), 3); + // A child's window is from its own side to move, below its parent's turned round. + let first = &result.children[0]; + assert_eq!(first.depth, 5); + assert!(first.score.is_some()); + + // The first child, read again, with a page of its own children. + let mv = first.mv.clone().unwrap(); + let page = TreeNodeParams { + offset: Some(1), + limit: Some(2), + ..TreeNodeParams::new(result.tree.clone(), [mv.clone()]) + }; + node.request(Request::new::(3, &page)); + let read = capture + .response(3) + .unwrap() + .result::() + .unwrap(); + assert_eq!(&read.node, first); + let all = TreeNodeParams::new(result.tree.clone(), [mv.clone()]); + node.request(Request::new::(4, &all)); + let every = capture + .response(4) + .unwrap() + .result::() + .unwrap(); + assert_eq!(every.children.len() as u32, first.child_count); + let expected: Vec<_> = every.children.iter().skip(1).take(2).cloned().collect(); + assert_eq!(read.children, expected); + // Past the last child, an empty page; a limit of 0, the node alone. + let past = TreeNodeParams { + offset: Some(first.child_count), + ..all.clone() + }; + node.request(Request::new::(5, &past)); + let past = capture + .response(5) + .unwrap() + .result::() + .unwrap(); + assert!(past.children.is_empty()); + + // A path the tree doesn't hold, and a handle it never gave. + let nowhere = TreeNodeParams::new(result.tree.clone(), [mv.as_str(), "e1e8"]); + node.request(Request::new::(6, &nowhere)); + assert_eq!(error_code(&capture, 6), code::INVALID_PARAMS); + node.request(Request::new::( + 7, + &TreeNodeParams::new("t99", [""; 0]), + )); + assert_eq!(error_code(&capture, 7), code::EXPIRED); + + // The same request records the same tree: its own engine, cleared, on one thread. + node.request(Request::new::(8, ¶ms)); + let again = capture + .wait_for(8, Duration::from_secs(60)) + .unwrap() + .result::() + .unwrap(); + assert_ne!(again.tree, result.tree); + assert_eq!( + (again.root, again.children, again.nodes, again.pv), + (result.root, result.children, result.nodes, result.pv) + ); + node.request(Request::new::(9, &StopParams { id: Id::Number(1) })); + assert!(capture.wait_for(1, Duration::from_secs(60)).is_some()); + node.finish(); + } + + #[test] + fn a_cancelled_tree_answers_cancelled_and_the_next_isn_t_busy() { + let capture = Capture::default(); + let mut node = running_node(&capture); + // Deep enough to be running when the cancel comes, and the next while it runs. + let deep = tree_of(&[], MAX_TREE_DEPTH, 2); + node.request(Request::new::(1, &deep)); + node.request(Request::new::(2, &deep)); + assert_eq!(error_code(&capture, 2), code::BUSY); + node.notification(&Notification::new::( + &cnp::lifecycle::CancelParams { id: Id::Number(1) }, + )); + node.request(Request::new::(3, &tree_of(&[], 2, 1))); + assert_eq!(error_code(&capture, 1), code::CANCELLED); + let next = capture.wait_for(3, Duration::from_secs(60)).unwrap(); + assert!(next.result::().is_ok(), "{next:?}"); + node.finish(); + // `shutdown` forgets the trees. + node.request(Request::new::( + 4, + &TreeNodeParams::new("t1", [""; 0]), + )); + assert_eq!(error_code(&capture, 4), code::EXPIRED); + } + + #[test] + fn a_tree_beyond_the_limits_or_of_an_illegal_position_is_refused() { + let capture = Capture::default(); + let mut node = running_node(&capture); + let cases = [ + (tree_of(&[], 0, 2), code::INVALID_PARAMS), + (tree_of(&[], 4, 0), code::INVALID_PARAMS), + (tree_of(&[], MAX_TREE_DEPTH + 1, 2), code::LIMIT_EXCEEDED), + (tree_of(&[], 4, MAX_TREE_PLIES + 1), code::LIMIT_EXCEEDED), + (tree_of(&["e2e5"], 4, 2), code::INVALID_POSITION), + ]; + for (id, (params, expected)) in (1..).zip(cases) { + node.request(Request::new::(id, ¶ms)); + assert_eq!(error_code(&capture, id), expected, "{params:?}"); + } + } + + #[test] + fn a_tree_of_a_position_with_no_legal_move_is_its_root_alone() { + let capture = Capture::default(); + let mut node = running_node(&capture); + let mated = tree_of(&["f2f3", "e7e5", "g2g4", "d8h4"], 8, 2); + node.request(Request::new::(1, &mated)); + let result = capture + .wait_for(1, Duration::from_secs(60)) + .unwrap() + .result::() + .unwrap(); + assert_eq!( + (result.best_move, result.score, result.depth), + (None, None, 0) + ); + assert_eq!((result.root.child_count, result.recorded.nodes), (0, 1)); + assert!(result.children.is_empty()); + node.finish(); + } + #[test] fn a_switch_s_name_is_its_description_without_the_note() { assert_eq!( diff --git a/crates/cnp/src/tree.rs b/crates/cnp/src/tree.rs new file mode 100644 index 0000000..14645d4 --- /dev/null +++ b/crates/cnp/src/tree.rs @@ -0,0 +1,834 @@ +//! `engine/tree` and `engine/treeNode` (spec 7.8): cb2026's search trees, recorded, kept for a +//! while, and read a node at a time. +//! +//! A tree request searches its position with [`Engine::search_tree`], which records the last +//! iteration's decisions near the root, folds the log into nodes ([`FoldedTree`]), keeps it +//! under a handle, and answers with the search's result, the root and its first children. +//! `engine/treeNode` then reads any node by the moves that lead to it. +//! +//! ## How it works +//! +//! - **Each tree has an engine of its own** ([`TreeSetup::engine`]): a fresh one, with its own +//! [`TREE_HASH_MB`] table and one thread, configured as every search starts (the switches at +//! their defaults), with the main engine's evaluation, network and tablebases. So a tree is +//! its own deterministic search, the same tree each time it is asked for, and it runs while +//! a search runs: the main engine belongs to that search's thread. +//! - **It is recorded on a thread of its own,** as a search is, so the command loop goes on +//! answering `ping`, `engine/stop` and cancels. One tree at a time (`maxConcurrentTrees` 1): +//! another that comes while one is recorded is `Busy`, unless that one is ending. A cancel +//! stops its search, and it answers `Cancelled` and keeps nothing. `engine/stop` doesn't +//! apply: a tree is wanted whole or not at all. The node's `maxTimeMs` bounds it, as it does +//! every search, and a tree that reaches it is `LimitExceeded`. +//! - **The trees are kept in a [`TreeStore`]**, shared by the recording thread, which adds a +//! tree just before it answers, and the command loop, which reads them. A tree unused for +//! [`TREE_EXPIRY_MS`] expires; past [`MAX_TREES_KEPT`] trees, or [`MAX_TREE_ENTRIES_KEPT`] +//! nodes and decisions in all, the tree unused longest goes first. A handle names one tree +//! and is never given twice, so an expired handle is `Expired`, never someone else's tree. +//! - **A tree is kept folded, as the engine's values,** and turned into CNP's terms when a node +//! is read: a few hundred bytes a node instead of the log's every event. +//! +//! ## Decisions in CNP's terms +//! +//! [`decision`] says each of the engine's notes in alpha-beta's terms (spec 7.8), naming the +//! switch behind it ([`cb2026_shell::SWITCHES`]) as its `technique`: +//! +//! | The engine's note | CNP's decision | Technique | +//! | --- | --- | --- | +//! | `BetaCutoff(m, i)` | `cutoff`, `move` m, `order` i | `alphabeta` | +//! | `TtCutoff` | `table` | `tt` | +//! | `Tablebase` | `tablebase` | | +//! | `NullMoveCutoff` | `nullMove` | `nullmove` | +//! | `ReverseFutility`, `Razoring`, `MultiCut` | `nodePruned` | `rfp`, `razoring`, `multicut` | +//! | `ProbCutCutoff(m)` | `nodePruned`, `move` m | `probcut` | +//! | `LateMovePruning(m)`, `HistoryPruning(m)`, `Futility(m)`, `SeePruning(m)`, `DeltaPruning(m)` | `movePruned`, `move` m | `lmp`, `histprune`, `futility`, `seeprune`, `delta` | +//! | `Reduced(_, n)` | `reduced`, `plies` n | `lmr` | +//! | `NegativeExtension(_)` | `reduced`, `plies` [`SearchParams::negative_extension_plies`] | `negext` | +//! | `SingularExtension(_)`, `DoubleExtension(_)` | `extended`, `plies` 1 | `singular`, `doubleext` | +//! | `ReductionResearch(_)` | `research`, `reason` `depth` | `lmr` | +//! | `PvsResearch(_)` | `research`, `reason` `window` | `pvs` | +//! | Each search of the root before its last ([`FoldedTree::root_searches`]) | `research`, `reason` `window`, at the root | `aspiration` | +//! +//! The rest are attempts that decided nothing (a table entry too shallow, a null move or +//! ProbCut tried, a singular extension's search started) or the brackets of a node's search, +//! which become its window and score; the fold leaves them out. +//! +//! ## Pitfalls +//! +//! - **Mates are counted from the node,** not from the root as the search counts them +//! ([`to_score_at`]), so a node's `{"mate": 1}` is a mate in one from that node. +//! - **A node's bound is read against the window of its last search,** the one that gave its +//! score. Its first window would misread a reduced move searched again: its null window's +//! edge is not the full window's. +//! - **The root's window is its last aspiration window,** which cb2026 widens until the +//! score falls inside it, so the root's score is exact. Its earlier searches show as its +//! `research` decisions, and every node below is its last search (see [`FoldedTree`]). +//! - **A recording past [`TREE_MAX_EVENTS`] stops,** and the tree is `truncated`: the later +//! root moves are then missing, not just deep nodes. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +use cb2026_chess::{Move, Position}; +use cb2026_engine::eval::EvalParams; +use cb2026_engine::search::{INFINITY, SearchParams, Techniques, to_score_at}; +use cb2026_engine::stats::{Note, SearchTree}; +use cb2026_engine::tablebase::{Tablebase, TablebaseParams}; +use cb2026_engine::tree::FoldedTree; +use cb2026_engine::{Engine, Network, SearchInfo}; +use cb2026_shell::SWITCHES; +use cnp::engine::{ + Bound, Decision, DecisionKind, Recorded, ResearchReason, Tree, TreeNode, TreeNodeParams, + TreeNodeResult, TreeParams, TreeResult, +}; +use cnp::{Id, Response, ResponseError, code}; + +use crate::{MAX_TIME_MS, Output, WATCHDOG_POLL, millis, moves, read_position, score, send}; + +/// The deepest tree the node records (`maxTreeDepth`). On an M1 Max a depth-16 tree took +/// 0.5–1.1 s and a depth-24 one 11–15 s, in an opening and a middlegame: 24 is about as long as +/// a player would wait, and a guard against a tree that would take hours. +pub const MAX_TREE_DEPTH: u32 = 24; + +/// The most plies from the root a tree records (`maxTreePlies`). Each ply more multiplies the +/// nodes by the replies searched at each, three to five: a depth-16 tree held 560–900 nodes +/// at three plies and 6,300–9,300, with 16,000–23,000 decisions, at six. +pub const MAX_TREE_PLIES: u32 = 6; + +/// The most events one recording keeps, the search's every decision near the root, `Enter` and +/// `Exit` included ([`Engine::search_tree`]'s `max_events`). Past it the tree is truncated. +/// Depth-14 trees of six plies recorded up to 218,000; an event takes about 70 bytes until the +/// log is folded. +pub const TREE_MAX_EVENTS: usize = 500_000; + +/// How long a tree is kept with no request for it, in milliseconds (the result's `expiresMs`): +/// long enough to look round a position, short enough that trees don't pile up. +pub const TREE_EXPIRY_MS: u64 = 5 * 60 * 1000; + +/// The most trees kept at once. Past it, the tree unused longest goes. +pub const MAX_TREES_KEPT: usize = 8; + +/// The most nodes and decisions the kept trees may hold together, about 25 bytes each. Past +/// it, the trees unused longest go, but never the newest. +pub const MAX_TREE_ENTRIES_KEPT: usize = 2_000_000; + +/// The hash table of a tree's engine, in megabytes: the engine's default size, plenty for +/// the second or so a tree's search takes on one thread. +pub const TREE_HASH_MB: usize = cb2026_engine::tt::DEFAULT_HASH_MB; + +/// What a tree's engine is made from: the main engine's evaluation, network and tablebases, as +/// they came configured, and its switches at their defaults, as every search starts. +pub(crate) struct TreeSetup { + params: EvalParams, + search_params: SearchParams, + techniques: Techniques, + network: Option>, + tablebase: Option>, + tablebase_params: TablebaseParams, +} + +impl TreeSetup { + /// The setup of trees searched as `engine` searches, with the switches at `defaults` (in + /// [`SWITCHES`]' order). + pub(crate) fn new(engine: &Engine, defaults: &[bool]) -> TreeSetup { + let mut template = Engine::new(); + template.techniques = engine.techniques; + for (switch, &default) in SWITCHES.iter().zip(defaults) { + *(switch.flag)(&mut template) = default; + } + TreeSetup { + params: engine.params.clone(), + search_params: engine.search_params, + techniques: template.techniques, + network: engine.network.clone(), + tablebase: engine.tablebase.clone(), + tablebase_params: engine.tablebase_params, + } + } + + /// A fresh engine for one tree: a cleared table of its own, one thread. + fn engine(&self) -> Engine { + let mut engine = Engine::new(); + engine.set_hash_size(TREE_HASH_MB); + engine.params = self.params.clone(); + engine.search_params = self.search_params; + engine.techniques = self.techniques; + engine.network = self.network.clone(); + engine.tablebase = self.tablebase.clone(); + engine.tablebase_params = self.tablebase_params; + engine.threads = 1; + engine + } +} + +/// A tree request, checked and turned into the engine's terms. +pub(crate) struct PreparedTree { + position: Position, + history: Vec, + depth: u32, + plies: u32, + limit: Option, + chess960: bool, +} + +/// Checks a tree request: its depth and plies within the node's limits, and its position. +pub(crate) fn prepare(params: &TreeParams) -> Result { + let invalid = |message: String| ResponseError::new(code::INVALID_PARAMS, message); + let too_far = |message: String| ResponseError::new(code::LIMIT_EXCEEDED, message); + let plies = params.recorded_plies(); + match params.depth { + 0 => return Err(invalid("a tree's depth is at least 1".to_string())), + depth if depth > MAX_TREE_DEPTH => { + return Err(too_far(format!( + "a tree's depth is at most {MAX_TREE_DEPTH}" + ))); + } + _ => {} + } + match plies { + 0 => return Err(invalid("a tree records at least 1 ply".to_string())), + plies if plies > MAX_TREE_PLIES => { + return Err(too_far(format!( + "a tree records at most {MAX_TREE_PLIES} plies" + ))); + } + _ => {} + } + let (position, history) = read_position(¶ms.position)?; + Ok(PreparedTree { + position, + history, + depth: params.depth, + plies, + limit: params.limit, + chess960: params.position.chess960, + }) +} + +/// A tree being recorded on its own thread. +pub(crate) struct Recording { + /// Its request's id. + pub(crate) id: Id, + /// Tells its search to stop (a cancel, `shutdown`, or the watchdog). + pub(crate) stop: Arc, + /// Set by a cancel or `shutdown`: the answer is `Cancelled`, and nothing is kept. + pub(crate) cancelled: Arc, + /// Set just before it answers: from then on it only has to end. + answered: Arc, + /// The thread. + handle: JoinHandle<()>, +} + +impl Recording { + /// Whether it has finished, answered or been told to stop: it has at most a few + /// milliseconds left. + pub(crate) fn ending(&self) -> bool { + self.handle.is_finished() + || self.answered.load(Ordering::Acquire) + || self.stop.load(Ordering::Relaxed) + } + + /// Waits for its thread to end. If it failed before it answered, answers for it, so the + /// request still gets its one answer. + pub(crate) fn join(self, output: &Output) { + if self.handle.join().is_err() && !self.answered.load(Ordering::Acquire) { + let error = ResponseError::new(code::INTERNAL_ERROR, "the tree's search failed"); + send(output, Response::error(Some(self.id), error).into()); + } + } +} + +/// Starts recording a tree on its own thread, which answers the request. +pub(crate) fn start( + setup: &TreeSetup, + prepared: PreparedTree, + id: Id, + output: &Output, + trees: &Arc>, +) -> Recording { + // Taken here, when the request has been read: durations count from then (spec 1). + let start = Instant::now(); + let engine = setup.engine(); + let stop = Arc::new(AtomicBool::new(false)); + let cancelled = Arc::new(AtomicBool::new(false)); + let answered = Arc::new(AtomicBool::new(false)); + let handle = { + let (stop, cancelled, answered) = (stop.clone(), cancelled.clone(), answered.clone()); + let (id, output, trees) = (id.clone(), output.clone(), trees.clone()); + thread::spawn(move || { + let flags = RecordingFlags { + stop, + cancelled, + answered, + }; + record(engine, prepared, id, start, &flags, &output, &trees); + }) + }; + Recording { + id, + stop, + cancelled, + answered, + handle, + } +} + +/// The flags a recording thread shares with the command loop. +struct RecordingFlags { + stop: Arc, + cancelled: Arc, + answered: Arc, +} + +/// Records one tree, keeps it, and answers its request. +fn record( + mut engine: Engine, + prepared: PreparedTree, + id: Id, + start: Instant, + flags: &RecordingFlags, + output: &Output, + trees: &Mutex, +) { + let finished = Arc::new(AtomicBool::new(false)); + // The node's maxTimeMs bounds a tree's search as it does every search. + let watchdog = { + let (stop, finished) = (flags.stop.clone(), finished.clone()); + thread::spawn(move || { + let deadline = Duration::from_millis(MAX_TIME_MS); + while !finished.load(Ordering::Relaxed) { + if start.elapsed() >= deadline { + stop.store(true, Ordering::Relaxed); + return; + } + thread::sleep(WATCHDOG_POLL); + } + }) + }; + let plies = prepared.plies as usize; + // With no legal move there is nothing to search: the tree is its root alone. + let searched = (!prepared.position.legal_moves().is_empty()).then(|| { + engine.search_tree( + &prepared.position, + &prepared.history, + prepared.depth, + plies, + TREE_MAX_EVENTS, + &flags.stop, + ) + }); + finished.store(true, Ordering::Relaxed); + let _ = watchdog.join(); + // Checked last, so a cancel that arrived at any time is honoured. + let response = if flags.cancelled.load(Ordering::Relaxed) { + Response::error(Some(id), ResponseError::new(code::CANCELLED, "cancelled")) + } else if flags.stop.load(Ordering::Relaxed) { + let message = format!("the tree's search took longer than maxTimeMs ({MAX_TIME_MS} ms)"); + Response::error(Some(id), ResponseError::new(code::LIMIT_EXCEEDED, message)) + } else { + let (folded, info) = match searched { + Some((log, info)) => (FoldedTree::fold(&log), Some(info)), + None => (FoldedTree::fold(&SearchTree::new(plies, 0)), None), + }; + let kept = KeptTree { + handle: String::new(), + root: prepared.position, + chess960: prepared.chess960, + depth: info.as_ref().map_or(0, |info| info.depth), + score: info.as_ref().map(|info| score(info.score)), + negative_extension_plies: engine.search_params.negative_extension_plies, + tree: folded, + last_used: Instant::now(), + }; + let mut store = lock(trees); + let kept = store.keep(kept); + let result = tree_result(kept, info.as_ref(), millis(start.elapsed()), prepared.limit); + drop(store); + Response::ok::(id, &result) + }; + // Before the answer goes: once the client has it, it may ask for the next tree at once. + flags.answered.store(true, Ordering::Release); + send(output, response.into()); +} + +/// One kept tree. +pub(crate) struct KeptTree { + /// Its handle. + handle: String, + /// The position searched, with the moves before it played. + root: Position, + /// Whether moves are written as Chess960's castling. + chess960: bool, + /// The depth searched (0 with no legal move). + depth: u32, + /// The search's score, exact (none with no legal move). + score: Option, + /// What a negative extension takes off, for its `reduced` decision. + negative_extension_plies: u32, + /// The tree. + tree: FoldedTree, + /// When a request last used it. + last_used: Instant, +} + +impl KeptTree { + /// How many nodes and decisions it holds. + fn entries(&self) -> usize { + self.tree.nodes.len() + self.tree.decisions() + } +} + +/// The trees kept for `engine/treeNode`, oldest use first. +#[derive(Default)] +pub(crate) struct TreeStore { + /// How many handles have been given: the next is one more. + given: u64, + /// The trees, the one unused longest first. + trees: Vec, +} + +impl TreeStore { + /// Drops the trees unused for [`TREE_EXPIRY_MS`]. + fn expire(&mut self) { + let expiry = Duration::from_millis(TREE_EXPIRY_MS); + self.trees.retain(|tree| tree.last_used.elapsed() < expiry); + } + + /// Keeps `tree` under a new handle, making room by dropping the trees unused longest, and + /// returns it. + fn keep(&mut self, mut tree: KeptTree) -> &KeptTree { + self.expire(); + self.given += 1; + tree.handle = format!("t{}", self.given); + self.trees.push(tree); + let mut entries: usize = self.trees.iter().map(KeptTree::entries).sum(); + while self.trees.len() > 1 + && (self.trees.len() > MAX_TREES_KEPT || entries > MAX_TREE_ENTRIES_KEPT) + { + entries -= self.trees.remove(0).entries(); + } + self.trees.last().expect("just kept") + } + + /// The tree `handle` names, used now, if it is still kept. + fn used(&mut self, handle: &str) -> Option<&KeptTree> { + self.expire(); + let at = self.trees.iter().position(|tree| tree.handle == handle)?; + let mut tree = self.trees.remove(at); + tree.last_used = Instant::now(); + self.trees.push(tree); + self.trees.last() + } + + /// Forgets every tree (`shutdown`). + pub(crate) fn clear(&mut self) { + self.trees.clear(); + } +} + +/// The store, even if a recording thread failed while holding it: its trees are whole, since a +/// tree is added in one push. +pub(crate) fn lock(trees: &Mutex) -> MutexGuard<'_, TreeStore> { + trees + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// `engine/treeNode`: the node `params.path` leads to in its tree, and a page of its children. +pub(crate) fn node_page( + trees: &Mutex, + params: &TreeNodeParams, +) -> Result { + let mut store = lock(trees); + let kept = store.used(¶ms.tree).ok_or_else(|| { + ResponseError::new( + code::EXPIRED, + format!("no tree {}: it has expired; ask for it again", params.tree), + ) + })?; + let mut position = kept.root.clone(); + let mut at = FoldedTree::ROOT; + for (n, text) in params.path.iter().enumerate() { + let child = position.parse_uci_move(text).and_then(|mv| { + position.make_move(mv); + kept.tree.nodes[at] + .children + .iter() + .copied() + .find(|&child| kept.tree.nodes[child].mv == Some(mv)) + }); + at = child.ok_or_else(|| { + ResponseError::new( + code::INVALID_PARAMS, + format!("the tree has no node at {}", params.path[..=n].join(" ")), + ) + })?; + } + Ok(TreeNodeResult { + node: tree_node(kept, at), + children: page(kept, at, params.offset.unwrap_or(0), params.limit), + }) +} + +/// The tree's answer: its handle, the search's result, and the root with its first children. +fn tree_result( + kept: &KeptTree, + info: Option<&SearchInfo>, + time_ms: u64, + limit: Option, +) -> TreeResult { + let chess960 = kept.chess960; + TreeResult { + tree: kept.handle.clone(), + expires_ms: TREE_EXPIRY_MS, + depth: kept.depth, + sel_depth: info.map_or(0, |info| info.seldepth), + nodes: info.map_or(0, |info| info.nodes), + time_ms, + best_move: info + .and_then(|info| info.pv.first()) + .map(|mv| mv.to_uci(chess960)), + score: kept.score, + pv: info.map_or_else(Vec::new, |info| moves(&info.pv, chess960)), + recorded: Recorded { + plies: kept.tree.max_ply as u32, + nodes: kept.tree.nodes.len() as u64, + decisions: (kept.tree.decisions() + kept.tree.root_searches.saturating_sub(1)) as u64, + truncated: kept.tree.truncated, + }, + root: tree_node(kept, FoldedTree::ROOT), + children: page(kept, FoldedTree::ROOT, 0, limit), + } +} + +/// The children of node `at`, from `offset`, at most `limit` of them. +fn page(kept: &KeptTree, at: usize, offset: u32, limit: Option) -> Vec { + let children = &kept.tree.nodes[at].children; + let limit = limit.map_or(usize::MAX, |limit| limit as usize); + children + .iter() + .skip(offset as usize) + .take(limit) + .map(|&child| tree_node(kept, child)) + .collect() +} + +/// Node `at` in CNP's terms: its window and score from its side to move, mates counted from +/// it, the score bounded by the window of the search that gave it. +fn tree_node(kept: &KeptTree, at: usize) -> TreeNode { + let node = &kept.tree.nodes[at]; + let chess960 = kept.chess960; + let ply = node.ply as u32; + let edge = |value: i32| (value.abs() < INFINITY).then(|| score(to_score_at(value, ply))); + let (depth, alpha, beta, node_score) = match node.window { + // A root with no legal move, never searched: no window, no score. + None => (kept.depth, None, None, kept.score), + Some(window) => { + let bounded = node.score.map(|value| { + let bound = if value <= window.alpha { + Bound::Upper + } else if value >= window.beta { + Bound::Lower + } else { + Bound::Exact + }; + cnp::engine::Score { + bound, + ..score(to_score_at(value, ply)) + } + }); + (window.depth, edge(window.alpha), edge(window.beta), bounded) + } + }; + TreeNode { + mv: node.mv.map(|mv| mv.to_uci(chess960)), + depth, + alpha, + beta, + score: node_score, + child_count: node.children.len() as u32, + subtree: node.subtree as u64, + decisions: aspiration_researches(kept, at) + .chain( + node.notes + .iter() + .filter_map(|¬e| decision(note, chess960, kept.negative_extension_plies)), + ) + .collect(), + } +} + +/// At the root, a `research` for each of its searches before the last: an aspiration window +/// the score fell outside, widened and searched again. +fn aspiration_researches(kept: &KeptTree, at: usize) -> impl Iterator { + let earlier = if at == FoldedTree::ROOT { + kept.tree.root_searches.saturating_sub(1) + } else { + 0 + }; + std::iter::repeat_n( + Decision::new(DecisionKind::Research { + reason: ResearchReason::Window, + }) + .by("aspiration"), + earlier, + ) +} + +/// One of the engine's notes as a CNP decision (the table in the module's docs). `None` for a +/// note that decides nothing, which the fold has already left out. +pub(crate) fn decision( + note: Note, + chess960: bool, + negative_extension_plies: u32, +) -> Option { + let text = |mv: Move| mv.to_uci(chess960); + let pruned = |mv: Move| DecisionKind::MovePruned { mv: text(mv) }; + let (kind, technique) = match note { + Note::BetaCutoff(mv, order) => ( + DecisionKind::Cutoff { + mv: text(mv), + order, + }, + Some("alphabeta"), + ), + Note::TtCutoff => (DecisionKind::Table, Some("tt")), + Note::Tablebase => (DecisionKind::Tablebase, None), + Note::NullMoveCutoff => (DecisionKind::NullMove, Some("nullmove")), + Note::ReverseFutility => (DecisionKind::NodePruned { mv: None }, Some("rfp")), + Note::Razoring => (DecisionKind::NodePruned { mv: None }, Some("razoring")), + Note::MultiCut => (DecisionKind::NodePruned { mv: None }, Some("multicut")), + Note::ProbCutCutoff(mv) => ( + DecisionKind::NodePruned { mv: Some(text(mv)) }, + Some("probcut"), + ), + Note::LateMovePruning(mv) => (pruned(mv), Some("lmp")), + Note::HistoryPruning(mv) => (pruned(mv), Some("histprune")), + Note::Futility(mv) => (pruned(mv), Some("futility")), + Note::SeePruning(mv) => (pruned(mv), Some("seeprune")), + Note::DeltaPruning(mv) => (pruned(mv), Some("delta")), + Note::Reduced(_, plies) => (DecisionKind::Reduced { plies }, Some("lmr")), + Note::NegativeExtension(_) => ( + DecisionKind::Reduced { + plies: negative_extension_plies, + }, + Some("negext"), + ), + Note::SingularExtension(_) => (DecisionKind::Extended { plies: 1 }, Some("singular")), + Note::DoubleExtension(_) => (DecisionKind::Extended { plies: 1 }, Some("doubleext")), + Note::ReductionResearch(_) => ( + DecisionKind::Research { + reason: ResearchReason::Depth, + }, + Some("lmr"), + ), + Note::PvsResearch(_) => ( + DecisionKind::Research { + reason: ResearchReason::Window, + }, + Some("pvs"), + ), + Note::Enter { .. } + | Note::Exit { .. } + | Note::Quiescence + | Note::TtHit + | Note::NullMove + | Note::ProbCut + | Note::SingularSearch(_) => return None, + }; + let decision = Decision::new(kind); + Some(match technique { + Some(id) => decision.by(id), + None => decision, + }) +} + +#[cfg(test)] +mod tests { + use cb2026_engine::search::MATE; + use cb2026_engine::tree::{FoldedNode, Window}; + use cnp::engine::ScoreValue; + + use super::*; + + /// Every note there is, with a move where it takes one. + fn every_note(mv: Move) -> Vec { + vec![ + Note::Enter { + depth: 1, + alpha: 0, + beta: 1, + }, + Note::Exit { score: 0 }, + Note::Quiescence, + Note::TtHit, + Note::TtCutoff, + Note::Tablebase, + Note::ReverseFutility, + Note::Razoring, + Note::NullMove, + Note::NullMoveCutoff, + Note::ProbCut, + Note::ProbCutCutoff(mv), + Note::LateMovePruning(mv), + Note::HistoryPruning(mv), + Note::Futility(mv), + Note::SeePruning(mv), + Note::DeltaPruning(mv), + Note::Reduced(mv, 2), + Note::ReductionResearch(mv), + Note::PvsResearch(mv), + Note::BetaCutoff(mv, 3), + Note::SingularSearch(mv), + Note::SingularExtension(mv), + Note::DoubleExtension(mv), + Note::MultiCut, + Note::NegativeExtension(mv), + ] + } + + #[test] + fn every_decision_names_a_switch_cb2026_has() { + let mv = Position::startpos().parse_uci_move("e2e4").unwrap(); + let mut decided = 0; + for note in every_note(mv) { + let Some(decision) = decision(note, false, 1) else { + continue; + }; + decided += 1; + if let Some(id) = &decision.technique { + assert!(SWITCHES.iter().any(|s| s.name == id), "{id} for {note:?}"); + } + } + // Every note but the brackets and the five attempts is a decision. + assert_eq!(decided, every_note(mv).len() - 7); + assert!(SWITCHES.iter().any(|s| s.name == "aspiration")); + // Their shapes, for the ones that carry something. + let cutoff = decision(Note::BetaCutoff(mv, 3), false, 1).unwrap(); + assert_eq!( + cutoff.kind, + DecisionKind::Cutoff { + mv: "e2e4".to_string(), + order: 3 + } + ); + let shallower = decision(Note::NegativeExtension(mv), false, 2).unwrap(); + assert_eq!(shallower.kind, DecisionKind::Reduced { plies: 2 }); + let probcut = decision(Note::ProbCutCutoff(mv), false, 1).unwrap(); + assert_eq!( + probcut.kind, + DecisionKind::NodePruned { + mv: Some("e2e4".to_string()) + } + ); + } + + /// A kept tree of the start position: the root and one child, `e2e4`, with `window` and + /// `score` as the search's values. + fn kept(window: Window, score: i32) -> KeptTree { + let e4 = Position::startpos().parse_uci_move("e2e4").unwrap(); + KeptTree { + handle: "t1".to_string(), + root: Position::startpos(), + chess960: false, + depth: 3, + score: Some(cnp::engine::Score::cp(10)), + negative_extension_plies: 1, + tree: FoldedTree { + nodes: vec![ + FoldedNode { + children: vec![1], + subtree: 1, + ..FoldedNode::default() + }, + FoldedNode { + mv: Some(e4), + parent: Some(0), + ply: 1, + window: Some(window), + score: Some(score), + notes: vec![Note::Reduced(e4, 1)], + ..FoldedNode::default() + }, + ], + root_searches: 3, + max_ply: 1, + truncated: false, + }, + last_used: Instant::now(), + } + } + + #[test] + fn a_node_s_score_is_bounded_by_its_window_and_mates_count_from_it() { + let window = Window { + depth: 2, + alpha: -11, + beta: -10, + }; + let bound = |score| tree_node(&kept(window, score), 1).score.unwrap().bound; + assert_eq!(bound(-10), Bound::Lower); + assert_eq!(bound(-11), Bound::Upper); + let open = Window { + depth: 2, + alpha: -INFINITY, + beta: INFINITY, + }; + let node = tree_node(&kept(open, -12), 1); + assert_eq!(node.mv.as_deref(), Some("e2e4")); + assert_eq!((node.alpha, node.beta), (None, None)); + assert_eq!(node.score, Some(cnp::engine::Score::cp(-12))); + assert_eq!( + node.decisions, + vec![Decision::new(DecisionKind::Reduced { plies: 1 }).by("lmr")] + ); + // A mate four plies from the root: at the node one ply down, its side mates in two + // moves (three plies); two plies down, the other side is mated in one. + let mated = tree_node(&kept(open, MATE - 4), 1).score.unwrap(); + assert_eq!(mated.value, ScoreValue::Mate(2)); + assert_eq!(to_score_at(-(MATE - 4), 2), cb2026_engine::Score::Mate(-1)); + // The root: its result, and a research for each of its searches before the last. + let root = tree_node(&kept(open, 0), FoldedTree::ROOT); + assert_eq!( + (root.mv, root.depth, root.child_count, root.subtree), + (None, 3, 1, 1) + ); + let research = Decision::new(DecisionKind::Research { + reason: ResearchReason::Window, + }) + .by("aspiration"); + assert_eq!(root.decisions, vec![research.clone(), research]); + } + + #[test] + fn the_store_drops_expired_trees_then_the_ones_unused_longest() { + let open = Window { + depth: 2, + alpha: -INFINITY, + beta: INFINITY, + }; + let mut store = TreeStore::default(); + let handles: Vec = (0..MAX_TREES_KEPT) + .map(|_| store.keep(kept(open, 0)).handle.clone()) + .collect(); + assert_eq!(handles[0], "t1"); + // Using the first makes the second the one unused longest, which the next tree drops. + assert!(store.used("t1").is_some()); + let newest = store.keep(kept(open, 0)).handle.clone(); + assert_eq!(newest, format!("t{}", MAX_TREES_KEPT + 1)); + assert!(store.used("t2").is_none()); + assert!(store.used("t1").is_some() && store.used("t3").is_some()); + // A tree unused for the expiry is gone, and its handle never comes back. + let expiry = Duration::from_millis(TREE_EXPIRY_MS); + for tree in &mut store.trees { + tree.last_used = Instant::now().checked_sub(expiry).unwrap(); + } + assert!(store.used("t1").is_none()); + assert!(store.trees.is_empty()); + assert_eq!( + store.keep(kept(open, 0)).handle, + format!("t{}", MAX_TREES_KEPT + 2) + ); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 705b714..1b56f3c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -87,6 +87,7 @@ pub mod see; pub mod stats; pub mod tablebase; pub mod time; +pub mod tree; pub mod tt; pub mod tuned; pub mod tuning; @@ -733,8 +734,13 @@ impl Engine { /// Searches `position` to `depth` on one thread and records the search tree of the last /// iteration, for nodes up to `max_ply` plies from the root (at most `max_events` - /// decisions; see [`stats`]). The earlier iterations run first, unrecorded, so the move - /// ordering is what a real search would have. Returns the tree and the iteration's result. + /// decisions; see [`stats`], and [`tree::FoldedTree`] for its nodes). The earlier + /// iterations run first, unrecorded, so the move ordering is what a real search would + /// have. Returns the tree and the iteration's result. + /// + /// Setting `stop` ends the search early, from another thread (a cancelled request): the + /// tree and the result are then incomplete, and the caller, which set it, knows to drop + /// them. pub fn search_tree( &mut self, position: &Position, @@ -742,9 +748,9 @@ impl Engine { depth: u32, max_ply: usize, max_events: usize, + stop: &AtomicBool, ) -> (SearchTree, SearchInfo) { let start = Instant::now(); - let stop = AtomicBool::new(false); let mut root_moves: Vec = position.legal_moves().iter().copied().collect(); if self.techniques.mvv_lva { ordering::order_moves(position, &mut root_moves); @@ -759,7 +765,7 @@ impl Engine { &mut self.ordering, self.techniques, StopConditions { - stop: &stop, + stop, deadline: None, max_nodes: None, }, @@ -1680,7 +1686,7 @@ mod tests { fn search_trees_record_the_last_iteration() { let pos = Position::startpos(); let mut engine = Engine::new(); - let (tree, info) = engine.search_tree(&pos, &[], 3, 1, 10_000); + let (tree, info) = engine.search_tree(&pos, &[], 3, 1, 10_000, &AtomicBool::new(false)); assert_eq!(info.depth, 3); assert!(!tree.truncated); // Every root move is entered at depth 2, and nothing deeper is recorded. diff --git a/crates/engine/src/search.rs b/crates/engine/src/search.rs index 661066c..bf3efa6 100644 --- a/crates/engine/src/search.rs +++ b/crates/engine/src/search.rs @@ -899,8 +899,19 @@ impl Techniques { /// Converts an internal score to a [`Score`], turning mate scores into "mate in N moves". pub fn to_score(value: i32) -> Score { + to_score_at(value, 0) +} + +/// [`to_score`] for a node `ply` plies from the root, with a mate counted from that node. +/// +/// The search scores a mate by its distance from the root (`MATE - ply` where it happens), at +/// every node, so that scores from different depths compare. A node's own mate is nearer than +/// the root's by the plies played to reach it: mated four plies from the root is mated in two +/// moves at the root, but in one at the node two plies down. Used to show the nodes of a +/// search tree ([`crate::tree`]). +pub fn to_score_at(value: i32, ply: u32) -> Score { if value.abs() >= MATE - MAX_PLY as i32 { - let plies = MATE - value.abs(); + let plies = (MATE - value.abs() - ply as i32).max(0); let moves = (plies + 1) / 2; Score::Mate(if value > 0 { moves } else { -moves }) } else { @@ -1207,6 +1218,12 @@ impl<'a> Searcher<'a> { /// Reports a decision to the statistics and, when one is being recorded, the search tree. fn note(&mut self, note: Note) { self.stats.count(note); + self.record(note); + } + + /// Writes `note` to the search tree being recorded, if any, and not to the statistics: for + /// what only a tree needs, such as the root search's own brackets. + fn record(&mut self, note: Note) { if let Some(tree) = &mut self.tree { tree.record(&self.path, note); } @@ -2234,6 +2251,10 @@ impl<'a> Searcher<'a> { }; let mut child_pv = Vec::new(); self.keys.push(pos.hash()); + // A recorded tree brackets each search of the root, as `negamax` does every other node, + // so that an aspiration re-search shows (`crate::tree`). Not counted: the root isn't a + // `negamax` node, and the statistics stay as they were. + self.record(Note::Enter { depth, alpha, beta }); for (index, &mv) in root_moves.iter().enumerate() { let mut child = pos.clone(); child.make_move(mv); @@ -2271,6 +2292,9 @@ impl<'a> Searcher<'a> { } } self.keys.pop(); + self.record(Note::Exit { + score: result.score, + }); result.nodes = self.nodes; result.seldepth = self.seldepth; result.complete = !self.aborted; diff --git a/crates/engine/src/stats.rs b/crates/engine/src/stats.rs index 7e106d5..c487a8f 100644 --- a/crates/engine/src/stats.rs +++ b/crates/engine/src/stats.rs @@ -27,7 +27,9 @@ use cb2026_chess::Move; /// [`SearchTree`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Note { - /// A main-search node is entered, `depth` plies to go, with the window `[alpha, beta]`. + /// A main-search node is entered, `depth` plies to go, with the window `[alpha, beta]`. A + /// recorded tree also brackets each search of the root with `Enter` and [`Note::Exit`], + /// which aren't counted. Enter { /// Remaining depth. depth: u32, diff --git a/crates/engine/src/tree.rs b/crates/engine/src/tree.rs new file mode 100644 index 0000000..0b7c280 --- /dev/null +++ b/crates/engine/src/tree.rs @@ -0,0 +1,572 @@ +//! Search trees folded into their nodes: the positions the search reached near the root, how it +//! searched each, and what it decided there. +//! +//! A [`SearchTree`] is a log: one [`Note`] after another, each made at the node its path leads +//! to. That is what the search can write cheaply, one line per decision, but not what a reader +//! wants, which is the tree: each root move with its window, its score and the reasons the +//! search gave, then its replies the same way. [`FoldedTree::fold`] turns the log into that +//! tree, once, so that a node can be read without going through the log again (CNP's +//! `engine/treeNode` reads a big tree a node at a time). +//! +//! ## How the log folds +//! +//! - **`Enter` and `Exit` pair up like brackets,** one pair for each search of a node, with its +//! window and remaining depth, then its score. A recorded tree brackets the root's searches +//! too. +//! - **A node is shown as its last search,** the one whose score counted: its window, its +//! score, its children and its decisions are that search's. A node can be searched more +//! than once: a late move reduced, then searched again at full depth, then again with the +//! full window; and the whole root again on each aspiration re-search. Mixed together, those +//! searches would repeat each decision and keep replies the deciding search never looked at, +//! with scores from another question; a score's bound would be read against the wrong +//! window. The earlier searches show as the decisions that led to the last: `Reduced`, +//! `ReductionResearch` and `PvsResearch` for a node, and [`FoldedTree::root_searches`] for +//! the root. +//! - **Each decision goes to the node it is about.** Most are made at the node they concern: a +//! cutoff, a table hit, null-move or reverse futility pruning, a move pruned (which has no +//! node of its own, so it stays with its parent, naming the move). A reduction and its +//! re-searches are noted with the move already played, at the child's path, and the singular, +//! double and negative extensions at the parent, before its moves, naming the hash move. Both +//! say how the parent searched that child, so they go to the child, before its own +//! decisions. A decision's move, when it has one, is always a move from its own node: the +//! reply that refuted it, the move left out, the capture that proved ProbCut. +//! - **Verification searches are left out.** A null move's search (its path has a null move) +//! and a singular extension's search (the node entered again while it is open, without its +//! hash move, at a lower depth and a lowered window) are the search checking something, not +//! lines of play. What they found shows as the decisions they led to (`NullMoveCutoff`, +//! `SingularExtension`, `MultiCut`). +//! - **Attempts that decided nothing are left out:** `TtHit` (an entry too shallow to use), +//! `NullMove`, `ProbCut` and `SingularSearch` (a check started; the decision follows if it +//! succeeded), and `Quiescence`. +//! +//! ## Pitfalls +//! +//! - **Scores are the search's own values**, from each node's side to move, with mates counted +//! from the root ([`crate::search::to_score_at`] counts them from the node). +//! - **A truncated log ends mid-search** ([`SearchTree::truncated`]): some nodes have no score, +//! and the later part of the search, the later root moves included, is missing. A node then +//! shows its last search that finished, if it has one. +//! - **A node's score comes from the whole search,** below the recorded plies too. The tree +//! shows the first plies' reasons, not every reason. +//! +//! See the Chess Programming Wiki, [Search Tree](https://www.chessprogramming.org/Search_Tree) +//! and [Node Types](https://www.chessprogramming.org/Node_Types). + +use cb2026_chess::Move; + +use crate::stats::{Note, SearchTree}; + +/// The window and remaining depth a node was searched with, as the search's values from the +/// node's side to move. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Window { + /// The depth still to go when the node was entered, in plies. + pub depth: u32, + /// The window's lower edge ([`crate::search::INFINITY`] negated when it has none). + pub alpha: i32, + /// The window's upper edge ([`crate::search::INFINITY`] when it has none). + pub beta: i32, +} + +/// One node of a [`FoldedTree`]: its last search. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct FoldedNode { + /// The move that reaches it from its parent; `None` at the root. + pub mv: Option, + /// Its parent's index; `None` at the root. + pub parent: Option, + /// How many plies from the root it is. + pub ply: usize, + /// The window of its last search. `None` for a root the log doesn't bracket. + pub window: Option, + /// Its last search's score, from its side to move. `None` if the log ended inside it, or + /// for a root the log doesn't bracket. + pub score: Option, + /// Its children's indices: the nodes its last search entered, in the order it first + /// entered each. + pub children: Vec, + /// How many nodes the tree holds below it. + pub subtree: usize, + /// What the search decided about it, in order: how its parent searched it (reduced, + /// extended, searched again), then what its last search decided at it (see the module's + /// docs for which notes these are). + pub notes: Vec, +} + +/// A [`SearchTree`] folded into its nodes (see the module's docs). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct FoldedTree { + /// The nodes, the root first; a node's parent always comes before it. + pub nodes: Vec, + /// How many times the root was searched (1, and one more for each aspiration re-search); + /// 0 for a log that doesn't bracket the root's searches. + pub root_searches: usize, + /// How many plies from the root were recorded. + pub max_ply: usize, + /// Whether the log was cut short ([`SearchTree::truncated`]). + pub truncated: bool, +} + +/// One search of one node, from its `Enter` to its `Exit`. +#[derive(Default)] +struct Search { + /// The move into the node; `None` at the root. + mv: Option, + /// Its window; `None` for the root of a log that doesn't bracket it. + window: Option, + /// Its score, once it has exited. + score: Option, + /// What it decided at the node. + notes: Vec, + /// How it searched its children, by the move to each: reductions, extensions, re-searches. + how: Vec<(Move, Note)>, + /// Its children's searches, in order. + children: Vec, +} + +/// A bracket opened by an `Enter`, closed by its `Exit`. +struct Frame { + /// Its search, or `None` inside a verification search. + search: Option, + /// Its distance from the root. + ply: usize, +} + +impl FoldedTree { + /// The root's index. + pub const ROOT: usize = 0; + + /// Folds a recorded log into its nodes. + pub fn fold(tree: &SearchTree) -> FoldedTree { + // The searches, the first being the root as the log has it outside any bracket. + let mut searches = vec![Search::default()]; + let mut roots: Vec = Vec::new(); + let mut open: Vec = Vec::new(); + // Open brackets of verification searches: while there are any, nothing is kept. + let mut verifying = 0usize; + for event in &tree.events { + // A null move's search, and everything below it. + let Some(path) = event.path.iter().copied().collect::>>() else { + continue; + }; + // The search the event happens in, and its distance from the root. + let (top, top_ply) = match open.last() { + Some(frame) => (frame.search, frame.ply), + None => (Some(0), 0), + }; + match event.note { + Note::Enter { depth, alpha, beta } => { + // A bracket inside a verification search, or the singular extension's + // search, which enters the open node again: skipped. So is one whose parent + // isn't open, which a well-formed log never has. + let parent = match (top, path.len()) { + (_, 0) if open.is_empty() => None, + (Some(parent), len) if verifying == 0 && len == top_ply + 1 => Some(parent), + _ => { + verifying += 1; + open.push(Frame { + search: None, + ply: path.len(), + }); + continue; + } + }; + let search = searches.len(); + searches.push(Search { + mv: path.last().copied(), + window: Some(Window { depth, alpha, beta }), + ..Search::default() + }); + match parent { + Some(parent) => searches[parent].children.push(search), + None => roots.push(search), + } + open.push(Frame { + search: Some(search), + ply: path.len(), + }); + } + Note::Exit { score } => match open.pop() { + Some(Frame { + search: Some(search), + .. + }) => searches[search].score = Some(score), + Some(Frame { search: None, .. }) => verifying -= 1, + None => {} + }, + _ if verifying > 0 => {} + Note::TtHit + | Note::NullMove + | Note::ProbCut + | Note::SingularSearch(_) + | Note::Quiescence => {} + note => { + let Some(top) = top else { continue }; + match note { + // Noted at the child's path, with its move already played. + Note::Reduced(mv, _) + | Note::ReductionResearch(mv) + | Note::PvsResearch(mv) => { + if path.len() == top_ply + 1 { + searches[top].how.push((mv, note)); + } + } + // Noted at the parent's, naming the hash move. + Note::SingularExtension(mv) + | Note::DoubleExtension(mv) + | Note::NegativeExtension(mv) => searches[top].how.push((mv, note)), + _ => { + if path.len() == top_ply { + searches[top].notes.push(note); + } + } + } + } + } + } + let root = Self::last_of(&searches, &roots).unwrap_or(0); + let mut folded = FoldedTree { + nodes: vec![FoldedNode { + window: searches[root].window, + score: searches[root].score, + notes: searches[root].notes.clone(), + ..FoldedNode::default() + }], + root_searches: roots.len(), + max_ply: tree.max_ply, + truncated: tree.truncated, + }; + folded.grow(Self::ROOT, root, &searches); + // Children come after their parents, so one pass from the end sums every subtree. + for i in (1..folded.nodes.len()).rev() { + let below = folded.nodes[i].subtree + 1; + if let Some(parent) = folded.nodes[i].parent { + folded.nodes[parent].subtree += below; + } + } + folded + } + + /// The last of `candidates` that finished, or else the last one. + fn last_of(searches: &[Search], candidates: &[usize]) -> Option { + candidates + .iter() + .rev() + .find(|&&search| searches[search].score.is_some()) + .or(candidates.last()) + .copied() + } + + /// Adds node `node`'s children, as its search `search` entered them, and theirs below. + fn grow(&mut self, node: usize, search: usize, searches: &[Search]) { + let parent = &searches[search]; + let mut moves: Vec = Vec::new(); + for &child in &parent.children { + if let Some(mv) = searches[child].mv + && !moves.contains(&mv) + { + moves.push(mv); + } + } + for mv in moves { + let tries: Vec = parent + .children + .iter() + .copied() + .filter(|&child| searches[child].mv == Some(mv)) + .collect(); + let Some(last) = Self::last_of(searches, &tries) else { + continue; + }; + let how = parent + .how + .iter() + .filter(|&&(about, _)| about == mv) + .map(|&(_, note)| note); + let child = self.nodes.len(); + self.nodes.push(FoldedNode { + mv: Some(mv), + parent: Some(node), + ply: self.nodes[node].ply + 1, + window: searches[last].window, + score: searches[last].score, + notes: how.chain(searches[last].notes.iter().copied()).collect(), + ..FoldedNode::default() + }); + self.nodes[node].children.push(child); + self.grow(child, last, searches); + } + } + + /// The root. + pub fn root(&self) -> &FoldedNode { + &self.nodes[Self::ROOT] + } + + /// The index of the node `path` leads to from the root, if the tree holds it. + pub fn find(&self, path: &[Move]) -> Option { + path.iter().try_fold(Self::ROOT, |node, &mv| { + self.nodes[node] + .children + .iter() + .copied() + .find(|&child| self.nodes[child].mv == Some(mv)) + }) + } + + /// How many decisions the tree holds, at every node together. + pub fn decisions(&self) -> usize { + self.nodes.iter().map(|node| node.notes.len()).sum() + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::AtomicBool; + + use cb2026_chess::Position; + + use super::*; + use crate::Engine; + use crate::stats::TreeEvent; + + /// The moves `uci` names, played one after another from the start. + fn line(uci: &[&str]) -> Vec { + let mut pos = Position::startpos(); + uci.iter() + .map(|text| { + let mv = pos.parse_uci_move(text).expect("a legal move"); + pos.make_move(mv); + mv + }) + .collect() + } + + fn at(path: &[Move], note: Note) -> TreeEvent { + TreeEvent { + path: path.iter().copied().map(Some).collect(), + note, + } + } + + fn enter(depth: u32, alpha: i32, beta: i32) -> Note { + Note::Enter { depth, alpha, beta } + } + + #[test] + fn a_node_is_its_last_search_after_the_notes_on_how_it_was_searched() { + let moves = line(&["e2e4", "e7e5", "g1f3"]); + let (e4, e5, nf3) = (&moves[..1], &moves[..2], moves[2]); + let d4 = line(&["d2d4"]); + let (d4_d5, d4_nf6) = (line(&["d2d4", "d7d5"]), line(&["d2d4", "g8f6"])); + let a6 = line(&["e2e4", "a7a6"])[1]; + let null_below_e4 = TreeEvent { + path: vec![Some(moves[0]), None], + note: enter(1, -10, -9), + }; + let log = SearchTree { + max_ply: 2, + max_events: 100, + truncated: false, + events: vec![ + // A first search of the root, which an aspiration re-search replaces. + at(&[], enter(3, -5, 5)), + at(e4, enter(2, -5, 5)), + at(e4, Note::Exit { score: -50 }), + at(&[], Note::Exit { score: 50 }), + // The second. + at(&[], enter(3, -100, 100)), + at(e4, enter(2, -100, 100)), + at(e4, Note::TtHit), + // The singular extension's search: e4's node again, then a reply inside it. + at(e4, Note::SingularSearch(moves[1])), + at(e4, enter(1, -40, -39)), + at(e5, enter(0, 39, 40)), + at(e5, Note::Exit { score: 50 }), + at(e4, Note::Exit { score: -50 }), + at(e4, Note::SingularExtension(moves[1])), + at(e5, enter(2, -100, 100)), + // An extension of a move beyond the recorded plies goes nowhere. + at(e5, Note::SingularExtension(nf3)), + at(e5, Note::Exit { score: 20 }), + // A null move's search is left out. + at(e4, Note::NullMove), + null_below_e4.clone(), + TreeEvent { + note: Note::Exit { score: 9 }, + ..null_below_e4 + }, + // A pruned reply stays with e4, naming it. + at(e4, Note::Futility(a6)), + at(e4, Note::Exit { score: -20 }), + // d4: reduced, refuted by d5; searched again with the full window, by Nf6. + at(&d4, Note::Reduced(d4[0], 2)), + at(&d4, enter(1, -21, -20)), + at(&d4_d5, enter(0, 20, 21)), + at(&d4_d5, Note::Exit { score: 25 }), + at(&d4, Note::BetaCutoff(d4_d5[1], 1)), + at(&d4, Note::Exit { score: -25 }), + at(&d4, Note::PvsResearch(d4[0])), + at(&d4, enter(2, -100, -20)), + at(&d4_nf6, enter(1, 20, 100)), + at(&d4_nf6, Note::Exit { score: 30 }), + at(&d4, Note::BetaCutoff(d4_nf6[1], 1)), + at(&d4, Note::Exit { score: -30 }), + at(&[], Note::Exit { score: 20 }), + ], + }; + let tree = FoldedTree::fold(&log); + let root = tree.root(); + assert_eq!(tree.root_searches, 2); + assert_eq!( + (root.window, root.score), + ( + Some(Window { + depth: 3, + alpha: -100, + beta: 100 + }), + Some(20) + ) + ); + assert_eq!(root.children.len(), 2); + assert_eq!(root.subtree, 4); + assert_eq!(tree.find(&[]), Some(FoldedTree::ROOT)); + + let e4_node = &tree.nodes[tree.find(e4).unwrap()]; + assert_eq!(e4_node.score, Some(-20)); + assert_eq!( + e4_node.window, + Some(Window { + depth: 2, + alpha: -100, + beta: 100 + }) + ); + assert_eq!(e4_node.notes, vec![Note::Futility(a6)]); + assert_eq!((e4_node.children.len(), e4_node.subtree), (1, 1)); + + // The reply is its real search, not the singular search's, and was extended. + let e5_node = &tree.nodes[tree.find(e5).unwrap()]; + assert_eq!(e5_node.score, Some(20)); + assert_eq!(e5_node.window.unwrap().depth, 2); + assert_eq!(e5_node.notes, vec![Note::SingularExtension(moves[1])]); + assert_eq!(tree.find(&moves), None); + + // d4 is its last search, with the reply that refuted it there; how it came to be + // searched that way comes first. + let d4_node = &tree.nodes[tree.find(&d4).unwrap()]; + assert_eq!(d4_node.score, Some(-30)); + assert_eq!( + d4_node.window, + Some(Window { + depth: 2, + alpha: -100, + beta: -20 + }) + ); + assert_eq!( + d4_node.notes, + vec![ + Note::Reduced(d4[0], 2), + Note::PvsResearch(d4[0]), + Note::BetaCutoff(d4_nf6[1], 1) + ] + ); + assert_eq!(tree.find(&d4_d5), None); + assert!(tree.find(&d4_nf6).is_some()); + assert_eq!(tree.decisions(), 5); + } + + #[test] + fn a_node_the_log_ends_inside_has_its_window_and_no_score() { + let e4 = line(&["e2e4"]); + let log = SearchTree { + max_ply: 1, + max_events: 1, + truncated: true, + events: vec![at(&e4, enter(2, -5, 5))], + }; + let tree = FoldedTree::fold(&log); + assert!(tree.truncated); + let node = &tree.nodes[tree.find(&e4).unwrap()]; + assert_eq!(node.window.map(|w| w.depth), Some(2)); + assert_eq!(node.score, None); + } + + /// A real search's tree: every decision's move is a move from its own node, and the notes + /// about how a node was searched name the move that leads to it. + #[test] + fn a_real_tree_gives_each_decision_to_the_node_it_is_about() { + // An open middlegame, deep enough for reductions, re-searches and pruning. + let fen = "r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/3P1N2/PPP2PPP/RNBQK2R b KQkq - 0 4"; + let root = Position::from_fen(fen).unwrap(); + let mut engine = Engine::new(); + let stop = AtomicBool::new(false); + let (log, info) = engine.search_tree(&root, &[], 8, 3, 1_000_000, &stop); + assert!(!log.truncated); + let tree = FoldedTree::fold(&log); + + // Every root move was searched, each a child of the root, and the best is one of them. + // The root is bracketed, and its last search's score is the result's. + let root_node = tree.root(); + assert!(tree.root_searches >= 1); + assert_eq!( + root_node.score.map(crate::search::to_score), + Some(info.score) + ); + assert_eq!(root_node.children.len(), root.legal_moves().len()); + assert!(tree.find(&info.pv[..1]).is_some()); + assert_eq!(root_node.subtree, tree.nodes.len() - 1); + + let mut kinds = std::collections::HashSet::new(); + for (i, node) in tree.nodes.iter().enumerate().skip(1) { + let mut path = Vec::new(); + let mut at = Some(i); + while let Some(n) = at.filter(|&n| n != FoldedTree::ROOT) { + path.push(tree.nodes[n].mv.unwrap()); + at = tree.nodes[n].parent; + } + path.reverse(); + let mut pos = root.clone(); + let mut parent = root.clone(); + for &mv in &path { + parent = pos.clone(); + pos.make_move(mv); + } + assert!(parent.legal_moves().contains(&node.mv.unwrap())); + assert!(node.ply <= 3 && node.window.is_some() && node.score.is_some()); + for note in &node.notes { + kinds.insert(std::mem::discriminant(note)); + match *note { + Note::BetaCutoff(mv, _) + | Note::ProbCutCutoff(mv) + | Note::LateMovePruning(mv) + | Note::HistoryPruning(mv) + | Note::Futility(mv) + | Note::SeePruning(mv) => { + assert!(pos.legal_moves().contains(&mv), "{note:?} at {path:?}"); + } + Note::Reduced(mv, _) + | Note::ReductionResearch(mv) + | Note::PvsResearch(mv) + | Note::SingularExtension(mv) + | Note::DoubleExtension(mv) + | Note::NegativeExtension(mv) => { + assert_eq!(Some(mv), node.mv, "{note:?} at {path:?}"); + } + Note::Enter { .. } + | Note::Exit { .. } + | Note::TtHit + | Note::NullMove + | Note::ProbCut + | Note::SingularSearch(_) + | Note::Quiescence => panic!("{note:?} isn't a decision"), + _ => {} + } + } + } + // Enough happened to test the rules on: cutoffs, reductions and re-searches at least. + assert!(kinds.len() >= 4, "only {} kinds of decision", kinds.len()); + } +} diff --git a/crates/shell/src/explain.rs b/crates/shell/src/explain.rs index d2117a8..0ceadac 100644 --- a/crates/shell/src/explain.rs +++ b/crates/shell/src/explain.rs @@ -618,6 +618,7 @@ impl Shell { depth, plies, TREE_MAX_EVENTS, + &AtomicBool::new(false), ); let mut out = format!( "Search tree of the depth-{depth} iteration (the earlier ones ran first), {plies} plies shown.\n\ diff --git a/docs/PRD.md b/docs/PRD.md index bc893f0..6f6e045 100644 --- a/docs/PRD.md +++ b/docs/PRD.md @@ -413,8 +413,11 @@ search evaluates with the network and the terms are the hand-crafted evaluation' also gives the network's score and, asked, what each piece is worth to it, and can first settle captures as a search's leaf does (`quiet`), for Solrac's Engine Mind (Solrac Chess AI #340). A search can ponder (`"ponder": true` and `engine/ponderHit`), as UCI's `go ponder` does, for Solrac's -pondering switch (cjus/chess-node-protocol#18, Solrac Chess AI #319). Every engine capability is -offered except a root score window. Every conformance session in the +pondering switch (cjus/chess-node-protocol#18, Solrac Chess AI #319). And it keeps search trees +(`engine/tree`, `engine/treeNode`): a search's decisions near the root, recorded on an engine of +the tree's own, kept a few minutes under a handle and read a node at a time, each decision said +in alpha-beta's terms with the switch behind it, so Solrac's Engine Mind can answer "why not that +move?" (Solrac Chess AI #350). Every engine capability is offered except a root score window. Every conformance session in the protocol's repository runs against the real binary in `cargo test` (`crates/cli/tests/cnp.rs`). ### Lichess bot (must) diff --git a/docs/status.md b/docs/status.md index 8c65a71..4effe58 100644 --- a/docs/status.md +++ b/docs/status.md @@ -4,7 +4,7 @@ The single place that says where cb2026 stands: what is merged, what is built an is blocked on whom, and how to carry on. **Claude: read this first in a new session.** Update it in every PR that changes the picture (a stage merged, a result in, a new blocker). -*Last updated 2026-11-01, 15:30 MST (M5: the check extension, IIR and three versions of +*Last updated 2026-11-01, 17:30 MST (M5: the check extension, IIR and three versions of improving merged, with chapter 14.1; improving is off by default and set aside; time losses not reproduced, #66; continuation history merged, +10.7 ± 7.3, #69; history in LMR merged off by default after no verdict, #70; singular extensions and multi-cut merged, +29.5 ± 13.3, #71; @@ -169,7 +169,19 @@ workers never download one: a toolchain bump needs `bootstrap.py apply --rebake --rust-toolchain ` (Carlos). The first remote `check.sh` passed every step, perft included, about 2 minutes on a warm cache, once two version tests accepted a source without `.git` (remote-build snapshots leave it out, as release tarballs do): they expect the plain -version there and still require the commit in a checkout; no functional change.* +version there and still require the commit in a checkout; no functional change. +**cb2026's CNP node keeps search trees** (capability `tree`, `engine/tree` and `engine/treeNode`, +spec 7.8, cjus/chess-node-protocol `claude/search-tree`), for the search-tree panel of Solrac's +Engine Mind (Solrac Chess AI #350): each tree is recorded by `Engine::search_tree` on an engine +and a thread of its own, so it is answered while a search runs and is the same tree every time, +then folded into its nodes (`cb2026_engine::tree::FoldedTree`): each node is its last search +(window, score, children and decisions), after the decisions that say how it came to be +searched that way, and the notes are said in alpha-beta's terms (cutoff, table, null move, a +node or a move pruned, reduced, extended, searched again), each naming the switch behind it. +Trees are kept five minutes after their last use, eight at most; up to depth 24 (11–15 s) and +six plies. `search_tree` takes a stop flag, so a tree can be cancelled, and a recorded tree +brackets the root's searches, so an aspiration re-search shows; no functional change. The +`cnp` pin points at the protocol's PR branch until it merges.* ## Stages @@ -248,6 +260,7 @@ version there and still require the commit in a checkout; no functional change.* | The build's commit: CNP's `initialize` and `cb2026 --version` name the version with the commit it was built from, `1.0.0+f1638bcb685b` (`build_version`, `COMMIT`, from `crates/engine/build.rs`), so Solrac's game review can say which build judged a game; UCI's `id name` and XBoard's `myname` stay `cb2026 1.0.0`. For Solrac's game review (Solrac Chess AI #174) | #238 | 767812 | Merged, no functional change | | CNP pondering: capability `ponder`, a search with `"ponder": true` and `engine/ponderHit` (spec 7.7). A ponder search searches with its depth, node and mate limits but no time and doesn't answer before the hit, a stop or a cancel; from the hit the watchdog gives it the time manager's budget (`timeMs`, or its share of the clock), and its answer has `ponderMs`. The `cnp` pin moves to cjus/chess-node-protocol `968e777`. For Solrac's pondering switch (Solrac Chess AI #319) | #242 | 767812 | Merged, no functional change | | UCI and XBoard ponder with `Limits::pondering` instead of an `infinite` search: no time until the hit, but the depth, node and mate limits stay, so a strength level keeps its person's horizon on pondered moves, XBoard keeps `sd` while pondering, and the opening book answers a ponder search (it waits for the hit). A UCI `ponderhit` with no clock lets a mate limit end the search too. Full strength unchanged | #243 | 767812 | Built, no functional change at full strength | +| CNP search trees: capability `tree`, `engine/tree` and `engine/treeNode` (spec 7.8). A tree is recorded by `Engine::search_tree` (which now takes a stop flag) on a fresh engine and thread of its own, folded into nodes by `cb2026_engine::tree` (each node its last search; decisions in alpha-beta's terms, each with its switch), kept five minutes after its last use (eight at most), and read a node and a page of children at a time; to depth 24 and six plies. The `cnp` pin moves to cjus/chess-node-protocol's `claude/search-tree` branch. For Solrac's Engine Mind (Solrac Chess AI #350) | — | 767812 | Open, no functional change | **The M3 is free** since gen3's gauntlet finished (2026-10-29, about 20:30 MDT; #227). Each generation's files stay in `~/nnue-data/genN` there, and in `~/engines/nets/genN` on From 1f57c1e029474d93df2753cdea54f2ef6adb292f Mon Sep 17 00:00:00 2001 From: cjus Date: Sun, 1 Nov 2026 16:34:43 -0700 Subject: [PATCH 2/3] Docs: status.md names the search trees' PR (#249) No functional change. Bench: 767812 Co-Authored-By: Claude Opus 5.5 --- docs/status.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/status.md b/docs/status.md index 4effe58..3964abc 100644 --- a/docs/status.md +++ b/docs/status.md @@ -181,7 +181,7 @@ node or a move pruned, reduced, extended, searched again), each naming the switc Trees are kept five minutes after their last use, eight at most; up to depth 24 (11–15 s) and six plies. `search_tree` takes a stop flag, so a tree can be cancelled, and a recorded tree brackets the root's searches, so an aspiration re-search shows; no functional change. The -`cnp` pin points at the protocol's PR branch until it merges.* +`cnp` pin points at cjus/chess-node-protocol#22's branch until it merges (#249).* ## Stages @@ -260,7 +260,7 @@ brackets the root's searches, so an aspiration re-search shows; no functional ch | The build's commit: CNP's `initialize` and `cb2026 --version` name the version with the commit it was built from, `1.0.0+f1638bcb685b` (`build_version`, `COMMIT`, from `crates/engine/build.rs`), so Solrac's game review can say which build judged a game; UCI's `id name` and XBoard's `myname` stay `cb2026 1.0.0`. For Solrac's game review (Solrac Chess AI #174) | #238 | 767812 | Merged, no functional change | | CNP pondering: capability `ponder`, a search with `"ponder": true` and `engine/ponderHit` (spec 7.7). A ponder search searches with its depth, node and mate limits but no time and doesn't answer before the hit, a stop or a cancel; from the hit the watchdog gives it the time manager's budget (`timeMs`, or its share of the clock), and its answer has `ponderMs`. The `cnp` pin moves to cjus/chess-node-protocol `968e777`. For Solrac's pondering switch (Solrac Chess AI #319) | #242 | 767812 | Merged, no functional change | | UCI and XBoard ponder with `Limits::pondering` instead of an `infinite` search: no time until the hit, but the depth, node and mate limits stay, so a strength level keeps its person's horizon on pondered moves, XBoard keeps `sd` while pondering, and the opening book answers a ponder search (it waits for the hit). A UCI `ponderhit` with no clock lets a mate limit end the search too. Full strength unchanged | #243 | 767812 | Built, no functional change at full strength | -| CNP search trees: capability `tree`, `engine/tree` and `engine/treeNode` (spec 7.8). A tree is recorded by `Engine::search_tree` (which now takes a stop flag) on a fresh engine and thread of its own, folded into nodes by `cb2026_engine::tree` (each node its last search; decisions in alpha-beta's terms, each with its switch), kept five minutes after its last use (eight at most), and read a node and a page of children at a time; to depth 24 and six plies. The `cnp` pin moves to cjus/chess-node-protocol's `claude/search-tree` branch. For Solrac's Engine Mind (Solrac Chess AI #350) | — | 767812 | Open, no functional change | +| CNP search trees: capability `tree`, `engine/tree` and `engine/treeNode` (spec 7.8). A tree is recorded by `Engine::search_tree` (which now takes a stop flag) on a fresh engine and thread of its own, folded into nodes by `cb2026_engine::tree` (each node its last search; decisions in alpha-beta's terms, each with its switch), kept five minutes after its last use (eight at most), and read a node and a page of children at a time; to depth 24 and six plies. The `cnp` pin moves to cjus/chess-node-protocol's `claude/search-tree` branch. For Solrac's Engine Mind (Solrac Chess AI #350) | #249 | 767812 | Open, no functional change | **The M3 is free** since gen3's gauntlet finished (2026-10-29, about 20:30 MDT; #227). Each generation's files stay in `~/nnue-data/genN` there, and in `~/engines/nets/genN` on From 3e0432ba5ce9335d1186bf62102b41b06d52a10f Mon Sep 17 00:00:00 2001 From: cjus Date: Sun, 1 Nov 2026 16:43:28 -0700 Subject: [PATCH 3/3] CNP: pin the protocol to cjus/chess-node-protocol#22's merge (deeab77) The same tree as the branch's 68cf80d, now on the protocol's main. No functional change. Bench: 767812 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- docs/status.md | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 43265f9..5d31fcb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -214,7 +214,7 @@ checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "cnp" version = "0.1.0" -source = "git+https://github.com/cjus/chess-node-protocol?rev=68cf80d917066de0e366952b334eb82a65fa42d6#68cf80d917066de0e366952b334eb82a65fa42d6" +source = "git+https://github.com/cjus/chess-node-protocol?rev=deeab7761f2c7f129bb2dac7732477f730f88927#deeab7761f2c7f129bb2dac7732477f730f88927" dependencies = [ "serde", "serde_json", @@ -223,7 +223,7 @@ dependencies = [ [[package]] name = "cnp-conformance" version = "0.1.0" -source = "git+https://github.com/cjus/chess-node-protocol?rev=68cf80d917066de0e366952b334eb82a65fa42d6#68cf80d917066de0e366952b334eb82a65fa42d6" +source = "git+https://github.com/cjus/chess-node-protocol?rev=deeab7761f2c7f129bb2dac7732477f730f88927#deeab7761f2c7f129bb2dac7732477f730f88927" dependencies = [ "cnp", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index d2910ca..f99248c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,8 +41,8 @@ cb2026-tools = { path = "crates/tools" } cb2026-trainer = { path = "crates/trainer" } # The Chess Node Protocol, how Solrac talks to cb2026 (`crates/cnp`), and its conformance # sessions (Solrac Chess AI #98). Pinned to a commit; bump both together. -cnp = { git = "https://github.com/cjus/chess-node-protocol", rev = "68cf80d917066de0e366952b334eb82a65fa42d6" } -cnp-conformance = { git = "https://github.com/cjus/chess-node-protocol", rev = "68cf80d917066de0e366952b334eb82a65fa42d6" } +cnp = { git = "https://github.com/cjus/chess-node-protocol", rev = "deeab7761f2c7f129bb2dac7732477f730f88927" } +cnp-conformance = { git = "https://github.com/cjus/chess-node-protocol", rev = "deeab7761f2c7f129bb2dac7732477f730f88927" } # Lints shared by every crate (each crate opts in with `[lints] workspace = true`). [workspace.lints.rust] diff --git a/docs/status.md b/docs/status.md index a9e30ff..ccd0fe8 100644 --- a/docs/status.md +++ b/docs/status.md @@ -179,7 +179,7 @@ in #61's text (removed, and its old revision deleted) and #242 and #244's links private repository (unlinked again, #247), and #157, the pnxfarm draft, is closed; no functional change. **cb2026's CNP node keeps search trees** (capability `tree`, `engine/tree` and `engine/treeNode`, -spec 7.8, cjus/chess-node-protocol `claude/search-tree`), for the search-tree panel of Solrac's +spec 7.8, cjus/chess-node-protocol#22), for the search-tree panel of Solrac's Engine Mind (Solrac Chess AI #350): each tree is recorded by `Engine::search_tree` on an engine and a thread of its own, so it is answered while a search runs and is the same tree every time, then folded into its nodes (`cb2026_engine::tree::FoldedTree`): each node is its last search @@ -189,7 +189,7 @@ node or a move pruned, reduced, extended, searched again), each naming the switc Trees are kept five minutes after their last use, eight at most; up to depth 24 (11–15 s) and six plies. `search_tree` takes a stop flag, so a tree can be cancelled, and a recorded tree brackets the root's searches, so an aspiration re-search shows; no functional change. The -`cnp` pin points at cjus/chess-node-protocol#22's branch until it merges (#249).* +`cnp` pin moves to cjus/chess-node-protocol#22's merge, `deeab77` (#249).* ## Stages @@ -268,7 +268,7 @@ brackets the root's searches, so an aspiration re-search shows; no functional ch | The build's commit: CNP's `initialize` and `cb2026 --version` name the version with the commit it was built from, `1.0.0+f1638bcb685b` (`build_version`, `COMMIT`, from `crates/engine/build.rs`), so Solrac's game review can say which build judged a game; UCI's `id name` and XBoard's `myname` stay `cb2026 1.0.0`. For Solrac's game review (Solrac Chess AI #174) | #238 | 767812 | Merged, no functional change | | CNP pondering: capability `ponder`, a search with `"ponder": true` and `engine/ponderHit` (spec 7.7). A ponder search searches with its depth, node and mate limits but no time and doesn't answer before the hit, a stop or a cancel; from the hit the watchdog gives it the time manager's budget (`timeMs`, or its share of the clock), and its answer has `ponderMs`. The `cnp` pin moves to cjus/chess-node-protocol `968e777`. For Solrac's pondering switch (Solrac Chess AI #319) | #242 | 767812 | Merged, no functional change | | UCI and XBoard ponder with `Limits::pondering` instead of an `infinite` search: no time until the hit, but the depth, node and mate limits stay, so a strength level keeps its person's horizon on pondered moves, XBoard keeps `sd` while pondering, and the opening book answers a ponder search (it waits for the hit). A UCI `ponderhit` with no clock lets a mate limit end the search too. Full strength unchanged | #243 | 767812 | Built, no functional change at full strength | -| CNP search trees: capability `tree`, `engine/tree` and `engine/treeNode` (spec 7.8). A tree is recorded by `Engine::search_tree` (which now takes a stop flag) on a fresh engine and thread of its own, folded into nodes by `cb2026_engine::tree` (each node its last search; decisions in alpha-beta's terms, each with its switch), kept five minutes after its last use (eight at most), and read a node and a page of children at a time; to depth 24 and six plies. The `cnp` pin moves to cjus/chess-node-protocol's `claude/search-tree` branch. For Solrac's Engine Mind (Solrac Chess AI #350) | #249 | 767812 | Open, no functional change | +| CNP search trees: capability `tree`, `engine/tree` and `engine/treeNode` (spec 7.8). A tree is recorded by `Engine::search_tree` (which now takes a stop flag) on a fresh engine and thread of its own, folded into nodes by `cb2026_engine::tree` (each node its last search; decisions in alpha-beta's terms, each with its switch), kept five minutes after its last use (eight at most), and read a node and a page of children at a time; to depth 24 and six plies. The `cnp` pin moves to cjus/chess-node-protocol#22's merge, `deeab77`. For Solrac's Engine Mind (Solrac Chess AI #350) | #249 | 767812 | Merged, no functional change | **The M3 is free** since gen3's gauntlet finished (2026-10-29, about 20:30 MDT; #227). Each generation's files stay in `~/nnue-data/genN` there, and in `~/engines/nets/genN` on