Opening index for large ChessBase bases (first 10 moves, built with the booster, loaded when memory allows); memory guard for big PGN position tables; CP_MEMORY_LIMIT
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
1506ebdf26
commit
4b92fa32de
16 changed files with 1164 additions and 77 deletions
11
CHANGELOG.md
11
CHANGELOG.md
|
|
@ -6,8 +6,15 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
|
||||||
|
|
||||||
- Position search in a large ChessBase database without a usable `.cbb` search index: the
|
- 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
|
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
|
then found in milliseconds instead of a pass over every game.
|
||||||
position and other early positions got about twice as fast.
|
- Opening positions (the start, 1.e4, …) in a large ChessBase database: an index of the
|
||||||
|
first ten moves of every game, built with the booster and kept in the cache, answers them
|
||||||
|
four to eight times faster. It is held in memory only when the machine has room for it
|
||||||
|
(about 600 MB for Mega Database); otherwise the search works as before.
|
||||||
|
- A big PGN file whose position table would not fit in memory now says so on the search
|
||||||
|
board instead of running out of memory.
|
||||||
|
- `chesspenguin --bench <database>` prints timings of opening, filtering and position
|
||||||
|
search for comparing machines.
|
||||||
- Settings → About: clicking the email address copies it instead of opening a mail app,
|
- Settings → About: clicking the email address copies it instead of opening a mail app,
|
||||||
which does nothing useful when none is installed.
|
which does nothing useful when none is installed.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -94,4 +94,5 @@ platform into the user's data directory and checks its SHA-256 (pinned in
|
||||||
## Rust crates
|
## Rust crates
|
||||||
|
|
||||||
Dependency licenses are recorded by `Cargo.lock`; key ones: shakmaty / pgn-reader (GPL-3.0-or-later),
|
Dependency licenses are recorded by `Cargo.lock`; key ones: shakmaty / pgn-reader (GPL-3.0-or-later),
|
||||||
egui / eframe (MIT OR Apache-2.0), zip (MIT), sevenz-rust2 (Apache-2.0).
|
egui / eframe (MIT OR Apache-2.0), zip (MIT), sevenz-rust2 (Apache-2.0), sysinfo (MIT),
|
||||||
|
sys-locale (MIT OR Apache-2.0).
|
||||||
|
|
|
||||||
|
|
@ -1558,12 +1558,20 @@ const ROWS: &[[&str; 6]] = &[
|
||||||
"Preparazione della ricerca rapida per posizione… {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.",
|
"The search index of the base 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.",
|
"L'index de recherche de la base est construit une fois et conservé dans le cache.",
|
||||||
"Die Datenbank hat keinen brauchbaren Suchindex (.cbb); er wird einmal erstellt und im Cache behalten.",
|
"Der Suchindex der Datenbank 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é.",
|
"El índice de búsqueda de la base 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.",
|
"L'indice di ricerca della base viene costruito una volta e tenuto nella cache.",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Position search needs about {n} MB of free memory for this database.",
|
||||||
|
"Поиску по позиции нужно около {n} МБ свободной памяти для этой базы.",
|
||||||
|
"La recherche par position nécessite environ {n} Mo de mémoire libre pour cette base.",
|
||||||
|
"Die Stellungssuche braucht für diese Datenbank etwa {n} MB freien Speicher.",
|
||||||
|
"La búsqueda por posición necesita unos {n} MB de memoria libre para esta base.",
|
||||||
|
"La ricerca per posizione richiede circa {n} MB di memoria libera per questa base.",
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
"Checking engine…",
|
"Checking engine…",
|
||||||
|
|
|
||||||
|
|
@ -236,8 +236,9 @@ pub struct LargeView {
|
||||||
in_order: Option<(usize, usize)>,
|
in_order: Option<(usize, usize)>,
|
||||||
cache: OutcomeCache,
|
cache: OutcomeCache,
|
||||||
job: Option<Job>,
|
job: Option<Job>,
|
||||||
/// Building our own search booster (a base without a usable `.cbb`), once the
|
/// Building the search index of the base (our booster when `.cbb` cannot be used,
|
||||||
/// board is used; `booster_failed` keeps a failure from being retried.
|
/// the opening positions), once the board is used; `booster_failed` keeps a
|
||||||
|
/// failure from being retried.
|
||||||
booster: Option<Background<bool>>,
|
booster: Option<Background<bool>>,
|
||||||
booster_failed: bool,
|
booster_failed: bool,
|
||||||
board: SearchBoard,
|
board: SearchBoard,
|
||||||
|
|
@ -457,8 +458,8 @@ impl LargeView {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds our own booster in the background when the board is in use and the
|
/// Builds the search index in the background when the board is in use and the
|
||||||
/// base has no usable `.cbb`; searches meanwhile run without it.
|
/// base lacks something (`Base::prepare`); searches meanwhile run without it.
|
||||||
fn update_booster(&mut self, db: &Arc<Database>, now: f64, ctx: &egui::Context) {
|
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()
|
&& let Some(result) = b.poll()
|
||||||
|
|
@ -470,17 +471,17 @@ impl LargeView {
|
||||||
if !wanted
|
if !wanted
|
||||||
|| self.booster.is_some()
|
|| self.booster.is_some()
|
||||||
|| self.booster_failed
|
|| self.booster_failed
|
||||||
|| !db.as_chessbase().is_some_and(|b| b.booster_wanted())
|
|| !db.as_chessbase().is_some_and(|b| b.prepare_wanted())
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let db = db.clone();
|
let db = db.clone();
|
||||||
self.booster = Background::spawn(ctx, now, move |progress, cancel| {
|
self.booster = Background::spawn(ctx, now, move |progress, cancel| {
|
||||||
match db.as_chessbase()?.build_booster(progress, cancel) {
|
match db.as_chessbase()?.prepare(progress, cancel) {
|
||||||
Ok(true) => Some(true),
|
Ok(true) => Some(true),
|
||||||
Ok(false) => None,
|
Ok(false) => None,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("search booster: {e}");
|
eprintln!("search index: {e}");
|
||||||
Some(false)
|
Some(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -590,7 +591,8 @@ impl LargeView {
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|j| (j.work.progress() as f32 / total.max(1) as f32).min(1.0));
|
.map(|j| (j.work.progress() as f32 / total.max(1) as f32).min(1.0));
|
||||||
if let Some(b) = &self.booster {
|
if let Some(b) = &self.booster {
|
||||||
let p = (b.progress() as f32 / total.max(1) as f32).min(1.0);
|
// 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);
|
||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
ui.add(egui::Spinner::new().size(14.0));
|
ui.add(egui::Spinner::new().size(14.0));
|
||||||
ui.label(
|
ui.label(
|
||||||
|
|
@ -601,7 +603,7 @@ impl LargeView {
|
||||||
.weak(),
|
.weak(),
|
||||||
)
|
)
|
||||||
.on_hover_text(tr(
|
.on_hover_text(tr(
|
||||||
"The base has no usable search index (.cbb); one is built once and kept in the cache.",
|
"The search index of the base is built once and kept in the cache.",
|
||||||
));
|
));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -81,6 +81,8 @@ struct SmallBoard {
|
||||||
table_hover: Option<UciMove>,
|
table_hover: Option<UciMove>,
|
||||||
/// Most games have no result: a book; continuations count chapters.
|
/// Most games have no result: a book; continuations count chapters.
|
||||||
books: bool,
|
books: bool,
|
||||||
|
/// The position table cannot be built: memory it would need (bytes).
|
||||||
|
blocked: Option<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SmallBoard {
|
impl SmallBoard {
|
||||||
|
|
@ -98,6 +100,7 @@ impl SmallBoard {
|
||||||
shown: None,
|
shown: None,
|
||||||
table_hover: None,
|
table_hover: None,
|
||||||
books: decided * 2 < db.len(),
|
books: decided * 2 < db.len(),
|
||||||
|
blocked: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -131,6 +134,12 @@ impl SmallBoard {
|
||||||
.map(|(r, ..)| r)
|
.map(|(r, ..)| r)
|
||||||
.or(self.shown.as_ref().map(|(r, ..)| r));
|
.or(self.shown.as_ref().map(|(r, ..)| r));
|
||||||
if current != Some(&wanted) {
|
if current != Some(&wanted) {
|
||||||
|
// No memory for the table: say so instead of starting a search that
|
||||||
|
// cannot answer.
|
||||||
|
self.blocked = db.positions_blocked();
|
||||||
|
if self.blocked.is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
let (db, query, text) = (db.clone(), self.board.query(), wanted.search.clone());
|
let (db, query, text) = (db.clone(), self.board.query(), wanted.search.clone());
|
||||||
let pos = query.position.clone();
|
let pos = query.position.clone();
|
||||||
let now = ctx.input(|i| i.time);
|
let now = ctx.input(|i| i.time);
|
||||||
|
|
@ -450,6 +459,15 @@ impl Library {
|
||||||
let counting = small.job.as_ref().map(|_| 0.0);
|
let counting = small.job.as_ref().map(|_| 0.0);
|
||||||
let mut events = Vec::new();
|
let mut events = Vec::new();
|
||||||
small.board.keys(ui.ctx(), outcome.as_ref(), &mut events);
|
small.board.keys(ui.ctx(), outcome.as_ref(), &mut events);
|
||||||
|
if let Some(need) = small.blocked {
|
||||||
|
ui.label(
|
||||||
|
egui::RichText::new(trf(
|
||||||
|
"Position search needs about {n} MB of free memory for this database.",
|
||||||
|
&[("n", &((need + (256 << 20)) / 1_000_000))],
|
||||||
|
))
|
||||||
|
.color(ui.visuals().warn_fg_color),
|
||||||
|
);
|
||||||
|
}
|
||||||
events.extend(small.board.panel(
|
events.extend(small.board.panel(
|
||||||
ui,
|
ui,
|
||||||
settings,
|
settings,
|
||||||
|
|
|
||||||
|
|
@ -119,6 +119,11 @@ impl PgnDatabase {
|
||||||
&self.entries
|
&self.entries
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Size of the PGN text, in bytes.
|
||||||
|
pub fn byte_len(&self) -> usize {
|
||||||
|
self.bytes.len()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn len(&self) -> usize {
|
pub fn len(&self) -> usize {
|
||||||
self.entries.len()
|
self.entries.len()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ use std::time::Instant;
|
||||||
use shakmaty::san::SanPlus;
|
use shakmaty::san::SanPlus;
|
||||||
use shakmaty::{Chess, Move, Position};
|
use shakmaty::{Chess, Move, Position};
|
||||||
|
|
||||||
use crate::chessbase::base::{Filter, NameFilter, SortKey};
|
use crate::chessbase::base::{Filter, NameFilter, OpeningsStatus, SortKey};
|
||||||
use crate::position::PositionQuery;
|
use crate::position::PositionQuery;
|
||||||
use crate::{Database, ScanProgress};
|
use crate::{Database, ScanProgress};
|
||||||
|
|
||||||
|
|
@ -94,19 +94,35 @@ pub fn run(path: &Path, booster_dir: Option<&Path>, out: &mut dyn Write) -> io::
|
||||||
if let Some(dir) = booster_dir {
|
if let Some(dir) = booster_dir {
|
||||||
base.set_booster_dir(dir);
|
base.set_booster_dir(dir);
|
||||||
}
|
}
|
||||||
let booster = if base.booster_ready() {
|
let mut prepared = String::new();
|
||||||
"yes".to_owned()
|
if base.prepare_wanted() {
|
||||||
} else if base.booster_wanted() {
|
|
||||||
let t = Instant::now();
|
let t = Instant::now();
|
||||||
match base.build_booster(&counter, &never) {
|
prepared = match base.prepare(&counter, &never) {
|
||||||
Ok(true) => format!("built in {:.1} s", t.elapsed().as_secs_f64()),
|
Ok(true) => format!(" (prepared in {:.1} s)", t.elapsed().as_secs_f64()),
|
||||||
Ok(false) => "cancelled".into(),
|
Ok(false) => " (cancelled)".into(),
|
||||||
Err(e) => format!("failed: {e}"),
|
Err(e) => format!(" (preparing failed: {e})"),
|
||||||
}
|
|
||||||
} else {
|
|
||||||
"none".into()
|
|
||||||
};
|
};
|
||||||
writeln!(out, "search booster (.cbb or our own): {booster}")?;
|
}
|
||||||
|
let openings = match base.openings_status() {
|
||||||
|
OpeningsStatus::Loaded(bytes) => format!("loaded, {}", mb(bytes as u64)),
|
||||||
|
OpeningsStatus::OnDisk { bytes, room } => format!(
|
||||||
|
"on disk, {}, not loaded ({})",
|
||||||
|
mb(bytes),
|
||||||
|
if room {
|
||||||
|
"room for it"
|
||||||
|
} else {
|
||||||
|
"not enough memory"
|
||||||
|
}
|
||||||
|
),
|
||||||
|
OpeningsStatus::Missing { room: true } => "not built".into(),
|
||||||
|
OpeningsStatus::Missing { room: false } => "not built: not enough memory".into(),
|
||||||
|
OpeningsStatus::NoCache => "no cache directory".into(),
|
||||||
|
};
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
"search booster (.cbb or our own): {} · opening index: {openings}{prepared}",
|
||||||
|
if base.booster_ready() { "yes" } else { "no" }
|
||||||
|
)?;
|
||||||
|
|
||||||
let carlsen = Filter {
|
let carlsen = Filter {
|
||||||
player: NameFilter {
|
player: NameFilter {
|
||||||
|
|
@ -168,7 +184,16 @@ pub fn run(path: &Path, booster_dir: Option<&Path>, out: &mut dyn Write) -> io::
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Database::Pgn(pgn) => {
|
Database::Pgn(pgn) => {
|
||||||
writeln!(out, "games: {}", pgn.db.len())?;
|
writeln!(
|
||||||
|
out,
|
||||||
|
"games: {} · position table estimated at {}{}",
|
||||||
|
pgn.db.len(),
|
||||||
|
mb(pgn.positions_estimate()),
|
||||||
|
match pgn.positions_blocked() {
|
||||||
|
Some(_) => " · not built: not enough memory",
|
||||||
|
None => "",
|
||||||
|
}
|
||||||
|
)?;
|
||||||
let t = Instant::now();
|
let t = Instant::now();
|
||||||
let Some(table) = pgn.positions(&counter, &never) else {
|
let Some(table) = pgn.positions(&counter, &never) else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
|
|
|
||||||
|
|
@ -8,12 +8,12 @@ use std::fs::File;
|
||||||
use std::io::{Read, Seek, SeekFrom};
|
use std::io::{Read, Seek, SeekFrom};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
use std::sync::{Mutex, OnceLock};
|
use std::sync::{Arc, Mutex, OnceLock};
|
||||||
|
|
||||||
use super::entities::{self, Entities, Kind};
|
use super::entities::{self, Entities, Kind};
|
||||||
use super::headers::{self, GameHeader, Record};
|
use super::headers::{self, GameHeader, Record};
|
||||||
use super::text::{self, Decoder};
|
use super::text::{self, Decoder};
|
||||||
use super::{annotations, be, moves, writer};
|
use super::{annotations, be, booster, moves, openings, writer};
|
||||||
use crate::ImportError;
|
use crate::ImportError;
|
||||||
|
|
||||||
const RECORD: usize = 46;
|
const RECORD: usize = 46;
|
||||||
|
|
@ -54,6 +54,8 @@ pub struct Base {
|
||||||
/// application), and that booster once found or built.
|
/// application), and that booster once found or built.
|
||||||
booster_dir: OnceLock<PathBuf>,
|
booster_dir: OnceLock<PathBuf>,
|
||||||
own_booster: OnceLock<PathBuf>,
|
own_booster: OnceLock<PathBuf>,
|
||||||
|
/// The opening index, once loaded (`openings.rs`; kept in the same directory).
|
||||||
|
openings: Mutex<Option<Arc<openings::Index>>>,
|
||||||
cba: Option<Mutex<File>>,
|
cba: Option<Mutex<File>>,
|
||||||
/// Titles of guiding texts read so far (they are stored with the text).
|
/// Titles of guiding texts read so far (they are stored with the text).
|
||||||
text_titles: Mutex<HashMap<usize, String>>,
|
text_titles: Mutex<HashMap<usize, String>>,
|
||||||
|
|
@ -438,6 +440,7 @@ impl Base {
|
||||||
cbb: OnceLock::new(),
|
cbb: OnceLock::new(),
|
||||||
booster_dir: OnceLock::new(),
|
booster_dir: OnceLock::new(),
|
||||||
own_booster: OnceLock::new(),
|
own_booster: OnceLock::new(),
|
||||||
|
openings: Mutex::new(None),
|
||||||
cba: cba.map(Mutex::new),
|
cba: cba.map(Mutex::new),
|
||||||
text_titles: Mutex::new(HashMap::new()),
|
text_titles: Mutex::new(HashMap::new()),
|
||||||
notes: Vec::new(),
|
notes: Vec::new(),
|
||||||
|
|
@ -586,9 +589,10 @@ impl Base {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Our booster's file: named after the database and the size and date of its
|
/// Where the files of this database go in the cache directory, without the
|
||||||
/// games, so a changed database gets a new one.
|
/// extension: named after the database and the size and date of its games, so a
|
||||||
fn own_booster_path(&self) -> Option<PathBuf> {
|
/// changed database gets new ones.
|
||||||
|
fn cache_stem(&self) -> Option<PathBuf> {
|
||||||
let dir = self.booster_dir.get()?;
|
let dir = self.booster_dir.get()?;
|
||||||
let path = std::fs::canonicalize(&self.path).unwrap_or_else(|_| self.path.clone());
|
let path = std::fs::canonicalize(&self.path).unwrap_or_else(|_| self.path.clone());
|
||||||
let meta = std::fs::metadata(&self.cbg_path).ok()?;
|
let meta = std::fs::metadata(&self.cbg_path).ok()?;
|
||||||
|
|
@ -608,7 +612,97 @@ impl Base {
|
||||||
h ^= u64::from(b);
|
h ^= u64::from(b);
|
||||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||||
}
|
}
|
||||||
Some(dir.join(format!("{h:016x}.cbb")))
|
Some(dir.join(format!("{h:016x}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn own_booster_path(&self) -> Option<PathBuf> {
|
||||||
|
self.cache_stem().map(|p| p.with_extension("cbb"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn openings_path(&self) -> Option<PathBuf> {
|
||||||
|
self.cache_stem().map(|p| p.with_extension("cpo"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The opening index, when it is loaded.
|
||||||
|
pub fn openings(&self) -> Option<Arc<openings::Index>> {
|
||||||
|
self.openings.lock().ok()?.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the opening index stands.
|
||||||
|
pub fn openings_status(&self) -> OpeningsStatus {
|
||||||
|
if let Some(index) = self.openings() {
|
||||||
|
return OpeningsStatus::Loaded(index.memory());
|
||||||
|
}
|
||||||
|
let Some(path) = self.openings_path() else {
|
||||||
|
return OpeningsStatus::NoCache;
|
||||||
|
};
|
||||||
|
match openings::Index::file_size(&path) {
|
||||||
|
Some(bytes) => OpeningsStatus::OnDisk {
|
||||||
|
bytes,
|
||||||
|
room: room_for(bytes),
|
||||||
|
},
|
||||||
|
None => OpeningsStatus::Missing {
|
||||||
|
room: room_for(self.records as u64 * openings::BYTES_PER_GAME),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Something is left to build or load for fast position searches
|
||||||
|
/// ([`Base::prepare`]).
|
||||||
|
pub fn prepare_wanted(&self) -> bool {
|
||||||
|
self.booster_wanted()
|
||||||
|
|| matches!(
|
||||||
|
self.openings_status(),
|
||||||
|
OpeningsStatus::Missing { room: true } | OpeningsStatus::OnDisk { 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
|
||||||
|
/// index is sorted), then loads the index. `Ok(false)` when cancelled.
|
||||||
|
pub fn prepare(&self, progress: &AtomicUsize, cancel: &AtomicBool) -> std::io::Result<bool> {
|
||||||
|
let Some(stem) = self.cache_stem() else {
|
||||||
|
return Err(std::io::Error::other("no cache directory"));
|
||||||
|
};
|
||||||
|
let booster_path = self.booster_wanted().then(|| stem.with_extension("cbb"));
|
||||||
|
let openings_path = stem.with_extension("cpo");
|
||||||
|
let build_openings = matches!(
|
||||||
|
self.openings_status(),
|
||||||
|
OpeningsStatus::Missing { room: true }
|
||||||
|
);
|
||||||
|
if booster_path.is_some() || build_openings {
|
||||||
|
let built = booster::build(
|
||||||
|
self,
|
||||||
|
booster_path.as_deref(),
|
||||||
|
build_openings.then_some(openings_path.as_path()),
|
||||||
|
progress,
|
||||||
|
cancel,
|
||||||
|
)?;
|
||||||
|
if !built {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
if let Some(p) = booster_path {
|
||||||
|
let _ = self.own_booster.set(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.openings().is_none()
|
||||||
|
&& let Some(bytes) = openings::Index::file_size(&openings_path)
|
||||||
|
&& room_for(bytes)
|
||||||
|
{
|
||||||
|
match openings::Index::load(&openings_path, self.records) {
|
||||||
|
Some(index) => {
|
||||||
|
if let Ok(mut o) = self.openings.lock() {
|
||||||
|
*o = Some(Arc::new(index));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Not an index for this database (an older layout): built anew next time.
|
||||||
|
None => {
|
||||||
|
let _ = std::fs::remove_file(&openings_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Position searches have a booster (ChessBase's or ours).
|
/// Position searches have a booster (ChessBase's or ours).
|
||||||
|
|
@ -631,7 +725,7 @@ impl Base {
|
||||||
let Some(path) = self.own_booster_path() else {
|
let Some(path) = self.own_booster_path() else {
|
||||||
return Err(std::io::Error::other("no booster directory"));
|
return Err(std::io::Error::other("no booster directory"));
|
||||||
};
|
};
|
||||||
if !super::booster::build(self, &path, progress, cancel)? {
|
if !booster::build(self, Some(&path), None, progress, cancel)? {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
let _ = self.own_booster.set(path);
|
let _ = self.own_booster.set(path);
|
||||||
|
|
@ -1086,6 +1180,25 @@ fn name_table(names: &Names, f: &NameFilter) -> Option<Vec<bool>> {
|
||||||
(!words(&f.text).is_empty()).then(|| names.matching(&f.text))
|
(!words(&f.text).is_empty()).then(|| names.matching(&f.text))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Where the opening index of a database stands (see [`Base::openings_status`]).
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum OpeningsStatus {
|
||||||
|
/// In memory, this many bytes.
|
||||||
|
Loaded(usize),
|
||||||
|
/// Built, but not loaded; `room`: the machine has memory for it now.
|
||||||
|
OnDisk { bytes: u64, room: bool },
|
||||||
|
/// Not built; `room`: the machine has memory to build and hold it.
|
||||||
|
Missing { room: bool },
|
||||||
|
/// No cache directory was given.
|
||||||
|
NoCache,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `bytes` more can be held in memory with a gigabyte to spare. Unknown
|
||||||
|
/// memory counts as no room.
|
||||||
|
fn room_for(bytes: u64) -> bool {
|
||||||
|
crate::memory::available().is_some_and(|free| free >= bytes + (1 << 30))
|
||||||
|
}
|
||||||
|
|
||||||
/// A booster file holds a record per `.cbh` record (plus its header) and says so.
|
/// A booster file holds a record per `.cbh` record (plus its header) and says so.
|
||||||
fn booster_consistent(path: &Path, file_records: usize) -> bool {
|
fn booster_consistent(path: &Path, file_records: usize) -> bool {
|
||||||
let Ok(mut f) = File::open(path) else {
|
let Ok(mut f) = File::open(path) else {
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,9 @@
|
||||||
//! date of `.cbg`), so a changed database gets a new file. The format is that of
|
//! 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
|
//! `.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).
|
//! ChessBase's byte for byte on Mega (`docs/research/position-index.md`, section 1.1).
|
||||||
|
//!
|
||||||
|
//! The same pass over the main lines also collects the opening index (`openings.rs`)
|
||||||
|
//! when it is wanted: [`build`] makes either or both.
|
||||||
|
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
@ -17,6 +20,7 @@ use shakmaty::{Board, Chess, Color, Position, Role};
|
||||||
use super::base::{Base, RecordKind};
|
use super::base::{Base, RecordKind};
|
||||||
use super::be;
|
use super::be;
|
||||||
use super::moves::{self, Step, WalkError};
|
use super::moves::{self, Step, WalkError};
|
||||||
|
use super::openings::{self, GameEntry};
|
||||||
use super::search::{BLOCK, CBB_RECORD, read_games};
|
use super::search::{BLOCK, CBB_RECORD, read_games};
|
||||||
|
|
||||||
/// Marks in `r` what stands on `b`: the layout of a `.cbb` record.
|
/// Marks in `r` what stands on `b`: the layout of a `.cbb` record.
|
||||||
|
|
@ -66,9 +70,18 @@ fn mark(b: &Board, r: &mut [u8; CBB_RECORD]) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn walk(cbg: &[u8], offset: u32, fast: bool) -> Result<[u8; CBB_RECORD], WalkError> {
|
/// What one walk of a game's main line yields.
|
||||||
|
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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk(cbg: &[u8], offset: u32, fast: bool, opening: Option<u32>) -> Result<GameData, WalkError> {
|
||||||
let mut r = [0u8; CBB_RECORD];
|
let mut r = [0u8; CBB_RECORD];
|
||||||
let mut end_pawns = 0u8;
|
let mut end_pawns = 0u8;
|
||||||
|
let mut entry = opening.map(GameEntry::new);
|
||||||
|
let mut ply = 0usize;
|
||||||
moves::main_line(cbg, offset, fast, |pos: &Chess, step| {
|
moves::main_line(cbg, offset, fast, |pos: &Chess, step| {
|
||||||
let b = pos.board();
|
let b = pos.board();
|
||||||
mark(b, &mut r);
|
mark(b, &mut r);
|
||||||
|
|
@ -76,23 +89,37 @@ fn walk(cbg: &[u8], offset: u32, fast: bool) -> Result<[u8; CBB_RECORD], WalkErr
|
||||||
let pawns = |c: Color| (b.by_color(c) & b.pawns()).count().min(7) as u8;
|
let pawns = |c: Color| (b.by_color(c) & b.pawns()).count().min(7) as u8;
|
||||||
end_pawns = pawns(Color::White) | (pawns(Color::Black) << 4);
|
end_pawns = pawns(Color::White) | (pawns(Color::Black) << 4);
|
||||||
}
|
}
|
||||||
|
if let Some(e) = entry.as_mut() {
|
||||||
|
e.visit(pos, ply, &step);
|
||||||
|
}
|
||||||
|
ply += 1;
|
||||||
true
|
true
|
||||||
})?;
|
})?;
|
||||||
r[0x03] |= end_pawns;
|
r[0x03] |= end_pawns;
|
||||||
Ok(r)
|
Ok(GameData {
|
||||||
|
record: r,
|
||||||
|
opening: entry.filter(|e| e.standard),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The booster record of the game at `offset` in `cbg`: the fast walk, and the
|
/// The booster record of the game at `offset` in `cbg` (and its opening entries when
|
||||||
/// checked one when the fast one stumbles. `None` when the game cannot be read (a
|
/// `opening` names the game): the fast walk, and the checked one when the fast one
|
||||||
/// position search cannot find it either).
|
/// stumbles. `None` when the game cannot be read (a position search cannot find it
|
||||||
pub(super) fn record_of(cbg: &[u8], offset: u32) -> Option<[u8; CBB_RECORD]> {
|
/// either).
|
||||||
match walk(cbg, offset, true) {
|
pub(super) fn game_data(cbg: &[u8], offset: u32, opening: Option<u32>) -> Option<GameData> {
|
||||||
Ok(r) => Some(r),
|
match walk(cbg, offset, true, opening) {
|
||||||
Err(WalkError::Moves(_)) => walk(cbg, offset, false).ok(),
|
Ok(d) => Some(d),
|
||||||
|
Err(WalkError::Moves(_)) => walk(cbg, offset, false, opening).ok(),
|
||||||
Err(WalkError::Unsupported(_)) => None,
|
Err(WalkError::Unsupported(_)) => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The booster record alone.
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(super) fn record_of(cbg: &[u8], offset: u32) -> Option<[u8; CBB_RECORD]> {
|
||||||
|
game_data(cbg, offset, None).map(|d| d.record)
|
||||||
|
}
|
||||||
|
|
||||||
fn write_all_at(f: &File, buf: &[u8], at: u64) -> io::Result<()> {
|
fn write_all_at(f: &File, buf: &[u8], at: u64) -> io::Result<()> {
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
{
|
||||||
|
|
@ -114,22 +141,31 @@ fn write_all_at(f: &File, buf: &[u8], at: u64) -> io::Result<()> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes the booster of `base` to `out` (a `.part` file next to it first, renamed
|
/// One pass over the main lines of `base`, in parallel, writing the booster to
|
||||||
/// when complete): one pass over the main lines, in parallel. `progress` counts the
|
/// `booster` and the opening index to `openings` (each when given; `.part` files
|
||||||
/// records done. `Ok(false)` when cancelled; then nothing is left behind.
|
/// first, renamed when complete). `progress` counts the records done, then the
|
||||||
|
/// records again while the index is sorted. `Ok(false)` when cancelled; then nothing
|
||||||
|
/// is left behind.
|
||||||
pub(super) fn build(
|
pub(super) fn build(
|
||||||
base: &Base,
|
base: &Base,
|
||||||
out: &Path,
|
booster: Option<&Path>,
|
||||||
|
openings: Option<&Path>,
|
||||||
progress: &AtomicUsize,
|
progress: &AtomicUsize,
|
||||||
cancel: &AtomicBool,
|
cancel: &AtomicBool,
|
||||||
) -> io::Result<bool> {
|
) -> io::Result<bool> {
|
||||||
|
let total = base.records();
|
||||||
|
let count = base.file_records() + 1;
|
||||||
|
let part = booster.map(|p| p.with_extension("part"));
|
||||||
|
if let (Some(out), Some(part)) = (booster, &part) {
|
||||||
if let Some(dir) = out.parent() {
|
if let Some(dir) = out.parent() {
|
||||||
std::fs::create_dir_all(dir)?;
|
std::fs::create_dir_all(dir)?;
|
||||||
}
|
}
|
||||||
let part = out.with_extension("part");
|
File::create(part)?.set_len((count * CBB_RECORD) as u64)?;
|
||||||
let count = base.file_records() + 1;
|
}
|
||||||
File::create(&part)?.set_len((count * CBB_RECORD) as u64)?;
|
let sink = match openings {
|
||||||
let total = base.records();
|
Some(out) => Some(openings::Sink::new(&out.with_extension("build"), total)?),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
let next = AtomicUsize::new(0);
|
let next = AtomicUsize::new(0);
|
||||||
let threads = std::thread::available_parallelism()
|
let threads = std::thread::available_parallelism()
|
||||||
.map_or(4, |n| n.get())
|
.map_or(4, |n| n.get())
|
||||||
|
|
@ -141,10 +177,14 @@ pub(super) fn build(
|
||||||
s.spawn(|| {
|
s.spawn(|| {
|
||||||
let run = || -> io::Result<()> {
|
let run = || -> io::Result<()> {
|
||||||
let cbg = File::open(base.cbg_path())?;
|
let cbg = File::open(base.cbg_path())?;
|
||||||
let file = File::options().write(true).open(&part)?;
|
let file = part
|
||||||
|
.as_ref()
|
||||||
|
.map(|p| File::options().write(true).open(p))
|
||||||
|
.transpose()?;
|
||||||
let mut games: Vec<(u32, u32)> = Vec::new();
|
let mut games: Vec<(u32, u32)> = Vec::new();
|
||||||
let (mut span, mut single) = (Vec::new(), Vec::new());
|
let (mut span, mut single) = (Vec::new(), Vec::new());
|
||||||
let mut block = vec![0u8; BLOCK * CBB_RECORD];
|
let mut block = vec![0u8; BLOCK * CBB_RECORD];
|
||||||
|
let mut entries: Vec<GameEntry> = Vec::new();
|
||||||
loop {
|
loop {
|
||||||
if cancel.load(Ordering::Relaxed) {
|
if cancel.load(Ordering::Relaxed) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
|
|
@ -156,6 +196,7 @@ pub(super) fn build(
|
||||||
let to = (from + BLOCK).min(total);
|
let to = (from + BLOCK).min(total);
|
||||||
let bytes = &mut block[..(to - from) * CBB_RECORD];
|
let bytes = &mut block[..(to - from) * CBB_RECORD];
|
||||||
bytes.fill(0);
|
bytes.fill(0);
|
||||||
|
entries.clear();
|
||||||
games.clear();
|
games.clear();
|
||||||
for i in from..to {
|
for i in from..to {
|
||||||
// Texts and Chess960 games (ECO field ≥ 64576) have no
|
// Texts and Chess960 games (ECO field ≥ 64576) have no
|
||||||
|
|
@ -167,12 +208,19 @@ pub(super) fn build(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
read_games(&cbg, &games, &mut span, &mut single, |index, data, rel| {
|
read_games(&cbg, &games, &mut span, &mut single, |index, data, rel| {
|
||||||
if let Some(r) = record_of(data, rel) {
|
let opening = sink.is_some().then_some(index);
|
||||||
|
if let Some(d) = game_data(data, rel, opening) {
|
||||||
let at = (index as usize - from) * CBB_RECORD;
|
let at = (index as usize - from) * CBB_RECORD;
|
||||||
bytes[at..at + CBB_RECORD].copy_from_slice(&r);
|
bytes[at..at + CBB_RECORD].copy_from_slice(&d.record);
|
||||||
|
entries.extend(d.opening);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
write_all_at(&file, bytes, ((from + 1) * CBB_RECORD) as u64)?;
|
if let Some(f) = &file {
|
||||||
|
write_all_at(f, bytes, ((from + 1) * CBB_RECORD) as u64)?;
|
||||||
|
}
|
||||||
|
if let Some(sink) = &sink {
|
||||||
|
sink.add(&entries)?;
|
||||||
|
}
|
||||||
progress.fetch_add(to - from, Ordering::Relaxed);
|
progress.fetch_add(to - from, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
@ -185,21 +233,37 @@ pub(super) fn build(
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
let clean = || {
|
||||||
|
if let Some(p) = &part {
|
||||||
|
let _ = std::fs::remove_file(p);
|
||||||
|
}
|
||||||
|
};
|
||||||
if let Some(e) = failure.into_inner().unwrap_or(None) {
|
if let Some(e) = failure.into_inner().unwrap_or(None) {
|
||||||
let _ = std::fs::remove_file(&part);
|
clean();
|
||||||
|
if let Some(s) = sink {
|
||||||
|
let _ = s.discard();
|
||||||
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
}
|
}
|
||||||
if cancel.load(Ordering::Relaxed) {
|
if cancel.load(Ordering::Relaxed) {
|
||||||
let _ = std::fs::remove_file(&part);
|
clean();
|
||||||
|
if let Some(s) = sink {
|
||||||
|
let _ = s.discard();
|
||||||
|
}
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
|
if let (Some(out), Some(part)) = (booster, &part) {
|
||||||
// The header last: a file without the count is never taken for a booster.
|
// The header last: a file without the count is never taken for a booster.
|
||||||
let mut header = [0u8; CBB_RECORD];
|
let mut header = [0u8; CBB_RECORD];
|
||||||
header[..4].copy_from_slice(&(count as u32).to_be_bytes());
|
header[..4].copy_from_slice(&(count as u32).to_be_bytes());
|
||||||
let file = File::options().write(true).open(&part)?;
|
let file = File::options().write(true).open(part)?;
|
||||||
write_all_at(&file, &header, 0)?;
|
write_all_at(&file, &header, 0)?;
|
||||||
file.sync_all()?;
|
file.sync_all()?;
|
||||||
drop(file);
|
drop(file);
|
||||||
std::fs::rename(&part, out)?;
|
std::fs::rename(part, out)?;
|
||||||
|
}
|
||||||
|
if let (Some(out), Some(sink)) = (openings, sink) {
|
||||||
|
return sink.finish(out, total, progress, cancel);
|
||||||
|
}
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ mod booster;
|
||||||
mod entities;
|
mod entities;
|
||||||
mod headers;
|
mod headers;
|
||||||
mod moves;
|
mod moves;
|
||||||
|
pub mod openings;
|
||||||
pub mod search;
|
pub mod search;
|
||||||
mod text;
|
mod text;
|
||||||
mod writer;
|
mod writer;
|
||||||
|
|
|
||||||
575
crates/chess-import/src/chessbase/openings.rs
Normal file
575
crates/chess-import/src/chessbase/openings.rs
Normal file
|
|
@ -0,0 +1,575 @@
|
||||||
|
//! Opening index of a large ChessBase database: the positions of the first `PLIES`
|
||||||
|
//! half-moves of every game, so a position of the opening is found without a pass
|
||||||
|
//! over the games (the booster cannot rule games out there: nearly every game passes
|
||||||
|
//! through 1.e4). Built in the same pass as the booster, kept in the cache directory
|
||||||
|
//! next to it, and held in memory only when the machine has room for it.
|
||||||
|
//!
|
||||||
|
//! Contents. Per game from the usual start position, its first `PLIES` moves as 16-bit
|
||||||
|
//! codes (`prefix`; `END` after the last move, `NULL` for a null move) — they give the
|
||||||
|
//! move a game played from a position, whether it came by the same move order and the
|
||||||
|
//! games that end there. Then one entry per (position, game) for plies 0..=`PLIES`:
|
||||||
|
//! the distinct position keys sorted (`keys`), and per key its games in ascending
|
||||||
|
//! order with the ply at which each reaches it (`games`: record index as a varint
|
||||||
|
//! delta, then the ply). A game that reaches a position twice within the opening
|
||||||
|
//! counts at its first ply. Games from a set-up position and the unreadable ones have
|
||||||
|
//! 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
|
||||||
|
//! 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
|
||||||
|
//! size is what it costs to keep.
|
||||||
|
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::{self, BufWriter, Read, Write};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
use shakmaty::uci::UciMove;
|
||||||
|
use shakmaty::{Chess, Role, Square};
|
||||||
|
|
||||||
|
use super::base::Base;
|
||||||
|
use crate::position::{self, Collector, GameResult, Match, PositionOutcome, PositionQuery, uci};
|
||||||
|
|
||||||
|
/// Half-moves of each game in the index.
|
||||||
|
pub const PLIES: usize = 10;
|
||||||
|
/// Moves kept per game: one more than the indexed plies, so that the move played
|
||||||
|
/// from the deepest indexed position is known too.
|
||||||
|
const PREFIX: usize = PLIES + 1;
|
||||||
|
/// Rough size of the index per game, to tell beforehand whether it fits in memory
|
||||||
|
/// (Mega: about 50 bytes).
|
||||||
|
pub const BYTES_PER_GAME: u64 = 60;
|
||||||
|
/// Prefix code: the game's main line ended before this move.
|
||||||
|
const END: u16 = u16::MAX;
|
||||||
|
/// Prefix code: a null move.
|
||||||
|
const NULL: u16 = u16::MAX - 1;
|
||||||
|
const MAGIC: &[u8; 8] = b"CPOPEN01";
|
||||||
|
/// 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;
|
||||||
|
/// Bytes of a raw entry in a bucket file: key (8), game (4), ply (1).
|
||||||
|
const RAW: usize = 13;
|
||||||
|
|
||||||
|
/// A move in 16 bits: from (6), to (6), promotion role (3).
|
||||||
|
fn encode(m: UciMove) -> u16 {
|
||||||
|
match m {
|
||||||
|
UciMove::Normal {
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
promotion,
|
||||||
|
} => {
|
||||||
|
u16::from(u8::from(from))
|
||||||
|
| u16::from(u8::from(to)) << 6
|
||||||
|
| u16::from(promotion.map_or(0, |r| r as u8)) << 12
|
||||||
|
}
|
||||||
|
_ => NULL,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode(v: u16) -> Option<UciMove> {
|
||||||
|
match v {
|
||||||
|
END => None,
|
||||||
|
NULL => Some(UciMove::Null),
|
||||||
|
v => Some(UciMove::Normal {
|
||||||
|
from: Square::new(u32::from(v & 63)),
|
||||||
|
to: Square::new(u32::from((v >> 6) & 63)),
|
||||||
|
promotion: Role::try_from(v >> 12).ok(),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the build pass collects for one game (see [`Sink`]).
|
||||||
|
pub(super) struct GameEntry {
|
||||||
|
pub index: u32,
|
||||||
|
/// The first `PREFIX` moves, `END`-padded.
|
||||||
|
pub prefix: [u16; PREFIX],
|
||||||
|
/// (position key, ply) for plies 0..=`PLIES`, up to the end of the line.
|
||||||
|
pub keys: Vec<(u64, u8)>,
|
||||||
|
/// The game starts from the usual position (else it gets no entries).
|
||||||
|
pub standard: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GameEntry {
|
||||||
|
pub(super) fn new(index: u32) -> GameEntry {
|
||||||
|
GameEntry {
|
||||||
|
index,
|
||||||
|
prefix: [END; PREFIX],
|
||||||
|
keys: Vec::with_capacity(PLIES + 1),
|
||||||
|
standard: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called by the pass for the position at `ply` and the step from it.
|
||||||
|
pub(super) fn visit(&mut self, pos: &Chess, ply: usize, step: &super::moves::Step<'_>) {
|
||||||
|
use super::moves::Step;
|
||||||
|
if !self.standard || ply > PLIES {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ply == 0 && !position::same_position(pos, &Chess::default()) {
|
||||||
|
self.standard = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.keys.push((position::key(pos), ply as u8));
|
||||||
|
self.prefix[ply] = match step {
|
||||||
|
Step::Move(m) => encode(uci(m)),
|
||||||
|
Step::Null => NULL,
|
||||||
|
Step::End => END,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collects the entries of the build pass into bucket files.
|
||||||
|
pub(super) struct Sink {
|
||||||
|
buckets: Vec<Mutex<BufWriter<File>>>,
|
||||||
|
prefix: Mutex<Vec<u16>>,
|
||||||
|
dir: std::path::PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sink {
|
||||||
|
pub(super) fn new(dir: &Path, records: usize) -> io::Result<Sink> {
|
||||||
|
std::fs::create_dir_all(dir)?;
|
||||||
|
let mut buckets = Vec::with_capacity(BUCKETS);
|
||||||
|
for b in 0..BUCKETS {
|
||||||
|
let f = File::create(dir.join(format!("bucket-{b:02}")))?;
|
||||||
|
buckets.push(Mutex::new(BufWriter::with_capacity(1 << 16, f)));
|
||||||
|
}
|
||||||
|
Ok(Sink {
|
||||||
|
buckets,
|
||||||
|
prefix: Mutex::new(vec![END; records * PREFIX]),
|
||||||
|
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<()> {
|
||||||
|
if let Ok(mut p) = self.prefix.lock() {
|
||||||
|
for e in entries {
|
||||||
|
let at = e.index as usize * PREFIX;
|
||||||
|
p[at..at + PREFIX].copy_from_slice(&e.prefix);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Group by bucket so that each lock is taken once per block.
|
||||||
|
let mut raw: Vec<Vec<u8>> = vec![Vec::new(); BUCKETS];
|
||||||
|
for e in entries {
|
||||||
|
for &(key, ply) in &e.keys {
|
||||||
|
let b = &mut raw[(key >> 58) as usize];
|
||||||
|
b.extend_from_slice(&key.to_le_bytes());
|
||||||
|
b.extend_from_slice(&e.index.to_le_bytes());
|
||||||
|
b.push(ply);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (b, bytes) in raw.iter().enumerate() {
|
||||||
|
if !bytes.is_empty() {
|
||||||
|
let mut w = self
|
||||||
|
.buckets
|
||||||
|
.get(b)
|
||||||
|
.and_then(|m| m.lock().ok())
|
||||||
|
.ok_or_else(|| io::Error::other("bucket lock"))?;
|
||||||
|
w.write_all(bytes)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes the bucket files (a cancelled or failed pass).
|
||||||
|
pub(super) fn discard(self) -> io::Result<()> {
|
||||||
|
self.remove_buckets();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_buckets(&self) {
|
||||||
|
for b in 0..BUCKETS {
|
||||||
|
let _ = std::fs::remove_file(self.dir.join(format!("bucket-{b:02}")));
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_dir(&self.dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sorts the entries and writes the index to `out` (`.part` first). `progress`
|
||||||
|
/// grows by `records` over the sort. The bucket files are removed either way.
|
||||||
|
/// `Ok(false)` when cancelled.
|
||||||
|
pub(super) fn finish(
|
||||||
|
self,
|
||||||
|
out: &Path,
|
||||||
|
records: usize,
|
||||||
|
progress: &AtomicUsize,
|
||||||
|
cancel: &AtomicBool,
|
||||||
|
) -> io::Result<bool> {
|
||||||
|
let result = self.write(out, records, progress, cancel);
|
||||||
|
self.remove_buckets();
|
||||||
|
if !matches!(result, Ok(true)) {
|
||||||
|
let _ = std::fs::remove_file(out.with_extension("part"));
|
||||||
|
let _ = std::fs::remove_file(out.with_extension("games"));
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(
|
||||||
|
&self,
|
||||||
|
out: &Path,
|
||||||
|
records: usize,
|
||||||
|
progress: &AtomicUsize,
|
||||||
|
cancel: &AtomicBool,
|
||||||
|
) -> io::Result<bool> {
|
||||||
|
for w in &self.buckets {
|
||||||
|
w.lock()
|
||||||
|
.map_err(|_| io::Error::other("bucket lock"))?
|
||||||
|
.flush()?;
|
||||||
|
}
|
||||||
|
let part = out.with_extension("part");
|
||||||
|
let mut file = BufWriter::with_capacity(1 << 20, File::create(&part)?);
|
||||||
|
// Header: magic, plies, records, then the section lengths filled in at the end.
|
||||||
|
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])?;
|
||||||
|
// 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);
|
||||||
|
for m in prefix.iter() {
|
||||||
|
bytes.extend_from_slice(&m.to_le_bytes());
|
||||||
|
}
|
||||||
|
drop(prefix);
|
||||||
|
let prefix_len = bytes.len() as u64;
|
||||||
|
file.write_all(&bytes)?;
|
||||||
|
drop(bytes);
|
||||||
|
// The keys (kept in memory: a few dozen bytes per position) and the games
|
||||||
|
// (streamed to a file, appended after the keys), bucket by bucket: the
|
||||||
|
// buckets are in key order.
|
||||||
|
let games_path = out.with_extension("games");
|
||||||
|
let mut games = BufWriter::with_capacity(
|
||||||
|
1 << 20,
|
||||||
|
File::options()
|
||||||
|
.read(true)
|
||||||
|
.write(true)
|
||||||
|
.create(true)
|
||||||
|
.truncate(true)
|
||||||
|
.open(&games_path)?,
|
||||||
|
);
|
||||||
|
let mut games_len = 0u64;
|
||||||
|
let mut keys: Vec<u8> = Vec::new();
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
let mut list = Vec::new();
|
||||||
|
for b in 0..BUCKETS {
|
||||||
|
if cancel.load(Ordering::Relaxed) {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
raw.clear();
|
||||||
|
File::open(self.dir.join(format!("bucket-{b:02}")))?.read_to_end(&mut raw)?;
|
||||||
|
let mut entries: Vec<(u64, u32, u8)> = raw
|
||||||
|
.as_chunks::<RAW>()
|
||||||
|
.0
|
||||||
|
.iter()
|
||||||
|
.map(|e| {
|
||||||
|
(
|
||||||
|
u64::from_le_bytes(e[..8].try_into().expect("8 bytes")),
|
||||||
|
u32::from_le_bytes(e[8..12].try_into().expect("4 bytes")),
|
||||||
|
e[12],
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
entries.sort_unstable();
|
||||||
|
let mut i = 0;
|
||||||
|
while i < entries.len() {
|
||||||
|
let key = entries[i].0;
|
||||||
|
list.clear();
|
||||||
|
let mut last = 0u32;
|
||||||
|
let mut count = 0u32;
|
||||||
|
while i < entries.len() && entries[i].0 == key {
|
||||||
|
let (_, game, ply) = entries[i];
|
||||||
|
i += 1;
|
||||||
|
// The same game twice (a repeated position): its first ply.
|
||||||
|
if count > 0 && game == last {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
varint(&mut list, game - if count == 0 { 0 } else { last + 1 });
|
||||||
|
list.push(ply);
|
||||||
|
last = game;
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
keys.extend_from_slice(&key.to_le_bytes());
|
||||||
|
keys.extend_from_slice(&games_len.to_le_bytes()[..5]);
|
||||||
|
keys.extend_from_slice(&count.to_le_bytes());
|
||||||
|
games.write_all(&list)?;
|
||||||
|
games_len += list.len() as u64;
|
||||||
|
}
|
||||||
|
progress.fetch_add(records / BUCKETS, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
let keys_len = keys.len() as u64;
|
||||||
|
file.write_all(&keys)?;
|
||||||
|
drop(keys);
|
||||||
|
let mut games = games.into_inner().map_err(|e| e.into_error())?;
|
||||||
|
{
|
||||||
|
use std::io::Seek;
|
||||||
|
games.seek(io::SeekFrom::Start(0))?;
|
||||||
|
io::copy(&mut games, &mut file)?;
|
||||||
|
}
|
||||||
|
drop(games);
|
||||||
|
let _ = std::fs::remove_file(&games_path);
|
||||||
|
let mut file = file.into_inner().map_err(|e| e.into_error())?;
|
||||||
|
{
|
||||||
|
use std::io::Seek;
|
||||||
|
file.seek(io::SeekFrom::Start(16))?;
|
||||||
|
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.sync_all()?;
|
||||||
|
drop(file);
|
||||||
|
std::fs::rename(&part, out)?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn varint(out: &mut Vec<u8>, mut v: u32) {
|
||||||
|
while v >= 0x80 {
|
||||||
|
out.push((v as u8) | 0x80);
|
||||||
|
v >>= 7;
|
||||||
|
}
|
||||||
|
out.push(v as u8);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_varint(bytes: &[u8], at: &mut usize) -> Option<u32> {
|
||||||
|
let mut v = 0u32;
|
||||||
|
let mut shift = 0;
|
||||||
|
loop {
|
||||||
|
let b = *bytes.get(*at)?;
|
||||||
|
*at += 1;
|
||||||
|
v |= u32::from(b & 0x7f) << shift;
|
||||||
|
if b & 0x80 == 0 {
|
||||||
|
return Some(v);
|
||||||
|
}
|
||||||
|
shift += 7;
|
||||||
|
if shift > 28 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Size of a key record: key (8), offset into the games (5), count (4).
|
||||||
|
const KEY: usize = 17;
|
||||||
|
|
||||||
|
/// The index in memory: the file's bytes and where its sections are.
|
||||||
|
pub struct Index {
|
||||||
|
bytes: Vec<u8>,
|
||||||
|
records: usize,
|
||||||
|
prefix: std::ops::Range<usize>,
|
||||||
|
keys: std::ops::Range<usize>,
|
||||||
|
games: std::ops::Range<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Index {
|
||||||
|
/// Size of the index file (what loading it takes in memory), if it is there.
|
||||||
|
pub fn file_size(path: &Path) -> Option<u64> {
|
||||||
|
std::fs::metadata(path).ok().map(|m| m.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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)?;
|
||||||
|
if &head[..8] != MAGIC {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let u32_at = |at: usize| -> Option<u64> {
|
||||||
|
Some(u64::from(u32::from_le_bytes(
|
||||||
|
head[at..at + 4].try_into().ok()?,
|
||||||
|
)))
|
||||||
|
};
|
||||||
|
let u64_at = |at: usize| -> Option<usize> {
|
||||||
|
Some(u64::from_le_bytes(head[at..at + 8].try_into().ok()?) as usize)
|
||||||
|
};
|
||||||
|
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 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 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(Index {
|
||||||
|
bytes,
|
||||||
|
records,
|
||||||
|
prefix,
|
||||||
|
keys,
|
||||||
|
games,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn memory(&self) -> usize {
|
||||||
|
self.bytes.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn positions(&self) -> usize {
|
||||||
|
self.keys.len() / KEY
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key_at(&self, i: usize) -> u64 {
|
||||||
|
let at = self.keys.start + i * KEY;
|
||||||
|
u64::from_le_bytes(self.bytes[at..at + 8].try_into().expect("8 bytes"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where `key` is among the keys, if it is.
|
||||||
|
fn find(&self, key: u64) -> Option<usize> {
|
||||||
|
let n = self.positions();
|
||||||
|
let (mut lo, mut hi) = (0, n);
|
||||||
|
while lo < hi {
|
||||||
|
let mid = (lo + hi) / 2;
|
||||||
|
if self.key_at(mid) < key {
|
||||||
|
lo = mid + 1;
|
||||||
|
} else {
|
||||||
|
hi = mid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(lo < n && self.key_at(lo) == key).then_some(lo)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Number of games that reach the position with `key` within the opening.
|
||||||
|
pub fn count(&self, key: u64) -> usize {
|
||||||
|
self.find(key).map_or(0, |i| {
|
||||||
|
let at = self.keys.start + i * KEY + 13;
|
||||||
|
u32::from_le_bytes(self.bytes[at..at + 4].try_into().expect("4 bytes")) as usize
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The games of the position with `key`: (record index, ply), ascending.
|
||||||
|
fn games_of(&self, key: u64) -> Vec<(u32, u8)> {
|
||||||
|
let Some(lo) = self.find(key) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let at = self.keys.start + lo * KEY + 8;
|
||||||
|
let mut off = [0u8; 8];
|
||||||
|
off[..5].copy_from_slice(&self.bytes[at..at + 5]);
|
||||||
|
let offset = u64::from_le_bytes(off) as usize;
|
||||||
|
let count = u32::from_le_bytes(self.bytes[at + 5..at + 9].try_into().expect("4 bytes"));
|
||||||
|
let games = &self.bytes[self.games.clone()];
|
||||||
|
let mut out = Vec::with_capacity(count as usize);
|
||||||
|
let mut pos = offset;
|
||||||
|
let mut last = 0u32;
|
||||||
|
for i in 0..count {
|
||||||
|
let Some(delta) = read_varint(games, &mut pos) else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
let game = if i == 0 { delta } else { last + 1 + delta };
|
||||||
|
let Some(&ply) = games.get(pos) else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
pos += 1;
|
||||||
|
out.push((game, ply));
|
||||||
|
last = game;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first `PREFIX` moves of a game (`END`-padded).
|
||||||
|
fn prefix_of(&self, game: u32) -> [u16; PREFIX] {
|
||||||
|
let at = self.prefix.start + game as usize * PREFIX * 2;
|
||||||
|
let mut out = [END; PREFIX];
|
||||||
|
for (i, m) in out.iter_mut().enumerate() {
|
||||||
|
let b = at + i * 2;
|
||||||
|
*m = u16::from_le_bytes([self.bytes[b], self.bytes[b + 1]]);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the index should answer `query`: a position reached from the usual
|
||||||
|
/// start by at most `PLIES` moves (then every game that reaches it within the
|
||||||
|
/// opening is in the index), unless `candidates` are so few against the games of
|
||||||
|
/// the position that walking them is cheaper than decoding its list.
|
||||||
|
pub fn answers(&self, query: &PositionQuery, candidates: Option<&[u32]>) -> bool {
|
||||||
|
let opening = query
|
||||||
|
.line
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|l| l.len() <= PLIES && self.records > 0);
|
||||||
|
opening && candidates.is_none_or(|c| c.len() * 32 >= self.count(query.key()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records `games` (record index, ply) that reach the position: what each played
|
||||||
|
/// next and its result, ratings and year.
|
||||||
|
fn tally(&self, base: &Base, games: &[(u32, u8)], line: &[u16]) -> Collector {
|
||||||
|
let mut out = Collector::default();
|
||||||
|
for &(game, ply) in games {
|
||||||
|
let prefix = self.prefix_of(game);
|
||||||
|
let ply = usize::from(ply);
|
||||||
|
let same_order = ply == line.len() && prefix[..ply] == line[..];
|
||||||
|
let next = decode(prefix[ply]);
|
||||||
|
let r = base.record(game as usize);
|
||||||
|
let u = |at, n| super::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: game,
|
||||||
|
ply: ply as u32,
|
||||||
|
same_order,
|
||||||
|
in_variation: false,
|
||||||
|
next: None,
|
||||||
|
},
|
||||||
|
next,
|
||||||
|
result,
|
||||||
|
u(0x1f, 2) as u16,
|
||||||
|
u(0x21, 2) as u16,
|
||||||
|
year,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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(
|
||||||
|
&self,
|
||||||
|
base: &Base,
|
||||||
|
candidates: Option<&[u32]>,
|
||||||
|
query: &PositionQuery,
|
||||||
|
) -> PositionOutcome {
|
||||||
|
let line: Vec<u16> = query
|
||||||
|
.line
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.iter()
|
||||||
|
.map(|m| encode(uci(m)))
|
||||||
|
.collect();
|
||||||
|
// The games asked for, in record order.
|
||||||
|
let mut games = self.games_of(query.key());
|
||||||
|
if let Some(c) = candidates {
|
||||||
|
let mut i = 0;
|
||||||
|
games.retain(|&(g, _)| {
|
||||||
|
while i < c.len() && c[i] < g {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
i < c.len() && c[i] == g
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Millions of games for an early position: tallied in parallel, each part
|
||||||
|
// keeping its order.
|
||||||
|
let threads = std::thread::available_parallelism()
|
||||||
|
.map_or(1, |n| n.get())
|
||||||
|
.min(games.len().div_ceil(1 << 16))
|
||||||
|
.max(1);
|
||||||
|
let chunk = games.len().div_ceil(threads).max(1);
|
||||||
|
let line = &line;
|
||||||
|
let parts: Vec<Collector> = std::thread::scope(|s| {
|
||||||
|
let handles: Vec<_> = games
|
||||||
|
.chunks(chunk)
|
||||||
|
.map(|part| s.spawn(move || self.tally(base, part, line)))
|
||||||
|
.collect();
|
||||||
|
handles
|
||||||
|
.into_iter()
|
||||||
|
.map(|h| h.join().unwrap_or_default())
|
||||||
|
.collect()
|
||||||
|
});
|
||||||
|
let mut out = Collector::default();
|
||||||
|
for part in parts {
|
||||||
|
out.merge(part);
|
||||||
|
}
|
||||||
|
out.finish(&query.position)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -43,6 +43,16 @@ pub fn search(
|
||||||
cancel: &AtomicBool,
|
cancel: &AtomicBool,
|
||||||
) -> Option<PositionOutcome> {
|
) -> Option<PositionOutcome> {
|
||||||
let total = candidates.map_or(base.records(), <[u32]>::len);
|
let total = candidates.map_or(base.records(), <[u32]>::len);
|
||||||
|
// A position of the opening: the index knows its games.
|
||||||
|
if let Some(index) = base.openings()
|
||||||
|
&& index.answers(query, candidates)
|
||||||
|
{
|
||||||
|
if cancel.load(Ordering::Relaxed) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
scanned.fetch_add(total, Ordering::Relaxed);
|
||||||
|
return Some(index.search(base, candidates, query));
|
||||||
|
}
|
||||||
let target = Target::new(query);
|
let target = Target::new(query);
|
||||||
let cbb = base
|
let cbb = base
|
||||||
.cbb_path()
|
.cbb_path()
|
||||||
|
|
@ -512,11 +522,11 @@ fn read_record(f: &File, offset: u32, buf: &mut Vec<u8>) -> usize {
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::position::Tally;
|
||||||
use shakmaty::san::SanPlus;
|
use shakmaty::san::SanPlus;
|
||||||
use shakmaty::{CastlingMode, EnPassantMode, FromSetup, Move, fen::Fen};
|
use shakmaty::{CastlingMode, EnPassantMode, FromSetup, Move, fen::Fen};
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// A sample `.cbv` unpacked into a fresh temporary directory (removed on drop).
|
/// A sample `.cbv` unpacked into a fresh temporary directory (removed on drop).
|
||||||
struct Sample {
|
struct Sample {
|
||||||
dir: PathBuf,
|
dir: PathBuf,
|
||||||
|
|
@ -978,6 +988,211 @@ mod tests {
|
||||||
assert_eq!(differ, 0);
|
assert_eq!(differ, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Everything of an outcome that the index must reproduce.
|
||||||
|
fn full(out: &PositionOutcome) -> (Vec<Match>, Vec<(UciMove, Tally)>, Tally) {
|
||||||
|
(
|
||||||
|
out.matches.clone(),
|
||||||
|
out.moves.iter().map(|m| (m.uci, m.tally.clone())).collect(),
|
||||||
|
out.ended.clone(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn opening_index_matches_the_pass() {
|
||||||
|
let Some(sample) = Sample::unpack("Anand 01-14.cbv") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let base = sample.open();
|
||||||
|
let dir = sample.dir.join("cache");
|
||||||
|
base.set_booster_dir(&dir);
|
||||||
|
assert!(base.prepare_wanted());
|
||||||
|
let progress = AtomicUsize::new(0);
|
||||||
|
assert!(
|
||||||
|
base.prepare(&progress, &AtomicBool::new(false))
|
||||||
|
.expect("prepares")
|
||||||
|
);
|
||||||
|
assert!(progress.load(Ordering::Relaxed) >= base.records());
|
||||||
|
let Some(index) = base.openings() else {
|
||||||
|
eprintln!("skipped: no memory for the index");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert!(index.positions() > 0 && !base.prepare_wanted());
|
||||||
|
let plain = sample.open();
|
||||||
|
assert!(plain.openings().is_none());
|
||||||
|
let lines: Vec<_> = (0..base.records()).map(|i| oracle_line(&base, i)).collect();
|
||||||
|
let every_third: Vec<u32> = (0..base.records() as u32).step_by(3).collect();
|
||||||
|
let mut checked = 0;
|
||||||
|
for line in lines.iter().flatten().step_by(23) {
|
||||||
|
for ply in [0, 1, 3, 6, super::super::openings::PLIES] {
|
||||||
|
let Some((pos, _)) = line.get(ply) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let moves: Vec<Move> = line[..ply]
|
||||||
|
.iter()
|
||||||
|
.scan(Chess::default(), |p, (_, m)| {
|
||||||
|
let m = m.as_ref()?.to_move(p).ok()?;
|
||||||
|
p.play_unchecked(m);
|
||||||
|
Some(m)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if moves.len() != ply {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let query = PositionQuery::new(pos.clone(), Some(moves));
|
||||||
|
assert!(index.answers(&query, None));
|
||||||
|
for cands in [None, Some(every_third.as_slice())] {
|
||||||
|
let fast = run(&base, cands, &query);
|
||||||
|
let slow = run(&plain, cands, &query);
|
||||||
|
assert_eq!(full(&fast), full(&slow), "ply {ply}");
|
||||||
|
checked += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(checked > 10, "{checked} queries");
|
||||||
|
// Deeper than the index: the pass answers.
|
||||||
|
let line = lines
|
||||||
|
.iter()
|
||||||
|
.flatten()
|
||||||
|
.find(|l| l.len() > 20)
|
||||||
|
.expect("a game");
|
||||||
|
let deep = PositionQuery::new(line[15].0.clone(), None);
|
||||||
|
assert!(!index.answers(&deep, None));
|
||||||
|
// Opened again: the index on disk is loaded without a build.
|
||||||
|
let again = sample.open();
|
||||||
|
again.set_booster_dir(&dir);
|
||||||
|
let progress = AtomicUsize::new(0);
|
||||||
|
assert!(
|
||||||
|
again
|
||||||
|
.prepare(&progress, &AtomicBool::new(false))
|
||||||
|
.expect("loads")
|
||||||
|
);
|
||||||
|
assert_eq!(progress.load(Ordering::Relaxed), 0);
|
||||||
|
assert!(again.openings().is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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`.
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn mega_openings() {
|
||||||
|
use super::super::base::{Filter, NameFilter, OpeningsStatus, SortKey};
|
||||||
|
use std::time::Instant;
|
||||||
|
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-openings-{}", std::process::id()));
|
||||||
|
base.set_booster_dir(&dir);
|
||||||
|
let t = Instant::now();
|
||||||
|
let progress = AtomicUsize::new(0);
|
||||||
|
assert!(
|
||||||
|
base.prepare(&progress, &AtomicBool::new(false))
|
||||||
|
.expect("prepares")
|
||||||
|
);
|
||||||
|
eprintln!(
|
||||||
|
"prepared in {:.2?}: {:?}, peak memory {}",
|
||||||
|
t.elapsed(),
|
||||||
|
base.openings_status(),
|
||||||
|
peak_memory()
|
||||||
|
);
|
||||||
|
let index = base.openings().expect("loaded");
|
||||||
|
eprintln!(
|
||||||
|
"{} positions, {} MB",
|
||||||
|
index.positions(),
|
||||||
|
index.memory() / 1_000_000
|
||||||
|
);
|
||||||
|
let plain = Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens");
|
||||||
|
let never = AtomicBool::new(false);
|
||||||
|
let carlsen = plain
|
||||||
|
.query(
|
||||||
|
&Filter {
|
||||||
|
player: NameFilter {
|
||||||
|
text: "carlsen, magnus".into(),
|
||||||
|
..NameFilter::default()
|
||||||
|
},
|
||||||
|
..Filter::default()
|
||||||
|
},
|
||||||
|
SortKey::Number,
|
||||||
|
true,
|
||||||
|
&AtomicUsize::new(0),
|
||||||
|
&never,
|
||||||
|
)
|
||||||
|
.expect("query");
|
||||||
|
for (name, line) in [
|
||||||
|
("start", ""),
|
||||||
|
("1.e4", "e4"),
|
||||||
|
("1.d4 Nf6 2.c4 e6", "d4 Nf6 c4 e6"),
|
||||||
|
("Najdorf", "e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6"),
|
||||||
|
] {
|
||||||
|
let (pos, moves) = san_line(line);
|
||||||
|
let query = PositionQuery::new(pos, Some(moves));
|
||||||
|
for cands in [None, Some(carlsen.as_slice())] {
|
||||||
|
let t = Instant::now();
|
||||||
|
let fast = run(&base, cands, &query);
|
||||||
|
let fast_ms = t.elapsed().as_secs_f64() * 1e3;
|
||||||
|
let t = Instant::now();
|
||||||
|
let slow = run(&plain, cands, &query);
|
||||||
|
let slow_ms = t.elapsed().as_secs_f64() * 1e3;
|
||||||
|
let same = |o: &PositionOutcome| o.matches.iter().filter(|m| m.same_order).count();
|
||||||
|
eprintln!(
|
||||||
|
"{name:18} {:8}: index {:9} games ({:9} same order) {fast_ms:8.1} ms · pass {:9} games ({:9} same order) {slow_ms:8.1} ms · ended {} / {}",
|
||||||
|
if cands.is_some() { "Carlsen" } else { "all" },
|
||||||
|
fast.matches.len(),
|
||||||
|
same(&fast),
|
||||||
|
slow.matches.len(),
|
||||||
|
same(&slow),
|
||||||
|
fast.ended.games,
|
||||||
|
slow.ended.games
|
||||||
|
);
|
||||||
|
// Both lists are in record order: one merge tells the differences.
|
||||||
|
let (mut missing, mut extra) = (0, 0);
|
||||||
|
let (mut i, mut j) = (0, 0);
|
||||||
|
while i < slow.matches.len() || j < fast.matches.len() {
|
||||||
|
match (slow.matches.get(i), fast.matches.get(j)) {
|
||||||
|
(Some(a), Some(b)) if a == b => {
|
||||||
|
i += 1;
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
(Some(a), Some(b)) if a.index < b.index => {
|
||||||
|
missing += 1;
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
(Some(a), Some(b)) if a.index > b.index => {
|
||||||
|
extra += 1;
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
(Some(_), Some(_)) => {
|
||||||
|
// Same game, different details.
|
||||||
|
missing += 1;
|
||||||
|
extra += 1;
|
||||||
|
i += 1;
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
(Some(_), None) => {
|
||||||
|
missing += 1;
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
(None, _) => {
|
||||||
|
extra += 1;
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if missing + extra > 0 {
|
||||||
|
eprintln!(" differ: {missing} only in the pass, {extra} only in the index");
|
||||||
|
}
|
||||||
|
assert!(matches!(base.openings_status(), OpeningsStatus::Loaded(_)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
eprintln!("peak memory {}", peak_memory());
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
/// Mega Database 2026 (not in the repository): builds our booster for the whole
|
/// 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
|
/// 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`.
|
/// `cargo test --release -p chess-import mega_build_booster -- --ignored --nocapture`.
|
||||||
|
|
|
||||||
|
|
@ -105,7 +105,26 @@ impl PgnDb {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The position table, built on first use. `None` when cancelled.
|
/// Memory the position table would need, built: about 20 bytes per position
|
||||||
|
/// and, while it is built, two to three times that (`docs/dev/import.md`),
|
||||||
|
/// estimated from the size of the PGN text (a move is some six bytes of it).
|
||||||
|
pub fn positions_estimate(&self) -> u64 {
|
||||||
|
self.db.byte_len() as u64 * 10
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why the position table cannot be built now: the memory it would need
|
||||||
|
/// ([`PgnDb::positions_estimate`]) is not there. `None` once it is built.
|
||||||
|
pub fn positions_blocked(&self) -> Option<u64> {
|
||||||
|
if self.positions.lock().ok()?.is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let need = self.positions_estimate();
|
||||||
|
let room = memory::available().is_some_and(|free| free >= need + (256 << 20));
|
||||||
|
(!room).then_some(need)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The position table, built on first use. `None` when cancelled, or when the
|
||||||
|
/// machine has no memory for it ([`PgnDb::positions_blocked`]).
|
||||||
pub(crate) fn positions(
|
pub(crate) fn positions(
|
||||||
&self,
|
&self,
|
||||||
progress: &AtomicUsize,
|
progress: &AtomicUsize,
|
||||||
|
|
@ -114,6 +133,9 @@ impl PgnDb {
|
||||||
if let Some(t) = self.positions.lock().ok()?.as_ref() {
|
if let Some(t) = self.positions.lock().ok()?.as_ref() {
|
||||||
return Some(t.clone());
|
return Some(t.clone());
|
||||||
}
|
}
|
||||||
|
if self.positions_blocked().is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
let table = Arc::new(pgn_positions::PositionTable::build(
|
let table = Arc::new(pgn_positions::PositionTable::build(
|
||||||
&self.db, progress, cancel,
|
&self.db, progress, cancel,
|
||||||
)?);
|
)?);
|
||||||
|
|
@ -220,6 +242,15 @@ impl Database {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Memory a position search would need first and does not have (a PGN
|
||||||
|
/// database's table, see [`PgnDb::positions_blocked`]).
|
||||||
|
pub fn positions_blocked(&self) -> Option<u64> {
|
||||||
|
match self {
|
||||||
|
Database::Pgn(db) => db.positions_blocked(),
|
||||||
|
Database::ChessBase(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn as_chessbase(&self) -> Option<&Base> {
|
pub fn as_chessbase(&self) -> Option<&Base> {
|
||||||
match self {
|
match self {
|
||||||
Database::ChessBase(b) => Some(b),
|
Database::ChessBase(b) => Some(b),
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,16 @@ fn system() -> System {
|
||||||
|
|
||||||
/// Bytes of memory the system reports as available to new allocations without
|
/// Bytes of memory the system reports as available to new allocations without
|
||||||
/// swapping (Linux `MemAvailable`; the other systems' equivalent). `None` when unknown.
|
/// swapping (Linux `MemAvailable`; the other systems' equivalent). `None` when unknown.
|
||||||
|
/// `CP_MEMORY_LIMIT=<MB>` caps it (a dev hook: the low-memory paths on a big machine).
|
||||||
pub fn available() -> Option<u64> {
|
pub fn available() -> Option<u64> {
|
||||||
Some(system().available_memory()).filter(|n| *n > 0)
|
let real = Some(system().available_memory()).filter(|n| *n > 0);
|
||||||
|
match std::env::var("CP_MEMORY_LIMIT")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.trim().parse::<u64>().ok())
|
||||||
|
{
|
||||||
|
Some(limit) => Some(real.unwrap_or(u64::MAX).min(limit * 1_000_000)),
|
||||||
|
None => real,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bytes of physical memory.
|
/// Bytes of physical memory.
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `app.rs` | Состояние верхнего уровня: библиотека ⇄ партия, настройки, движок, фоновые диалоги (rfd в отдельных потоках), подтверждение закрытия изменённой партии |
|
| `app.rs` | Состояние верхнего уровня: библиотека ⇄ партия, настройки, движок, фоновые диалоги (rfd в отдельных потоках), подтверждение закрытия изменённой партии |
|
||||||
| `library.rs` | Полка баз, фоновое открытие через `chess_import::open` (PGN, ChessBase, архивы; прогресс, отмена), формат и «Замечания импорта» по каждой базе, таблица с поиском, сортировкой, клавиатурой |
|
| `library.rs` | Полка баз, фоновое открытие через `chess_import::open` (PGN, ChessBase, архивы; прогресс, отмена), формат и «Замечания импорта» по каждой базе, таблица с поиском, сортировкой, клавиатурой |
|
||||||
| `large_db.rs` | Большая база ChessBase: панель фильтров справа (игроки с подсказками, турнир, годы, Эло, результат, ECO, ходы, аннотации), фоновые проходы с отменой и задержкой 250 мс для текста, счётчик и прогресс, таблица из записей `.cbh`; компоновка — `docs/design/large-databases.md`; переключатель `[Фильтры | Доска]`, строка условий (чипы), колонка «Ход», «только этот порядок», «сильнейшие сверху»; без пригодного `.cbb` при открытой доске в фоне строится свой ускоритель поиска (`Base::build_booster`, каталог кэша `boosters/`) со строкой прогресса над доской |
|
| `large_db.rs` | Большая база ChessBase: панель фильтров справа (игроки с подсказками, турнир, годы, Эло, результат, ECO, ходы, аннотации), фоновые проходы с отменой и задержкой 250 мс для текста, счётчик и прогресс, таблица из записей `.cbh`; компоновка — `docs/design/large-databases.md`; переключатель `[Фильтры | Доска]`, строка условий (чипы), колонка «Ход», «только этот порядок», «сильнейшие сверху»; при открытой доске в фоне строится, чего не хватает для быстрого поиска (`Base::prepare`: свой ускоритель без пригодного `.cbb`, дебютный индекс при достаточной памяти; каталог кэша `boosters/`) со строкой прогресса над доской |
|
||||||
| `board_search.rs` | Доска поиска по позиции (решение 13, `docs/design/board-search.md`): ввод ходов, линия с переходами по ходам, продолжения со статистикой (полоса Б/Н/Ч, средний Эло, год; для книг — «N глав»), клавиши ←/→/Home/End/Backspace/1–9/F/Ctrl+Backspace, «Вернуть» после сброса, фоновые задачи `Background` с отменой |
|
| `board_search.rs` | Доска поиска по позиции (решение 13, `docs/design/board-search.md`): ввод ходов, линия с переходами по ходам, продолжения со статистикой (полоса Б/Н/Ч, средний Эло, год; для книг — «N глав»), клавиши ←/→/Home/End/Backspace/1–9/F/Ctrl+Backspace, «Вернуть» после сброса, фоновые задачи `Background` с отменой |
|
||||||
| `game_view.rs` | Экран партии: доска, шкала оценки, панель анализа, предпросмотр PV, нотация, панель инструментов, клавиатура |
|
| `game_view.rs` | Экран партии: доска, шкала оценки, панель анализа, предпросмотр PV, нотация, панель инструментов, клавиатура |
|
||||||
| `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках |
|
| `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках |
|
||||||
|
|
@ -42,7 +42,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe
|
||||||
```
|
```
|
||||||
|
|
||||||
`CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии,
|
`CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии,
|
||||||
`CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»).
|
`CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN).
|
||||||
|
|
||||||
## Языки
|
## Языки
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -99,6 +99,20 @@
|
||||||
|
|
||||||
На файлах пользователя (`pgnFilesforExample/`: 3 `.cbv` и 4 книги в `.7z`, всего ≈1900 записей) ни одной ошибки декодирования; все партии читаются обратно PGN-парсером без предупреждений (`tests/samples.rs`).
|
На файлах пользователя (`pgnFilesforExample/`: 3 `.cbv` и 4 книги в `.7z`, всего ≈1900 записей) ни одной ошибки декодирования; все партии читаются обратно PGN-парсером без предупреждений (`tests/samples.rs`).
|
||||||
|
|
||||||
|
## Дебютный индекс (большие базы)
|
||||||
|
|
||||||
|
`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-дельтой и полуход). Партия, проходящая позицию дважды в дебюте, записана на первом полуходе. Партии с заданной позиции и нечитаемые записей не имеют.
|
||||||
|
|
||||||
|
Строится тем же проходом, что и ускоритель (`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 ГБ.
|
||||||
|
|
||||||
|
**Память.** `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=<МБ>` ограничивает «доступную память» для проверки этих путей.
|
||||||
|
|
||||||
|
**Запрос** (`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`).
|
||||||
|
|
||||||
|
**Замеры** (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 мс.
|
||||||
|
|
||||||
## Замер на другой машине
|
## Замер на другой машине
|
||||||
|
|
||||||
`chesspenguin --bench <база> [отчёт.txt]` (`crates/chess-import/src/bench.rs`) печатает отчёт вместо окна: система, потоки, память (всего / доступно, `memory.rs` через `sysinfo`), время открытия, для базы ChessBase — ускоритель (есть / построен за N с / нет), фильтр по игроку и сортировка всей базы, поиск пяти позиций (начальная, 1.e4, Найдорф, Нимцович на 20-м полуходе, испанская на 40-м) дважды подряд — первый прогон показывает холодный файловый кэш, второй тёплый — и среди партий игрока; для PGN — построение таблицы позиций и те же поиски. На Windows релизная сборка без консоли, поэтому там нужен второй аргумент с файлом отчёта. Ничего в базу не пишется; свой ускоритель, если он нужен, строится в кэше приложения, как и в окне. Так сравниваются ноутбуки с числами выше (i7-13700KF, 24 потока): на нём Mega открывается за 0,55 с, фильтр по Карлсену 46 мс, сортировка всей базы по белым 0,39 с, начальная позиция 0,39 с, Найдорф 80 мс, глубокие позиции 16–21 мс, среди партий Карлсена 1–5 мс.
|
`chesspenguin --bench <база> [отчёт.txt]` (`crates/chess-import/src/bench.rs`) печатает отчёт вместо окна: система, потоки, память (всего / доступно, `memory.rs` через `sysinfo`), время открытия, для базы ChessBase — ускоритель (есть / построен за N с / нет), фильтр по игроку и сортировка всей базы, поиск пяти позиций (начальная, 1.e4, Найдорф, Нимцович на 20-м полуходе, испанская на 40-м) дважды подряд — первый прогон показывает холодный файловый кэш, второй тёплый — и среди партий игрока; для PGN — построение таблицы позиций и те же поиски. На Windows релизная сборка без консоли, поэтому там нужен второй аргумент с файлом отчёта. Ничего в базу не пишется; свой ускоритель, если он нужен, строится в кэше приложения, как и в окне. Так сравниваются ноутбуки с числами выше (i7-13700KF, 24 потока): на нём Mega открывается за 0,55 с, фильтр по Карлсену 46 мс, сортировка всей базы по белым 0,39 с, начальная позиция 0,39 с, Найдорф 80 мс, глубокие позиции 16–21 мс, среди партий Карлсена 1–5 мс.
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue