From e9dbb9486c7b72b36e3bb2c7dc3b6c80584f5028 Mon Sep 17 00:00:00 2001 From: cjus Date: Sun, 1 Nov 2026 16:05:45 -0700 Subject: [PATCH 1/3] Engine: the search tree's types (engine/tree, engine/treeNode, capability tree) The tree's request and result, its nodes and their decisions in alpha-beta's terms, the tree limits (maxTreeDepth, maxTreePlies, maxConcurrentTrees) and the error Expired. The spec and the conformance sessions follow. Co-Authored-By: Claude Opus 5.5 --- crates/cnp/src/engine.rs | 329 ++++++++++++++++++++++++++++++ crates/cnp/src/lifecycle.rs | 19 ++ crates/cnp/src/message.rs | 5 +- crates/cnp/tests/messages.rs | 193 ++++++++++++++++++ crates/cnp/tests/spec_examples.rs | 4 + 5 files changed, 549 insertions(+), 1 deletion(-) diff --git a/crates/cnp/src/engine.rs b/crates/cnp/src/engine.rs index aa7262c..0135da0 100644 --- a/crates/cnp/src/engine.rs +++ b/crates/cnp/src/engine.rs @@ -10,6 +10,8 @@ //! | `engine/levels` | request | [`Levels`]: no params → [`LevelsResult`] | //! | `engine/evaluate` | request | [`Evaluate`]: [`EvaluateParams`] → [`EvaluateResult`] | //! | `engine/ponderHit` | request | [`PonderHit`]: [`PonderHitParams`] → `null` | +//! | `engine/tree` | request | [`Tree`]: [`TreeParams`] → [`TreeResult`] | +//! | `engine/treeNode` | request | [`TreeNodePage`]: [`TreeNodeParams`] → [`TreeNodeResult`] | //! //! Positions and moves are chess, not any engine's internals: a FEN and the moves played //! from it, and moves in coordinate notation (`e2e4`, `e7e8q`). Every request stands alone: @@ -24,6 +26,13 @@ //! says the expected move was played. On a miss the client cancels it and starts another. The //! pitfall is time: a ponder search's time limits, the clock included, count from the hit, not //! from the request. +//! +//! **The search tree** (spec, 7.8) is the one thing a node keeps for a client: [`Tree`] searches +//! a position, records which moves the search looked at and what it decided about each, and +//! answers with a handle and the root's children; [`TreeNodePage`] reads one node and a page of +//! its children by the moves that lead to it. A tree is too large for one message, so it is +//! read a part at a time. The handle is a cache, not state a client can rely on: it expires, +//! and then the client asks for the tree again. use std::collections::BTreeMap; @@ -84,6 +93,9 @@ pub struct EngineCapabilities { /// Searching on the opponent's time (`ponder`, `engine/ponderHit`). #[serde(default)] pub ponder: bool, + /// A search's tree, kept for a while (`engine/tree`, `engine/treeNode`). + #[serde(default)] + pub tree: bool, } /// The `engine/search` request: search a position and answer with the best move. @@ -746,6 +758,323 @@ pub struct Term { pub black: i32, } +/// How many plies from the root a tree records when [`TreeParams::plies`] doesn't say: the +/// root's moves and the replies to them. +pub const DEFAULT_TREE_PLIES: u32 = 2; + +/// The `engine/tree` request (capability `tree`): search a position to a depth, keep the +/// search's tree for a while, and answer with a handle to it, the search's result, and the +/// root's children. +/// +/// A tree says which moves the search looked at and what it decided about each: which reply +/// refuted a move, which moves it set aside without a search, which it searched shallower or +/// again. It is the answer to a player's "why not that move?". +/// +/// **Pitfall:** a tree is recorded only near the root ([`TreeParams::plies`]), but the search +/// goes on below it; a node's score comes from the whole search. A node may also stop +/// recording at a cap of its own ([`Recorded::truncated`]): the search's later decisions, +/// the later root moves' among them, are then missing. +pub enum Tree {} + +impl RequestMethod for Tree { + const NAME: &'static str = "engine/tree"; + type Params = TreeParams; + type Result = TreeResult; +} + +/// What to search, and how much of its tree to keep. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TreeParams { + /// The position. + pub position: Position, + /// Search this many plies deep, from 1 to the node's `maxTreeDepth`. + pub depth: u32, + /// Record the nodes up to this many plies from the root, from 1 to the node's + /// `maxTreePlies`. Missing: [`DEFAULT_TREE_PLIES`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plies: Option, + /// How many of the root's children to answer with. Missing: all of them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +impl TreeParams { + /// A tree of `position` searched `depth` plies deep, with the default plies recorded. + pub fn new(position: Position, depth: u32) -> TreeParams { + TreeParams { + position, + depth, + plies: None, + limit: None, + } + } + + /// How many plies from the root the tree records: [`TreeParams::plies`], or + /// [`DEFAULT_TREE_PLIES`]. + pub fn recorded_plies(&self) -> u32 { + self.plies.unwrap_or(DEFAULT_TREE_PLIES) + } +} + +/// A recorded tree: its handle, the search's result, and the root with its first children. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TreeResult { + /// The tree's handle, for `engine/treeNode` on this connection. + pub tree: String, + /// The handle expires once this many milliseconds pass with no request for the tree: from + /// this answer, and again from each `engine/treeNode`. A node may drop it sooner, to keep + /// newer trees. + pub expires_ms: u64, + /// The depth searched, in plies. + pub depth: u32, + /// The deepest any line went, extensions and quiescence included. + #[serde(default)] + pub sel_depth: u32, + /// Nodes searched. + pub nodes: u64, + /// Time spent, in milliseconds. + pub time_ms: u64, + /// The best move, or `null` when the side to move has no legal move. + pub best_move: Option, + /// The best move's score. Missing when there is no legal move. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub score: Option, + /// The best line, starting with the best move. + #[serde(default)] + pub pv: Vec, + /// What the tree holds. + pub recorded: Recorded, + /// The root: the position searched. + pub root: TreeNode, + /// The root's children, the first [`TreeParams::limit`] of them, in the order the search + /// first tried them. + #[serde(default)] + pub children: Vec, +} + +/// What a tree holds. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Recorded { + /// How many plies from the root were recorded. + pub plies: u32, + /// How many nodes the tree holds, the root included. + pub nodes: u64, + /// How many decisions the tree holds, at every node together. + pub decisions: u64, + /// Whether the node stopped recording before the search ended, at a cap of its own. The + /// tree then holds what the search decided until then, and nothing after. + #[serde(default)] + pub truncated: bool, +} + +/// One node of a search tree: a position the search reached, how it searched it, and what it +/// decided there. +/// +/// Scores and windows are from the point of view of the side to move at the node, so a child's +/// window is its parent's turned round: `[-beta, -alpha]`. +/// +/// **Pitfall:** a node may be searched more than once (shallower first, then again; or with +/// a narrow window, then a wider one). Its `depth`, `alpha`, `beta` and `score` are those of +/// the search that gave its score, the last; its [`Decision`]s say what came before. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TreeNode { + /// The move that reaches it from its parent, in coordinate notation. `None` at the root. + #[serde(rename = "move", default, skip_serializing_if = "Option::is_none")] + pub mv: Option, + /// How many plies deep it was searched (the depth still to go when it was reached). + pub depth: u32, + /// The lower edge of its window, the score its side to move already had elsewhere. `None` + /// when the window had no lower edge, and at the root. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub alpha: Option, + /// The upper edge of its window, the score the other side already had elsewhere. `None` + /// when the window had no upper edge, and at the root. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub beta: Option, + /// Its score, with its bound: a lower bound at or above `beta`, an upper bound at or + /// below `alpha`, and otherwise exact. `None` when the recording ended before the node + /// returned. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub score: Option, + /// How many of its children the tree holds. + pub child_count: u32, + /// How many nodes the tree holds below it, at every recorded ply. + pub subtree: u64, + /// What the search decided about it, in the order it decided. + #[serde(default)] + pub decisions: Vec, +} + +/// One decision of the search about a node, in alpha-beta's terms rather than any engine's. +/// +/// A decision with a move names a move from its own node: the reply that refuted it, a move +/// left out, a capture that proved a cutoff. One without is about the node itself. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Decision { + /// What was decided. + #[serde(flatten)] + pub kind: DecisionKind, + /// The id of the technique that decided it, as `engine/techniques` lists it, from a node + /// that offers `techniques`. Missing when no switchable technique applies. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub technique: Option, +} + +impl Decision { + /// A decision of this kind, with no technique named. + pub fn new(kind: DecisionKind) -> Decision { + Decision { + kind, + technique: None, + } + } + + /// The same decision, made by the technique `id`. + pub fn by(mut self, id: impl Into) -> Decision { + self.technique = Some(id.into()); + self + } +} + +/// The kinds of decision (spec, 7.8). In JSON, `kind` and the kind's own fields. +/// +/// Later minor versions may add kinds: a client ignores one it doesn't know, which this crate +/// reads as [`DecisionKind::Unknown`]. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde( + tag = "kind", + rename_all = "camelCase", + rename_all_fields = "camelCase" +)] +pub enum DecisionKind { + /// `mv` scored at or above beta, the `order`-th move searched (from 1), so the node's + /// other moves weren't searched: `mv` refutes the move that led here. + Cutoff { + /// The move, from this node. + #[serde(rename = "move")] + mv: String, + /// Its place among the moves searched at this node, from 1. + order: u32, + }, + /// An earlier search's result for this position, kept in the engine's table, settled it + /// without a search of its own. + Table, + /// Endgame tablebases settled it. + Tablebase, + /// Even passing, as if the side to move could skip its turn, kept the score at or above + /// beta, so the node wasn't searched further. + NullMove, + /// The node was settled before any of its moves was searched, by an estimate that the + /// search wouldn't change the outcome. Its score's bound says which side of the window. + NodePruned { + /// The capture whose shallower search proved it, when one did. + #[serde(rename = "move", default, skip_serializing_if = "Option::is_none")] + mv: Option, + }, + /// `mv` was left out without a search, as a move that couldn't change the outcome. + MovePruned { + /// The move, from this node. + #[serde(rename = "move")] + mv: String, + }, + /// The node was searched this many plies shallower than its place called for, as a move + /// unlikely to matter. + Reduced { + /// How many plies shallower. + plies: u32, + }, + /// The node was searched this many plies deeper than its place called for, as a move that + /// matters more than most. + Extended { + /// How many plies deeper. + plies: u32, + }, + /// The node was searched again. + Research { + /// Why. + reason: ResearchReason, + }, + /// A kind this crate doesn't know, from a later version. Only read, never sent. + #[serde(other)] + Unknown, +} + +/// Why a node was searched again. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ResearchReason { + /// A shallower search's score was above alpha, so it was searched again at its full depth. + Depth, + /// A search with a narrower window scored inside the full one, so it was searched again + /// with the full window to find its exact score. + Window, + /// A reason this crate doesn't know, from a later version. Only read, never sent. + #[serde(other)] + Unknown, +} + +/// The `engine/treeNode` request (capability `tree`): one node of a recorded tree, and a page +/// of its children. +/// +/// A handle the node no longer keeps is [`code::EXPIRED`](crate::code::EXPIRED), and a path +/// that leads to no node of the tree is `InvalidParams`. +pub enum TreeNodePage {} + +impl RequestMethod for TreeNodePage { + const NAME: &'static str = "engine/treeNode"; + type Params = TreeNodeParams; + type Result = TreeNodeResult; +} + +/// Which node to read, and which of its children. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TreeNodeParams { + /// The tree's handle, from `engine/tree`. + pub tree: String, + /// The moves from the root to the node, in coordinate notation. Empty: the root. + #[serde(default)] + pub path: Vec, + /// How many children to skip, in the order the search first tried them. Missing: 0. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub offset: Option, + /// How many children to answer with after those; 0 for the node alone. Missing: the rest. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +impl TreeNodeParams { + /// The node `path` leads to in `tree`, with all its children. + pub fn new>( + tree: impl Into, + path: impl IntoIterator, + ) -> TreeNodeParams { + TreeNodeParams { + tree: tree.into(), + path: path.into_iter().map(Into::into).collect(), + offset: None, + limit: None, + } + } +} + +/// A node, and a page of its children. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TreeNodeResult { + /// The node. Its `child_count` is how many children it has in all. + pub node: TreeNode, + /// Its children from `offset`, at most `limit` of them, in the order the search first + /// tried them. Empty past the last. + #[serde(default)] + pub children: Vec, +} + /// Whether `text` has the form of a move in coordinate notation: two squares, and a promotion /// piece in lower case (`e2e4`, `e7e8q`). It says nothing about legality. pub fn is_move_text(text: &str) -> bool { diff --git a/crates/cnp/src/lifecycle.rs b/crates/cnp/src/lifecycle.rs index e33bb17..bbd6355 100644 --- a/crates/cnp/src/lifecycle.rs +++ b/crates/cnp/src/lifecycle.rs @@ -195,6 +195,15 @@ pub struct Limits { /// The longest message the node reads, in bytes. [`DEFAULT_MAX_MESSAGE_BYTES`] if missing. #[serde(default, skip_serializing_if = "Option::is_none")] pub max_message_bytes: Option, + /// The deepest `engine/tree` search, in plies. `max_depth` if missing. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_tree_depth: Option, + /// The most plies from the root an `engine/tree` records. No limit if missing. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_tree_plies: Option, + /// How many `engine/tree` searches may run at once, besides the searches. 1 if missing. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_concurrent_trees: Option, } impl Limits { @@ -212,6 +221,16 @@ impl Limits { pub fn message_bytes(&self) -> u64 { self.max_message_bytes.unwrap_or(DEFAULT_MAX_MESSAGE_BYTES) } + + /// The deepest `engine/tree` search: `max_tree_depth`, or else `max_depth`, or none. + pub fn tree_depth(&self) -> Option { + self.max_tree_depth.or(self.max_depth) + } + + /// How many `engine/tree` searches may run at once. + pub fn concurrent_trees(&self) -> u32 { + self.max_concurrent_trees.unwrap_or(1) + } } /// The `data` of an [`code::INCOMPATIBLE_VERSION`](crate::code::INCOMPATIBLE_VERSION) error: diff --git a/crates/cnp/src/message.rs b/crates/cnp/src/message.rs index e6dacd9..1c9bc84 100644 --- a/crates/cnp/src/message.rs +++ b/crates/cnp/src/message.rs @@ -58,7 +58,7 @@ pub mod code { pub const INVALID_POSITION: i64 = -32011; /// A request goes beyond the limits the node advertised. pub const LIMIT_EXCEEDED: i64 = -32012; - /// The node is already running as many searches as it can. + /// The node is already running as many searches, or `engine/tree` searches, as it can. pub const BUSY: i64 = -32013; /// The request needs a capability the node didn't offer. pub const UNSUPPORTED: i64 = -32014; @@ -68,6 +68,9 @@ pub mod code { pub const SHUTTING_DOWN: i64 = -32016; /// What the request needs isn't ready yet (a voice model still downloading). pub const NOT_READY: i64 = -32017; + /// A handle the node no longer keeps, or never gave: an `engine/tree`'s tree that has + /// expired. Ask for it again. + pub const EXPIRED: i64 = -32018; } /// A request's id: a number or a string, chosen by whoever sends the request. diff --git a/crates/cnp/tests/messages.rs b/crates/cnp/tests/messages.rs index 06520d1..2a2c0f1 100644 --- a/crates/cnp/tests/messages.rs +++ b/crates/cnp/tests/messages.rs @@ -374,6 +374,199 @@ fn an_evaluation_can_settle_captures_and_value_each_piece() { assert!(offered.quiet && offered.pieces); } +#[test] +fn a_tree_request_leaves_out_what_it_doesn_t_ask_and_defaults_its_plies() { + let plain = engine::TreeParams::new(Position::start(), 12); + let value = serde_json::to_value(&plain).unwrap(); + assert_eq!( + value, + json!({"position": {"fen": engine::START_FEN}, "depth": 12}) + ); + assert_eq!(plain.recorded_plies(), engine::DEFAULT_TREE_PLIES); + let asked = engine::TreeParams { + plies: Some(3), + limit: Some(5), + ..plain + }; + assert_eq!(asked.recorded_plies(), 3); + let value = serde_json::to_value(&asked).unwrap(); + assert_eq!( + (value["plies"].clone(), value["limit"].clone()), + (json!(3), json!(5)) + ); + assert_eq!( + serde_json::from_value::(value).unwrap(), + asked + ); + // A page: the path from the root, and an offset and limit only when asked. + let page = engine::TreeNodeParams::new("t1", ["e2e4", "c7c5"]); + assert_eq!( + serde_json::to_value(&page).unwrap(), + json!({"tree": "t1", "path": ["e2e4", "c7c5"]}) + ); + let root: engine::TreeNodeParams = serde_json::from_value(json!({"tree": "t1"})).unwrap(); + assert_eq!((root.path, root.offset, root.limit), (vec![], None, None)); +} + +#[test] +fn a_tree_node_has_its_window_its_bounded_score_and_its_decisions() { + use engine::{Decision, DecisionKind, ResearchReason}; + + let node = engine::TreeNode { + mv: Some("f1c4".to_string()), + depth: 15, + alpha: Some(Score::cp(-31)), + beta: Some(Score::cp(-30)), + score: Some(Score { + value: ScoreValue::Centipawns(-12), + bound: Bound::Lower, + }), + child_count: 1, + subtree: 14, + decisions: vec![ + Decision::new(DecisionKind::Reduced { plies: 1 }).by("lmr"), + Decision::new(DecisionKind::Research { + reason: ResearchReason::Depth, + }) + .by("lmr"), + Decision::new(DecisionKind::Cutoff { + mv: "g8f6".to_string(), + order: 1, + }) + .by("alphabeta"), + ], + }; + let value = serde_json::to_value(&node).unwrap(); + assert_eq!( + value, + json!({"move": "f1c4", "depth": 15, "alpha": {"cp": -31}, "beta": {"cp": -30}, + "score": {"cp": -12, "bound": "lower"}, "childCount": 1, "subtree": 14, + "decisions": [ + {"kind": "reduced", "plies": 1, "technique": "lmr"}, + {"kind": "research", "reason": "depth", "technique": "lmr"}, + {"kind": "cutoff", "move": "g8f6", "order": 1, "technique": "alphabeta"}]}) + ); + assert_eq!( + serde_json::from_value::(value).unwrap(), + node + ); + + // The root: no move and no window. A window's missing edge means it had none. + let root: engine::TreeNode = serde_json::from_value( + json!({"depth": 16, "score": {"cp": 31}, "childCount": 27, "subtree": 802}), + ) + .unwrap(); + assert_eq!((root.mv, root.alpha, root.beta), (None, None, None)); + assert!(root.decisions.is_empty()); + + // Each kind, as JSON has it; a node-level one with and without a move. + let kinds = [ + ( + json!({"kind": "table", "technique": "tt"}), + DecisionKind::Table, + ), + (json!({"kind": "tablebase"}), DecisionKind::Tablebase), + ( + json!({"kind": "nullMove", "technique": "nullmove"}), + DecisionKind::NullMove, + ), + ( + json!({"kind": "nodePruned", "technique": "rfp"}), + DecisionKind::NodePruned { mv: None }, + ), + ( + json!({"kind": "nodePruned", "move": "c3d5", "technique": "probcut"}), + DecisionKind::NodePruned { + mv: Some("c3d5".to_string()), + }, + ), + ( + json!({"kind": "movePruned", "move": "a2a3", "technique": "lmp"}), + DecisionKind::MovePruned { + mv: "a2a3".to_string(), + }, + ), + ( + json!({"kind": "extended", "plies": 1, "technique": "singular"}), + DecisionKind::Extended { plies: 1 }, + ), + ( + json!({"kind": "research", "reason": "window", "technique": "pvs"}), + DecisionKind::Research { + reason: ResearchReason::Window, + }, + ), + ]; + for (value, kind) in kinds { + let decision: Decision = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(decision.kind, kind); + assert_eq!(serde_json::to_value(&decision).unwrap(), value); + } + // A later version's kind, or reason, is read rather than refused, so a client can skip it. + let later: Decision = + serde_json::from_value(json!({"kind": "aspiration", "technique": "x", "by": 3})).unwrap(); + assert_eq!(later.kind, DecisionKind::Unknown); + let later: Decision = + serde_json::from_value(json!({"kind": "research", "reason": "aspiration"})).unwrap(); + assert_eq!( + later.kind, + DecisionKind::Research { + reason: ResearchReason::Unknown + } + ); + // A cutoff names its move. + assert!(serde_json::from_value::(json!({"kind": "cutoff", "order": 1})).is_err()); +} + +#[test] +fn a_tree_says_what_it_holds_and_the_tree_capability_and_limits_are_offered() { + let result: engine::TreeResult = serde_json::from_value(json!({ + "tree": "t1", "expiresMs": 300000, "depth": 4, "nodes": 900, "timeMs": 3, + "bestMove": "e2e4", "score": {"cp": 30}, "pv": ["e2e4", "e7e5"], + "recorded": {"plies": 2, "nodes": 61, "decisions": 75}, + "root": {"depth": 4, "score": {"cp": 30}, "childCount": 20, "subtree": 60}, + "children": [] + })) + .unwrap(); + assert!(!result.recorded.truncated); + assert_eq!(result.sel_depth, 0); + // No legal move: no best move and no score, as for a search. + let mated: engine::TreeResult = serde_json::from_value(json!({ + "tree": "t2", "expiresMs": 300000, "depth": 0, "nodes": 0, "timeMs": 0, + "bestMove": null, "pv": [], + "recorded": {"plies": 2, "nodes": 1, "decisions": 0}, + "root": {"depth": 0, "childCount": 0, "subtree": 0} + })) + .unwrap(); + assert_eq!((mated.best_move, mated.score), (None, None)); + assert!(mated.children.is_empty()); + + let offered: engine::EngineCapabilities = serde_json::from_value(json!({})).unwrap(); + assert!(!offered.tree); + let offered: engine::EngineCapabilities = + serde_json::from_value(json!({"tree": true})).unwrap(); + assert!(offered.tree); + // A tree's depth falls back on maxDepth, and one tree at a time is the default. + let limits: lifecycle::Limits = serde_json::from_value(json!({"maxDepth": 64})).unwrap(); + assert_eq!( + (limits.tree_depth(), limits.concurrent_trees()), + (Some(64), 1) + ); + let limits: lifecycle::Limits = serde_json::from_value( + json!({"maxDepth": 64, "maxTreeDepth": 24, "maxTreePlies": 6, "maxConcurrentTrees": 2}), + ) + .unwrap(); + assert_eq!( + ( + limits.tree_depth(), + limits.max_tree_plies, + limits.concurrent_trees() + ), + (Some(24), Some(6), 2) + ); + assert_eq!(code::EXPIRED, -32018); +} + #[test] fn versions_are_text_and_agree_on_the_major_version() { let v: Version = serde_json::from_value(json!("1.3")).unwrap(); diff --git a/crates/cnp/tests/spec_examples.rs b/crates/cnp/tests/spec_examples.rs index 58bb3ee..e955012 100644 --- a/crates/cnp/tests/spec_examples.rs +++ b/crates/cnp/tests/spec_examples.rs @@ -41,6 +41,8 @@ fn request_params(request: &Request) -> Result<(), String> { "engine/levels" => check::(request), "engine/evaluate" => check::(request), "engine/ponderHit" => check::(request), + "engine/tree" => check::(request), + "engine/treeNode" => check::(request), "voice/voices" => check::(request), "voice/speak" => check::(request), "voice/transcribe" => check::(request), @@ -68,6 +70,8 @@ fn response_result(method: &str, response: &Response) -> Result<(), String> { "engine/levels" => check::(response), "engine/evaluate" => check::(response), "engine/ponderHit" => check::(response), + "engine/tree" => check::(response), + "engine/treeNode" => check::(response), "voice/voices" => check::(response), "voice/speak" => check::(response), "voice/transcribe" => check::(response), From dcf54f7101de069954ce8c85d89557f820b3b71b Mon Sep 17 00:00:00 2001 From: cjus Date: Sun, 1 Nov 2026 16:24:14 -0700 Subject: [PATCH 2/3] Engine: the search tree in the spec (7.8) and its conformance sessions engine/tree searches a position and keeps its tree under a handle that expires; engine/treeNode reads a node and a page of its children by its path. A node is its last search: its window, its score bounded by that window, its children and its decisions, which are alpha-beta's (cutoff, table, tablebase, nullMove, nodePruned, movePruned, reduced, extended, research), each naming the engine/techniques id behind it. The capability tree, the limits maxTreeDepth, maxTreePlies and maxConcurrentTrees, and the error Expired (-32018), recorded in 1.0's changes and taken off the reserved names. The examples are cb2026's tree of 7.1's position. Seven sessions: reading a tree, its errors, its limits, a tree during a search, a cancelled one, a checkmated position, and a node without tree (cjus/chessgui#350). Co-Authored-By: Claude Opus 5.5 --- conformance/README.md | 2 +- conformance/engine/tree-cancel.jsonl | 11 ++ conformance/engine/tree-checkmated.jsonl | 9 + conformance/engine/tree-errors.jsonl | 18 ++ conformance/engine/tree-limits.jsonl | 11 ++ conformance/engine/tree-unsupported.jsonl | 11 ++ conformance/engine/tree-while-searching.jsonl | 12 ++ conformance/engine/tree.jsonl | 17 ++ crates/cnp/src/engine.rs | 8 +- spec/cnp.md | 168 +++++++++++++++++- 10 files changed, 254 insertions(+), 13 deletions(-) create mode 100644 conformance/engine/tree-cancel.jsonl create mode 100644 conformance/engine/tree-checkmated.jsonl create mode 100644 conformance/engine/tree-errors.jsonl create mode 100644 conformance/engine/tree-limits.jsonl create mode 100644 conformance/engine/tree-unsupported.jsonl create mode 100644 conformance/engine/tree-while-searching.jsonl create mode 100644 conformance/engine/tree.jsonl diff --git a/conformance/README.md b/conformance/README.md index 30395a4..2e0fd43 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -15,7 +15,7 @@ conforms to CNP 1.0 if it passes every session that applies to it. | Directory | What it checks | Applies to | | --- | --- | --- | | `lifecycle/` | `initialize`, `ping`, `shutdown`, `exit`, cancelling, and the errors around them (spec 4, 5, 9) | Every node | -| `engine/` | Searches, stop and cancel, each engine capability, and pondering's hit and miss (spec 7) | Engine nodes | +| `engine/` | Searches, stop and cancel, each engine capability, pondering's hit and miss, and the search tree: reading it, its errors and limits, during a search and cancelled (spec 7) | Engine nodes | | `voice/` | Voices, models, refusing bad requests, and audio for a listen that isn't there (spec 8) | Voice nodes | | `preferences/` | The draft preferences extension's read (`spec/preferences.md`) | Nodes that keep preferences | | `games/` | The draft games extension: a save, its retry, a reused version, get, list, searching, deleting, importing and a game's source (`spec/games.md`) | Nodes that keep games (searching, deleting, importing and sources: those that offer them) | diff --git a/conformance/engine/tree-cancel.jsonl b/conformance/engine/tree-cancel.jsonl new file mode 100644 index 0000000..6687745 --- /dev/null +++ b/conformance/engine/tree-cancel.jsonl @@ -0,0 +1,11 @@ +{"session": "tree-cancel", "description": "$/cancelRequest drops a tree, which answers Cancelled, and the next tree isn't Busy because of it (spec 4.1, 7.8)", "requires": ["engine", "engine.tree"]} +{"send": {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocol": "1.0", "client": {"name": "cnp-conformance", "version": "1.0"}}}} +{"expect": {"id": 1, "result": {"protocol": "1.0", "node": {"name": "$string", "version": "$string", "license": "$string"}, "capabilities": "$object"}}} +{"send": {"jsonrpc": "2.0", "id": 2, "method": "engine/tree", "params": {"position": {"fen": "r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 4 4"}, "depth": 12, "plies": 1}}} +{"send": {"jsonrpc": "2.0", "method": "$/cancelRequest", "params": {"id": 2}}} +{"send": {"jsonrpc": "2.0", "id": 3, "method": "engine/tree", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "depth": 2, "plies": 1}}} +{"expectAll": [{"id": 2, "error": {"code": -32800, "message": "$string"}}, {"id": 3, "result": {"tree": "$string", "bestMove": "$move"}}]} +{"send": {"jsonrpc": "2.0", "id": 99, "method": "shutdown"}} +{"expect": {"id": 99, "result": null}} +{"send": {"jsonrpc": "2.0", "method": "exit"}} +{"expectExit": 0} diff --git a/conformance/engine/tree-checkmated.jsonl b/conformance/engine/tree-checkmated.jsonl new file mode 100644 index 0000000..e9aad84 --- /dev/null +++ b/conformance/engine/tree-checkmated.jsonl @@ -0,0 +1,9 @@ +{"session": "tree-checkmated", "description": "a tree of a position with no legal move answers at once: no best move, no score, depth 0, and the root alone (spec 7.8)", "requires": ["engine", "engine.tree"]} +{"send": {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocol": "1.0", "client": {"name": "cnp-conformance", "version": "1.0"}}}} +{"expect": {"id": 1, "result": {"protocol": "1.0", "node": {"name": "$string", "version": "$string", "license": "$string"}, "capabilities": "$object"}}} +{"send": {"jsonrpc": "2.0", "id": 2, "method": "engine/tree", "params": {"position": {"fen": "rnb1kbnr/pppp1ppp/8/4p3/6Pq/5P2/PPPPP2P/RNBQKBNR w KQkq - 1 3"}, "depth": 6}}} +{"expect": {"id": 2, "result": {"tree": "$string", "depth": 0, "bestMove": null, "score": "$absent", "pv": [], "recorded": {"nodes": 1}, "root": {"move": "$absent", "childCount": 0, "subtree": 0}, "children": []}}} +{"send": {"jsonrpc": "2.0", "id": 99, "method": "shutdown"}} +{"expect": {"id": 99, "result": null}} +{"send": {"jsonrpc": "2.0", "method": "exit"}} +{"expectExit": 0} diff --git a/conformance/engine/tree-errors.jsonl b/conformance/engine/tree-errors.jsonl new file mode 100644 index 0000000..589439d --- /dev/null +++ b/conformance/engine/tree-errors.jsonl @@ -0,0 +1,18 @@ +{"session": "tree-errors", "description": "a handle the node never gave is Expired, a path to no node of the tree and a depth of 0 are InvalidParams, and an invalid FEN is InvalidPosition (spec 7.8, 9)", "requires": ["engine", "engine.tree"]} +{"send": {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocol": "1.0", "client": {"name": "cnp-conformance", "version": "1.0"}}}} +{"expect": {"id": 1, "result": {"protocol": "1.0", "node": {"name": "$string", "version": "$string", "license": "$string"}, "capabilities": "$object"}}} +{"send": {"jsonrpc": "2.0", "id": 2, "method": "engine/treeNode", "params": {"tree": "never-given", "path": []}}} +{"expect": {"id": 2, "error": {"code": -32018, "message": "$string"}}} +{"send": {"jsonrpc": "2.0", "id": 3, "method": "engine/tree", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "depth": 0}}} +{"expect": {"id": 3, "error": {"code": -32602, "message": "$string"}}} +{"send": {"jsonrpc": "2.0", "id": 4, "method": "engine/tree", "params": {"position": {"fen": "not a fen"}, "depth": 2}}} +{"expect": {"id": 4, "error": {"code": -32011, "message": "$string"}}} +{"send": {"jsonrpc": "2.0", "id": 5, "method": "engine/tree", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "depth": 2, "plies": 1, "limit": 0}}} +{"expect": {"id": 5, "result": {"tree": "$bind:TREE", "children": []}}} +{"comment": "No root move goes from e1 to e8, and the tree records one ply only."} +{"send": {"jsonrpc": "2.0", "id": 6, "method": "engine/treeNode", "params": {"tree": "$ref:TREE", "path": ["e1e8"]}}} +{"expect": {"id": 6, "error": {"code": -32602, "message": "$string"}}} +{"send": {"jsonrpc": "2.0", "id": 99, "method": "shutdown"}} +{"expect": {"id": 99, "result": null}} +{"send": {"jsonrpc": "2.0", "method": "exit"}} +{"expectExit": 0} diff --git a/conformance/engine/tree-limits.jsonl b/conformance/engine/tree-limits.jsonl new file mode 100644 index 0000000..4ca3995 --- /dev/null +++ b/conformance/engine/tree-limits.jsonl @@ -0,0 +1,11 @@ +{"session": "tree-limits", "description": "a tree deeper than maxTreeDepth, or recording more plies than maxTreePlies, is LimitExceeded, not trimmed (spec 6.3, 7.8)", "requires": ["engine", "engine.tree", "limits.maxTreeDepth", "limits.maxTreePlies"]} +{"send": {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocol": "1.0", "client": {"name": "cnp-conformance", "version": "1.0"}}}} +{"expect": {"id": 1, "result": {"protocol": "1.0", "node": {"name": "$string", "version": "$string", "license": "$string"}, "capabilities": "$object"}}} +{"send": {"jsonrpc": "2.0", "id": 2, "method": "engine/tree", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "depth": 4294967295}}} +{"expect": {"id": 2, "error": {"code": -32012, "message": "$string"}}} +{"send": {"jsonrpc": "2.0", "id": 3, "method": "engine/tree", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "depth": 2, "plies": 4294967295}}} +{"expect": {"id": 3, "error": {"code": -32012, "message": "$string"}}} +{"send": {"jsonrpc": "2.0", "id": 99, "method": "shutdown"}} +{"expect": {"id": 99, "result": null}} +{"send": {"jsonrpc": "2.0", "method": "exit"}} +{"expectExit": 0} diff --git a/conformance/engine/tree-unsupported.jsonl b/conformance/engine/tree-unsupported.jsonl new file mode 100644 index 0000000..cfa6075 --- /dev/null +++ b/conformance/engine/tree-unsupported.jsonl @@ -0,0 +1,11 @@ +{"session": "tree-unsupported", "description": "a node without tree refuses engine/tree and engine/treeNode with Unsupported (spec 6.1, 7.8)", "requires": ["engine", "!engine.tree"]} +{"send": {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocol": "1.0", "client": {"name": "cnp-conformance", "version": "1.0"}}}} +{"expect": {"id": 1, "result": {"protocol": "1.0", "node": {"name": "$string", "version": "$string", "license": "$string"}, "capabilities": "$object"}}} +{"send": {"jsonrpc": "2.0", "id": 2, "method": "engine/tree", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "depth": 2}}} +{"expect": {"id": 2, "error": {"code": -32014, "message": "$string"}}} +{"send": {"jsonrpc": "2.0", "id": 3, "method": "engine/treeNode", "params": {"tree": "t1", "path": []}}} +{"expect": {"id": 3, "error": {"code": -32014, "message": "$string"}}} +{"send": {"jsonrpc": "2.0", "id": 99, "method": "shutdown"}} +{"expect": {"id": 99, "result": null}} +{"send": {"jsonrpc": "2.0", "method": "exit"}} +{"expectExit": 0} diff --git a/conformance/engine/tree-while-searching.jsonl b/conformance/engine/tree-while-searching.jsonl new file mode 100644 index 0000000..1e11522 --- /dev/null +++ b/conformance/engine/tree-while-searching.jsonl @@ -0,0 +1,12 @@ +{"session": "tree-while-searching", "description": "a tree is answered while a search runs: it counts toward maxConcurrentTrees, not maxConcurrentSearches (spec 7.8)", "requires": ["engine", "engine.tree"]} +{"send": {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocol": "1.0", "client": {"name": "cnp-conformance", "version": "1.0"}}}} +{"expect": {"id": 1, "result": {"protocol": "1.0", "node": {"name": "$string", "version": "$string", "license": "$string"}, "capabilities": "$object"}}} +{"send": {"jsonrpc": "2.0", "id": 2, "method": "engine/search", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "limits": {"infinite": true}}}} +{"send": {"jsonrpc": "2.0", "id": 3, "method": "engine/tree", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "depth": 3, "plies": 1}}} +{"expect": {"id": 3, "result": {"tree": "$string", "depth": 3, "bestMove": "$move", "root": "$object", "children": "$array"}}} +{"send": {"jsonrpc": "2.0", "method": "$/cancelRequest", "params": {"id": 2}}} +{"expect": {"id": 2, "error": {"code": -32800, "message": "$string"}}} +{"send": {"jsonrpc": "2.0", "id": 99, "method": "shutdown"}} +{"expect": {"id": 99, "result": null}} +{"send": {"jsonrpc": "2.0", "method": "exit"}} +{"expectExit": 0} diff --git a/conformance/engine/tree.jsonl b/conformance/engine/tree.jsonl new file mode 100644 index 0000000..b425c1a --- /dev/null +++ b/conformance/engine/tree.jsonl @@ -0,0 +1,17 @@ +{"session": "tree", "description": "engine/tree answers with a handle, the search's result and the root's first children, and engine/treeNode reads the root and a child by its path, a page at a time (spec 7.8)", "requires": ["engine", "engine.tree"]} +{"send": {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocol": "1.0", "client": {"name": "cnp-conformance", "version": "1.0"}}}} +{"expect": {"id": 1, "result": {"protocol": "1.0", "node": {"name": "$string", "version": "$string", "license": "$string"}, "capabilities": "$object"}}} +{"send": {"jsonrpc": "2.0", "id": 2, "method": "engine/tree", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "moves": ["e2e4", "e7e5"]}, "depth": 4, "plies": 2, "limit": 1}}} +{"expect": {"id": 2, "result": {"tree": "$bind:TREE", "expiresMs": "$integer", "depth": 4, "nodes": "$integer", "timeMs": "$integer", "bestMove": "$move", "score": "$object", "pv": "$array", "recorded": {"plies": 2, "nodes": "$integer", "decisions": "$integer", "truncated": false}, "root": {"move": "$absent", "depth": 4, "score": "$object", "childCount": "$integer", "subtree": "$integer", "decisions": "$array"}, "children": [{"move": "$bind:FIRST", "depth": "$integer", "childCount": "$integer", "subtree": "$integer", "decisions": "$array"}]}}} +{"comment": "The root again, and its first child, which must be the same."} +{"send": {"jsonrpc": "2.0", "id": 3, "method": "engine/treeNode", "params": {"tree": "$ref:TREE", "path": [], "limit": 1}}} +{"expect": {"id": 3, "result": {"node": {"move": "$absent", "depth": 4, "childCount": "$integer"}, "children": [{"move": "$ref:FIRST"}]}}} +{"comment": "The first child alone, with a limit of 0, then with all its children."} +{"send": {"jsonrpc": "2.0", "id": 4, "method": "engine/treeNode", "params": {"tree": "$ref:TREE", "path": ["$ref:FIRST"], "limit": 0}}} +{"expect": {"id": 4, "result": {"node": {"move": "$ref:FIRST", "depth": "$integer", "childCount": "$integer", "subtree": "$integer", "decisions": "$array"}, "children": []}}} +{"send": {"jsonrpc": "2.0", "id": 5, "method": "engine/treeNode", "params": {"tree": "$ref:TREE", "path": ["$ref:FIRST"]}}} +{"expect": {"id": 5, "result": {"node": {"move": "$ref:FIRST"}, "children": "$array"}}} +{"send": {"jsonrpc": "2.0", "id": 99, "method": "shutdown"}} +{"expect": {"id": 99, "result": null}} +{"send": {"jsonrpc": "2.0", "method": "exit"}} +{"expectExit": 0} diff --git a/crates/cnp/src/engine.rs b/crates/cnp/src/engine.rs index 0135da0..cc6968e 100644 --- a/crates/cnp/src/engine.rs +++ b/crates/cnp/src/engine.rs @@ -982,14 +982,14 @@ pub enum DecisionKind { #[serde(rename = "move")] mv: String, }, - /// The node was searched this many plies shallower than its place called for, as a move - /// unlikely to matter. + /// The node was searched this many plies shallower than its place called for, its move + /// judged unlikely to change the outcome. Reduced { /// How many plies shallower. plies: u32, }, - /// The node was searched this many plies deeper than its place called for, as a move that - /// matters more than most. + /// The node was searched this many plies deeper than its place called for, its move judged + /// to matter more than most, such as a forced one. Extended { /// How many plies deeper. plies: u32, diff --git a/spec/cnp.md b/spec/cnp.md index 2d5e1b8..cc69e0e 100644 --- a/spec/cnp.md +++ b/spec/cnp.md @@ -43,7 +43,10 @@ The words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in request can be sent again, and a reconnection loses nothing. Hints that only make a node faster are allowed, such as "the same game as before", because a node that ignores them still answers correctly. Durations are counted from when the node receives the request, never as - clock times, since clocks on different machines differ. + clock times, since clocks on different machines differ. The one exception is a search tree's + handle ([7.8](#78-the-search-tree)), which names a tree an earlier request recorded, so that a + client can read a large tree a part at a time. It is a cache: a client that has lost it asks + for the tree again. - **Each side says what it supports.** A node lists its capabilities and limits when the connection starts, so an engine can implement part of the protocol, and a client knows what to offer. @@ -249,6 +252,7 @@ Every engine node answers `engine/search` with the limits `depth`, `nodes`, `tim | `quiet` | `quiet` on `engine/evaluate`: settling captures before evaluating ([7.6](#76-engineevaluate)) | | `pieces` | `pieces` on `engine/evaluate`, and `searchScore` in its result: what each piece is worth to the search's evaluation ([7.6](#76-engineevaluate)) | | `ponder` | `ponder`, and `engine/ponderHit`: searching on the opponent's time ([7.7](#77-pondering)) | +| `tree` | `engine/tree` and `engine/treeNode`: a search's tree, kept for a while ([7.8](#78-the-search-tree)) | ### 6.3 Limits @@ -263,6 +267,9 @@ Every engine node answers `engine/search` with the limits `depth`, `nodes`, `tim | `maxMultipv` | integer | 1 | The most lines one search may return | | `maxConcurrentSearches` | integer | 1 | How many searches may run at once, ponder searches included; one more is refused with `Busy` | | `maxMessageBytes` | integer | 16777216 | The longest message the node reads | +| `maxTreeDepth` | integer | `maxDepth` | The deepest `engine/tree` search, in plies | +| `maxTreePlies` | integer | none | The most plies from the root an `engine/tree` records | +| `maxConcurrentTrees` | integer | 1 | How many `engine/tree` searches may run at once, besides the searches; one more is refused with `Busy` | ## 7. The engine domain @@ -275,6 +282,8 @@ Every engine node answers `engine/search` with the limits `depth`, `nodes`, `tim | `engine/levels` | request | The playing levels and their ratings | | `engine/evaluate` | request | A position's evaluation without a search, term by term | | `engine/ponderHit` | request | The move a ponder search expected was played: search on the clock now | +| `engine/tree` | request | Search a position and keep its tree for a while | +| `engine/treeNode` | request | One node of a kept tree, and a page of its children | ### 7.1 `engine/search` @@ -512,6 +521,147 @@ after it. A hit for a search that has already answered, or that never existed, o had its hit, is not an error, because the messages can cross; its result is `null` and it does nothing. A hit for a running search that isn't a ponder search is `InvalidParams`. +### 7.8 The search tree + +Needs `tree`. A search's tree says which moves the search looked at and what it decided about +each: which reply refuted a move, which moves it left out without a search, which it searched +shallower, deeper or again. It answers a player's "why not that move?". A tree has hundreds or +thousands of nodes, so the node keeps it for a while and the client reads it a part at a time: +`engine/tree` searches a position and answers with a handle, the search's result and the root's +children, and `engine/treeNode` reads any node of the tree and a page of its children. + +The handle is the one exception to requests standing alone ([1](#1-design)): it names a tree an +earlier request recorded. It is a cache, good only on the connection that asked for it, and it +expires. A client whose handle has expired, or that has reconnected, asks for the tree again. A +node SHOULD record a tree as a deterministic search does (one thread, a cleared hash table, the +default techniques), so that the same request gives the same tree. + +**`engine/tree`.** Params: + +| Field | Type | | +| --- | --- | --- | +| `position` | object | The position ([2](#2-conventions)) | +| `depth` | integer | Search this many plies deep, from 1 to `maxTreeDepth` ([6.3](#63-limits)) | +| `plies` | integer | Record the nodes up to this many plies from the root, from 1 to `maxTreePlies`. Missing: 2, the root's moves and the replies to them | +| `limit` | integer | How many of the root's children to answer with. Missing: all of them | + +A tree's search is a full-strength search with the node's default techniques. A position whose +FEN isn't valid, or with a move that isn't legal, is answered with `InvalidPosition`; a `depth` +or `plies` of 0 with `InvalidParams`, and one beyond the node's limits with `LimitExceeded`. + +A tree's search counts toward `maxConcurrentTrees`, not `maxConcurrentSearches`, so that a +client can ask for a tree while the engine plays. One more is refused with `Busy`, but, as for +searches ([7.7](#77-pondering)), not because of a tree whose `$/cancelRequest` the node has read. +A cancelled tree answers `Cancelled` and keeps nothing. `engine/stop` doesn't end a tree's +search, since a tree is wanted whole or not at all. A tree's search keeps to the node's +`maxTimeMs` as every search does, and one that reaches it is answered with `LimitExceeded`. + +Result: + +| Field | Type | | +| --- | --- | --- | +| `tree` | string | The tree's handle, for `engine/treeNode` on this connection | +| `expiresMs` | integer | The handle expires once this long passes with no request for the tree: from this answer, and again from each `engine/treeNode` for it. A node MAY drop a tree sooner, to keep newer ones | +| `depth`, `selDepth`, `nodes`, `timeMs` | integers | As in a search's result ([7.1](#71-enginesearch)) | +| `bestMove` | move or `null` | The best move. `null` when the side to move has no legal move | +| `score` | score | The best move's score. Missing when there is no legal move | +| `pv` | array of moves | The best line, starting with the best move | +| `recorded` | object | What the tree holds: `plies`; `nodes`, the root included; `decisions`, at every node together; and `truncated`, whether the node stopped recording at a cap of its own before the search ended. A truncated tree holds what the search decided until then and nothing after, the later root moves' nodes among it | +| `root` | node | The root, the position searched (below) | +| `children` | array of nodes | The root's children, the first `limit` of them, in the order the search first tried them | + +A position with no legal move is answered at once, as a search is: `bestMove` is `null`, there +is no `score`, `depth` is 0, and the tree is its root alone. + +**A node** of the tree is a position the search reached. The search may search a node more than +once: shallower first and then again, or with a narrow window and then a wider one. 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, after the decisions that say how it came to be searched that +way. + +| Field | Type | | +| --- | --- | --- | +| `move` | move | The move that reaches it from its parent. Missing at the root | +| `depth` | integer | How many plies deep it was searched: the depth still to go when it was reached | +| `alpha`, `beta` | scores | Its window: the score the side to move already had elsewhere (`alpha`), and the score the other side already had (`beta`), always exact. An edge is left out when the window had none on that side | +| `score` | score | Its score, with its bound: `lower` at or above `beta` (the side to move found enough, so the move that led here is refuted), `upper` at or below `alpha` (no better for the side to move than what it already had), and otherwise exact. Missing when the recording ended before the node returned | +| `childCount` | integer | How many of its children the tree holds | +| `subtree` | integer | How many nodes the tree holds below it, at every recorded ply | +| `decisions` | array | What the search decided about it, in the order it decided (below) | + +Scores and windows are from the point of view of the side to move at the node, as everywhere +([2](#2-conventions)), so a child's window is its parent's turned round, and a mate is counted +from the node. A node's score comes from the whole search, below the recorded plies too. + +**Decisions** are alpha-beta's, not any engine's, so a client can say what each means without +knowing the engine. Each has a `kind`, the fields of its kind, and optionally `technique`: the +id of the technique that decided it, as `engine/techniques` lists it ([7.4](#74-enginetechniques)), +from a node that offers `techniques`, so a client can name it and link to it. A decision's +`move` is always a move from its own node. + +| Kind | Fields | What the search decided | +| --- | --- | --- | +| `cutoff` | `move`, `order` | `move` scored at or above `beta`, the `order`-th move searched (from 1), so the node's other moves weren't searched: `move` refutes the move that led here | +| `table` | | An earlier search's result for this position, kept in the engine's table, settled it without a search of its own | +| `tablebase` | | Endgame tablebases settled it | +| `nullMove` | | Even passing, as if the side to move could skip its turn, kept its score at or above `beta`, so it wasn't searched further | +| `nodePruned` | `move` (optional) | It was settled before any of its moves was searched, by an estimate that a search wouldn't change the outcome. `move`, when there is one, is the capture whose shallower search proved it. Its score's bound says on which side of the window | +| `movePruned` | `move` | `move` was left out without a search, as a move that couldn't change the outcome | +| `reduced` | `plies` | It was searched this many plies shallower than its place called for, its move judged unlikely to change the outcome | +| `extended` | `plies` | It was searched this many plies deeper than its place called for, its move judged to matter more than most, such as a forced one | +| `research` | `reason` | It was searched again: `depth`, at its full depth, after a shallower search scored above `alpha`; or `window`, with a wider window, after a narrower one couldn't give its exact score | + +A client MUST ignore a decision of a kind it doesn't know, and a `research` with a `reason` it +doesn't know: later minor versions may add them. + +With cb2026's tree of the position in [7.1](#71-enginesearch), three of its 27 root moves asked +for, and its line shortened: + +```cnp +→ {"jsonrpc": "2.0", "id": 16, "method": "engine/tree", "params": {"position": {"fen": "r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3"}, "depth": 16, "plies": 3, "limit": 3}} +← {"jsonrpc": "2.0", "id": 16, "result": {"tree": "t1", "expiresMs": 300000, "depth": 16, "selDepth": 26, "nodes": 1066155, "timeMs": 939, "bestMove": "f1b5", "score": {"cp": 27}, "pv": ["f1b5", "a7a6", "b5c6", "d7c6"], "recorded": {"plies": 3, "nodes": 559, "decisions": 956, "truncated": false}, "root": {"depth": 16, "alpha": {"cp": 4}, "beta": {"cp": 54}, "score": {"cp": 27}, "childCount": 27, "subtree": 558, "decisions": []}, "children": [{"move": "d2d4", "depth": 15, "alpha": {"cp": -54}, "beta": {"cp": -4}, "score": {"cp": -16}, "childCount": 32, "subtree": 87, "decisions": []}, {"move": "f1b5", "depth": 15, "alpha": {"cp": -54}, "beta": {"cp": -16}, "score": {"cp": -27}, "childCount": 30, "subtree": 91, "decisions": [{"kind": "research", "reason": "window", "technique": "pvs"}]}, {"move": "f1c4", "depth": 15, "alpha": {"cp": -28}, "beta": {"cp": -27}, "score": {"cp": -27, "bound": "lower"}, "childCount": 1, "subtree": 34, "decisions": [{"kind": "cutoff", "move": "g8f6", "order": 1, "technique": "alphabeta"}]}]}} +``` + +The search tried d4 first, which scored 16 for White (−16 for Black, who is to move after it). +Bb5, searched with a narrow window first, scored inside the full one, so it was searched again +with it: 27, exact, the best. Bc4 was refuted by the first reply tried, Nf6: at least −27 for +Black, so no better for White than Bb5. + +**`engine/treeNode`.** Params: + +| Field | Type | | +| --- | --- | --- | +| `tree` | string | The tree's handle | +| `path` | array of moves | The moves from the root to the node. Missing or empty: the root | +| `offset` | integer | How many of the node's children to skip, in the order the search first tried them. Missing: 0 | +| `limit` | integer | How many children to answer with after those; 0 for the node alone. Missing: the rest | + +The result is `node`, the node, whose `childCount` says how many children it has in all, and +`children`, those from `offset`, at most `limit` of them, which is empty past the last. A node +answers `engine/treeNode` promptly, even while a search or a tree's search runs. + +A handle the node doesn't keep is answered with `Expired`: the tree expired, or the node dropped +it for newer ones, or never gave the handle. A `path` that leads to no node of the tree is +`InvalidParams`. + +The reply that refuted Bc4, searched a ply shallower than its place called for (cb2026 does +that to a hash move that beats `beta` without being the only good move), and then two of Bb5's +replies, the second and the third: + +```cnp +→ {"jsonrpc": "2.0", "id": 17, "method": "engine/treeNode", "params": {"tree": "t1", "path": ["f1c4"]}} +← {"jsonrpc": "2.0", "id": 17, "result": {"node": {"move": "f1c4", "depth": 15, "alpha": {"cp": -28}, "beta": {"cp": -27}, "score": {"cp": -27, "bound": "lower"}, "childCount": 1, "subtree": 34, "decisions": [{"kind": "cutoff", "move": "g8f6", "order": 1, "technique": "alphabeta"}]}, "children": [{"move": "g8f6", "depth": 13, "alpha": {"cp": 27}, "beta": {"cp": 28}, "score": {"cp": 27, "bound": "upper"}, "childCount": 33, "subtree": 33, "decisions": [{"kind": "reduced", "plies": 1, "technique": "negext"}]}]}} +→ {"jsonrpc": "2.0", "id": 18, "method": "engine/treeNode", "params": {"tree": "t1", "path": ["f1b5"], "offset": 1, "limit": 2}} +← {"jsonrpc": "2.0", "id": 18, "result": {"node": {"move": "f1b5", "depth": 15, "alpha": {"cp": -54}, "beta": {"cp": -16}, "score": {"cp": -27}, "childCount": 30, "subtree": 91, "decisions": [{"kind": "research", "reason": "window", "technique": "pvs"}]}, "children": [{"move": "f8e7", "depth": 14, "alpha": {"cp": 26}, "beta": {"cp": 27}, "score": {"cp": 27, "bound": "lower"}, "childCount": 1, "subtree": 1, "decisions": [{"kind": "cutoff", "move": "b1c3", "order": 1, "technique": "alphabeta"}]}, {"move": "g8f6", "depth": 14, "alpha": {"cp": 26}, "beta": {"cp": 27}, "score": {"cp": 28, "bound": "lower"}, "childCount": 4, "subtree": 4, "decisions": [{"kind": "cutoff", "move": "e1g1", "order": 4, "technique": "alphabeta"}]}]}} +``` + +Five minutes later, with no request for the tree in between: + +```cnp +→ {"jsonrpc": "2.0", "id": 19, "method": "engine/treeNode", "params": {"tree": "t1", "path": ["f1b5"]}} +← {"jsonrpc": "2.0", "id": 19, "error": {"code": -32018, "message": "no tree t1: it has expired; ask for it again"}} +``` + ## 8. The voice domain A voice node turns text into speech and speech into text. It never touches a microphone or a @@ -713,11 +863,12 @@ its own outside the ranges below. | -32010 | `IncompatibleVersion` | The client's major version isn't spoken. `data`: `{"supported": [...]}` | | -32011 | `InvalidPosition` | The FEN, a move, or a root move isn't legal | | -32012 | `LimitExceeded` | A request beyond the node's limits ([6.3](#63-limits)) | -| -32013 | `Busy` | Already running `maxConcurrentSearches` searches | +| -32013 | `Busy` | Already running `maxConcurrentSearches` searches, or `maxConcurrentTrees` trees' searches | | -32014 | `Unsupported` | A capability the node didn't offer, or an unknown technique | | -32015 | `Unauthorized` | On the network, without valid credentials | | -32016 | `ShuttingDown` | A request after `shutdown` | | -32017 | `NotReady` | What the request needs isn't ready yet, like a model still downloading | +| -32018 | `Expired` | A handle the node no longer keeps, or never gave, such as an expired tree's ([7.8](#78-the-search-tree)): ask again | ## 10. Security @@ -726,8 +877,9 @@ already holds both to these rules, so that the network can be added without chan - **No file paths in any request.** Opening books, tablebases and models are the node's own configuration. A request that can name a file is how a server is turned against itself. -- **Advertised limits** for depth, nodes, time, lines, concurrent searches and message size. - Requests beyond them are refused, not trimmed. +- **Advertised limits** for depth, nodes, time, lines, concurrent searches, trees and message + size. Requests beyond them are refused, not trimmed. A node bounds what it keeps for a client, + the trees of [7.8](#78-the-search-tree), and drops the oldest rather than run out of memory. - **Credentials never travel in messages,** and are never logged. ## 11. Versions @@ -753,9 +905,6 @@ These names are reserved, so that nothing else uses them: - **WebSocket over TLS** ([3.2](#32-the-network)), with credentials given when the connection opens, never in messages. -- **The search tree:** `engine/tree` searches a position and keeps its tree for a while, - answering with a handle and the root's children. `engine/treeNode` returns one node's - children, a page at a time. A handle expires after a stated time. - **Distributed search:** `worker/register`, which a worker sends after connecting out to a coordinator, with its capabilities and hardware. Either side may then send requests. - **Streamed speech:** `voice/speak` sending its audio piece by piece. @@ -777,5 +926,8 @@ These names are reserved, so that nothing else uses them: game clock (#18, cjus/chessgui#319); and an evaluation's `quiet` and `pieces`, with `searchScore` (capabilities `quiet` and `pieces`), so a client can explain the score of a search that evaluates with a neural network, from the quiet position it came from - (cjus/chessgui#340). Its design came from + (cjus/chessgui#340); and the search tree (capability `tree`, `engine/tree` and + `engine/treeNode`, the limits `maxTreeDepth`, `maxTreePlies` and `maxConcurrentTrees`, and + the error `Expired`), reserved until then, so a client can show which moves a search looked + at and why it set each aside (cjus/chessgui#350). Its design came from Solrac, a chess board that teaches, and cb2026, its engine. From 68cf80d917066de0e366952b334eb82a65fa42d6 Mon Sep 17 00:00:00 2001 From: cjus Date: Sun, 1 Nov 2026 16:31:36 -0700 Subject: [PATCH 3/3] Engine: a tree node is its last search, in the types' docs too; the example's prose Co-Authored-By: Claude Opus 5.5 --- crates/cnp/src/engine.rs | 5 +++-- spec/cnp.md | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/cnp/src/engine.rs b/crates/cnp/src/engine.rs index cc6968e..732e9a5 100644 --- a/crates/cnp/src/engine.rs +++ b/crates/cnp/src/engine.rs @@ -877,8 +877,9 @@ pub struct Recorded { /// window is its parent's turned round: `[-beta, -alpha]`. /// /// **Pitfall:** a node may be searched more than once (shallower first, then again; or with -/// a narrow window, then a wider one). Its `depth`, `alpha`, `beta` and `score` are those of -/// the search that gave its score, the last; its [`Decision`]s say what came before. +/// a narrow window, then a wider one). It is shown as its last search, the one whose score +/// counted: its `depth`, `alpha`, `beta`, `score`, children and [`Decision`]s are that +/// search's, after the decisions that say how it came to be searched that way. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TreeNode { diff --git a/spec/cnp.md b/spec/cnp.md index cc69e0e..a12ffd2 100644 --- a/spec/cnp.md +++ b/spec/cnp.md @@ -623,8 +623,8 @@ for, and its line shortened: ``` The search tried d4 first, which scored 16 for White (−16 for Black, who is to move after it). -Bb5, searched with a narrow window first, scored inside the full one, so it was searched again -with it: 27, exact, the best. Bc4 was refuted by the first reply tried, Nf6: at least −27 for +Bb5, searched first with a null window just above d4's score, beat it, so it was searched again +with the root's whole window: 27, exact, the best. Bc4 was refuted by the first reply tried, Nf6: at least −27 for Black, so no better for White than Bb5. **`engine/treeNode`.** Params: