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

@ -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`.