diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f70481..0e1b88a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] +- Position search in a large ChessBase database without a usable `.cbb` search index: the + program builds its own once (in the background, kept in the cache) and deep positions are + then found in milliseconds instead of a pass over every game. Searches for the start + position and other early positions got about twice as fast. - Settings → About: clicking the email address copies it instead of opening a mail app, which does nothing useful when none is installed. diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 14d1476..1e7dfb5 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -1549,6 +1549,22 @@ const ROWS: &[[&str; 6]] = &[ "+ Añadir motor…", "+ Aggiungi motore…", ], + [ + "Preparing fast position search… {p} %", + "Подготовка быстрого поиска по позиции… {p} %", + "Préparation de la recherche rapide par position… {p} %", + "Schnelle Stellungssuche wird vorbereitet… {p} %", + "Preparando la búsqueda rápida por posición… {p} %", + "Preparazione della ricerca rapida per posizione… {p} %", + ], + [ + "The base has no usable search index (.cbb); one is built once and kept in the cache.", + "У базы нет пригодного индекса поиска (.cbb); он строится один раз и хранится в кэше.", + "La base n'a pas d'index de recherche utilisable (.cbb) ; il est construit une fois et conservé dans le cache.", + "Die Datenbank hat keinen brauchbaren Suchindex (.cbb); er wird einmal erstellt und im Cache behalten.", + "La base no tiene un índice de búsqueda utilizable (.cbb); se construye una vez y se guarda en la caché.", + "La base non ha un indice di ricerca utilizzabile (.cbb); viene costruito una volta e tenuto nella cache.", + ], [ "Checking engine…", "Проверка движка…", diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 7c086de..c425380 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -236,6 +236,10 @@ pub struct LargeView { in_order: Option<(usize, usize)>, cache: OutcomeCache, job: Option, + /// Building our own search booster (a base without a usable `.cbb`), once the + /// board is used; `booster_failed` keeps a failure from being retried. + booster: Option>, + booster_failed: bool, board: SearchBoard, only_order: bool, /// Next move of the game under the pointer in the table (an arrow on the board). @@ -304,6 +308,8 @@ impl LargeView { in_order: None, cache: HashMap::new(), job: None, + booster: None, + booster_failed: false, board, only_order: false, table_hover: None, @@ -445,11 +451,42 @@ impl LargeView { highlighted: None, }); } - if self.job.is_some() || self.suggest_job.is_some() { + self.update_booster(db, now, ctx); + if self.job.is_some() || self.suggest_job.is_some() || self.booster.is_some() { ctx.request_repaint_after(std::time::Duration::from_millis(50)); } } + /// Builds our own booster in the background when the board is in use and the + /// base has no usable `.cbb`; searches meanwhile run without it. + fn update_booster(&mut self, db: &Arc, now: f64, ctx: &egui::Context) { + if let Some(b) = &self.booster + && let Some(result) = b.poll() + { + self.booster = None; + self.booster_failed = result != Some(true); + } + let wanted = self.pane == Pane::Board || self.board.is_set(); + if !wanted + || self.booster.is_some() + || self.booster_failed + || !db.as_chessbase().is_some_and(|b| b.booster_wanted()) + { + return; + } + let db = db.clone(); + self.booster = Background::spawn(ctx, now, move |progress, cancel| { + match db.as_chessbase()?.build_booster(progress, cancel) { + Ok(true) => Some(true), + Ok(false) => None, + Err(e) => { + eprintln!("search booster: {e}"); + Some(false) + } + } + }); + } + fn start(&mut self, db: &Arc, request: Request, now: f64, ctx: &egui::Context) { // Dropping the old job cancels it. self.job = None; @@ -552,6 +589,22 @@ impl LargeView { .job .as_ref() .map(|j| (j.work.progress() as f32 / total.max(1) as f32).min(1.0)); + if let Some(b) = &self.booster { + let p = (b.progress() as f32 / total.max(1) as f32).min(1.0); + ui.horizontal(|ui| { + ui.add(egui::Spinner::new().size(14.0)); + ui.label( + RichText::new(trf( + "Preparing fast position search… {p} %", + &[("p", &format!("{:.0}", p * 100.0))], + )) + .weak(), + ) + .on_hover_text(tr( + "The base has no usable search index (.cbb); one is built once and kept in the cache.", + )); + }); + } let outcome = self.board_outcome().cloned(); let mut events = Vec::new(); self.board.keys(ui.ctx(), outcome.as_ref(), &mut events); diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 2c5b264..6e0c950 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -324,6 +324,13 @@ impl Library { notes: o.notes, }, ); + // Position searches without a usable `.cbb` get our own + // booster, kept in the cache directory. + if let Database::ChessBase(b) = &o.db + && let Some(dir) = Settings::cache_dir() + { + b.set_booster_dir(&dir.join("boosters")); + } Slot::Ready(Arc::new(o.db)) } Err(e) => Slot::Failed(import_error(&e)), diff --git a/crates/chess-import/src/chessbase/base.rs b/crates/chess-import/src/chessbase/base.rs index 09d078f..ca7a7fc 100644 --- a/crates/chess-import/src/chessbase/base.rs +++ b/crates/chess-import/src/chessbase/base.rs @@ -50,6 +50,10 @@ pub struct Base { file_records: usize, /// The `.cbb` search booster, when present and consistent (checked on first use). cbb: OnceLock>, + /// Where our own booster is kept when `.cbb` cannot be used (set by the + /// application), and that booster once found or built. + booster_dir: OnceLock, + own_booster: OnceLock, cba: Option>, /// Titles of guiding texts read so far (they are stored with the text). text_titles: Mutex>, @@ -432,6 +436,8 @@ impl Base { cbg: Mutex::new(cbg), file_records, cbb: OnceLock::new(), + booster_dir: OnceLock::new(), + own_booster: OnceLock::new(), cba: cba.map(Mutex::new), text_titles: Mutex::new(HashMap::new()), notes: Vec::new(), @@ -548,25 +554,88 @@ impl Base { be(self.record(index), 1, 4).unwrap_or(0) } - /// The `.cbb` search booster if it can be trusted: its record count is that of - /// the `.cbh` file plus one, it holds that many 52-byte records and it is not - /// older than `.cbg` (a program that does not maintain it may have changed the - /// games since). + /// The search booster to use: `.cbb` if it can be trusted (its record count is + /// that of the `.cbh` file plus one, it holds that many 52-byte records and it is + /// not older than `.cbg`: a program that does not maintain it may have changed the + /// games since), else our own one (see [`Base::build_booster`]). pub(super) fn cbb_path(&self) -> Option<&Path> { self.cbb .get_or_init(|| { let path = find_companion(&self.path, "cbb")?; - let mut f = File::open(&path).ok()?; - let mut head = [0u8; 4]; - f.read_exact(&mut head).ok()?; - let count = u32::from_be_bytes(head) as u64; - let meta = f.metadata().ok()?; let cbg_time = std::fs::metadata(&self.cbg_path).ok()?.modified().ok()?; - let fresh = meta.modified().ok()? >= cbg_time; - (count == self.file_records as u64 + 1 && meta.len() >= 52 * count && fresh) - .then_some(path) + let fresh = std::fs::metadata(&path).ok()?.modified().ok()? >= cbg_time; + (fresh && booster_consistent(&path, self.file_records)).then_some(path) }) .as_deref() + .or_else(|| self.own_booster.get().map(PathBuf::as_path)) + } + + /// Records in the `.cbh` file, trailing empty ones included. + pub(super) fn file_records(&self) -> usize { + self.file_records + } + + /// Tells where our own booster lives (a cache directory), and takes the one + /// built earlier for this database if it is there. + pub fn set_booster_dir(&self, dir: &Path) { + let _ = self.booster_dir.set(dir.to_owned()); + if let Some(p) = self.own_booster_path() + && booster_consistent(&p, self.file_records) + { + let _ = self.own_booster.set(p); + } + } + + /// Our booster's file: named after the database and the size and date of its + /// games, so a changed database gets a new one. + fn own_booster_path(&self) -> Option { + let dir = self.booster_dir.get()?; + let path = std::fs::canonicalize(&self.path).unwrap_or_else(|_| self.path.clone()); + let meta = std::fs::metadata(&self.cbg_path).ok()?; + let modified = meta + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_nanos()); + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in path + .to_string_lossy() + .bytes() + .chain(meta.len().to_le_bytes()) + .chain(modified.to_le_bytes()) + .chain((self.file_records as u64).to_le_bytes()) + { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + Some(dir.join(format!("{h:016x}.cbb"))) + } + + /// Position searches have a booster (ChessBase's or ours). + pub fn booster_ready(&self) -> bool { + self.cbb_path().is_some() + } + + /// A booster of our own would help and can be built ([`Base::set_booster_dir`]). + pub fn booster_wanted(&self) -> bool { + !self.booster_ready() && self.booster_dir.get().is_some() + } + + /// Builds our own booster (one pass over all the games; `progress` counts the + /// records done) and uses it from then on. `Ok(false)` when cancelled. + pub fn build_booster( + &self, + progress: &AtomicUsize, + cancel: &AtomicBool, + ) -> std::io::Result { + let Some(path) = self.own_booster_path() else { + return Err(std::io::Error::other("no booster directory")); + }; + if !super::booster::build(self, &path, progress, cancel)? { + return Ok(false); + } + let _ = self.own_booster.set(path); + Ok(true) } /// Number of records (games, texts and deleted records); a record's index is its @@ -1017,6 +1086,19 @@ fn name_table(names: &Names, f: &NameFilter) -> Option> { (!words(&f.text).is_empty()).then(|| names.matching(&f.text)) } +/// A booster file holds a record per `.cbh` record (plus its header) and says so. +fn booster_consistent(path: &Path, file_records: usize) -> bool { + let Ok(mut f) = File::open(path) else { + return false; + }; + let mut head = [0u8; 4]; + if f.read_exact(&mut head).is_err() { + return false; + } + let count = u32::from_be_bytes(head) as u64; + count == file_records as u64 + 1 && f.metadata().is_ok_and(|m| m.len() >= 52 * count) +} + /// ECO code number 0 (A00) … 499 (E99) of a `.cbh` ECO field. fn eco_number(eco: u16) -> Option { if eco == 0 || eco >= 64576 { diff --git a/crates/chess-import/src/chessbase/booster.rs b/crates/chess-import/src/chessbase/booster.rs new file mode 100644 index 0000000..7453178 --- /dev/null +++ b/crates/chess-import/src/chessbase/booster.rs @@ -0,0 +1,205 @@ +//! Our own search booster for a large ChessBase database whose `.cbb` is missing or +//! stale: the same 52-byte record per game (what was ever on the board in the main +//! line, see `Signature` in `search.rs`), computed from `.cbg` once and kept in the +//! user's cache directory under a name derived from the database (path, size and +//! date of `.cbg`), so a changed database gets a new file. The format is that of +//! `.cbb`, header included, so the search reads both the same way; our record matched +//! ChessBase's byte for byte on Mega (`docs/research/position-index.md`, section 1.1). + +use std::fs::File; +use std::io; +use std::path::Path; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use shakmaty::{Board, Chess, Color, Position, Role}; + +use super::base::{Base, RecordKind}; +use super::be; +use super::moves::{self, Step, WalkError}; +use super::search::{BLOCK, CBB_RECORD, read_games}; + +/// Marks in `r` what stands on `b`: the layout of a `.cbb` record. +fn mark(b: &Board, r: &mut [u8; CBB_RECORD]) { + for (sq, piece) in b.clone() { + let file = 1u8 << (sq.file() as u32); + let rank = sq.rank() as usize; + let white = piece.color == Color::White; + match piece.role { + Role::Pawn if white && (2..=6).contains(&rank) => r[0x06 + rank - 2] |= file, + Role::Pawn if !white && (1..=5).contains(&rank) => r[0x0b + rank - 1] |= file, + Role::Pawn => {} + Role::King => { + let (rk, f) = if white { (0x10, 0x12) } else { (0x11, 0x13) }; + r[rk] |= 1 << rank; + r[f] |= file; + } + Role::Rook | Role::Queen => r[if white { 0x14 } else { 0x1c } + rank] |= file, + Role::Knight | Role::Bishop => r[if white { 0x24 } else { 0x2c } + rank] |= file, + } + } + for (c, shift) in [(Color::White, 0), (Color::Black, 4)] { + let count = |role: Role| (b.by_color(c) & b.by_role(role)).count(); + let (q, rook, bishop, knight) = ( + count(Role::Queen), + count(Role::Rook), + count(Role::Bishop), + count(Role::Knight), + ); + // "Was without" (byte 5) and "had at most one" (byte 4); for the queen + // ChessBase sets the bit of byte 4 together with that of byte 5. + if q == 0 { + r[0x05] |= 1 << shift; + r[0x04] |= 1 << shift; + } + for (flag, n) in [(2u8, rook), (4, bishop), (8, knight)] { + if n == 0 { + r[0x05] |= flag << shift; + } + if n <= 1 { + r[0x04] |= flag << shift; + } + } + if q + rook + bishop + knight == 0 { + r[0x03] |= 8 << shift; + } + } +} + +fn walk(cbg: &[u8], offset: u32, fast: bool) -> Result<[u8; CBB_RECORD], WalkError> { + let mut r = [0u8; CBB_RECORD]; + let mut end_pawns = 0u8; + moves::main_line(cbg, offset, fast, |pos: &Chess, step| { + let b = pos.board(); + mark(b, &mut r); + if matches!(step, Step::End) { + let pawns = |c: Color| (b.by_color(c) & b.pawns()).count().min(7) as u8; + end_pawns = pawns(Color::White) | (pawns(Color::Black) << 4); + } + true + })?; + r[0x03] |= end_pawns; + Ok(r) +} + +/// The booster record of the game at `offset` in `cbg`: the fast walk, and the +/// checked one when the fast one stumbles. `None` when the game cannot be read (a +/// position search cannot find it either). +pub(super) fn record_of(cbg: &[u8], offset: u32) -> Option<[u8; CBB_RECORD]> { + match walk(cbg, offset, true) { + Ok(r) => Some(r), + Err(WalkError::Moves(_)) => walk(cbg, offset, false).ok(), + Err(WalkError::Unsupported(_)) => None, + } +} + +fn write_all_at(f: &File, buf: &[u8], at: u64) -> io::Result<()> { + #[cfg(unix)] + { + std::os::unix::fs::FileExt::write_all_at(f, buf, at) + } + #[cfg(windows)] + { + let (mut buf, mut at) = (buf, at); + while !buf.is_empty() { + match std::os::windows::fs::FileExt::seek_write(f, buf, at)? { + 0 => return Err(io::ErrorKind::WriteZero.into()), + n => { + buf = &buf[n..]; + at += n as u64; + } + } + } + Ok(()) + } +} + +/// Writes the booster of `base` to `out` (a `.part` file next to it first, renamed +/// when complete): one pass over the main lines, in parallel. `progress` counts the +/// records done. `Ok(false)` when cancelled; then nothing is left behind. +pub(super) fn build( + base: &Base, + out: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> io::Result { + if let Some(dir) = out.parent() { + std::fs::create_dir_all(dir)?; + } + let part = out.with_extension("part"); + let count = base.file_records() + 1; + File::create(&part)?.set_len((count * CBB_RECORD) as u64)?; + let total = base.records(); + let next = AtomicUsize::new(0); + let threads = std::thread::available_parallelism() + .map_or(4, |n| n.get()) + .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 = File::options().write(true).open(&part)?; + 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]; + 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); + 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| { + if let Some(r) = record_of(data, rel) { + let at = (index as usize - from) * CBB_RECORD; + bytes[at..at + CBB_RECORD].copy_from_slice(&r); + } + }); + write_all_at(&file, bytes, ((from + 1) * CBB_RECORD) as u64)?; + 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); + } + } + }); + } + }); + if let Some(e) = failure.into_inner().unwrap_or(None) { + let _ = std::fs::remove_file(&part); + return Err(e); + } + if cancel.load(Ordering::Relaxed) { + let _ = std::fs::remove_file(&part); + return Ok(false); + } + // The header last: a file without the count is never taken for a booster. + let mut header = [0u8; CBB_RECORD]; + header[..4].copy_from_slice(&(count as u32).to_be_bytes()); + let file = File::options().write(true).open(&part)?; + write_all_at(&file, &header, 0)?; + file.sync_all()?; + drop(file); + std::fs::rename(&part, out)?; + Ok(true) +} diff --git a/crates/chess-import/src/chessbase/mod.rs b/crates/chess-import/src/chessbase/mod.rs index 966c809..ae8e65a 100644 --- a/crates/chess-import/src/chessbase/mod.rs +++ b/crates/chess-import/src/chessbase/mod.rs @@ -6,6 +6,7 @@ mod annotations; pub mod base; +mod booster; mod entities; mod headers; mod moves; diff --git a/crates/chess-import/src/chessbase/search.rs b/crates/chess-import/src/chessbase/search.rs index 2583e9f..2473463 100644 --- a/crates/chess-import/src/chessbase/search.rs +++ b/crates/chess-import/src/chessbase/search.rs @@ -5,6 +5,7 @@ //! Research and measurements: `docs/research/position-index.md`. use std::fs::File; +use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use shakmaty::uci::UciMove; @@ -18,7 +19,7 @@ use crate::position::{ }; /// Candidates handed to a thread at a time; cancellation is checked between blocks. -const BLOCK: usize = 2048; +pub(super) const BLOCK: usize = 2048; /// Games whose moves lie closer than this are read with one `pread`. const GAP: u32 = 64 << 10; /// Longest span of `.cbg` read at once. @@ -26,7 +27,10 @@ const SPAN: u32 = 4 << 20; /// Read past the last record start of a span (most records are shorter). const TAIL: u32 = 4096; /// Size of a `.cbb` record (the file starts with a header of the same size). -const CBB_RECORD: usize = 52; +pub(super) const CBB_RECORD: usize = 52; +/// Booster records sampled before a search; when most of them admit the target the +/// booster is left out (it would read its whole file to rule out almost nothing). +const SAMPLE: usize = 4096; /// Games among `candidates` (record indices in ascending order; `None`: all records) /// whose main line reaches the position. `scanned` counts the candidates looked at. @@ -40,7 +44,9 @@ pub fn search( ) -> Option { let total = candidates.map_or(base.records(), <[u32]>::len); let target = Target::new(query); - let cbb = base.cbb_path(); + let cbb = base + .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()) @@ -304,41 +310,21 @@ impl Worker<'_> { } } self.booster(); - let mut start = 0; - while start < self.games.len() { - // A run of games whose moves lie close together, in file order. - let lo = self.games[start].1; - let mut end = start + 1; - while let Some(&(_, off)) = self.games.get(end) { - let prev = self.games[end - 1].1; - if off < prev || off - prev > GAP || off - lo > SPAN { - break; - } - end += 1; + let Worker { + base, + target, + cbg, + games, + span, + single, + out, + .. + } = self; + read_games(cbg, games, span, single, |index, data, rel| { + if let Some(h) = find(target, data, rel) { + add(base, out, index, h); } - let hi = self.games[end - 1].1; - let len = (hi - lo) as usize + TAIL as usize; - read_span(&self.cbg, u64::from(lo), &mut self.span, len); - for k in start..end { - let (index, off) = self.games[k]; - let rel = off - lo; - let size = be(&self.span, rel as usize + 1, 3).unwrap_or(u32::MAX) as usize; - let hit = if rel as usize + size <= self.span.len() { - find(self.target, &self.span, rel) - } else { - // A record running past the span: read it alone. - let size = read_record(&self.cbg, off, &mut self.single); - if size == 0 { - continue; - } - find(self.target, &self.single, 0) - }; - if let Some(h) = hit { - self.add(index, h); - } - } - start = end; - } + }); } /// Drops the games of the block that the `.cbb` booster rules out. @@ -366,34 +352,95 @@ impl Worker<'_> { .retain(|&(i, _)| read_exact_at(cbb, &mut rec, at(i)).is_err() || sig.admits(&rec)); } } +} - fn add(&mut self, index: u32, hit: Hit) { - let r = self.base.record(index as usize); - let u = |at, n| be(r, at, n).unwrap_or(0); - let result = match r.get(0x1b) { - Some(2 | 6) => GameResult::WhiteWins, - Some(1 | 5) => GameResult::Draw, - Some(0 | 4) => GameResult::BlackWins, - _ => GameResult::Unknown, - }; - let year = ((u(0x18, 3) >> 9) & 0xfff) as u16; - self.out.add( - Match { - index, - ply: hit.ply, - same_order: hit.same_order, - in_variation: false, - next: None, - }, - hit.next, - result, - u(0x1f, 2) as u16, - u(0x21, 2) as u16, - year, - ); +/// Records the game `index` that reached the target as `hit`. +fn add(base: &Base, out: &mut Collector, index: u32, hit: Hit) { + let r = base.record(index as usize); + let u = |at, n| be(r, at, n).unwrap_or(0); + let result = match r.get(0x1b) { + Some(2 | 6) => GameResult::WhiteWins, + Some(1 | 5) => GameResult::Draw, + Some(0 | 4) => GameResult::BlackWins, + _ => GameResult::Unknown, + }; + let year = ((u(0x18, 3) >> 9) & 0xfff) as u16; + out.add( + Match { + index, + ply: hit.ply, + same_order: hit.same_order, + in_variation: false, + next: None, + }, + hit.next, + result, + u(0x1f, 2) as u16, + u(0x21, 2) as u16, + year, + ); +} + +/// Calls `f(index, data, offset)` with the moves of every game of `games` (record +/// index and `.cbg` offset, in file order within a run): games whose records lie +/// close together are read with one `pread` into `span`, a record running past the +/// span is read alone into `single`. +pub(super) fn read_games( + cbg: &File, + games: &[(u32, u32)], + span: &mut Vec, + single: &mut Vec, + mut f: impl FnMut(u32, &[u8], u32), +) { + let mut start = 0; + while start < games.len() { + // A run of games whose moves lie close together, in file order. + let lo = games[start].1; + let mut end = start + 1; + while let Some(&(_, off)) = games.get(end) { + let prev = games[end - 1].1; + if off < prev || off - prev > GAP || off - lo > SPAN { + break; + } + end += 1; + } + let hi = games[end - 1].1; + let len = (hi - lo) as usize + TAIL as usize; + read_span(cbg, u64::from(lo), span, len); + for &(index, off) in &games[start..end] { + let rel = off - lo; + let size = be(span, rel as usize + 1, 3).unwrap_or(u32::MAX) as usize; + if rel as usize + size <= span.len() { + f(index, span, rel); + } else { + // A record running past the span: read it alone. + if read_record(cbg, off, single) == 0 { + continue; + } + f(index, single, 0); + } + } + start = end; } } +/// Whether the booster at `path` rules out a worthwhile share of games for `sig`, +/// judged on its first records: early positions (the start, 1.e4) pass nearly every +/// game, and reading the file for them only costs time. +fn booster_helps(path: &Path, sig: &Signature) -> bool { + let Ok(f) = File::open(path) else { + return false; + }; + let mut buf = Vec::new(); + read_span(&f, CBB_RECORD as u64, &mut buf, SAMPLE * CBB_RECORD); + let records = buf.as_chunks::().0; + if records.is_empty() { + return false; + } + let admitted = records.iter().filter(|r| sig.admits(*r)).count(); + admitted * 2 < records.len() +} + /// The fast walk, and the checked one when the fast one stumbles (damaged moves). /// A game that neither can read is not found. fn find(target: &Target, cbg: &[u8], offset: u32) -> Option { @@ -802,6 +849,178 @@ mod tests { .unwrap_or_default() } + #[test] + fn own_booster_when_cbb_is_missing() { + let Some(sample) = Sample::unpack("Anand 01-14.cbv") else { + return; + }; + let base = sample.open(); + assert!(base.cbb_path().is_none() && !base.booster_wanted()); + let lines: Vec<_> = (0..base.records()).map(|i| oracle_line(&base, i)).collect(); + let targets = targets(&lines); + let without: Vec<_> = targets + .iter() + .map(|t| summary(&run(&base, None, &PositionQuery::new(t.clone(), None)))) + .collect(); + + let dir = sample.dir.join("cache"); + base.set_booster_dir(&dir); + assert!(base.booster_wanted() && !base.booster_ready()); + // Cancelled: nothing is left behind. + let cancelled = AtomicBool::new(true); + assert!( + !base + .build_booster(&AtomicUsize::new(0), &cancelled) + .expect("builds") + ); + assert!(std::fs::read_dir(&dir).map_or(true, |d| d.count() == 0)); + let progress = AtomicUsize::new(0); + assert!( + base.build_booster(&progress, &AtomicBool::new(false)) + .expect("builds") + ); + assert_eq!(progress.load(Ordering::Relaxed), base.records()); + let path = base.cbb_path().expect("our booster").to_owned(); + assert!(path.starts_with(&dir) && !base.booster_wanted()); + let cbb = std::fs::read(&path).expect("file"); + assert_eq!(cbb.len(), (base.records() + 1) * CBB_RECORD); + assert_eq!(be(&cbb, 0, 4), Some(base.records() as u32 + 1)); + // Our record holds everything the search may require of a game's record. + for (i, line) in lines.iter().enumerate() { + let rec = &cbb[(i + 1) * CBB_RECORD..(i + 2) * CBB_RECORD]; + match line { + Some(l) => { + let want = own_cbb(l); + assert!( + rec.iter().zip(want).all(|(r, w)| r & w == w), + "game {}", + i + 1 + ); + assert_eq!(rec[3] & 0x77, want[3] & 0x77, "game {}", i + 1); + } + None => assert!(rec.iter().all(|b| *b == 0), "record {}", i + 1), + } + } + for (t, want) in targets.iter().zip(&without) { + let got = summary(&run(&base, None, &PositionQuery::new(t.clone(), None))); + assert_eq!(&got, want); + } + // Opened again, the booster is found and not built anew. + let again = sample.open(); + again.set_booster_dir(&dir); + assert_eq!(again.cbb_path(), Some(path.as_path())); + // A `.cbb` that can be trusted comes first. + let cbb_path = sample.cbh.with_extension("cbb"); + std::fs::write(&cbb_path, &cbb).expect("write"); + let with_cbb = sample.open(); + with_cbb.set_booster_dir(&dir); + assert_eq!(with_cbb.cbb_path(), Some(cbb_path.as_path())); + } + + /// Mega Database 2026 (not in the repository): our booster record equals + /// ChessBase's byte for byte. Run with + /// `cargo test --release -p chess-import mega_own_booster -- --ignored --nocapture`. + #[test] + #[ignore] + fn mega_own_booster() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample/Mega2026/Mega Database 2026.cbh"); + if !path.exists() { + eprintln!("skipped: no Mega"); + return; + } + let base = Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens"); + let cbb = File::open(base.cbb_path().expect(".cbb")).expect("open"); + let cbg = File::open(base.cbg_path()).expect("open"); + let (mut buf, mut rec) = (Vec::new(), [0u8; CBB_RECORD]); + let (mut checked, mut differ, mut unreadable, mut chess960) = (0, 0, 0, 0); + for i in (0..base.records()).step_by(97) { + read_exact_at(&cbb, &mut rec, ((i + 1) * CBB_RECORD) as u64).expect("read"); + if base.kind(i) == RecordKind::Game + && be(base.record(i), 0x23, 2).is_some_and(|eco| eco >= 64576) + { + // Chess960: no search reads these games, their record does not matter. + chess960 += 1; + continue; + } + let ours = if base.kind(i) == RecordKind::Game + && read_record(&cbg, base.moves_offset(i), &mut buf) > 0 + { + match super::super::booster::record_of(&buf, 0) { + Some(r) => r, + None => { + // A game our decoder does not read: no search finds it, and + // its record does not matter. + let why = moves::main_line(&buf, 0, false, |_, _| true) + .err() + .map(|e| e.reason().to_owned()); + unreadable += 1; + if unreadable <= 5 { + eprintln!("game {}: unreadable ({why:?})", i + 1); + } + continue; + } + } + } else { + [0; CBB_RECORD] + }; + checked += 1; + if ours != rec { + differ += 1; + if differ <= 5 { + eprintln!("game {}: ours {ours:02x?}\n cbb {rec:02x?}", i + 1); + } + } + } + eprintln!( + "{checked} records checked, {differ} differ; skipped: {unreadable} unreadable, {chess960} Chess960" + ); + assert_eq!(differ, 0); + } + + /// Mega Database 2026 (not in the repository): builds our booster for the whole + /// base into a temporary directory and times it, then searches with it. Run with + /// `cargo test --release -p chess-import mega_build_booster -- --ignored --nocapture`. + #[test] + #[ignore] + fn mega_build_booster() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample/Mega2026/Mega Database 2026.cbh"); + if !path.exists() { + eprintln!("skipped: no Mega"); + return; + } + let base = Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens"); + base.without_booster(); + let dir = std::env::temp_dir().join(format!("chess-import-booster-{}", std::process::id())); + base.set_booster_dir(&dir); + assert!(base.booster_wanted()); + let t = std::time::Instant::now(); + let progress = AtomicUsize::new(0); + assert!( + base.build_booster(&progress, &AtomicBool::new(false)) + .expect("builds") + ); + let built = t.elapsed(); + let own = base.cbb_path().expect("ours").to_owned(); + let size = std::fs::metadata(&own).expect("file").len(); + eprintln!( + "built in {built:.2?}: {} ({size} bytes), peak memory {}", + own.display(), + peak_memory() + ); + let (pos, line) = san_line("e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6"); + let t = std::time::Instant::now(); + let out = run(&base, None, &PositionQuery::new(pos, Some(line))); + eprintln!( + "Najdorf with our booster: {} games in {:.1?}", + out.matches.len(), + t.elapsed() + ); + assert_eq!(out.matches.len(), 291_273); + let _ = std::fs::remove_dir_all(&dir); + } + /// Mega Database 2026 (not in the repository): the counts of the research /// (`docs/research/position-index.md`, section 3) and timings. Run with /// `cargo test --release -p chess-import mega_position_search -- --ignored --nocapture`. diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 3c9a1e5..9d6120f 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -8,7 +8,7 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i | --- | --- | | `app.rs` | Состояние верхнего уровня: библиотека ⇄ партия, настройки, движок, фоновые диалоги (rfd в отдельных потоках), подтверждение закрытия изменённой партии | | `library.rs` | Полка баз, фоновое открытие через `chess_import::open` (PGN, ChessBase, архивы; прогресс, отмена), формат и «Замечания импорта» по каждой базе, таблица с поиском, сортировкой, клавиатурой | -| `large_db.rs` | Большая база ChessBase: панель фильтров справа (игроки с подсказками, турнир, годы, Эло, результат, ECO, ходы, аннотации), фоновые проходы с отменой и задержкой 250 мс для текста, счётчик и прогресс, таблица из записей `.cbh`; компоновка — `docs/design/large-databases.md`; переключатель `[Фильтры | Доска]`, строка условий (чипы), колонка «Ход», «только этот порядок», «сильнейшие сверху» | +| `large_db.rs` | Большая база ChessBase: панель фильтров справа (игроки с подсказками, турнир, годы, Эло, результат, ECO, ходы, аннотации), фоновые проходы с отменой и задержкой 250 мс для текста, счётчик и прогресс, таблица из записей `.cbh`; компоновка — `docs/design/large-databases.md`; переключатель `[Фильтры | Доска]`, строка условий (чипы), колонка «Ход», «только этот порядок», «сильнейшие сверху»; без пригодного `.cbb` при открытой доске в фоне строится свой ускоритель поиска (`Base::build_booster`, каталог кэша `boosters/`) со строкой прогресса над доской | | `board_search.rs` | Доска поиска по позиции (решение 13, `docs/design/board-search.md`): ввод ходов, линия с переходами по ходам, продолжения со статистикой (полоса Б/Н/Ч, средний Эло, год; для книг — «N глав»), клавиши ←/→/Home/End/Backspace/1–9/F/Ctrl+Backspace, «Вернуть» после сброса, фоновые задачи `Background` с отменой | | `game_view.rs` | Экран партии: доска, шкала оценки, панель анализа, предпросмотр PV, нотация, панель инструментов, клавиатура | | `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках | diff --git a/docs/dev/import.md b/docs/dev/import.md index dd90805..b9c162d 100644 --- a/docs/dev/import.md +++ b/docs/dev/import.md @@ -57,6 +57,10 @@ **`.cbb`** — ускоритель ChessBase, 52 байта на партию: что когда-либо стояло на доске в основной линии (поля пешек на горизонталях 3–7 / 2–6, горизонтали и вертикали королей, поля ладей+ферзей и коней+слонов по цветам, признаки «был без ферзя/ладьи/слона/коня», «не больше одной ладьи/слона/коня», «только пешки и король», число пешек в конце). Для цели строится маска требуемых битов (`Signature`): партия проходит, только если все биты есть и пешек в конце не больше, чем в цели. Описание формата — Morphy (только факты); наш расчёт записи совпал с файлом Mega побайтно на 120 999 партиях (исследование, §1.1). Файл используется, если счётчик в заголовке = записей в `.cbh` + 1, размер ≥ 52 · счётчик и `.cbb` не старше `.cbg` (иначе его могла обойти программа, не обновляющая ускоритель); проверка один раз, лениво (`Base::cbb_path`, `OnceLock`). Файл в память не читается: плотный блок кандидатов — одно `pread` его диапазона (≤ 2048 · 52 байт), разреженная выборка — по записи. Так поиск не держит 613 МБ Mega; по замерам разница с чтением в память не видна (весь фильтр — десятки миллисекунд при тёплом кэше). +**Свой ускоритель** (`chessbase/booster.rs`, 2026-10-19). Если `.cbb` нет или он не проходит проверку, запись того же формата считается самим приложением: один параллельный проход по основным линиям (тот же быстрый декодер и то же чтение `.cbg` спанами, `search::read_games`), результат — файл в формате `.cbb` (заголовок со счётчиком, записи по 52 байта; тексты, Chess960 и нечитаемые партии — нули) в каталоге кэша приложения `boosters/.cbb`, где hash — FNV-1a от канонического пути `.cbh`, размера и даты `.cbg` и числа записей, так что изменённая база получает новый файл. Пишется в `.part`, заголовок — последним, затем переименование; отмена или ошибка не оставляют файла. API `Base`: `set_booster_dir(dir)` (приложение задаёт каталог после открытия; готовый файл подхватывается сразу), `booster_ready()`, `booster_wanted()`, `build_booster(progress, cancel)`; `cbb_path()` отдаёт `.cbb`, если он пригоден, иначе свой. В приложении (`large_db.rs`) сборка запускается в фоне, когда открыта доска поиска, со строкой «Подготовка быстрого поиска по позиции… N %»; поиски до готовности идут без ускорителя. Mega без `.cbb`: сборка 11,9 с (24 потока), 610 МБ, пик памяти процесса 0,7 ГБ; наша запись совпадает с `.cbb` ChessBase побайтно на 121 016 из 121 016 проверенных партий (тест `mega_own_booster`; 47 партий Chess960 пропущены — их не читает ни поиск, ни ускоритель). Поиск Найдорфа с нашим файлом — 76 мс, как с `.cbb`. + +**Ускоритель не всегда полезен.** Для ранних позиций (начальная, после 1.e4) запись почти каждой партии содержит требуемые биты, а чтение 613 МБ файла стоит времени: начальная позиция искалась 965 мс с `.cbb` против 412 мс без него. Поэтому перед поиском проверяются первые 4096 записей ускорителя (`search::booster_helps`): если он пропускает больше половины, в этом поиске он не используется. Начальная позиция теперь 391 мс с `.cbb` и без. + В `Base` для поиска добавлены: `cbg_path()`, `moves_offset(index)`, `cbb_path()` (pub(super)), число записей в файле `.cbh` с хвостовыми пустыми (для проверки `.cbb`). Там же `SortKey::AverageElo` (среднее Эло при обоих известных, при равенстве — дата) и `Base::sort_records(records, sort, ascending)` — сортировка, которой пользуется и `query`, и сортировка результатов поиска. **Замеры** (Mega, i7-13700KF, 24 потока, тёплый кэш, `--release`; тест `mega_position_search`, `cargo test --release -p chess-import mega_position_search -- --ignored --nocapture`):