From 82f304534a38d61e091b9744c1ef3c45105de89e Mon Sep 17 00:00:00 2001 From: cjus Date: Sun, 1 Nov 2026 19:10:38 -0700 Subject: [PATCH 1/3] Engine: following the root's types (engine/root, rootMs, capability root) RootParams says which root move a search is on (move, number, of, its line and depth), the best so far, the nodes each root move has had, and, at once, a RootResearch: a later move searched again to see whether it is the new best (better), or a depth's score above or below its aspiration window (failHigh, failLow, with the bounded score). For Solrac's Engine Mind (cjus/chessgui#357). Co-Authored-By: Claude Opus 5.5 --- crates/cnp/src/engine.rs | 127 ++++++++++++++++++++++++++++++ crates/cnp/tests/messages.rs | 117 +++++++++++++++++++++++++++ crates/cnp/tests/spec_examples.rs | 1 + 3 files changed, 245 insertions(+) diff --git a/crates/cnp/src/engine.rs b/crates/cnp/src/engine.rs index 732e9a5..12a1a63 100644 --- a/crates/cnp/src/engine.rs +++ b/crates/cnp/src/engine.rs @@ -5,6 +5,7 @@ //! | --- | --- | --- | //! | `engine/search` | request | [`Search`]: [`SearchParams`] → [`SearchResult`] | //! | `engine/progress` | notification, node to client | [`EngineProgress`]: [`Progress`] | +//! | `engine/root` | notification, node to client | [`Root`]: [`RootParams`] | //! | `engine/stop` | request | [`Stop`]: [`StopParams`] → `null` | //! | `engine/techniques` | request | [`Techniques`]: no params → [`TechniquesResult`] | //! | `engine/levels` | request | [`Levels`]: no params → [`LevelsResult`] | @@ -33,6 +34,13 @@ //! 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. +//! +//! **Following the root** (spec, 7.9) is the search's other view while it runs: a search with +//! [`SearchParams::root_ms`] gets [`Root`] notifications saying which root move it is on, where +//! its effort has gone, and, at once, when it goes back over something ([`RootResearch`]): a +//! later move that may be the new best, or a depth whose score fell outside its window. The +//! pitfall is the node counts: a node may follow its root on one thread only, so a move's +//! nodes are its share of that thread's effort, not of [`RootParams::nodes`]. use std::collections::BTreeMap; @@ -96,6 +104,10 @@ pub struct EngineCapabilities { /// A search's tree, kept for a while (`engine/tree`, `engine/treeNode`). #[serde(default)] pub tree: bool, + /// Following a search's root: which root move it is on, and where its effort goes + /// (`rootMs`, `engine/root`). + #[serde(default)] + pub root: bool, } /// The `engine/search` request: search a position and answer with the best move. @@ -179,6 +191,9 @@ pub struct SearchParams { /// Send `engine/progress` at most this often, in milliseconds. Missing: no progress. #[serde(default, skip_serializing_if = "Option::is_none")] pub progress_ms: Option, + /// Send `engine/root` at most this often, in milliseconds (capability `root`). Missing: none. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub root_ms: Option, /// A hint that searches with the same value belong to one game, so the node may keep its /// hash table between them. A node may ignore it. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -205,6 +220,7 @@ impl SearchParams { multipv: None, deterministic: false, progress_ms: None, + root_ms: None, game: None, ponder: false, } @@ -215,6 +231,13 @@ impl SearchParams { self.limits = limits; self } + + /// The same search, following its root: `engine/root` at most every `ms` milliseconds + /// ([`SearchParams::root_ms`]). + pub fn root_ms(mut self, ms: u64) -> SearchParams { + self.root_ms = Some(ms); + self + } } /// When a search stops: at the first limit reached. Times are durations from when the node @@ -519,6 +542,110 @@ pub struct Progress { pub tb_hits: Option, } +/// The `engine/root` notification, from the node (capability `root`): which root move a search +/// is on, and where its effort has gone. Sent only for a search that asked (`rootMs`), at most +/// that often, and never after its result; a [`RootResearch`] is sent at once. +/// +/// UCI's `currmove`, `currmovenumber`, `lowerbound` and `upperbound` say the same. It is +/// separate from [`EngineProgress`], and throttled on its own, so following the root never +/// holds the lines back. +pub enum Root {} + +impl NotificationMethod for Root { + const NAME: &'static str = "engine/root"; + type Params = RootParams; +} + +/// Where a search is at its root: the move it is searching, the best so far, and the effort +/// each root move has had. +/// +/// **Pitfall:** a node may follow its root on one thread only, the one that reports its lines. +/// The nodes in [`RootParams::moves`] are then that thread's, and what they show is each move's +/// share; [`RootParams::nodes`] counts every thread, as [`Progress::nodes`] does. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RootParams { + /// The `engine/search` request it belongs to. + pub id: Id, + /// The depth being searched: one more than the last completed. + pub depth: u32, + /// Which line is being searched, from 1, when searching several. `None` otherwise. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub multipv: Option, + /// The root move being searched now, in coordinate notation. + #[serde(rename = "move")] + pub mv: String, + /// Its place in this depth's order of root 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, or the last completed depth's + /// until this depth has one. `None` before there is any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub best: Option, + /// Every root move searched so far in this search, with the nodes spent below it, at every + /// depth and for every line together, in no particular order. + #[serde(default)] + pub moves: Vec, + /// Nodes searched so far, every thread together. + pub nodes: u64, + /// Time so far, in milliseconds. + pub time_ms: u64, + /// What the search is going back over, when it is: sent when it happens, without waiting + /// for `rootMs`. `None` otherwise. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub research: Option, +} + +/// One root move, and the effort spent on it so far. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RootMove { + /// The move, in coordinate notation. + #[serde(rename = "move")] + pub mv: String, + /// The nodes searched below it. + pub nodes: u64, +} + +/// What a search is going back over at its root (spec, 7.9). 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 [`RootResearch::Unknown`]. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde( + tag = "kind", + rename_all = "camelCase", + rename_all_fields = "camelCase" +)] +pub enum RootResearch { + /// `mv`, a root move searched after the best, scored above it on its quick search (with a + /// null window), and is being searched again in full to see whether it is the new best. + /// The next notifications' [`RootParams::best`] say whether it was. + Better { + /// The move, in coordinate notation. + #[serde(rename = "move")] + mv: String, + }, + /// The depth's score came out above its aspiration window, the window around the last + /// depth's score it was searched in: the best move looks better than the last depth said. + /// The depth is searched again with a wider window. + FailHigh { + /// The score it came out at, a lower bound. + score: Score, + }, + /// The depth's score came out below its aspiration window: worse than the last depth said. + /// The depth is searched again with a wider window. + FailLow { + /// The score it came out at, an upper bound. + score: Score, + }, + /// A kind this crate doesn't know, from a later version. Only read, never sent. + #[serde(other)] + Unknown, +} + /// The `engine/stop` request: end a search early. The search answers at once with the best it /// has, marked `stopped`. Stopping a search that has already answered, or never existed, is /// not an error: the two can cross. diff --git a/crates/cnp/tests/messages.rs b/crates/cnp/tests/messages.rs index 2a2c0f1..5d622e7 100644 --- a/crates/cnp/tests/messages.rs +++ b/crates/cnp/tests/messages.rs @@ -567,6 +567,123 @@ fn a_tree_says_what_it_holds_and_the_tree_capability_and_limits_are_offered() { assert_eq!(code::EXPIRED, -32018); } +#[test] +fn a_search_can_ask_to_follow_its_root_and_a_node_can_offer_it() { + let plain = SearchParams::new(Position::start()); + assert_eq!(serde_json::to_value(&plain).unwrap().get("rootMs"), None); + let following = plain.root_ms(250); + assert_eq!(following.root_ms, Some(250)); + let value = serde_json::to_value(&following).unwrap(); + assert_eq!(value["rootMs"], json!(250)); + assert_eq!( + serde_json::from_value::(value).unwrap(), + following + ); + + let offered: engine::EngineCapabilities = serde_json::from_value(json!({})).unwrap(); + assert!(!offered.root); + let offered: engine::EngineCapabilities = + serde_json::from_value(json!({"root": true})).unwrap(); + assert!(offered.root); +} + +#[test] +fn following_the_root_says_the_move_its_place_the_best_and_the_effort() { + use engine::{RootMove, RootParams, RootResearch}; + + let params = RootParams { + id: Id::Number(20), + depth: 14, + multipv: Some(2), + mv: "d2d4".to_string(), + number: 3, + of: 26, + best: Some("f1c4".to_string()), + moves: vec![ + RootMove { + mv: "f1c4".to_string(), + nodes: 81_234, + }, + RootMove { + mv: "d2d4".to_string(), + nodes: 1_203, + }, + ], + nodes: 190_011, + time_ms: 250, + research: Some(RootResearch::Better { + mv: "d2d4".to_string(), + }), + }; + let notification = Notification::new::(¶ms); + assert_eq!(notification.method, "engine/root"); + let value = Message::from(notification).to_value(); + assert_eq!( + value, + json!({"jsonrpc": "2.0", "method": "engine/root", "params": { + "id": 20, "depth": 14, "multipv": 2, "move": "d2d4", "number": 3, "of": 26, + "best": "f1c4", + "moves": [{"move": "f1c4", "nodes": 81234}, {"move": "d2d4", "nodes": 1203}], + "nodes": 190011, "timeMs": 250, "research": {"kind": "better", "move": "d2d4"}}}) + ); + let Message::Notification(read) = parse(value) else { + panic!("not a notification"); + }; + assert!(read.is::()); + assert_eq!(read.params::().unwrap(), params); + + // The first: one line, no best yet, nothing gone back over. + let first: RootParams = serde_json::from_value(json!({ + "id": 3, "depth": 1, "move": "e2e4", "number": 1, "of": 20, + "moves": [{"move": "e2e4", "nodes": 0}], "nodes": 1, "timeMs": 0 + })) + .unwrap(); + let value = serde_json::to_value(&first).unwrap(); + assert_eq!( + (first.multipv, first.best, first.research), + (None, None, None) + ); + for left_out in ["multipv", "best", "research"] { + assert_eq!(value.get(left_out), None, "{left_out}"); + } + + // A depth's score outside its window comes with its bound. + let kinds = [ + ( + json!({"kind": "failHigh", "score": {"cp": 45, "bound": "lower"}}), + RootResearch::FailHigh { + score: Score { + value: ScoreValue::Centipawns(45), + bound: Bound::Lower, + }, + }, + ), + ( + json!({"kind": "failLow", "score": {"cp": -8, "bound": "upper"}}), + RootResearch::FailLow { + score: Score { + value: ScoreValue::Centipawns(-8), + bound: Bound::Upper, + }, + }, + ), + ]; + for (value, research) in kinds { + assert_eq!( + serde_json::from_value::(value.clone()).unwrap(), + research + ); + assert_eq!(serde_json::to_value(&research).unwrap(), value); + } + // A later version's kind is read rather than refused, so a client can skip it. + let later: RootResearch = + serde_json::from_value(json!({"kind": "singular", "move": "e2e4"})).unwrap(); + assert_eq!(later, RootResearch::Unknown); + // A better move names itself, and a window's failure its score. + assert!(serde_json::from_value::(json!({"kind": "better"})).is_err()); + assert!(serde_json::from_value::(json!({"kind": "failHigh"})).is_err()); +} + #[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 e955012..622c7c1 100644 --- a/crates/cnp/tests/spec_examples.rs +++ b/crates/cnp/tests/spec_examples.rs @@ -86,6 +86,7 @@ fn notification_params(notification: &Notification) -> Result<(), String> { "exit" => notification.params::().map(drop), "$/cancelRequest" => notification.params::().map(drop), "engine/progress" => notification.params::().map(drop), + "engine/root" => notification.params::().map(drop), "voice/modelState" => notification.params::().map(drop), "voice/audio" => notification.params::().map(drop), "voice/speechStarted" => notification.params::().map(drop), From a220d408e516e6370f200c910a0f352611ab81aa Mon Sep 17 00:00:00 2001 From: cjus Date: Sun, 1 Nov 2026 19:10:38 -0700 Subject: [PATCH 2/3] Engine: following the root in the spec (7.9) and its conformance sessions The sessions check a search that follows its root gets engine/root before its result and none after, that each names its line when there are several, and that a node without root refuses rootMs. A session's new forbid step says a message must not come: from that step on, one matching its pattern fails the session, even a notification that would be skipped. Co-Authored-By: Claude Opus 5.5 --- conformance/README.md | 9 ++++- conformance/engine/root-multipv.jsonl | 10 +++++ conformance/engine/root-unsupported.jsonl | 9 +++++ conformance/engine/root.jsonl | 13 +++++++ crates/cnp-conformance/src/runner.rs | 20 ++++++++++ crates/cnp-conformance/src/session.rs | 10 ++++- crates/cnp-conformance/tests/runner.rs | 28 ++++++++++++++ spec/cnp.md | 45 +++++++++++++++++++++++ 8 files changed, 141 insertions(+), 3 deletions(-) create mode 100644 conformance/engine/root-multipv.jsonl create mode 100644 conformance/engine/root-unsupported.jsonl create mode 100644 conformance/engine/root.jsonl diff --git a/conformance/README.md b/conformance/README.md index 2e0fd43..3a6b8ca 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, pondering's hit and miss, and the search tree: reading it, its errors and limits, during a search and cancelled (spec 7) | Engine nodes | +| `engine/` | Searches, stop and cancel, each engine capability, pondering's hit and miss, the search tree: reading it, its errors and limits, during a search and cancelled, and following a search's root (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) | @@ -45,11 +45,16 @@ Each later line is one step, with optionally a `comment`: | `{"expect": pattern}` | Waits for a message matching the pattern | | `{"expectAll": [pattern, …]}` | Waits for messages matching all of them, in any order | | `{"expectExit": code}` | Waits for the node to end with this exit code (`null`: any) | +| `{"forbid": pattern}` | From here on, a message matching the pattern fails the session | | `{"close": true}` | Closes the node's input | | `{"comment": "text"}` | Nothing: a note for people | While a step waits, notifications that match nothing are skipped (a search's progress, a -model's state), but any other message that doesn't match fails the session. +model's state), but any other message that doesn't match fails the session. `forbid` is how a +session says a notification must not come, such as one about a search after its result: from +that step on, a message matching the pattern fails the session, even one a step expects. The +node's messages are read in the order it sent them, so a forbidden one sent before the answer +the next step waits for is always caught. ## Patterns diff --git a/conformance/engine/root-multipv.jsonl b/conformance/engine/root-multipv.jsonl new file mode 100644 index 0000000..b5eb8da --- /dev/null +++ b/conformance/engine/root-multipv.jsonl @@ -0,0 +1,10 @@ +{"session": "root-multipv", "description": "following the root of a search for two lines says which line each engine/root is about (spec 7.9)", "requires": ["engine", "engine.root", "engine.multipv", "limits.maxMultipv"]} +{"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": {"depth": 5}, "multipv": 2, "rootMs": 0}}} +{"expect": {"method": "engine/root", "params": {"id": 2, "multipv": "$integer", "move": "$move"}}} +{"expect": {"id": 2, "result": {"bestMove": "$move", "lines": [{"multipv": 1}, {"multipv": 2}]}}} +{"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/root-unsupported.jsonl b/conformance/engine/root-unsupported.jsonl new file mode 100644 index 0000000..87d5d29 --- /dev/null +++ b/conformance/engine/root-unsupported.jsonl @@ -0,0 +1,9 @@ +{"session": "root-unsupported", "description": "a node without root refuses a search with rootMs with Unsupported (spec 6.1, 7.9)", "requires": ["engine", "!engine.root"]} +{"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": {"depth": 2}, "rootMs": 100}}} +{"expect": {"id": 2, "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/root.jsonl b/conformance/engine/root.jsonl new file mode 100644 index 0000000..a948c99 --- /dev/null +++ b/conformance/engine/root.jsonl @@ -0,0 +1,13 @@ +{"session": "root", "description": "a search that follows its root gets engine/root before its result, and none after it (spec 7.9)", "requires": ["engine", "engine.root"]} +{"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": {"depth": 5}, "rootMs": 0}}} +{"expect": {"method": "engine/root", "params": {"id": 2, "depth": "$integer", "move": "$move", "number": "$integer", "of": "$integer", "moves": "$array", "nodes": "$integer", "timeMs": "$integer"}}} +{"expect": {"id": 2, "result": {"bestMove": "$move"}}} +{"forbid": {"method": "engine/root", "params": {"id": 2}}, "comment": "nothing about the search after its result"} +{"send": {"jsonrpc": "2.0", "id": 3, "method": "ping"}} +{"expect": {"id": 3, "result": null}} +{"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-conformance/src/runner.rs b/crates/cnp-conformance/src/runner.rs index f5b169c..c706b12 100644 --- a/crates/cnp-conformance/src/runner.rs +++ b/crates/cnp-conformance/src/runner.rs @@ -58,6 +58,8 @@ pub struct Node { stderr: Arc>>, /// Notifications skipped while waiting, for a failure's report. skipped: Vec, + /// Patterns no message may match from now on (`forbid`), each with its step's number. + forbidden: Vec<(usize, Value)>, } impl Node { @@ -108,6 +110,7 @@ impl Node { received, stderr, skipped: Vec::new(), + forbidden: Vec::new(), }) } @@ -126,6 +129,12 @@ impl Node { self.stdin = None; } + /// From now on, fails at any message matching `pattern`, a notification included, even + /// one a step expects. `step` is the number of the step that forbade it, for the report. + pub fn forbid(&mut self, step: usize, pattern: Value) { + self.forbidden.push((step, pattern)); + } + /// Waits for a message matching `pattern`, skipping notifications that don't. pub fn expect( &mut self, @@ -165,6 +174,13 @@ impl Node { )); } }; + for (step, pattern) in &self.forbidden { + if matches(pattern, &message, bindings).is_ok() { + return Err(format!( + "got {message}, which step {step} forbids ({pattern})" + )); + } + } let mut mismatches = Vec::new(); let found = waiting @@ -254,6 +270,10 @@ pub fn run_session(session: &Session, command: &[String]) -> Outcome { )), Err(e) => Err(e), }, + Step::Forbid(pattern) => { + node.forbid(n + 1, pattern.clone()); + Ok(()) + } Step::Close => { node.close(); Ok(()) diff --git a/crates/cnp-conformance/src/session.rs b/crates/cnp-conformance/src/session.rs index 12d8abb..667a7c5 100644 --- a/crates/cnp-conformance/src/session.rs +++ b/crates/cnp-conformance/src/session.rs @@ -22,11 +22,16 @@ //! | `{"expect": pattern}` | Waits for a message matching the pattern ([`crate::pattern`]) | //! | `{"expectAll": [pattern, …]}` | Waits for messages matching all of them, in any order | //! | `{"expectExit": code}` | Waits for the node to end with this exit code (`null`: any) | +//! | `{"forbid": pattern}` | From here on, a message matching the pattern fails the session | //! | `{"close": true}` | Closes the node's input | //! | `{"comment": "text"}` | Nothing: a note for people | //! //! While waiting, notifications that don't match are skipped (a search's progress, a model's -//! state), but any other message that doesn't match fails the session. +//! state), but any other message that doesn't match fails the session. `forbid` is how a +//! session says a notification must not come, such as one about a search after its result: a +//! message matching a forbidden pattern fails the session even when a step expects it. +//! Messages are read in the order the node sent them, so a forbidden one sent before the +//! answer the next step waits for is always caught. use std::fs; use std::path::{Path, PathBuf}; @@ -67,6 +72,8 @@ pub enum Step { ExpectAll(Vec), /// Wait for the node to end, with this exit code (`None`: any). ExpectExit(Option), + /// From here on, fail at any message matching this pattern. + Forbid(Value), /// Close the node's input. Close, } @@ -127,6 +134,7 @@ pub fn parse(text: &str, path: &Path) -> Result { .and_then(|c| i32::try_from(c).ok()) .ok_or(format!("line {number}: an exit code is a whole number"))?, )), + ("forbid", pattern) => Step::Forbid(pattern), ("close", Value::Bool(true)) => Step::Close, (key, _) => return Err(format!("line {number}: no step {key:?} of that form")), }); diff --git a/crates/cnp-conformance/tests/runner.rs b/crates/cnp-conformance/tests/runner.rs index 9898885..cf050a3 100644 --- a/crates/cnp-conformance/tests/runner.rs +++ b/crates/cnp-conformance/tests/runner.rs @@ -149,3 +149,31 @@ fn a_session_can_need_a_capability_absent() { ); assert_eq!(missing(&session, &offered(&[])), vec!["engine".to_string()]); } + +#[test] +fn a_forbidden_message_fails_the_session_even_when_a_step_expects_it() { + let ping = |id: u32| { + format!("{{\"send\": {{\"jsonrpc\": \"2.0\", \"id\": {id}, \"method\": \"ping\"}}}}") + }; + let outcome = run(&format!( + "{{\"session\": \"forbid\"}}\n{INIT}\n\ + {{\"forbid\": {{\"id\": 3}}}}\n{}\n\ + {{\"expect\": {{\"id\": 2, \"result\": null}}}}\n{}\n\ + {{\"expect\": {{\"id\": 3, \"result\": null}}}}", + ping(2), + ping(3) + )); + let Outcome::Failed(why) = outcome else { + panic!("passed: {outcome:?}"); + }; + assert!(why.contains("step 7"), "{why}"); + assert!(why.contains("step 3 forbids"), "{why}"); + // A message it doesn't match passes. + let passes = run(&format!( + "{{\"session\": \"forbid\"}}\n{INIT}\n\ + {{\"forbid\": {{\"id\": 3}}}}\n{}\n\ + {{\"expect\": {{\"id\": 2, \"result\": null}}}}", + ping(2) + )); + assert_eq!(passes, Outcome::Passed); +} diff --git a/spec/cnp.md b/spec/cnp.md index a12ffd2..a36e45b 100644 --- a/spec/cnp.md +++ b/spec/cnp.md @@ -253,6 +253,7 @@ Every engine node answers `engine/search` with the limits `depth`, `nodes`, `tim | `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)) | +| `root` | `rootMs` on `engine/search`, and `engine/root`: which root move a search is on, and where its effort goes ([7.9](#79-engineroot)) | ### 6.3 Limits @@ -284,6 +285,7 @@ Every engine node answers `engine/search` with the limits `depth`, `nodes`, `tim | `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 | +| `engine/root` | notification, node to client | Which root move a search is on, and where its effort has gone | ### 7.1 `engine/search` @@ -300,6 +302,7 @@ Params: | `multipv` | integer | `multipv` | How many lines to find, the best first. Missing: 1 | | `deterministic` | boolean | `deterministic` | One thread and a cleared hash table, so the same request gives the same result, node counts included | | `progressMs` | integer | `progress` | Send `engine/progress` at most this often. Missing: no progress | +| `rootMs` | integer | `root` | Send `engine/root` at most this often ([7.9](#79-engineroot)). Missing: none | | `game` | string | | A hint that searches with the same `game` belong to one game, so the node may keep its hash table between them. A node MAY ignore it | | `ponder` | boolean | `ponder` | Search on the opponent's time, until `engine/ponderHit` ([7.7](#77-pondering)) | @@ -662,6 +665,48 @@ Five minutes later, with no request for the tree in between: ← {"jsonrpc": "2.0", "id": 19, "error": {"code": -32018, "message": "no tree t1: it has expired; ask for it again"}} ``` +### 7.9 `engine/root` + +Needs `root`. A notification from the node saying which root move a search is on and where its +effort has gone, sent only for a search that asked with `rootMs`, at most that often, and never +after the search's result. A node MUST send at least one before the result of a search that +searched a root move. UCI's `currmove`, `currmovenumber`, `lowerbound` and `upperbound` say the +same. A client can show what the engine is looking at while it looks, and when it may be +changing its mind. It is separate from `engine/progress` ([7.2](#72-engineprogress)) and +throttled on its own, so following the root never holds the lines back. + +A node MAY follow its root on one thread only, the one that reports its lines. The nodes in +`moves` are then that thread's, and what they show is each move's share of the effort, while +`nodes` counts every thread, as in `engine/progress`. Its params: + +| Field | Type | | +| --- | --- | --- | +| `id` | id | The `engine/search` request it belongs to | +| `depth` | integer | The depth being searched: one more than the last completed | +| `multipv` | integer | Which line is being searched, from 1, when searching several. Missing otherwise | +| `move` | move | The root move being searched now | +| `number` | integer | Its place in this depth's order of root moves for this line, from 1 | +| `of` | integer | How many root moves this line searches | +| `best` | move | The best root move so far for this line: this depth's, or the last completed depth's until this depth has one. Missing before there is any | +| `moves` | array | Every root move searched so far in this search, each `{"move": m, "nodes": n}`: the nodes spent below it, at every depth and for every line together, in no particular order | +| `nodes`, `timeMs` | integers | So far, as in `engine/progress` | +| `research` | object | What the search is going back over, when it is (below). Missing when not | + +A `research` is sent when it happens, without waiting for `rootMs`, and the interval then counts +from it. Its `kind` says what the search is going back over, and the fields of its kind: + +| Kind | Fields | When | +| --- | --- | --- | +| `better` | `move` | A root move searched after the best scored above it on its quick search, with a null window, and is being searched again in full to see whether it is the new best. The next notifications' `best` say whether it was | +| `failHigh` | `score`, with `bound` `lower` | The depth's score came out above its aspiration window, the window around the last depth's score that the depth was searched in: the best move looks better than the last depth said. The depth is searched again with a wider window | +| `failLow` | `score`, with `bound` `upper` | The depth's score came out below its aspiration window: worse than the last depth said. The depth is searched again with a wider window | + +After a `failHigh` or a `failLow`, `move` and `number` are those the depth's next search starts +with. A client MUST ignore a `research` of a kind it doesn't know: later minor versions may add +them. + +EXAMPLE_PLACEHOLDER + ## 8. The voice domain A voice node turns text into speech and speech into text. It never touches a microphone or a From c605e6c71edd653fba2cc473d7c2bc6c2b59393d Mon Sep 17 00:00:00 2001 From: cjus Date: Sun, 1 Nov 2026 19:26:16 -0700 Subject: [PATCH 3/3] Engine: the root example, from cb2026, and the change in 14 A search of 7.1's position followed at its root: d4 leads depth 15, Bb5 beats it on its quick search at depth 16 and is searched again, and the next notification's best says the second search confirmed it. Co-Authored-By: Claude Opus 5.5 --- spec/cnp.md | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/spec/cnp.md b/spec/cnp.md index a36e45b..4eaabfe 100644 --- a/spec/cnp.md +++ b/spec/cnp.md @@ -705,7 +705,21 @@ After a `failHigh` or a `failLow`, `move` and `number` are those the depth's nex with. A client MUST ignore a `research` of a kind it doesn't know: later minor versions may add them. -EXAMPLE_PLACEHOLDER +With cb2026, following the root of a search of the position in [7.1](#71-enginesearch), with +three of the 27 moves' counts shown in each notification and the line shortened: + +```cnp +→ {"jsonrpc": "2.0", "id": 20, "method": "engine/search", "params": {"position": {"fen": "r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3"}, "limits": {"depth": 18}, "rootMs": 250}} +← {"jsonrpc": "2.0", "method": "engine/root", "params": {"id": 20, "depth": 15, "move": "d2d4", "number": 1, "of": 27, "best": "d2d4", "moves": [{"move": "f1b5", "nodes": 243851}, {"move": "d2d4", "nodes": 180650}, {"move": "f1c4", "nodes": 133439}], "nodes": 651264, "timeMs": 601}} +← {"jsonrpc": "2.0", "method": "engine/root", "params": {"id": 20, "depth": 16, "move": "f1b5", "number": 2, "of": 27, "best": "d2d4", "moves": [{"move": "d2d4", "nodes": 304188}, {"move": "f1b5", "nodes": 263912}, {"move": "f1c4", "nodes": 133945}], "nodes": 816665, "timeMs": 809, "research": {"kind": "better", "move": "f1b5"}}} +← {"jsonrpc": "2.0", "method": "engine/root", "params": {"id": 20, "depth": 16, "move": "h2h3", "number": 26, "of": 27, "best": "f1b5", "moves": [{"move": "f1b5", "nodes": 447814}, {"move": "d2d4", "nodes": 304188}, {"move": "f1c4", "nodes": 143193}], "nodes": 1060864, "timeMs": 1059}} +← {"jsonrpc": "2.0", "id": 20, "result": {"bestMove": "f1b5", "ponder": "a7a6", "score": {"cp": 30}, "pv": ["f1b5", "a7a6", "b5c6", "d7c6"], "depth": 18, "selDepth": 32, "nodes": 2171171, "timeMs": 2292, "stopped": false}} +``` + +At depth 15 the search starts with d4, the last depth's best, though Bb5 has had more of its +effort so far. At depth 16 Bb5, searched second, scores above d4 on its quick search and is +searched again in full. A quarter of a second later the search is on its 26th move and Bb5 is +the best: the second search confirmed it. It stays the best to the end. ## 8. The voice domain @@ -974,5 +988,7 @@ These names are reserved, so that nothing else uses them: (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 + at and why it set each aside (cjus/chessgui#350); and following the root (capability `root`, + `rootMs` and `engine/root`), so a client can show which root move a search is on, where its + effort goes, and when it may be changing its mind (cjus/chessgui#357). Its design came from Solrac, a chess board that teaches, and cb2026, its engine.