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 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-30 14:19:21 +03:00
parent 89269b8849
commit a66d1016d9
13 changed files with 858 additions and 493 deletions

52
crates/uci/src/events.rs Normal file
View file

@ -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<dyn Fn() + Send + 'static>;
/// 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<String>,
ponder: Option<String>,
},
/// `info string`, attributed to the running search if any.
InfoString {
search_id: Option<SearchId>,
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<std::process::ExitStatus>,
},
/// The engine exited on its own (crash, end of its output, write failure).
Exited {
status: Option<std::process::ExitStatus>,
},
/// The engine did not answer `stop` or `isready` in time and was killed.
Hung { waiting_for: &'static str },
}

View file

@ -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,

View file

@ -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<dyn Fn() + Send + 'static>;
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<String>,
ponder: Option<String>,
},
/// `info string`, attributed to the running search if any.
InfoString {
search_id: Option<SearchId>,
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<ExitStatus> },
/// The process exited on its own (crash, EOF on stdout, write failure).
Exited { status: Option<ExitStatus> },
/// 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<String>,
},
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<ExitStatus> {
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<EngineHandle, EngineErr
}
let mut stdin = stdin;
let mut warnings = Vec::new();
let handshake = handshake(&mut stdin, &rx, &cfg.timeouts, &mut warnings);
let info = match handshake {
Ok(info) => 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<EngineHandle, EngineErr
let child = Arc::new(Mutex::new(child));
let (done_tx, done_rx) = mpsc::channel::<()>();
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<Input>,
t: &Timeouts,
warnings: &mut Vec<String>,
) -> Result<EngineInfo, EngineError> {
) -> Result<(EngineInfo, Vec<String>), 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<R: Read>(mut r: BufReader<R>, 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<Instant> {
match self {
State::Syncing { deadline } | State::Stopping { deadline, .. } => Some(deadline),
_ => None,
}
}
}
struct PendingSearch {
position: EnginePosition,
id: SearchId,
limits: SearchLimits,
among: Vec<String>,
}
struct Supervisor {
/// The process side of the session: the engine's stdin and the events' channel.
struct Pipes {
stdin: ChildStdin,
child: Arc<Mutex<Child>>,
events: Sender<EngineEvent>,
waker: Waker,
alive: Arc<AtomicBool>,
timeouts: Timeouts,
state: State,
pending: Option<PendingSearch>,
pending_setup: Vec<String>,
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<Mutex<Child>>,
alive: Arc<AtomicBool>,
timeouts: Timeouts,
}
impl Supervisor {
fn run(mut self, rx: Receiver<Input>) {
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<SearchId> {
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 }));
}
}

545
crates/uci/src/protocol.rs Normal file
View file

@ -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<String>,
},
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<String>,
/// Malformed lines, reported once the session runs.
warnings: Vec<String>,
}
/// 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<String>),
}
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<String>,
}
/// 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<Gone> 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<PendingSearch>,
pending_setup: Vec<String>,
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<Instant> {
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<SearchId> {
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<String>,
events: Vec<EngineEvent>,
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::<String>::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));
}
}

View file

@ -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}"),