Web version, stage 2: Stockfish 19 in workers, live analysis, game review on N workers, My games, files, keys
game-review: what the job does for one target (the full search, the second best without the move played, the shallow ones) becomes a machine without I/O (job/work.rs), driven by the engine processes on a computer (job/engines.rs, the same searches as before) and by Web Workers in a browser (job/workers.rs: a dispatcher polled from the frames, never blocking). The analysis cache goes through a CacheStore (a folder, or the program's files of the platform). The browser's engine: Stockfish.js 19.0.1 (npm stockfish, GPL-3.0), its single-threaded build served beside /app/ (engine/, build.sh checks the package's sha512), its 99 MB wasm downloaded only through the engine offer, checked against its SHA-256 and kept in Cache Storage; workers get it as a blob: address. Live analysis (lines, arrows, the bar) and the review run on it; the review uses one worker per logical CPU, at most 8. My games (the web version): a PGN in the browser's storage, always on the shelf; Ctrl+S puts a game there (its own record, or a new one); deleting with undo. chess-core's store gives the bytes of append/replace/remove/restore, so the platform writes them into the browser's files; on a computer the files are written as before. Settings: Browser data (used and free space, keeping the data for good, Download all as PGN, deleting the engine). Files: a file of the last visit offers Choose the file again; Keep a copy in the browser (refused with the room it needs when the browser gives too little); files over 1 GB are not opened, with a word on why. No reference tab and no search by position in the web version. Keys: Alt+Left, plain 1-6, Ctrl+C, N in the library (the browser keeps Ctrl+W/N/1-6/Shift+C). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4ccf8099a5
commit
61ccd763bc
34 changed files with 2063 additions and 253 deletions
|
|
@ -97,21 +97,38 @@ fn check_writable(db: &PgnDatabase) -> Result<&Path, WriteError> {
|
|||
/// before the new record stay as they were.
|
||||
pub fn append(db: &PgnDatabase, record: &str) -> Result<Appended, WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
let bytes = db.bytes();
|
||||
let eol = line_ending(bytes);
|
||||
let sep = separator(bytes, eol);
|
||||
let mut data = sep.as_bytes().to_vec();
|
||||
data.extend(record_bytes(record, eol));
|
||||
let (data, sep) = tail_for(db.bytes(), record);
|
||||
let mut file = std::fs::OpenOptions::new().append(true).open(path)?;
|
||||
let offset = file.metadata()?.len() + sep.len() as u64;
|
||||
let offset = file.metadata()?.len() + sep as u64;
|
||||
file.write_all(&data)?;
|
||||
file.sync_all()?;
|
||||
Ok(Appended { offset })
|
||||
}
|
||||
|
||||
/// Replaces record `index` with `record`; every other byte of the file stays.
|
||||
pub fn replace(db: &PgnDatabase, index: usize, record: &str) -> Result<(), WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
/// What goes at the end of `bytes` to add `record` after a blank line, and how many of
|
||||
/// its bytes come before the record.
|
||||
fn tail_for(bytes: &[u8], record: &str) -> (Vec<u8>, usize) {
|
||||
let eol = line_ending(bytes);
|
||||
let sep = separator(bytes, eol);
|
||||
let mut data = sep.as_bytes().to_vec();
|
||||
data.extend(record_bytes(record, eol));
|
||||
(data, sep.len())
|
||||
}
|
||||
|
||||
/// The text of `db` with `record` added at the end, and where the record starts: the
|
||||
/// same bytes [`append`] writes, for a database kept elsewhere than in a file (the web
|
||||
/// version's games in the browser).
|
||||
pub fn appended(db: &PgnDatabase, record: &str) -> (Vec<u8>, u64) {
|
||||
let bytes = db.bytes();
|
||||
let (tail, sep) = tail_for(bytes, record);
|
||||
let mut out = Vec::with_capacity(bytes.len() + tail.len());
|
||||
out.extend_from_slice(bytes);
|
||||
out.extend(tail);
|
||||
(out, (bytes.len() + sep) as u64)
|
||||
}
|
||||
|
||||
/// The text of `db` with record `index` replaced by `record` (what [`replace`] writes).
|
||||
pub fn replaced(db: &PgnDatabase, index: usize, record: &str) -> Result<Vec<u8>, WriteError> {
|
||||
let bytes = db.bytes();
|
||||
let range = db
|
||||
.entries()
|
||||
|
|
@ -124,14 +141,11 @@ pub fn replace(db: &PgnDatabase, index: usize, record: &str) -> Result<(), Write
|
|||
out.extend_from_slice(&bytes[..range.start]);
|
||||
out.extend(record_bytes(record, eol));
|
||||
out.extend_from_slice(&bytes[range.end..]);
|
||||
write_atomic(path, &out)?;
|
||||
Ok(())
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Removes record `index`; the bytes before and after it stay. What was removed comes
|
||||
/// back with [`restore`].
|
||||
pub fn remove(db: &PgnDatabase, index: usize) -> Result<Removed, WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
/// The text of `db` without record `index` (what [`remove`] writes) and the record.
|
||||
pub fn removed(db: &PgnDatabase, index: usize) -> Result<(Vec<u8>, Removed), WriteError> {
|
||||
let bytes = db.bytes();
|
||||
let range = db
|
||||
.entries()
|
||||
|
|
@ -142,11 +156,29 @@ pub fn remove(db: &PgnDatabase, index: usize) -> Result<Removed, WriteError> {
|
|||
let mut out = Vec::with_capacity(bytes.len());
|
||||
out.extend_from_slice(&bytes[..range.start]);
|
||||
out.extend_from_slice(&bytes[range.end..]);
|
||||
Ok((
|
||||
out,
|
||||
Removed {
|
||||
index,
|
||||
bytes: bytes[range].to_vec(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// Replaces record `index` with `record`; every other byte of the file stays.
|
||||
pub fn replace(db: &PgnDatabase, index: usize, record: &str) -> Result<(), WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
write_atomic(path, &replaced(db, index, record)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes record `index`; the bytes before and after it stay. What was removed comes
|
||||
/// back with [`restore`].
|
||||
pub fn remove(db: &PgnDatabase, index: usize) -> Result<Removed, WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
let (out, gone) = removed(db, index)?;
|
||||
write_atomic(path, &out)?;
|
||||
Ok(Removed {
|
||||
index,
|
||||
bytes: bytes[range].to_vec(),
|
||||
})
|
||||
Ok(gone)
|
||||
}
|
||||
|
||||
/// Puts a removed record back at its place: the file is byte for byte what it was
|
||||
|
|
@ -154,6 +186,12 @@ pub fn remove(db: &PgnDatabase, index: usize) -> Result<Removed, WriteError> {
|
|||
/// database as read after the removal.
|
||||
pub fn restore(db: &PgnDatabase, removed: &Removed) -> Result<(), WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
write_atomic(path, &restored(db, removed)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The text of `db` with a removed record back at its place (what [`restore`] writes).
|
||||
pub fn restored(db: &PgnDatabase, removed: &Removed) -> Result<Vec<u8>, WriteError> {
|
||||
let bytes = db.bytes();
|
||||
let at = match db.entries().get(removed.index) {
|
||||
Some(e) => e.byte_range.start,
|
||||
|
|
@ -164,8 +202,7 @@ pub fn restore(db: &PgnDatabase, removed: &Removed) -> Result<(), WriteError> {
|
|||
out.extend_from_slice(&bytes[..at]);
|
||||
out.extend_from_slice(&removed.bytes);
|
||||
out.extend_from_slice(&bytes[at..]);
|
||||
write_atomic(path, &out)?;
|
||||
Ok(())
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Writes every record of `db` into `dest` as UTF-8 (LF, one blank line between
|
||||
|
|
|
|||
|
|
@ -15,3 +15,4 @@ uci.workspace = true
|
|||
chess-openings.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
web-time.workspace = true
|
||||
|
|
|
|||
|
|
@ -14,12 +14,19 @@ use uci::{EnginePosition, Side};
|
|||
|
||||
use crate::PosEval;
|
||||
|
||||
// What the job does for one target, whatever drives it.
|
||||
mod work;
|
||||
// The job in engine processes, each on a thread of its own: a computer's and a
|
||||
// phone's.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
mod engines;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub use engines::run;
|
||||
// The job in Web Workers: a browser's.
|
||||
#[cfg(target_family = "wasm")]
|
||||
mod workers;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub use workers::Dispatcher;
|
||||
|
||||
/// Nodes of every search of a game analysis (0.85 s on one thread of an i7-13700KF,
|
||||
/// depth about 24).
|
||||
|
|
|
|||
|
|
@ -5,10 +5,10 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|||
use std::sync::mpsc::channel;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side};
|
||||
use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits};
|
||||
|
||||
use super::work::{Answer, Next, Work};
|
||||
use super::{JobEvent, JobFailure, JobSettings, MAX_PROCESSES, SEARCH_HASH_MB, Target};
|
||||
use crate::{Eval, PosEval, Second, Shallow};
|
||||
|
||||
/// A node-limited search should never take this long; stop it if it does.
|
||||
const SEARCH_GUARD: Duration = Duration::from_secs(300);
|
||||
|
|
@ -107,133 +107,33 @@ fn worker(
|
|||
let _ = handle.new_game();
|
||||
search_once(&handle, pos, SearchId(next_id), among, nodes, halted)
|
||||
};
|
||||
while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||
'targets: while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||
if halted() {
|
||||
break;
|
||||
}
|
||||
let (mut eval, nps) = match &t.known {
|
||||
Some(e) => (e.clone(), 0),
|
||||
None => {
|
||||
let Some((info, best)) = search(&t.pos, Vec::new(), settings.nodes)? else {
|
||||
continue;
|
||||
};
|
||||
let Some(score) = info.score else { continue };
|
||||
let mut pv: Vec<String> = info.pv.iter().take(12).cloned().collect();
|
||||
if let Some(b) = best
|
||||
&& pv.first() != Some(&b)
|
||||
{
|
||||
pv = vec![b];
|
||||
}
|
||||
let eval = PosEval {
|
||||
eval: Eval::from_white_eval(score.to_white(t.turn).eval),
|
||||
pv,
|
||||
depth: info.depth.unwrap_or(0),
|
||||
second: None,
|
||||
shallow: None,
|
||||
};
|
||||
(eval, info.nps.unwrap_or(0))
|
||||
}
|
||||
};
|
||||
// The move played is the engine's best: what the best of the others gives says
|
||||
// whether it was the only good move, or a sacrifice when nothing else won.
|
||||
let mover = match t.turn {
|
||||
Side::White => chess_core::shakmaty::Color::White,
|
||||
Side::Black => chess_core::shakmaty::Color::Black,
|
||||
};
|
||||
let played = t.played.as_ref().filter(|p| {
|
||||
eval.pv.first() == Some(*p)
|
||||
&& !t.others.is_empty()
|
||||
&& crate::report::worth_second(eval.eval, mover)
|
||||
});
|
||||
if let Some(played) = played
|
||||
&& eval.second.as_ref().map(|s| &s.without) != Some(played)
|
||||
{
|
||||
match search(&t.pos, t.others.clone(), settings.nodes)? {
|
||||
// An engine that ignores `searchmoves` answers with the move played:
|
||||
// no second move then.
|
||||
Some((info, best))
|
||||
if best.as_ref() != Some(played) && info.pv.first() != Some(played) =>
|
||||
{
|
||||
if let Some(score) = info.score {
|
||||
eval.second = Some(Second {
|
||||
without: played.clone(),
|
||||
eval: Eval::from_white_eval(score.to_white(t.turn).eval),
|
||||
});
|
||||
let mut work = Work::new(t.clone(), settings.nodes);
|
||||
loop {
|
||||
match work.next() {
|
||||
Next::Search { pos, among, nodes } => {
|
||||
let answer = search(&pos, among, nodes)?;
|
||||
if answer.is_none() && halted() {
|
||||
break 'targets;
|
||||
}
|
||||
work.answer(answer);
|
||||
}
|
||||
Next::Done(event) => {
|
||||
if let Some(e) = event {
|
||||
on_event(e);
|
||||
}
|
||||
break;
|
||||
}
|
||||
None if halted() => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// How hard it was to find: what a shallow search makes of it.
|
||||
if let (Some(played), Some(nodes)) = (played, t.shallow)
|
||||
&& !eval
|
||||
.shallow
|
||||
.as_ref()
|
||||
.is_some_and(|s| &s.played == played && s.nodes == nodes)
|
||||
{
|
||||
match shallow(&mut search, t, played, nodes)? {
|
||||
Some(s) => eval.shallow = Some(s),
|
||||
None if halted() => break,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
on_event(JobEvent::Eval {
|
||||
key: t.key.clone(),
|
||||
eval,
|
||||
nps,
|
||||
});
|
||||
}
|
||||
handle.quit();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What a search gave: its last full line and the best move, `None` when there is none
|
||||
/// (see [`search_once`]).
|
||||
type SearchResult = Result<Option<(uci::SearchInfo, Option<String>)>, JobFailure>;
|
||||
|
||||
/// The shallow search of `played` at `t`: the best move at `nodes` and, when it is
|
||||
/// another, the move played alone. `None` when the engine gave no answer (or ignored
|
||||
/// `searchmoves`) or the job was halted.
|
||||
fn shallow(
|
||||
search: &mut dyn FnMut(&EnginePosition, Vec<String>, u64) -> SearchResult,
|
||||
t: &Target,
|
||||
played: &str,
|
||||
nodes: u64,
|
||||
) -> Result<Option<Shallow>, JobFailure> {
|
||||
let eval_of = |info: &uci::SearchInfo| {
|
||||
info.score
|
||||
.map(|s| Eval::from_white_eval(s.to_white(t.turn).eval))
|
||||
};
|
||||
let Some((info, best)) = search(&t.pos, Vec::new(), nodes)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (Some(best), Some(best_eval)) = (best.or_else(|| info.pv.first().cloned()), eval_of(&info))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let played_eval = if best == played {
|
||||
best_eval
|
||||
} else {
|
||||
match search(&t.pos, vec![played.to_owned()], nodes)? {
|
||||
Some((info, b)) if b.as_deref().is_none_or(|b| b == played) => {
|
||||
let Some(e) = eval_of(&info) else {
|
||||
return Ok(None);
|
||||
};
|
||||
e
|
||||
}
|
||||
_ => return Ok(None),
|
||||
}
|
||||
};
|
||||
Ok(Some(Shallow {
|
||||
nodes,
|
||||
played: played.to_owned(),
|
||||
best,
|
||||
best_eval,
|
||||
played_eval,
|
||||
}))
|
||||
}
|
||||
|
||||
/// One node-limited search: its last full line and the best move. `None` when it gave
|
||||
/// no line or the job was halted.
|
||||
fn search_once(
|
||||
|
|
@ -243,7 +143,7 @@ fn search_once(
|
|||
among: Vec<String>,
|
||||
nodes: u64,
|
||||
halted: &dyn Fn() -> bool,
|
||||
) -> SearchResult {
|
||||
) -> Result<Answer, JobFailure> {
|
||||
handle
|
||||
.search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among)
|
||||
.map_err(|e| JobFailure::Engine(e.to_string()))?;
|
||||
|
|
|
|||
223
crates/game-review/src/job/work.rs
Normal file
223
crates/game-review/src/job/work.rs
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
//! What the job does for one target, as a machine without I/O: it names the next
|
||||
//! search (the full one, the second best without the move played, the shallow ones)
|
||||
//! and takes its answer; at the end it gives the target's [`JobEvent::Eval`]. Engine
|
||||
//! processes on a computer and Web Workers in a browser drive the same machine, so the
|
||||
//! evaluations — and the marks — are the same everywhere.
|
||||
|
||||
use uci::{EnginePosition, SearchInfo, Side};
|
||||
|
||||
use super::{JobEvent, Target};
|
||||
use crate::{Eval, PosEval, Second, Shallow};
|
||||
|
||||
/// A search's answer: its last full line and the best move; `None` when it gave none.
|
||||
pub(crate) type Answer = Option<(SearchInfo, Option<String>)>;
|
||||
|
||||
/// What the machine wants now.
|
||||
pub(crate) enum Next {
|
||||
/// A node-limited search of `pos` (among these moves only; empty: all), from a
|
||||
/// clear hash.
|
||||
Search {
|
||||
pos: EnginePosition,
|
||||
among: Vec<String>,
|
||||
nodes: u64,
|
||||
},
|
||||
/// The target is done: its evaluation (`None`: the engine gave nothing to use).
|
||||
Done(Option<JobEvent>),
|
||||
}
|
||||
|
||||
enum Stage {
|
||||
Full,
|
||||
Second,
|
||||
ShallowBest,
|
||||
ShallowPlayed { best: String, best_eval: Eval },
|
||||
Finish,
|
||||
}
|
||||
|
||||
pub(crate) struct Work {
|
||||
t: Target,
|
||||
nodes: u64,
|
||||
stage: Stage,
|
||||
eval: Option<PosEval>,
|
||||
nps: u64,
|
||||
/// The move played, when it is the engine's best and worth a second search.
|
||||
played: Option<String>,
|
||||
}
|
||||
|
||||
impl Work {
|
||||
pub(crate) fn new(t: Target, nodes: u64) -> Self {
|
||||
let mut w = Work {
|
||||
t,
|
||||
nodes,
|
||||
stage: Stage::Full,
|
||||
eval: None,
|
||||
nps: 0,
|
||||
played: None,
|
||||
};
|
||||
if let Some(e) = w.t.known.clone() {
|
||||
w.got_eval(e, 0);
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
fn eval_of(&self, info: &SearchInfo) -> Option<Eval> {
|
||||
info.score
|
||||
.map(|s| Eval::from_white_eval(s.to_white(self.t.turn).eval))
|
||||
}
|
||||
|
||||
/// The full evaluation is there: the second search, if it is worth one.
|
||||
fn got_eval(&mut self, eval: PosEval, nps: u64) {
|
||||
let t = &self.t;
|
||||
// The move played is the engine's best: what the best of the others gives says
|
||||
// whether it was the only good move, or a sacrifice when nothing else won.
|
||||
let mover = match t.turn {
|
||||
Side::White => chess_core::shakmaty::Color::White,
|
||||
Side::Black => chess_core::shakmaty::Color::Black,
|
||||
};
|
||||
self.played = t
|
||||
.played
|
||||
.as_ref()
|
||||
.filter(|p| {
|
||||
eval.pv.first() == Some(*p)
|
||||
&& !t.others.is_empty()
|
||||
&& crate::report::worth_second(eval.eval, mover)
|
||||
})
|
||||
.cloned();
|
||||
let second_known = eval.second.as_ref().map(|s| &s.without) == self.played.as_ref();
|
||||
self.eval = Some(eval);
|
||||
self.nps = nps;
|
||||
self.stage = if self.played.is_some() && !second_known {
|
||||
Stage::Second
|
||||
} else {
|
||||
Stage::ShallowBest
|
||||
};
|
||||
if matches!(self.stage, Stage::ShallowBest) {
|
||||
self.after_second();
|
||||
}
|
||||
}
|
||||
|
||||
/// The shallow search, when the rules want one and it is not there yet.
|
||||
fn after_second(&mut self) {
|
||||
let wanted = match (&self.played, self.t.shallow, &self.eval) {
|
||||
(Some(played), Some(nodes), Some(eval)) => !eval
|
||||
.shallow
|
||||
.as_ref()
|
||||
.is_some_and(|s| &s.played == played && s.nodes == nodes),
|
||||
_ => false,
|
||||
};
|
||||
self.stage = if wanted {
|
||||
Stage::ShallowBest
|
||||
} else {
|
||||
Stage::Finish
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn next(&self) -> Next {
|
||||
let t = &self.t;
|
||||
match &self.stage {
|
||||
Stage::Full => Next::Search {
|
||||
pos: t.pos.clone(),
|
||||
among: Vec::new(),
|
||||
nodes: self.nodes,
|
||||
},
|
||||
Stage::Second => Next::Search {
|
||||
pos: t.pos.clone(),
|
||||
among: t.others.clone(),
|
||||
nodes: self.nodes,
|
||||
},
|
||||
Stage::ShallowBest => Next::Search {
|
||||
pos: t.pos.clone(),
|
||||
among: Vec::new(),
|
||||
nodes: t.shallow.unwrap_or_default(),
|
||||
},
|
||||
Stage::ShallowPlayed { .. } => Next::Search {
|
||||
pos: t.pos.clone(),
|
||||
among: self.played.iter().cloned().collect(),
|
||||
nodes: t.shallow.unwrap_or_default(),
|
||||
},
|
||||
Stage::Finish => Next::Done(self.eval.clone().map(|eval| JobEvent::Eval {
|
||||
key: t.key.clone(),
|
||||
eval,
|
||||
nps: self.nps,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer to the search [`Self::next`] asked for.
|
||||
pub(crate) fn answer(&mut self, answer: Answer) {
|
||||
match std::mem::replace(&mut self.stage, Stage::Finish) {
|
||||
Stage::Full => {
|
||||
let Some((info, best)) = answer else { return };
|
||||
let Some(score) = info.score else { return };
|
||||
let mut pv: Vec<String> = info.pv.iter().take(12).cloned().collect();
|
||||
if let Some(b) = best
|
||||
&& pv.first() != Some(&b)
|
||||
{
|
||||
pv = vec![b];
|
||||
}
|
||||
let eval = PosEval {
|
||||
eval: Eval::from_white_eval(score.to_white(self.t.turn).eval),
|
||||
pv,
|
||||
depth: info.depth.unwrap_or(0),
|
||||
second: None,
|
||||
shallow: None,
|
||||
};
|
||||
self.got_eval(eval, info.nps.unwrap_or(0));
|
||||
}
|
||||
Stage::Second => {
|
||||
let played = self.played.clone();
|
||||
// An engine that ignores `searchmoves` answers with the move played: no
|
||||
// second move then.
|
||||
if let Some((info, best)) = answer
|
||||
&& best.as_ref() != played.as_ref()
|
||||
&& info.pv.first() != played.as_ref()
|
||||
&& let (Some(score), Some(played), Some(eval)) =
|
||||
(info.score, played, self.eval.as_mut())
|
||||
{
|
||||
eval.second = Some(Second {
|
||||
without: played,
|
||||
eval: Eval::from_white_eval(score.to_white(self.t.turn).eval),
|
||||
});
|
||||
}
|
||||
self.after_second();
|
||||
}
|
||||
Stage::ShallowBest => {
|
||||
let Some((info, best)) = answer else { return };
|
||||
let (Some(best), Some(best_eval)) = (
|
||||
best.or_else(|| info.pv.first().cloned()),
|
||||
self.eval_of(&info),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
if self.played.as_ref() == Some(&best) {
|
||||
self.shallow(best, best_eval, best_eval);
|
||||
} else {
|
||||
self.stage = Stage::ShallowPlayed { best, best_eval };
|
||||
}
|
||||
}
|
||||
Stage::ShallowPlayed { best, best_eval } => {
|
||||
if let Some((info, b)) = answer
|
||||
&& b.as_deref()
|
||||
.is_none_or(|b| Some(b) == self.played.as_deref())
|
||||
&& let Some(played_eval) = self.eval_of(&info)
|
||||
{
|
||||
self.shallow(best, best_eval, played_eval);
|
||||
}
|
||||
}
|
||||
Stage::Finish => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn shallow(&mut self, best: String, best_eval: Eval, played_eval: Eval) {
|
||||
if let (Some(eval), Some(played), Some(nodes)) =
|
||||
(self.eval.as_mut(), self.played.clone(), self.t.shallow)
|
||||
{
|
||||
eval.shallow = Some(Shallow {
|
||||
nodes,
|
||||
played,
|
||||
best,
|
||||
best_eval,
|
||||
played_eval,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
220
crates/game-review/src/job/workers.rs
Normal file
220
crates/game-review/src/job/workers.rs
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
//! The engine job in a browser: engines in Web Workers, each taking the next target,
|
||||
//! driven from the page's frames by their messages — nothing here blocks. The search
|
||||
//! of every target is the same machine as on a computer ([`super::work`]).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use uci::{
|
||||
EngineEvent, EngineHandle, ScoreBound, SearchId, SearchInfo, SearchLimits, Starting,
|
||||
WorkerConfig,
|
||||
};
|
||||
use web_time::Instant;
|
||||
|
||||
use super::work::{Next, Work};
|
||||
use super::{JobEvent, JobFailure, JobSettings, MAX_PROCESSES, SEARCH_HASH_MB, Target};
|
||||
|
||||
/// A node-limited search should never take this long; stop it if it does.
|
||||
const SEARCH_GUARD: Duration = Duration::from_secs(300);
|
||||
|
||||
/// How long an engine may take to start: a worker compiles the whole engine (≈ 100 MB
|
||||
/// of WebAssembly), several at once.
|
||||
const START_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
enum Engine {
|
||||
Starting(Starting),
|
||||
Ready(EngineHandle),
|
||||
Done,
|
||||
}
|
||||
|
||||
struct Running {
|
||||
id: SearchId,
|
||||
last: Option<SearchInfo>,
|
||||
started: Instant,
|
||||
stopping: bool,
|
||||
}
|
||||
|
||||
struct Slot {
|
||||
engine: Engine,
|
||||
work: Option<Work>,
|
||||
search: Option<Running>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
/// The job: started by [`Dispatcher::start`], driven by [`Dispatcher::poll`].
|
||||
pub struct Dispatcher {
|
||||
slots: Vec<Slot>,
|
||||
targets: std::vec::IntoIter<Target>,
|
||||
nodes: u64,
|
||||
names: HashSet<String>,
|
||||
events: Vec<JobEvent>,
|
||||
failure: Option<JobFailure>,
|
||||
halted: bool,
|
||||
}
|
||||
|
||||
impl Dispatcher {
|
||||
/// Starts `settings.processes` engines of the worker script `script`; `wake` is
|
||||
/// called whenever one of them has something new.
|
||||
pub fn start(
|
||||
script: &str,
|
||||
settings: &JobSettings,
|
||||
targets: Vec<Target>,
|
||||
wake: Arc<dyn Fn() + Send + Sync>,
|
||||
) -> Result<Dispatcher, JobFailure> {
|
||||
let workers = settings
|
||||
.processes
|
||||
.clamp(1, MAX_PROCESSES)
|
||||
.min(targets.len().max(1));
|
||||
let mut slots = Vec::with_capacity(workers);
|
||||
if !targets.is_empty() {
|
||||
for _ in 0..workers {
|
||||
let mut config = WorkerConfig::new(script);
|
||||
config.timeouts.uciok = START_TIMEOUT;
|
||||
config.timeouts.readyok = START_TIMEOUT;
|
||||
let wake = wake.clone();
|
||||
let starting = uci::Engine::start_worker(config, Box::new(move || wake()))
|
||||
.map_err(|e| JobFailure::Start(e.to_string()))?;
|
||||
slots.push(Slot {
|
||||
engine: Engine::Starting(starting),
|
||||
work: None,
|
||||
search: None,
|
||||
next_id: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Dispatcher {
|
||||
slots,
|
||||
targets: targets.into_iter(),
|
||||
nodes: settings.nodes,
|
||||
names: HashSet::new(),
|
||||
events: Vec::new(),
|
||||
failure: None,
|
||||
halted: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Stops the job: the engines are stopped, what came stays.
|
||||
pub fn cancel(&mut self) {
|
||||
self.halted = true;
|
||||
for s in &mut self.slots {
|
||||
s.engine = Engine::Done;
|
||||
}
|
||||
}
|
||||
|
||||
/// What came since the last call, and the end once the job is over (`Ok` also when
|
||||
/// cancelled). Call it every frame and when woken.
|
||||
pub fn poll(&mut self) -> (Vec<JobEvent>, Option<Result<(), JobFailure>>) {
|
||||
for i in 0..self.slots.len() {
|
||||
if let Err(e) = self.step(i) {
|
||||
self.failure.get_or_insert(e);
|
||||
self.cancel();
|
||||
}
|
||||
}
|
||||
let events = std::mem::take(&mut self.events);
|
||||
let over = self.slots.iter().all(|s| matches!(s.engine, Engine::Done));
|
||||
let end = over.then(|| match self.failure.take() {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
});
|
||||
(events, end)
|
||||
}
|
||||
|
||||
fn step(&mut self, i: usize) -> Result<(), JobFailure> {
|
||||
let slot = &mut self.slots[i];
|
||||
if let Engine::Starting(s) = &mut slot.engine {
|
||||
match s.poll() {
|
||||
None => return Ok(()),
|
||||
Some(Err(e)) => return Err(JobFailure::Start(e.to_string())),
|
||||
Some(Ok(h)) => {
|
||||
// Unknown options are not fatal: some engines lack Threads/Hash/MultiPV.
|
||||
let _ = h.set_threads(1);
|
||||
let _ = h.set_hash_mb(SEARCH_HASH_MB);
|
||||
let _ = h.set_multipv(1);
|
||||
if let Some(name) = &h.info().name
|
||||
&& self.names.insert(name.clone())
|
||||
{
|
||||
self.events.push(JobEvent::Engine(name.clone()));
|
||||
}
|
||||
slot.engine = Engine::Ready(h);
|
||||
}
|
||||
}
|
||||
}
|
||||
let Engine::Ready(h) = &slot.engine else {
|
||||
return Ok(());
|
||||
};
|
||||
// The answer of the running search, once it is there.
|
||||
let mut answer = None;
|
||||
for ev in h.drain_events() {
|
||||
let Some(run) = slot.search.as_mut() else {
|
||||
continue;
|
||||
};
|
||||
match ev {
|
||||
EngineEvent::Info { search_id, info } if search_id == run.id => {
|
||||
if info.multipv_index() == 1 && info.score.is_some() {
|
||||
let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact);
|
||||
if exact || run.last.is_none() {
|
||||
run.last = Some(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
EngineEvent::BestMove {
|
||||
search_id, best, ..
|
||||
} if search_id == run.id => {
|
||||
let last = run.last.take();
|
||||
answer = Some(last.map(|info| (info, best)));
|
||||
slot.search = None;
|
||||
}
|
||||
EngineEvent::Terminated(reason) => return Err(JobFailure::Terminated(reason)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(run) = slot.search.as_mut() {
|
||||
if !run.stopping && run.started.elapsed() > SEARCH_GUARD {
|
||||
let _ = h.stop();
|
||||
run.stopping = true;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let (Some(answer), Some(work)) = (answer, slot.work.as_mut()) {
|
||||
work.answer(answer);
|
||||
}
|
||||
// The next search: of this target, or of the next one.
|
||||
loop {
|
||||
if slot.work.is_none() {
|
||||
match self.targets.next().filter(|_| !self.halted) {
|
||||
Some(t) => slot.work = Some(Work::new(t, self.nodes)),
|
||||
None => {
|
||||
slot.engine = Engine::Done;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(work) = slot.work.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
match work.next() {
|
||||
Next::Search { pos, among, nodes } => {
|
||||
slot.next_id += 1;
|
||||
let id = SearchId(slot.next_id);
|
||||
// Every search starts from a clear hash, so that it depends on its
|
||||
// position alone.
|
||||
let _ = h.new_game();
|
||||
h.search_among(pos, id, SearchLimits::Nodes(nodes), among)
|
||||
.map_err(|e| JobFailure::Engine(e.to_string()))?;
|
||||
slot.search = Some(Running {
|
||||
id,
|
||||
last: None,
|
||||
started: Instant::now(),
|
||||
stopping: false,
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
Next::Done(event) => {
|
||||
self.events.extend(event);
|
||||
slot.work = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -8,7 +8,7 @@
|
|||
//! are used without an engine.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
|
||||
use chess_core::shakmaty::san::SanPlus;
|
||||
use chess_core::shakmaty::uci::UciMove;
|
||||
|
|
@ -22,6 +22,8 @@ mod job;
|
|||
pub mod report;
|
||||
|
||||
pub use features::{MoveFeatures, Rules};
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub use job::Dispatcher;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub use job::run;
|
||||
pub use job::{
|
||||
|
|
@ -157,11 +159,37 @@ pub struct GameAnalysis {
|
|||
shallow_nodes: u64,
|
||||
}
|
||||
|
||||
/// Where cached analyses are kept, one file per main line by name: a folder (`Path`),
|
||||
/// or whatever else a program keeps files in (the web version's browser storage).
|
||||
pub trait CacheStore {
|
||||
fn read(&self, name: &str) -> Option<Vec<u8>>;
|
||||
fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()>;
|
||||
}
|
||||
|
||||
/// The cache in a folder of the disk.
|
||||
pub struct CacheDir<'a>(pub &'a Path);
|
||||
|
||||
impl CacheStore for CacheDir<'_> {
|
||||
fn read(&self, name: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(self.0.join(name)).ok()
|
||||
}
|
||||
|
||||
fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()> {
|
||||
write_atomic(&self.0.join(name), bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl GameAnalysis {
|
||||
/// The analysis of `game`: from the cache in `cache_dir` (the folder of the cached
|
||||
/// analyses) when this main line was analysed before, else from `[%eval]` comments
|
||||
/// when every move has one, else empty.
|
||||
pub fn new(game: &Game, cache_dir: Option<&Path>) -> Self {
|
||||
let dir = cache_dir.map(CacheDir);
|
||||
Self::with_store(game, dir.as_ref().map(|d| d as &dyn CacheStore))
|
||||
}
|
||||
|
||||
/// [`Self::new`] with the cache in `store`.
|
||||
pub fn with_store(game: &Game, store: Option<&dyn CacheStore>) -> Self {
|
||||
let mut a = GameAnalysis {
|
||||
evals: HashMap::new(),
|
||||
meta: None,
|
||||
|
|
@ -181,7 +209,7 @@ impl GameAnalysis {
|
|||
shallow_nodes: SHALLOW_NODES,
|
||||
};
|
||||
a.rebuild(game);
|
||||
if cache_dir.is_some_and(|d| a.load_cache(d)) || a.load_pgn_evals(game) {
|
||||
if store.is_some_and(|s| a.load_cache(s)) || a.load_pgn_evals(game) {
|
||||
a.rebuild(game);
|
||||
}
|
||||
a
|
||||
|
|
@ -556,8 +584,8 @@ impl GameAnalysis {
|
|||
|
||||
// ----- cache -----------------------------------------------------------------
|
||||
|
||||
/// The cache file of this main line in `dir`.
|
||||
fn cache_path(&self, dir: &Path) -> PathBuf {
|
||||
/// The name of the cache file of this main line.
|
||||
fn cache_name(&self) -> String {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for k in &self.keys {
|
||||
for b in k.bytes().chain(std::iter::once(b'\n')) {
|
||||
|
|
@ -565,11 +593,16 @@ impl GameAnalysis {
|
|||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
dir.join(format!("{h:016x}.json"))
|
||||
format!("{h:016x}.json")
|
||||
}
|
||||
|
||||
/// Keeps engine results in `dir` (nothing for evaluations read from the PGN).
|
||||
pub fn save_cache(&self, dir: &Path) -> std::io::Result<()> {
|
||||
self.save_to(&CacheDir(dir))
|
||||
}
|
||||
|
||||
/// Keeps engine results in `store` (nothing for evaluations read from the PGN).
|
||||
pub fn save_to(&self, store: &dyn CacheStore) -> std::io::Result<()> {
|
||||
let Some(meta) = self.meta.clone().filter(|m| m.nodes > 0) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
|
@ -588,11 +621,11 @@ impl GameAnalysis {
|
|||
.collect(),
|
||||
};
|
||||
let bytes = serde_json::to_vec(&file).map_err(std::io::Error::other)?;
|
||||
write_atomic(&self.cache_path(dir), &bytes)
|
||||
store.write(&self.cache_name(), &bytes)
|
||||
}
|
||||
|
||||
fn load_cache(&mut self, dir: &Path) -> bool {
|
||||
let Ok(bytes) = std::fs::read(self.cache_path(dir)) else {
|
||||
fn load_cache(&mut self, store: &dyn CacheStore) -> bool {
|
||||
let Some(bytes) = store.read(&self.cache_name()) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(file) = serde_json::from_slice::<CacheFile>(&bytes) else {
|
||||
|
|
@ -837,7 +870,7 @@ mod tests {
|
|||
let targets = a.begin(&g, false);
|
||||
fake_results(&mut a, targets);
|
||||
a.refresh(&g);
|
||||
let path = a.cache_path(&dir);
|
||||
let path = dir.join(a.cache_name());
|
||||
a.save_cache(&dir).expect("saved");
|
||||
// The file as 1.x wrote it: no `search` in the meta, 3M nodes.
|
||||
let mut json: serde_json::Value =
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue