Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down Expand Up @@ -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

Expand Down
10 changes: 10 additions & 0 deletions conformance/engine/root-multipv.jsonl
Original file line number Diff line number Diff line change
@@ -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}
9 changes: 9 additions & 0 deletions conformance/engine/root-unsupported.jsonl
Original file line number Diff line number Diff line change
@@ -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}
13 changes: 13 additions & 0 deletions conformance/engine/root.jsonl
Original file line number Diff line number Diff line change
@@ -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}
20 changes: 20 additions & 0 deletions crates/cnp-conformance/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ pub struct Node {
stderr: Arc<Mutex<Vec<u8>>>,
/// Notifications skipped while waiting, for a failure's report.
skipped: Vec<Value>,
/// Patterns no message may match from now on (`forbid`), each with its step's number.
forbidden: Vec<(usize, Value)>,
}

impl Node {
Expand Down Expand Up @@ -108,6 +110,7 @@ impl Node {
received,
stderr,
skipped: Vec::new(),
forbidden: Vec::new(),
})
}

Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(())
Expand Down
10 changes: 9 additions & 1 deletion crates/cnp-conformance/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -67,6 +72,8 @@ pub enum Step {
ExpectAll(Vec<Value>),
/// Wait for the node to end, with this exit code (`None`: any).
ExpectExit(Option<i32>),
/// From here on, fail at any message matching this pattern.
Forbid(Value),
/// Close the node's input.
Close,
}
Expand Down Expand Up @@ -127,6 +134,7 @@ pub fn parse(text: &str, path: &Path) -> Result<Session, String> {
.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")),
});
Expand Down
28 changes: 28 additions & 0 deletions crates/cnp-conformance/tests/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
127 changes: 127 additions & 0 deletions crates/cnp/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`] |
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<u64>,
/// 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<u64>,
/// 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")]
Expand All @@ -205,6 +220,7 @@ impl SearchParams {
multipv: None,
deterministic: false,
progress_ms: None,
root_ms: None,
game: None,
ponder: false,
}
Expand All @@ -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
Expand Down Expand Up @@ -519,6 +542,110 @@ pub struct Progress {
pub tb_hits: Option<u64>,
}

/// 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<u32>,
/// 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<String>,
/// 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<RootMove>,
/// 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<RootResearch>,
}

/// 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.
Expand Down
Loading
Loading