diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 882765d3..0b499e77 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -97,9 +97,13 @@ jobs: if: matrix.os == 'ubuntu-latest' env: CBVAULT_NO_MMAP: "1" - run: cargo test -p cbvault --all-features --test twocbh_bridge --test twocbh_parallel_sink --test twocbh_annotation_fail_closed + run: cargo test -p cbvault --all-features --test twocbh_bridge --test twocbh_parallel_sink --test twocbh_annotation_fail_closed --test query_position + - name: Private oracle checker generated negative controls + if: matrix.os == 'ubuntu-latest' + run: python3 scripts/test-query-private-acceptance.py + - name: Cargo fmt run: cargo fmt --all --check diff --git a/.github/workflows/native-bench.yml b/.github/workflows/native-bench.yml index dfa4bfa5..84c1fc9d 100644 --- a/.github/workflows/native-bench.yml +++ b/.github/workflows/native-bench.yml @@ -43,6 +43,8 @@ jobs: needed += 4 * 1024**3 elif os.environ["TIER"] == "standard": needed += 2 * 1024**3 + if os.environ.get("GITHUB_HEAD_REF") == "integration/position-search-pr11": + needed += 2 * 1024**3 # contributor comparison build assert shutil.disk_usage(os.environ["RUNNER_TEMP"]).free >= needed, "insufficient runner disk" PY - uses: actions/checkout@v4 @@ -78,6 +80,48 @@ jobs: mkdir -p benchmark-report { rustc --version; uname -a; lscpu; echo "base=${{ steps.corpus.outputs.baseline }}"; git rev-parse HEAD; } > benchmark-report/environment.txt python3 scripts/bench-corpus/native-bench.py --tier "$TIER" --fixtures "$RUNNER_TEMP/native" --base "$RUNNER_TEMP/base-target/release/cbvault" --head "$RUNNER_TEMP/head-target/release/cbvault" --base-workload "$RUNNER_TEMP/base-target/release/examples/native_workload" --head-workload "$RUNNER_TEMP/head-target/release/examples/native_workload" --report benchmark-report/results.json --repetitions 5 + - uses: actions/checkout@v4 + if: github.head_ref == 'integration/position-search-pr11' + with: + ref: 0c6e42642eb06809bb2a114f6fd81059f1573adc + path: position-reference-src + persist-credentials: false + - name: Build original position-search contributor revision + if: github.head_ref == 'integration/position-search-pr11' + run: | + cargo +1.97.1 build --locked --release -p cbvault-cli --manifest-path position-reference-src/Cargo.toml --target-dir "$RUNNER_TEMP/position-reference-target" + - name: Position search correctness and timing diagnostics + if: matrix.tier == 'smoke' || matrix.tier == 'extreme' + run: | + reference=() + if [[ -x "$RUNNER_TEMP/position-reference-target/release/cbvault" ]]; then + reference=(--reference-cli "$RUNNER_TEMP/position-reference-target/release/cbvault") + echo "position-reference=0c6e42642eb06809bb2a114f6fd81059f1573adc" >> benchmark-report/environment.txt + fi + python3 scripts/bench-corpus/position-bench.py --tier "$TIER" --fixtures "$RUNNER_TEMP/native" --cli "$RUNNER_TEMP/head-target/release/cbvault" --report benchmark-report/position-search.json "${reference[@]}" + - name: Independent PGN fragment matcher and controlled ChessBase fixtures + if: matrix.tier == 'smoke' + run: | + python3 -m venv "$RUNNER_TEMP/audit-venv" + "$RUNNER_TEMP/audit-venv/bin/pip" install --no-cache-dir -r scripts/requirements-position-audit.txt + audit="$RUNNER_TEMP/audit-venv/bin/python" + "$audit" scripts/test-position-audit.py + "$audit" scripts/position-audit.py fixture --out benchmark-report/controlled-position-fixture + for ext in cbh 2cbh; do + db="$RUNNER_TEMP/native/realistic-25000.$ext" + cli="$RUNNER_TEMP/head-target/release/cbvault" + "$cli" pgn "$db" "$RUNNER_TEMP/audit-$ext.pgn" --from 1 --to 512 --threads 1 + "$audit" scripts/position-audit.py oracle --pgn "$RUNNER_TEMP/audit-$ext.pgn" --first-id 1 --expected-games 512 --controlled --cli "$cli" --db "$db" --out "benchmark-report/independent-$ext" + done + - name: Independent exact-key replay and audit-tool end-to-end checks + if: matrix.tier == 'smoke' + run: | + cargo +1.97.1 build --locked --release -p cbvault --example exact_position_ids --target-dir "$RUNNER_TEMP/head-target" + reference=() + if [[ -x "$RUNNER_TEMP/position-reference-target/release/cbvault" ]]; then + reference=(--contributor "$RUNNER_TEMP/position-reference-target/release/cbvault") + fi + "$RUNNER_TEMP/audit-venv/bin/python" scripts/test-position-public.py --cli "$RUNNER_TEMP/head-target/release/cbvault" --exact "$RUNNER_TEMP/head-target/release/examples/exact_position_ids" --fixtures "$RUNNER_TEMP/native" --out benchmark-report/public-exact-audit "${reference[@]}" - uses: actions/upload-artifact@v4 if: always() with: diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ce28f75..6b3772a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 The project is pre-1.0. +## [Unreleased] + +### Added + +- **The "Position" page of the search.** `GameDataQuery::position` takes a `PositionQuery`: "Look for", "Or" and "Exclude" boards of men (a piece, or a joker for any man of a colour), horizontal and vertical mirrors, and First, Length and Last with the dialog's defaults; it combines with every "Game data" field. The fragment compiles to bitboards and is tested on each main-line position in the same replay as mate, stalemate and check, which stops as soon as the answer is known. "Sacrifice" is refused as unsupported. `cbvault search` gains `--look-for`, `--or`, `--exclude`, `--mirror`, `--first-move`, `--length` and `--last-move`; `parse_fragment` reads the same board text (`Kg1 Rf1 Pf2g2h2 bh7`). + ## [0.3.0] - 2026-11-30 ### Breaking diff --git a/README.md b/README.md index 9faca42c..689100b1 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ cbvault pgn "MyDatabase.2cbh" games.pgn --threads 8 cbvault archive list "Collection.cbv" cbvault archive extract "Collection.cbv" ./extracted --threads 8 cbvault search "MyDatabase.2cbh" --white "Carlsen, Magnus" --ignore-colours --elo 2700- --elo-mode both --pgn found.pgn +cbvault search "MyDatabase.2cbh" --look-for "Bh7 kg8" --mirror h --result 1-0 ``` The same database commands also work with classic `.cbh` files; archive commands accept `.cbz` with `--password`. The CLI can emit machine-readable JSON and redirect PGN to stdout. @@ -83,7 +84,7 @@ cbvault book verify "MyBook.ctg" --children --json **Direct database browsing.** List games, inspect player/event metadata, open a game with its annotations and variations, or export a selected record to PGN. Headers can be read independently of move decoding. -**Search and preparation.** Filter by players, ECO, result, year, rating or round. `cbvault::query` and `cbvault search` support composable ChessBase-style Game data criteria: names with "ignore colours" and "wins only", tournament, annotator, date and ECO ranges, move count, Elo in each mode with a rating difference, results including mate, stalemate and check, guiding texts, "any text" and native 2CBH time control ([docs/search.md](docs/search.md)). Resolve multiple matching player IDs instead of silently picking one. Scan positions with legal replay, stop when enough results are found, or generate Polyglot keys for a separate opening index. +**Search and preparation.** Filter by players, ECO, result, year, rating or round. `cbvault::query` and `cbvault search` support composable ChessBase-style Game data criteria: names with "ignore colours" and "wins only", tournament, annotator, date and ECO ranges, move count, Elo in each mode with a rating difference, results including mate, stalemate and check, guiding texts, "any text" and native 2CBH time control, combined with the Position page: partial positions on "Look for", "Or" and "Exclude" boards with jokers, mirrors and a window of moves ([docs/search.md](docs/search.md)). Resolve multiple matching player IDs instead of silently picking one. Scan positions with legal replay, stop when enough results are found, or generate Polyglot keys for a separate opening index. **High-throughput data pipelines.** Use `GameSink` with `for_each_game`, `for_each_range` or `convert_parallel`. Each callback receives borrowed game data; the sink can request moves, keys and/or native annotations as needed. Parallel processing **preserves source record order**, so consumers do not need to reorder games afterward. diff --git a/crates/cbvault-cli/src/search.rs b/crates/cbvault-cli/src/search.rs index f5901589..970debfb 100644 --- a/crates/cbvault-cli/src/search.rs +++ b/crates/cbvault-cli/src/search.rs @@ -1,5 +1,5 @@ -//! `cbvault search [options]`: the "Game data" page of ChessBase's search -//! dialog, as options. A thin shell over [`cbvault::query`]: it reads the +//! `cbvault search [options]`: the "Game data" and "Position" pages of +//! ChessBase's search dialog, as options. A thin shell over [`cbvault::query`]: it reads the //! options into a [`GameDataQuery`], runs it, and prints the count, the first //! matches, or their PGN. @@ -8,8 +8,8 @@ use std::time::Instant; use cbvault::bridge::{Database, Entity, GameBuf, ReadMode}; use cbvault::query::{ - AnyText, EloDifference, EloMode, EloQuery, GameDataQuery, PlayerName, SearchOptions, TextMatch, TextsMatch, - TimeControl, parse_range, + AnyText, EloDifference, EloMode, EloQuery, GameDataQuery, PlayerName, PositionQuery, PositionWindow, SearchOptions, + TextMatch, TextsMatch, TimeControl, parse_fragment, parse_range, }; use crate::json_str; @@ -28,10 +28,27 @@ criteria (the \"Game data\" page of ChessBase's search dialog; all must hold): --text search guiding texts instead of games --time-control classical|rapid|blitz|correspondence +position (the \"Position\" page; replays the main line of the games kept above): + --look-for BOARD --or BOARD --exclude BOARD + BOARD is men and squares: KQRBNP White, kqrbnp Black, X/x any white/black man, + e.g. \"Kg1 Rf1 Pf2g2h2 bh7\"; Or/Exclude may name a square more than once + --mirror h|v|hv also look for the fragment reflected top-bottom with the + colours swapped (h) or left-right (v) + --first-move N --length N --last-move N (defaults 1, 1, 40, as in ChessBase; + Length counts consecutive positions, i.e. plies; + as in ChessBase, the window runs from the start through + move max(Last, First+1), plus White's next move) + --position-window chessbase|strict strict counts only First through Last + The count and timings go to stderr; the matches (or --json) to stdout. --limit caps the listed matches (default 50, 0 = all); --pgn writes every match as PGN. --ids-only omits metadata; text output is one ID per line with JSON statistics on stderr."; +/// The query's "Position" page, created with the dialog's defaults. +fn position(query: &mut GameDataQuery) -> &mut PositionQuery { + query.position.get_or_insert_with(PositionQuery::default) +} + /// Runs `cbvault search`. pub(crate) fn run(mut args: impl Iterator) -> Result> { let mut db_path: Option = None; @@ -100,6 +117,29 @@ pub(crate) fn run(mut args: impl Iterator) -> Result return Err(format!("unknown --time-control {other:?}").into()), }) } + "--look-for" => position(&mut query).look_for = parse_fragment(&value("--look-for")?)?, + "--or" => position(&mut query).or = parse_fragment(&value("--or")?)?, + "--exclude" => position(&mut query).exclude = parse_fragment(&value("--exclude")?)?, + "--mirror" => { + let axes = value("--mirror")?; + if axes.is_empty() || !axes.chars().all(|c| c == 'h' || c == 'v') { + return Err(format!("unknown --mirror {axes:?}: use h, v or hv").into()); + } + let p = position(&mut query); + p.mirror_horizontal |= axes.contains('h'); + p.mirror_vertical |= axes.contains('v'); + } + "--first-move" => position(&mut query).first = value("--first-move")?.parse()?, + "--length" => position(&mut query).length = value("--length")?.parse()?, + "--last-move" => position(&mut query).last = value("--last-move")?.parse()?, + "--position-window" => { + position(&mut query).window = match value("--position-window")?.as_str() { + "chessbase" => PositionWindow::ChessBaseCompatible, + "strict" => PositionWindow::Strict, + other => return Err(format!("unknown --position-window {other:?}").into()), + }; + } + "--sacrifice" => position(&mut query).sacrifice = true, "--from" => options.first = value("--from")?.parse()?, "--to" => options.last = value("--to")?.parse()?, "--threads" => options.threads = value("--threads")?.parse()?, diff --git a/crates/cbvault-cli/tests/cli_search.rs b/crates/cbvault-cli/tests/cli_search.rs index 8a247c66..543f3c9a 100644 --- a/crates/cbvault-cli/tests/cli_search.rs +++ b/crates/cbvault-cli/tests/cli_search.rs @@ -126,3 +126,41 @@ fn id_only_export_is_ordered_and_has_exact_count() { assert!(json.starts_with("{\"matches\":3,")); assert!(json.contains("\"ids\":[1]")); } + +#[test] +fn position_options_reach_the_query() { + let temp = db("cli_search_position"); + // Every game is 1.e4 e5: the e-pawns meet on e4 and e5 on move 1. + let (ok, json) = search(&temp, &["--look-for", "Pe4 pe5", "--json"]); + assert!(ok); + assert!(json.starts_with("{\"matches\":3,"), "{json}"); + let (_, json) = search(&temp, &["--look-for", "Pe4", "--exclude", "pe5", "--length", "2", "--json"]); + assert!(json.starts_with("{\"matches\":0,"), "{json}"); + // d4 reflected left to right is e4. + let (_, json) = search(&temp, &["--look-for", "Pd4", "--white", "Carlsen", "--json"]); + assert!(json.starts_with("{\"matches\":0,"), "{json}"); + let (_, json) = search(&temp, &["--look-for", "Pd4", "--mirror", "v", "--white", "Carlsen", "--json"]); + assert!(json.starts_with("{\"matches\":1,") && json.contains("\"id\":3,"), "{json}"); + // The horizontal mirror swaps colours: a black pawn on e4 becomes a white + // pawn on e5, not the black pawn that stands there. + let (_, json) = search(&temp, &["--look-for", "pe4", "--mirror", "h", "--last-move", "1", "--json"]); + assert!(json.starts_with("{\"matches\":0,"), "{json}"); + let (_, json) = search(&temp, &["--look-for", "pe4", "--mirror", "hv", "--last-move", "1", "--json"]); + assert!(json.starts_with("{\"matches\":0,"), "{json}"); + let (_, json) = search(&temp, &["--look-for", "Pe2", "--first-move", "2", "--last-move", "2", "--json"]); + assert!(json.starts_with("{\"matches\":3,"), "{json}"); + let (_, json) = search( + &temp, + &["--look-for", "Pe2", "--first-move", "2", "--last-move", "2", "--position-window", "strict", "--json"], + ); + assert!(json.starts_with("{\"matches\":0,"), "{json}"); + for bad in [ + &["--look-for", "Ki9"][..], + &["--look-for", "Ke1", "--position-window", "invalid"], + &["--mirror", "x", "--look-for", "Ke1"], + &["--look-for", "Ke1", "--sacrifice"], + &["--first-move", "5", "--last-move", "2", "--look-for", "Ke1"], + ] { + assert!(!search(&temp, bad).0, "{bad:?}"); + } +} diff --git a/crates/cbvault/benches/query.rs b/crates/cbvault/benches/query.rs index 8a615251..9f2ab0b4 100644 --- a/crates/cbvault/benches/query.rs +++ b/crates/cbvault/benches/query.rs @@ -19,7 +19,7 @@ use std::time::Instant; use cbvault::bridge::{Database, Filter, Range, scan}; -use cbvault::query::{EloMode, EloQuery, GameDataQuery, PlayerName, search}; +use cbvault::query::{EloMode, EloQuery, GameDataQuery, PlayerName, PositionQuery, parse_fragment, search}; use criterion::{Criterion, Throughput, criterion_group, criterion_main}; /// How many games the fixture benches scan per iteration. @@ -47,9 +47,31 @@ fn fixture(criterion: &mut Criterion) { group.bench_function("query_every_field_1_thread", |b| { b.iter(|| std::hint::black_box(search(&database, &full, 1).expect("a search").ids.len())) }); + // The replay stage: every game's main line, to its end (mate) or to the + // first position that settles the fragment. + let mut mate = GameDataQuery::default(); + mate.endings.mate = true; + group.bench_function("query_mate_1_thread", |b| { + b.iter(|| std::hint::black_box(search(&database, &mate, 1).expect("a search").ids.len())) + }); + let knight = position("Nf3 pe5"); + group.bench_function("query_position_1_thread", |b| { + b.iter(|| std::hint::black_box(search(&database, &knight, 1).expect("a search").ids.len())) + }); group.finish(); } +/// A query with only the "Position" page: `look_for` on the dialog's defaults. +fn position(look_for: &str) -> GameDataQuery { + GameDataQuery { + position: Some(PositionQuery { + look_for: parse_fragment(look_for).expect("a board"), + ..PositionQuery::default() + }), + ..GameDataQuery::default() + } +} + /// A query that sets every header field the fixture can satisfy. fn full_query() -> GameDataQuery { let mut q = GameDataQuery { @@ -136,6 +158,17 @@ fn report(_criterion: &mut Criterion) { }, ), ("mate, 2025 on (replays the year)", mate), + ("position: white bishop on h7, moves 1-40", position("Bh7")), + ("position: white pawn on e2, move 1", { + let mut q = position("Pe2"); + q.position.as_mut().expect("a position").last = 1; + q + }), + ("position: bishop h7 and Elo >= 2700, both", { + let mut q = position("Bh7"); + q.elo = Some(EloQuery { range: Range::at_least(2700), mode: EloMode::Both }); + q + }), ]; let _ = search(&db, &GameDataQuery::default(), 10); println!("| query | matches | 1 thread | 10 threads |"); diff --git a/crates/cbvault/examples/exact_position_ids.rs b/crates/cbvault/examples/exact_position_ids.rs new file mode 100644 index 00000000..4182168f --- /dev/null +++ b/crates/cbvault/examples/exact_position_ids.rs @@ -0,0 +1,56 @@ +//! Ordered, unique record IDs for an exact Polyglot-key replay. +//! Diagnostic for downstream position indexes; not a fragment query. +#![allow(missing_docs)] +use cbvault::bridge::{Database, PositionQuery, for_each_position_key}; +use std::fs::OpenOptions; +use std::io::{BufWriter, Write}; + +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().skip(1).collect(); + if args.len() != 4 { + return Err("usage: exact_position_ids DB FEN THREADS OUTPUT_IDS".into()); + } + let db = Database::open(&args[0])?; + let board = gigachess::fen::parse_fen(&args[1]).map_err(|_| "invalid FEN")?; + let threads = args[2].parse::()?; + if threads == 0 { + return Err("threads must be positive".into()); + } + let mut out = BufWriter::new(OpenOptions::new().write(true).create_new(true).open(&args[3])?); + let key = board.zobrist(); + let query = PositionQuery::of(key); + let mut previous = 0; + let mut count = 0u64; + let mut error = None; + let stats = for_each_position_key(&db, &query, threads, |hit| { + if error.is_some() || hit.game == previous { + return; + } + if hit.game < previous { + error = Some(std::io::Error::other("out-of-order replay hit")); + return; + } + match writeln!(out, "{}", hit.game) { + Ok(()) => { + count += 1; + previous = hit.game; + } + Err(e) => error = Some(e), + } + })?; + if let Some(e) = error { + return Err(e.into()); + } + out.flush()?; + eprintln!( + "{{\"key\":\"{key:016x}\",\"records\":{},\"unique_ids\":{count},\"hits\":{},\"failures\":{},\"complete\":{}}}", + db.records(), + stats.hits, + stats.failures, + stats.complete + ); + if !stats.complete { + return Err("incomplete exact-key replay".into()); + } + Ok(()) +} diff --git a/crates/cbvault/src/bridge/search.rs b/crates/cbvault/src/bridge/search.rs index 192f5264..859906b0 100644 --- a/crates/cbvault/src/bridge/search.rs +++ b/crates/cbvault/src/bridge/search.rs @@ -1868,6 +1868,17 @@ impl<'db> SelectedReplay<'db> { } pub(crate) fn walk(&mut self, header: GameHeaderRef<'_>, sink: &mut impl MoveSink) -> Result { + self.walk_with_start(header, sink, |_, _| false) + } + + /// Visit the validated initial board before decoding any move. Returning + /// true from on_start ends the query without replaying the move stream. + pub(crate) fn walk_with_start( + &mut self, + header: GameHeaderRef<'_>, + sink: &mut S, + on_start: impl FnOnce(&mut S, &Board) -> bool, + ) -> Result { let db = self.db; let id = header.id(); let at = db.move_offset(&header)?; @@ -1889,7 +1900,9 @@ impl<'db> SelectedReplay<'db> { let game = cbvault_format::twocbh::moves::GameMoves::from_record(moves.path(), record)?; let start = cbvault_chess::v2::decode_v2_start(&game)?; let initial = start_board_cached(&start, &mut self.cache)?; - cbvault_chess::v2::walk_v2_from(what, &game, &start, sink)?; + if !on_start(sink, &initial) { + cbvault_chess::v2::walk_v2_from(what, &game, &start, sink)?; + } Ok(initial) } else { let moves = db.moves()?; @@ -1897,7 +1910,9 @@ impl<'db> SelectedReplay<'db> { let game = cbvault_format::cbh::moves::GameMoves::parse(&db.members().moves, bytes)?; let start = start_as_played(what, &game)?; let initial = start_board_cached(&start, &mut self.cache)?; - walk_from(what, &game, &start, sink)?; + if !on_start(sink, &initial) { + walk_from(what, &game, &start, sink)?; + } Ok(initial) } } diff --git a/crates/cbvault/src/query/ending.rs b/crates/cbvault/src/query/ending.rs index 7a85d153..9a536ee1 100644 --- a/crates/cbvault/src/query/ending.rs +++ b/crates/cbvault/src/query/ending.rs @@ -1,6 +1,8 @@ -//! The final position of a game: mate, stalemate, check, or none of them. +//! The replay stage: a game's main line, replayed once, against the final +//! position (mate, stalemate, check) and the "Position" page's fragment. use super::Endings; +use super::position::{Pattern, Tracker}; use crate::bridge::{GameHeaderRef, search::SelectedReplay}; use cbvault_chess::decode::MoveSink; use gigachess::Board; @@ -18,6 +20,7 @@ pub enum Ending { Other, } +/// The sink of an ending-only query: the final main-line board. struct FinalBoard<'a> { cancelled: Option<&'a (dyn Fn() -> bool + Sync)>, stopped: std::cell::Cell, @@ -48,8 +51,108 @@ impl MoveSink for FinalBoard<'_> { } } +/// The sink of a query with a position fragment: every main-line position +/// through the [`Tracker`], and the final board when endings are wanted too. +struct MainLine<'a> { + cancelled: Option<&'a (dyn Fn() -> bool + Sync)>, + stopped: std::cell::Cell, + /// Whether the last move reported belongs to the main line. + main: bool, + /// The number of the last main-line move reported. + move_number: u16, + /// Whether the final position is needed. + endings: bool, + last: Option, + position: Tracker<'a>, +} + +impl MainLine<'_> { + fn start(&mut self, board: &Board) -> bool { + self.position.start(board); + self.stopped() + } +} + +impl MoveSink for MainLine<'_> { + fn play(&mut self, board: &Board, _: u16, main: bool) { + self.main = main; + self.move_number = board.fullmove_number(); + } + fn played(&mut self, board: &Board) { + if self.main { + if self.endings { + self.last = Some(*board); + } + self.position.position(board, self.move_number, board.turn() == gigachess::Color::Black); + // The next move is past "Last": no counted position can follow. + self.position.passed(board.fullmove_number()); + } + } + fn branch(&mut self) {} + fn resume(&mut self) { + // The main line has ended; a variation takes over. + self.main = false; + } + fn stopped(&self) -> bool { + let stop = self.stopped.get() || self.cancelled.is_some_and(|f| f()); + self.stopped.set(stop); + // The main line is reported first: once a variation starts, it is over. + // A fragment that failed fails the game; one that matched is enough + // unless the final position is still needed. + let t = &self.position; + stop || !self.main || t.decided() && (!t.matched() || !self.endings) + } + fn wants_checkers(&self) -> bool { + self.endings + } + fn wants_variation_caches(&self) -> bool { + false + } +} + +/// Replays `header`'s main line once and tests the wanted endings and the +/// position fragment. `Ok(None)` when the game cannot be replayed. +pub(crate) fn matches_replay( + replay: &mut SelectedReplay<'_>, + header: GameHeaderRef<'_>, + cancelled: Option<&(dyn Fn() -> bool + Sync)>, + wanted: Endings, + pattern: Option<&Pattern>, +) -> Result, super::QueryError> { + let Some(pattern) = pattern else { + return final_board_matches(replay, header, cancelled, wanted); + }; + let is_cancelled = || cancelled.is_some_and(|f| f()); + if is_cancelled() { + return Err(super::QueryError::Cancelled); + } + let mut sink = MainLine { + cancelled, + stopped: std::cell::Cell::new(false), + main: true, + move_number: 0, + endings: wanted.is_set(), + last: None, + position: Tracker::new(pattern), + }; + let initial = replay.walk_with_start(header, &mut sink, MainLine::start); + if sink.stopped.get() || is_cancelled() { + return Err(super::QueryError::Cancelled); + } + let Ok(initial) = initial else { + return Ok(None); + }; + if !sink.position.matched() { + return Ok(Some(false)); + } + if !wanted.is_set() { + return Ok(Some(true)); + } + Ok(Some(matches_ending(&sink.last.unwrap_or(initial), wanted))) +} + /// Classify the actual native start or final mainline board once. -pub(crate) fn matches_ending( +fn final_board_matches( replay: &mut SelectedReplay<'_>, header: GameHeaderRef<'_>, cancelled: Option<&(dyn Fn() -> bool + Sync)>, @@ -66,14 +169,18 @@ pub(crate) fn matches_ending( let Ok(initial) = initial else { return Ok(None); }; - let board = sink.last.unwrap_or(initial); + Ok(Some(matches_ending(&sink.last.unwrap_or(initial), wanted))) +} + +/// Classifies a final position against the wanted endings. +fn matches_ending(board: &Board, wanted: Endings) -> bool { let check = board.in_check(); if !check && !wanted.stalemate || check && !wanted.mate && !wanted.check { - return Ok(Some(false)); + return false; } if check && wanted.mate && wanted.check { - return Ok(Some(true)); + return true; } let stuck = board.count_legal_moves() == 0; - Ok(Some(if check { if stuck { wanted.mate } else { wanted.check } } else { stuck && wanted.stalemate })) + if check { if stuck { wanted.mate } else { wanted.check } } else { stuck && wanted.stalemate } } diff --git a/crates/cbvault/src/query/header.rs b/crates/cbvault/src/query/header.rs index 4580d5e9..216cd045 100644 --- a/crates/cbvault/src/query/header.rs +++ b/crates/cbvault/src/query/header.rs @@ -5,6 +5,7 @@ use cbvault_format::game::{GameResult, Head, RecordKind}; use super::names::{self, Table}; +use super::position::Pattern; use super::text::Needle; use super::{ EcoCode, EloDifference, EloMode, EloQuery, Endings, GameDataQuery, PlayerName, QueryError, QueryResult, ResultSet, @@ -39,6 +40,7 @@ pub(crate) struct Compiled { elo_difference: Option, results: ResultSet, pub(crate) endings: Endings, + pub(crate) position: Option, pub(crate) text_records: bool, any_text: Option, time_control: Option, @@ -163,6 +165,7 @@ impl Compiled { elo_difference: query.elo_difference, results: query.results, endings: query.endings, + position: query.position.as_ref().map(Pattern::new), text_records: query.text_records, any_text, time_control, @@ -170,6 +173,11 @@ impl Compiled { }) } + /// Whether the games the header stage keeps are replayed. + pub(crate) fn replays(&self) -> bool { + self.endings.is_set() || self.position.is_some() + } + /// An empty required entity set makes a match impossible even with /// ignored colours or wins-only. A negated any-text predicate is different: /// an empty union satisfies it. Keep text-record semantics separate. @@ -201,6 +209,7 @@ impl Compiled { || self.elo_difference.is_some() || !self.results.is_any() || self.endings.is_set() + || self.position.is_some() || self.text_records || self.any_text.is_some() || self.time_control.is_some() @@ -229,6 +238,7 @@ impl Compiled { || self.elo_difference.is_some() || !self.results.is_any() || self.endings.is_set() + || self.position.is_some() || self.text_records || self.any_text.is_some() || self.time_control.is_some() diff --git a/crates/cbvault/src/query/mod.rs b/crates/cbvault/src/query/mod.rs index a1b8ad08..ec7bc67e 100644 --- a/crates/cbvault/src/query/mod.rs +++ b/crates/cbvault/src/query/mod.rs @@ -7,15 +7,18 @@ //! rating difference, the result boxes including mate, stalemate and check, //! guiding texts, "any text" with "not", and the time control. Every field is //! optional and every field set must hold: an empty query is every game. +//! [`GameDataQuery::position`] adds the "Position" page: a partial position +//! ([`PositionQuery`]). //! //! [`search`] answers it in two stages: //! //! 1. **The header stage** compiles the names to entity-id sets once (ADR-007 //! §2), then scans the header file in parallel, comparing integers. It //! never opens the moves file. -//! 2. **The ending stage** runs only when mate, stalemate or check is asked -//! for, and only on the games the first stage kept: it replays each main -//! line with `gigachess` and looks at the final position. +//! 2. **The replay stage** runs only when mate, stalemate or check, or a +//! position, is asked for, and only on the games the first stage kept: it +//! replays each main line once with `gigachess`, tests the fragment on +//! its positions and looks at the final one. //! //! The module sits beside [`crate::bridge::search`] and builds only on the //! bridge's public API, so a caller can mix the two: a resolved @@ -26,6 +29,7 @@ mod ending; mod header; pub(crate) mod names; mod parse; +mod position; mod scan; mod text; @@ -35,7 +39,8 @@ use cbvault_format::game::Tournament; use crate::bridge::{Database, Filter, Range}; pub use ending::Ending; -pub use parse::{ParseError, parse_range}; +pub use parse::{ParseError, parse_fragment, parse_range}; +pub use position::{Fragment, Man, PositionQuery, PositionWindow}; pub use scan::{Found, QueryPagePlan, QueryPlan, SearchOptions, search, search_with, search_with_context}; pub use text::TextMatch; @@ -87,6 +92,8 @@ pub struct GameDataQuery { pub time_control: Option, /// A filter of the bridge's own vocabulary, combined with the rest. pub extra: Option, + /// The "Position" page: a partial position of the main line. + pub position: Option, } /// A player line of the dialog: last name, forename, or both. @@ -353,6 +360,9 @@ impl GameDataQuery { if self.wins_only && self.white.is_blank() { return invalid("wins only needs a White player"); } + if let Some(position) = &self.position { + position.validate()?; + } if self.any_text.as_ref().is_some_and(|a| a.text.trim().is_empty()) { return invalid("any text must not be blank"); } @@ -369,7 +379,8 @@ impl GameDataQuery { || !self.results.is_any() || self.endings.is_set() || self.any_text.is_some() - || self.time_control.is_some()) + || self.time_control.is_some() + || self.position.is_some()) { return invalid("guiding text supports date and extra filter only"); } diff --git a/crates/cbvault/src/query/parse.rs b/crates/cbvault/src/query/parse.rs index 8675c2d6..869d4b1c 100644 --- a/crates/cbvault/src/query/parse.rs +++ b/crates/cbvault/src/query/parse.rs @@ -1,9 +1,12 @@ //! The text forms of the dialog's fields, as a user types them: `2020-2026.11`, -//! `A00-E99/99`, `2500-3500`, `0-22`. +//! `A00-E99/99`, `2500-3500`, `0-22`, and a board of the "Position" page: +//! `Kg1 Rf1 Pf2g2h2 bh7`. use std::str::FromStr; -use super::{DateRange, EcoCode, EcoRange, PartialDate}; +use gigachess::{Color, Role}; + +use super::{DateRange, EcoCode, EcoRange, Fragment, Man, PartialDate}; use crate::bridge::Range; /// A field whose text could not be read. @@ -125,10 +128,64 @@ pub fn parse_range(text: &str) -> Result { } } +/// A board of the "Position" page as typed: men separated by spaces or commas, +/// each a letter and one or more squares. `K Q R B N P` are White's pieces, +/// `k q r b n p` Black's, and `X` / `x` the jokers (any white / any black man): +/// `Kg1 Rf1 Pf2g2h2 bh7 xe5`. A square may be named more than once, for the +/// alternatives of an "Or" board or the men an "Exclude" board rules out. +pub fn parse_fragment(text: &str) -> Result { + let bad = || error("a board (letter and squares, such as Kg1 Pf2g2h2)", text); + let mut men = Vec::new(); + for token in text.split(|c: char| c.is_whitespace() || c == ',' || c == ';').filter(|t| !t.is_empty()) { + let mut chars = token.chars(); + let letter = chars.next().ok_or_else(bad)?; + let colour = if letter.is_ascii_uppercase() { Color::White } else { Color::Black }; + let man = match letter.to_ascii_uppercase() { + 'K' => Man::Piece(colour, Role::King), + 'Q' => Man::Piece(colour, Role::Queen), + 'R' => Man::Piece(colour, Role::Rook), + 'B' => Man::Piece(colour, Role::Bishop), + 'N' => Man::Piece(colour, Role::Knight), + 'P' => Man::Piece(colour, Role::Pawn), + 'X' => Man::Any(colour), + _ => return Err(bad()), + }; + let squares = chars.as_str().as_bytes(); + if squares.is_empty() || squares.len() % 2 != 0 { + return Err(bad()); + } + for pair in squares.chunks(2) { + let (file, rank) = (pair[0].to_ascii_lowercase(), pair[1]); + if !(b'a'..=b'h').contains(&file) || !(b'1'..=b'8').contains(&rank) { + return Err(bad()); + } + men.push(((rank - b'1') * 8 + (file - b'a'), man)); + } + } + if men.is_empty() { + return Err(bad()); + } + Ok(Fragment { men }) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn boards_read_with_pieces_jokers_and_several_squares() { + let f = parse_fragment("Kg1, Pf2g2h2 bh7 xe5").unwrap(); + assert_eq!(f, parse_fragment("Kg1,\tPf2g2h2\nbh7;xe5").unwrap()); + assert_eq!(f.men.len(), 6); + assert_eq!(f.men[0], (6, Man::Piece(Color::White, Role::King))); + assert_eq!(f.men[3], (15, Man::Piece(Color::White, Role::Pawn))); + assert_eq!(f.men[4], (55, Man::Piece(Color::Black, Role::Bishop))); + assert_eq!(f.men[5], (36, Man::Any(Color::Black))); + for bad in ["", "Kg", "Ki1", "Zg1", "Kg9"] { + assert!(parse_fragment(bad).is_err(), "{bad}"); + } + } + #[test] fn dates_read_with_one_two_or_three_parts() { let range: DateRange = "2020-2026.11".parse().unwrap(); diff --git a/crates/cbvault/src/query/position.rs b/crates/cbvault/src/query/position.rs new file mode 100644 index 00000000..68ac8288 --- /dev/null +++ b/crates/cbvault/src/query/position.rs @@ -0,0 +1,513 @@ +//! The "Position" page of ChessBase's search dialog: a partial position that +//! must stand on the board at some point of a game's main line. +//! +//! [`PositionQuery`] holds the page's three boards and its options: +//! +//! - **Look for**: every man set here stands on its square. +//! - **Or**: at least one of the men set here stands on its square. A square +//! may hold several alternatives. +//! - **Exclude**: none of the men set here stands on its square. A square may +//! hold several. +//! - **Mirror**: the fragment is also looked for reflected across the +//! horizontal axis, top to bottom with the colours swapped (horizontal), and +//! across the vertical axis, left to right (vertical). +//! - **First, Length, Last**: as ChessBase answers them, the positions from +//! the start through move `max(last, first + 1)` count, and the one after +//! White's following move; the fragment must stand in `length` consecutive +//! positions of them. +//! +//! A man is a piece of a colour, or the dialog's "joker": any man of a colour. +//! +//! The fragment compiles to one set of bitboards per orientation, so testing a +//! position is a few integer operations and no allocation. + +use gigachess::{Board, Color, Role}; + +/// What may stand on a square of a fragment. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Man { + /// A piece of a colour. + Piece(Color, Role), + /// Any man of a colour: the dialog's white or black joker. + Any(Color), +} + +impl Man { + /// The man with its colour swapped. + fn swapped(self) -> Man { + match self { + Man::Piece(c, r) => Man::Piece(c.other(), r), + Man::Any(c) => Man::Any(c.other()), + } + } +} + +/// One board of the page: men on squares (0 = a1 … 63 = h8). +/// +/// On the "Or" and "Exclude" boards a square may hold several men. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Fragment { + /// The men and their squares. + pub men: Vec<(u8, Man)>, +} + +impl Fragment { + /// Whether nothing is set on this board. + pub fn is_empty(&self) -> bool { + self.men.is_empty() + } +} + +/// Interpretation of the move-number window. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PositionWindow { + /// Reproduce the window observed in ChessBase's Position dialog. + #[default] + ChessBaseCompatible, + /// Count only positions labelled with a move number in First..=Last. + Strict, +} + +/// The "Position" page of the search dialog. +/// +/// The default is the dialog's: empty boards, no mirror, moves 1 to 40, a +/// length of one position. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PositionQuery { + /// The "Look for" board. + pub look_for: Fragment, + /// The "Or" board. + pub or: Fragment, + /// The "Exclude" board. + pub exclude: Fragment, + /// "Mirror: Horizontal": also look for the fragment reflected across the + /// horizontal axis (ranks 1↔8), with the colours swapped. + pub mirror_horizontal: bool, + /// "Mirror: Vertical": also look for the fragment reflected across the + /// vertical axis (files a↔h). + pub mirror_vertical: bool, + /// Lower move bound in strict mode; in compatibility mode it only + /// makes the window reach at least move `first + 1`. + pub first: u16, + /// "Length": how many consecutive positions the fragment must stand in. + pub length: u16, + /// Last move number; compatibility mode also counts the extra positions + /// observed in ChessBase. + pub last: u16, + /// How to interpret First and Last. + pub window: PositionWindow, + /// "Sacrifice": ChessBase's own sacrifice detection. Not established, so + /// a query that sets it is refused. + pub sacrifice: bool, +} + +impl Default for PositionQuery { + fn default() -> PositionQuery { + PositionQuery { + look_for: Fragment::default(), + or: Fragment::default(), + exclude: Fragment::default(), + mirror_horizontal: false, + mirror_vertical: false, + first: 1, + length: 1, + last: 40, + window: PositionWindow::default(), + sacrifice: false, + } + } +} + +impl PositionQuery { + /// Checks the page is answerable, before any database I/O. + pub(crate) fn validate(&self) -> Result<(), super::QueryError> { + use super::QueryError::{Invalid, Unsupported}; + if self.sacrifice { + return Err(Unsupported("\"Sacrifice\": which sacrifices ChessBase finds is not established")); + } + if self.look_for.is_empty() && self.or.is_empty() && self.exclude.is_empty() { + return Err(Invalid("a position search needs at least one man on a board")); + } + let boards = [&self.look_for, &self.or, &self.exclude]; + if boards.iter().any(|b| b.men.iter().any(|&(sq, _)| sq > 63)) { + return Err(Invalid("a square is outside the board")); + } + for (i, &(sq, _)) in self.look_for.men.iter().enumerate() { + if self.look_for.men[..i].iter().any(|&(s, _)| s == sq) { + return Err(Invalid("the \"Look for\" board has two men on one square")); + } + } + if self.first == 0 || self.length == 0 || self.first > self.last { + return Err(Invalid("First, Length and Last need 1 <= First <= Last and Length >= 1")); + } + Ok(()) + } +} + +/// One board compiled for one orientation: bitboards per colour and role +/// (`[colour][role]`, colours as `Color::index`) and per colour for jokers. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Masks { + pieces: [[u64; 6]; 2], + any: [u64; 2], +} + +impl Masks { + fn of(fragment: &Fragment, flip_files: bool, flip_ranks: bool) -> Masks { + let mut m = Masks::default(); + for &(sq, man) in &fragment.men { + let mut sq = sq; + if flip_files { + sq ^= 7; + } + let man = if flip_ranks { + sq ^= 56; + man.swapped() + } else { + man + }; + let bit = 1u64 << sq; + match man { + Man::Piece(c, r) => m.pieces[c.index()][r.index()] |= bit, + Man::Any(c) => m.any[c.index()] |= bit, + } + } + m + } + + fn is_empty(&self) -> bool { + self.any == [0; 2] && self.pieces.iter().all(|p| *p == [0; 6]) + } +} + +const COLOURS: [Color; 2] = [Color::Black, Color::White]; +const ROLES: [Role; 6] = [Role::Pawn, Role::Knight, Role::Bishop, Role::Rook, Role::Queen, Role::King]; + +/// A fragment in one orientation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Oriented { + look_for: Masks, + or: Option, + exclude: Masks, +} + +impl Oriented { + #[inline] + fn holds(&self, board: &Board) -> bool { + let mut any_or = self.or.is_none(); + for c in COLOURS { + let i = c.index(); + let own = board.occ_color(c); + if own & self.look_for.any[i] != self.look_for.any[i] || own & self.exclude.any[i] != 0 { + return false; + } + if let Some(or) = &self.or { + any_or |= own & or.any[i] != 0; + } + for r in ROLES { + let j = r.index(); + let (need, banned) = (self.look_for.pieces[i][j], self.exclude.pieces[i][j]); + let or_bits = self.or.as_ref().map_or(0, |o| o.pieces[i][j]); + if need | banned | or_bits == 0 { + continue; + } + let have = board.piece_bb(c, r); + if have & need != need || have & banned != 0 { + return false; + } + any_or |= have & or_bits != 0; + } + } + any_or + } +} + +/// A [`PositionQuery`] ready to test positions. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Pattern { + orientations: Vec, + first: u16, + length: u16, + /// The last move whose positions all count: see [`window_end`]. + end: u16, + window: PositionWindow, +} + +/// The last move whose positions all count, as ChessBase answers the dialog. +/// +/// Measured on Mega Database 2026 (`docs/search.md`): ChessBase looks at every +/// position from the start through move `max(Last, First + 1)`, and at the +/// position after White's following move as well. "First" only pushes that end. +fn window_end(first: u16, last: u16) -> u16 { + last.max(first.saturating_add(1)) +} + +impl Pattern { + pub(crate) fn new(query: &PositionQuery) -> Pattern { + let mut orientations: Vec = Vec::with_capacity(4); + let mut add = |flip_files: bool, flip_ranks: bool| { + let or = Masks::of(&query.or, flip_files, flip_ranks); + let o = Oriented { + look_for: Masks::of(&query.look_for, flip_files, flip_ranks), + or: (!or.is_empty()).then_some(or), + exclude: Masks::of(&query.exclude, flip_files, flip_ranks), + }; + // A symmetric fragment reflects onto itself: test it once. + if !orientations.contains(&o) { + orientations.push(o); + } + }; + add(false, false); + // The axis is the one each box names: "Vertical" reflects the files + // across the vertical axis, "Horizontal" the ranks (and colours) + // across the horizontal one. + if query.mirror_vertical { + add(true, false); + } + if query.mirror_horizontal { + add(false, true); + } + if query.mirror_horizontal && query.mirror_vertical { + add(true, true); + } + let end = match query.window { + PositionWindow::ChessBaseCompatible => window_end(query.first, query.last), + PositionWindow::Strict => query.last, + }; + Pattern { orientations, first: query.first, length: query.length, end, window: query.window } + } + + #[inline] + fn holds(&self, board: &Board) -> bool { + self.orientations.iter().any(|o| o.holds(board)) + } +} + +/// Follows one main line through a [`Pattern`]. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Tracker<'a> { + pattern: &'a Pattern, + run: u16, + /// `Some` once the answer is known. + decided: Option, +} + +impl<'a> Tracker<'a> { + pub(crate) fn new(pattern: &'a Pattern) -> Tracker<'a> { + Tracker { pattern, run: 0, decided: None } + } + + /// The initial board is labelled with its own fullmove number. If a + /// custom start is immediately before the compatibility window's final + /// extra White move, the initial board is outside the window but that + /// move's resulting position is still eligible. + #[inline] + pub(crate) fn start(&mut self, board: &Board) { + if self.pattern.window == PositionWindow::ChessBaseCompatible + && self.pattern.end.checked_add(1) == Some(board.fullmove_number()) + && board.turn() == Color::White + { + return; + } + self.position(board, board.fullmove_number(), false); + } + + /// A position of the main line, in order: `move_number` is the number of + /// the move that led to it (for the start position, the number of the + /// first move to come), and `after_white` whether White's move led to it. + #[inline] + pub(crate) fn position(&mut self, board: &Board, move_number: u16, after_white: bool) { + if self.decided.is_some() || (self.pattern.window == PositionWindow::Strict && move_number < self.pattern.first) + { + return; + } + let end = self.pattern.end; + // The position after White's move following the window still counts. + let extra = self.pattern.window == PositionWindow::ChessBaseCompatible + && after_white + && end.checked_add(1) == Some(move_number); + if move_number > end && !extra { + self.decided = Some(false); + return; + } + if self.pattern.holds(board) { + self.run += 1; + if self.run >= self.pattern.length { + self.decided = Some(true); + } + } else { + self.run = 0; + } + if extra && self.decided.is_none() { + self.decided = Some(false); + } + } + + /// The move to come is `next_move`: past the window, the answer is known. + #[inline] + pub(crate) fn passed(&mut self, next_move: u16) { + let limit = match self.pattern.window { + PositionWindow::ChessBaseCompatible => self.pattern.end.saturating_add(1), + PositionWindow::Strict => self.pattern.end, + }; + if self.decided.is_none() && next_move > limit { + self.decided = Some(false); + } + } + + /// Whether the answer is known before the main line ends. + #[inline] + pub(crate) fn decided(&self) -> bool { + self.decided.is_some() + } + + /// The answer once the main line has ended. + #[inline] + pub(crate) fn matched(&self) -> bool { + self.decided == Some(true) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gigachess::fen::parse_fen; + + fn sq(name: &str) -> u8 { + let b = name.as_bytes(); + (b[1] - b'1') * 8 + (b[0] - b'a') + } + + fn frag(men: &[(&str, Man)]) -> Fragment { + Fragment { men: men.iter().map(|&(s, m)| (sq(s), m)).collect() } + } + + fn holds(q: &PositionQuery, fen: &str) -> bool { + Pattern::new(q).holds(&parse_fen(fen).unwrap()) + } + + const W: Color = Color::White; + const B: Color = Color::Black; + + #[test] + fn look_for_or_exclude_and_jokers() { + let start = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; + let mut q = PositionQuery { + look_for: frag(&[("e1", Man::Piece(W, Role::King)), ("d8", Man::Piece(B, Role::Queen))]), + ..PositionQuery::default() + }; + assert!(holds(&q, start)); + q.exclude = frag(&[("e4", Man::Any(W)), ("e4", Man::Any(B))]); + assert!(holds(&q, start), "e4 is empty"); + q.exclude = frag(&[("e2", Man::Piece(W, Role::Knight)), ("e2", Man::Piece(W, Role::Pawn))]); + assert!(!holds(&q, start), "a pawn stands on e2"); + q.exclude = Fragment::default(); + q.or = frag(&[("c4", Man::Piece(W, Role::Bishop)), ("b5", Man::Piece(W, Role::Bishop))]); + assert!(!holds(&q, start)); + assert!(holds(&q, "rnbqkbnr/pppp1ppp/8/4p3/2B1P3/8/PPPP1PPP/RNBQK1NR b KQkq - 1 2")); + q.look_for = frag(&[("a2", Man::Any(W)), ("a7", Man::Any(B))]); + q.or = Fragment::default(); + assert!(holds(&q, start)); + q.look_for = frag(&[("a2", Man::Any(B))]); + assert!(!holds(&q, start)); + } + + #[test] + fn mirrors() { + // A white bishop on h7 (the classic sacrifice square). + let a7 = "4k3/B7/8/8/8/8/8/4K3 w - - 0 1"; + let h2_black = "4k3/8/8/8/8/8/7b/4K3 w - - 0 1"; + let mut q = + PositionQuery { look_for: frag(&[("h7", Man::Piece(W, Role::Bishop))]), ..PositionQuery::default() }; + assert!(!holds(&q, a7) && !holds(&q, h2_black)); + q.mirror_vertical = true; + assert!(holds(&q, a7) && !holds(&q, h2_black)); + q.mirror_vertical = false; + q.mirror_horizontal = true; + assert!(!holds(&q, a7) && holds(&q, h2_black)); + } + + #[test] + fn first_length_last() { + let q = PositionQuery { + look_for: frag(&[("e1", Man::Piece(W, Role::King))]), + first: 3, + length: 2, + last: 4, + ..PositionQuery::default() + }; + let p = Pattern::new(&q); + let board = parse_fen("4k3/8/8/8/8/8/8/4K3 w - - 0 1").unwrap(); + let other = parse_fen("4k3/8/8/8/8/8/8/3K4 w - - 0 1").unwrap(); + // As ChessBase answers: First does not cut the start, and the position + // after White's move following Last still counts. + let mut t = Tracker::new(&p); + t.position(&board, 1, false); + t.position(&board, 1, true); + assert!(t.matched(), "First does not cut the positions before it"); + let mut t = Tracker::new(&p); + for (n, white) in [(3, true), (3, false), (4, true), (4, false)] { + t.position(&other, n, white); + } + assert!(!t.decided()); + t.position(&board, 5, true); + assert!(t.decided() && !t.matched(), "one position after Last is not two in a row"); + let mut t = Tracker::new(&p); + t.position(&other, 4, true); + t.position(&board, 4, false); + t.position(&board, 5, true); + assert!(t.matched(), "the position after White's move 5 counts"); + let mut t = Tracker::new(&p); + t.position(&board, 5, false); + assert!(t.decided() && !t.matched(), "after Black's move 5 nothing counts"); + } + + #[test] + fn refusals() { + let mut q = PositionQuery::default(); + assert!(q.validate().is_err(), "empty boards"); + q.look_for = frag(&[("e1", Man::Piece(W, Role::King)), ("e1", Man::Any(W))]); + assert!(q.validate().is_err(), "two men on one Look for square"); + q.look_for = frag(&[("e1", Man::Piece(W, Role::King))]); + assert!(q.validate().is_ok()); + q.sacrifice = true; + assert!(matches!(q.validate(), Err(crate::query::QueryError::Unsupported(_)))); + } + + #[test] + fn custom_start_at_extra_white_move() { + let mut q = PositionQuery { + look_for: frag(&[("e4", Man::Piece(W, Role::Pawn))]), + first: 1, + last: 2, + ..PositionQuery::default() + }; + let before = parse_fen("4k3/8/8/8/8/8/4P3/4K3 w - - 0 3").unwrap(); + let after = parse_fen("4k3/8/8/8/4P3/8/8/4K3 b - - 0 3").unwrap(); + let pattern = Pattern::new(&q); + let mut tracker = Tracker::new(&pattern); + tracker.start(&before); + assert!(!tracker.decided()); + tracker.position(&after, 3, true); + assert!(tracker.matched()); + + q.look_for = frag(&[("e2", Man::Piece(W, Role::Pawn))]); + let pattern = Pattern::new(&q); + let mut tracker = Tracker::new(&pattern); + tracker.start(&before); + assert!(!tracker.decided()); + tracker.position(&after, 3, true); + assert!(tracker.decided() && !tracker.matched()); + + let black = parse_fen("4k3/8/8/8/8/8/4P3/4K3 b - - 0 3").unwrap(); + let mut tracker = Tracker::new(&pattern); + tracker.start(&black); + assert!(tracker.decided() && !tracker.matched()); + + q.window = PositionWindow::Strict; + let pattern = Pattern::new(&q); + let mut tracker = Tracker::new(&pattern); + tracker.start(&before); + assert!(tracker.decided() && !tracker.matched()); + } +} diff --git a/crates/cbvault/src/query/scan.rs b/crates/cbvault/src/query/scan.rs index f4af845e..2ac6def6 100644 --- a/crates/cbvault/src/query/scan.rs +++ b/crates/cbvault/src/query/scan.rs @@ -1,4 +1,4 @@ -//! Running a [`GameDataQuery`]: the parallel header scan, then the ending +//! Running a [`GameDataQuery`]: the parallel header scan, then the replay //! stage on the survivors. use super::header::Compiled; @@ -84,9 +84,9 @@ pub struct Found { pub ids: Vec, /// Header records scanned. pub records: u64, - /// Games replayed by the ending stage. + /// Games replayed by the replay stage (endings, position). pub replayed: u64, - /// Games the ending stage could not replay; they are not matches. + /// Games the replay stage could not replay; they are not matches. pub failed: u64, /// Whether the search ran to the end, rather than being cancelled. pub complete: bool, @@ -250,6 +250,8 @@ impl<'db> QueryPlan<'db> { ) -> Result { let mut out = Found::default(); let endings = self.compiled.endings; + let pattern = self.compiled.position.as_ref(); + let replays = self.compiled.replays(); if self.compiled.rejects_all() { if let Some(cancelled) = cancel { let (records, complete) = visit_query_ids(self.db, first, last, &RejectAll, cancelled, |_| true)?; @@ -263,12 +265,12 @@ impl<'db> QueryPlan<'db> { return Ok(out); } if cancel.is_none() { - if endings.is_set() { + if replays { let mut replay = SelectedReplay::new(self.db); visit_matching_records(self.db, first, last, &self.compiled, |header| { let id = header.id(); out.replayed += 1; - match ending::matches_ending(&mut replay, header, None, endings) { + match ending::matches_replay(&mut replay, header, None, endings, pattern) { Ok(Some(true)) => visit(id), Ok(Some(false)) => {} Ok(None) => out.failed += 1, @@ -297,7 +299,7 @@ impl<'db> QueryPlan<'db> { } let cancelled = || cancel.is_some_and(|f| f()); let mut replay = SelectedReplay::new(self.db); - let (records, complete) = if !endings.is_set() { + let (records, complete) = if !replays { visit_query_ids(self.db, first, last, &self.compiled, cancelled, |id| { visit(id); true @@ -309,7 +311,7 @@ impl<'db> QueryPlan<'db> { return false; } out.replayed += 1; - match ending::matches_ending(&mut replay, header, cancel, endings) { + match ending::matches_replay(&mut replay, header, cancel, endings, pattern) { Ok(Some(true)) => visit(id), Ok(Some(false)) => {} Ok(None) => out.failed += 1, diff --git a/crates/cbvault/tests/query_position.rs b/crates/cbvault/tests/query_position.rs new file mode 100644 index 00000000..a3341d0b --- /dev/null +++ b/crates/cbvault/tests/query_position.rs @@ -0,0 +1,650 @@ +//! The "Position" search over generated classic and 2CBH databases: each board, +//! the jokers, the mirrors, First / Length / Last, and the combinations with +//! the "Game data" page. + +use cbvault::bridge::Database; +use cbvault::query::{ + Endings, GameDataQuery, PlayerName, PositionQuery, PositionWindow, QueryError, parse_fragment, search, +}; +use cbvault_fixtures::classic::{self, Builder, Tok}; +use cbvault_fixtures::twocbh; +use gigachess::Board; + +/// The games both databases hold, in this order (White is player 0 in all +/// but game 2): +/// +/// 1. 1.e4 e5 2.Nf3 Nc6 3.Bc4: the bishop reaches c4 on the last move +/// 2. 1.f3 e5 2.g4 Qh4#: fool's mate, White is player 1 +/// 3. 1.e4 e5 2.Nf3 Nc6 3.Bc4 Bc5 4.d3: the bishop stays on c4 +/// 4. no moves at all +const LINES: [&str; 4] = ["e2e4 e7e5 g1f3 b8c6 f1c4", "f2f3 e7e5 g2g4 d8h4", "e2e4 e7e5 g1f3 b8c6 f1c4 f8c5 d2d3", ""]; + +/// The classic database: the four games and, with `variation`, a fifth whose +/// main line is 1.e4 e5 2.Nf3 with 2.Bc4 only as a variation. +fn classic_db(name: &str, variation: bool) -> cbvault_fixtures::TempDb { + let board = Board::startpos(); + let record = |toks: &[Tok<'_>]| classic::move_record(0, None, None, &classic::encode(&board, toks, 0, false)); + let mut records: Vec> = LINES + .iter() + .map(|line| { + let mut toks: Vec> = line.split_whitespace().map(Tok::Mv).collect(); + toks.push(Tok::End); + record(&toks) + }) + .collect(); + if variation { + records.push(record(&[ + Tok::Mv("e2e4"), + Tok::Mv("e7e5"), + Tok::Var, + Tok::Mv("g1f3"), + Tok::End, + Tok::Mv("f1c4"), + Tok::End, + ])); + } + let mut b = Builder::new(); + for (i, r) in records.iter().enumerate() { + let h = b.game(r); + if i == 1 { + h[0x09..0x0c].copy_from_slice(&1u32.to_be_bytes()[1..]); + h[0x0c..0x0f].copy_from_slice(&0u32.to_be_bytes()[1..]); + h[0x1b] = 0; + } + } + b.write(name) +} + +/// The 2CBH database: the four games. +fn twocbh_db(name: &str) -> cbvault_fixtures::TempDb { + let temp = cbvault_fixtures::TempDb::create(name); + let mut b = twocbh::Builder::new(); + b.player("Morphy", "Paul"); + b.player("Anderssen", "Adolf"); + b.tournament_with_type("Paris", "FRA", 0, 0); + let moves: Vec = LINES.iter().map(|line| b.moves(1, &twocbh::words(&mut Board::startpos(), line))).collect(); + for (i, m) in moves.into_iter().enumerate() { + let rec = b.game(m); + let (white, black) = if i == 1 { (1, 0) } else { (0, 1) }; + twocbh::set_entities(rec, white, black, 0); + rec[0x30..0x40].copy_from_slice(&[0xff; 16]); + rec[0x58] = if i == 1 { 0 } else { 2 }; + } + b.write_to(&temp); + temp +} + +fn ids(db: &Database, query: &GameDataQuery) -> Vec { + let one = search(db, query, 1).expect("a search").ids; + let many = search(db, query, 4).expect("a parallel search").ids; + assert_eq!(one, many, "the thread count does not change the answer"); + one +} + +/// A query with only the "Position" page, built by `set`. +fn position(set: impl FnOnce(&mut PositionQuery)) -> GameDataQuery { + let mut p = PositionQuery::default(); + set(&mut p); + GameDataQuery { position: Some(p), ..GameDataQuery::default() } +} + +fn board_of(text: &str) -> cbvault::query::Fragment { + parse_fragment(text).expect("a board") +} + +/// The checks both generations must pass alike. +fn shared_checks(db: &Database) { + // "Look for": every man on its square, other squares free. + assert_eq!(ids(db, &position(|p| p.look_for = board_of("Bc4"))), [1, 3]); + assert_eq!(ids(db, &position(|p| p.look_for = board_of("Bc4 bc5"))), [3]); + assert_eq!(ids(db, &position(|p| p.look_for = board_of("qh4 Pf3g4"))), [2]); + // The start position counts, and so does a game without moves. + assert_eq!(ids(db, &position(|p| p.look_for = board_of("Ke1 Pe2"))), [1, 2, 3, 4]); + + // Jokers: any white man on f3 (a knight in 1 and 3, a pawn in 2). + assert_eq!(ids(db, &position(|p| p.look_for = board_of("Xf3"))), [1, 2, 3]); + assert_eq!(ids(db, &position(|p| p.look_for = board_of("xf3"))), [] as [u32; 0]); + + // "Or": at least one of its men, together with "Look for". + let or = position(|p| { + p.look_for = board_of("Ke1"); + p.or = board_of("Bc4 qh4"); + }); + assert_eq!(ids(db, &or), [1, 2, 3]); + assert_eq!(ids(db, &position(|p| p.or = board_of("bc5 qh4"))), [2, 3]); + + // "Exclude": none of its men; several may share a square. + let exclude = |men: &str| { + position(|p| { + p.look_for = board_of("Bc4"); + p.exclude = board_of(men); + }) + }; + assert_eq!(ids(db, &exclude("bc5")), [1, 3], "game 3 has Bc4 before ...Bc5 too"); + assert_eq!(ids(db, &exclude("Pe2 Pe4")), [] as [u32; 0], "the e-pawn is on e4 in both"); + assert_eq!(ids(db, &exclude("Pd2 Pd3")), [] as [u32; 0]); + assert_eq!( + ids( + db, + &position(|p| { + p.look_for = board_of("Bc4"); + p.exclude = board_of("bc5"); + p.length = 2; + }) + ), + [] as [u32; 0], + "in game 3 the second position with Bc4 has ...Bc5" + ); + + // Mirrors: vertical reflects left to right; horizontal top to bottom with + // the colours swapped. + assert_eq!(ids(db, &position(|p| p.look_for = board_of("Bf4"))), [] as [u32; 0]); + assert_eq!( + ids( + db, + &position(|p| { + p.look_for = board_of("Bf4"); + p.mirror_vertical = true; + }) + ), + [1, 3] + ); + assert_eq!( + ids( + db, + &position(|p| { + p.look_for = board_of("Qh5"); + p.mirror_horizontal = true; + }) + ), + [2], + "the white queen on h5, reflected, is the black queen on h4" + ); + + // First, Length, Last, as ChessBase answers them: every position from the + // start through move max(Last, First + 1), and the one after White's + // following move. + let window = |first, length, last| { + position(|p| { + p.look_for = board_of("qh4"); + (p.first, p.length, p.last) = (first, length, last); + }) + }; + assert_eq!(ids(db, &window(1, 1, 40)), [2]); + assert_eq!(ids(db, &window(1, 1, 1)), [2], "Last 1 reaches move 2, where the queen arrives"); + assert_eq!(ids(db, &window(3, 1, 40)), [2], "First does not cut the positions before it"); + let last2 = |men: &str| { + position(|p| { + p.look_for = board_of(men); + p.last = 2; + }) + }; + assert_eq!(ids(db, &last2("Bc4")), [1, 3], "after White's move 3 still counts"); + assert_eq!(ids(db, &last2("bc5")), [] as [u32; 0], "after Black's move 3 does not"); + assert_eq!(ids(db, &window(1, 2, 40)), [] as [u32; 0], "the game ends as she arrives"); + let bishop = |length| { + position(|p| { + p.look_for = board_of("Bc4"); + p.length = length; + }) + }; + assert_eq!(ids(db, &bishop(3)), [3], "Bc4, ...Bc5, d3: three positions"); + assert_eq!(ids(db, &bishop(4)), [] as [u32; 0]); + + // Combined with the "Game data" page: names, results and endings. + let mut q = position(|p| p.look_for = board_of("qh4")); + q.endings = Endings { mate: true, ..Endings::default() }; + assert_eq!(ids(db, &q), [2]); + let mut q = position(|p| p.look_for = board_of("Bc4")); + q.endings = Endings { mate: true, ..Endings::default() }; + assert_eq!(ids(db, &q), [] as [u32; 0]); + let mut q = position(|p| p.look_for = board_of("Ke1")); + q.white = PlayerName::parse("Anderssen"); + assert_eq!(ids(db, &q), [2]); + + // Refusals. + let refused = |q: GameDataQuery| search(db, &q, 1).expect_err("refused"); + assert!(matches!(refused(position(|p| p.sacrifice = true)), QueryError::Unsupported(_))); + assert!(matches!(refused(position(|_| {})), QueryError::Invalid(_))); + assert!(matches!( + refused(position(|p| { + p.look_for = board_of("Ke1"); + (p.first, p.last) = (10, 5); + })), + QueryError::Invalid(_) + )); +} + +#[test] +fn every_position_feature_works_on_a_classic_database() { + let temp = classic_db("query_position_classic", false); + let db = Database::open(temp.base()).expect("open"); + shared_checks(&db); + let temp = classic_db("query_position_variation", true); + let db = Database::open(temp.base()).expect("open"); + // Only the main line is searched: game 5 has Bc4 in a variation only. + assert_eq!(ids(&db, &position(|p| p.look_for = board_of("Nf3"))), [1, 3, 5]); + assert_eq!(ids(&db, &position(|p| p.look_for = board_of("Bc4"))), [1, 3]); +} + +#[test] +fn every_position_feature_works_on_a_twocbh_database() { + let temp = twocbh_db("query_position_twocbh"); + let db = Database::open(temp.base()).expect("open"); + shared_checks(&db); +} + +#[test] +fn cancelled_position_search_reports_incomplete() { + let temp = twocbh_db("query_position_cancel"); + let db = Database::open(temp.base()).expect("open"); + let q = position(|p| p.look_for = board_of("Ke1")); + let stop = || true; + let options = cbvault::query::SearchOptions { threads: 2, cancelled: Some(&stop), ..Default::default() }; + let found = cbvault::query::search_with(&db, &q, options).expect("a cancelled search is not an error"); + assert!(!found.complete); + assert!(found.ids.is_empty()); +} + +/// A 2CBH database of `games`, each a list of raw move words. +fn twocbh_words_db(name: &str, games: &[Vec]) -> cbvault_fixtures::TempDb { + let temp = cbvault_fixtures::TempDb::create(name); + let mut b = twocbh::Builder::new(); + b.player("Morphy", "Paul"); + b.player("Anderssen", "Adolf"); + b.tournament_with_type("Paris", "FRA", 0, 0); + let moves: Vec = games.iter().map(|w| b.moves(1, w)).collect(); + for m in moves { + let rec = b.game(m); + twocbh::set_entities(rec, 0, 1, 0); + rec[0x30..0x40].copy_from_slice(&[0xff; 16]); + } + b.write_to(&temp); + temp +} + +#[test] +fn twocbh_variations_are_not_searched() { + // 1.e4 e5 2.Nf3 (2.Bc4): Bc4 stands in the variation only. + let mut board = Board::startpos(); + let mut words = twocbh::words(&mut board, "e2e4 e7e5"); + let mut after = board; + words.extend(twocbh::words(&mut board, "g1f3")); + words.extend([0xfffd, 0xffff]); + words.extend(twocbh::words(&mut after, "f1c4")); + words.push(0xffff); + let temp = twocbh_words_db("query_position_twocbh_variation", &[words]); + let db = Database::open(temp.base()).expect("open"); + assert_eq!(ids(&db, &position(|p| p.look_for = board_of("Nf3"))), [1]); + assert_eq!(ids(&db, &position(|p| p.look_for = board_of("Bc4"))), [] as [u32; 0]); +} + +#[test] +fn the_search_stops_at_last_before_a_corrupt_move() { + use cbvault_chess::movetable::{Color as MColor, Piece as MPiece}; + // 1.e4 e5 2.Nf3 Nc6 3.Bc4, then a word that is not a legal move for Black. + let mut board = Board::startpos(); + let mut words = twocbh::words(&mut board, "e2e4 e7e5 g1f3 b8c6 f1c4"); + words.push(twocbh::quiet(MColor::Black, MPiece::Queen, "d8", "d1")); + let temp = twocbh_words_db("query_position_corrupt_after_last", &[words]); + let db = Database::open(temp.base()).expect("open"); + let q = position(|p| { + p.look_for = board_of("Nc3"); + p.last = 1; + }); + let found = search(&db, &q, 1).expect("a search"); + assert!(found.ids.is_empty()); + assert_eq!(found.failed, 0, "the last position counted is after 3.Bc4: the next move is never decoded"); + let q = position(|p| p.look_for = board_of("Nc3")); + assert_eq!(search(&db, &q, 1).expect("a search").failed, 1, "without the bound it is"); +} + +#[test] +fn boundaries_mirrors_and_conflicts() { + let temp = twocbh_db("query_position_boundaries"); + let db = Database::open(temp.base()).expect("open"); + // Both mirrors add the reflection through the centre: a white queen on a5 + // becomes the black queen on h4 of game 2, which neither mirror alone finds. + let qa5 = |h, v| { + position(|p| { + p.look_for = board_of("Qa5"); + (p.mirror_vertical, p.mirror_horizontal) = (h, v); + }) + }; + assert_eq!(ids(&db, &qa5(true, false)), [] as [u32; 0]); + assert_eq!(ids(&db, &qa5(false, true)), [] as [u32; 0]); + assert_eq!(ids(&db, &qa5(true, true)), [2]); + // Length up to Last: in game 3, Bc4 stands after 3.Bc4, 3...Bc5 and 4.d3. + let span = |last| { + position(|p| { + p.look_for = board_of("Bc4"); + p.length = 3; + p.last = last; + }) + }; + assert_eq!(ids(&db, &span(2)), [] as [u32; 0], "Last 2 counts only the position after 3.Bc4"); + assert_eq!(ids(&db, &span(3)), [3], "Last 3 counts 3.Bc4, 3...Bc5 and 4.d3"); + // The same man on one square in "Look for" and "Exclude" never matches; + // other men on that square in "Exclude" do not get in the way. + let conflict = |exclude: &str| { + position(|p| { + p.look_for = board_of("Bc4"); + p.exclude = board_of(exclude); + }) + }; + assert_eq!(ids(&db, &conflict("Bc4")), [] as [u32; 0]); + assert_eq!(ids(&db, &conflict("bc4 Nc4")), [1, 3]); +} + +#[test] +fn a_set_up_start_counts_with_its_own_move_number() { + use gigachess::{Color, Role}; + // Black to move on move 10: 10...Kd8 11.e4 Ke8. + let board = gigachess::fen::parse_fen("4k3/8/8/8/8/8/4P3/4K3 b - - 0 10").expect("a FEN"); + let pieces = [("e8", Role::King, Color::Black), ("e2", Role::Pawn, Color::White), ("e1", Role::King, Color::White)]; + let mut setup = classic::start_position(&pieces, true, 0, 0); + setup[3] = 10; + let toks = [Tok::Mv("e8d8"), Tok::Mv("e2e4"), Tok::Mv("d8e8"), Tok::End]; + let record = classic::move_record(0x40 | 4, Some(&setup), None, &classic::encode(&board, &toks, 4, false)); + let mut b = Builder::new(); + b.game(&record); + let temp = b.write("query_position_setup"); + let db = Database::open(temp.base()).expect("open"); + let window = |men: &str, first, last| { + position(|p| { + p.look_for = board_of(men); + (p.first, p.last) = (first, last); + }) + }; + assert_eq!(ids(&db, &window("Pe2 ke8", 10, 10)), [1], "the start position is move 10's"); + assert_eq!(ids(&db, &window("Pe2", 1, 9)), [] as [u32; 0]); + assert_eq!(ids(&db, &window("Pe4 kd8", 11, 11)), [1]); + assert_eq!(ids(&db, &window("Pe4", 1, 9)), [] as [u32; 0], "the game starts after the window"); +} + +/// The fragment, tested square by square: the reference the bitboards must equal. +fn reference_holds(q: &PositionQuery, board: &Board) -> bool { + use cbvault::query::Man; + [(false, false), (true, false), (false, true), (true, true)].iter().any(|&(h, v)| { + if (h && !q.mirror_vertical) || (v && !q.mirror_horizontal) { + return false; + } + let on = |sq: u8, man: Man| { + let sq = if h { sq ^ 7 } else { sq }; + let (sq, man) = if v { + let swapped = match man { + Man::Piece(c, r) => Man::Piece(c.other(), r), + Man::Any(c) => Man::Any(c.other()), + }; + (sq ^ 56, swapped) + } else { + (sq, man) + }; + match (board.piece_at(gigachess::Square::new(sq)), man) { + (Some(p), Man::Piece(c, r)) => p.color == c && p.role == r, + (Some(p), Man::Any(c)) => p.color == c, + (None, _) => false, + } + }; + q.look_for.men.iter().all(|&(s, m)| on(s, m)) + && (q.or.men.is_empty() || q.or.men.iter().any(|&(s, m)| on(s, m))) + && !q.exclude.men.iter().any(|&(s, m)| on(s, m)) + }) +} + +/// The games of [`LINES`] matching `q`, by replaying each with gigachess. +fn reference(q: &PositionQuery) -> Vec { + let mut out = Vec::new(); + for (i, line) in LINES.iter().enumerate() { + let mut board = Board::startpos(); + let mut positions = vec![(board, board.fullmove_number(), false)]; + for uci in line.split_whitespace() { + let number = board.fullmove_number(); + let mv = board.legal_moves().into_iter().find(|m| m.to_string() == uci).expect("a legal move"); + board.play(mv).expect("legal"); + positions.push((board, number, board.turn() == gigachess::Color::Black)); + } + // ChessBase's window: from the start through move max(Last, First + 1), + // and the position after White's following move. + let end = match q.window { + PositionWindow::ChessBaseCompatible => u32::from(q.last).max(u32::from(q.first) + 1), + PositionWindow::Strict => u32::from(q.last), + }; + let (mut run, mut hit) = (0, false); + for (b, n, after_white) in positions { + let n = u32::from(n); + if q.window == PositionWindow::Strict && n < u32::from(q.first) { + continue; + } + if n > end && !(q.window == PositionWindow::ChessBaseCompatible && n == end + 1 && after_white) { + break; + } + run = if reference_holds(q, &b) { run + 1 } else { 0 }; + hit |= run >= q.length; + } + if hit { + out.push(i as u32 + 1); + } + } + out +} + +#[test] +fn bitboards_equal_an_exhaustive_square_by_square_reference() { + use cbvault::query::{Fragment, Man}; + use gigachess::{Color, Role}; + let temp = twocbh_db("query_position_reference"); + let db = Database::open(temp.base()).expect("open"); + let run = |q: &PositionQuery| { + let query = GameDataQuery { position: Some(q.clone()), ..GameDataQuery::default() }; + assert_eq!(search(&db, &query, 1).expect("a search").ids, reference(q), "{q:?}"); + }; + let roles = [Role::Pawn, Role::Knight, Role::Bishop, Role::Rook, Role::Queen, Role::King]; + let mut men = Vec::new(); + for c in [Color::White, Color::Black] { + men.push(Man::Any(c)); + men.extend(roles.iter().map(|&r| Man::Piece(c, r))); + } + // Every man on every square, alone. + for &man in &men { + for sq in 0..64u8 { + run(&PositionQuery { look_for: Fragment { men: vec![(sq, man)] }, ..PositionQuery::default() }); + } + } + // Pseudo-random combinations of the three boards, mirrors and windows. + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |n: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed % n + }; + let mut combined = 0; + while combined < 2000 { + let counts = (next(3), next(3), next(3)); + let mut fragment = |count: u64| Fragment { + men: (0..count).map(|_| (next(64) as u8, men[next(men.len() as u64) as usize])).collect(), + }; + let (look_for, or, exclude) = (fragment(counts.0), fragment(counts.1), fragment(counts.2)); + let twice = look_for.men.iter().enumerate().any(|(i, a)| look_for.men[..i].iter().any(|b| a.0 == b.0)); + if twice || (look_for.is_empty() && or.is_empty() && exclude.is_empty()) { + continue; + } + let first = 1 + next(3) as u16; + run(&PositionQuery { + look_for, + or, + exclude, + mirror_vertical: next(2) == 1, + mirror_horizontal: next(2) == 1, + first, + last: first + next(4) as u16, + length: 1 + next(3) as u16, + window: if next(2) == 0 { PositionWindow::Strict } else { PositionWindow::ChessBaseCompatible }, + sacrifice: false, + }); + combined += 1; + } +} + +#[test] +fn start_position_match_does_not_decode_corrupt_first_move() { + use cbvault_chess::movetable::{Color as MColor, Piece as MPiece}; + // The queen cannot move through the d2 pawn. + let bad = twocbh::quiet(MColor::White, MPiece::Queen, "d1", "d8"); + let temp = twocbh_words_db("query_position_bad_first", &[vec![bad, 0xffff]]); + let db = Database::open(temp.base()).expect("open"); + let q = position(|p| p.look_for = board_of("Pe2")); + let found = search(&db, &q, 1).expect("search"); + assert_eq!(found.ids, [1]); + assert_eq!(found.failed, 0); + let q = position(|p| p.look_for = board_of("Pe4")); + let found = search(&db, &q, 1).expect("search"); + assert!(found.ids.is_empty()); + assert_eq!(found.failed, 1); + let mut q = position(|p| p.look_for = board_of("Pe2")); + q.endings = Endings { mate: true, ..Endings::default() }; + assert_eq!(search(&db, &q, 1).expect("search").failed, 1, "ending still needs replay"); +} + +#[test] +fn strict_window_and_execution_paths_agree() { + use cbvault::bridge::SearchContext; + use cbvault::query::{QueryPlan, SearchOptions}; + let temp = twocbh_db("query_position_strict"); + let db = Database::open(temp.base()).expect("open"); + let q = position(|p| { + p.look_for = board_of("Bc4"); + p.first = 1; + p.last = 2; + p.window = PositionWindow::Strict; + }); + assert!(ids(&db, &q).is_empty()); + let q = position(|p| { + p.look_for = board_of("Bc4"); + p.first = 3; + p.last = 3; + p.window = PositionWindow::Strict; + p.length = 2; + }); + assert_eq!(ids(&db, &q), [3]); + let q = position(|p| { + p.look_for = board_of("Pe2"); + p.first = 2; + p.last = 2; + p.window = PositionWindow::Strict; + }); + assert_eq!(ids(&db, &q), [2]); + let q = position(|p| p.look_for = board_of("Bc4")); + let expected = ids(&db, &q); + let context = SearchContext::new(2).expect("context"); + let plan = QueryPlan::new(&db, &q).expect("plan"); + let opts = SearchOptions { threads: 2, ..SearchOptions::default() }; + let mut visited = Vec::new(); + let stats = plan.visit(&context, opts, |id| visited.push(id)).expect("visit"); + assert!(stats.complete); + assert_eq!(visited, expected); + let pages = plan.prepare_pages(&context, opts).expect("pages"); + assert_eq!(pages.count(), expected.len() as u64); + assert_eq!(pages.page(0, 1).expect("page"), [1]); + assert_eq!(pages.page(1, 1).expect("page"), [3]); + assert!(pages.page(2, 1).expect("page").is_empty()); +} + +/// Exercise actual replay occupancy changes, not just static FEN predicates. +#[test] +fn special_moves_update_the_fragment_in_both_generations() { + let mut lines = vec![ + "e2e4 a7a6 e4e5 d7d5 e5d6".to_owned(), // en passant + "e2e4 e7e5 g1f3 b8c6 f1c4 g8f6 e1g1 f8c5 d2d3 e8g8".to_owned(), + "e2e4 -- g1f3 --".to_owned(), + ]; + // Both sides promote by capturing the original rook. Cover every role. + for role in ['q', 'r', 'b', 'n'] { + lines.push(format!("a2a4 h7h5 a4a5 h5h4 a5a6 h4h3 a6b7 h3g2 b7a8{role} g2h1{role}")); + } + let mut classic = Builder::new(); + let mut native = twocbh::Builder::new(); + let native_temp = cbvault_fixtures::TempDb::create("query_special_native"); + native.player("White", "Test"); + native.player("Black", "Test"); + native.tournament_with_type("Test", "ISR", 0, 0); + for line in &lines { + let mut toks: Vec<_> = + line.split_whitespace().map(|m| Tok::Mv(if m == "e1g1" || m == "e8g8" { "O-O" } else { m })).collect(); + toks.push(Tok::End); + let stream = classic::encode(&Board::startpos(), &toks, 0, false); + classic.game(&classic::move_record(0, None, None, &stream)); + let words = twocbh::words(&mut Board::startpos(), line); + let offset = native.moves(1, &words); + let record = native.game(offset); + twocbh::set_entities(record, 0, 1, 0); + record[0x30..0x40].copy_from_slice(&[0xff; 16]); + } + let classic_temp = classic.write("query_special_classic"); + native.write_to(&native_temp); + for temp in [&classic_temp, &native_temp] { + let db = Database::open(temp.base()).expect("open"); + let cases = [ + ("Pd6", "Xd5 xd5", 1, vec![1]), + ("Kg1 Rf1 kg8 rf8", "", 1, vec![2]), + ("Pe4 Nf3 pe7", "", 2, vec![3]), + ("Qa8 qh1", "", 1, vec![4]), + ("Ra8 rh1", "", 1, vec![5]), + ("Ba8 bh1", "", 1, vec![6]), + ("Na8 nh1", "", 1, vec![7]), + ]; + for (look, exclude, length, expected) in cases { + let q = position(|p| { + p.look_for = board_of(look); + if !exclude.is_empty() { + p.exclude = board_of(exclude); + } + p.length = length; + }); + let found = search(&db, &q, 1).expect("search"); + assert_eq!(found.failed, 0, "{look}"); + assert_eq!(found.ids, expected, "{look}"); + assert_eq!(ids(&db, &q), expected, "{look}"); + } + } +} + +#[test] +fn corrupt_alternative_is_not_needed_for_position_and_ending() { + use cbvault_chess::movetable::{Color as MColor, Piece as MPiece}; + let mut words = twocbh::words(&mut Board::startpos(), "f2f3 e7e5 g2g4 d8h4"); + words.extend([0xfffd, 0xffff]); + words.push(twocbh::quiet(MColor::Black, MPiece::Queen, "d8", "d1")); + words.push(0xffff); + let temp = twocbh_words_db("query_bad_alternative", &[words]); + let db = Database::open(temp.base()).expect("open"); + let mut q = position(|p| p.look_for = board_of("Pe2")); + q.endings = Endings { mate: true, ..Endings::default() }; + let found = search(&db, &q, 1).expect("search"); + assert_eq!(found.ids, [1]); + assert_eq!(found.failed, 0); +} + +#[test] +fn chess960_start_is_not_the_standard_board() { + let temp = cbvault_fixtures::TempDb::create("query_chess960_start"); + let mut b = twocbh::Builder::new(); + b.player("White", "Test"); + b.player("Black", "Test"); + b.tournament_with_type("Test", "ISR", 0, 0); + let mut board = cbvault_chess::start::start_board(&cbvault_chess::start::Start::Chess960(0)).unwrap(); + let mut words = vec![0xfffb, 0, 0xfffc]; + words.extend(twocbh::words_960(&mut board, 0, "d2d4")); + words.push(0xffff); + let offset = b.moves(2, &words); + let record = b.game(offset); + twocbh::set_entities(record, 0, 1, 0); + record[0x30..0x40].copy_from_slice(&[0xff; 16]); + b.write_to(&temp); + let db = Database::open(temp.base()).expect("open"); + // Scharnagl index 0 is BBQNNRKR, not BBNNRKRQ. + assert_eq!(ids(&db, &position(|p| p.look_for = board_of("Kg1 Ba1 Qc1"))), [1]); + assert_eq!(ids(&db, &position(|p| p.look_for = board_of("Kg1 Pd4"))), [1]); + assert!(ids(&db, &position(|p| p.look_for = board_of("Ke1"))).is_empty()); +} diff --git a/crates/cbvault/tests/twocbh_bridge.rs b/crates/cbvault/tests/twocbh_bridge.rs index e7a24914..cf859e53 100644 --- a/crates/cbvault/tests/twocbh_bridge.rs +++ b/crates/cbvault/tests/twocbh_bridge.rs @@ -215,7 +215,7 @@ fn test_twocbh_960_and_variations() { let temp = TempDb::create("twocbh_960_var_test"); let mut builder = Builder::new(); - // 1. Chess960 game (position 0: BBNNRKRQ) + // 1. Chess960 game (position 0: BBQNNRKR) let mut b960 = cbvault_chess::start::start_board(&cbvault_chess::start::Start::Chess960(0)).unwrap(); let move_words_960 = cbvault_fixtures::twocbh::words_960(&mut b960, 0, "d2d4"); let mut c960 = Vec::new(); diff --git a/docs/position-search-acceptance.md b/docs/position-search-acceptance.md new file mode 100644 index 00000000..61609eec --- /dev/null +++ b/docs/position-search-acceptance.md @@ -0,0 +1,220 @@ +# Private position-search acceptance (maintainer) + +Use a licensed local ChessBase installation and matching immutable source files. +Never upload proprietary databases, private IDs, or their fingerprints to GitHub. +The CI corpora are public CC0 fixtures; they are not substitutes for this oracle. + +## Build and collect baseline + +Fetch the integration branch and build the candidate CLI in release mode. Use +the same database revision in ChessBase and cbvault, not merely the same product +year. Check whether the database has analysis, deleted, text, or damaged records. +Write outputs outside the database directory. + +```sh +git fetch origin integration/position-search-pr11 +git switch --detach origin/integration/position-search-pr11 +cargo build --locked --release -p cbvault-cli +DB="/absolute/path/to/Mega Database 2026.2cbh" +OUT="/absolute/private/results" +mkdir -p "$OUT" +target/release/cbvault info "$DB" --json > "$OUT/info.json" +target/release/cbvault verify "$DB" --threads 4 --json > "$OUT/verify.json" +target/release/cbvault search "$DB" --look-for Pe2 --last-move 1 --ids-only --limit 0 --threads 4 > "$OUT/pe2.ids" 2> "$OUT/pe2.stats.json" +``` + +Record the build SHA, source revision, source record count, ChessBase version, +search settings, and timings. Reproduce the contributor's eleven documented +cases first on the identical Mega revision if available. Do not infer that a +different edition's counts are wrong just because they differ. + +## Independent ChessBase cases + +Run each with Include lines in search disabled unless intentionally testing it. + +| Case | Look for | Or | Exclude | Mirror | First/Length/Last | +|---|---|---|---|---|---| +| Initial board | Pe2 | | | none | 1/1/1 | +| Horizontal axis | Bh7 | | | horizontal | 1/1/40 | +| Vertical axis | Bh7 | | | vertical | 1/1/40 | +| Or | Bc4 | Nf5 | | none | 1/1/40 | +| Window endpoint | Pe4 pe5 Nf3 | | | none | 1/1/1 and 1/1/2 | +| Castling | Kg1 | | | none | 1/1/5 and 1/1/10 | +| Black castling | kg8 | | | none | 1/1/10 | +| First behavior | Kg1 | | | none | 10/1/10 and 10/1/40 | +| Persistence | Bc4 | | | none | 1/2/10 and 1/3/10 | +| Exclusion only | | | Xd5 xd5 | none | 1/2/10 | +| Joker and exclusions | Xf3 | | Nf3 | vertical | 1/2/10 | +| Mixed orientation | Ke1 | | | vertical | 1/2/5 | + +The mixed-orientation case should also be checked on a tiny controlled database +where a white king changes from e1 to d1 on its first move, with no other pieces +satisfying the predicate and no later qualifying positions. Set Length=2. +Distinguish an orientation that persists from a union of per-position matches. +Also include a controlled custom-start game with Black to move on move 10; +a zero-move record, an analysis record, and a variation-only hit. Record whether +the ChessBase dialog includes these records by default. + +## Exact membership + +Export or otherwise obtain ChessBase's independent result membership with a +verified mapping to physical cbvault IDs, not result-list row numbers or +renumbered copies. If only counts are obtainable, record that limitation; +counts are diagnostic evidence, not an exact membership pass. + +Use the existing schema in [search.md](search.md#local-reference-manifest-private-only). +Set the environment paths to the same licensed source files and execute: + +```sh +export CBVAULT_TEST_DB_2CBH="$DB" +python3 scripts/query-private-acceptance.py --position-only \ + --manifest "$OUT/position-manifest.json" \ + --cli target/release/cbvault --report "$OUT/position-report.json" +``` + +A classic source may be supplied with CBVAULT_TEST_DB. The diagnostic supports +one or more independently mapped sources. It checks mapped/positioned modes +and available worker configurations, and reports missing/extra counts and +bounded ID samples. A position-only report is not the full release gate. + +Investigate the Pe2 differences first: classify discrepant IDs as live games, +analysis, deleted/guiding text, custom setups, malformed initial boards, +corrupt move streams or mapping differences. Compare the original contributor +revision with the candidate to isolate the initial-board early-stop effect. +Do not include analysis records by changing the public API until independent +ChessBase evidence establishes the intended eligibility. Strict move windows +are a separate library contract, not a ChessBase parity claim. + +A release decision requires exact memberships or individually explained +differences, public CI, and fresh performance measurements. Preserve the +contributor's original results as historical measurements. + +## Automated local audit + +Use a separate worktree for the contributor (pinned revision +`0c6e42642eb06809bb2a114f6fd81059f1573adc`). Build each executable independently, +and use its absolute path. Keep the database closed for edits throughout the +audit. The following outputs may include licensed game data and must stay local. + +```sh +python3 -m venv "$OUT/position-venv" +"$OUT/position-venv/bin/pip" install -r scripts/requirements-position-audit.txt +PY="$OUT/position-venv/bin/python" +CANDIDATE="/absolute/candidate/target/release/cbvault" +CONTRIBUTOR="/absolute/contributor/target/release/cbvault" +"$PY" scripts/position-audit.py fixture --out "$OUT/controlled" +"$PY" scripts/position-audit.py collect --db "$DB" --candidate "$CANDIDATE" \ + --contributor "$CONTRIBUTOR" --case pe2-last1 --out "$OUT/pe2-initial" +``` + +Start with Pe2 before spending time on all eleven cases. The collector records +binary and source SHA-256 hashes, statistics, complete ordered IDs and exact +missing/extra lists. Native record counts exclude the reserved header slot 0. +It checks source file size and modification time after scanning. This is an +additional immutability check, not a replacement for keeping the DB closed. + +Import controlled.pgn into **new scratch databases** in both ChessBase formats. +Use the unique CBV-audit-* Event tags for identity, not copied row numbers. +expected.json gives candidate semantics and alternative fixed-orientation +semantics independently evaluated with python-chess. The zero-move import may +be dropped by ChessBase: record that as an import limitation. Create analysis, +deleted and guiding-text records separately in the ChessBase GUI; PGN cannot +preserve these record kinds. Record all settings and observed memberships. +Do not claim that expected.json is actual ChessBase output. + +For the real source, place one independently mapped sorted physical ID per line +in each ChessBase result file, named by case (for example pe2-last1.ids). +Do not copy result-list row numbers. Verify source identity and mapping against +a representative selection of original records. If there is no reliable +mapping, record counts only and keep the exact-membership gate blocked. + +```sh +"$PY" scripts/position-audit.py collect --db "$DB" --candidate "$CANDIDATE" \ + --contributor "$CONTRIBUTOR" --chessbase-ids "$OUT/chessbase-ids" \ + --id-mapping "Describe the verified mapping method here" --out "$OUT/full-comparison" +"$PY" scripts/position-audit.py inspect --db "$DB" --candidate "$CANDIDATE" \ + --contributor "$CONTRIBUTOR" --case pe2-last1 --direction missing \ + --ids "$OUT/full-comparison/pe2-last1.vs-chessbase.missing.ids" \ + --out "$OUT/pe2-missing-inspection" +``` + +Repeat inspect for the extra ID file with --direction extra. Where possible, +export each disputed original game directly from ChessBase to a separate +.pgn file, in UTF-8, and rerun inspect into a new output directory +with --chessbase-pgn-dir pointing to those exports. evidence.jsonl contains +record-kind/deletion metadata, per-record search results from each revision, +independent replay witnesses of the exported PGN and a provisional classification. +Corruption, invalid PGN and absent independent exports are evidence gaps, not +proof of a false negative. Compare game identity before interpreting a decoder +discrepancy. Each pair of readable exports also receives an export_comparison containing +tag comparisons, mainline lengths, and the first divergent ply with both +FENs and moves. Counter-only, board-state, variant, move-encoding and +length differences are distinguished. A tag conflict or insufficient tags +requires source identity review before blaming either search implementation. +Legal en passant normalization avoids differences caused only by PGN +exporter conventions. Matching tags are only a plausibility check, not proof +of correct physical-ID mapping. A differing mainline takes precedence over +an apparent agreement in query membership. + +Classifications require human adjudication; the script does not +automatically certify either search engine. + +The public CI smoke tier runs a separate python-chess oracle on 512 verified +contiguous records per format. This independently tests fragment evaluation, +not decoding: its PGN is exported by the candidate. Independent ChessBase PGN +is needed for decoder adjudication. The controlled fixtures and their expected +results are published only as synthetic CI artifacts. The private collector +and inspection output must not be uploaded. + +## Exact-position index cross-check + +The downstream hash index stores distinct Polyglot keys and game IDs, not +fragment masks or ply ordinals. For disputed games, extract the exact witness +FEN from independent replay and query the existing index for that FEN. Compare +membership with a full exact-position replay, under the same mainline and record +eligibility policies. Verify full positions to rule out hash collisions and +remember that Polyglot includes turn, castling and en passant state but not +move counters. The witness need not represent every board satisfying a fragment. +An index derived from CBVault is not an independent decoder oracle, and complete +game indexing can exclude a game whose early fragment matched before corruption. +Never require a full Mega index rebuild to start this investigation. + +## Merge gate + +Public tests, including the paired benchmarks, passed at bff110a (all eight jobs). Keep the +licensed comparison task open until complete independent ID lists, controlled +ChessBase behavior, and an explanation or regression fix for every difference +are available. Strict mode is separately specified; do not silently change it +to imitate unexpected commercial search behavior. + +For an executable exact-key replay comparator (one unique source ID per line): + +```sh +cargo build --locked --release -p cbvault --example exact_position_ids +FEN="independent witness FEN here" +target/release/examples/exact_position_ids "$DB" "$FEN" 4 "$OUT/exact-replay.ids" 2> "$OUT/exact-replay.json" +"$PY" scripts/position-audit.py compare --actual "$OUT/exact-replay.ids" \ + --reference "$OUT/exact-index.ids" --records SEARCHABLE_RECORD_COUNT \ + --out "$OUT/exact-comparison" +``` + +Export exact-index.ids using the downstream index lookup for the identical FEN, +as sorted unique original game IDs. Check the index manifest against the same +source snapshot. exact_position_ids reports replay failures separately; a +complete search with failures is not evidence of index completeness. Inspect +differing games and full boards, rather than treating key equality as collision- +free proof. + +The public smoke gate additionally verifies the full pinned 25,000-game PGN +against three independent python-chess Polyglot-key memberships, in both +formats and both I/O modes, with one and four workers. It exercises the actual +collector and per-record inspector against public data. Equivalent public +native generations must agree on ordered fragment IDs, not just counts. +These tests do not establish licensed ChessBase parity. + +The synthetic public negative controls replace one matching ID with one +nonmatching ID (equal total counts) and compare both identical and deliberately +altered PGN exports. These are explicitly test doubles, never actual ChessBase +results. They verify that an apparently correct count cannot hide missing and +extra memberships and that a differing decoded board is not attributed to +ChessBase search semantics. diff --git a/docs/provenance.md b/docs/provenance.md index fb135be2..125e9f57 100644 --- a/docs/provenance.md +++ b/docs/provenance.md @@ -167,6 +167,7 @@ State: `planned` until the porting task lands; then `ported`/`ported (chess swap | `cbvault-chess::ctg` — stored form (colour flip, mirror), keys, move decoding | Original; same evidence. Verified on the whole probed book: 27,592,793/27,592,793 keys round-trip and 28,264,190/28,264,190 decoded moves lead to a position that is in the book | | `cbvault::book` — `Book`, the in-memory index, `probe`, `verify`; `cbvault-cli` `book` | Original. The index hash (FNV-1a + SplitMix64) is this crate's own choice; the book's `.cto` hash is not established and is not used | | `cbvault::query` — the "Game data" search; `cbvault-cli` `search` | Original contributor work by Tulio Vianna (PR #9, `search-game-data`); maintainer adaptation in `integrate-game-data-search-v03` shares the bridge execution and canonical entity/replay readers. The fields and their meanings are those of ChessBase's own search dialog as a user sees it; the matching rules are checked against the counts ChessBase gives on a test database. One format fact was established here from the reference database: a 2CBH header's annotator id indexes the **player** table (annotator ids name players such as "ChessBase" and "Kasparov") | +| `cbvault::query::PositionQuery` — the "Position" page; `cbvault-cli` `search --look-for …` | Original (`search-position`). The controls and their meanings are those of ChessBase's dialog and its public help page ("Search mask – Position"); the points the help leaves open (the mirror axes, how "Or" combines, whether the start position counts) are compared with the counts ChessBase gives on a reference database. No third-party position-search code was read; `gigachess` bitboards and replay are the oracle | | `cbvault-chess` — gigachess bridge helpers (start boards, key alignment) | Task 3.3 | | `scripts/oracles/**`, `scripts/fetch-ancestor.sh`, benchmark harness | Tasks 0.4, 0.7, 6.2 | | `crates/cbvault-format/fuzz/` (`cbh_record`, `cbg_framing` targets + seed corpus) | Original (`low-memory-footprint` tasks 3.1–3.2): harness calls only the public `GameHeader`/`GameMoves` readers over fuzzer bytes; seeds are zeros, ones and a minimal record head, no database bytes | diff --git a/docs/search.md b/docs/search.md index 73892911..a72e0a22 100644 --- a/docs/search.md +++ b/docs/search.md @@ -1,8 +1,8 @@ -# Searching a database: the "Game data" page +# Searching a database: the "Game data" and "Position" pages -`cbvault::query` answers the supported fields of the **Game data** page of ChessBase's -search dialog, combined, over a raw classic (`.cbh`) or 2CBH (`.2cbh`) -database. `cbvault search` is the same query from the command line. +`cbvault::query` answers the supported fields of the **Game data** and +**Position** pages of ChessBase's search dialog, combined, over a raw classic +(`.cbh`) or 2CBH (`.2cbh`) database. `cbvault search` is the same query from the command line. ```rust,no_run use cbvault::bridge::{Database, Range}; @@ -55,6 +55,68 @@ removed, so `gonzalez` finds `González` and the decomposed Latin spelling. Cano A bridge `Filter` can be added as one more criterion with `GameDataQuery::extra`. +## The "Position" page + +`GameDataQuery::position` (a `PositionQuery`) adds the "Position" page: a +partial position that must stand on the board at some point of the main line. +It combines with every field above, which are checked first, on the header. + +```bash +cbvault search "Mega Database 2026.2cbh" --look-for "Bh7 kg8" --mirror v \ + --elo 2600- --elo-mode both --result 1-0 +``` + +| Dialog | `PositionQuery` | `cbvault search` | Meaning | +|---|---|---|---| +| "Look for" board | `look_for` (`Fragment`) | `--look-for BOARD` | Every man set stands on its square; other squares are free | +| "Or" board | `or` | `--or BOARD` | At least one of its men stands on its square, together with "Look for". A square may hold several men | +| "Exclude" board | `exclude` | `--exclude BOARD` | None of its men stands on its square. A square may hold several men | +| White and black jokers | `Man::Any(colour)` | `X`, `x` | Any man of that colour, pawn or piece | +| Mirror: Horizontal | `mirror_horizontal` | `--mirror h` | Also the fragment reflected across the horizontal axis (1↔8), with the colours swapped | +| Mirror: Vertical | `mirror_vertical` | `--mirror v` | Also the fragment reflected across the vertical axis (a↔h). Both boxes add the reflection through the centre as well | +| First, Last | `first`, `last` | `--first-move N`, `--last-move N` | As ChessBase answers them (measured, see below): every position from the start through move `max(Last, First + 1)` counts, and so does the position after White's following move. The position after a move has that move's number; the start position, the number of the first move to come. Defaults 1 and 40 | +| Window | `window` (`PositionWindow`) | `--position-window chessbase\|strict` | Default ChessBase compatibility; strict counts only positions labelled First through Last, including a start position labelled with its own fullmove number | +| Length | `length` | `--length N` | The fragment stands in this many consecutive counted positions (plies). Each position may match a different enabled mirror orientation; ChessBase parity for that case remains unverified. Default 1 | +| Sacrifice | `sacrifice` | `--sacrifice` | Refused with `QueryError::Unsupported`: ChessBase's sacrifice detection is its own look-ahead, and which sacrifices it finds is not established | + +`BOARD` is men and squares separated by spaces or commas: `KQRBNP` are White's +pieces, `kqrbnp` Black's, `X` and `x` the jokers; one letter may take several +squares (`Kg1 Rf1 Pf2g2h2 bh7`). `parse_fragment` reads the same text. + +Only the **main line** of live game records is searched, from its start position. Analysis/position-only records and guiding texts are not included; whether ChessBase includes analysis records in this dialog remains to be verified. A board with two +men on one "Look for" square, empty boards, or First after Last are refused +with `QueryError::Invalid`. + +The fragment compiles to bitboards, one set per orientation, so testing a +position is a dozen integer operations. The main line is replayed with the +same walk as the ending stage, and stops as soon as the answer is known: at +the first match (including the validated start board, before decoding moves, unless the final position is also asked for), when the configured window is exhausted, or at the end of the main line. + +Measured on Mega Database 2026 (2CBH, 11,740,862 records), warm, +`CBVAULT_QUERY_REPORT=1 cargo bench -p cbvault --bench query`: + +| Query | Matches | 1 thread | 10 threads | +|---|---:|---:|---:| +| White bishop on h7, moves 1-40 (replays every game) | 211,902 | 44.680 s | 7.120 s | +| White pawn on e2, move 1 (stops after the first move) | 11,737,194 | 2.597 s | 0.448 s | +| White bishop on h7, Elo ≥ 2700 both (the header stage keeps 35,561) | 611 | 0.440 s | 0.084 s | + +A fragment over the whole database costs about what a full main-line replay +costs (ADR-007 §3); header criteria in the same query cut it to the games they +keep. An ending-only query keeps its own sink: "mate, 2025 on" measured +2.70 s / 0.416 s before this change and 2.67 s / 0.407 s after (one / ten +threads, mean of three alternating runs). On the 20,000-game fixture, one +thread: `query_mate_1_thread` 3.60 ms before, 3.53 ms after; +`query_position_1_thread` 4.01 ms. + +The public native-corpus CI additionally measures the candidate position search +on both generations, in mapped/positioned mode with 1/4 workers, comparing exact +ordered membership fingerprints within each generation and match counts across +the equivalent corpora. Integration PR CI also alternates candidate and original +contributor binaries on common compatible queries, checks identical membership +and records median timings. Strict windows are candidate-only. Timings are +diagnostics, not universal speed gates. + ## How it runs 1. **Name fields are cached lazily.** Canonical readers populate compact folded fields once per database/name table. Both player lines, annotator (native) and any text share the player scan. Cancelled builds are not published; no lock is held during I/O. @@ -109,14 +171,31 @@ Run `scripts/query-paired-bench.py --report /absolute/private/report.json` for t query refuses it rather than guessing. - **Good games / Beautiful games**: which header, flag or medal bits ChessBase uses is not established; they are not offered. -- **In repertoire** needs a position search, which this page does not cover. -- Matching rules compared with ChessBase's own counts on Mega Database 2026 so - far, all equal: White `Carlsen` (4,363 games), White `Carlsen` and Black - `Caruana` with ignored colours (212), White `Gonzalez` without the accent - (22,438) and Annotator `Kasparov` (67). Still to compare: "wins only", the - Elo modes with a missing rating, whether "Difference" is an upper or a lower - bound, whether "Check" includes mate, a tournament text in the middle of - a title, mixed score/ending selections, and missing/unknown time-control flags. +- **In repertoire** needs a repertoire database's positions; it is not offered yet. +- **Sacrifice** on the "Position" page: ChessBase's own look-ahead, refused. +- The **Position** page is searched in the **main line** only, as ChessBase + does unless "Include lines in search" is ticked (not offered here). Its + rules were set from ChessBase's own counts on Mega Database 2026: the mirror + axes, "Or" as "Look for and at least one Or man", the start position, and + the window of moves. The last one is not what the dialog's labels suggest: + ChessBase looks at every position from the start through move + `max(Last, First + 1)`, plus the position after White's following move. + + | Search (defaults unless stated) | ChessBase | cbvault | + |---|---:|---:| + | wBh7, Horizontal | 344,642 | 344,630 | + | wBh7, Vertical | 395,103 | 395,089 | + | wBc4, Or wNf5 | 47,245 | 47,244 | + | wPe2, Last 1 | 11,737,625 | 11,737,194 | + | wPe4 bPe5 wNf3, Last 1 | 1,323,164 | 1,323,125 | + | wPe4 bPe5 wNf3, Last 2 | 1,323,164 | 1,323,125 | + | wKg1, Last 5 | 2,125,503 | 2,125,073 | + | wKg1, Last 10 | 7,308,826 | 7,308,249 | + | bKg8, Last 10 | 6,702,349 | 6,701,773 | + | wKg1, First 10, Last 10 | 7,794,831 | 7,794,229 | + | wKg1, First 10, Last 40 | 9,239,530 | 9,239,209 | + + The remaining differences (at most 0.03%) are not explained yet. ## Local reference manifest (private only) @@ -124,6 +203,7 @@ The private membership gate requires `CBVAULT_QUERY_GOLD_MANIFEST`, an absolute JSON path on the licensed database host. Do not commit it. Schema 1 has `oracle: "independent-chessbase"` and a `datasets` array with roles classic, native and special. Each dataset has `db` (absolute header path), `records`, +(one-based searchable records, excluding reserved file header slot 0), `reference_revision`, `id_mapping` (description of how reference game IDs were mapped to physical 1-based CBVault records), `members` (all member paths and SHA-256 hashes), and `cases`. Fingerprint the actual same-stem reader @@ -142,7 +222,11 @@ Use the same licensed main databases as existing private gold tests. The script checks source and reference fingerprints, exact ordered membership, counts and failure diagnostics across mapped/positioned reads and 1/4/10 workers (bounded by available hardware). This is a correctness gate, not a -substitute for private paired performance and resource acceptance. +substitute for private paired performance and resource acceptance. Position +criteria can be included in the manifest; `--position-only` runs just those +cases on one or more independently fingerprinted sources as a diagnostic, +not as a substitute for the full gate. Reports give exact missing/extra +counts and bounded samples of physical IDs for local adjudication. ## Continuous GitHub acceptance diff --git a/openspec/changes/search-position/proposal.md b/openspec/changes/search-position/proposal.md new file mode 100644 index 00000000..956a2680 --- /dev/null +++ b/openspec/changes/search-position/proposal.md @@ -0,0 +1,51 @@ +## Why + +The "Game data" search answers the header fields of ChessBase's search dialog, +but its **Position** page is the one a player reaches for when studying a +structure or a pattern: a partial position ("a white bishop on h7 with the +black king on g8", "an isolated d-pawn") that must stand on the board at some +point of a game. The page has three boards ("Look for", "Or", "Exclude"), +jokers for any man of a colour, horizontal and vertical mirrors, and a window +of moves with a minimum length. Roadmap item 5, +`advanced-position-search-and-index-feeds`, asks for exactly this kind of +explicitly defined partial-board predicate, with gigachess replay as the +oracle; this change delivers the dialog's page as one such predicate. + +## What Changes + +- `cbvault::query::PositionQuery`, one value per control of the page, set on + `GameDataQuery::position` and combined with every "Game data" field: + - `Fragment`s of `Man`s (a piece of a colour, or a joker) on squares; + - `mirror_horizontal` (ranks, colours swapped), `mirror_vertical` (files); + - `first`, `length`, `last`, with the dialog's defaults (1, 1, 40); + - `sacrifice`, refused with `QueryError::Unsupported` (ChessBase's own + look-ahead; not established). +- The fragment compiles to bitboards per orientation, and the existing replay + stage (the one that classifies mate, stalemate and check) tests it on every + position of the main line in the same single replay, stopping as soon as the + answer is known. +- `parse_fragment`: the text form of a board (`Kg1 Rf1 Pf2g2h2 bh7 xe5`). +- `cbvault search` gains `--look-for`, `--or`, `--exclude`, `--mirror h|v|hv`, + `--first-move`, `--length`, `--last-move` and `--sacrifice`. +- Fixture and whole-database benchmarks for the position stage, and a + before/after measurement of the shared replay stage. + +**Not changed:** the header stage, the bridge, and the replay walker. The +ending stage's sink is extended, not replaced: an ending-only query does the +same work as before. + +## Capabilities + +### Modified Capabilities +- `cbvault`: the ChessBase-style search gains the "Position" page. + +## Impact + +- New: `crates/cbvault/src/query/position.rs`, + `crates/cbvault/tests/query_position.rs`. +- Touched: `query/{mod,header,scan,ending,parse}.rs`, + `crates/cbvault-cli/src/search.rs`, `crates/cbvault-cli/tests/cli_search.rs`, + `crates/cbvault/benches/query.rs`, `docs/search.md`, README, CHANGELOG, + `docs/provenance.md`. +- Additive API: one new field on `GameDataQuery` (a struct literal without + `..Default::default()` must add it). No new dependency. diff --git a/openspec/changes/search-position/specs/cbvault/spec.md b/openspec/changes/search-position/specs/cbvault/spec.md new file mode 100644 index 00000000..a777e88a --- /dev/null +++ b/openspec/changes/search-position/specs/cbvault/spec.md @@ -0,0 +1,43 @@ +## ADDED Requirements + +### Requirement: A ChessBase-style "Position" search + +The library SHALL answer the "Position" page of ChessBase's search dialog, +combined with the "Game data" fields, over a classic or a 2CBH database: a +"Look for", an "Or" and an "Exclude" board of men on squares, where a man is a +piece of a colour or any man of a colour; horizontal and vertical mirrors; and +First, Length and Last. A game SHALL match when, among the positions of its +main line counted by ChessBase's window (from the start through move +max(Last, First + 1), plus the position after White's following move), the +fragment holds in at least Length consecutive positions. The results SHALL be the same at any +thread count and SHALL equal an exhaustive gigachess replay of the main line. + +#### Scenario: Boards and jokers +- **WHEN** the "Look for" board holds men, the "Or" board alternatives and the "Exclude" board men +- **THEN** a position holds the fragment when every "Look for" man stands on its square, at least one "Or" man (if any) stands on its square, and no "Exclude" man does +- **AND** a joker matches any man of its colour, and squares left empty are unconstrained. + +#### Scenario: Mirrors +- **WHEN** "Horizontal" is set +- **THEN** the fragment reflected across the horizontal axis (ranks 1↔8), with the colours swapped, also matches +- **AND** with "Vertical" set, the fragment reflected across the vertical axis (files a↔h) also matches. + +#### Scenario: First, Length and Last +- **WHEN** First, Length and Last are given +- **THEN** the positions from the start through move max(Last, First + 1) count, and the position after White's following move +- **AND** the fragment must hold in Length consecutive counted positions. +- **AND** an explicit strict window instead counts only positions labelled with a move number in First..=Last (the start board is labelled with its own fullmove number). + +#### Scenario: Only the main line +- **WHEN** a fragment stands only in a variation +- **THEN** the game does not match. + +#### Scenario: Unanswerable pages are refused +- **WHEN** "Sacrifice" is set +- **THEN** the query is refused with `QueryError::Unsupported` +- **AND** empty boards, two men on one "Look for" square, or First after Last are refused with `QueryError::Invalid`. + +#### Scenario: The replay stops early +- **WHEN** the answer is known before the end of the main line +- **THEN** the replay of that game stops, unless a matching fragment still needs the final position checked. +- **AND** a validated initial board is evaluated before decoding the first move; a corrupt unneeded suffix does not invalidate a settled answer. diff --git a/openspec/changes/search-position/tasks.md b/openspec/changes/search-position/tasks.md new file mode 100644 index 00000000..a5010e7e --- /dev/null +++ b/openspec/changes/search-position/tasks.md @@ -0,0 +1,41 @@ +# Tasks + +## 1. Implement + +- [x] 1.1 `PositionQuery`, `Fragment`, `Man`; validation and the `Sacrifice` refusal +- [x] 1.2 Bitboard compilation per orientation (vertical a↔h, horizontal 1↔8 with colours swapped, both) +- [x] 1.3 One replay for endings and fragment, main line only, with early stop +- [x] 1.4 `parse_fragment` and the `cbvault search` options + +## 2. Tests + +- [x] 2.1 Each board, jokers, mirrors, First/Length/Last, combinations with names and endings, on a classic and a 2CBH fixture; thread-count invariance +- [x] 2.2 A fragment standing only in a variation does not match +- [x] 2.3 Refusals and cancellation +- [x] 2.4 CLI options and bad options +- [x] 2.6 Review follow-up: 2CBH variation, both mirrors, a set-up start (Black to move, move 10), Length up to Last, Look for / Exclude on one square, a corrupt move right after Last, and an exhaustive square-by-square gigachess reference (every man on every square, plus 2,000 pseudo-random combinations) +- [x] 2.5 Spot checks against ChessBase on Mega Database 2026 (counts in `docs/search.md`): mirror axes, "Or" and the start position agree; observed move-window behavior is implemented; exact membership and Length/mirror persistence remain to be checked + +## 3. Measurements + +- [x] 3.1 Fixture gates: the ending stage before and after, and the position stage +- [x] 3.2 Whole-database report on Mega Database 2026 (2CBH), 1 and 10 threads + +## 4. Documentation + +- [x] 4.1 `docs/search.md`, README, CHANGELOG, provenance row + +## 5. Maintainer integration acceptance + +- [x] 5.1 Evaluate the validated start board before decoding moves; retain ending-only behavior. +- [x] 5.2 Expose an explicit strict move window alongside the default ChessBase-compatible window. +- [x] 5.3 Add corrupt-first-move, strict-window and ordered visit/page regression cases, and run position tests in positioned-read CI. +- [x] 5.4 Cross-platform CI on the integrated candidate (bff110a, 6/6 functional jobs and 2/2 paired jobs; rerun on final head). +- [ ] 5.5 Independent licensed ChessBase exact-membership comparisons, record-kind and replay-failure adjudication, Length/mirror semantics. +- [ ] 5.6 Final paired performance measurements and release acceptance. +- [x] 5.7 Add generated special-move, strict oracle, Chess960 and corrupt-alternative regressions. +- [x] 5.8 Add public native corpus position diagnostics and private acceptance runbook. +- [x] 5.9 Prepare complete local discrepancy capture, independent python-chess oracle, controlled PGN and record adjudication tooling. +- [ ] 5.10 Verify independent ChessBase exports, controlled cases and all disputed memberships before merge. +- [x] 5.11 Verify public cross-generation ordered fragment memberships, independent PGN matcher (44 case/format checks), full 25,000-game exact-key oracle (24 configurations) and public audit tooling (bff110a). +- [ ] 5.12 Run synthetic external-ID and divergent-export negative controls in CI and retain the final results. diff --git a/scripts/bench-corpus/position-bench.py b/scripts/bench-corpus/position-bench.py new file mode 100644 index 00000000..d5fa2b6f --- /dev/null +++ b/scripts/bench-corpus/position-bench.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Public native-corpus position diagnostics; timings are observations, not gates. +No proprietary fixtures. Compare exact ordered IDs across execution modes and +worker counts within each generation, and exact ordered IDs between equivalent corpora. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import statistics +import subprocess + +CASES = { + "start": ["--look-for", "Pe2", "--last-move", "1"], + "rare": ["--look-for", "Bh7"], + "window": ["--look-for", "Kg1", "--first-move", "10", "--last-move", "20", + "--position-window", "strict"], + "mirrors_length": ["--look-for", "Bh7", "--or", "Nf5 Ng5", "--exclude", "pg6", + "--mirror", "hv", "--length", "2"], + "combined": ["--look-for", "Nf3", "--elo", "2200-", "--elo-mode", "both"], + "ending": ["--look-for", "Pe2", "--result", "mate"], +} + + +def run(cli, db, args, threads, mode, slots): + cmd = [str(cli), "search", str(db), *args, "--threads", str(threads), + "--ids-only", "--limit", "0", "--json"] + if mode == "positioned": + cmd += ["--no-mmap"] + env = dict(os.environ) + env.pop("CBVAULT_NO_MMAP", None) + env.pop("CBVAULT_MMAP", None) + result = subprocess.run(cmd, capture_output=True, text=True, check=True, env=env) + stats = json.loads(result.stdout) + ids = stats.pop("ids") + if (not stats["complete"] or stats["failed"] != 0 or stats["records"] != slots + or stats["matches"] != len(ids) or any(not 0 < i <= slots for i in ids) + or any(a >= b for a, b in zip(ids, ids[1:]))): + raise ValueError(f"invalid corpus query result: {db.name}: {args}: {stats}") + stats["ids_sha256"] = hashlib.sha256( + b"".join(i.to_bytes(4, "little") for i in ids)).hexdigest() + return stats + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--cli", type=Path, required=True) + p.add_argument("--reference-cli", type=Path, help="Optional contributor revision supporting compatible queries") + p.add_argument("--fixtures", type=Path, required=True) + p.add_argument("--tier", choices=["smoke", "extreme"], required=True) + p.add_argument("--report", type=Path, required=True) + p.add_argument("--repetitions", type=int, default=3) + a = p.parse_args() + if a.repetitions < 1: + p.error("repetitions must be positive") + manifest = json.loads(Path(__file__).with_name("native-manifest.json").read_text())["tiers"][a.tier] + report = {"tier": a.tier, "archive_sha256": manifest["sha256"], "private_gold": "NOT RUN", + "passed": False, "cases": []} + memberships = {} + try: + for ext in ("cbh", "2cbh"): + db = a.fixtures / (manifest["stem"] + "." + ext) + # The 2CBH native manifest counts slot 0 (the file header). + # Search uses one-based game IDs and excludes that physical slot. + records = manifest["slots"][ext] - (ext == "2cbh") + for name, args in CASES.items(): + expected = None + for mode in ("mapped", "positioned"): + for threads in (1, 4): + executables = {"candidate": a.cli.resolve()} + if a.reference_cli and "--position-window" not in args: + executables["contributor"] = a.reference_cli.resolve() + samples = {side: [] for side in executables} + for rep in range(-1, a.repetitions): + order = list(executables) + if rep % 2 == 0: + order.reverse() + for side in order: + stats = run(executables[side], db, args, threads, mode, records) + signature = (stats["matches"], stats["ids_sha256"], stats["replayed"], stats["failed"]) + if expected is None: + expected = signature + if signature != expected: + raise ValueError(f"membership or replay diagnostics differ: {side}/{ext}/{name}/{mode}/{threads}: {signature} != {expected}") + if rep >= 0: + samples[side].append(stats["seconds"]) + row = dict(format=ext, query=name, args=args, mode=mode, threads=threads, + matches=expected[0], ids_sha256=expected[1], replayed=expected[2], + failed=expected[3], median_seconds=statistics.median(samples["candidate"]), + seconds=samples["candidate"]) + if "contributor" in samples: + row["contributor_seconds"] = samples["contributor"] + row["contributor_median_seconds"] = statistics.median(samples["contributor"]) + row["candidate_speedup"] = row["contributor_median_seconds"] / max(row["median_seconds"], 1e-9) + report["cases"].append(row) + print(json.dumps(row), flush=True) + membership = expected[:2] + if name in memberships and memberships[name] != membership: + raise ValueError(f"cross-generation ordered membership differs: {name}") + memberships[name] = membership + report["passed"] = True + finally: + a.report.parent.mkdir(parents=True, exist_ok=True) + a.report.write_text(json.dumps(report, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/position-audit.py b/scripts/position-audit.py new file mode 100644 index 00000000..815a47c5 --- /dev/null +++ b/scripts/position-audit.py @@ -0,0 +1,553 @@ +#!/usr/bin/env python3 +"""Local position-search audit. Independent PGN replay uses python-chess. +All outputs from licensed data stay local. No result is assumed independent +merely because it came from a different CBVault executable. +""" +import argparse +import hashlib +import json +from pathlib import Path +import subprocess + +# Exact contributor settings. Names also identify the expected ChessBase ID files. +CASES = { + "bh7-horizontal": ["--look-for", "Bh7", "--mirror", "h"], + "bh7-vertical": ["--look-for", "Bh7", "--mirror", "v"], + "bc4-or-nf5": ["--look-for", "Bc4", "--or", "Nf5"], + "pe2-last1": ["--look-for", "Pe2", "--last-move", "1"], + "opening-last1": ["--look-for", "Pe4 pe5 Nf3", "--last-move", "1"], + "opening-last2": ["--look-for", "Pe4 pe5 Nf3", "--last-move", "2"], + "kg1-last5": ["--look-for", "Kg1", "--last-move", "5"], + "kg1-last10": ["--look-for", "Kg1", "--last-move", "10"], + "black-kg8-last10": ["--look-for", "kg8", "--last-move", "10"], + "kg1-first10-last10": ["--look-for", "Kg1", "--first-move", "10", "--last-move", "10"], + "kg1-first10-last40": ["--look-for", "Kg1", "--first-move", "10", "--last-move", "40"], +} +CONTROL = { + "mirror-switch": ["--look-for", "Ke1", "--mirror", "v", "--length", "2", "--last-move", "5"], + "length2": ["--look-for", "Bc4", "--length", "2", "--last-move", "10"], + "length3": ["--look-for", "Bc4", "--length", "3", "--last-move", "10"], + "extra-white": ["--look-for", "Pe4", "--last-move", "2"], + "initial-extra": ["--look-for", "Pe2", "--last-move", "2"], + "strict": ["--look-for", "Pe4", "--first-move", "3", "--last-move", "3", "--position-window", "strict"], + "ep": ["--look-for", "Pd6", "--exclude", "Xd5 xd5"], + "promotion": ["--look-for", "Na8 nh1"], + "variation": ["--look-for", "Bc4"], + "exclude-only": ["--exclude", "Xd5 xd5", "--length", "2"], + "joker": ["--look-for", "Xf3", "--exclude", "Nf3", "--mirror", "v"], +} + + +def chess_module(): + import chess + import chess.pgn + return chess + + +def parse_board(text): + chess = chess_module() + pieces = [] + for word in text.replace(",", " ").replace(";", " ").split(): + role = word[0].lower() + if role not in "kqrbnpx" or len(word) < 3 or len(word) % 2 != 1: + raise ValueError(f"invalid fragment: {word}") + for i in range(1, len(word), 2): + pieces.append((chess.parse_square(word[i:i+2].lower()), + word[0].isupper(), role)) + return pieces + + +def compile_query(args): + # Only position predicates: never silently ignore a metadata condition. + allowed = {"--look-for", "--or", "--exclude", "--mirror", "--length", + "--first-move", "--last-move", "--position-window"} + if len(args) % 2 or any(k not in allowed for k in args[::2]): + raise ValueError("oracle supports only fragment query flags") + if len(set(args[::2])) != len(args[::2]): + raise ValueError("duplicate query option") + q = dict(zip(args[::2], args[1::2])) + first, last, length = (int(q.get(k, d)) for k, d in + [("--first-move", 1), ("--last-move", 40), ("--length", 1)]) + if not 1 <= first <= last <= 65535 or not 1 <= length <= 65535: + raise ValueError("invalid window") + window = q.get("--position-window", "chessbase") + mirror = q.get("--mirror", "") + if window not in ("chessbase", "strict") or mirror not in ("", "h", "v", "hv"): + raise ValueError("invalid mode") + boards = [parse_board(q.get(k, "")) for k in ("--look-for", "--or", "--exclude")] + if not any(boards) or len({s for s, _, _ in boards[0]}) != len(boards[0]): + raise ValueError("empty or conflicting Look for") + orientations = [] + for h, v in ((False, False), (True, False), (False, True), (True, True)): + if (h and "h" not in mirror) or (v and "v" not in mirror): + continue + orientations.append([[(sq ^ (56 if h else 0) ^ (7 if v else 0), + color ^ h, role) for sq, color, role in fragment] + for fragment in boards]) + return first, last, length, window, orientations + + +def evaluate(game, compiled): + """Independent square-by-square replay, with witness plies for both + union-of-orientations and fixed-orientation persistence semantics.""" + if game.errors or not game.board().is_valid(): + raise ValueError("invalid PGN or initial position: " + str(game.errors)) + chess = chess_module() + first, last, length, window, orientations = compiled + end = min(65535, max(last, first + 1)) if window == "chessbase" else last + board = game.board() + union = 0 + runs = [0] * len(orientations) + witness = fixed = None + + def check(ply, number, white, initial): + nonlocal union, witness, fixed + extra = window == "chessbase" and number == end + 1 and white and not initial + eligible = (number <= end and (window != "strict" or number >= first)) or extra + if not eligible: + union = 0 + runs[:] = [0] * len(runs) + return + def holds(man): + sq, color, role = man + piece = board.piece_at(sq) + return piece is not None and piece.color == color and (role == "x" or piece.symbol().lower() == role) + matched = [all(map(holds, look)) and (not either or any(map(holds, either))) + and not any(map(holds, exclude)) for look, either, exclude in orientations] + union = union + 1 if any(matched) else 0 + for i, hit in enumerate(matched): + runs[i] = runs[i] + 1 if hit else 0 + if witness is None and union >= length: + witness = {"first_ply": ply-length+1, "last_ply": ply, "fen": board.fen()} + if fixed is None and max(runs) >= length: + fixed = {"first_ply": ply-length+1, "last_ply": ply, "fen": board.fen()} + check(0, board.fullmove_number, False, True) + for ply, move in enumerate(game.mainline_moves(), 1): + number, white = board.fullmove_number, board.turn == chess.WHITE + if move not in board.legal_moves and move != chess.Move.null(): + raise ValueError(f"illegal mainline move at ply {ply}") + board.push(move) + check(ply, number, white, False) + return {"match": witness is not None, "witness": witness, + "fixed_orientation_match": fixed is not None, "fixed_witness": fixed} + + +def fixture(out): + chess = chess_module() + # Unique Event tags survive an import/export roundtrip and identify each + # controlled game without trusting a result-list row number. + entries = [ + ("empty", None, "", None), + ("bishop-end", None, "e2e4 e7e5 g1f3 b8c6 f1c4", None), + ("bishop-stays", None, "e2e4 e7e5 g1f3 b8c6 f1c4 f8c5 d2d3", None), + ("variation-only", None, "e2e4 e7e5 g1f3", "f1c4"), + ("mirror-switch", "4k3/8/8/8/8/8/8/4K3 w - - 0 1", "e1d1", None), + ("custom-white3", "4k3/8/8/8/8/8/4P3/4K3 w - - 0 3", "e2e4", None), + ("custom-black3", "4k3/8/8/8/8/8/4P3/4K3 b - - 0 3", "e8d8 e2e4", None), + ("custom-black10", "4k3/8/8/8/8/8/4P3/4K3 b - - 0 10", "e8d8 e2e4", None), + ("ep", None, "e2e4 a7a6 e4e5 d7d5 e5d6", None), + ("castle", None, "e2e4 e7e5 g1f3 b8c6 f1c4 g8f6 e1g1 f8c5 d2d3 e8g8", None), + ("joker-pawn", None, "f2f3 e7e5", None), + ] + for role in "qrbn": + entries.append(("promotion-" + role, None, + f"a2a4 h7h5 a4a5 h5h4 a5a6 h4h3 a6b7 h3g2 b7a8{role} g2h1{role}", None)) + out.mkdir(parents=True, exist_ok=False) + games = [] + with (out / "controlled.pgn").open("x") as f: + for name, fen, line, alt in entries: + game = chess.pgn.Game() + game.headers["Event"] = "CBV-audit-" + name + game.headers["White"] = "Audit, White" + game.headers["Black"] = "Audit, Black" + if fen: + game.setup(chess.Board(fen)) + node = game + for uci in line.split(): + move = node.board().parse_uci(uci) + node = node.add_variation(move) + if alt: + node.parent.add_variation(node.parent.board().parse_uci(alt)) + print(game, end="\n\n", file=f) + games.append(game) + expected = {} + for name, args in {**CASES, **CONTROL}.items(): + compiled = compile_query(args) + expected[name] = {"args": args, "matches": [], "fixed_orientation_matches": []} + for game in games: + result = evaluate(game, compiled) + if result["match"]: + expected[name]["matches"].append(game.headers["Event"]) + if result["fixed_orientation_match"]: + expected[name]["fixed_orientation_matches"].append(game.headers["Event"]) + (out / "expected.json").write_text(json.dumps(expected, indent=2) + "\n") + + +def checked_ids(lines, records): + previous = 0 + for line in lines: + value = int(line.strip()) + if not previous < value <= records: + raise ValueError(f"invalid or unordered ID: {value}") + previous = value + yield value + + +def diff(left, right, records, missing, extra): + """All missing/extra IDs, not just bounded samples; O(1) working memory.""" + a, b = iter(checked_ids(left, records)), iter(checked_ids(right, records)) + x, y = next(a, None), next(b, None) + counts = {"actual": 0, "reference": 0, "missing": 0, "extra": 0} + while x is not None or y is not None: + if x is not None and (y is None or x < y): + print(x, file=extra) + counts["actual"] += 1 + counts["extra"] += 1 + x = next(a, None) + elif y is not None and (x is None or y < x): + print(y, file=missing) + counts["reference"] += 1 + counts["missing"] += 1 + y = next(b, None) + else: + counts["actual"] += 1 + counts["reference"] += 1 + x, y = next(a, None), next(b, None) + return counts + + +def compare_files(actual, reference, records, stem): + with actual.open() as a, reference.open() as b, Path(str(stem)+".missing.ids").open("x") as m, Path(str(stem)+".extra.ids").open("x") as e: + return diff(a, b, records, m, e) + + +def invoke(cli, *args): + return subprocess.run([str(cli.resolve()), *map(str, args)], capture_output=True, encoding="utf-8") + + +def identity(cli, db): + p = invoke(cli, "info", db, "--json") + p.check_returncode() + info = json.loads(p.stdout) + # info counts the native slot 0, search does not. + records = info["records"] - (db.suffix.lower() == ".2cbh") + return records, info + + +def digest(path): + with path.open("rb") as f: + return hashlib.file_digest(f, "sha256").hexdigest() + + +def collect(a): + a.out.mkdir(parents=True, exist_ok=False) + records, info = identity(a.candidate, a.db) + if a.db.suffix.lower() not in (".cbh", ".2cbh"): + raise ValueError("use explicit .cbh or .2cbh header") + # Same-stem reader files only; reject ambiguous case-insensitive names. + import importlib.util + spec = importlib.util.spec_from_file_location("private_gate", Path(__file__).with_name("query-private-acceptance.py")) + gate = importlib.util.module_from_spec(spec) + spec.loader.exec_module(gate) + required, optional = gate.MEMBERS[a.db.suffix.lower()] + members = [p for p in a.db.parent.iterdir() if p.stem.lower() == a.db.stem.lower() + and p.suffix.lower() in required | optional] + if len({p.suffix.lower() for p in members}) != len(members) or not required.issubset({p.suffix.lower() for p in members}): + raise ValueError("missing or ambiguous reader members") + def snapshot(): + return {str(p.resolve()): (p.stat().st_size, p.stat().st_mtime_ns) for p in members} + before = snapshot() + fingerprints = {str(p.resolve()): digest(p) for p in sorted(members)} + if snapshot() != before: + raise ValueError("source modified during fingerprinting") + if a.contributor and identity(a.contributor, a.db)[0] != records: + raise ValueError("different record ranges") + report = {"records": records, "info": info, "candidate_sha256": digest(a.candidate), + "contributor_sha256": digest(a.contributor) if a.contributor else None, + "independent_chessbase_ids": str(a.chessbase_ids) if a.chessbase_ids else None, + "source_sha256": fingerprints, "source_stable": False, + "id_mapping": a.id_mapping, "completed": False, "cases": {}} + try: + for name in a.case or ["pe2-last1", *(n for n in CASES if n != "pe2-last1")]: + args = CASES[name] + row = report["cases"][name] = {"args": args} + for side, cli in (("candidate", a.candidate), ("contributor", a.contributor)): + if cli is None: + continue + path = a.out / f"{name}.{side}.ids" + with path.open("x") as f: + p = subprocess.run([str(cli.resolve()), "search", str(a.db), *args, "--threads", str(a.threads), + "--limit", "0", "--ids-only"], stdout=f, stderr=subprocess.PIPE, encoding="utf-8") + p.check_returncode() + stats = json.loads(p.stderr) + with path.open() as f: + count = sum(1 for _ in checked_ids(f, records)) + if not stats["complete"] or stats["records"] != records or stats["matches"] != count: + raise ValueError(f"incomplete or inconsistent {name}/{side}") + row[side] = {**stats, "ids_sha256": digest(path)} + candidate = a.out / f"{name}.candidate.ids" + if a.contributor: + row["versus_contributor"] = compare_files(candidate, a.out / f"{name}.contributor.ids", records, + a.out / f"{name}.vs-contributor") + if a.chessbase_ids: + reference = a.chessbase_ids / f"{name}.ids" + reference_hash = digest(reference) + row["versus_chessbase"] = compare_files(candidate, reference, records, a.out / f"{name}.vs-chessbase") + if a.contributor: + row["contributor_versus_chessbase"] = compare_files(a.out / f"{name}.contributor.ids", reference, records, + a.out / f"{name}.contributor-vs-chessbase") + if digest(reference) != reference_hash: + raise ValueError(f"reference IDs changed during comparison: {name}") + row["chessbase_ids_sha256"] = reference_hash + print(name, json.dumps(row), flush=True) + report["source_stable"] = snapshot() == before + if not report["source_stable"]: + raise ValueError("source modified during audit") + report["completed"] = True + finally: + (a.out / "collection.json").write_text(json.dumps(report, indent=2) + "\n") + + +def read_one_pgn(text): + import io + chess = chess_module() + stream = io.StringIO(text) + game = chess.pgn.read_game(stream) + if game is None or game.errors or chess.pgn.read_game(stream) is not None: + raise ValueError("expected exactly one valid PGN game") + return game + + +def compare_pgns(candidate, reference): + """Identify a first mainline board divergence, not just a search witness. + Matching tags are a plausibility check, never proof of physical-ID mapping. + Normalize only case, Unicode composition and spacing; do not guess names. + Legal en passant normalization avoids exporter-specific FEN conventions. + """ + import unicodedata + from itertools import zip_longest + def normalize(value): + return " ".join(unicodedata.normalize("NFKC", value).casefold().split()) + unknown = {"", "?", "????.??.??", "*", "-"} + tags = {} + for tag in ("White", "Black", "Event", "Site", "Date", "Round", "Result"): + a, b = candidate.headers.get(tag, ""), reference.headers.get(tag, "") + x, y = normalize(a), normalize(b) + # Partial dates and unknown fields are not evidence against identity. + if x in unknown or y in unknown or (tag == "Date" and ("?" in x or "?" in y)): + status = "unknown" + else: + status = "equal" if x == y else "different" + tags[tag] = {"candidate": a, "reference": b, "status": status} + conflicts = [k for k, v in tags.items() if v["status"] == "different"] + equal = [k for k, v in tags.items() if v["status"] == "equal"] + identity = "tag-conflict" if conflicts else ("plausible" if {"White", "Black"}.issubset(equal) and + any(k in equal for k in ("Event", "Date", "Round")) else "insufficient-tags") + def positions(game): + board = game.board() + yield {"ply": 0, "move": None, "fen": board.fen(en_passant="legal"), "chess960": board.chess960} + for ply, move in enumerate(game.mainline_moves(), 1): + uci = board.uci(move) + board.push(move) + yield {"ply": ply, "move": uci, "fen": board.fen(en_passant="legal"), "chess960": board.chess960} + first = None + lengths = [0, 0] + for left, right in zip_longest(positions(candidate), positions(reference)): + for i, value in enumerate((left, right)): + if value is not None: + lengths[i] = value["ply"] + if first is None and left != right: + # FEN includes move numbers, side to move, castling, legal EP + # and halfmove clock; distinguish counter-only differences. + if left is None or right is None: + kind = "mainline-length" + elif left["chess960"] != right["chess960"]: + kind = "variant" + elif left["fen"].split()[:4] != right["fen"].split()[:4]: + kind = "board-state" + elif left["fen"] != right["fen"]: + kind = "move-counters" + else: + kind = "move-encoding" + first = {"kind": kind, "candidate": left, "reference": right} + return {"identity": identity, "tags": tags, "conflicting_tags": conflicts, + "candidate_plies": lengths[0], "reference_plies": lengths[1], + "mainline_equal": first is None, "first_divergence": first} + + +def inspect(a): + records, _ = identity(a.candidate, a.db) + query = compile_query(CASES[a.case]) + a.out.mkdir(parents=True, exist_ok=False) + # Separate private evidence per record. Failures are retained, never treated as nonmatches. + with a.ids.open() as ids, (a.out / "evidence.jsonl").open("x") as out: + for record in checked_ids(ids, records): + row = {"id": record} + meta = invoke(a.candidate, "meta", a.db, record, "--json") + row["metadata"] = json.loads(meta.stdout) if meta.returncode == 0 else {"error": meta.stderr} + for side, cli in (("candidate", a.candidate), ("contributor", a.contributor)): + if cli: + p = invoke(cli, "search", a.db, *CASES[a.case], "--from", record, "--to", record, + "--threads", 1, "--ids-only", "--limit", 0, "--json") + row[side] = json.loads(p.stdout) if p.returncode == 0 else {"error": p.stderr} + own_game = independent_game = None + p = invoke(a.candidate, "pgn", a.db, "--from", record, "--to", record, "--threads", 1) + if p.returncode == 0: + (a.out / f"{record}.cbvault.pgn").write_text(p.stdout, encoding="utf-8") + try: + game = read_one_pgn(p.stdout) + row["cbvault_export_replay"] = evaluate(game, query) + own_game = game + except ValueError as e: + row["cbvault_export_replay"] = {"error": str(e)} + else: + row["cbvault_export_replay"] = {"error": p.stderr} + if a.chessbase_pgn_dir: + path = a.chessbase_pgn_dir / f"{record}.pgn" + try: + game = read_one_pgn(path.read_text(encoding="utf-8-sig")) + row["chessbase_export_replay"] = evaluate(game, query) + independent_game = game + except (OSError, ValueError) as e: + row["chessbase_export_replay"] = {"error": str(e)} + if own_game is not None and independent_game is not None: + row["export_comparison"] = compare_pgns(own_game, independent_game) + row["classification"] = classify(row, a.direction) + print(json.dumps(row), file=out, flush=True) + + +def classify(row, direction): + """Diagnostic leads, not automatic adjudication of either engine.""" + meta = row["metadata"] + stats = row.get("candidate", {}) + if "error" in meta or "error" in stats or not stats.get("complete"): + return "unreadable-or-incomplete" + if meta.get("deleted"): + return "deleted-record-policy" + if meta.get("kind") != "Game": + return "record-kind-policy:" + str(meta.get("kind")) + independent = row.get("chessbase_export_replay", {}) + own = row.get("cbvault_export_replay", {}) + if stats.get("failed"): + return "candidate-replay-failure" + if "match" not in independent: + return "independent-export-required" + candidate_match = bool(stats.get("matches")) + reference_match = direction == "missing" + if candidate_match == reference_match: + return "membership-input-inconsistent" + if "match" not in own: + return "candidate-export-unreadable" + comparison = row.get("export_comparison", {}) + if comparison.get("identity") != "plausible": + return "source-identity-review-required" + if not comparison.get("mainline_equal"): + return "decoded-position-or-source-mapping-discrepancy" + if own["match"] != independent["match"]: + return "oracle-inconsistent-for-equal-mainlines" + if independent["match"] == candidate_match: + return "chessbase-search-semantics-or-index-discrepancy" + return "candidate-fragment-matcher-or-eligibility-discrepancy" + + +def oracle(a): + chess = chess_module() + cases = {**CASES, **CONTROL} if a.controlled else CASES + compiled = {name: compile_query(args) for name, args in cases.items()} + matches = {name: [] for name in cases} + count = 0 + # Public verified contiguous corpus only; private exports must use explicit + # record mappings, or inspect per-ID exports instead. + with a.pgn.open(encoding="utf-8-sig") as f: + while (game := chess.pgn.read_game(f)) is not None: + count += 1 + for name, q in compiled.items(): + if evaluate(game, q)["match"]: + matches[name].append(a.first_id + count - 1) + if count != a.expected_games: + raise ValueError(f"PGN count {count} != {a.expected_games}") + a.out.mkdir(parents=True, exist_ok=False) + for name, values in matches.items(): + with (a.out / (name + ".ids")).open("x") as f: + for v in values: + print(v, file=f) + if a.cli: + records, _ = identity(a.cli, a.db) + last = a.first_id + count - 1 + if last > records: + raise ValueError("public PGN range exceeds source records") + summary = {} + for name, args in cases.items(): + p = invoke(a.cli, "search", a.db, *args, "--from", a.first_id, "--to", last, + "--threads", 1, "--ids-only", "--limit", 0, "--json") + p.check_returncode() + stats = json.loads(p.stdout) + ids = stats.pop("ids") + if not stats["complete"] or stats["failed"] or stats["records"] != count or ids != matches[name]: + raise ValueError(f"independent replay mismatch for {name}: {stats}") + summary[name] = stats + (a.out / "public-verification.json").write_text(json.dumps(summary, indent=2) + "\n") + print(f"Independent PGN matcher: {len(cases)} cases over {count} games agree", flush=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + sub = p.add_subparsers(dest="command", required=True) + f = sub.add_parser("fixture") + f.add_argument("--out", type=Path, required=True) + o = sub.add_parser("oracle", help="replay a verified contiguous public PGN export") + o.add_argument("--pgn", type=Path, required=True) + o.add_argument("--out", type=Path, required=True) + o.add_argument("--first-id", type=int, required=True) + o.add_argument("--expected-games", type=int, required=True) + o.add_argument("--controlled", action="store_true") + o.add_argument("--cli", type=Path) + o.add_argument("--db", type=Path) + for name in ("collect", "inspect"): + c = sub.add_parser(name) + c.add_argument("--db", type=Path, required=True) + c.add_argument("--candidate", type=Path, required=True) + c.add_argument("--contributor", type=Path) + c.add_argument("--out", type=Path, required=True) + c.add_argument("--case", choices=CASES, required=name=="inspect", action="append" if name=="collect" else "store") + if name == "collect": + c.add_argument("--threads", type=int, default=4) + c.add_argument("--chessbase-ids", type=Path) + c.add_argument("--id-mapping", help="Describe independently verified source-ID mapping") + else: + c.add_argument("--ids", type=Path, required=True) + c.add_argument("--direction", choices=["missing", "extra"], required=True) + c.add_argument("--chessbase-pgn-dir", type=Path) + c = sub.add_parser("compare", help="compare any independently verified ordered ID lists") + c.add_argument("--actual", type=Path, required=True) + c.add_argument("--reference", type=Path, required=True) + c.add_argument("--records", type=int, required=True) + c.add_argument("--out", type=Path, required=True) + a = p.parse_args() + if a.command == "compare": + if a.records < 1: + p.error("positive searchable record count required") + a.out.mkdir(parents=True, exist_ok=False) + stats = compare_files(a.actual, a.reference, a.records, a.out / "comparison") + (a.out / "comparison.json").write_text(json.dumps(stats, indent=2) + "\n") + print(json.dumps(stats)) + elif a.command == "fixture": + fixture(a.out) + elif a.command == "collect": + if a.chessbase_ids and not (a.id_mapping or "").strip(): + p.error("independent ChessBase ID comparison requires --id-mapping") + if a.threads < 1: + p.error("positive worker count required") + collect(a) + elif a.command == "inspect": + inspect(a) + else: + if bool(a.cli) != bool(a.db): + p.error("--cli and --db must be supplied together") + if a.first_id < 1 or a.expected_games < 1: + p.error("positive first-id and expected-games required") + oracle(a) + + +if __name__ == "__main__": + main() diff --git a/scripts/query-private-acceptance.py b/scripts/query-private-acceptance.py index 0a9391f4..1580279c 100755 --- a/scripts/query-private-acceptance.py +++ b/scripts/query-private-acceptance.py @@ -4,7 +4,6 @@ """ import argparse import hashlib -import itertools import json import os from pathlib import Path @@ -21,7 +20,9 @@ NATIVE = {"time_classical", "time_rapid", "time_blitz", "time_correspondence"} ALLOWED_VALUES = {"--white", "--black", "--names", "--texts", "--tournament", "--annotator", "--any-text", "--year", "--eco", "--moves", "--elo", "--elo-mode", - "--elo-diff-min", "--elo-diff-max", "--result", "--time-control"} + "--elo-diff-min", "--elo-diff-max", "--result", "--time-control", + "--look-for", "--or", "--exclude", "--mirror", "--first-move", "--length", + "--last-move", "--position-window"} ALLOWED_FLAGS = {"--ignore-colours", "--ignore-colors", "--wins-only", "--not", "--text"} # Match the actual reader's mandatory/optional members, not merely suffixes @@ -94,6 +95,45 @@ def validate_args(flags): raise ValueError("manifest contains unsupported or execution-related arguments") +def compare_membership(actual, expected, records, sample_limit=32): + """Merge two ordered ID streams in bounded memory; keep only small samples.""" + valid = True + + def ordered(lines): + nonlocal valid + previous = 0 + for line in lines: + value = int(line.strip()) + if not previous < value <= records: + valid = False + previous = value + yield value + + left, right = iter(ordered(actual)), iter(ordered(expected)) + a, e = next(left, None), next(right, None) + count = reference_count = missing = extra = 0 + missing_sample, extra_sample = [], [] + while a is not None or e is not None: + if a is not None and (e is None or a < e): + count += 1 + extra += 1 + if len(extra_sample) < sample_limit: + extra_sample.append(a) + a = next(left, None) + elif e is not None and (a is None or e < a): + reference_count += 1 + missing += 1 + if len(missing_sample) < sample_limit: + missing_sample.append(e) + e = next(right, None) + else: + count += 1 + reference_count += 1 + a, e = next(left, None), next(right, None) + return dict(count=count, reference_count=reference_count, missing=missing, extra=extra, + missing_sample=missing_sample, extra_sample=extra_sample, ordered=valid) + + def run_case(cli, db, case, manifest_dir, threads, mode, expected_records): flags = case["args"] validate_args(flags) @@ -108,19 +148,8 @@ def run_case(cli, db, case, manifest_dir, threads, mode, expected_records): env.pop("CBVAULT_MMAP", None) with tempfile.TemporaryFile(mode="w+t", encoding="utf-8") as err, reference.open(encoding="utf-8") as gold: proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=err, text=True, env=env) - count = 0 - previous = 0 - mismatch = False try: - for actual, expected in itertools.zip_longest(proc.stdout, gold): - if actual is None or expected is None: - mismatch = True - continue - aid, eid = int(actual.strip()), int(expected.strip()) - if aid != eid or eid <= previous or eid > expected_records: - mismatch = True - previous = eid - count += 1 + membership = compare_membership(proc.stdout, gold, expected_records) except BaseException: proc.kill() proc.wait() @@ -130,11 +159,12 @@ def run_case(cli, db, case, manifest_dir, threads, mode, expected_records): code = proc.wait() err.seek(0) stats = json.loads(err.read()) - passed = (code == 0 and not mismatch and stats["complete"] is True - and count == case["expected_count"] == stats["matches"] + passed = (code == 0 and membership["ordered"] and not membership["missing"] + and not membership["extra"] and stats["complete"] is True + and membership["count"] == membership["reference_count"] == case["expected_count"] == stats["matches"] and stats["records"] == expected_records and stats["failed"] == case.get("expected_failed", 0)) - return dict(case=case["name"], mode=mode, threads=threads, count=count, stats=stats, passed=passed) + return dict(case=case["name"], mode=mode, threads=threads, **membership, stats=stats, passed=passed) def main(): @@ -142,6 +172,8 @@ def main(): p.add_argument("--manifest", required=True, type=Path) p.add_argument("--cli", required=True, type=Path) p.add_argument("--report", required=True, type=Path) + p.add_argument("--position-only", action="store_true", + help="Diagnostic subset: run only position cases from independently mapped datasets") args = p.parse_args() if not args.manifest.is_absolute() or not args.report.is_absolute(): p.error("use absolute private paths") @@ -150,17 +182,23 @@ def main(): p.error("manifest must declare independent ChessBase reference provenance") datasets = m["datasets"] by_role = {d["role"]: d for d in datasets} - if len(by_role) != len(datasets) or set(by_role) != {"classic", "native", "special"}: + roles = {"classic", "native", "special"} + if len(by_role) != len(datasets) or not by_role or not set(by_role).issubset(roles): + p.error("invalid or duplicate source roles") + if not args.position_only and set(by_role) != roles: p.error("manifest requires classic, native and special source sets") # Existing private acceptance and query acceptance must use identical main databases. for role, variable in [("classic", "CBVAULT_TEST_DB"), ("native", "CBVAULT_TEST_DB_2CBH")]: + if role not in by_role: + continue path = Path(os.environ[variable]).resolve() suffix = ".cbh" if role == "classic" else ".2cbh" header = path if path.suffix.lower() == suffix else Path(str(path) + suffix) if Path(by_role[role]["db"]).resolve() != header.resolve(): p.error("query manifest source does not match existing private acceptance") results = [] - report = {"schema": 1, "scope": "private membership gate (not performance gate)", "passed": False, "results": results} + report = {"schema": 1, "scope": "private position diagnostic" if args.position_only else "private membership gate (not performance gate)", + "passed": False, "results": results} try: for dataset in datasets: db = Path(dataset["db"]) @@ -171,7 +209,12 @@ def main(): raise ValueError("duplicate case names") coverage = {k for c in cases for k in c["covers"]} required = REQUIRED | (NATIVE if dataset["role"] == "native" else set()) if dataset["role"] != "special" else {"mate","stalemate","check","chess960","custom_setup","corrupt"} - if not required.issubset(coverage): + if args.position_only: + cases = [case for case in cases if set(case["args"]) & {"--look-for", "--or", "--exclude"}] + if not cases: + raise ValueError(f"no position cases for {dataset['role']}") + dataset["cases"] = cases + elif not required.issubset(coverage): raise ValueError(f"missing cases for {dataset['role']}: {sorted(required-coverage)}") if not dataset.get("reference_revision") or not dataset.get("id_mapping"): raise ValueError("missing independent oracle revision/ID mapping") diff --git a/scripts/requirements-position-audit.txt b/scripts/requirements-position-audit.txt new file mode 100644 index 00000000..c87940bd --- /dev/null +++ b/scripts/requirements-position-audit.txt @@ -0,0 +1 @@ +chess==1.11.2 diff --git a/scripts/test-position-audit.py b/scripts/test-position-audit.py new file mode 100644 index 00000000..fb4a743a --- /dev/null +++ b/scripts/test-position-audit.py @@ -0,0 +1,116 @@ +import importlib.util +import io +import json +from pathlib import Path +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location("audit", Path(__file__).with_name("position-audit.py")) +audit = importlib.util.module_from_spec(spec) +spec.loader.exec_module(audit) + +class AuditTests(unittest.TestCase): + def test_all_differences(self): + missing, extra = io.StringIO(), io.StringIO() + self.assertEqual(audit.diff(["1", "3", "5"], ["2", "3", "4"], 5, missing, extra), + dict(actual=3, reference=3, missing=2, extra=2)) + self.assertEqual(missing.getvalue(), "2\n4\n") + self.assertEqual(extra.getvalue(), "1\n5\n") + + def test_bad_id_streams(self): + for lines in (["0"], ["1", "1"], ["2", "1"], ["6"]): + with self.assertRaises(ValueError): + audit.diff(lines, [], 5, io.StringIO(), io.StringIO()) + + def test_controlled_fixture(self): + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "fixture" + audit.fixture(out) + expected = json.loads((out / "expected.json").read_text()) + def matches(name, tag, key="matches"): + return "CBV-audit-" + tag in expected[name][key] + self.assertTrue(matches("mirror-switch", "mirror-switch")) + self.assertFalse(matches("mirror-switch", "mirror-switch", "fixed_orientation_matches")) + self.assertTrue(matches("extra-white", "custom-white3")) + self.assertFalse(matches("initial-extra", "custom-white3")) + self.assertFalse(matches("extra-white", "custom-black3")) + self.assertTrue(matches("strict", "custom-white3")) + self.assertFalse(matches("variation", "variation-only")) + self.assertFalse(matches("length2", "bishop-end")) + self.assertTrue(matches("length3", "bishop-stays")) + self.assertTrue(matches("ep", "ep")) + self.assertTrue(matches("promotion", "promotion-n")) + self.assertFalse(matches("promotion", "promotion-q")) + self.assertTrue(matches("pe2-last1", "empty")) + self.assertTrue(matches("joker", "joker-pawn")) + chess = audit.chess_module() + with (out / "controlled.pgn").open() as f: + games = [] + while (game := chess.pgn.read_game(f)) is not None: + games.append(game) + self.assertEqual(len(games), 15) + for name, case in expected.items(): + self.assertEqual([g.headers["Event"] for g in games if audit.evaluate(g, audit.compile_query(case["args"]))["match"]], case["matches"], name) + + def test_classification(self): + row = {"metadata": {"kind":"Game","deleted":False}, + "candidate":{"complete":True,"matches":0,"failed":0}, + "cbvault_export_replay":{"match":True}} + self.assertEqual(audit.classify(row, "missing"), "independent-export-required") + row["chessbase_export_replay"] = {"match":True} + self.assertEqual(audit.classify(row, "missing"), "source-identity-review-required") + row["export_comparison"] = {"identity": "plausible", "mainline_equal": True} + self.assertEqual(audit.classify(row, "missing"), "candidate-fragment-matcher-or-eligibility-discrepancy") + row["cbvault_export_replay"] = {"match":False} + self.assertEqual(audit.classify(row, "missing"), "oracle-inconsistent-for-equal-mainlines") + row["export_comparison"]["mainline_equal"] = False + self.assertEqual(audit.classify(row, "missing"), "decoded-position-or-source-mapping-discrepancy") + row["chessbase_export_replay"] = {"match":False} + # Even when membership agrees with the candidate, differing decoded + # mainlines must not be classified as a ChessBase search discrepancy. + self.assertEqual(audit.classify(row, "missing"), "decoded-position-or-source-mapping-discrepancy") + row["export_comparison"]["mainline_equal"] = True + self.assertEqual(audit.classify(row, "missing"), "chessbase-search-semantics-or-index-discrepancy") + row["candidate"]["failed"] = 1 + self.assertEqual(audit.classify(row, "missing"), "candidate-replay-failure") + row["metadata"]["kind"] = "Analysis" + self.assertEqual(audit.classify(row, "missing"), "record-kind-policy:Analysis") + + def test_export_comparison(self): + header = '[Event "Test"]\n[White "Alpha"]\n[Black "Beta"]\n[Date "2026.01.01"]\n\n' + def game(line, tags=header): + return audit.read_one_pgn(tags + line + " *") + a = game("1. e4 e5 2. Nf3") + same = game("1. e4 {comment} e5 (1... c5) 2. Nf3") + r = audit.compare_pgns(a, same) + self.assertEqual(r["identity"], "plausible") + self.assertTrue(r["mainline_equal"]) + self.assertEqual(r["candidate_plies"], 3) + r = audit.compare_pgns(a, game("1. e4 c5 2. Nf3")) + self.assertEqual(r["first_divergence"]["kind"], "board-state") + self.assertEqual(r["first_divergence"]["reference"]["ply"], 2) + r = audit.compare_pgns(a, game("1. e4 e5")) + self.assertEqual(r["first_divergence"]["kind"], "mainline-length") + self.assertIsNone(r["first_divergence"]["reference"]) + r = audit.compare_pgns(a, game("1. e4 e5 2. Nf3", header.replace("Beta", "Other"))) + self.assertEqual(r["identity"], "tag-conflict") + self.assertTrue(r["mainline_equal"]) + self.assertEqual(r["conflicting_tags"], ["Black"]) + r = audit.compare_pgns(game("1. e4", ""), game("1. e4", "")) + self.assertEqual(r["identity"], "insufficient-tags") + fen1 = '[SetUp "1"]\n[FEN "4k3/8/8/8/8/8/4P3/4K3 w - - 0 1"]\n' + fen2 = fen1.replace("0 1", "0 10") + x = audit.read_one_pgn(fen1 + header + "1. e4 *") + y = audit.read_one_pgn(fen2 + header + "10. e4 *") + r = audit.compare_pgns(x, y) + self.assertEqual(r["first_divergence"]["kind"], "move-counters") + self.assertEqual(r["first_divergence"]["reference"]["ply"], 0) + + def test_unknown_options_rejected(self): + for args in (["--elo", "2200-"], ["--look-for", "Pe2", "--last-move", "0"], + ["--look-for", "Pe2 Pe2"], ["--look-for", "Pe2", "--mirror", "x"]): + with self.assertRaises(ValueError): + audit.compile_query(args) + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test-position-public.py b/scripts/test-position-public.py new file mode 100644 index 00000000..7886aef3 --- /dev/null +++ b/scripts/test-position-public.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Exercise the local audit tools on verified, public native fixtures only.""" +import argparse +import importlib.util +import json +import os +from pathlib import Path +import subprocess + +import chess +import chess.pgn +import chess.polyglot + +spec = importlib.util.spec_from_file_location("audit", Path(__file__).with_name("position-audit.py")) +audit = importlib.util.module_from_spec(spec) +spec.loader.exec_module(audit) + + +def run(*args, env=None): + result = subprocess.run([str(a) for a in args], capture_output=True, text=True, env=env) + if result.returncode: + raise RuntimeError(f"{args}: {result.stderr[-4000:]}") + return result + + +def require(ok, message): + if not ok: + raise ValueError(message) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--cli", type=Path, required=True) + p.add_argument("--exact", type=Path, required=True) + p.add_argument("--fixtures", type=Path, required=True) + p.add_argument("--out", type=Path, required=True) + p.add_argument("--contributor", type=Path) + a = p.parse_args() + a.out.mkdir(parents=True, exist_ok=False) + manifest = json.loads((Path(__file__).parent / "bench-corpus/native-manifest.json").read_text())["tiers"]["smoke"] + dbs = [a.fixtures / (manifest["stem"] + "." + ext) for ext in ("cbh", "2cbh")] + pgn = a.out / "verified-public.pgn" + run(a.cli, "pgn", dbs[0], pgn, "--threads", 2) + require(audit.digest(pgn) == manifest["export_sha256"]["cbh"] == manifest["export_sha256"]["2cbh"], + "public PGN does not match pinned cross-generation export") + fens = {} + for name, moves in (("start", ""), ("e4", "e2e4"), ("sicilian", "e2e4 c7c5 g1f3")): + board = chess.Board() + for move in moves.split(): + board.push_uci(move) + fens[name] = board.fen() + keys = {name: chess.polyglot.zobrist_hash(chess.Board(fen)) for name, fen in fens.items()} + expected = {name: [] for name in keys} + pe2 = [] + sample_id = None + count = 0 + fragment = audit.compile_query(audit.CASES["pe2-last1"]) + with pgn.open(encoding="utf-8") as source: + while (game := chess.pgn.read_game(source)) is not None: + count += 1 + board = game.board() + require(not game.errors and board.is_valid(), f"invalid public PGN record {count}") + seen = set() + # An exact-key search includes the initial board and all mainline + # plies, not just the fragment search window. + for move in [None, *game.mainline_moves()]: + if move is not None: + require(move in board.legal_moves or move == chess.Move.null(), f"illegal move {count}") + board.push(move) + key = chess.polyglot.zobrist_hash(board) + seen.add(key) + for name, key in keys.items(): + if key in seen: + expected[name].append(count) + initial = game.board().piece_at(chess.E2) + if initial == chess.Piece(chess.PAWN, chess.WHITE) or audit.evaluate(game, fragment)["match"]: + pe2.append(count) + # A divergent first move needs a game with an existing move. + # The corpus also contains zero-move games. + if sample_id is None and game.next() is not None: + sample_id = count + require(count == manifest["games"], "public game count differs") + pgn.unlink() + require(all(expected.values()) and pe2 and sample_id is not None, + "public test needs nonempty memberships and a nonempty inspection game") + summary = {"source_games": count, "formats": {}} + for db in dbs: + ext = db.suffix[1:] + row = summary["formats"][ext] = {} + for name, fen in fens.items(): + for threads, positioned in ((1, False), (4, False), (1, True), (4, True)): + env = os.environ.copy() + env.pop("CBVAULT_NO_MMAP", None) + env.pop("CBVAULT_MMAP", None) + if positioned: + env["CBVAULT_NO_MMAP"] = "1" + path = a.out / f"{ext}-{name}-{threads}-{positioned}.ids" + result = run(a.exact, db, fen, threads, path, env=env) + stats = json.loads(result.stderr) + with path.open() as f: + ids = list(audit.checked_ids(f, count)) + require(stats["complete"] and stats["failures"] == 0 and stats["records"] == count + and stats["unique_ids"] == len(ids) and int(stats["key"], 16) == keys[name] + and ids == expected[name], f"exact-key parity failed: {ext}/{name}/{threads}/{positioned}: {stats}") + row[f"{name}-{threads}-{positioned}"] = stats + # Run the real collector against the public source. Its output format, + # source fingerprinting, contributor comparison, and inspection must + # work before entrusting the scripts with licensed data. + out = a.out / f"{ext}-collect" + args = [a.cli, "search", db, *audit.CASES["pe2-last1"], "--ids-only", "--limit", "0", "--json"] + result = json.loads(run(*args).stdout) + require(result["ids"] == pe2 and result["failed"] == 0 and result["complete"], + f"full corpus independent initial-position membership differs: {ext}") + import sys + script = Path(__file__).with_name("position-audit.py") + contributor = ["--contributor", a.contributor] if a.contributor else [] + run(sys.executable, script, "collect", "--db", db, "--candidate", a.cli, + *contributor, "--case", "pe2-last1", "--out", out) + collected = json.loads((out / "collection.json").read_text()) + case = collected["cases"]["pe2-last1"] + require(collected["completed"] and collected["source_stable"] and case["candidate"]["failed"] == 0, + f"collector incomplete: {ext}") + with (out / "pe2-last1.candidate.ids").open() as f: + require(list(audit.checked_ids(f, count)) == pe2, f"collector membership differs: {ext}") + if contributor: + require(case["versus_contributor"]["missing"] == case["versus_contributor"]["extra"] == 0, + f"contributor membership differs: {ext}") + one = a.out / f"{ext}-sample.ids" + one.write_text(str(sample_id) + "\n") + inspected = a.out / f"{ext}-inspect" + run(sys.executable, script, "inspect", "--db", db, "--candidate", a.cli, + *contributor, "--case", "pe2-last1", "--ids", one, "--direction", "extra", "--out", inspected) + evidence = json.loads((inspected / "evidence.jsonl").read_text()) + require(evidence["id"] == sample_id and evidence["metadata"]["kind"] == "Game" + and evidence["candidate"]["matches"] == 1 and evidence["cbvault_export_replay"]["match"] + and evidence["classification"] == "independent-export-required", + f"inspection failed or overclaimed independence: {ext}") + # Exercise the external-ID comparison with deliberately injected + # differences. These are synthetic references, NOT ChessBase output. + case_name = "bh7-horizontal" + rare = json.loads(run(a.cli, "search", db, *audit.CASES[case_name], + "--ids-only", "--limit", 0, "--json").stdout) + ids = rare["ids"] + require(rare["complete"] and rare["failed"] == 0 and 0 < len(ids) < count, + "need a nontrivial public query for negative controls") + removed = ids[0] + membership = set(ids) + added = next(i for i in range(1, count + 1) if i not in membership) + reference = a.out / f"{ext}-synthetic-reference" + reference.mkdir() + (reference / f"{case_name}.ids").write_text( + "".join(f"{i}\n" for i in sorted((membership - {removed}) | {added})), encoding="utf-8") + injected = a.out / f"{ext}-injected" + run(sys.executable, script, "collect", "--db", db, "--candidate", a.cli, + *contributor, "--case", case_name, "--chessbase-ids", reference, + "--id-mapping", "SYNTHETIC CI negative control; original public physical IDs with one injected difference each way", + "--out", injected) + injected_report = json.loads((injected / "collection.json").read_text()) + versus = injected_report["cases"][case_name]["versus_chessbase"] + require(injected_report["completed"] and versus["missing"] == versus["extra"] == 1 + and (injected / f"{case_name}.vs-chessbase.missing.ids").read_text() == f"{added}\n" + and (injected / f"{case_name}.vs-chessbase.extra.ids").read_text() == f"{removed}\n", + f"collector failed to expose equal-count membership differences: {ext}") + + # Inspect a copied export as a test double, then change its mainline + # while preserving all tags. Both paths must retain explicit evidence. + fake_exports = a.out / f"{ext}-synthetic-exports" + fake_exports.mkdir() + raw = (inspected / f"{sample_id}.cbvault.pgn").read_text(encoding="utf-8") + path = fake_exports / f"{sample_id}.pgn" + path.write_text(raw, encoding="utf-8") + def compare_export(suffix): + dest = a.out / f"{ext}-inspect-{suffix}" + run(sys.executable, script, "inspect", "--db", db, "--candidate", a.cli, + "--case", "pe2-last1", "--ids", one, "--direction", "extra", + "--chessbase-pgn-dir", fake_exports, "--out", dest) + return json.loads((dest / "evidence.jsonl").read_text()) + same = compare_export("synthetic-equal") + require(same["export_comparison"]["mainline_equal"] + and same["export_comparison"]["first_divergence"] is None + and same["classification"] in ("chessbase-search-semantics-or-index-discrepancy", + "source-identity-review-required"), + f"equal-export control failed: {ext}") + game = audit.read_one_pgn(raw) + altered = chess.pgn.Game() + altered.headers.update(game.headers) + altered.setup(game.board()) + first = next(game.mainline_moves(), None) + replacement = next(move for move in game.board().legal_moves if move != first) + altered.add_variation(replacement) + path.write_text(str(altered) + "\n", encoding="utf-8") + different = compare_export("synthetic-different") + comparison = different["export_comparison"] + require(not comparison["mainline_equal"] and comparison["first_divergence"]["kind"] == "board-state" + and comparison["first_divergence"]["reference"]["ply"] == 1 + and different["classification"] in ("decoded-position-or-source-mapping-discrepancy", + "source-identity-review-required"), + f"divergent-export control failed: {ext}") + row["collector_and_inspector"] = "passed" + row["synthetic_external_id_and_export_negative_controls"] = "passed" + (a.out / "summary.json").write_text(json.dumps(summary, indent=2) + "\n") + print(f"Independent exact Polyglot oracle: {count} games, 3 keys, 2 generations, 4 modes each; collector/inspector passed") + + +if __name__ == "__main__": + main() diff --git a/scripts/test-query-private-acceptance.py b/scripts/test-query-private-acceptance.py index cdffa71d..e7bb81f8 100644 --- a/scripts/test-query-private-acceptance.py +++ b/scripts/test-query-private-acceptance.py @@ -86,6 +86,21 @@ def test_argument_injection(self): with self.subTest(args=args), self.assertRaises(ValueError): gate.validate_args(args) gate.validate_args(["--white", "Morphy", "--elo", "2700-"]) + gate.validate_args(["--look-for", "Bh7", "--or", "Nf5", "--exclude", "pg6", "--mirror", "hv", + "--first-move", "1", "--last-move", "40", "--length", "2", + "--position-window", "chessbase"]) + with self.assertRaises(ValueError): + gate.validate_args(["--look-for", "--threads", "4"]) + + def test_streaming_membership_counts(self): + result = gate.compare_membership(["1", "3", "7", "9"], ["1", "2", "3", "8", "9"], 10, 1) + self.assertEqual((result["count"], result["reference_count"]), (4, 5)) + self.assertEqual((result["missing"], result["extra"]), (2, 1)) + self.assertEqual((result["missing_sample"], result["extra_sample"]), ([2], [7])) + self.assertTrue(result["ordered"]) + self.assertFalse(gate.compare_membership(["3", "1"], ["1", "3"], 10)["ordered"]) + self.assertFalse(gate.compare_membership(["1", "1"], ["1"], 10)["ordered"]) + self.assertFalse(gate.compare_membership(["11"], ["11"], 10)["ordered"]) def test_exact_membership_and_diagnostics(self): ref = self.root / "ids.txt"