From a66d1016d9b9d2a6fa35441aa7968ca804578acb Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 30 Oct 2026 14:19:21 +0300 Subject: [PATCH] uci: the protocol as a machine without I/O, the process as its transport; chess-import: passes and positional I/O on a target without threads The handshake and the session after it move to uci::protocol: lines, commands and the time go in, lines to write and events come out, deadlines are named instead of waited for. The child process with its reader and supervisor threads is now one transport of it (process.rs, not built for WebAssembly). Behaviour on the computer and Android is unchanged; the fake engine tests pass as before, and the machine has its own tests. chess-import: the parallel passes (booster, position search, opening tallies) go through parallel::map, which runs a single worker on the calling thread; on WebAssembly there is one worker (std threads panic there). read_at and write_all_at have a portable form through the file cursor for targets other than Unix and Windows. The bench command is not built for WebAssembly. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + Cargo.toml | 2 + crates/chess-import/src/chessbase/booster.rs | 132 +++-- crates/chess-import/src/chessbase/openings.rs | 19 +- crates/chess-import/src/chessbase/search.rs | 83 +-- crates/chess-import/src/lib.rs | 3 + crates/chess-import/src/parallel.rs | 58 ++ crates/uci/Cargo.toml | 1 + crates/uci/src/events.rs | 52 ++ crates/uci/src/lib.rs | 25 +- crates/uci/src/{engine.rs => process.rs} | 424 ++------------ crates/uci/src/protocol.rs | 545 ++++++++++++++++++ crates/uci/src/types.rs | 6 +- 13 files changed, 858 insertions(+), 493 deletions(-) create mode 100644 crates/chess-import/src/parallel.rs create mode 100644 crates/uci/src/events.rs rename crates/uci/src/{engine.rs => process.rs} (61%) create mode 100644 crates/uci/src/protocol.rs diff --git a/Cargo.lock b/Cargo.lock index 6fdca1b..3a1d753 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4680,6 +4680,7 @@ version = "2.1.1" dependencies = [ "libc", "thiserror 2.0.21", + "web-time", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index fdba624..71cd9c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,8 @@ shakmaty = "0.30.2" pgn-reader = "0.29.1" encoding_rs = "0.8" thiserror = "2" +# `Instant`/`SystemTime` that also work in a browser (std's panic there). +web-time = "1.1" serde = { version = "1", features = ["derive"] } serde_json = "1" egui = "=0.36.2" diff --git a/crates/chess-import/src/chessbase/booster.rs b/crates/chess-import/src/chessbase/booster.rs index ce843ce..eef1db7 100644 --- a/crates/chess-import/src/chessbase/booster.rs +++ b/crates/chess-import/src/chessbase/booster.rs @@ -143,6 +143,15 @@ fn write_all_at(f: &File, buf: &[u8], at: u64) -> io::Result<()> { } Ok(()) } + // Elsewhere (WebAssembly) through the cursor: such a target has no threads to + // share it with. + #[cfg(not(any(unix, windows)))] + { + use std::io::{Seek, SeekFrom, Write}; + let mut f = f; + f.seek(SeekFrom::Start(at))?; + f.write_all(buf) + } } /// One pass over the main lines of `base`, in parallel, writing the booster to @@ -171,75 +180,70 @@ pub(super) fn build( None => None, }; let next = AtomicUsize::new(0); - let threads = std::thread::available_parallelism() - .map_or(4, |n| n.get()) + let threads = crate::parallel::threads(4) .min(total.div_ceil(BLOCK)) .max(1); let failure: Mutex> = Mutex::new(None); - std::thread::scope(|s| { - for _ in 0..threads { - s.spawn(|| { - let run = || -> io::Result<()> { - let cbg = File::open(base.cbg_path())?; - let file = part - .as_ref() - .map(|p| File::options().write(true).open(p)) - .transpose()?; - let mut games: Vec<(u32, u32)> = Vec::new(); - let (mut span, mut single) = (Vec::new(), Vec::new()); - let mut block = vec![0u8; BLOCK * CBB_RECORD]; - let mut entries: Vec = Vec::new(); - let mut set_up: Vec = Vec::new(); - loop { - if cancel.load(Ordering::Relaxed) { - return Ok(()); - } - let from = next.fetch_add(BLOCK, Ordering::Relaxed); - if from >= total { - return Ok(()); - } - let to = (from + BLOCK).min(total); - let bytes = &mut block[..(to - from) * CBB_RECORD]; - bytes.fill(0); - entries.clear(); - set_up.clear(); - games.clear(); - for i in from..to { - // Texts and Chess960 games (ECO field ≥ 64576) have no - // record, like in ChessBase's own file. - if base.kind(i) == RecordKind::Game - && be(base.record(i), 0x23, 2).is_some_and(|eco| eco < 64576) - { - games.push((i as u32, base.moves_offset(i))); - } - } - read_games(&cbg, &games, &mut span, &mut single, |index, data, rel| { - let opening = sink.is_some().then_some(index); - if let Some(d) = game_data(data, rel, opening) { - let at = (index as usize - from) * CBB_RECORD; - bytes[at..at + CBB_RECORD].copy_from_slice(&d.record); - entries.extend(d.opening); - if d.set_up { - set_up.push(index); - } - } - }); - if let Some(f) = &file { - write_all_at(f, bytes, ((from + 1) * CBB_RECORD) as u64)?; - } - if let Some(sink) = &sink { - sink.add(&entries, &set_up)?; - } - progress.fetch_add(to - from, Ordering::Relaxed); - } - }; - if let Err(e) = run() { - cancel.store(true, Ordering::Relaxed); - if let Ok(mut f) = failure.lock() { - f.get_or_insert(e); + crate::parallel::map(vec![(); threads], |()| { + let run = || -> io::Result<()> { + let cbg = File::open(base.cbg_path())?; + let file = part + .as_ref() + .map(|p| File::options().write(true).open(p)) + .transpose()?; + let mut games: Vec<(u32, u32)> = Vec::new(); + let (mut span, mut single) = (Vec::new(), Vec::new()); + let mut block = vec![0u8; BLOCK * CBB_RECORD]; + let mut entries: Vec = Vec::new(); + let mut set_up: Vec = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + return Ok(()); + } + let from = next.fetch_add(BLOCK, Ordering::Relaxed); + if from >= total { + return Ok(()); + } + let to = (from + BLOCK).min(total); + let bytes = &mut block[..(to - from) * CBB_RECORD]; + bytes.fill(0); + entries.clear(); + set_up.clear(); + games.clear(); + for i in from..to { + // Texts and Chess960 games (ECO field ≥ 64576) have no + // record, like in ChessBase's own file. + if base.kind(i) == RecordKind::Game + && be(base.record(i), 0x23, 2).is_some_and(|eco| eco < 64576) + { + games.push((i as u32, base.moves_offset(i))); } } - }); + read_games(&cbg, &games, &mut span, &mut single, |index, data, rel| { + let opening = sink.is_some().then_some(index); + if let Some(d) = game_data(data, rel, opening) { + let at = (index as usize - from) * CBB_RECORD; + bytes[at..at + CBB_RECORD].copy_from_slice(&d.record); + entries.extend(d.opening); + if d.set_up { + set_up.push(index); + } + } + }); + if let Some(f) = &file { + write_all_at(f, bytes, ((from + 1) * CBB_RECORD) as u64)?; + } + if let Some(sink) = &sink { + sink.add(&entries, &set_up)?; + } + progress.fetch_add(to - from, Ordering::Relaxed); + } + }; + if let Err(e) = run() { + cancel.store(true, Ordering::Relaxed); + if let Ok(mut f) = failure.lock() { + f.get_or_insert(e); + } } }); let clean = || { diff --git a/crates/chess-import/src/chessbase/openings.rs b/crates/chess-import/src/chessbase/openings.rs index 78375c1..16a3d43 100644 --- a/crates/chess-import/src/chessbase/openings.rs +++ b/crates/chess-import/src/chessbase/openings.rs @@ -578,22 +578,17 @@ impl Index { } // Millions of games for an early position: tallied in parallel, each part // keeping its order. - let threads = std::thread::available_parallelism() - .map_or(1, |n| n.get()) + let threads = crate::parallel::threads(1) .min(games.len().div_ceil(1 << 16)) .max(1); let chunk = games.len().div_ceil(threads).max(1); let line = &line; - let parts: Vec = std::thread::scope(|s| { - let handles: Vec<_> = games - .chunks(chunk) - .map(|part| s.spawn(move || self.tally(base, part, line))) - .collect(); - handles - .into_iter() - .map(|h| h.join().unwrap_or_default()) - .collect() - }); + let parts: Vec = crate::parallel::map(games.chunks(chunk).collect(), |part| { + self.tally(base, part, line) + }) + .into_iter() + .map(Option::unwrap_or_default) + .collect(); let mut out = Collector::default(); for part in parts { out.merge(part); diff --git a/crates/chess-import/src/chessbase/search.rs b/crates/chess-import/src/chessbase/search.rs index a8c5dfa..e3fb296 100644 --- a/crates/chess-import/src/chessbase/search.rs +++ b/crates/chess-import/src/chessbase/search.rs @@ -78,51 +78,43 @@ fn collect( .cbb_path() .filter(|p| booster_helps(p, &target.signature)); let next = AtomicUsize::new(0); - let threads = std::thread::available_parallelism() - .map_or(4, |n| n.get()) + let threads = crate::parallel::threads(4) .min(total.div_ceil(BLOCK)) .max(1); // Per thread: its collector and, per block, (first candidate, first match). type Part = (Collector, Vec<(usize, usize)>); - let parts: Vec> = std::thread::scope(|s| { - let handles: Vec<_> = (0..threads) - .map(|_| { - s.spawn(|| { - let mut worker = Worker { - base, - target: &target, - cbg: File::open(base.cbg_path()).ok()?, - cbb: cbb.and_then(|p| File::open(p).ok()), - games: Vec::new(), - span: Vec::new(), - single: Vec::new(), - out: Collector::default(), - }; - let mut blocks = Vec::new(); - loop { - if cancel.load(Ordering::Relaxed) { - return None; - } - let from = next.fetch_add(BLOCK, Ordering::Relaxed); - if from >= total { - return Some((worker.out, blocks)); - } - let to = (from + BLOCK).min(total); - blocks.push((from, worker.out.matches.len())); - match candidates { - Some(c) => worker.block(c[from..to].iter().copied()), - None => worker.block(from as u32..to as u32), - } - scanned.fetch_add(to - from, Ordering::Relaxed); - } - }) - }) - .collect(); - handles - .into_iter() - .map(|h| h.join().ok().flatten()) - .collect() - }); + let parts: Vec> = crate::parallel::map(vec![(); threads], |()| { + let mut worker = Worker { + base, + target: &target, + cbg: File::open(base.cbg_path()).ok()?, + cbb: cbb.and_then(|p| File::open(p).ok()), + games: Vec::new(), + span: Vec::new(), + single: Vec::new(), + out: Collector::default(), + }; + let mut blocks = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + return None; + } + let from = next.fetch_add(BLOCK, Ordering::Relaxed); + if from >= total { + return Some((worker.out, blocks)); + } + let to = (from + BLOCK).min(total); + blocks.push((from, worker.out.matches.len())); + match candidates { + Some(c) => worker.block(c[from..to].iter().copied()), + None => worker.block(from as u32..to as u32), + } + scanned.fetch_add(to - from, Ordering::Relaxed); + } + }) + .into_iter() + .map(Option::flatten) + .collect(); if cancel.load(Ordering::Relaxed) { return None; } @@ -492,6 +484,15 @@ fn read_at(f: &File, buf: &mut [u8], at: u64) -> std::io::Result { { std::os::windows::fs::FileExt::seek_read(f, buf, at) } + // Elsewhere (WebAssembly) through the cursor: such a target has no threads to + // share it with. + #[cfg(not(any(unix, windows)))] + { + use std::io::{Read, Seek, SeekFrom}; + let mut f = f; + f.seek(SeekFrom::Start(at))?; + f.read(buf) + } } fn read_exact_at(f: &File, mut buf: &mut [u8], mut at: u64) -> std::io::Result<()> { diff --git a/crates/chess-import/src/lib.rs b/crates/chess-import/src/lib.rs index efa18b4..930e11a 100644 --- a/crates/chess-import/src/lib.rs +++ b/crates/chess-import/src/lib.rs @@ -8,10 +8,13 @@ //! records and a game is converted to PGN when it is opened. Sources are only read. mod archive; +// Timings of a database on disk: a command of the desktop program. +#[cfg(not(target_family = "wasm"))] pub mod bench; pub mod cbv; pub mod chessbase; pub mod memory; +mod parallel; pub mod pgn_catalog; pub mod pgn_positions; pub mod position; diff --git a/crates/chess-import/src/parallel.rs b/crates/chess-import/src/parallel.rs new file mode 100644 index 0000000..99c0c30 --- /dev/null +++ b/crates/chess-import/src/parallel.rs @@ -0,0 +1,58 @@ +//! Worker threads of the parallel passes (booster, position search, opening tallies). +//! +//! A target without threads (WebAssembly in a browser: `std::thread::spawn` panics +//! there) runs every pass on the calling thread; so does a pass with one worker. + +/// Workers for a parallel pass: the threads the system offers, `fallback` when it +/// cannot tell; always one where there are no threads. +pub(crate) fn threads(fallback: usize) -> usize { + if cfg!(target_family = "wasm") { + return 1; + } + std::thread::available_parallelism().map_or(fallback, |n| n.get()) +} + +/// `work` for every item, each on its own scoped thread, results in the items' order +/// (`None`: that worker panicked). One item runs on the calling thread. +pub(crate) fn map(items: Vec, work: F) -> Vec> +where + I: Send, + T: Send, + F: Fn(I) -> T + Sync, +{ + if items.len() <= 1 { + return items.into_iter().map(|i| Some(work(i))).collect(); + } + let work = &work; + std::thread::scope(|s| { + let handles: Vec<_> = items + .into_iter() + .map(|i| s.spawn(move || work(i))) + .collect(); + handles.into_iter().map(|h| h.join().ok()).collect() + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keeps_order_and_runs_one_inline() { + let out = map(vec![3, 1, 2], |n| n * 10); + assert_eq!(out, vec![Some(30), Some(10), Some(20)]); + let here = std::thread::current().id(); + let one = map(vec![()], |()| std::thread::current().id()); + assert_eq!(one, vec![Some(here)]); + assert!(map(Vec::::new(), |n| n).is_empty()); + } + + #[test] + fn a_panicking_worker_gives_none() { + let out = map(vec![0, 1], |n| { + assert!(n == 0, "worker {n}"); + n + }); + assert_eq!(out, vec![Some(0), None]); + } +} diff --git a/crates/uci/Cargo.toml b/crates/uci/Cargo.toml index 9c9253f..326f1fd 100644 --- a/crates/uci/Cargo.toml +++ b/crates/uci/Cargo.toml @@ -8,6 +8,7 @@ description = "UCI chess engine process supervisor (no UI dependencies)" [dependencies] thiserror.workspace = true +web-time.workspace = true [target.'cfg(unix)'.dependencies] # nice(2) for EngineConfig::nice (std has no way to lower a child's priority). diff --git a/crates/uci/src/events.rs b/crates/uci/src/events.rs new file mode 100644 index 0000000..16a1460 --- /dev/null +++ b/crates/uci/src/events.rs @@ -0,0 +1,52 @@ +//! What a running engine tells the UI, whatever carries it. + +use crate::types::{SearchId, SearchInfo}; + +/// Callback invoked after every new event (from the transport's thread on a +/// computer); the UI passes `ctx.request_repaint()` here. +pub type Waker = Box; + +/// Event delivered to the UI. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EngineEvent { + /// `position` + `go` for this id were sent to the engine. + SearchStarted { search_id: SearchId }, + /// The request was replaced by a newer one (or cancelled by `stop`) + /// before it was sent to the engine; no events will follow for this id. + Superseded { search_id: SearchId }, + /// Search output. Only lines with a score or a PV are forwarded. + Info { + search_id: SearchId, + info: SearchInfo, + }, + /// Final `bestmove` of a started search. Exactly one per `SearchStarted` + /// unless the engine terminates first. + BestMove { + search_id: SearchId, + best: Option, + ponder: Option, + }, + /// `info string`, attributed to the running search if any. + InfoString { + search_id: Option, + text: String, + }, + /// Malformed or unexpected engine output; the line was skipped. + Warning(String), + /// The supervisor has stopped; the handle is no longer usable. + Terminated(TerminationReason), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TerminationReason { + /// `quit()` or drop of the handle. + Quit { + status: Option, + }, + /// The engine exited on its own (crash, end of its output, write failure). + Exited { + status: Option, + }, + /// The engine did not answer `stop` or `isready` in time and was killed. + Hung { waiting_for: &'static str }, +} diff --git a/crates/uci/src/lib.rs b/crates/uci/src/lib.rs index b8c8a06..2bce809 100644 --- a/crates/uci/src/lib.rs +++ b/crates/uci/src/lib.rs @@ -1,10 +1,12 @@ -//! UCI engine process supervisor. +//! UCI engine supervisor. //! -//! The engine runs as a separate child process started without a shell. -//! stdout and stderr are read by two dedicated threads; a supervisor thread -//! owns the protocol state machine. The UI talks to it through the -//! non-blocking [`EngineHandle`] and polls [`EngineEvent`]s every frame; the -//! [`Waker`] callback is invoked after each new event. +//! The protocol is a state machine without I/O ([`protocol`]); a transport drives +//! it. On a computer the engine is a child process started without a shell: +//! stdout and stderr are read by two dedicated threads, a supervisor thread +//! feeds the machine. The UI talks to it through the non-blocking +//! [`EngineHandle`] and polls [`EngineEvent`]s every frame; the [`Waker`] +//! callback is invoked after each new event. WebAssembly in a browser has no +//! processes, so there is no process transport there. //! //! Search boundary: UCI has no request ids. A new `position`/`go` is written //! only after the previous search ended with `bestmove` and a subsequent @@ -14,13 +16,20 @@ //! [`EngineEvent::Superseded`]. No dependency on egui or chess-core: //! positions are strings (FEN / UCI moves). -mod engine; mod error; +mod events; pub mod parse; +#[cfg(not(target_family = "wasm"))] +mod process; +// The machine is built where a transport drives it. +#[cfg(not(target_family = "wasm"))] +mod protocol; mod types; -pub use engine::{Engine, EngineConfig, EngineEvent, EngineHandle, TerminationReason, Waker}; pub use error::EngineError; +pub use events::{EngineEvent, TerminationReason, Waker}; +#[cfg(not(target_family = "wasm"))] +pub use process::{Engine, EngineConfig, EngineHandle}; pub use types::{ EngineInfo, EngineOption, EnginePosition, EngineScore, OptionKind, PositionBase, Score, ScoreBound, SearchId, SearchInfo, SearchLimits, Side, Timeouts, WhiteEval, WhiteScore, diff --git a/crates/uci/src/engine.rs b/crates/uci/src/process.rs similarity index 61% rename from crates/uci/src/engine.rs rename to crates/uci/src/process.rs index 6a4b726..d35dfff 100644 --- a/crates/uci/src/engine.rs +++ b/crates/uci/src/process.rs @@ -1,4 +1,6 @@ -//! Engine process, handshake and the supervisor thread. +//! The engine as a child process: started without a shell, its stdout and stderr +//! read by two threads, the protocol ([`crate::protocol`]) driven by a supervisor +//! thread that waits for input with the session's deadline. use std::collections::VecDeque; use std::ffi::{OsStr, OsString}; @@ -12,62 +14,14 @@ use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; use crate::error::EngineError; -use crate::parse::{EngineLine, parse_line}; -use crate::types::{ - EngineInfo, EnginePosition, OptionKind, SearchId, SearchInfo, SearchLimits, Timeouts, -}; - -/// Callback invoked (from the supervisor thread) after every new event; the -/// UI passes `ctx.request_repaint()` here. -pub type Waker = Box; +use crate::events::{EngineEvent, TerminationReason, Waker}; +use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session}; +use crate::types::{EngineInfo, EnginePosition, OptionKind, SearchId, SearchLimits, Timeouts}; /// Maximum stored length of one output line; longer lines are truncated. const MAX_LINE_BYTES: usize = 64 * 1024; /// Number of stderr lines kept for diagnostics. const STDERR_TAIL_LINES: usize = 256; -/// Maximum number of `Warning` events emitted per engine (flood protection). -const MAX_WARNINGS: usize = 100; - -/// Event delivered to the UI. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum EngineEvent { - /// `position` + `go` for this id were sent to the engine. - SearchStarted { search_id: SearchId }, - /// The request was replaced by a newer one (or cancelled by `stop`) - /// before it was sent to the engine; no events will follow for this id. - Superseded { search_id: SearchId }, - /// Search output. Only lines with a score or a PV are forwarded. - Info { - search_id: SearchId, - info: SearchInfo, - }, - /// Final `bestmove` of a started search. Exactly one per `SearchStarted` - /// unless the engine terminates first. - BestMove { - search_id: SearchId, - best: Option, - ponder: Option, - }, - /// `info string`, attributed to the running search if any. - InfoString { - search_id: Option, - text: String, - }, - /// Malformed or unexpected engine output; the line was skipped. - Warning(String), - /// The supervisor has stopped; the handle is no longer usable. - Terminated(TerminationReason), -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum TerminationReason { - /// `quit()` or drop of the handle. - Quit { status: Option }, - /// The process exited on its own (crash, EOF on stdout, write failure). - Exited { status: Option }, - /// The engine did not answer `stop` or `isready` in time and was killed. - Hung { waiting_for: &'static str }, -} /// Spawn configuration. #[derive(Debug, Clone)] @@ -128,23 +82,11 @@ impl Engine { enum Input { Cmd(Cmd), + Quit, Stdout(String), StdoutClosed, } -enum Cmd { - Search { - position: EnginePosition, - id: SearchId, - limits: SearchLimits, - among: Vec, - }, - Stop, - /// A complete `setoption ...` / `ucinewgame` line, applied while idle. - Setup(String), - Quit, -} - /// Handle owned by the UI. Dropping it quits (and if needed kills) the engine. pub struct EngineHandle { info: EngineInfo, @@ -337,7 +279,7 @@ impl EngineHandle { fn shutdown(&mut self) -> Option { if let Some(join) = self.supervisor.take() { - let _ = self.tx.send(Input::Cmd(Cmd::Quit)); + let _ = self.tx.send(Input::Quit); // The supervisor bounds its own shutdown by stop+quit timeouts; // the margin covers scheduling. If it is still stuck (e.g. a // blocked write), kill the process from here. @@ -492,10 +434,8 @@ fn spawn_impl(cfg: EngineConfig, waker: Waker) -> Result info, + let (info, warnings) = match handshake(&mut stdin, &rx, &cfg.timeouts) { + Ok(done) => done, Err(mut e) => { let _ = child.kill(); let status = child.wait().ok(); @@ -518,19 +458,18 @@ fn spawn_impl(cfg: EngineConfig, waker: Waker) -> Result(); let mut sup = Supervisor { - stdin, + pipes: Pipes { + stdin, + events: ev_tx, + waker, + }, + session: Session::new(cfg.timeouts), child: Arc::clone(&child), - events: ev_tx, - waker, alive: Arc::clone(&alive), timeouts: cfg.timeouts, - state: State::Idle, - pending: None, - pending_setup: Vec::new(), - warnings: 0, }; for w in warnings { - sup.warn(w); + sup.session.warn(w, &mut sup.pipes); } let supervisor = thread::Builder::new() .name(format!("uci-supervisor-{pid}")) @@ -562,12 +501,13 @@ fn write_line(stdin: &mut ChildStdin, line: &str) -> std::io::Result<()> { stdin.flush() } +/// The handshake over the pipes: every line read goes to [`Handshake`], until it is +/// complete or its deadline passes. fn handshake( stdin: &mut ChildStdin, rx: &Receiver, t: &Timeouts, - warnings: &mut Vec, -) -> Result { +) -> Result<(EngineInfo, Vec), EngineError> { let exited = || EngineError::ProcessExited { status: None, stderr: Vec::new(), @@ -579,68 +519,20 @@ fn handshake( EngineError::Io(e) } }; - write_line(stdin, "uci").map_err(io)?; - let mut info = EngineInfo::default(); - let mut seen_uci = false; - let mut output = Vec::new(); - let deadline = Instant::now() + t.uciok; + let mut hs = Handshake::new(t, Instant::now()); + write_line(stdin, Handshake::FIRST_LINE).map_err(io)?; loop { - let line = match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + let wait = hs.deadline().saturating_duration_since(Instant::now()); + let line = match rx.recv_timeout(wait) { Ok(Input::Stdout(l)) => l, Ok(Input::StdoutClosed) | Err(RecvTimeoutError::Disconnected) => return Err(exited()), - Ok(Input::Cmd(_)) => continue, - Err(RecvTimeoutError::Timeout) => { - return Err(if seen_uci { - EngineError::HandshakeTimeout { - waiting_for: "uciok", - } - } else { - EngineError::NotUci { output } - }); - } + Ok(Input::Cmd(_) | Input::Quit) => continue, + Err(RecvTimeoutError::Timeout) => return Err(hs.timed_out()), }; - if output.len() < 20 { - output.push(line.clone()); - } - match parse_line(&line) { - Ok(EngineLine::IdName(n)) => { - seen_uci = true; - info.name = Some(n); - } - Ok(EngineLine::IdAuthor(a)) => { - seen_uci = true; - info.author = Some(a); - } - Ok(EngineLine::Option(o)) => { - seen_uci = true; - info.options.push(o); - } - Ok(EngineLine::UciOk) => break, - Ok(_) => {} - Err(e) => { - if line.starts_with("option") { - seen_uci = true; - } - warnings.push(format!("handshake: {e}")); - } - } - } - write_line(stdin, "isready").map_err(io)?; - let deadline = Instant::now() + t.readyok; - loop { - match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { - Ok(Input::Stdout(l)) => { - if matches!(parse_line(&l), Ok(EngineLine::ReadyOk)) { - return Ok(info); - } - } - Ok(Input::StdoutClosed) | Err(RecvTimeoutError::Disconnected) => return Err(exited()), - Ok(Input::Cmd(_)) => {} - Err(RecvTimeoutError::Timeout) => { - return Err(EngineError::HandshakeTimeout { - waiting_for: "readyok", - }); - } + match hs.on_line(line, Instant::now()) { + HandshakeStep::Continue => {} + HandshakeStep::Write(l) => write_line(stdin, l).map_err(io)?, + HandshakeStep::Done(info, warnings) => return Ok((info, warnings)), } } } @@ -688,109 +580,50 @@ fn read_lines(mut r: BufReader, mut f: impl FnMut(String) -> bool) { } } -/// Supervisor state. Invariant: `position`/`go` is only written in -/// `Syncing → Searching`, i.e. after the previous search's `bestmove` *and* a -/// fresh `readyok`; therefore every `info` read while `Searching`/`Stopping` -/// belongs to the current search, and `info` read while `Idle`/`Syncing` is -/// stale and dropped. -#[derive(Debug, Clone, Copy)] -enum State { - /// No search running, nothing pending. - Idle, - /// `isready` sent before starting the pending search; waiting `readyok`. - Syncing { - deadline: Instant, - }, - Searching { - id: SearchId, - }, - /// `stop` sent; waiting for the final `bestmove` of `id`. - Stopping { - id: SearchId, - deadline: Instant, - }, -} - -impl State { - fn deadline(self) -> Option { - match self { - State::Syncing { deadline } | State::Stopping { deadline, .. } => Some(deadline), - _ => None, - } - } -} - -struct PendingSearch { - position: EnginePosition, - id: SearchId, - limits: SearchLimits, - among: Vec, -} - -struct Supervisor { +/// The process side of the session: the engine's stdin and the events' channel. +struct Pipes { stdin: ChildStdin, - child: Arc>, events: Sender, waker: Waker, - alive: Arc, - timeouts: Timeouts, - state: State, - pending: Option, - pending_setup: Vec, - warnings: usize, } -/// Why the loop must end. -enum Exit { - ProcessGone, - Hung(&'static str), -} +impl Link for Pipes { + fn write(&mut self, line: &str) -> Result<(), Gone> { + write_line(&mut self.stdin, line).map_err(|_| Gone) + } -impl Supervisor { - fn emit(&self, ev: EngineEvent) { + fn emit(&mut self, ev: EngineEvent) { if self.events.send(ev).is_ok() { (self.waker)(); } } +} - fn warn(&mut self, msg: String) { - self.warnings += 1; - if self.warnings < MAX_WARNINGS { - self.emit(EngineEvent::Warning(msg)); - } else if self.warnings == MAX_WARNINGS { - self.emit(EngineEvent::Warning( - "too many warnings; further warnings suppressed".into(), - )); - } - } - - fn write(&mut self, line: &str) -> Result<(), Exit> { - write_line(&mut self.stdin, line).map_err(|_| Exit::ProcessGone) - } +struct Supervisor { + pipes: Pipes, + session: Session, + child: Arc>, + alive: Arc, + timeouts: Timeouts, +} +impl Supervisor { fn run(mut self, rx: Receiver) { let result = loop { - let msg = match self.state.deadline() { + let msg = match self.session.deadline() { Some(d) => rx.recv_timeout(d.saturating_duration_since(Instant::now())), None => rx.recv().map_err(|_| RecvTimeoutError::Disconnected), }; + let now = Instant::now(); let step = match msg { - Ok(Input::Cmd(Cmd::Quit)) | Err(RecvTimeoutError::Disconnected) => { + Ok(Input::Quit) | Err(RecvTimeoutError::Disconnected) => { self.quit(); return; } - Ok(Input::Cmd(cmd)) => self.on_cmd(cmd), - Ok(Input::Stdout(line)) => self.on_line(&line), - Ok(Input::StdoutClosed) => Err(Exit::ProcessGone), - Err(RecvTimeoutError::Timeout) => match self.state { - State::Syncing { deadline } if Instant::now() >= deadline => { - Err(Exit::Hung("readyok")) - } - State::Stopping { deadline, .. } if Instant::now() >= deadline => { - Err(Exit::Hung("bestmove")) - } - _ => Ok(()), - }, + Ok(Input::Cmd(cmd)) => self.session.on_cmd(cmd, now, &mut self.pipes), + Ok(Input::Stdout(line)) => self.session.on_line(&line, now, &mut self.pipes), + Ok(Input::StdoutClosed) => Err(Exit::Gone), + Err(RecvTimeoutError::Timeout) => self.session.on_time(now), }; if let Err(e) = step { break e; @@ -804,11 +637,11 @@ impl Supervisor { let _ = child.wait(); TerminationReason::Hung { waiting_for } } - Exit::ProcessGone => TerminationReason::Exited { + Exit::Gone => TerminationReason::Exited { status: self.reap(Duration::from_millis(500)), }, }; - self.emit(EngineEvent::Terminated(reason)); + self.pipes.emit(EngineEvent::Terminated(reason)); } /// Waits up to `grace` for the process to exit, then kills it. Always reaps. @@ -832,150 +665,9 @@ impl Supervisor { fn quit(&mut self) { self.alive.store(false, Ordering::Release); - if matches!(self.state, State::Searching { .. }) { - let _ = self.write("stop"); - } - let _ = self.write("quit"); + self.session.quit(&mut self.pipes); let status = self.reap(self.timeouts.quit); - self.emit(EngineEvent::Terminated(TerminationReason::Quit { status })); - } - - fn on_cmd(&mut self, cmd: Cmd) -> Result<(), Exit> { - match cmd { - Cmd::Search { - position, - id, - limits, - among, - } => { - if let Some(old) = self.pending.replace(PendingSearch { - position, - id, - limits, - among, - }) { - self.emit(EngineEvent::Superseded { search_id: old.id }); - } - match self.state { - State::Idle => self.begin_sync()?, - State::Searching { id } => self.send_stop(id)?, - State::Syncing { .. } | State::Stopping { .. } => {} - } - } - Cmd::Stop => { - if let Some(old) = self.pending.take() { - self.emit(EngineEvent::Superseded { search_id: old.id }); - } - if let State::Searching { id } = self.state { - self.send_stop(id)?; - } - } - Cmd::Setup(line) => match self.state { - // The engine is not searching: safe to send right away; the - // `isready` before the next `go` fences it. - State::Idle | State::Syncing { .. } => self.write(&line)?, - State::Searching { .. } | State::Stopping { .. } => self.pending_setup.push(line), - }, - Cmd::Quit => unreachable!("handled in run"), - } - Ok(()) - } - - fn send_stop(&mut self, id: SearchId) -> Result<(), Exit> { - self.write("stop")?; - self.state = State::Stopping { - id, - deadline: Instant::now() + self.timeouts.stop, - }; - Ok(()) - } - - /// Engine is idle: flush queued setup, then `isready` if a search waits. - fn begin_sync(&mut self) -> Result<(), Exit> { - for line in std::mem::take(&mut self.pending_setup) { - self.write(&line)?; - } - if self.pending.is_some() { - self.write("isready")?; - self.state = State::Syncing { - deadline: Instant::now() + self.timeouts.readyok, - }; - } else { - self.state = State::Idle; - } - Ok(()) - } - - fn current_search(&self) -> Option { - match self.state { - State::Searching { id } | State::Stopping { id, .. } => Some(id), - _ => None, - } - } - - fn on_line(&mut self, line: &str) -> Result<(), Exit> { - let parsed = match parse_line(line) { - Ok(p) => p, - Err(e) => { - self.warn(e.to_string()); - return Ok(()); - } - }; - match parsed { - EngineLine::Info(info) => { - if let Some(id) = self.current_search() - && (info.score.is_some() || !info.pv.is_empty()) - { - self.emit(EngineEvent::Info { - search_id: id, - info, - }); - } - // Otherwise: stale output of a finished search, dropped. - } - EngineLine::InfoString(text) => { - let search_id = self.current_search(); - self.emit(EngineEvent::InfoString { search_id, text }); - } - EngineLine::BestMove { best, ponder } => match self.current_search() { - Some(id) => { - self.emit(EngineEvent::BestMove { - search_id: id, - best, - ponder, - }); - self.state = State::Idle; - self.begin_sync()?; - } - None => self.warn(format!("unexpected bestmove ignored: {line:?}")), - }, - EngineLine::ReadyOk => { - if let State::Syncing { .. } = self.state { - match self.pending.take() { - Some(p) => { - self.write(&p.position.to_command())?; - let mut go = p.limits.to_command(); - if !p.among.is_empty() { - go += " searchmoves "; - go += &p.among.join(" "); - } - self.write(&go)?; - self.state = State::Searching { id: p.id }; - self.emit(EngineEvent::SearchStarted { search_id: p.id }); - } - None => self.state = State::Idle, - } - } - } - EngineLine::Empty => {} - EngineLine::UciOk - | EngineLine::IdName(_) - | EngineLine::IdAuthor(_) - | EngineLine::Option(_) - | EngineLine::Unknown(_) => { - self.warn(format!("unexpected engine output: {line:?}")); - } - } - Ok(()) + self.pipes + .emit(EngineEvent::Terminated(TerminationReason::Quit { status })); } } diff --git a/crates/uci/src/protocol.rs b/crates/uci/src/protocol.rs new file mode 100644 index 0000000..71b0fc4 --- /dev/null +++ b/crates/uci/src/protocol.rs @@ -0,0 +1,545 @@ +//! The UCI protocol as a state machine without I/O: the handshake and the session +//! after it. A transport (a child process on a computer, a Web Worker in a browser) +//! feeds it the engine's lines, the user's commands and the time, and carries out +//! what it asks: lines to write, events to deliver. Waiting is the transport's +//! business — the machine never blocks, it only names its next deadline. + +use web_time::Instant; + +use crate::error::EngineError; +use crate::events::EngineEvent; +use crate::parse::{EngineLine, parse_line}; +use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts}; + +/// Maximum number of `Warning` events emitted per engine (flood protection). +const MAX_WARNINGS: usize = 100; + +/// A command from the handle to the session. +pub(crate) enum Cmd { + Search { + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + among: Vec, + }, + Stop, + /// A complete `setoption ...` / `ucinewgame` line, applied while idle. + Setup(String), +} + +/// The engine could not be written to: it is gone. +#[derive(Debug)] +pub(crate) struct Gone; + +/// What the session does to the outside world. +pub(crate) trait Link { + /// Writes one line (without its `\n`) to the engine. + fn write(&mut self, line: &str) -> Result<(), Gone>; + /// Delivers an event to the handle (and wakes the UI). + fn emit(&mut self, ev: EngineEvent); +} + +/// The step of the handshake: `uci` → `uciok`, then `isready` → `readyok`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Phase { + Uci, + Ready, +} + +/// `uci`/`uciok` and `isready`/`readyok`: the engine's name, author and options. +pub(crate) struct Handshake { + phase: Phase, + deadline: Instant, + readyok: std::time::Duration, + info: EngineInfo, + seen_uci: bool, + /// First lines of output, for [`EngineError::NotUci`]. + output: Vec, + /// Malformed lines, reported once the session runs. + warnings: Vec, +} + +/// How a line moved the handshake on. +pub(crate) enum HandshakeStep { + /// Keep feeding lines. + Continue, + /// Write this line, then keep feeding lines. + Write(&'static str), + /// Complete: the engine is ready for the session. + Done(EngineInfo, Vec), +} + +impl Handshake { + /// Starts the handshake at `now`; the caller writes [`Self::FIRST_LINE`]. + pub(crate) fn new(t: &Timeouts, now: Instant) -> Self { + Handshake { + phase: Phase::Uci, + deadline: now + t.uciok, + readyok: t.readyok, + info: EngineInfo::default(), + seen_uci: false, + output: Vec::new(), + warnings: Vec::new(), + } + } + + pub(crate) const FIRST_LINE: &'static str = "uci"; + + pub(crate) fn deadline(&self) -> Instant { + self.deadline + } + + /// One line of the engine's output, read at `now`. + pub(crate) fn on_line(&mut self, line: String, now: Instant) -> HandshakeStep { + match self.phase { + Phase::Uci => { + if self.output.len() < 20 { + self.output.push(line.clone()); + } + match parse_line(&line) { + Ok(EngineLine::IdName(n)) => { + self.seen_uci = true; + self.info.name = Some(n); + } + Ok(EngineLine::IdAuthor(a)) => { + self.seen_uci = true; + self.info.author = Some(a); + } + Ok(EngineLine::Option(o)) => { + self.seen_uci = true; + self.info.options.push(o); + } + Ok(EngineLine::UciOk) => { + self.phase = Phase::Ready; + self.deadline = now + self.readyok; + return HandshakeStep::Write("isready"); + } + Ok(_) => {} + Err(e) => { + if line.starts_with("option") { + self.seen_uci = true; + } + self.warnings.push(format!("handshake: {e}")); + } + } + HandshakeStep::Continue + } + Phase::Ready => { + if matches!(parse_line(&line), Ok(EngineLine::ReadyOk)) { + HandshakeStep::Done( + std::mem::take(&mut self.info), + std::mem::take(&mut self.warnings), + ) + } else { + HandshakeStep::Continue + } + } + } + } + + /// The error once [`Self::deadline`] has passed. + pub(crate) fn timed_out(self) -> EngineError { + match self.phase { + Phase::Uci if self.seen_uci => EngineError::HandshakeTimeout { + waiting_for: "uciok", + }, + Phase::Uci => EngineError::NotUci { + output: self.output, + }, + Phase::Ready => EngineError::HandshakeTimeout { + waiting_for: "readyok", + }, + } + } +} + +/// Session state. Invariant: `position`/`go` is only written in +/// `Syncing → Searching`, i.e. after the previous search's `bestmove` *and* a +/// fresh `readyok`; therefore every `info` read while `Searching`/`Stopping` +/// belongs to the current search, and `info` read while `Idle`/`Syncing` is +/// stale and dropped. +#[derive(Debug, Clone, Copy)] +enum State { + /// No search running, nothing pending. + Idle, + /// `isready` sent before starting the pending search; waiting `readyok`. + Syncing { + deadline: Instant, + }, + Searching { + id: SearchId, + }, + /// `stop` sent; waiting for the final `bestmove` of `id`. + Stopping { + id: SearchId, + deadline: Instant, + }, +} + +struct PendingSearch { + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + among: Vec, +} + +/// Why the session must end. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Exit { + /// The engine stopped reading or writing. + Gone, + /// The engine did not answer this in time; the transport kills it. + Hung(&'static str), +} + +impl From for Exit { + fn from(_: Gone) -> Self { + Exit::Gone + } +} + +/// The session after the handshake: searches, their boundaries, setup lines. +pub(crate) struct Session { + timeouts: Timeouts, + state: State, + pending: Option, + pending_setup: Vec, + warnings: usize, +} + +impl Session { + pub(crate) fn new(timeouts: Timeouts) -> Self { + Session { + timeouts, + state: State::Idle, + pending: None, + pending_setup: Vec::new(), + warnings: 0, + } + } + + /// When [`Self::on_time`] must be called next (`None`: nothing to wait for). + pub(crate) fn deadline(&self) -> Option { + match self.state { + State::Syncing { deadline } | State::Stopping { deadline, .. } => Some(deadline), + _ => None, + } + } + + /// The time is `now`: an engine past its deadline is hung. + pub(crate) fn on_time(&mut self, now: Instant) -> Result<(), Exit> { + match self.state { + State::Syncing { deadline } if now >= deadline => Err(Exit::Hung("readyok")), + State::Stopping { deadline, .. } if now >= deadline => Err(Exit::Hung("bestmove")), + _ => Ok(()), + } + } + + pub(crate) fn warn(&mut self, msg: String, link: &mut impl Link) { + self.warnings += 1; + if self.warnings < MAX_WARNINGS { + link.emit(EngineEvent::Warning(msg)); + } else if self.warnings == MAX_WARNINGS { + link.emit(EngineEvent::Warning( + "too many warnings; further warnings suppressed".into(), + )); + } + } + + /// The last words before `quit`: a running search is stopped. + pub(crate) fn quit(&mut self, link: &mut impl Link) { + if matches!(self.state, State::Searching { .. }) { + let _ = link.write("stop"); + } + let _ = link.write("quit"); + } + + pub(crate) fn on_cmd( + &mut self, + cmd: Cmd, + now: Instant, + link: &mut impl Link, + ) -> Result<(), Exit> { + match cmd { + Cmd::Search { + position, + id, + limits, + among, + } => { + if let Some(old) = self.pending.replace(PendingSearch { + position, + id, + limits, + among, + }) { + link.emit(EngineEvent::Superseded { search_id: old.id }); + } + match self.state { + State::Idle => self.begin_sync(now, link)?, + State::Searching { id } => self.send_stop(id, now, link)?, + State::Syncing { .. } | State::Stopping { .. } => {} + } + } + Cmd::Stop => { + if let Some(old) = self.pending.take() { + link.emit(EngineEvent::Superseded { search_id: old.id }); + } + if let State::Searching { id } = self.state { + self.send_stop(id, now, link)?; + } + } + Cmd::Setup(line) => match self.state { + // The engine is not searching: safe to send right away; the + // `isready` before the next `go` fences it. + State::Idle | State::Syncing { .. } => link.write(&line)?, + State::Searching { .. } | State::Stopping { .. } => self.pending_setup.push(line), + }, + } + Ok(()) + } + + fn send_stop(&mut self, id: SearchId, now: Instant, link: &mut impl Link) -> Result<(), Exit> { + link.write("stop")?; + self.state = State::Stopping { + id, + deadline: now + self.timeouts.stop, + }; + Ok(()) + } + + /// Engine is idle: flush queued setup, then `isready` if a search waits. + fn begin_sync(&mut self, now: Instant, link: &mut impl Link) -> Result<(), Exit> { + for line in std::mem::take(&mut self.pending_setup) { + link.write(&line)?; + } + if self.pending.is_some() { + link.write("isready")?; + self.state = State::Syncing { + deadline: now + self.timeouts.readyok, + }; + } else { + self.state = State::Idle; + } + Ok(()) + } + + fn current_search(&self) -> Option { + match self.state { + State::Searching { id } | State::Stopping { id, .. } => Some(id), + _ => None, + } + } + + /// One line of the engine's output, read at `now`. + pub(crate) fn on_line( + &mut self, + line: &str, + now: Instant, + link: &mut impl Link, + ) -> Result<(), Exit> { + let parsed = match parse_line(line) { + Ok(p) => p, + Err(e) => { + self.warn(e.to_string(), link); + return Ok(()); + } + }; + match parsed { + EngineLine::Info(info) => { + if let Some(id) = self.current_search() + && (info.score.is_some() || !info.pv.is_empty()) + { + link.emit(EngineEvent::Info { + search_id: id, + info, + }); + } + // Otherwise: stale output of a finished search, dropped. + } + EngineLine::InfoString(text) => { + let search_id = self.current_search(); + link.emit(EngineEvent::InfoString { search_id, text }); + } + EngineLine::BestMove { best, ponder } => match self.current_search() { + Some(id) => { + link.emit(EngineEvent::BestMove { + search_id: id, + best, + ponder, + }); + self.state = State::Idle; + self.begin_sync(now, link)?; + } + None => self.warn(format!("unexpected bestmove ignored: {line:?}"), link), + }, + EngineLine::ReadyOk => { + if let State::Syncing { .. } = self.state { + match self.pending.take() { + Some(p) => { + link.write(&p.position.to_command())?; + let mut go = p.limits.to_command(); + if !p.among.is_empty() { + go += " searchmoves "; + go += &p.among.join(" "); + } + link.write(&go)?; + self.state = State::Searching { id: p.id }; + link.emit(EngineEvent::SearchStarted { search_id: p.id }); + } + None => self.state = State::Idle, + } + } + } + EngineLine::Empty => {} + EngineLine::UciOk + | EngineLine::IdName(_) + | EngineLine::IdAuthor(_) + | EngineLine::Option(_) + | EngineLine::Unknown(_) => { + self.warn(format!("unexpected engine output: {line:?}"), link); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + /// A link that records what the session did. + #[derive(Default)] + struct Record { + written: Vec, + events: Vec, + broken: bool, + } + + impl Link for Record { + fn write(&mut self, line: &str) -> Result<(), Gone> { + if self.broken { + return Err(Gone); + } + self.written.push(line.to_owned()); + Ok(()) + } + fn emit(&mut self, ev: EngineEvent) { + self.events.push(ev); + } + } + + fn search(id: u64) -> Cmd { + Cmd::Search { + position: EnginePosition::startpos(Vec::::new()), + id: SearchId(id), + limits: SearchLimits::Infinite, + among: Vec::new(), + } + } + + #[test] + fn handshake_collects_info_and_asks_ready() { + let t0 = Instant::now(); + let mut h = Handshake::new(&Timeouts::default(), t0); + assert!(matches!( + h.on_line("id name Fake".into(), t0), + HandshakeStep::Continue + )); + assert!(matches!( + h.on_line( + "option name Hash type spin default 16 min 1 max 1024".into(), + t0 + ), + HandshakeStep::Continue + )); + let later = t0 + Duration::from_secs(1); + assert!(matches!( + h.on_line("uciok".into(), later), + HandshakeStep::Write("isready") + )); + assert_eq!(h.deadline(), later + Timeouts::default().readyok); + // Output before `readyok` is not taken for the engine's description. + assert!(matches!( + h.on_line("id name Other".into(), later), + HandshakeStep::Continue + )); + match h.on_line("readyok".into(), later) { + HandshakeStep::Done(info, warnings) => { + assert_eq!(info.name.as_deref(), Some("Fake")); + assert_eq!(info.options.len(), 1); + assert!(warnings.is_empty()); + } + _ => panic!("handshake not done"), + } + } + + #[test] + fn handshake_timeouts_name_what_was_missing() { + let t0 = Instant::now(); + let silent = Handshake::new(&Timeouts::default(), t0); + assert!(matches!(silent.timed_out(), EngineError::NotUci { .. })); + let mut uci = Handshake::new(&Timeouts::default(), t0); + let _ = uci.on_line("id name Fake".into(), t0); + assert!(matches!( + uci.timed_out(), + EngineError::HandshakeTimeout { + waiting_for: "uciok" + } + )); + let mut ready = Handshake::new(&Timeouts::default(), t0); + let _ = ready.on_line("uciok".into(), t0); + assert!(matches!( + ready.timed_out(), + EngineError::HandshakeTimeout { + waiting_for: "readyok" + } + )); + } + + #[test] + fn a_search_waits_for_readyok_and_stale_info_is_dropped() { + let now = Instant::now(); + let mut s = Session::new(Timeouts::default()); + let mut link = Record::default(); + s.on_cmd(search(1), now, &mut link).unwrap(); + assert_eq!(link.written, ["isready"]); + // Info before the search starts belongs to nobody. + s.on_line("info depth 1 score cp 5 pv e2e4", now, &mut link) + .unwrap(); + assert!(link.events.is_empty()); + s.on_line("readyok", now, &mut link).unwrap(); + assert_eq!(link.written[1], "position startpos"); + assert_eq!(link.written[2], "go infinite"); + assert_eq!( + link.events, + [EngineEvent::SearchStarted { + search_id: SearchId(1) + }] + ); + // A newer request stops the running search; the old `bestmove` ends it. + s.on_cmd(search(2), now, &mut link).unwrap(); + assert_eq!(link.written[3], "stop"); + s.on_line("bestmove e2e4", now, &mut link).unwrap(); + assert_eq!(link.written[4], "isready"); + s.on_line("readyok", now, &mut link).unwrap(); + assert!(link.events.contains(&EngineEvent::SearchStarted { + search_id: SearchId(2) + })); + } + + #[test] + fn deadlines_and_a_broken_link_end_the_session() { + let now = Instant::now(); + let mut s = Session::new(Timeouts::default()); + let mut link = Record::default(); + assert_eq!(s.deadline(), None); + s.on_cmd(search(1), now, &mut link).unwrap(); + let d = s.deadline().expect("waiting for readyok"); + assert_eq!(s.on_time(now), Ok(())); + assert_eq!(s.on_time(d), Err(Exit::Hung("readyok"))); + link.broken = true; + assert_eq!(s.on_line("readyok", now, &mut link), Err(Exit::Gone)); + } +} diff --git a/crates/uci/src/types.rs b/crates/uci/src/types.rs index 148354f..7b57cca 100644 --- a/crates/uci/src/types.rs +++ b/crates/uci/src/types.rs @@ -253,7 +253,8 @@ impl EnginePosition { Ok(()) } - pub(crate) fn to_command(&self) -> String { + /// The `position …` line for this position. + pub fn to_command(&self) -> String { let mut s = match &self.base { PositionBase::StartPos => "position startpos".to_string(), PositionBase::Fen(fen) => format!("position fen {}", fen.trim()), @@ -290,7 +291,8 @@ pub enum SearchLimits { } impl SearchLimits { - pub(crate) fn to_command(self) -> String { + /// The `go …` line for these limits. + pub fn to_command(self) -> String { match self { SearchLimits::Infinite => "go infinite".into(), SearchLimits::Depth(d) => format!("go depth {d}"),