diff --git a/Cargo.lock b/Cargo.lock index 5d31fcb..c89f0f0 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=deeab7761f2c7f129bb2dac7732477f730f88927#deeab7761f2c7f129bb2dac7732477f730f88927" +source = "git+https://github.com/cjus/chess-node-protocol?rev=62744203c4a92a505c79579c5ad094c5f46e6833#62744203c4a92a505c79579c5ad094c5f46e6833" 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=deeab7761f2c7f129bb2dac7732477f730f88927#deeab7761f2c7f129bb2dac7732477f730f88927" +source = "git+https://github.com/cjus/chess-node-protocol?rev=62744203c4a92a505c79579c5ad094c5f46e6833#62744203c4a92a505c79579c5ad094c5f46e6833" dependencies = [ "cnp", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index f99248c..2095942 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 = "deeab7761f2c7f129bb2dac7732477f730f88927" } -cnp-conformance = { git = "https://github.com/cjus/chess-node-protocol", rev = "deeab7761f2c7f129bb2dac7732477f730f88927" } +cnp = { git = "https://github.com/cjus/chess-node-protocol", rev = "62744203c4a92a505c79579c5ad094c5f46e6833" } +cnp-conformance = { git = "https://github.com/cjus/chess-node-protocol", rev = "62744203c4a92a505c79579c5ad094c5f46e6833" } # 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 aeaf124..febeceb 100644 --- a/crates/cli/tests/cnp.rs +++ b/crates/cli/tests/cnp.rs @@ -4,7 +4,8 @@ //! 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, the search tree), are skipped, and the test says which. +//! one it does (pondering, the search tree, following the root), are skipped, and the test says +//! which. use std::path::PathBuf; use std::time::Duration; @@ -69,13 +70,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 - // three are for nodes without capabilities it has: pondering, an evaluation's quiet line - // and piece values, and the search tree. + // four are for nodes without capabilities it has: pondering, an evaluation's quiet line + // and piece values, the search tree, and following the root. assert_eq!( skipped, vec![ "evaluate-quiet-pieces-unsupported (needs !engine.quiet, !engine.pieces)".to_string(), "ponder-unsupported (needs !engine.ponder)".to_string(), + "root-unsupported (needs !engine.root)".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 e8579c1..abc282c 100644 --- a/crates/cnp/src/lib.rs +++ b/crates/cnp/src/lib.rs @@ -11,7 +11,9 @@ //! It ponders: a search with `"ponder": true` runs on the opponent's time until //! `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). +//! Solrac's Engine Mind can say why cb2026 set a move aside (the `tree` module). And a search +//! with `rootMs` is followed at its root (spec 7.9): `engine/root` says which root move it is +//! on, where its effort has gone, and, at once, when it goes back over something. //! `cb2026 --cnp` speaks it, and so does a plain `cb2026` whose first input line is JSON. //! //! ```text @@ -51,6 +53,12 @@ //! 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`). +//! - **Following the root is throttled on its own.** The engine tells the search thread where +//! its root loop is at every root move and whenever it looks at the clock +//! ([`cb2026_engine::root`]). The thread passes it on as `engine/root` once `rootMs` has +//! passed since the last one, and a research (a better move, an aspiration window's failure) +//! at once, the interval then counting from it. `engine/progress` keeps its own interval, so neither holds the other +//! back. Only the main thread follows its root, so a move's nodes are that thread's. //! - **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, @@ -59,9 +67,9 @@ //! ## What it offers //! //! Every engine capability except `window`: cb2026's search always starts with an open window -//! 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 +//! at the root. Pondering, the search tree and following the root 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`] //! picks a level as `UCI_Elo` does. @@ -118,12 +126,16 @@ use cb2026_engine::levels::{ELO_RANGE, FULL_STRENGTH, RATINGS}; use cb2026_engine::search::MAX_PLY; use cb2026_engine::tablebase::TablebaseLoader; use cb2026_engine::time; -use cb2026_engine::{AUTHOR, Engine, Limits, NAME, Score, SearchInfo, SearchResult, build_version}; +use cb2026_engine::{ + AUTHOR, Engine, Limits, NAME, RootInfo, RootResearch, Score, SearchInfo, SearchResult, + build_version, +}; 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, Tree, TreeNodePage, + Bound, EloRange, EngineCapabilities, EngineProgress, Evaluate, EvaluateParams, EvaluateResult, + Level, Levels, LevelsResult, Line, PieceValue, PonderHit, Progress, Root, RootMove, RootParams, + Search, SearchParams, SearchStats, Stop, Technique, Techniques, TechniquesResult, Term, Tree, + TreeNodePage, }; use cnp::lifecycle::{ CancelRequest, Capabilities, IncompatibleVersionData, Initialize, InitializeResult, @@ -331,6 +343,8 @@ struct Prepared { techniques: Vec<(usize, bool)>, deterministic: bool, progress: Option, + /// How often to send `engine/root`, when the search follows its root (`rootMs`). + root: Option, game: Option, chess960: bool, /// A ponder search: `limits` count from its hit (spec 7.7). @@ -493,6 +507,7 @@ impl Node { pieces: true, ponder: true, tree: true, + root: true, }), voice: None, preferences: None, @@ -826,6 +841,7 @@ fn prepare(params: &SearchParams) -> Result { techniques, deterministic: params.deterministic, progress: params.progress_ms.map(Duration::from_millis), + root: params.root_ms.map(Duration::from_millis), game: params.game.clone(), chess960: params.position.chess960, ponder: params.ponder, @@ -878,6 +894,7 @@ fn search_thread( // The latest report of each line, by its MultiPV number. let mut lines: BTreeMap = BTreeMap::new(); let mut last_progress: Option = None; + let mut last_root: Option = None; let result = { let mut on_info = |info: &SearchInfo| { lines.insert(info.multipv.max(1), info.clone()); @@ -891,12 +908,24 @@ fn search_thread( last_progress = Some(Instant::now()); } }; - engine.search( + // Following the root (spec 7.9): at most every `rootMs`, on an interval of its own, and + // a research at once, the interval then counting from it. + let mut on_root = |info: &RootInfo<'_>| { + if let Some(every) = prepared.root + && (info.research.is_some() || last_root.is_none_or(|at| at.elapsed() >= every)) + { + send(&output, root(&id, info, prepared.multipv, chess960).into()); + last_root = Some(Instant::now()); + } + }; + let following: &mut dyn FnMut(&RootInfo<'_>) = &mut on_root; + engine.search_following_root( &prepared.position, &prepared.history, &limits, &flags.stop, &mut on_info, + prepared.root.is_some().then_some(following), ) }; // An infinite search waits for `engine/stop` or a cancel (or the watchdog), and a ponder @@ -1012,6 +1041,42 @@ fn progress(id: &Id, info: &SearchInfo, multipv: usize, chess960: bool) -> Notif Notification::new::(¶ms) } +/// An `engine/root` notification from where the root loop is. +fn root(id: &Id, info: &RootInfo<'_>, multipv: usize, chess960: bool) -> Notification { + let research = info.research.map(|research| match research { + RootResearch::Better(mv) => cnp::engine::RootResearch::Better { + mv: mv.to_uci(chess960), + }, + RootResearch::FailHigh(at_least) => cnp::engine::RootResearch::FailHigh { + score: bounded(at_least, Bound::Lower), + }, + RootResearch::FailLow(at_most) => cnp::engine::RootResearch::FailLow { + score: bounded(at_most, Bound::Upper), + }, + }); + let params = RootParams { + id: id.clone(), + depth: info.depth, + multipv: (multipv > 1).then_some(info.multipv), + mv: info.current.to_uci(chess960), + number: info.number, + of: info.of, + best: info.best.map(|mv| mv.to_uci(chess960)), + moves: info + .moves + .iter() + .map(|&(mv, nodes)| RootMove { + mv: mv.to_uci(chess960), + nodes, + }) + .collect(), + nodes: info.nodes, + time_ms: millis(info.time), + research, + }; + Notification::new::(¶ms) +} + /// A request's position: its FEN with its moves played, and the hash of each position before /// a move, for repetitions. `InvalidPosition` if the FEN or a move isn't legal. fn read_position(wanted: &cnp::engine::Position) -> Result<(Position, Vec), ResponseError> { @@ -1119,6 +1184,14 @@ fn score(score: Score) -> cnp::engine::Score { } } +/// A score that is only a bound, `bound`. +fn bounded(value: Score, bound: Bound) -> cnp::engine::Score { + cnp::engine::Score { + bound, + ..score(value) + } +} + fn moves(line: &[Move], chess960: bool) -> Vec { line.iter().map(|mv| mv.to_uci(chess960)).collect() } @@ -1458,6 +1531,17 @@ mod tests { None } + /// Every message sent so far, in order. + fn messages(&self) -> Vec { + let bytes = self.0.lock().unwrap().clone(); + let mut input = io::Cursor::new(bytes); + let mut messages = Vec::new(); + while let Ok(Some(message)) = read_message(&mut input, usize::MAX) { + messages.push(message); + } + messages + } + /// Waits up to `timeout` for the response to request `id`. fn wait_for(&self, id: i64, timeout: Duration) -> Option { let start = Instant::now(); @@ -1744,6 +1828,108 @@ mod tests { node.finish(); } + /// The `engine/root` notifications among `messages`, each with its place. + fn roots(messages: &[Message]) -> Vec<(usize, RootParams)> { + messages + .iter() + .enumerate() + .filter_map(|(at, message)| match message { + Message::Notification(notification) if notification.is::() => { + Some((at, notification.params::().unwrap())) + } + _ => None, + }) + .collect() + } + + #[test] + fn following_the_root_is_throttled_and_never_comes_after_the_answer() { + let capture = Capture::default(); + let mut node = running_node(&capture); + let every = 50; + let mut params = start().root_ms(every); + params.limits = SearchLimits { + time_ms: Some(600), + ..SearchLimits::default() + }; + params.multipv = Some(2); + node.request(Request::new::(1, ¶ms)); + let answer = capture + .wait_for(1, Duration::from_secs(10)) + .expect("an answer") + .result::() + .unwrap(); + // A moment for anything late to show. + thread::sleep(Duration::from_millis(100)); + let messages = capture.messages(); + let answered = messages + .iter() + .position(|m| matches!(m, Message::Response(r) if r.id == Some(Id::Number(1)))) + .unwrap(); + let roots = roots(&messages); + assert!(!roots.is_empty(), "no engine/root"); + assert!( + roots.iter().all(|(at, _)| *at < answered), + "after the answer" + ); + // The first, before there is a best move: depth 1's first move. + let first = &roots[0].1; + assert_eq!( + (first.depth, first.number, first.best.as_ref()), + (1, 1, None) + ); + let mut previous: Option = None; + for (_, root) in &roots { + assert_eq!(root.id, Id::Number(1)); + assert!(matches!(root.multipv, Some(1 | 2)), "{root:?}"); + assert!((1..=root.of).contains(&root.number), "{root:?}"); + assert!(root.moves.iter().any(|m| m.mv == root.mv), "{root:?}"); + let below: u64 = root.moves.iter().map(|m| m.nodes).sum(); + assert!(below <= root.nodes, "{root:?}"); + match &root.research { + // At most every `rootMs`, counted from the last of any kind (give or take the + // millisecond the report takes to reach the throttle). + None => { + if let Some(at) = previous { + assert!(root.time_ms + 1 >= at + every, "{at} then {root:?}"); + } + } + Some(cnp::engine::RootResearch::Better { mv }) => assert_eq!(mv, &root.mv), + Some(cnp::engine::RootResearch::FailHigh { score }) => { + assert_eq!(score.bound, Bound::Lower); + } + Some(cnp::engine::RootResearch::FailLow { score }) => { + assert_eq!(score.bound, Bound::Upper); + } + Some(cnp::engine::RootResearch::Unknown) => panic!("{root:?}"), + } + previous = Some(root.time_ms); + } + // The move played was among those followed. + let best = answer.best_move.unwrap(); + assert!(roots.last().unwrap().1.moves.iter().any(|m| m.mv == best)); + node.finish(); + } + + #[test] + fn a_search_that_doesn_t_ask_isn_t_followed() { + let capture = Capture::default(); + let mut node = running_node(&capture); + let mut params = start(); + params.limits = SearchLimits::depth(6); + params.progress_ms = Some(0); + node.request(Request::new::(1, ¶ms)); + assert!(capture.wait_for(1, Duration::from_secs(10)).is_some()); + let messages = capture.messages(); + assert!(roots(&messages).is_empty()); + // Its progress still comes. + assert!(messages.iter().any(|m| matches!( + m, + Message::Notification(n) if n.is::() + ))); + node.finish(); + } + #[test] fn a_switch_s_name_is_its_description_without_the_note() { assert_eq!( diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1b56f3c..fdaabe1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -25,7 +25,8 @@ //! protocols set it on `stop` and `quit`. //! - The **info callback** receives a [`SearchInfo`] as the search makes progress (depth, //! score, nodes, principal variation); UCI turns it into `info` lines and the shell into its -//! thinking display. +//! thinking display. [`Engine::search_following_root`] also says, as it goes, which root +//! move the search is on and where its effort goes ([`root`]), for CNP's `engine/root`. //! - The **history** argument holds the hash keys of the positions before this one in the //! game, for spotting repetitions. //! @@ -82,6 +83,7 @@ pub mod eval; pub mod hce; pub mod levels; pub mod ordering; +pub mod root; pub mod search; pub mod see; pub mod stats; @@ -107,6 +109,8 @@ use book::OpeningBook; use correction::CorrectionHistory; use eval::EvalParams; use ordering::OrderingTables; +use root::RootFollower; +pub use root::{RootInfo, RootResearch}; use search::{ DEFAULT_DEPTH, INFINITY, MATE, MAX_PLY, NNUE_EVAL_LIMIT, RootResult, SearchParams, Searcher, StopConditions, Techniques, to_score, @@ -483,6 +487,22 @@ impl Engine { limits: &Limits, stop: &AtomicBool, on_info: &mut dyn FnMut(&SearchInfo), + ) -> SearchResult { + self.search_following_root(position, history, limits, stop, on_info, None) + } + + /// [`Engine::search`], also telling `on_root`, if given, where the main thread's root loop + /// is as it goes: at each root move, whenever the search looks at the clock, and at once + /// when the search goes back over something ([`root`]). The search is the same, node for + /// node, followed or not. + pub fn search_following_root( + &mut self, + position: &Position, + history: &[u64], + limits: &Limits, + stop: &AtomicBool, + on_info: &mut dyn FnMut(&SearchInfo), + on_root: Option<&mut dyn FnMut(&RootInfo<'_>)>, ) -> SearchResult { let start = Instant::now(); let mut root_moves: Vec = position @@ -671,6 +691,10 @@ impl Engine { if let Some(net) = network { searcher.use_network(net); } + if let Some(on_root) = on_root { + let follower = RootFollower::new(on_root, start, &helper_nodes, self_multipv); + searcher.follow_root(follower); + } let result = main_search( &mut searcher, MainSearch { @@ -1042,6 +1066,8 @@ fn main_search( .filter(|&mv| !this_depth.iter().any(|line| line.best_move == Some(mv))) .collect(); let previous = lines.get(k).map(|line| line.score); + let previous_move = lines.get(k).and_then(|line| line.best_move); + searcher.follow_line(depth, k, &moves, previous_move); let result = searcher.search_depth(position, &mut moves, depth, previous); // A stopped iteration still counts if it finished at least one move: the first // move searched is the previous best, so its result is at least as well-founded. diff --git a/crates/engine/src/root.rs b/crates/engine/src/root.rs new file mode 100644 index 0000000..b8e6a3b --- /dev/null +++ b/crates/engine/src/root.rs @@ -0,0 +1,418 @@ +//! Following the root: which root move the search is on, where its effort goes, and when it may +//! be changing its mind, reported as it searches ([`Engine::search_following_root`]). +//! +//! The search reports its lines after each depth ([`crate::SearchInfo`]), which can be seconds +//! apart. In between, a player watching the engine think sees nothing, though the search is +//! busy: trying one root move after another, giving most of its effort to a few, and now and +//! then going back over something. UCI shows the same with `currmove`, `currmovenumber`, +//! `lowerbound` and `upperbound`; CNP's `engine/root` (spec 7.9) is built from [`RootInfo`]. +//! +//! ## What is reported +//! +//! - **The move being searched,** its place in the depth's order of root moves, and how many +//! there are, for the line being searched (MultiPV searches the root once per line). +//! - **The best move so far** for the line: this depth's once a move has raised the score, or +//! the last completed depth's until then. +//! - **The effort:** the nodes searched below each root move, every depth and line together, +//! so a reader can see where the search spends its time (usually on the best move, and on +//! the moves that came close). +//! - **What the search goes back over,** at once ([`RootResearch`]): a later move that scored +//! above the best on its null-window search (PVS) and is searched again in full, and a depth +//! whose score fell outside its aspiration window and is searched again wider. +//! +//! ## How it works +//! +//! The main thread's searcher ([`crate::search`]) holds a `RootFollower` when the caller +//! follows the root. The root loop tells it when a line and each move start and end; the PVS +//! re-search at the root and the aspiration window's failures tell it what is gone back over; +//! and whenever the search looks at the clock and its stop flag, every thousand nodes or so, it +//! reports where the root is, so a long first move still shows its nodes growing. +//! The caller is called every time and decides what to pass on: CNP's node throttles to its +//! client's `rootMs`, letting research through at once. +//! +//! ## Pitfalls +//! +//! - **Only the main thread follows its root.** Lazy SMP's helpers search the same root in +//! their own orders (and odd ones a depth ahead), so their moves would make no single story. +//! A move's nodes are then the main thread's, and show each move's share; the total +//! ([`RootInfo::nodes`]) counts every thread, as [`crate::SearchInfo::nodes`] does. +//! - **It must change nothing.** The follower reads the search's node count and never touches +//! the search's state, so a search followed or not makes the same moves in the same order, +//! node for node. A test checks it. +//! - **It must cost nothing much.** The work is per root move and per look at the clock, never +//! per node, and nothing is allocated after the root's moves are first seen. Without a +//! follower the cost is a check of an `Option` at those same places. +//! - **The search's hottest loop barely knows.** The PVS re-search is noticed where it already +//! happens, behind a check that the node is a root move's, so the inner nodes pay one +//! comparison on the rare re-search. +//! +//! [`Engine::search_following_root`]: crate::Engine::search_following_root + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use cb2026_chess::Move; + +use crate::Score; + +/// Where the main thread's root loop is, reported as the search goes +/// ([`crate::Engine::search_following_root`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RootInfo<'a> { + /// The depth being searched: one more than the last completed. + pub depth: u32, + /// Which line is being searched, from 1 (MultiPV). + pub multipv: u32, + /// The root move being searched now. After a [`RootResearch::FailHigh`] or + /// [`RootResearch::FailLow`], the one the depth's next search starts with. + pub current: Move, + /// Its place in this search of the root's order of moves for this line, from 1. + pub number: u32, + /// How many root moves this line searches. + pub of: u32, + /// The best root move so far for this line: this depth's, once a move has raised the score, + /// or the last completed depth's until then. `None` before there is any. + pub best: Option, + /// Every root move searched so far, with the main thread's nodes below it, every depth and + /// line together, in the order they were first searched. + pub moves: &'a [(Move, u64)], + /// Nodes searched so far, every thread together. + pub nodes: u64, + /// Time since the search started. + pub time: Duration, + /// What the search is going back over, if it is: reported when it happens. + pub research: Option, +} + +/// What the search goes back over at its root. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RootResearch { + /// This root move, searched after the best, scored above it on its null-window search + /// (PVS), and is being searched again with the full window to see whether it is the new + /// best. + Better(Move), + /// The depth's score came out at or above its aspiration window: at least this. The best + /// move looks better than the last depth said, and the depth is searched again, wider. + FailHigh(Score), + /// The depth's score came out at or below its aspiration window: at most this. The depth is + /// searched again, wider. + FailLow(Score), +} + +/// The main thread's account of its root loop, and whom to tell. +pub(crate) struct RootFollower<'a> { + /// The caller, told every time; it decides what to pass on. + report: &'a mut dyn FnMut(&RootInfo<'_>), + /// When the search started. + start: Instant, + /// The helper threads' nodes, for the total. + helper_nodes: &'a AtomicU64, + /// How many lines are reported: a level's extra candidate lines are searched, and their + /// nodes counted, but they aren't reported, as their lines aren't. + reported: usize, + /// The depth being searched. + depth: u32, + /// The line being searched, from 0. + line: usize, + /// The move being searched, and its place in `moves`. + current: Option<(Move, usize)>, + /// Its place in the order of root moves, from 1. + number: u32, + /// How many root moves the line searches. + of: u32, + /// The line's best move so far. + best: Option, + /// Each root move searched so far and the nodes of its finished searches. + moves: Vec<(Move, u64)>, + /// The thread's node count when the current move's search began. + move_start: u64, +} + +impl<'a> RootFollower<'a> { + /// A follower that tells `report`, for a search that started at `start`, the first + /// `reported` lines. + pub(crate) fn new( + report: &'a mut dyn FnMut(&RootInfo<'_>), + start: Instant, + helper_nodes: &'a AtomicU64, + reported: usize, + ) -> RootFollower<'a> { + RootFollower { + report, + start, + helper_nodes, + reported, + depth: 0, + line: 0, + current: None, + number: 0, + of: 0, + best: None, + moves: Vec::new(), + move_start: 0, + } + } + + /// Line `line` (from 0) is about to be searched to `depth`, over `moves`. `previous` is the + /// line's best move at the last completed depth, its best until this depth has one, unless + /// an earlier line has taken it at this depth. + pub(crate) fn begin_line( + &mut self, + depth: u32, + line: usize, + moves: &[Move], + previous: Option, + ) { + self.depth = depth; + self.line = line; + self.best = previous.filter(|mv| moves.contains(mv)); + self.current = None; + } + + /// The root loop starts searching `mv`, the `number`-th of `of`, `nodes` into the search. + pub(crate) fn begin_move(&mut self, mv: Move, number: u32, of: u32, nodes: u64) { + let index = self.index(mv); + self.current = Some((mv, index)); + self.number = number; + self.of = of; + self.move_start = nodes; + self.report(nodes, None); + } + + /// The current move's search has ended, `nodes` into the search: its nodes are counted, and + /// `best` says whether it raised the score, as the line's new best. + pub(crate) fn end_move(&mut self, nodes: u64, best: bool) { + if let Some((mv, index)) = self.current { + self.moves[index].1 += nodes - self.move_start; + self.move_start = nodes; + if best { + self.best = Some(mv); + } + } + } + + /// The whole depth is to be searched again, starting with `first` of `of` moves, because + /// of `research`: reports it, `nodes` into the search. + pub(crate) fn restart(&mut self, first: Move, of: u32, nodes: u64, research: RootResearch) { + let index = self.index(first); + self.current = Some((first, index)); + self.number = 1; + self.of = of; + self.move_start = nodes; + self.report(nodes, Some(research)); + } + + /// Reports where the root is, `nodes` into the search, with the current move's nodes so + /// far counted in, and `research` if the search is going back over something. + pub(crate) fn report(&mut self, nodes: u64, research: Option) { + let Some((current, index)) = self.current else { + return; + }; + if self.line >= self.reported { + return; + } + // The current move's search so far, counted in for this report only, so nothing is + // allocated. + let partial = nodes - self.move_start; + self.moves[index].1 += partial; + (self.report)(&RootInfo { + depth: self.depth, + multipv: self.line as u32 + 1, + current, + number: self.number, + of: self.of, + best: self.best, + moves: &self.moves, + nodes: nodes + self.helper_nodes.load(Ordering::Relaxed), + time: self.start.elapsed(), + research, + }); + self.moves[index].1 -= partial; + } + + /// `mv`'s place in `moves`, added if it is new. A linear search: a position has a few dozen + /// moves (218 at most), and it runs once per root move searched. + fn index(&mut self, mv: Move) -> usize { + match self.moves.iter().position(|&(m, _)| m == mv) { + Some(index) => index, + None => { + self.moves.push((mv, 0)); + self.moves.len() - 1 + } + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::AtomicBool; + + use cb2026_chess::Position; + + use super::*; + use crate::{Engine, Limits, SearchInfo, SearchResult}; + + /// The position after 1.e4 e5 2.Nf3 Nc6, where White has 27 moves. + const RUY_OR_ITALIAN: &str = "r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3"; + + /// What a test keeps of a report: all of it, its moves copied. + #[derive(Clone, Debug)] + struct Seen { + depth: u32, + multipv: u32, + current: Move, + number: u32, + of: u32, + best: Option, + moves: Vec<(Move, u64)>, + nodes: u64, + research: Option, + } + + /// Searches `fen` to `depth` for `lines` lines on one thread, following the root if + /// `follow`: the result, the lines reported, and what the follower heard. + fn search( + fen: &str, + depth: u32, + lines: usize, + follow: bool, + ) -> (SearchResult, Vec, Vec) { + let mut engine = Engine::new(); + engine.multipv = lines; + let stop = AtomicBool::new(false); + let mut infos = Vec::new(); + let mut seen = Vec::new(); + let mut on_root = |root: &RootInfo<'_>| { + seen.push(Seen { + depth: root.depth, + multipv: root.multipv, + current: root.current, + number: root.number, + of: root.of, + best: root.best, + moves: root.moves.to_vec(), + nodes: root.nodes, + research: root.research, + }); + }; + let result = engine.search_following_root( + &Position::from_fen(fen).unwrap(), + &[], + &Limits::depth(depth), + &stop, + &mut |info| infos.push(info.clone()), + follow.then_some(&mut on_root as &mut dyn FnMut(&RootInfo<'_>)), + ); + (result, infos, seen) + } + + #[test] + fn following_the_root_changes_nothing_in_the_search() { + for lines in [1, 3] { + let (plain, plain_infos, none) = search(RUY_OR_ITALIAN, 8, lines, false); + let (followed, followed_infos, seen) = search(RUY_OR_ITALIAN, 8, lines, true); + assert!(none.is_empty()); + assert!(!seen.is_empty()); + // The same moves and lines, node for node. + assert_eq!(plain, followed); + let without_time = |infos: Vec| { + infos + .into_iter() + .map(|info| (info.depth, info.score, info.nodes, info.pv, info.multipv)) + .collect::>() + }; + assert_eq!(without_time(plain_infos), without_time(followed_infos)); + } + } + + #[test] + fn every_root_move_is_followed_with_the_nodes_below_it() { + let (_, infos, seen) = search(RUY_OR_ITALIAN, 8, 1, true); + let position = Position::from_fen(RUY_OR_ITALIAN).unwrap(); + let legal = position.legal_moves(); + // The first report is the first move of depth 1, before there is a best move. + let first = &seen[0]; + assert_eq!((first.depth, first.number, first.best), (1, 1, None)); + assert_eq!(first.of as usize, legal.len()); + let mut depth = 1; + for report in &seen { + assert!(report.depth >= depth && report.depth <= 8, "{report:?}"); + depth = report.depth; + assert_eq!(report.multipv, 1); + assert_eq!(report.of as usize, legal.len()); + assert!((1..=report.of).contains(&report.number), "{report:?}"); + assert!(legal.contains(&report.current)); + assert!(report.moves.iter().any(|&(mv, _)| mv == report.current)); + // The main thread's nodes below the root moves are some of all the nodes. + let below: u64 = report.moves.iter().map(|&(_, nodes)| nodes).sum(); + assert!( + below <= report.nodes, + "{below} > {}: {report:?}", + report.nodes + ); + } + // Every move was searched, and the nodes only grow. + let last = seen.last().unwrap(); + assert_eq!(last.moves.len(), legal.len()); + for window in seen.windows(2) { + assert!(window[0].nodes <= window[1].nodes); + } + // Once depth 1 has a best move, every later report has one: the depth's best. + assert!( + seen.iter() + .filter(|r| r.depth > 1) + .all(|r| r.best.is_some()) + ); + let best_at_8 = infos.last().unwrap().pv[0]; + assert_eq!(last.best, Some(best_at_8)); + } + + #[test] + fn a_better_move_and_a_window_s_failure_are_heard_when_they_happen() { + // At depth 8 from the start, the search changes its mind seven times, and its score + // falls below its window once. + let (_, _, seen) = search(&Position::startpos().to_fen(), 8, 1, true); + let better: Vec<&Seen> = seen + .iter() + .filter(|r| matches!(r.research, Some(RootResearch::Better(_)))) + .collect(); + assert!( + !better.is_empty(), + "no better move in {} reports", + seen.len() + ); + for report in &better { + // A later move than the first, about itself. + assert!(report.number > 1, "{report:?}"); + assert_eq!(report.research, Some(RootResearch::Better(report.current))); + } + let windows: Vec<&Seen> = seen + .iter() + .filter(|r| { + matches!( + r.research, + Some(RootResearch::FailHigh(_) | RootResearch::FailLow(_)) + ) + }) + .collect(); + assert!(!windows.is_empty(), "no aspiration failure"); + for report in &windows { + // The depth starts again, with the move that failed high if one did. + assert_eq!(report.number, 1, "{report:?}"); + if let Some(RootResearch::FailHigh(_)) = report.research { + assert_eq!(report.best, Some(report.current), "{report:?}"); + } + } + } + + #[test] + fn each_line_of_several_is_followed_over_its_own_moves() { + let (_, _, seen) = search(&Position::startpos().to_fen(), 5, 3, true); + for line in 1..=3 { + let reports: Vec<&Seen> = seen.iter().filter(|r| r.multipv == line).collect(); + assert!(!reports.is_empty(), "line {line}"); + // Each line leaves out the moves of the lines before it. + assert!(reports.iter().all(|r| r.of == 21 - line), "line {line}"); + } + } +} diff --git a/crates/engine/src/search.rs b/crates/engine/src/search.rs index bf3efa6..e467edc 100644 --- a/crates/engine/src/search.rs +++ b/crates/engine/src/search.rs @@ -384,6 +384,7 @@ use crate::eval::{EvalParams, evaluate}; use crate::ordering::{ CONTINUATION_PLIES, MovePicker, OrderingTables, PieceTo, Previous, is_noisy, }; +use crate::root::{RootFollower, RootResearch}; use crate::see::{SEE_VALUES, see}; use crate::stats::{Note, SearchStats, SearchTree}; use crate::tablebase::{self, Tablebase, TablebaseParams}; @@ -999,6 +1000,9 @@ pub(crate) struct Searcher<'a> { nnue: Option>, /// The search tree, when one is being recorded. tree: Option, + /// Whom to tell where the root loop is, when the caller follows it (the main thread only; + /// see [`crate::root`]). + root: Option>, } /// The late move reduction table covers depths and move numbers below this. @@ -1105,6 +1109,7 @@ impl<'a> Searcher<'a> { stats: SearchStats::default(), nnue: None, tree: None, + root: None, } } @@ -1210,6 +1215,46 @@ impl<'a> Searcher<'a> { self.tree.take() } + /// Tells `follower` where the root loop is from now on ([`crate::root`]). + pub(crate) fn follow_root(&mut self, follower: RootFollower<'a>) { + self.root = Some(follower); + } + + /// Tells a root follower, if any, that line `line` (from 0) is about to be searched to + /// `depth` over `moves`, its best move at the last depth having been `previous`. + pub(crate) fn follow_line( + &mut self, + depth: u32, + line: usize, + moves: &[Move], + previous: Option, + ) { + if let Some(root) = &mut self.root { + root.begin_line(depth, line, moves, previous); + } + } + + /// Tells a root follower, if any, that `mv`, a root move searched after the best, beat it + /// on its null-window search and is searched again with the full window. + fn follow_better(&mut self, mv: Move) { + // Only a root move's search: the path holds just the root move then. + if self.path.len() == 1 + && let Some(root) = &mut self.root + { + root.report(self.nodes, Some(RootResearch::Better(mv))); + } + } + + /// Tells a root follower, if any, that the depth is searched again because of `research`, + /// starting with the first of `root_moves`. + fn follow_research(&mut self, root_moves: &[Move], research: RootResearch) { + if let Some(root) = &mut self.root + && let Some(&first) = root_moves.first() + { + root.restart(first, root_moves.len() as u32, self.nodes, research); + } + } + /// What the search has done so far. pub(crate) fn stats(&self) -> SearchStats { self.stats @@ -1262,6 +1307,11 @@ impl<'a> Searcher<'a> { } self.aborted = self.stop.load(Ordering::Relaxed) || self.deadline.is_some_and(|d| Instant::now() >= d); + // A root follower hears where the root is as often, so a long move's nodes show + // growing between root moves. + if let Some(root) = &mut self.root { + root.report(self.nodes, None); + } } self.aborted } @@ -2073,6 +2123,7 @@ impl<'a> Searcher<'a> { if score > alpha && score < beta && !self.aborted { if let Some(mv) = mv { self.note(Note::PvsResearch(mv)); + self.follow_better(mv); } score = self.search_child(child, depth, alpha, beta, false, pv); } @@ -2256,6 +2307,9 @@ impl<'a> Searcher<'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() { + if let Some(root) = &mut self.root { + root.begin_move(mv, index as u32 + 1, root_moves.len() as u32, self.nodes); + } let mut child = pos.clone(); child.make_move(mv); self.push_move(pos, Some(mv)); @@ -2274,6 +2328,11 @@ impl<'a> Searcher<'a> { &mut child_pv, ); self.pop_move(); + if let Some(root) = &mut self.root { + // A move that raised the score is the line's new best. + let best = !self.aborted && score > result.score && score > alpha; + root.end_move(self.nodes, best); + } if self.aborted { break; } @@ -2342,12 +2401,14 @@ impl<'a> Searcher<'a> { } if result.score <= alpha { alpha = (result.score - delta).max(-INFINITY); + self.follow_research(root_moves, RootResearch::FailLow(to_score(result.score))); } else if result.score >= beta { beta = (result.score + delta).min(INFINITY); if let Some(mv) = result.best_move { root_moves.retain(|&m| m != mv); root_moves.insert(0, mv); } + self.follow_research(root_moves, RootResearch::FailHigh(to_score(result.score))); fail_high = Some(result); } else { return result; diff --git a/docs/PRD.md b/docs/PRD.md index b0c22bc..35530d3 100644 --- a/docs/PRD.md +++ b/docs/PRD.md @@ -417,7 +417,10 @@ pondering switch (cjus/chess-node-protocol#18, Solrac Chess AI #319). And it kee (`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 +move?" (Solrac Chess AI #350). And a search can be followed at its root (`rootMs` and +`engine/root`): which root move it is on, the nodes each root move has had, and, at once, a later +move searched again as perhaps the new best or a depth whose score fell outside its aspiration +window, so Solrac's Engine Mind can show the search live (Solrac Chess AI #357). 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 ccd0fe8..cdce628 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, 17:30 MST (M5: the check extension, IIR and three versions of +*Last updated 2026-11-01, 20:00 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; @@ -189,7 +189,17 @@ 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 moves to cjus/chess-node-protocol#22's merge, `deeab77` (#249).* +`cnp` pin moves to cjus/chess-node-protocol#22's merge, `deeab77` (#249). +**cb2026's CNP node follows a search's root** (capability `root`, `rootMs` and `engine/root`, +spec 7.9, cjus/chess-node-protocol#23), for the live search of Solrac's Engine Mind (Solrac +Chess AI #357): `Engine::search_following_root` tells a caller where the main thread's root loop +is (`cb2026_engine::root`): the move it is on, its place and the line's count, the line's best +so far and the nodes below each root move, at every root move and every 1024 nodes, and at +once when a later move beats the best on its null-window search (`better`) or a depth's score +falls outside its aspiration window (`failHigh`, `failLow`). The node passes it on at most +every `rootMs`, research at once; helpers don't follow. Searches are the same node for node +with or without it, and its cost is within noise (PR #250); no functional change. The `cnp` +pin moves to cjus/chess-node-protocol#23's merge, `6274420` (#250).* ## Stages @@ -269,6 +279,7 @@ brackets the root's searches, so an aspiration re-search shows; no functional ch | 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#22's merge, `deeab77`. For Solrac's Engine Mind (Solrac Chess AI #350) | #249 | 767812 | Merged, no functional change | +| CNP following the root: capability `root`, `rootMs` and `engine/root` (spec 7.9). `Engine::search_following_root` tells a caller where the main thread's root loop is (`cb2026_engine::root`): the move it is on, its place, the line's best so far and each root move's nodes, at each root move and every 1024 nodes, and at once on a `better` move (a PVS re-search at the root) or an aspiration `failHigh` or `failLow`; the node throttles it to `rootMs`, research at once. Same search node for node, cost within noise. The `cnp` pin moves to cjus/chess-node-protocol#23's merge, `6274420`. For Solrac's Engine Mind (Solrac Chess AI #357) | #250 | 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