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 19a586ce..4cd1f870 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,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. @@ -79,7 +80,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..77c0aa81 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, SearchOptions, TextMatch, + TextsMatch, TimeControl, parse_fragment, parse_range, }; use crate::json_str; @@ -28,10 +28,26 @@ 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) + 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 +116,22 @@ 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()?, + "--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..ff7cae86 100644 --- a/crates/cbvault-cli/tests/cli_search.rs +++ b/crates/cbvault-cli/tests/cli_search.rs @@ -126,3 +126,33 @@ 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}"); + for bad in [ + &["--look-for", "Ki9"][..], + &["--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/src/query/ending.rs b/crates/cbvault/src/query/ending.rs index 7a85d153..d2b17fd2 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,113 @@ 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, + /// Whether any move has been reported. + moved: 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 MoveSink for MainLine<'_> { + fn play(&mut self, board: &Board, _: u16, main: bool) { + if !self.moved { + self.moved = true; + // The start position, before the first move. + self.position.position(board, board.fullmove_number(), false); + } + 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 && self.moved) || 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, + moved: false, + move_number: 0, + endings: wanted.is_set(), + last: None, + position: Tracker::new(pattern), + }; + let initial = replay.walk(header, &mut sink); + if sink.stopped.get() || is_cancelled() { + return Err(super::QueryError::Cancelled); + } + let Ok(initial) = initial else { + return Ok(None); + }; + if !sink.moved { + // A game without moves: its start position is its only one. + sink.position.position(&initial, initial.fullmove_number(), false); + } + 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 +174,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..da941c62 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}; 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..1c5b82f1 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,63 @@ 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([' ', ',', ';']).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.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..0ecc0123 --- /dev/null +++ b/crates/cbvault/src/query/position.rs @@ -0,0 +1,440 @@ +//! 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() + } +} + +/// 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, + /// "First". As ChessBase answers it, it does not cut the positions before + /// it: 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": the last move whose positions all count; the position after + /// White's following move counts too, as in ChessBase. + pub last: u16, + /// "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, + 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, +} + +/// Whether "First" cuts the positions before it. ChessBase does not (see +/// [`window_end`]); kept as a switch so that the measurement can be repeated. +const FIRST_IS_LOWER_BOUND: bool = false; + +/// 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); + } + Pattern { orientations, first: query.first, length: query.length, end: window_end(query.first, query.last) } + } + + #[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 } + } + + /// 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() || (FIRST_IS_LOWER_BOUND && move_number < self.pattern.first) { + return; + } + let end = self.pattern.end; + // The position after White's move following the window still counts. + let extra = after_white && move_number == end.saturating_add(1); + 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) { + if self.decided.is_none() && next_move > self.pattern.end.saturating_add(1) { + 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(_)))); + } +} 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..2f769962 --- /dev/null +++ b/crates/cbvault/tests/query_position.rs @@ -0,0 +1,478 @@ +//! 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, 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 = q.last.max(q.first + 1); + let (mut run, mut hit) = (0, false); + for (b, n, after_white) in positions { + if n > end + 1 || (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, + sacrifice: false, + }); + combined += 1; + } +} 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..93715b60 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,60 @@ 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 | +| Length | `length` | `--length N` | The fragment stands in this many consecutive counted positions (plies). 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** is searched, from its start position. 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 (unless the final position is also asked for), at the first +position after "Last", 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. + ## 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 +163,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) 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..cb8131fc --- /dev/null +++ b/openspec/changes/search-position/specs/cbvault/spec.md @@ -0,0 +1,41 @@ +## 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. + +#### 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 the final position is also asked for. diff --git a/openspec/changes/search-position/tasks.md b/openspec/changes/search-position/tasks.md new file mode 100644 index 00000000..8f5f0bf7 --- /dev/null +++ b/openspec/changes/search-position/tasks.md @@ -0,0 +1,26 @@ +# 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; ChessBase reads past move Last by a rule not yet established, left open + +## 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