ChessPenguin 0.6.3
Some checks failed
CI / macos-build (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / check (push) Waiting to run
Release / version (push) Has been cancelled
Release / linux (push) Has been cancelled
Release / flatpak (push) Has been cancelled
Release / windows (push) Has been cancelled
Release / macos (push) Has been cancelled
Release / publish (push) Has been cancelled

Opening index: games from a set-up position are left to the pass; exact preparation
progress; quiet import notes; clearer preparation text; randomized Mega test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-19 19:48:14 +03:00
parent 4b92fa32de
commit e11e09aa18
13 changed files with 305 additions and 67 deletions

View file

@ -2,8 +2,10 @@
All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [0.6.3] — 2026-10-19
- Import notes (for example, Chess960 games shown without moves) are a quiet grey "ℹ" now
instead of an orange warning sign.
- 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.

8
Cargo.lock generated
View file

@ -661,7 +661,7 @@ dependencies = [
[[package]]
name = "chess-core"
version = "0.6.2"
version = "0.6.3"
dependencies = [
"encoding_rs",
"pgn-reader",
@ -671,7 +671,7 @@ dependencies = [
[[package]]
name = "chess-import"
version = "0.6.2"
version = "0.6.3"
dependencies = [
"chess-core",
"encoding_rs",
@ -684,7 +684,7 @@ dependencies = [
[[package]]
name = "chesspenguin"
version = "0.6.2"
version = "0.6.3"
dependencies = [
"arboard",
"chess-core",
@ -4284,7 +4284,7 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "uci"
version = "0.6.2"
version = "0.6.3"
dependencies = [
"thiserror 2.0.21",
]

View file

@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/chess-core", "crates/chess-import", "crates/uci", "apps/desktop"]
[workspace.package]
version = "0.6.2"
version = "0.6.3"
edition = "2024"
rust-version = "1.97"
license = "GPL-3.0-or-later"

View file

@ -1550,20 +1550,20 @@ const ROWS: &[[&str; 6]] = &[
"+ 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} %",
"Speeding up search in this database (once)… {p} %",
"Ускоряю поиск по этой базе (один раз)… {p} %",
"Accélération de la recherche dans cette base (une seule fois)… {p} %",
"Suche in dieser Datenbank wird beschleunigt (einmalig)… {p} %",
"Acelerando la búsqueda en esta base (una sola vez)… {p} %",
"Velocizzo la ricerca in questa base (una volta sola)… {p} %",
],
[
"The search index of the base is built once and kept in the cache.",
"Индекс поиска по базе строится один раз и хранится в кэше.",
"L'index de recherche de la base est construit une fois et conservé dans le cache.",
"Der Suchindex der Datenbank wird einmal erstellt und im Cache behalten.",
"El índice de búsqueda de la base se construye una vez y se guarda en la caché.",
"L'indice di ricerca della base viene costruito una volta e tenuto nella cache.",
"An index for fast position search is built once and kept in the cache. Searching works meanwhile, only slower.",
"Строится индекс для быстрого поиска по позиции. Это делается один раз, результат хранится в кэше. Пока идёт подготовка, поиск работает, но медленнее.",
"Un index pour la recherche rapide par position est construit une fois et conservé dans le cache. La recherche fonctionne en attendant, mais plus lentement.",
"Ein Index für die schnelle Stellungssuche wird einmal erstellt und im Cache behalten. Die Suche funktioniert währenddessen, nur langsamer.",
"Se construye una vez un índice para la búsqueda rápida por posición y se guarda en la caché. Mientras tanto la búsqueda funciona, aunque más despacio.",
"Un indice per la ricerca rapida per posizione viene costruito una volta e tenuto nella cache. Nel frattempo la ricerca funziona, solo più lentamente.",
],
[
"Position search needs about {n} MB of free memory for this database.",

View file

@ -239,7 +239,8 @@ pub struct LargeView {
/// Building the search index of the base (our booster when `.cbb` cannot be used,
/// the opening positions), once the board is used; `booster_failed` keeps a
/// failure from being retried.
booster: Option<Background<bool>>,
/// The job and the work it has to do (in its progress units).
booster: Option<(Background<bool>, usize)>,
booster_failed: bool,
board: SearchBoard,
only_order: bool,
@ -461,7 +462,7 @@ impl LargeView {
/// Builds the search index in the background when the board is in use and the
/// base lacks something (`Base::prepare`); searches meanwhile run without it.
fn update_booster(&mut self, db: &Arc<Database>, now: f64, ctx: &egui::Context) {
if let Some(b) = &self.booster
if let Some((b, _)) = &self.booster
&& let Some(result) = b.poll()
{
self.booster = None;
@ -475,8 +476,9 @@ impl LargeView {
{
return;
}
let work = db.as_chessbase().map_or(0, |b| b.prepare_work());
let db = db.clone();
self.booster = Background::spawn(ctx, now, move |progress, cancel| {
let job = Background::spawn(ctx, now, move |progress, cancel| {
match db.as_chessbase()?.prepare(progress, cancel) {
Ok(true) => Some(true),
Ok(false) => None,
@ -486,6 +488,7 @@ impl LargeView {
}
}
});
self.booster = job.map(|j| (j, work));
}
fn start(&mut self, db: &Arc<Database>, request: Request, now: f64, ctx: &egui::Context) {
@ -590,20 +593,19 @@ 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 {
// The pass over the records, then the sort of the index.
let p = (b.progress() as f32 / (2 * total).max(1) as f32).min(1.0);
if let Some((b, work)) = &self.booster {
let p = (b.progress() as f32 / (*work).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} %",
"Speeding up search in this database (once)… {p} %",
&[("p", &format!("{:.0}", p * 100.0))],
))
.weak(),
)
.on_hover_text(tr(
"The search index of the base is built once and kept in the cache.",
"An index for fast position search is built once and kept in the cache. Searching works meanwhile, only slower.",
));
});
}
@ -1330,12 +1332,7 @@ impl LargeView {
ui.add(egui::Spinner::new().size(14.0));
ui.label(RichText::new(format!("{:.0} %", p * 100.0)).weak());
}
if notes > 0
&& ui
.button(RichText::new(format!("⚠ {notes}")).color(ui.visuals().warn_fg_color))
.on_hover_text(tr("Import notes"))
.clicked()
{
if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() {
open_notes = true;
}
});

View file

@ -517,7 +517,7 @@ impl Library {
ui.add_space(4.0);
egui::ScrollArea::vertical().max_height(420.0).show(ui, |ui| {
for n in &info.notes {
ui.label(RichText::new(format!("⚠ {n}")).color(ui.visuals().warn_fg_color));
ui.label(format!("• {n}"));
}
});
});
@ -838,14 +838,7 @@ impl Library {
}
}
let notes = self.info.get(&path).map_or(0, |i| i.notes.len());
if notes > 0
&& ui
.button(
RichText::new(format!("⚠ {notes}")).color(ui.visuals().warn_fg_color),
)
.on_hover_text(tr("Import notes"))
.clicked()
{
if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() {
self.notes_open = Some(path.clone());
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {

View file

@ -26,3 +26,9 @@ fn x_button(ui: &mut Ui, size: egui::Vec2, d: f32) -> egui::Response {
.line_segment([c + vec2(-d, d), c + vec2(d, -d)], stroke);
resp
}
/// The quiet "ℹ n" of import notes: minor remarks, so no colour and no frame.
pub fn notes_button(ui: &mut egui::Ui, notes: usize) -> egui::Response {
ui.add(egui::Button::new(egui::RichText::new(format!("ℹ {notes}")).weak().small()).frame(false))
.on_hover_text(crate::i18n::tr("Import notes"))
}

View file

@ -657,6 +657,21 @@ impl Base {
)
}
/// The work [`Base::prepare`] has to do, in the units of its `progress`: the
/// records of the pass, and as many again for sorting the opening index.
pub fn prepare_work(&self) -> usize {
let pass = self.booster_wanted() || self.openings_to_build();
let sort = self.openings_to_build();
self.records * (usize::from(pass) + usize::from(sort))
}
fn openings_to_build(&self) -> bool {
matches!(
self.openings_status(),
OpeningsStatus::Missing { room: true }
)
}
/// Builds what is missing for fast position searches — our booster when `.cbb`
/// cannot be used, the opening index when the machine has room for it — in one
/// pass over the games (`progress` counts the records done, and again while the

View file

@ -75,6 +75,8 @@ pub(super) struct GameData {
pub record: [u8; CBB_RECORD],
/// The opening entries, when asked for; `None` for a game from a set-up position.
pub opening: Option<GameEntry>,
/// The game starts from a set-up position (with `opening` asked for).
pub set_up: bool,
}
fn walk(cbg: &[u8], offset: u32, fast: bool, opening: Option<u32>) -> Result<GameData, WalkError> {
@ -96,9 +98,11 @@ fn walk(cbg: &[u8], offset: u32, fast: bool, opening: Option<u32>) -> Result<Gam
true
})?;
r[0x03] |= end_pawns;
let set_up = entry.as_ref().is_some_and(|e| !e.standard);
Ok(GameData {
record: r,
opening: entry.filter(|e| e.standard),
set_up,
})
}
@ -185,6 +189,7 @@ pub(super) fn build(
let (mut span, mut single) = (Vec::new(), Vec::new());
let mut block = vec![0u8; BLOCK * CBB_RECORD];
let mut entries: Vec<GameEntry> = Vec::new();
let mut set_up: Vec<u32> = Vec::new();
loop {
if cancel.load(Ordering::Relaxed) {
return Ok(());
@ -197,6 +202,7 @@ pub(super) fn build(
let bytes = &mut block[..(to - from) * CBB_RECORD];
bytes.fill(0);
entries.clear();
set_up.clear();
games.clear();
for i in from..to {
// Texts and Chess960 games (ECO field ≥ 64576) have no
@ -213,13 +219,16 @@ pub(super) fn build(
let at = (index as usize - from) * CBB_RECORD;
bytes[at..at + CBB_RECORD].copy_from_slice(&d.record);
entries.extend(d.opening);
if d.set_up {
set_up.push(index);
}
}
});
if let Some(f) = &file {
write_all_at(f, bytes, ((from + 1) * CBB_RECORD) as u64)?;
}
if let Some(sink) = &sink {
sink.add(&entries)?;
sink.add(&entries, &set_up)?;
}
progress.fetch_add(to - from, Ordering::Relaxed);
}

View file

@ -15,9 +15,10 @@
//! no entries (a search finds them in the pass, as before; the index answers only for
//! positions reached by at most `PLIES` moves from the usual start).
//!
//! File. `<hash>.cpo` in the cache directory (same hash as the booster): a 40-byte
//! File. `<hash>.cpo` in the cache directory (same hash as the booster): a 48-byte
//! header (magic, plies, records, section lengths), the prefixes, the keys, the
//! games; all little-endian. It is read whole into memory ([`Index::load`]), so its
//! games, the games from a set-up position (u32 each, ascending: a search walks
//! them as before); all little-endian. It is read whole into memory ([`Index::load`]), so its
//! size is what it costs to keep.
use std::fs::File;
@ -30,7 +31,7 @@ use shakmaty::uci::UciMove;
use shakmaty::{Chess, Role, Square};
use super::base::Base;
use crate::position::{self, Collector, GameResult, Match, PositionOutcome, PositionQuery, uci};
use crate::position::{self, Collector, GameResult, Match, PositionQuery, uci};
/// Half-moves of each game in the index.
pub const PLIES: usize = 10;
@ -44,7 +45,9 @@ pub const BYTES_PER_GAME: u64 = 60;
const END: u16 = u16::MAX;
/// Prefix code: a null move.
const NULL: u16 = u16::MAX - 1;
const MAGIC: &[u8; 8] = b"CPOPEN01";
const MAGIC: &[u8; 8] = b"CPOPEN02";
/// Header: magic, plies, records, then the lengths of the four sections.
const HEADER: usize = 48;
/// Temporary files the entries are spread over by the top bits of the key, so that
/// no more than a fraction of them is sorted in memory at a time.
const BUCKETS: usize = 64;
@ -123,6 +126,8 @@ impl GameEntry {
pub(super) struct Sink {
buckets: Vec<Mutex<BufWriter<File>>>,
prefix: Mutex<Vec<u16>>,
/// Games from a set-up position (the index has no entries for them).
set_up: Mutex<Vec<u32>>,
dir: std::path::PathBuf,
}
@ -137,12 +142,19 @@ impl Sink {
Ok(Sink {
buckets,
prefix: Mutex::new(vec![END; records * PREFIX]),
set_up: Mutex::new(Vec::new()),
dir: dir.to_owned(),
})
}
/// Adds the entries of a block of games; `entries` hold distinct games.
pub(super) fn add(&self, entries: &[GameEntry]) -> io::Result<()> {
/// Adds the entries of a block of games (`entries` hold distinct games) and the
/// games of the block that start from a set-up position.
pub(super) fn add(&self, entries: &[GameEntry], set_up: &[u32]) -> io::Result<()> {
if !set_up.is_empty()
&& let Ok(mut s) = self.set_up.lock()
{
s.extend_from_slice(set_up);
}
if let Ok(mut p) = self.prefix.lock() {
for e in entries {
let at = e.index as usize * PREFIX;
@ -222,7 +234,7 @@ impl Sink {
file.write_all(MAGIC)?;
file.write_all(&(PLIES as u32).to_le_bytes())?;
file.write_all(&(records as u32).to_le_bytes())?;
file.write_all(&[0u8; 24])?;
file.write_all(&[0u8; HEADER - 16])?;
// The prefix section: records × PREFIX × u16.
let prefix = self.prefix.lock().map_err(|_| io::Error::other("lock"))?;
let mut bytes = Vec::with_capacity(prefix.len() * 2);
@ -293,7 +305,11 @@ impl Sink {
games.write_all(&list)?;
games_len += list.len() as u64;
}
progress.fetch_add(records / BUCKETS, Ordering::Relaxed);
// In all exactly `records` over the buckets.
progress.fetch_add(
records * (b + 1) / BUCKETS - records * b / BUCKETS,
Ordering::Relaxed,
);
}
let keys_len = keys.len() as u64;
file.write_all(&keys)?;
@ -306,6 +322,14 @@ impl Sink {
}
drop(games);
let _ = std::fs::remove_file(&games_path);
// The games from a set-up position, ascending.
let mut set_up =
std::mem::take(&mut *self.set_up.lock().map_err(|_| io::Error::other("lock"))?);
set_up.sort_unstable();
for g in &set_up {
file.write_all(&g.to_le_bytes())?;
}
let set_up_len = set_up.len() as u64 * 4;
let mut file = file.into_inner().map_err(|e| e.into_error())?;
{
use std::io::Seek;
@ -313,6 +337,7 @@ impl Sink {
file.write_all(&prefix_len.to_le_bytes())?;
file.write_all(&keys_len.to_le_bytes())?;
file.write_all(&games_len.to_le_bytes())?;
file.write_all(&set_up_len.to_le_bytes())?;
}
file.sync_all()?;
drop(file);
@ -356,6 +381,7 @@ pub struct Index {
prefix: std::ops::Range<usize>,
keys: std::ops::Range<usize>,
games: std::ops::Range<usize>,
set_up: std::ops::Range<usize>,
}
impl Index {
@ -367,7 +393,7 @@ impl Index {
/// Reads the whole file; `None` when it is not an index for `records` records.
pub fn load(path: &Path, records: usize) -> Option<Index> {
let bytes = std::fs::read(path).ok()?;
let head = bytes.get(..40)?;
let head = bytes.get(..HEADER)?;
if &head[..8] != MAGIC {
return None;
}
@ -382,11 +408,12 @@ impl Index {
if u32_at(8) != Some(PLIES as u64) || u32_at(12) != Some(records as u64) {
return None;
}
let (p, k, g) = (u64_at(16)?, u64_at(24)?, u64_at(32)?);
let prefix = 40..40 + p;
let (p, k, g, u) = (u64_at(16)?, u64_at(24)?, u64_at(32)?, u64_at(40)?);
let prefix = HEADER..HEADER + p;
let keys = prefix.end..prefix.end + k;
let games = keys.end..keys.end + g;
if games.end != bytes.len() || p != records * PREFIX * 2 || k % KEY != 0 {
let set_up = games.end..games.end + u;
if set_up.end != bytes.len() || p != records * PREFIX * 2 || k % KEY != 0 || u % 4 != 0 {
return None;
}
Some(Index {
@ -395,6 +422,7 @@ impl Index {
prefix,
keys,
games,
set_up,
})
}
@ -524,12 +552,12 @@ impl Index {
/// The games (among `candidates`, ascending; `None`: all) that reach the position,
/// with what they played next, as the pass would find them.
pub fn search(
pub fn collect(
&self,
base: &Base,
candidates: Option<&[u32]>,
query: &PositionQuery,
) -> PositionOutcome {
) -> Collector {
let line: Vec<u16> = query
.line
.as_deref()
@ -570,6 +598,28 @@ impl Index {
for part in parts {
out.merge(part);
}
out.finish(&query.position)
out
}
/// The games from a set-up position (not in the index) among `candidates`.
pub fn set_up_games(&self, candidates: Option<&[u32]>) -> Vec<u32> {
let all = self
.set_up
.clone()
.step_by(4)
.map(|at| u32::from_le_bytes(self.bytes[at..at + 4].try_into().expect("4 bytes")));
match candidates {
None => all.collect(),
Some(c) => {
let mut i = 0;
all.filter(|&g| {
while i < c.len() && c[i] < g {
i += 1;
}
i < c.len() && c[i] == g
})
.collect()
}
}
}
}

View file

@ -42,16 +42,36 @@ pub fn search(
scanned: &AtomicUsize,
cancel: &AtomicBool,
) -> Option<PositionOutcome> {
let total = candidates.map_or(base.records(), <[u32]>::len);
// A position of the opening: the index knows its games.
// A position of the opening: the index knows its games, except those from a
// set-up position, which the pass looks at.
if let Some(index) = base.openings()
&& index.answers(query, candidates)
{
let others = index.set_up_games(candidates);
let mut out = collect(base, Some(&others), query, scanned, cancel)?;
if cancel.load(Ordering::Relaxed) {
return None;
}
scanned.fetch_add(total, Ordering::Relaxed);
return Some(index.search(base, candidates, query));
out.merge(index.collect(base, candidates, query));
let total = candidates.map_or(base.records(), <[u32]>::len);
scanned.fetch_add(total.saturating_sub(others.len()), Ordering::Relaxed);
return Some(out.finish(&query.position));
}
collect(base, candidates, query, scanned, cancel).map(|c| c.finish(&query.position))
}
/// The pass of [`search`]: the matches in record order and the statistics, not yet
/// finished. `None` when cancelled.
fn collect(
base: &Base,
candidates: Option<&[u32]>,
query: &PositionQuery,
scanned: &AtomicUsize,
cancel: &AtomicBool,
) -> Option<Collector> {
let total = candidates.map_or(base.records(), <[u32]>::len);
if total == 0 {
return Some(Collector::default());
}
let target = Target::new(query);
let cbb = base
@ -129,7 +149,7 @@ pub fn search(
all.merge(c);
}
all.matches = matches;
Some(all.finish(&query.position))
Some(all)
}
/// The searched position, prepared for cheap checks.
@ -1070,6 +1090,147 @@ mod tests {
assert!(again.openings().is_some());
}
#[test]
fn opening_index_leaves_set_up_games_to_the_pass() {
let Some(sample) = Sample::unpack("Endgame Manual.cbv") else {
return;
};
let base = sample.open();
base.set_booster_dir(&sample.dir.join("cache"));
assert!(base.prepare_work() > 0);
let progress = AtomicUsize::new(0);
assert!(
base.prepare(&progress, &AtomicBool::new(false))
.expect("prepares")
);
let Some(index) = base.openings() else {
eprintln!("skipped: no memory for the index");
return;
};
let lines: Vec<_> = (0..base.records()).map(|i| oracle_line(&base, i)).collect();
let set_up: Vec<u32> = lines
.iter()
.enumerate()
.filter(|(_, l)| {
l.as_ref()
.and_then(|l| l.first())
.is_some_and(|(p, _)| !same_position(p, &Chess::default()))
})
.map(|(i, _)| i as u32)
.collect();
assert!(!set_up.is_empty());
assert_eq!(index.set_up_games(None), set_up);
let some: Vec<u32> = set_up.iter().copied().step_by(2).collect();
assert_eq!(index.set_up_games(Some(&some)), some);
// A position of the opening, also reached by a set-up game: what the pass finds.
let plain = sample.open();
let (pos, _) = &lines[set_up[0] as usize].as_ref().expect("readable")[0];
for query in [
PositionQuery::new(pos.clone(), Some(Vec::new())),
PositionQuery::new(Chess::default(), Some(Vec::new())),
] {
let (fast, slow) = (run(&base, None, &query), run(&plain, None, &query));
assert_eq!(full(&fast), full(&slow));
}
// The set-up start itself is found (by the pass, through the index's list).
let query = PositionQuery::new(pos.clone(), Some(Vec::new()));
assert!(
run(&base, None, &query)
.matches
.iter()
.any(|m| m.index == set_up[0])
);
}
/// Mega Database 2026 (not in the repository): the opening index against the pass
/// on positions of the opening taken from games all over the base. The index may
/// only miss games that reach the position later than its plies (by a detour),
/// and finds nothing the pass does not; the rest of every match is the same. Run
/// with `cargo test --release -p chess-import mega_openings_random -- --ignored --nocapture`.
#[test]
#[ignore]
fn mega_openings_random() {
use super::super::openings::PLIES;
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 dir = std::env::temp_dir().join(format!("chess-import-random-{}", std::process::id()));
base.set_booster_dir(&dir);
assert!(
base.prepare(&AtomicUsize::new(0), &AtomicBool::new(false))
.expect("prepares")
);
assert!(base.openings().is_some(), "no memory for the index");
let plain = Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens");
let cbg = File::open(base.cbg_path()).expect("cbg");
let mut buf = Vec::new();
let (mut queries, mut detours, mut games_seen) = (0, 0, 0usize);
let mut i = 7usize;
while queries < 120 {
i = (i * 7_919 + 104_729) % base.records();
if base.kind(i) != RecordKind::Game
|| read_record(&cbg, base.moves_offset(i), &mut buf) == 0
{
continue;
}
let mut line: Vec<(Chess, Option<Move>)> = Vec::new();
let walked = moves::main_line(&buf, 0, false, |pos, step| {
line.push((
pos.clone(),
match step {
Step::Move(m) => Some(*m),
_ => None,
},
));
line.len() <= PLIES
});
if walked.is_err()
|| line
.first()
.is_none_or(|(p, _)| !same_position(p, &Chess::default()))
{
continue;
}
let ply = (queries * 3) % (PLIES + 1);
if ply >= line.len() || line[..ply].iter().any(|(_, m)| m.is_none()) {
continue;
}
let moves: Vec<Move> = line[..ply].iter().filter_map(|(_, m)| *m).collect();
let query = PositionQuery::new(line[ply].0.clone(), Some(moves));
let fast = run(&base, None, &query);
let slow = run(&plain, None, &query);
let mut j = 0;
for m in &slow.matches {
if fast.matches.get(j) == Some(m) {
j += 1;
} else {
assert!(
m.ply as usize > PLIES,
"game {} at ply {} missing from the index (query ply {ply})",
m.index + 1,
m.ply
);
detours += 1;
}
}
assert_eq!(
j,
fast.matches.len(),
"the index found games the pass did not"
);
games_seen += slow.matches.len();
queries += 1;
}
eprintln!(
"{queries} positions, {games_seen} matches of the pass, {detours} reached only by a detour after ply {PLIES}"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Mega Database 2026 (not in the repository): the opening index against the
/// pass, with timings. Run with
/// `cargo test --release -p chess-import mega_openings -- --ignored --nocapture`.

View file

@ -57,7 +57,7 @@
**`.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/<hash>.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`.
**Свой ускоритель** (`chessbase/booster.rs`, 2026-10-19). Если `.cbb` нет или он не проходит проверку, запись того же формата считается самим приложением: один параллельный проход по основным линиям (тот же быстрый декодер и то же чтение `.cbg` спанами, `search::read_games`), результат — файл в формате `.cbb` (заголовок со счётчиком, записи по 52 байта; тексты, Chess960 и нечитаемые партии — нули) в каталоге кэша приложения `boosters/<hash>.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` и без.
@ -101,15 +101,15 @@
## Дебютный индекс (большие базы)
`chessbase/openings.rs`, 2026-10-19. Для ранних позиций ускоритель бессилен (через 1.e4 проходит половина базы), а проход читает заголовок каждой из 11,7 млн записей: 0,4 с на 24 потоках и 2,2 с на 4. Индекс хранит позиции первых `PLIES` = 10 полуходов каждой партии из обычной начальной позиции: на партию — её первые 11 ходов кодом u16 (`prefix`, `END` после конца линии, `NULL` для null move), и по записи на каждую пару (позиция, партия) для полуходов 0…10: отсортированные ключи Zobrist (`keys`: ключ, смещение, число партий) и списки партий по ключу (`games`: номер записи varint-дельтой и полуход). Партия, проходящая позицию дважды в дебюте, записана на первом полуходе. Партии с заданной позиции и нечитаемые записей не имеют.
`chessbase/openings.rs`, 2026-10-19. Для ранних позиций ускоритель бессилен (через 1.e4 проходит половина базы), а проход читает заголовок каждой из 11,7 млн записей: 0,4 с на 24 потоках и 2,2 с на 4. Индекс хранит позиции первых `PLIES` = 10 полуходов каждой партии из обычной начальной позиции: на партию — её первые 11 ходов кодом u16 (`prefix`, `END` после конца линии, `NULL` для null move), и по записи на каждую пару (позиция, партия) для полуходов 0…10: отсортированные ключи Zobrist (`keys`: ключ, смещение, число партий) и списки партий по ключу (`games`: номер записи varint-дельтой и полуход). Партия, проходящая позицию дважды в дебюте, записана на первом полуходе. Нечитаемые партии записей не имеют (их не находит и проход). Партии с заданной позиции (FEN) в индекс не входят, но их номера хранятся отдельной секцией: запрос, на который отвечает индекс, проверяет их обычным проходом и сливает результат (`Index::set_up_games`, `search::collect`); в Mega их 2 398.
Строится тем же проходом, что и ускоритель (`booster::build` с приёмником `openings::Sink`): записи раскладываются по 64 временным файлам по старшим битам ключа в каталоге `<hash>.build/`, затем каждый файл сортируется в памяти и кодируется; префиксы в памяти (22 байта на партию), списки партий — во временный файл, который дописывается после ключей. Файл `<hash>.cpo` (тот же hash, что у ускорителя): заголовок 40 байт (`CPOPEN01`, число полуходов, число записей, длины секций), префиксы, ключи, списки. Читается целиком в память (`Index::load`), так что занимает ровно размер файла. Mega: 1 286 225 позиций, 600 МБ (≈51 байт на партию; оценка заранее — `BYTES_PER_GAME` = 60), построение вместе с ускорителем 16,8 с (24 потока), пик памяти процесса 1,44 ГБ при базе 0,7 ГБ.
Строится тем же проходом, что и ускоритель (`booster::build` с приёмником `openings::Sink`): записи раскладываются по 64 временным файлам по старшим битам ключа в каталоге `<hash>.build/`, затем каждый файл сортируется в памяти и кодируется; префиксы в памяти (22 байта на партию), списки партий — во временный файл, который дописывается после ключей. Файл `<hash>.cpo` (тот же hash, что у ускорителя): заголовок 48 байт (`CPOPEN02`, число полуходов, число записей, длины четырёх секций), префиксы, ключи, списки, партии с заданной позиции (u32 по возрастанию). Файл другого формата не загружается и удаляется, индекс строится заново. Читается целиком в память (`Index::load`), так что занимает ровно размер файла. Mega: 1 286 225 позиций, 600 МБ (≈51 байт на партию; оценка заранее — `BYTES_PER_GAME` = 60), построение вместе с ускорителем 16,8 с (24 потока), пик памяти процесса 1,44 ГБ при базе 0,7 ГБ.
**Память.** `Base::openings_status()`: `Loaded` / `OnDisk { room }` / `Missing { room }` / `NoCache`; `room` — `memory::available()` (крейт `sysinfo`, MIT) не меньше размера плюс 1 ГиБ. `Base::prepare(progress, cancel)` строит ускоритель, если `.cbb` непригоден, и индекс, если его нет и память позволяет, одним проходом, затем загружает индекс, если есть место; `prepare_wanted()` говорит, есть ли что делать. Приложение запускает `prepare` в фоне при открытой доске («Подготовка быстрого поиска по позиции… N %», прогресс — записи прохода, затем ещё столько же на сортировку). Если памяти нет, поиск идёт проходом, как раньше; индекс на диске не загружается, пока место не появится. Дев-хук `CP_MEMORY_LIMIT=<МБ>` ограничивает «доступную память» для проверки этих путей.
**Память.** `Base::openings_status()`: `Loaded` / `OnDisk { room }` / `Missing { room }` / `NoCache`; `room` — `memory::available()` (крейт `sysinfo`, MIT) не меньше размера плюс 1 ГиБ. `Base::prepare(progress, cancel)` строит ускоритель, если `.cbb` непригоден, и индекс, если его нет и память позволяет, одним проходом, затем загружает индекс, если есть место; `prepare_wanted()` говорит, есть ли что делать. Приложение запускает `prepare` в фоне при открытой доске («Ускоряю поиск по этой базе (один раз)… N %»; объём работы заранее — `Base::prepare_work()`: записи прохода и, если строится индекс, ещё столько же на сортировку). Прерванная подготовка (закрыли базу или программу) удаляет свои временные файлы. Если памяти нет, поиск идёт проходом, как раньше; индекс на диске не загружается, пока место не появится. Дев-хук `CP_MEMORY_LIMIT=<МБ>` ограничивает «доступную память» для проверки этих путей.
**Запрос** (`Index::search`): позиция должна быть достигнута из обычной начальной позиции не более чем за 10 ходов (`Index::answers`; иначе — проход), список партий пересекается с кандидатами слиянием, затем партии считаются параллельно (ход после позиции — из префикса, `same_order` — сравнением префикса с линией запроса, результат/Эло/год — из записи `.cbh`), части сливаются в порядке записей. Если кандидатов мало против партий позиции (меньше 1/32), выгоднее проход по ним с ускорителем — так фильтр «Карлсен» остаётся на 4 мс.
**Отличие от прохода.** Индекс не видит партии, которые приходят в дебютную позицию позже 10-го полухода обходным путём (1.Кf3 … Кg1 … и т. п.): на Mega это 23 партии из 5 873 563 для 1.e4, 2 из 564 718 для 1.d4 Кf6 2.c4 e6, 9 из 291 273 для Найдорфа; в остальном списки, порядок ходов и продолжения совпадают с проходом (тест `mega_openings`; на «Anand 01-14» совпадение полное, тест `opening_index_matches_the_pass`).
**Отличие от прохода.** Индекс не видит партии, которые приходят в дебютную позицию позже 10-го полухода обходным путём (1.Кf3 … Кg1 … и т. п.): на Mega это 16 партий из 5 873 563 для 1.e4, 2 из 564 718 для 1.d4 Кf6 2.c4 e6, 9 из 291 273 для Найдорфа. Тест `mega_openings_random` проверяет это свойство на 120 дебютных позициях из партий по всей базе (205 млн совпадений прохода): индекс не находит ничего лишнего, каждое пропущенное совпадение достигнуто позже 10-го полухода (279 таких, 0,00014 %), остальное — номер, полуход, порядок ходов, следующий ход — совпадает. На «Anand 01-14» и «Endgame Manual» (партии с заданной позиции) совпадение полное (`opening_index_matches_the_pass`, `opening_index_leaves_set_up_games_to_the_pass`).
**Замеры** (Mega, i7-13700KF, 24 потока, тёплый кэш; индекс / проход): начальная позиция 103 / 399 мс, 1.e4 55 / 404 мс, 1.d4 Кf6 2.c4 e6 15 / 152 мс, Найдорф 12,5 / 76 мс. На 4 потоках (`taskset -c 0-3`, оценка ноутбука; `--bench`, индекс / без индекса): начальная 286 / 2226 мс, 1.e4 148 / 2318 мс, Найдорф 13 / 435 мс; глубокие позиции без изменений (40–52 мс), фильтр по игроку с позицией 1–4 мс.

View file

@ -43,6 +43,11 @@
<category>BoardGame</category>
</categories>
<releases>
<release version="0.6.3" date="2026-10-19">
<description>
<p>Faster position search in large ChessBase databases: an opening index (when there is enough memory) and a search index of its own for databases without one. Quieter import notes; the email in Settings → About is copied on click.</p>
</description>
</release>
<release version="0.6.2" date="2026-10-19">
<description>
<p>Settings → About: the version, links to the website, the release notes and the source code, and the support contacts.</p>