Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
359342d
[search-position] Add the "Position" page of ChessBase's search dialog
tuliovianna-lab Nov 30, 2026
c985159
[search-position] Document the Position page in README, CHANGELOG, pr…
tuliovianna-lab Nov 30, 2026
99b4257
[search-position] Stop at Last and at the end of the main line; add r…
tuliovianna-lab Dec 1, 2026
1761dd0
[search-position] Name the mirrors by their axis, as ChessBase does
tuliovianna-lab Dec 1, 2026
0f1986b
[search-position] Record the ChessBase spot checks
tuliovianna-lab Dec 1, 2026
0c6e426
[search-position] Count the window of moves as ChessBase does
tuliovianna-lab Dec 2, 2026
914bfc1
Merge remote-tracking branch 'origin/pr/11' into integration/position…
itshak Dec 2, 2026
1b03963
fix(query): evaluate initial position and expose strict search window
itshak Dec 2, 2026
fec4bb5
test(query): enable private position membership diagnostics
itshak Dec 2, 2026
01c38ed
test(query): cover special moves and benchmark position search in CI
itshak Dec 2, 2026
57c5153
fix(query): correct boundary fixtures and pair contributor performance
itshak Dec 2, 2026
d3f5e1f
test(query): prepare independent replay and private discrepancy adjud…
itshak Dec 2, 2026
44df1eb
test(query): expose exact-key replay membership for index cross-checks
itshak Dec 2, 2026
bff110a
test(query): verify full public exact-key and audit-tool membership
itshak Dec 2, 2026
db7b3a6
test(query): adjudicate divergent exports and equal-count mismatches
itshak Dec 2, 2026
e181d8d
docs: clean position acceptance runbook whitespace
itshak Dec 2, 2026
728fb4b
test(query): select played game for divergent-board control
itshak Dec 2, 2026
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: 5 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,13 @@ jobs:
if: matrix.os == 'ubuntu-latest'
env:
CBVAULT_NO_MMAP: "1"
run: cargo test -p cbvault --all-features --test twocbh_bridge --test twocbh_parallel_sink --test twocbh_annotation_fail_closed
run: cargo test -p cbvault --all-features --test twocbh_bridge --test twocbh_parallel_sink --test twocbh_annotation_fail_closed --test query_position


- name: Private oracle checker generated negative controls
if: matrix.os == 'ubuntu-latest'
run: python3 scripts/test-query-private-acceptance.py

- name: Cargo fmt
run: cargo fmt --all --check

Expand Down
44 changes: 44 additions & 0 deletions .github/workflows/native-bench.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ jobs:
needed += 4 * 1024**3
elif os.environ["TIER"] == "standard":
needed += 2 * 1024**3
if os.environ.get("GITHUB_HEAD_REF") == "integration/position-search-pr11":
needed += 2 * 1024**3 # contributor comparison build
assert shutil.disk_usage(os.environ["RUNNER_TEMP"]).free >= needed, "insufficient runner disk"
PY
- uses: actions/checkout@v4
Expand Down Expand Up @@ -78,6 +80,48 @@ jobs:
mkdir -p benchmark-report
{ rustc --version; uname -a; lscpu; echo "base=${{ steps.corpus.outputs.baseline }}"; git rev-parse HEAD; } > benchmark-report/environment.txt
python3 scripts/bench-corpus/native-bench.py --tier "$TIER" --fixtures "$RUNNER_TEMP/native" --base "$RUNNER_TEMP/base-target/release/cbvault" --head "$RUNNER_TEMP/head-target/release/cbvault" --base-workload "$RUNNER_TEMP/base-target/release/examples/native_workload" --head-workload "$RUNNER_TEMP/head-target/release/examples/native_workload" --report benchmark-report/results.json --repetitions 5
- uses: actions/checkout@v4
if: github.head_ref == 'integration/position-search-pr11'
with:
ref: 0c6e42642eb06809bb2a114f6fd81059f1573adc
path: position-reference-src
persist-credentials: false
- name: Build original position-search contributor revision
if: github.head_ref == 'integration/position-search-pr11'
run: |
cargo +1.97.1 build --locked --release -p cbvault-cli --manifest-path position-reference-src/Cargo.toml --target-dir "$RUNNER_TEMP/position-reference-target"
- name: Position search correctness and timing diagnostics
if: matrix.tier == 'smoke' || matrix.tier == 'extreme'
run: |
reference=()
if [[ -x "$RUNNER_TEMP/position-reference-target/release/cbvault" ]]; then
reference=(--reference-cli "$RUNNER_TEMP/position-reference-target/release/cbvault")
echo "position-reference=0c6e42642eb06809bb2a114f6fd81059f1573adc" >> benchmark-report/environment.txt
fi
python3 scripts/bench-corpus/position-bench.py --tier "$TIER" --fixtures "$RUNNER_TEMP/native" --cli "$RUNNER_TEMP/head-target/release/cbvault" --report benchmark-report/position-search.json "${reference[@]}"
- name: Independent PGN fragment matcher and controlled ChessBase fixtures
if: matrix.tier == 'smoke'
run: |
python3 -m venv "$RUNNER_TEMP/audit-venv"
"$RUNNER_TEMP/audit-venv/bin/pip" install --no-cache-dir -r scripts/requirements-position-audit.txt
audit="$RUNNER_TEMP/audit-venv/bin/python"
"$audit" scripts/test-position-audit.py
"$audit" scripts/position-audit.py fixture --out benchmark-report/controlled-position-fixture
for ext in cbh 2cbh; do
db="$RUNNER_TEMP/native/realistic-25000.$ext"
cli="$RUNNER_TEMP/head-target/release/cbvault"
"$cli" pgn "$db" "$RUNNER_TEMP/audit-$ext.pgn" --from 1 --to 512 --threads 1
"$audit" scripts/position-audit.py oracle --pgn "$RUNNER_TEMP/audit-$ext.pgn" --first-id 1 --expected-games 512 --controlled --cli "$cli" --db "$db" --out "benchmark-report/independent-$ext"
done
- name: Independent exact-key replay and audit-tool end-to-end checks
if: matrix.tier == 'smoke'
run: |
cargo +1.97.1 build --locked --release -p cbvault --example exact_position_ids --target-dir "$RUNNER_TEMP/head-target"
reference=()
if [[ -x "$RUNNER_TEMP/position-reference-target/release/cbvault" ]]; then
reference=(--contributor "$RUNNER_TEMP/position-reference-target/release/cbvault")
fi
"$RUNNER_TEMP/audit-venv/bin/python" scripts/test-position-public.py --cli "$RUNNER_TEMP/head-target/release/cbvault" --exact "$RUNNER_TEMP/head-target/release/examples/exact_position_ids" --fixtures "$RUNNER_TEMP/native" --out benchmark-report/public-exact-audit "${reference[@]}"
- uses: actions/upload-artifact@v4
if: always()
with:
Expand Down
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 @@ -67,6 +67,7 @@ cbvault pgn "MyDatabase.2cbh" games.pgn --threads 8
cbvault archive list "Collection.cbv"
cbvault archive extract "Collection.cbv" ./extracted --threads 8
cbvault search "MyDatabase.2cbh" --white "Carlsen, Magnus" --ignore-colours --elo 2700- --elo-mode both --pgn found.pgn
cbvault search "MyDatabase.2cbh" --look-for "Bh7 kg8" --mirror h --result 1-0
```

The same database commands also work with classic `.cbh` files; archive commands accept `.cbz` with `--password`. The CLI can emit machine-readable JSON and redirect PGN to stdout.
Expand All @@ -83,7 +84,7 @@ cbvault book verify "MyBook.ctg" --children --json

**Direct database browsing.** List games, inspect player/event metadata, open a game with its annotations and variations, or export a selected record to PGN. Headers can be read independently of move decoding.

**Search and preparation.** Filter by players, ECO, result, year, rating or round. `cbvault::query` and `cbvault search` support composable ChessBase-style Game data criteria: names with "ignore colours" and "wins only", tournament, annotator, date and ECO ranges, move count, Elo in each mode with a rating difference, results including mate, stalemate and check, guiding texts, "any text" and native 2CBH time control ([docs/search.md](docs/search.md)). Resolve multiple matching player IDs instead of silently picking one. Scan positions with legal replay, stop when enough results are found, or generate Polyglot keys for a separate opening index.
**Search and preparation.** Filter by players, ECO, result, year, rating or round. `cbvault::query` and `cbvault search` support composable ChessBase-style Game data criteria: names with "ignore colours" and "wins only", tournament, annotator, date and ECO ranges, move count, Elo in each mode with a rating difference, results including mate, stalemate and check, guiding texts, "any text" and native 2CBH time control, combined with the Position page: partial positions on "Look for", "Or" and "Exclude" boards with jokers, mirrors and a window of moves ([docs/search.md](docs/search.md)). Resolve multiple matching player IDs instead of silently picking one. Scan positions with legal replay, stop when enough results are found, or generate Polyglot keys for a separate opening index.

**High-throughput data pipelines.** Use `GameSink` with `for_each_game`, `for_each_range` or `convert_parallel`. Each callback receives borrowed game data; the sink can request moves, keys and/or native annotations as needed. Parallel processing **preserves source record order**, so consumers do not need to reorder games afterward.

Expand Down
48 changes: 44 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, PositionWindow, SearchOptions,
TextMatch, TextsMatch, TimeControl, parse_fragment, parse_range,
};

use crate::json_str;
Expand All @@ -28,10 +28,27 @@ criteria (the \"Game data\" page of ChessBase's search dialog; all must hold):
--text search guiding texts instead of games
--time-control classical|rapid|blitz|correspondence

position (the \"Position\" page; replays the main line of the games kept above):
--look-for BOARD --or BOARD --exclude BOARD
BOARD is men and squares: KQRBNP White, kqrbnp Black, X/x any white/black man,
e.g. \"Kg1 Rf1 Pf2g2h2 bh7\"; Or/Exclude may name a square more than once
--mirror h|v|hv also look for the fragment reflected top-bottom with the
colours swapped (h) or left-right (v)
--first-move N --length N --last-move N (defaults 1, 1, 40, as in ChessBase;
Length counts consecutive positions, i.e. plies;
as in ChessBase, the window runs from the start through
move max(Last, First+1), plus White's next move)
--position-window chessbase|strict strict counts only First through Last

The count and timings go to stderr; the matches (or --json) to stdout. --limit
caps the listed matches (default 50, 0 = all); --pgn writes every match as PGN.
--ids-only omits metadata; text output is one ID per line with JSON statistics on stderr.";

/// The query's "Position" page, created with the dialog's defaults.
fn position(query: &mut GameDataQuery) -> &mut PositionQuery {
query.position.get_or_insert_with(PositionQuery::default)
}

/// Runs `cbvault search`.
pub(crate) fn run(mut args: impl Iterator<Item = String>) -> Result<bool, Box<dyn std::error::Error>> {
let mut db_path: Option<String> = None;
Expand Down Expand Up @@ -100,6 +117,29 @@ 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()?,
"--position-window" => {
position(&mut query).window = match value("--position-window")?.as_str() {
"chessbase" => PositionWindow::ChessBaseCompatible,
"strict" => PositionWindow::Strict,
other => return Err(format!("unknown --position-window {other:?}").into()),
};
}
"--sacrifice" => position(&mut query).sacrifice = true,
"--from" => options.first = value("--from")?.parse()?,
"--to" => options.last = value("--to")?.parse()?,
"--threads" => options.threads = value("--threads")?.parse()?,
Expand Down
38 changes: 38 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,41 @@ fn id_only_export_is_ordered_and_has_exact_count() {
assert!(json.starts_with("{\"matches\":3,"));
assert!(json.contains("\"ids\":[1]"));
}

#[test]
fn position_options_reach_the_query() {
let temp = db("cli_search_position");
// Every game is 1.e4 e5: the e-pawns meet on e4 and e5 on move 1.
let (ok, json) = search(&temp, &["--look-for", "Pe4 pe5", "--json"]);
assert!(ok);
assert!(json.starts_with("{\"matches\":3,"), "{json}");
let (_, json) = search(&temp, &["--look-for", "Pe4", "--exclude", "pe5", "--length", "2", "--json"]);
assert!(json.starts_with("{\"matches\":0,"), "{json}");
// d4 reflected left to right is e4.
let (_, json) = search(&temp, &["--look-for", "Pd4", "--white", "Carlsen", "--json"]);
assert!(json.starts_with("{\"matches\":0,"), "{json}");
let (_, json) = search(&temp, &["--look-for", "Pd4", "--mirror", "v", "--white", "Carlsen", "--json"]);
assert!(json.starts_with("{\"matches\":1,") && json.contains("\"id\":3,"), "{json}");
// The horizontal mirror swaps colours: a black pawn on e4 becomes a white
// pawn on e5, not the black pawn that stands there.
let (_, json) = search(&temp, &["--look-for", "pe4", "--mirror", "h", "--last-move", "1", "--json"]);
assert!(json.starts_with("{\"matches\":0,"), "{json}");
let (_, json) = search(&temp, &["--look-for", "pe4", "--mirror", "hv", "--last-move", "1", "--json"]);
assert!(json.starts_with("{\"matches\":0,"), "{json}");
let (_, json) = search(&temp, &["--look-for", "Pe2", "--first-move", "2", "--last-move", "2", "--json"]);
assert!(json.starts_with("{\"matches\":3,"), "{json}");
let (_, json) = search(
&temp,
&["--look-for", "Pe2", "--first-move", "2", "--last-move", "2", "--position-window", "strict", "--json"],
);
assert!(json.starts_with("{\"matches\":0,"), "{json}");
for bad in [
&["--look-for", "Ki9"][..],
&["--look-for", "Ke1", "--position-window", "invalid"],
&["--mirror", "x", "--look-for", "Ke1"],
&["--look-for", "Ke1", "--sacrifice"],
&["--first-move", "5", "--last-move", "2", "--look-for", "Ke1"],
] {
assert!(!search(&temp, bad).0, "{bad:?}");
}
}
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
56 changes: 56 additions & 0 deletions crates/cbvault/examples/exact_position_ids.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! Ordered, unique record IDs for an exact Polyglot-key replay.
//! Diagnostic for downstream position indexes; not a fragment query.
#![allow(missing_docs)]
use cbvault::bridge::{Database, PositionQuery, for_each_position_key};
use std::fs::OpenOptions;
use std::io::{BufWriter, Write};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().skip(1).collect();
if args.len() != 4 {
return Err("usage: exact_position_ids DB FEN THREADS OUTPUT_IDS".into());
}
let db = Database::open(&args[0])?;
let board = gigachess::fen::parse_fen(&args[1]).map_err(|_| "invalid FEN")?;
let threads = args[2].parse::<usize>()?;
if threads == 0 {
return Err("threads must be positive".into());
}
let mut out = BufWriter::new(OpenOptions::new().write(true).create_new(true).open(&args[3])?);
let key = board.zobrist();
let query = PositionQuery::of(key);
let mut previous = 0;
let mut count = 0u64;
let mut error = None;
let stats = for_each_position_key(&db, &query, threads, |hit| {
if error.is_some() || hit.game == previous {
return;
}
if hit.game < previous {
error = Some(std::io::Error::other("out-of-order replay hit"));
return;
}
match writeln!(out, "{}", hit.game) {
Ok(()) => {
count += 1;
previous = hit.game;
}
Err(e) => error = Some(e),
}
})?;
if let Some(e) = error {
return Err(e.into());
}
out.flush()?;
eprintln!(
"{{\"key\":\"{key:016x}\",\"records\":{},\"unique_ids\":{count},\"hits\":{},\"failures\":{},\"complete\":{}}}",
db.records(),
stats.hits,
stats.failures,
stats.complete
);
if !stats.complete {
return Err("incomplete exact-key replay".into());
}
Ok(())
}
Loading
Loading