Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.

Expand Down
40 changes: 36 additions & 4 deletions crates/cbvault-cli/src/search.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! `cbvault search <db> [options]`: the "Game data" page of ChessBase's search
//! dialog, as options. A thin shell over [`cbvault::query`]: it reads the
//! `cbvault search <db> [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.

Expand All @@ -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;
Expand All @@ -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<Item = String>) -> Result<bool, Box<dyn std::error::Error>> {
let mut db_path: Option<String> = None;
Expand Down Expand Up @@ -100,6 +116,22 @@ pub(crate) fn run(mut args: impl Iterator<Item = String>) -> Result<bool, Box<dy
other => 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()?,
Expand Down
30 changes: 30 additions & 0 deletions crates/cbvault-cli/tests/cli_search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:?}");
}
}
35 changes: 34 additions & 1 deletion crates/cbvault/benches/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 |");
Expand Down
124 changes: 118 additions & 6 deletions crates/cbvault/src/query/ending.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<bool>,
Expand Down Expand Up @@ -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<bool>,
/// 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<Board>,
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<Option<bool>, 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)>,
Expand All @@ -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 }
}
10 changes: 10 additions & 0 deletions crates/cbvault/src/query/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -39,6 +40,7 @@ pub(crate) struct Compiled {
elo_difference: Option<EloDifference>,
results: ResultSet,
pub(crate) endings: Endings,
pub(crate) position: Option<Pattern>,
pub(crate) text_records: bool,
any_text: Option<AnyIds>,
time_control: Option<EntityIdSet>,
Expand Down Expand Up @@ -163,13 +165,19 @@ 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,
extra: query.extra.clone(),
})
}

/// 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.
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down
Loading
Loading