From 131e4b62fb5009f3a3b2b07be1ffcd5e5ea09a49 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 19 Oct 2026 09:03:26 +0300 Subject: [PATCH] Position search fixes from QA report 3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The result cache keys on the board's move order too, so "in this move order" is not reused from another order of the same position. - While a search runs, the hover arrow and the position a game opens at belong to the rows shown; small databases keep the last result dimmed. - PGN: a game ending in its chosen occurrence has no next move (it was taken from a variation); Collector::add_match_with_next. - Average rating of a continuation only from games with both ratings. - Narrow windows: the pane switch stays visible, chips that do not fit become "+N more", columns hide by priority, the date becomes the year. - Ctrl+Shift+Backspace clears all conditions with the position; × for the position in small databases; the outcome cache is bounded. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 + apps/desktop/src/board_search.rs | 3 +- apps/desktop/src/i18n.rs | 9 + apps/desktop/src/large_db.rs | 217 ++++++++++++++------ apps/desktop/src/library.rs | 43 ++-- crates/chess-import/src/chessbase/search.rs | 5 +- crates/chess-import/src/pgn_positions.rs | 20 +- crates/chess-import/src/position.rs | 51 +++-- docs/qa/report-3.md | 34 +++ 9 files changed, 289 insertions(+), 104 deletions(-) create mode 100644 docs/qa/report-3.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 2908afa..0578430 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Position search fixes (QA report 3): "in this move order" no longer reused from another move + order of the same position; while a search runs, the arrow and the position a game opens at + belong to the rows shown; in books the next move of a game ending in the position is no longer + taken from a variation; average rating of a continuation only from games with both ratings. +- Narrow windows: the [Filters | Board] switch stays visible, conditions that do not fit become + "+N more", columns hide by priority and the date becomes the year. +- Ctrl+Shift+Backspace clears all conditions with the position; a × removes the position in small + databases; the cache of search results is bounded. + ## [0.5.0] — 2026-10-19 - Find games by position: the "Board" pane next to the game list (Ctrl+B). Play moves and the list diff --git a/apps/desktop/src/board_search.rs b/apps/desktop/src/board_search.rs index a41f1cb..a7ed77d 100644 --- a/apps/desktop/src/board_search.rs +++ b/apps/desktop/src/board_search.rs @@ -271,7 +271,8 @@ impl SearchBoard { let now = ctx.input(|i| i.time); let mut changed = false; ctx.input_mut(|i| { - if i.consume_key(Modifiers::COMMAND, Key::Backspace) { + // Ctrl+Backspace (not with Shift: that clears all conditions). + if !i.modifiers.shift && i.consume_key(Modifiers::COMMAND, Key::Backspace) { self.reset(now); changed = true; } diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 285cb16..f01bdcb 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -80,6 +80,15 @@ pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String { // [English, Русский, Français, Deutsch, Español, Italiano] const ROWS: &[[&str; 6]] = &[ // --- position search --- + ["Year", "Год", "Année", "Jahr", "Año", "Anno"], + [ + "+{n} more", + "ещё {n}", + "+{n} autres", + "+{n} weitere", + "+{n} más", + "+{n} altri", + ], [ "Clear", "Очистить", diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 585e017..5f2196a 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -181,9 +181,27 @@ pub enum Pane { Board, } -/// Search outcomes of the session, by filter and position. +/// Search outcomes of the session, by filter and position with the board's move order +/// (it decides "in this move order"). type OutcomeCache = HashMap<(u64, u64), Arc>; +/// Matching games kept in the cache at most (16 bytes each). +const CACHE_MATCHES: usize = 20_000_000; + +/// Identity of a searched position with the board's move order. +fn position_id((key, query): &(u64, PositionQuery)) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + key.hash(&mut h); + if let Some(line) = &query.line { + for m in line { + chess_import::position::uci(m).to_string().hash(&mut h); + } + } else { + "no line".hash(&mut h); + } + h.finish() +} + fn filter_hash(f: &Filter) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); f.hash(&mut h); @@ -347,12 +365,15 @@ impl LargeView { && s.position.as_ref().map(|p| p.0) != job.request.position.as_ref().map(|p| p.0)) }); - if let (Some(out), Some((key, _))) = (&answer.outcome, &job.request.position) { - if self.cache.len() > 256 { + if let (Some(out), Some(pos)) = (&answer.outcome, &job.request.position) { + let kept: usize = self.cache.values().map(|o| o.matches.len()).sum(); + if kept + out.matches.len() > CACHE_MATCHES { self.cache.clear(); } - self.cache - .insert((filter_hash(&job.request.filter), *key), out.clone()); + self.cache.insert( + (filter_hash(&job.request.filter), position_id(pos)), + out.clone(), + ); } self.view = answer.view; self.outcome = answer.outcome; @@ -408,7 +429,10 @@ impl LargeView { let cached = request .position .as_ref() - .and_then(|(key, _)| self.cache.get(&(filter_hash(&request.filter), *key))) + .and_then(|pos| { + self.cache + .get(&(filter_hash(&request.filter), position_id(pos))) + }) .cloned(); let (db, req) = (db.clone(), request.clone()); let work = Background::spawn(ctx, now, move |progress, cancel| { @@ -718,23 +742,12 @@ impl LargeView { let mut toggle_order = false; ui.horizontal(|ui| { ui.set_min_height(22.0); - if conditions.is_empty() { - ui.label(RichText::new(tr("No conditions: all games are shown")).weak()); - } - for c in &conditions { - let (open, remove) = chip(ui, c); - if open { - goto = Some(c.pane); - } - if remove { - clear = Some(c.clear); - } - } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if let Some((same, all)) = self.in_order && self.board.is_set() && (same < all || self.only_order) { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + { let link = if self.only_order { tr("all move orders") } else { @@ -755,8 +768,36 @@ impl LargeView { .weak() .size(12.0), ); - }); + } } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if conditions.is_empty() { + ui.label(RichText::new(tr("No conditions: all games are shown")).weak()); + } + for (n, c) in conditions.iter().enumerate() { + // No room for another chip: the rest in a tooltip. + if ui.available_width() < 140.0 && n + 1 < conditions.len() { + let rest: Vec<&str> = + conditions[n..].iter().map(|c| c.text.as_str()).collect(); + if ui + .link(trf("+{n} more", &[("n", &rest.len())])) + .on_hover_text(rest.join("\n")) + .clicked() + { + goto = Some(Pane::Filters); + } + break; + } + let (open, remove) = chip(ui, c); + if open { + goto = Some(c.pane); + } + if remove { + clear = Some(c.clear); + } + } + }); + }); }); if toggle_order { self.only_order = !self.only_order; @@ -803,14 +844,6 @@ impl LargeView { ui.add_space(4.0); self.annotations_group(ui); }); - if ui.input_mut(|i| { - i.consume_key( - egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, - egui::Key::Backspace, - ) - }) { - self.reset(); - } } fn reset(&mut self) { @@ -1164,19 +1197,31 @@ impl LargeView { let progress = self.slow_progress(now, base.records()); let total = base.games() + base.texts(); + // The pane switch comes first (right): it stays visible in a narrow window, + // the rest of the line is shortened. ui.horizontal(|ui| { - ui.label( - RichText::new( - path.file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(), + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + // The switch packs its segments; the rest keeps the usual spacing. + ui.scope(|ui| self.pane_switch(ui)); + ui.add_space(8.0); + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.add( + egui::Label::new( + RichText::new( + path.file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(), + ) + .strong(), ) - .strong(), + .truncate(), ); - ui.label(RichText::new(tr("· ChessBase, read-only")).weak()) - .on_hover_text(tr( - "Read in place; the original files are not changed. Save a game to keep your edits.", - )); + if ui.available_width() > 520.0 { + ui.label(RichText::new(tr("· ChessBase, read-only")).weak()) + .on_hover_text(tr( + "Read in place; the original files are not changed. Save a game to keep your edits.", + )); + } let counter = match &self.shown { Some(s) if s.use_position @@ -1198,7 +1243,7 @@ impl LargeView { if progress.is_some() { counter = counter.weak(); } - ui.label(counter); + ui.add(egui::Label::new(counter).truncate()); if let Some(p) = progress { ui.add(egui::Spinner::new().size(14.0)); ui.label(RichText::new(format!("{:.0} %", p * 100.0)).weak()); @@ -1211,9 +1256,8 @@ impl LargeView { { open_notes = true; } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - self.pane_switch(ui); }); + }); }); self.chips(ui, settings); ui.add_space(2.0); @@ -1225,8 +1269,26 @@ impl LargeView { if ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::B)) { self.pane = Pane::Board; } + // Ctrl+Shift+Backspace: all conditions, the position included. + if ui.input_mut(|i| { + i.consume_key( + egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, + egui::Key::Backspace, + ) + }) { + self.reset(); + self.board = SearchBoard::new(); + self.only_order = false; + } let use_position = self.shown.as_ref().is_some_and(|s| s.use_position); + // The position the shown rows were found for (the board may be ahead of it). + let shown_position = self + .shown + .as_ref() + .filter(|s| s.use_position) + .and_then(|s| s.position.as_ref()) + .map(|(_, q)| q.position.clone()); if self.shown.is_some() && self.view.is_empty() && self.job.is_none() { ui.vertical_centered(|ui| { ui.add_space(40.0); @@ -1262,46 +1324,60 @@ impl LargeView { None }; // Narrow windows drop the least needed columns first. + // Narrow windows drop the least needed columns first (round, number, marks, + // length, ECO, event); the date becomes the year. let width = ui.available_width(); - let show_round = width >= 1000.0; - let show_moves = width >= 760.0; - let show_marks = width >= 720.0; + let show_round = width >= 1100.0; + let show_number = !use_position || width >= 1100.0; + let show_moves = width >= 1000.0; + let show_marks = width >= 1000.0; + let show_eco = width >= 860.0; + let show_event = width >= 720.0; + let year_only = width < 1000.0; let mut columns: Vec<(&str, Option, Column)> = Vec::new(); if use_position { columns.push((tr("Move"), None, Column::exact(52.0))); } + if show_number { + columns.push(("№", Some(SortKey::Number), Column::exact(84.0))); + } + // Without the event the names share the rest of the width. + let name = if show_event { + Column::initial(170.0).at_least(60.0).clip(true) + } else { + Column::remainder().at_least(60.0).clip(true) + }; columns.extend([ - ("№", Some(SortKey::Number), Column::exact(84.0)), - ( - tr("White"), - Some(SortKey::White), - Column::initial(170.0).at_least(60.0).clip(true), - ), + (tr("White"), Some(SortKey::White), name), ("Elo", Some(SortKey::WhiteElo), Column::exact(44.0)), - ( - tr("Black"), - Some(SortKey::Black), - Column::initial(170.0).at_least(60.0).clip(true), - ), + (tr("Black"), Some(SortKey::Black), name), ("Elo", Some(SortKey::BlackElo), Column::exact(44.0)), (tr("Result"), Some(SortKey::Result), Column::exact(56.0)), ]); if show_moves { columns.push((tr("Length"), Some(SortKey::Moves), Column::exact(56.0))); } - columns.push(("ECO", Some(SortKey::Eco), Column::exact(44.0))); + if show_eco { + columns.push(("ECO", Some(SortKey::Eco), Column::exact(44.0))); + } if show_marks { columns.push(("💬", None, Column::exact(40.0))); } - columns.push(( - tr("Event"), - Some(SortKey::Event), - Column::remainder().at_least(80.0).clip(true), - )); + if show_event { + columns.push(( + tr("Event"), + Some(SortKey::Event), + Column::remainder().at_least(80.0).clip(true), + )); + } if show_round { columns.push((tr("Round"), None, Column::exact(48.0))); } - columns.push((tr("Date"), Some(SortKey::Date), Column::exact(88.0))); + if year_only { + columns.push((tr("Year"), Some(SortKey::Date), Column::exact(48.0))); + } else { + columns.push((tr("Date"), Some(SortKey::Date), Column::exact(88.0))); + } if progress.is_some() { ui.set_opacity(0.6); @@ -1432,6 +1508,9 @@ impl LargeView { RichText::new(marks).weak() } (_, Some(SortKey::Event)) => RichText::new(r.event.as_str()).italics(), + (_, Some(SortKey::Date)) if year_only => { + RichText::new(r.date.get(..4).filter(|y| !y.contains('?')).unwrap_or("")) + } (_, Some(SortKey::Date)) => RichText::new(crate::library::display_date(&r.date)), _ => RichText::new(if r.round == "?" { "" } else { r.round.as_str() }).weak(), }; @@ -1439,7 +1518,7 @@ impl LargeView { }); } let resp = row.response(); - let resp = if show_round { + let resp = if show_round && show_event { resp } else { resp.on_hover_text(format!("{} · {}", r.event, r.round)) @@ -1466,7 +1545,10 @@ impl LargeView { } }); }); + // The shown rows belong to the shown position: no arrow on another one. + let shown_here = shown_position.as_ref() == Some(&self.board.position()); self.table_hover = hovered + .filter(|_| shown_here) .zip(self.outcome.as_deref().filter(|_| use_position)) .and_then(|(i, out)| board_search::next_move_of(out, i)); if let Some((k, v)) = toggle_viewed { @@ -1490,7 +1572,7 @@ impl LargeView { actions.push(LibraryAction::OpenGame { path: path.to_path_buf(), index, - at: use_position.then(|| self.board.position()), + at: shown_position.clone(), }); } open_notes @@ -1534,7 +1616,12 @@ impl LargeView { actions.push(LibraryAction::OpenGame { path: path.to_path_buf(), index, - at: self.board.is_set().then(|| self.board.position()), + at: self + .shown + .as_ref() + .filter(|s| s.use_position) + .and_then(|s| s.position.as_ref()) + .map(|(_, q)| q.position.clone()), }); } } diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index ff8fef8..2c5b264 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -75,8 +75,9 @@ struct SmallRequest { struct SmallBoard { board: SearchBoard, open: bool, - job: Option<(SmallRequest, Background)>, - shown: Option<(SmallRequest, Arc)>, + job: Option<(SmallRequest, shakmaty::Chess, Background)>, + /// The last result, the request and the position it answers. + shown: Option<(SmallRequest, shakmaty::Chess, Arc)>, table_hover: Option, /// Most games have no result: a book; continuations count chapters. books: bool, @@ -111,13 +112,13 @@ impl SmallBoard { /// Collects a finished search and starts the one the board and search text ask for. fn update(&mut self, db: &Arc, search: &str, ctx: &egui::Context) { - if let Some((req, job)) = &self.job + if let Some((req, pos, job)) = &self.job && let Some(result) = job.poll() { - let req = req.clone(); + let (req, pos) = (req.clone(), pos.clone()); self.job = None; if let Some(out) = result { - self.shown = Some((req, Arc::new(out))); + self.shown = Some((req, pos, Arc::new(out))); } } if !self.open && !self.board.is_set() { @@ -127,10 +128,11 @@ impl SmallBoard { let current = self .job .as_ref() - .map(|(r, _)| r) - .or(self.shown.as_ref().map(|(r, _)| r)); + .map(|(r, ..)| r) + .or(self.shown.as_ref().map(|(r, ..)| r)); if current != Some(&wanted) { let (db, query, text) = (db.clone(), self.board.query(), wanted.search.clone()); + let pos = query.position.clone(); let now = ctx.input(|i| i.time); self.job = Background::spawn(ctx, now, move |progress, cancel| { let pgn = db.as_pgn()?; @@ -145,7 +147,7 @@ impl SmallBoard { }); db.search_position(candidates.as_deref(), &query, progress, cancel) }) - .map(|j| (wanted, j)); + .map(|j| (wanted, pos, j)); } if self.job.is_some() { ctx.request_repaint_after(std::time::Duration::from_millis(50)); @@ -154,7 +156,7 @@ impl SmallBoard { /// The outcome for the current board and search text, if ready. fn outcome(&self, search: &str) -> Option<&PositionOutcome> { - let (req, out) = self.shown.as_ref()?; + let (req, _, out) = self.shown.as_ref()?; (*req == self.request(search)).then_some(out.as_ref()) } } @@ -867,17 +869,22 @@ impl Library { // With a position on the board: only the games that reach it. let small = self.small.get(&path); let position = small.filter(|s| s.board.is_set()); - let outcome: Option> = position.and_then(|s| { - s.outcome(&self.search) - .map(|_| s.shown.as_ref().expect("shown").1.clone()) - }); - let searching = position.is_some() && outcome.is_none(); - let ordered = position.is_some_and(|s| s.board.query().line.is_some()); - let at = position.map(|s| s.board.position()); + // While a new search runs the last result stays (dimmed): its rows, arrows and + // the position a game opens at all belong to the position it was found for. + let last = position.and_then(|s| s.shown.as_ref()); + let outcome: Option> = last.map(|(_, _, out)| out.clone()); + let current = position.is_some_and(|s| s.outcome(&self.search).is_some()); + let searching = position.is_some() && !current; + let ordered = last.is_some_and(|(req, ..)| req.line.is_some()); + let at = last.map(|(_, pos, _)| pos.clone()); + let mut clear_position = false; if let Some(s) = position { ui.horizontal(|ui| { let text = trf("Position: {line}", &[("line", &s.board.chip_text())]); ui.label(RichText::new(text).size(13.0)); + clear_position = crate::widgets::small_close_button(ui) + .on_hover_text(tr("Remove the condition")) + .clicked(); if searching { ui.add(egui::Spinner::new().size(14.0)); } else if let Some(out) = &outcome { @@ -1122,10 +1129,14 @@ impl Library { }); }); let next = hovered + .filter(|_| current) .zip(outcome.as_deref()) .and_then(|(i, out)| board_search::next_move_of(out, i)); if let Some(small) = self.small.get_mut(&path) { small.table_hover = next; + if clear_position { + small.board = SearchBoard::new(); + } } if let Some((k, v)) = toggle_viewed { self.viewed.set(k, v); diff --git a/crates/chess-import/src/chessbase/search.rs b/crates/chess-import/src/chessbase/search.rs index c7046aa..2583e9f 100644 --- a/crates/chess-import/src/chessbase/search.rs +++ b/crates/chess-import/src/chessbase/search.rs @@ -362,9 +362,8 @@ impl Worker<'_> { }); } else { let mut rec = [0u8; CBB_RECORD]; - self.games.retain(|&(i, _)| { - read_exact_at(cbb, &mut rec, at(i)).is_err() || sig.admits(&rec) - }); + self.games + .retain(|&(i, _)| read_exact_at(cbb, &mut rec, at(i)).is_err() || sig.admits(&rec)); } } diff --git a/crates/chess-import/src/pgn_positions.rs b/crates/chess-import/src/pgn_positions.rs index 35bbf3a..f1c5d4a 100644 --- a/crates/chess-import/src/pgn_positions.rs +++ b/crates/chess-import/src/pgn_positions.rs @@ -300,15 +300,16 @@ impl PositionTable { return; }; let index = game as u32; - out.add_match(Match { + // The move after the chosen occurrence is the game's `next` (none when the + // game ends there, whatever its other branches play). + let first = self.first_child_move(at, refs); + out.add_match_with_next(Match { index, ply: u32::from(self.nodes[at].ply), same_order: !other_order, in_variation, - next: None, + next: first.map(decode), }); - // The move after the chosen occurrence goes first: it is the game's `next`. - let first = self.first_child_move(at, refs); if let Some(pos) = moves.iter().position(|m| Some(m.0) == first) { moves.swap(0, pos); } @@ -647,6 +648,17 @@ mod tests { ); } + #[test] + fn next_move_belongs_to_the_chosen_occurrence() { + // The main line ends in the position; a variation reaches it and goes on. + let db = db("1. e4 (1. Nf3 e5 2. e4 Nc6) 1... e5 2. Nf3 *\n"); + let t = table(&db); + let out = search(&t, &db, &query(&["e4", "e5", "Nf3"])); + assert_eq!(out.matches.len(), 1); + assert!(!out.matches[0].in_variation); + assert_eq!(out.matches[0].next, None); + } + #[test] fn counts_each_move_of_a_game_once() { let db = db(PGN); diff --git a/crates/chess-import/src/position.rs b/crates/chess-import/src/position.rs index 1bb6c47..1c15a15 100644 --- a/crates/chess-import/src/position.rs +++ b/crates/chess-import/src/position.rs @@ -86,11 +86,11 @@ impl Tally { GameResult::BlackWins => self.black_wins += 1, GameResult::Unknown => {} } - for e in [white_elo, black_elo] { - if e > 0 { - self.elo_sum += u64::from(e); - self.elo_count += 1; - } + // The average rating counts games where both ratings are known, like the + // "strongest first" sort. + if white_elo > 0 && black_elo > 0 { + self.elo_sum += u64::from(white_elo) + u64::from(black_elo); + self.elo_count += 2; } self.last_year = self.last_year.max(year); } @@ -161,6 +161,8 @@ pub struct Collector { /// Per move: games that played it in their main line. main_line: HashMap, ended: Tally, + /// The last match whose first continuation was recorded (it decides `next`). + continued: Option, } impl Collector { @@ -187,6 +189,13 @@ impl Collector { self.matches.push(m); } + /// Records a matching game whose [`Match::next`] is already decided (the move + /// after its chosen occurrence); its continuations do not change it. + pub fn add_match_with_next(&mut self, m: Match) { + self.matches.push(m); + self.continued = Some(m.index); + } + /// Records one continuation of game `index` (added with [`Collector::add_match`]): /// a move played next (`main_line`: in the game's main line) or `None` when the /// game ends here. The first move recorded for a game is its [`Match::next`]. @@ -201,14 +210,18 @@ impl Collector { black_elo: u16, year: u16, ) { + // The first continuation belongs to the chosen occurrence: it is the game's + // next move, even when it is the end of the game (later ones come from other + // branches of a PGN game). + if self.continued != Some(index) + && let Some(m) = self.matches.last_mut() + && m.index == index + { + m.next = next; + self.continued = Some(index); + } let tally = match next { Some(uci) => { - if let Some(m) = self.matches.last_mut() - && m.index == index - && m.next.is_none() - { - m.next = Some(uci); - } if main_line { *self.main_line.entry(uci).or_default() += 1; } @@ -309,17 +322,25 @@ mod tests { let mut b = Collector::default(); b.add(m(2), Some(e4), GameResult::BlackWins, 2500, 0, 2024); b.add(m(5), None, GameResult::Unknown, 0, 0, 0); + // A game ending in its chosen occurrence keeps no next move, whatever its other + // branches play. + b.add_match(m(7)); + b.add_continuation(7, None, true, GameResult::Draw, 0, 0, 0); + b.add_continuation(7, Some(e4), false, GameResult::Draw, 0, 0, 0); a.merge(b); let out = a.finish(&pos); assert_eq!( out.matches.iter().map(|m| m.index).collect::>(), - vec![1, 2, 3, 5] + vec![1, 2, 3, 5, 7] ); + assert_eq!(out.matches[4].next, None, "ends in its chosen occurrence"); + assert_eq!(out.matches[2].next, Some(e4)); assert_eq!(out.moves[0].san, "e4"); - assert_eq!(out.moves[0].tally.games, 2); - assert_eq!(out.moves[0].tally.average_elo(), Some(2600)); + assert_eq!(out.moves[0].tally.games, 3); + // Only game 3 has both ratings. + assert_eq!(out.moves[0].tally.average_elo(), Some(2650)); assert_eq!(out.moves[0].tally.last_year, 2024); assert_eq!(out.moves[1].san, "d4"); - assert_eq!(out.ended.games, 1); + assert_eq!(out.ended.games, 2); } } diff --git a/docs/qa/report-3.md b/docs/qa/report-3.md new file mode 100644 index 0000000..12a2477 --- /dev/null +++ b/docs/qa/report-3.md @@ -0,0 +1,34 @@ +# QA-отчёт №3 — поиск партий по позиции + +Дата: 2026-10-19. Проверка независимого тестировщика (профиль `tester`) версии 0.5.0 (коммит 307c55d); отчёт записан оркестратором (среда запрещает субагентам создавать `.md`), исправления — оркестратор, после релиза 0.5.0. +Окружение: i7-13700KF (24 потока), 31 ГБ, NVMe, Hyprland, release-сборки, 3840×2160 при масштабе 2. Код проверок, скриншоты и логи — `target/tester2/` (не в git). + +## Дефекты и статус + +| # | Серьёзность | Суть | Статус | +| --- | --- | --- | --- | +| 1 | средняя | Кэш результатов в большой базе по ключу (фильтр, позиция) без линии ходов: после смены порядка ходов «этим порядком», ↪ и «только этот порядок» брались от прежнего порядка (найдено по коду) | Исправлено: ключ кэша включает линию ходов (`large_db.rs::position_id`) | +| 2 | средняя | Пока идёт поиск, стрелка при наведении на строку и позиция открытия партии брались от новой позиции, а строки — старой; в малой базе во время поиска таблица показывала всю базу | Исправлено: стрелка только для показанной позиции, партия открывается на позиции, для которой найдена строка; малая база держит прошлый результат (приглушённо) | +| 3 | средняя | PGN: если выбранное вхождение заканчивает партию, `Match::next` брал ход из варианта (15 случаев в сэмплах) | Исправлено: `Collector::add_match_with_next`, следующий ход выбранного вхождения задаётся явно; правило «первое продолжение» в `Collector`; тест `next_move_belongs_to_the_chosen_occurrence` | +| 4 | средняя | Узкое окно (1000 и 900 px): переключатель `[Фильтры \| Доска]` обрезался или пропадал, чипы наезжали на строку порядка ходов, колонки не прятались по приоритету | Исправлено: переключатель и строка порядка рисуются первыми справа, остальное сокращается; чипы, которым нет места, — «ещё N» с подсказкой; колонки прячутся по приоритету (раунд, №, длина, отметки, ECO, турнир), дата → год. Проверено на половине ширины; 900×600 вживую не перепроверялось | +| 5 | низкая | «Ход» для партий с FEN-стартом считается от числа полуходов, без номера хода и очереди из FEN | Открыто | +| 6 | низкая | Ctrl+Shift+Backspace в режиме «Доска» сбрасывал только позицию (egui игнорирует лишний Shift); «сбросить всё» было только в панели фильтров | Исправлено: Ctrl+Backspace доски не срабатывает с Shift; Ctrl+Shift+Backspace сбрасывает все условия вместе с позицией из любого режима | +| 7 | низкая | Средний Эло продолжений считался по каждому известному рейтингу («6.Bb5+ · 1 партия · 730») | Исправлено: только партии, где известны оба рейтинга (как сортировка «сильнейшие сверху») | +| 8 | низкая | Кэш до 256 результатов без учёта памяти (начальная позиция Mega ≈ 188 МБ) | Исправлено: кэш очищается, когда в нём больше 20 млн совпадений | +| 9 | низкая | Малая база: у позиции нет ×, нет строки порядка ходов и «только этот порядок» | Частично: × добавлен; строка порядка — открыто | +| 10 | низкая | Не реализованы части проекта §7.1: кнопки пустого состояния, метка «дальше партий нет», частичный подсчёт продолжений, «Не из начальной позиции: N», «Не прочитаны: N» | Открыто | +| 11 | косметика | «183 партий» — нет форм множественного числа в русском | Открыто | +| 12 | косметика | Открытие главы книги: первое вхождение в обходе дерева, без предпочтения того же порядка ходов | Открыто | + +## Проверено тестировщиком + +- **Ядро против независимого оракула** (`load_game` → дерево chess-core, своя идентичность позиции по FEN): Mega, детерминированная выборка 250 000 записей, 32 позиции (начальная, 1.e4, Найдорф, переход в двух порядках, Нимцович-20, Испанская-40, взятие на проходе легальное и нет, глубокие, случайные, после превращений) — 0 расхождений, кроме 84 партий без единого хода (пропускаются, как задумано). Малые базы (2 PGN, 4 `.7z`, 4 `.cbv`), ≈ 1 900 позиций — единственный класс расхождений — дефект 3. +- **Эталоны Mega:** Найдорф 291 273 / 273 875 (79 мс), Нимцович-20 — 2 208 / 665 (20 мс), Испанская-40 — 406 / 325 (16 мс); продолжения + «закончились» = числу партий. Переход 1.Nf3…: 182 259 партий, тем же порядком 9 170. Отмена — `None` через 102 мс. `Collector` при параллельной сборке даёт тот же результат. +- **Регрессии:** fmt, clippy `-D warnings`, `cargo test --workspace` (133 + 3 ignored), ignored-тесты по Mega — все проходят; «Carlsen, Magnus» = 7 857; Carlsen + Найдорф = 183 / 173. +- **UI по скриншотам:** строка «этим порядком ходов», сортировка «сильнейшие сверху», значки ↪ и 🔀, полоса Б/Н/Ч, «Закончились здесь», пустое состояние, свёрнутая полка при высоте 700. +- **Производительность** (поиск + сортировка): вся Mega — начальная 0,9 с, 1.e4 0,59 с, Найдорф 94 мс, глубже 17–40 мс; выборка «Карлсен» — 1–5 мс; с фильтром +45 мс на запрос кандидатов. Память: Mega с доской 1,0–1,1 ГБ, в начальной позиции 1,75 ГБ; малая база ≈ 0,42 ГБ. +- **Сохранность:** SHA-256, размер и mtime всех файлов `pgnFilesforExample/` до и после совпадают. + +## Не проверено + +Ввод мышью и с клавиатуры в живом окне (ходы, ←/→/Home/End/Backspace/цифры/F, «Вернуть», фокус между таблицей, полями и доской); Ctrl+W и возврат к позиции; «Найти в базе» из партии; «Открыть как новую партию»; копирование; звук; доска из FEN-партии; рост памяти за длинную сессию; X11, другие масштабы, холодный диск.