diff --git a/crates/trainer/src/repertoire/advanced_tests.rs b/crates/trainer/src/repertoire/advanced_tests.rs index 83c58ab..cdc0c40 100644 --- a/crates/trainer/src/repertoire/advanced_tests.rs +++ b/crates/trainer/src/repertoire/advanced_tests.rs @@ -1,4 +1,3 @@ -use chess_core::shakmaty::{Color, Position}; use chess_core::{Game, NodeId}; use super::*; @@ -11,721 +10,6 @@ fn repertoire(pgn: &str) -> Repertoire { library.repertoire(&id).unwrap().clone() } -fn repertoire_from_lines(lines: &[&str]) -> Repertoire { - let mut game = Game::new(); - for line in lines { - game.add_uci_line(NodeId::ROOT, &[*line]).unwrap(); - } - let mut library = Library::default(); - let id = library.create("Many", &game).unwrap(); - library.repertoire(&id).unwrap().clone() -} - -fn strings(moves: &[&str]) -> Vec { - moves.iter().map(|mv| (*mv).to_owned()).collect() -} - -fn random_session(rep: &Repertoire, mode: TrainingMode, seed: u64) -> TrainingSession { - TrainingSession::scoped_random_with_seed( - rep, - TrainingScope::whole(), - mode, - StatsData::default(), - 0, - seed, - ) - .unwrap() -} - -fn random_route(session: &TrainingSession) -> Vec { - let mut route = session.scope().parent_prefix().to_vec(); - route.extend(session.suggested_path().unwrap().iter().cloned()); - route -} - -fn path_key(rep: &Repertoire, scope: &TrainingScope, path: &[String]) -> PathKey { - PathKey { - repertoire_id: rep.id.clone(), - scope: scope.key(), - path: path.to_vec(), - } -} - -#[test] -fn scope_starts_at_black_move_with_context_and_stops_at_early_boundary() { - let rep = repertoire("1. e4 e5 2. Nf3 Nc6 (2... Nf6) 3. Bb5 a6 4. Ba4 Nf6 *"); - let prefix = strings(&["e2e4", "e7e5", "g1f3", "b8c6"]); - let end = strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6"]); - let scope = TrainingScope::between(prefix, end); - let mut session = TrainingSession::scoped( - &rep, - scope.clone(), - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - - assert_eq!(session.position().turn(), Color::Black); - assert_eq!( - session - .path() - .iter() - .map(|mv| mv.uci.as_str()) - .collect::>(), - ["e2e4", "e7e5", "g1f3"] - ); - assert!(session.path().iter().all(|mv| mv.automatic)); - assert!(session.attempts().is_empty()); - assert_eq!( - session - .candidates() - .iter() - .map(|c| c.uci.as_str()) - .collect::>(), - ["b8c6"] - ); - - assert_eq!(session.play_uci("g8f6", 1).unwrap(), TrainingVerdict::Wrong); - assert_eq!(session.play_uci("b8c6", 2).unwrap(), TrainingVerdict::Right); - assert_eq!(session.play_uci("f1b5", 3).unwrap(), TrainingVerdict::Right); - assert_eq!( - session.play_uci("a7a6", 4).unwrap(), - TrainingVerdict::Finished - ); - assert!(session.is_done()); - let actual = strings(&["b8c6", "f1b5", "a7a6"]); - let stats = session - .stats() - .path_stats(&path_key(&rep, &scope, &actual)) - .unwrap(); - assert_eq!(stats.completions, 1); - assert_eq!(stats.mistakes, 1); - assert_eq!(stats.recent[0].path, actual); - assert_eq!(stats.recent[0].scope, scope.key()); - assert_eq!(stats.recent[0].automatic_moves, 3); - - let mut without_context = TrainingSession::scoped( - &rep, - scope.with_context(false), - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 10, - ) - .unwrap(); - assert!(without_context.path().is_empty()); - assert_eq!(without_context.position().turn(), Color::Black); - assert_eq!( - without_context.play_uci("b8c6", 10).unwrap(), - TrainingVerdict::Right - ); -} - -#[test] -fn scope_honours_disabled_depth_and_selected_move_as_its_only_early_end() { - let mut rep = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 (3. Bc4) a6 4. Ba4 *"); - rep.set_prefix_disabled(&strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5"]), true) - .unwrap(); - let scope = TrainingScope::from_prefix(strings(&["e2e4", "e7e5", "g1f3", "b8c6"])); - let mut session = TrainingSession::scoped( - &rep, - scope.clone(), - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - session.play_uci("b8c6", 1).unwrap(); - assert_eq!(session.play_uci("f1b5", 2).unwrap(), TrainingVerdict::Wrong); - assert_eq!( - session.play_uci("f1c4", 3).unwrap(), - TrainingVerdict::Finished - ); - - rep.set_max_plies(4); - let mut depth = TrainingSession::scoped( - &rep, - scope.clone(), - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 10, - ) - .unwrap(); - assert_eq!( - depth.play_uci("b8c6", 10).unwrap(), - TrainingVerdict::Finished - ); - - let only = TrainingScope::between(scope.prefix.clone(), scope.prefix.clone()); - let mut one_move = TrainingSession::scoped( - &rep, - only, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 20, - ) - .unwrap(); - assert_eq!( - one_move.play_uci("b8c6", 20).unwrap(), - TrainingVerdict::Finished - ); -} - -#[test] -fn scoped_one_side_black_targets_use_context_but_never_count_it() { - let rep = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); - let scope = TrainingScope::from_prefix(strings(&["e2e4", "e7e5", "g1f3", "b8c6"])); - let mut session = TrainingSession::scoped( - &rep, - scope, - TrainingMode::Black, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.target().unwrap().expected_uci, "b8c6"); - assert_eq!(session.path().len(), 3); - assert!(session.path().iter().all(|mv| mv.automatic)); - assert!(session.attempts().is_empty()); - assert_eq!(session.play_uci("b8c6", 1).unwrap(), TrainingVerdict::Right); - assert!( - session - .path() - .iter() - .any(|mv| mv.uci == "f1b5" && mv.automatic) - ); - assert_eq!(session.attempts().len(), 1); - assert_eq!( - session.play_uci("a7a6", 2).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.attempts().len(), 2); - assert!(session.path().iter().filter(|mv| mv.automatic).count() >= 2); - - let mut no_context = TrainingSession::scoped( - &rep, - TrainingScope::from_prefix(strings(&["e2e4", "e7e5", "g1f3", "b8c6"])).with_context(false), - TrainingMode::Black, - QueueMode::ReviewInOrder, - StatsData::default(), - 10, - ) - .unwrap(); - assert!(no_context.path().is_empty()); - assert_eq!(no_context.target().unwrap().expected_uci, "b8c6"); - assert_eq!( - no_context.play_uci("b8c6", 10).unwrap(), - TrainingVerdict::Right - ); - assert_eq!(no_context.attempts().len(), 1); -} - -#[test] -fn scoped_transpositions_do_not_import_continuations_from_outside_scope() { - let mut library = Library::default(); - let id = library.create_empty("Transpositions").unwrap(); - library - .add_game( - &id, - &chess_core::parse_str("1. d4 d5 2. Nf3 Nf6 3. g3 *").game, - ) - .unwrap(); - library - .add_game(&id, &chess_core::parse_str("1. Nf3 d5 2. d4 Nf6 *").game) - .unwrap(); - let rep = library.repertoire(&id).unwrap().clone(); - let scope = TrainingScope::from_prefix(strings(&["g1f3"])); - let mut session = TrainingSession::scoped( - &rep, - scope, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.play_uci("g1f3", 1).unwrap(), TrainingVerdict::Right); - assert_eq!(session.play_uci("d7d5", 2).unwrap(), TrainingVerdict::Right); - assert_eq!(session.play_uci("d2d4", 3).unwrap(), TrainingVerdict::Right); - assert_eq!( - session.play_uci("g8f6", 4).unwrap(), - TrainingVerdict::Finished - ); - assert!(session.candidates().is_empty()); - - let mut whole = TrainingSession::scoped( - &rep, - TrainingScope::whole(), - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 10, - ) - .unwrap(); - for (now, mv) in ["g1f3", "d7d5", "d2d4", "g8f6", "g2g3"] - .into_iter() - .enumerate() - { - whole.play_uci(mv, 10 + now as i64).unwrap(); - } - assert!(whole.is_done()); -} - -#[test] -fn both_review_queue_advances_proposals_but_repeat_keeps_the_same_route() { - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 (2. c4) *"); - let main = strings(&["e2e4", "e7e5", "g1f3"]); - let second = strings(&["e2e4", "e7e5", "c2c4"]); - let deviation = strings(&["e2e4", "c7c5"]); - let scope = TrainingScope::whole(); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.suggested_path().unwrap(), main); - session.play_uci("e2e4", 1).unwrap(); - assert_eq!( - session.play_uci("c7c5", 2).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!( - session - .stats() - .path_stats(&path_key(&rep, &scope, &deviation)) - .unwrap() - .completions, - 1 - ); - assert!( - session - .stats() - .path_stats(&path_key(&rep, &scope, &main)) - .is_none() - ); - - session.next_path(3).unwrap(); - assert_eq!(session.suggested_path().unwrap(), second); - session.restart(4).unwrap(); - assert_eq!(session.suggested_path().unwrap(), second); -} - -#[test] -fn path_history_records_hints_mistakes_and_last_seen() { - let rep = repertoire("1. e4 e5 *"); - let scope = TrainingScope::whole(); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for now in 1..=3 { - session.play_uci("d2d4", now).unwrap(); - } - session.hint(4).unwrap(); - session.play_uci("e2e4", 5).unwrap(); - session.play_uci("e7e5", 6).unwrap(); - let path = strings(&["e2e4", "e7e5"]); - let stats = session - .stats() - .path_stats(&path_key(&rep, &scope, &path)) - .unwrap(); - assert_eq!(stats.completions, 1); - assert_eq!(stats.mistakes, 3); - assert_eq!(stats.hints, 1); - assert_eq!(stats.last_seen, Some(6)); - assert!(stats.recent[0].hinted); -} - -#[test] -fn both_least_recent_uses_completions_then_oldest_actual_path() { - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 (2. c4) *"); - let paths = [ - strings(&["e2e4", "e7e5", "g1f3"]), - strings(&["e2e4", "e7e5", "c2c4"]), - strings(&["e2e4", "c7c5"]), - ]; - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::LeastRecent, - StatsData::default(), - 0, - ) - .unwrap(); - for (index, expected) in paths.iter().enumerate() { - assert_eq!(session.suggested_path().unwrap(), expected); - for (ply, mv) in expected.iter().enumerate() { - session.play_uci(mv, (index * 10 + ply) as i64).unwrap(); - } - assert!(session.is_done()); - session.next_path((index * 10 + 8) as i64).unwrap(); - } - assert_eq!(session.suggested_path().unwrap(), paths[0]); -} - -#[test] -fn repeated_position_is_a_terminal_path_not_a_hang() { - let rep = repertoire("1. Nf3 Nf6 2. Ng1 Ng8 3. Nf3 Nf6 4. Ng1 Ng8 *"); - let scope = TrainingScope::whole(); - let paths = RepertoireTree::new(&rep).training_paths(&scope).unwrap(); - assert_eq!(paths.len(), 1); - assert_eq!(paths[0].moves, strings(&["g1f3", "g8f6", "f3g1", "f6g8"])); - - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for (now, mv) in ["g1f3", "g8f6", "f3g1", "f6g8"].into_iter().enumerate() { - session.play_uci(mv, now as i64).unwrap(); - } - assert!(session.is_done()); - let stats = session - .stats() - .path_stats(&path_key(&rep, &scope, &paths[0].moves)) - .unwrap(); - assert_eq!(stats.completions, 1); -} - -#[test] -fn introduction_is_explicit_batches_of_ten_then_unscheduled() { - let rep = repertoire_from_lines(&[ - "e2e4", "d2d4", "c2c4", "g1f3", "g2g3", "b2b3", "b1c3", "e2e3", "d2d3", "c2c3", "f2f4", - "a2a3", - ]); - let mut first = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - let mut played = 0; - while !first.is_done() { - let target = first.target().unwrap().expected_uci.clone(); - first.play_uci(&target, played as i64).unwrap(); - played += 1; - } - assert_eq!(played, INTRODUCTION_BATCH_SIZE); - assert_eq!(first.stats().move_stats.len(), INTRODUCTION_BATCH_SIZE); - - first.restart_with_policy(20, SrsPolicy::Introduce).unwrap(); - let mut remaining = 0; - while !first.is_done() { - let target = first.target().unwrap().expected_uci.clone(); - first.play_uci(&target, 20 + remaining).unwrap(); - remaining += 1; - } - assert_eq!(remaining, 2); - assert_eq!(first.stats().move_stats.len(), 12); - - first.restart_with_policy(30, SrsPolicy::Introduce).unwrap(); - assert!(first.is_done()); -} - -#[test] -fn introduction_takes_unseen_before_previously_reviewed_unscheduled() { - let rep = repertoire_from_lines(&["e2e4", "d2d4"]); - let mut review = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - review.play_uci("e2e4", 10).unwrap(); - assert!(review.stats().move_stats[0].due.is_none()); - - let mut introduction = TrainingSession::new_srs( - &rep, - TrainingMode::White, - review.into_stats(), - 20, - SrsPolicy::Introduce, - ) - .unwrap(); - assert_eq!(introduction.target().unwrap().expected_uci, "d2d4"); - introduction.play_uci("d2d4", 21).unwrap(); - assert_eq!(introduction.target().unwrap().expected_uci, "e2e4"); - introduction.play_uci("e2e4", 22).unwrap(); - assert!(introduction.is_done()); - assert!( - introduction - .stats() - .move_stats - .iter() - .all(|stats| stats.due.is_some()) - ); -} - -#[test] -fn due_policy_does_not_fall_through_to_unseen_and_early_review_preserves_due() { - let rep = repertoire_from_lines(&["e2e4", "d2d4"]); - let mut initial = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - initial.play_uci("e2e4", 100).unwrap(); - initial.restart_with_policy(200, SrsPolicy::Due).unwrap(); - assert!(initial.is_done()); - assert_eq!(initial.stats().move_stats.len(), 1); - - initial - .restart_with_policy(200, SrsPolicy::Introduce) - .unwrap(); - assert_eq!(initial.target().unwrap().expected_uci, "d2d4"); - initial.play_uci("d2d4", 201).unwrap(); - let original_due: Vec> = initial - .stats() - .move_stats - .iter() - .map(|stats| stats.due) - .collect(); - - initial - .restart_with_policy(300, SrsPolicy::EarlyReview) - .unwrap(); - assert_eq!(initial.srs_policy(), SrsPolicy::EarlyReview); - let target = initial.target().unwrap().expected_uci.clone(); - let key = MoveKey { - repertoire_id: rep.id.clone(), - mode: TrainingMode::White, - position_fen4: initial.target().unwrap().position_fen4.clone(), - expected_uci: target.clone(), - }; - let before_attempts = initial.stats().get(&key).unwrap().attempts; - assert_eq!( - initial.play_uci("h2h3", 301).unwrap(), - TrainingVerdict::Wrong - ); - initial.play_uci(&target, 302).unwrap(); - let stats = initial.stats().get(&key).unwrap(); - assert_eq!(stats.attempts, before_attempts + 2); - assert_eq!(stats.last_seen, Some(302)); - let after_due: Vec> = initial - .stats() - .move_stats - .iter() - .map(|stats| stats.due) - .collect(); - assert_eq!(after_due, original_due); -} - -#[test] -fn path_history_and_scope_cursor_survive_stats_store_roundtrip() { - let dir = std::env::temp_dir().join(format!("cp-path-store-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let store = StatsStore::new(dir.join("stats.json")); - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - store.load().unwrap(), - 0, - ) - .unwrap(); - let completed = session.suggested_path().unwrap().to_vec(); - for (now, mv) in completed.clone().into_iter().enumerate() { - session.play_uci(&mv, now as i64).unwrap(); - } - store.save(session.stats_mut()).unwrap(); - - let loaded = store.load().unwrap(); - assert_eq!( - loaded - .path_stats(&path_key(&rep, &TrainingScope::whole(), &completed)) - .unwrap() - .completions, - 1 - ); - let next = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - loaded, - 10, - ) - .unwrap(); - assert_ne!(next.suggested_path().unwrap(), completed); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn default_srs_never_introduces_new_targets_or_records_empty_completion() { - let rep = repertoire("1. e4 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::SpacedRepetition, - StatsData::default(), - 0, - ) - .unwrap(); - assert!(session.is_done()); - assert_eq!(session.srs_policy(), SrsPolicy::Due); - assert!(session.stats().runs.is_empty()); - session.restart(1).unwrap(); - assert!(session.is_done()); - assert!(session.stats().move_stats.is_empty()); -} - -#[test] -fn repeated_hint_requests_do_not_inflate_hint_statistics() { - let rep = repertoire("1. e4 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for now in 1..=3 { - session.play_uci("d2d4", now).unwrap(); - } - assert!(session.hint(4).is_some()); - assert!(session.hint(5).is_some()); - session.play_uci("e2e4", 6).unwrap(); - let stats = &session.stats().move_stats[0]; - assert!(stats.key.expected_uci.is_empty()); - assert_eq!((stats.attempts, stats.hints, stats.wrong), (4, 1, 3)); - assert!(session.attempts().iter().all(|a| a.expected_uci.is_empty())); -} - -#[test] -fn transposition_continuation_preserves_actual_depth_and_position_counters() { - let mut library = Library::default(); - let id = library.create_empty("Depth").unwrap(); - for line in [ - "1. d4 d5 2. Nf3 Nf6 3. g3 g6 4. Bg2 *", - "1. Nh3 Nh6 2. Ng5 Ng4 3. Nf3 Nf6 4. d4 d5 *", - ] { - library - .add_game(&id, &chess_core::parse_str(line).game) - .unwrap(); - } - let rep = library.repertoire_mut(&id).unwrap(); - rep.set_max_plies(9); - let paths = RepertoireTree::new(rep) - .training_paths(&TrainingScope::whole()) - .unwrap(); - assert!(paths.iter().all(|path| path.moves.len() <= 9)); - let mut session = TrainingSession::new( - rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for (i, mv) in [ - "g1h3", "g8h6", "h3g5", "h6g4", "g5f3", "g4f6", "d2d4", "d7d5", - ] - .iter() - .enumerate() - { - assert_eq!( - session.play_uci(mv, i as i64).unwrap(), - TrainingVerdict::Right - ); - } - assert_eq!( - session.play_uci("g2g3", 9).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.position().fullmoves().get(), 5); - assert_eq!(session.path().len(), 9); - assert!(session.candidates().is_empty()); -} - -#[test] -fn scoped_target_context_cannot_be_borrowed_from_an_outside_transposition() { - let mut library = Library::default(); - let id = library.create_empty("Scope").unwrap(); - for pgn in ["1. d4 d5 2. Nf3 Nf6 *", "1. Nf3 d5 2. d4 Nf6 3. g3 *"] { - library - .add_game(&id, &chess_core::parse_str(pgn).game) - .unwrap(); - } - let rep = library.repertoire(&id).unwrap(); - let scope = TrainingScope::from_prefix(strings(&["g1f3"])); - let targets = RepertoireTree::new(rep).scoped_targets(Color::White, &scope); - assert!( - targets - .iter() - .all(|t| t.path.is_empty() || t.path[0] == "g1f3") - ); -} - -#[test] -fn early_review_preserves_the_next_scheduled_interval() { - let rep = repertoire("1. e4 *"); - let mut stats = StatsData::default(); - let mut due = 0; - for interval in [INITIAL_INTERVAL_SECONDS, 2 * INITIAL_INTERVAL_SECONDS] { - let policy = if due == 0 { - SrsPolicy::Introduce - } else { - SrsPolicy::Due - }; - let mut session = - TrainingSession::new_srs(&rep, TrainingMode::White, stats, due, policy).unwrap(); - session.play_uci("e2e4", due).unwrap(); - due += interval; - stats = session.into_stats(); - } - let mut review = TrainingSession::new_srs( - &rep, - TrainingMode::White, - stats, - due - 100, - SrsPolicy::EarlyReview, - ) - .unwrap(); - review.play_uci("e2e4", due - 100).unwrap(); - assert_eq!( - review.stats().move_stats[0].interval_seconds, - Some(2 * INITIAL_INTERVAL_SECONDS) - ); - let mut next = TrainingSession::new_srs( - &rep, - TrainingMode::White, - review.into_stats(), - due, - SrsPolicy::Due, - ) - .unwrap(); - next.play_uci("e2e4", due).unwrap(); - assert_eq!( - next.stats().move_stats[0].due, - Some(due + 4 * INITIAL_INTERVAL_SECONDS) - ); -} - #[test] fn simultaneous_writers_cannot_overwrite_the_same_revision() { let path = std::env::temp_dir().join(format!("cp-trainer-race-{}.json", std::process::id())); @@ -798,207 +82,6 @@ fn previous_both_move_keys_migrate_to_position_statistics_without_data_loss() { std::fs::remove_file(path).unwrap(); } -#[test] -fn removing_repertoire_cleans_all_modern_statistics_and_cursors_but_keeps_others() { - let first = repertoire("1. e4 (1. d4) *"); - let second = repertoire("1. Nf3 (1. c4) *"); - let mut data = StatsData::default(); - data.legacy_lines - .insert("original".into(), serde_json::json!({"runs": 3})); - for rep in [&first, &second] { - for mode in [TrainingMode::White, TrainingMode::Both] { - let mut session = - TrainingSession::new(rep, mode, QueueMode::ReviewInOrder, data, 0).unwrap(); - while !session.is_done() { - let mv = session - .target() - .map(|t| t.expected_uci.clone()) - .unwrap_or_else(|| session.candidates()[0].uci.clone()); - session.play_uci(&mv, 1).unwrap(); - } - data = session.into_stats(); - } - } - let before = serde_json::to_value(&data).unwrap(); - for field in [ - "move_stats", - "runs", - "path_stats", - "review_cursors", - "path_review_cursors", - ] { - assert!( - before[field].as_array().unwrap().iter().any(|entry| { - entry - .get("repertoire_id") - .or_else(|| entry.get("key").and_then(|key| key.get("repertoire_id"))) - == Some(&serde_json::json!(first.id)) - }), - "missing fixture for {field}" - ); - } - data.remove_repertoire(&first.id); - let after = serde_json::to_value(&data).unwrap(); - for field in [ - "move_stats", - "runs", - "path_stats", - "review_cursors", - "path_review_cursors", - ] { - let expected: Vec<_> = before[field] - .as_array() - .unwrap() - .iter() - .filter(|entry| { - entry - .get("repertoire_id") - .or_else(|| entry.get("key").and_then(|key| key.get("repertoire_id"))) - == Some(&serde_json::json!(second.id)) - }) - .cloned() - .collect(); - assert_eq!( - after[field], - serde_json::json!(expected), - "incorrect cleanup of {field}" - ); - } - assert_eq!(after["legacy_lines"], before["legacy_lines"]); - data.remove_repertoire(&first.id); - assert_eq!(serde_json::to_value(&data).unwrap(), after); -} - -#[test] -fn resetting_one_mode_preserves_other_modes_and_repertoires() { - let first = repertoire("1. e4 (1. d4) *"); - let second = repertoire("1. Nf3 (1. c4) *"); - let mut data = StatsData::default(); - data.legacy_lines - .insert("original".into(), serde_json::json!({"runs": 3})); - for (rep, mode) in [ - (&first, TrainingMode::White), - (&first, TrainingMode::Both), - (&second, TrainingMode::White), - ] { - let mut session = TrainingSession::new_random(rep, mode, data, 0).unwrap(); - while !session.is_done() { - let mv = session.candidates()[0].uci.clone(); - session.play_uci(&mv, 1).unwrap(); - } - data = session.into_stats(); - } - - data.remove_repertoire_mode(&first.id, TrainingMode::White); - - assert!(data.runs(&first.id, TrainingMode::White).is_none()); - assert!(data.runs(&first.id, TrainingMode::Both).is_some()); - assert!(data.runs(&second.id, TrainingMode::White).is_some()); - assert!( - data.move_stats - .iter() - .all(|entry| entry.key.repertoire_id != first.id - || entry.key.mode != TrainingMode::White) - ); - assert!( - data.move_stats.iter().any( - |entry| entry.key.repertoire_id == first.id && entry.key.mode == TrainingMode::Both - ) - ); - assert!( - data.path_stats - .iter() - .any(|entry| entry.key.repertoire_id == first.id) - ); - let after = serde_json::to_value(&data).unwrap(); - let cursors = after["random_practice_cursors"].as_array().unwrap(); - assert!(cursors.iter().all( - |entry| entry["repertoire_id"] != serde_json::json!(first.id) - || entry["mode"] != serde_json::json!("White") - )); - assert!(cursors.iter().any( - |entry| entry["repertoire_id"] == serde_json::json!(first.id) - && entry["mode"] == serde_json::json!("Both") - )); - assert_eq!( - after["legacy_lines"], - serde_json::json!({"original": {"runs": 3}}) - ); -} - -#[test] -fn streaming_paths_stop_early_and_match_full_queue_across_wraps_and_history() { - use std::ops::ControlFlow; - let rep = repertoire( - "1. d4 d5 2. Nf3 Nf6 (2... Nc6) (1... Nf6 2. Nf3 d5 3. c4) (1. Nf3 d5 2. d4 Nf6 3. c4) *", - ); - let tree = RepertoireTree::new(&rep); - let scopes = [ - TrainingScope::whole(), - TrainingScope::from_prefix(strings(&["d2d4"])), - ]; - for scope in scopes { - let paths = tree.training_paths(&scope).unwrap(); - assert!(!paths.is_empty()); - assert_eq!(tree.training_path_count(&scope).unwrap(), paths.len()); - let mut visited = 0; - tree.visit_training_paths(&scope, |moves| { - visited += 1; - assert_eq!(moves, paths[0].moves); - ControlFlow::Break(()) - }) - .unwrap(); - assert_eq!(visited, 1); - let mut stats = StatsData::default(); - for step in 0..paths.len() * 3 { - for mode in [ - QueueMode::ReviewInOrder, - QueueMode::LeastRecent, - QueueMode::SpacedRepetition, - ] { - let full = stats.path_queue(&tree, &rep.id, &scope, mode).unwrap(); - assert_eq!( - stats - .next_training_path(&tree, &rep.id, &scope, mode) - .unwrap(), - full.first().cloned() - ); - } - let path = &paths[step % paths.len()]; - stats.record_path_run( - path_key(&rep, &scope, &path.moves), - RunRecord { - at: step as i64, - mistakes: 0, - hints: 0, - hinted: false, - path: path.moves.clone(), - user_attempts: path.moves.len() as u32, - automatic_moves: 0, - scope: scope.key(), - }, - ); - stats.path_presented(&rep.id, &scope, QueueMode::ReviewInOrder); - } - } - let empty = RepertoireTree::new(&repertoire("*")); - assert_eq!( - empty.training_path_count(&TrainingScope::whole()).unwrap(), - 0 - ); - assert_eq!( - StatsData::default() - .next_training_path( - &empty, - &rep.id, - &TrainingScope::whole(), - QueueMode::ReviewInOrder - ) - .unwrap(), - None - ); -} - #[test] fn null_subtree_grafts_under_the_exact_path_instead_of_an_earlier_transposition() { let base = chess_core::parse_str("1. d4 (1. Nf3 d5 2. d4) d5 2. Nf3 *").game; @@ -1057,613 +140,3 @@ fn null_subtree_grafts_under_the_exact_path_instead_of_an_earlier_transposition( canonical ); } - -#[test] -fn practice_follows_the_users_branch_without_hidden_targets_or_automatic_attempts() { - let rep = repertoire("1. e4 (1. d4 d5 2. c4) e5 2. Nf3 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert!(session.target().is_none()); - assert!(session.may_hint()); - assert_eq!(session.play_uci("d2d4", 1).unwrap(), TrainingVerdict::Right); - assert_eq!( - session - .path() - .iter() - .map(|m| m.uci.as_str()) - .collect::>(), - vec!["d2d4", "d7d5"] - ); - assert_eq!(session.attempts().len(), 1); - assert_eq!( - session.play_uci("c2c4", 2).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.play_uci("a2a3", 3).unwrap(), TrainingVerdict::Done); - let stats = session.stats(); - assert_eq!(stats.move_stats.len(), 2); - assert!( - stats - .move_stats - .iter() - .all(|m| m.correct == 1 && m.due.is_none()) - ); - assert_eq!( - stats - .runs(&rep.id, TrainingMode::White) - .unwrap() - .completions, - 1 - ); -} - -#[test] -fn practice_black_starts_with_an_automatic_white_move_and_rotates_opponent_branches() { - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.play_uci("e2e4", 1).unwrap(), TrainingVerdict::Right); - assert_eq!(session.path()[1].uci, "e7e5"); - session.next_path(2).unwrap(); - assert_eq!( - session.play_uci("e2e4", 3).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.path()[1].uci, "c7c5"); - session.restart(4).unwrap(); - session.play_uci("e2e4", 5).unwrap(); - assert_eq!(session.path()[1].uci, "c7c5"); - let saved = serde_json::to_vec(session.stats()).unwrap(); - let stats: StatsData = serde_json::from_slice(&saved).unwrap(); - let mut black = - TrainingSession::new(&rep, TrainingMode::Black, QueueMode::Practice, stats, 6).unwrap(); - assert_eq!(black.path()[0].uci, "e2e4"); - assert!(black.path()[0].automatic); - assert!(black.attempts().is_empty()); - assert_eq!( - black.play_uci("c7c5", 7).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(black.attempts().len(), 1); -} - -#[test] -fn practice_wrong_move_stays_put_and_hint_is_available_before_any_error() { - let rep = repertoire("1. e4 e5 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert!(session.hint(1).is_some()); - let position = session.position_key(); - assert_eq!(session.play_uci("d2d4", 2).unwrap(), TrainingVerdict::Wrong); - assert_eq!(session.position_key(), position); - assert_eq!(session.total_mistakes(), 1); - assert_eq!( - session.play_uci("e2e4", 3).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.stats().move_stats[0].hints, 1); - assert_eq!(session.stats().move_stats[0].wrong, 1); - assert_eq!(session.stats().move_stats[0].correct, 1); - assert!(session.stats().move_stats[0].due.is_none()); -} - -#[test] -fn practice_obeys_depth_disabled_repetition_and_both_never_answers_automatically() { - let mut rep = repertoire("1. Nf3 (1. d4 d5) Nf6 2. Ng1 Ng8 3. e4 *"); - rep.set_prefix_disabled(&strings(&["d2d4"]), true).unwrap(); - let mut both = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(both.play_uci("d2d4", 1).unwrap(), TrainingVerdict::Wrong); - for uci in ["g1f3", "g8f6", "f3g1"] { - assert_eq!(both.play_uci(uci, 2).unwrap(), TrainingVerdict::Right); - } - assert_eq!(both.play_uci("f6g8", 3).unwrap(), TrainingVerdict::Finished); - assert!(both.path().iter().all(|m| !m.automatic)); - assert_eq!(both.path().len(), 4); - rep.max_plies = 1; - let mut white = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::Practice, - StatsData::default(), - 4, - ) - .unwrap(); - assert_eq!( - white.play_uci("g1f3", 5).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(white.path().len(), 1); -} - -#[test] -fn scheduled_alternative_is_credited_only_to_actual_move_and_hidden_target_stays_unseen() { - let rep = repertoire("1. e4 (1. d4) *"); - let mut session = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - assert_eq!(session.target().unwrap().expected_uci, "e2e4"); - assert_eq!( - session.play_uci("d2d4", 1).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.total_mistakes(), 0); - assert_eq!(session.stats().move_stats.len(), 1); - assert_eq!(session.stats().move_stats[0].key.expected_uci, "d2d4"); - assert_eq!(session.stats().move_stats[0].correct, 1); - let next = TrainingSession::new_srs( - &rep, - TrainingMode::White, - session.into_stats(), - 2, - SrsPolicy::Introduce, - ) - .unwrap(); - assert_eq!(next.target().unwrap().expected_uci, "e2e4"); -} - -#[test] -fn practice_preserves_existing_srs_due_and_interval() { - let rep = repertoire("1. e4 *"); - let mut srs = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - srs.play_uci("e2e4", 1).unwrap(); - let due = srs.stats().move_stats[0].due; - let interval = srs.stats().move_stats[0].interval_seconds; - let mut practice = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::Practice, - srs.into_stats(), - 2, - ) - .unwrap(); - practice.play_uci("e2e4", 3).unwrap(); - assert_eq!(practice.stats().move_stats[0].due, due); - assert_eq!(practice.stats().move_stats[0].interval_seconds, interval); -} - -#[test] -fn practice_scope_replay_origin_precedes_automatic_moves_and_preserves_counters() { - let rep = repertoire( - "[SetUp \"1\"]\n[FEN \"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 7 42\"]\n\n42. e4 e5 *", - ); - let session = TrainingSession::scoped( - &rep, - TrainingScope::whole().with_context(false), - TrainingMode::Black, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.scope_start_position().turn(), Color::White); - assert_eq!(session.position().turn(), Color::Black); - assert_eq!(session.path().len(), 1); - assert_eq!(session.scope_start_position().fullmoves().get(), 42); - assert_eq!(session.scope_start_position().halfmoves(), 7); -} - -#[test] -fn practice_next_branch_hint_follows_proposal_and_both_path_completion_is_once() { - let rep = repertoire("1. e4 (1. d4 d5) e5 (1... c5) *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.hint(1).unwrap().uci, "e2e4"); - session.next_path(2).unwrap(); - assert_eq!(session.hint(3).unwrap().uci, "e2e4"); - session.next_path(4).unwrap(); - assert_eq!(session.hint(5).unwrap().uci, "d2d4"); - assert_eq!(session.play_uci("d2d4", 6).unwrap(), TrainingVerdict::Right); - assert_eq!(session.hint(7).unwrap().uci, "d7d5"); - assert_eq!( - session.play_uci("d7d5", 8).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.play_uci("c2c4", 9).unwrap(), TrainingVerdict::Done); - let paths = &session.stats().path_stats; - assert_eq!(paths.len(), 1); - assert_eq!(paths[0].key.path, strings(&["d2d4", "d7d5"])); - assert_eq!(paths[0].completions, 1); - assert_eq!( - session - .stats() - .runs(&rep.id, TrainingMode::Both) - .unwrap() - .completions, - 1 - ); - session.next_path(10).unwrap(); - assert_eq!(session.hint(11).unwrap().uci, "e2e4"); - // Deviating to another valid branch makes the hint follow that actual branch. - session.play_uci("d2d4", 12).unwrap(); - assert_eq!(session.hint(13).unwrap().uci, "d7d5"); -} - -#[test] -fn source_paths_and_random_cycle_do_not_multiply_transpositions() { - let mut rep = repertoire( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O (7... d6 8. c3 O-O 9. h3 Nb8 (9... Bb7 10. d4 Re8 11. Nbd2 Bf8) (9... Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 cxd4) 10. d4 Nbd7) 8. c3 d6 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 Bd7 13. Nf1 *", - ); - rep.max_plies = u32::MAX; - let tree = RepertoireTree::new(&rep); - let source: std::collections::BTreeSet> = { - let mut paths = std::collections::BTreeSet::new(); - tree.visit_source_paths(&TrainingScope::whole(), |moves| { - paths.insert(moves.to_vec()); - std::ops::ControlFlow::Continue(()) - }) - .unwrap(); - paths - }; - assert_eq!(source.len(), 4); - assert!(tree.training_paths(&TrainingScope::whole()).unwrap().len() > source.len()); - - let mut session = random_session(&rep, TrainingMode::Both, 42); - for step in 0..source.len() { - let route = random_route(&session); - assert!( - source.contains(&route), - "route={route:?}\nsource={source:?}" - ); - if step + 1 < source.len() { - session.next_path(step as i64).unwrap(); - } - } - let saved = serde_json::to_value(session.stats()).unwrap(); - assert_eq!(saved["random_practice_cursors"][0]["count"], 4); -} - -#[test] -fn random_practice_is_deterministic_and_covers_every_route_before_a_new_cycle() { - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 (2. c4) *"); - let expected: std::collections::BTreeSet> = RepertoireTree::new(&rep) - .training_paths(&TrainingScope::whole()) - .unwrap() - .into_iter() - .map(|path| path.moves) - .collect(); - assert_eq!(expected.len(), 3); - let mut left = random_session(&rep, TrainingMode::Both, 42); - let mut right = random_session(&rep, TrainingMode::Both, 42); - let mut routes = Vec::new(); - for step in 0..6 { - assert_eq!(left.scope(), right.scope()); - assert_eq!(random_route(&left), random_route(&right)); - routes.push(random_route(&left)); - if step < 5 { - left.next_path(step).unwrap(); - right.next_path(step).unwrap(); - } - } - for cycle in routes.chunks(3) { - let actual: std::collections::BTreeSet> = cycle.iter().cloned().collect(); - assert_eq!(actual.len(), 3); - assert_eq!(actual, expected); - } -} - -#[test] -fn random_practice_mid_path_context_has_the_correct_side_for_every_mode() { - let rep = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 *"); - for mode in [TrainingMode::White, TrainingMode::Black, TrainingMode::Both] { - let mut session = None; - for seed in 0..64 { - let candidate = random_session(&rep, mode, seed); - if !candidate.path().is_empty() { - session = Some(candidate); - break; - } - } - let mut session = session.expect("a deterministic mid-path start"); - let start = session.path().len(); - assert!(start > 0); - assert!(session.path().iter().all(|played| played.automatic)); - assert!(session.attempts().is_empty()); - assert_eq!(session.scope().prefix.len(), start + 1); - assert_eq!( - session.scope().prefix.last().unwrap(), - &session.suggested_path().unwrap()[0] - ); - assert_eq!(random_route(&session).len(), 12); - assert!(session.suggested_path().unwrap().len() >= stats::MIN_RANDOM_CONTINUATION_PLIES); - assert_eq!( - session.position_key(), - session.path().last().unwrap().position_after - ); - if let Some(color) = mode.user_color() { - assert_eq!(session.position().turn(), color); - } - let target = session.suggested_path().unwrap()[0].clone(); - assert!(matches!( - session.play_uci(&target, 1).unwrap(), - TrainingVerdict::Right | TrainingVerdict::Finished - )); - assert!(!session.path()[start].automatic); - } -} - -#[test] -fn random_repeat_preserves_actual_route_start_and_the_next_cursor() { - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 (2. c4) Nc6 3. Bb5 a6 4. Ba4 Nf6 *"); - let mut session = (0..64) - .map(|seed| random_session(&rep, TrainingMode::Both, seed)) - .find(|session| !session.path().is_empty()) - .expect("a deterministic mid-path start"); - let initial_scope = session.scope().clone(); - let initial_context = session.path().to_vec(); - let selected = session.suggested_path().unwrap().to_vec(); - for (index, mv) in selected.iter().enumerate() { - session.play_uci(mv, index as i64).unwrap(); - } - assert!(session.is_done()); - let completed_path = session.path().to_vec(); - let completed_route = random_route(&session); - let before_repeat = serde_json::to_vec(session.stats()).unwrap(); - - session.restart(10).unwrap(); - assert_eq!(session.scope(), &initial_scope); - assert_eq!(session.path(), initial_context); - assert_eq!(serde_json::to_vec(session.stats()).unwrap(), before_repeat); - for (index, mv) in selected.iter().enumerate() { - session.play_uci(mv, 10 + index as i64).unwrap(); - } - assert_eq!(session.path(), completed_path); - - session.next_path(20).unwrap(); - let next = random_route(&session); - assert_ne!(next, completed_route); - assert!( - RepertoireTree::new(&rep) - .training_paths(&TrainingScope::whole()) - .unwrap() - .iter() - .any(|path| path.moves == next) - ); -} - -#[test] -fn random_practice_path_count_change_starts_a_fresh_complete_cycle() { - let rep = repertoire("1. e4 (1. d4 d5) e5 *"); - let mut initial = random_session(&rep, TrainingMode::Both, 7); - initial.next_path(1).unwrap(); - let before = serde_json::to_value(initial.stats()).unwrap(); - let old_seed = before["random_practice_cursors"][0]["seed"] - .as_u64() - .unwrap(); - let stats = initial.into_stats(); - let mut expanded = rep.clone(); - expanded.pgn = chess_core::parse_str("1. e4 (1. d4 d5) (1. c4 e5) (1. Nf3 Nf6) e5 (1... c5) *") - .game - .to_pgn(); - let mut session = TrainingSession::scoped_random_with_seed( - &expanded, - TrainingScope::whole(), - TrainingMode::Both, - stats, - 2, - 7, - ) - .unwrap(); - let after = serde_json::to_value(session.stats()).unwrap(); - assert_ne!( - after["random_practice_cursors"][0]["seed"] - .as_u64() - .unwrap(), - old_seed - ); - assert_eq!(after["random_practice_cursors"][0]["position"], 1); - assert_eq!(after["random_practice_cursors"][0]["count"], 5); - - let mut routes = vec![random_route(&session)]; - for now in 3..7 { - session.next_path(now).unwrap(); - routes.push(random_route(&session)); - } - let unique: std::collections::BTreeSet> = routes.into_iter().collect(); - assert_eq!(unique.len(), 5); -} - -#[test] -fn random_practice_reads_old_stats_without_the_random_cursor_field() { - let rep = repertoire("1. e4 e5 (1... c5) *"); - let mut old = serde_json::to_value(StatsData::default()).unwrap(); - assert!( - old.as_object_mut() - .unwrap() - .remove("random_practice_cursors") - .is_some() - ); - let stats: StatsData = serde_json::from_value(old).unwrap(); - let session = TrainingSession::scoped_random_with_seed( - &rep, - TrainingScope::whole(), - TrainingMode::Both, - stats, - 0, - 11, - ) - .unwrap(); - assert!(session.suggested_path().is_some()); - let saved = serde_json::to_value(session.stats()).unwrap(); - assert_eq!(saved["random_practice_cursors"][0]["position"], 1); -} - -#[test] -fn random_start_keeps_seven_plies_and_finishes_on_the_actual_last_move() { - let mut long = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 *"); - long.max_plies = 1; - for seed in 0..64 { - let session = random_session(&long, TrainingMode::Both, seed); - assert_eq!(random_route(&session).len(), 12); - assert!(session.suggested_path().unwrap().len() >= stats::MIN_RANDOM_CONTINUATION_PLIES); - } - - let short = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); - for seed in 0..64 { - let session = random_session(&short, TrainingMode::Both, seed); - assert!(session.path().is_empty()); - assert_eq!(session.suggested_path().unwrap().len(), 6); - } - - let mut session = random_session(&long, TrainingMode::Both, 42); - let selected = session.suggested_path().unwrap().to_vec(); - let automatic = session.path().len(); - for (index, mv) in selected.iter().enumerate() { - session.play_uci(mv, index as i64).unwrap(); - } - assert!(session.is_done()); - let record = session - .stats() - .runs(&long.id, TrainingMode::Both) - .unwrap() - .recent - .last() - .unwrap(); - assert_eq!(record.path, selected); - assert_eq!(record.automatic_moves, automatic as u32); - assert_eq!(record.user_attempts, selected.len() as u32); -} - -#[test] -fn random_scoped_start_never_escapes_the_base_end_or_creates_an_invalid_scope() { - let rep = repertoire("1. e4 e5 2. Nf3 Nc6 (2... Nf6) 3. Bb5 a6 *"); - let prefix = strings(&["e2e4", "e7e5", "g1f3"]); - let end = strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5"]); - let base = TrainingScope::between(prefix.clone(), end.clone()); - let mut saw_short = false; - let mut saw_end = false; - for seed in 0..64 { - let session = TrainingSession::scoped_random_with_seed( - &rep, - base.clone(), - TrainingMode::Both, - StatsData::default(), - 0, - seed, - ) - .unwrap(); - let route = random_route(&session); - assert!(route.starts_with(&prefix)); - assert!(route.len() <= end.len()); - assert_eq!(session.scope().end_prefix.as_ref(), Some(&route)); - saw_short |= route.len() < end.len(); - saw_end |= route == end; - } - assert!(saw_short && saw_end); -} - -#[test] -fn random_practice_pgn_fingerprint_change_restarts_the_cycle_at_the_same_count() { - let rep = repertoire("1. e4 (1. d4 d5) e5 *"); - let initial = random_session(&rep, TrainingMode::Both, 19); - let before = serde_json::to_value(initial.stats()).unwrap(); - let old_seed = before["random_practice_cursors"][0]["seed"] - .as_u64() - .unwrap(); - let old_fingerprint = before["random_practice_cursors"][0]["fingerprint"].clone(); - assert_eq!(before["random_practice_cursors"][0]["position"], 1); - assert_eq!(before["random_practice_cursors"][0]["count"], 2); - - let mut changed = rep.clone(); - changed.pgn = chess_core::parse_str("1. c4 (1. Nf3 Nf6) e5 *") - .game - .to_pgn(); - let mut session = TrainingSession::scoped_random_with_seed( - &changed, - TrainingScope::whole(), - TrainingMode::Both, - initial.into_stats(), - 1, - 19, - ) - .unwrap(); - let after = serde_json::to_value(session.stats()).unwrap(); - assert_eq!(after["random_practice_cursors"][0]["count"], 2); - assert_eq!(after["random_practice_cursors"][0]["position"], 1); - assert_ne!( - after["random_practice_cursors"][0]["seed"] - .as_u64() - .unwrap(), - old_seed - ); - assert_ne!( - after["random_practice_cursors"][0]["fingerprint"], - old_fingerprint - ); - let first = random_route(&session); - session.next_path(2).unwrap(); - assert_ne!(random_route(&session), first); -} - -#[test] -fn random_practice_cursor_without_fingerprint_safely_starts_a_new_cycle() { - let rep = repertoire("1. e4 (1. d4 d5) e5 *"); - let initial = random_session(&rep, TrainingMode::Both, 23); - let mut old = serde_json::to_value(initial.stats()).unwrap(); - let cursor = old["random_practice_cursors"][0].as_object_mut().unwrap(); - assert!(cursor.remove("fingerprint").is_some()); - let old_seed = cursor["seed"].as_u64().unwrap(); - assert_eq!(cursor["position"], 1); - let stats: StatsData = serde_json::from_value(old).unwrap(); - - let session = TrainingSession::scoped_random_with_seed( - &rep, - TrainingScope::whole(), - TrainingMode::Both, - stats, - 1, - 23, - ) - .unwrap(); - let after = serde_json::to_value(session.stats()).unwrap(); - assert!(after["random_practice_cursors"][0]["fingerprint"].is_number()); - assert_eq!(after["random_practice_cursors"][0]["position"], 1); - assert_ne!( - after["random_practice_cursors"][0]["seed"] - .as_u64() - .unwrap(), - old_seed - ); -} diff --git a/crates/trainer/src/repertoire/mod.rs b/crates/trainer/src/repertoire/mod.rs index 7c4bfaa..183f091 100644 --- a/crates/trainer/src/repertoire/mod.rs +++ b/crates/trainer/src/repertoire/mod.rs @@ -12,7 +12,6 @@ mod learning_session; mod line_analytics; mod model; mod scope; -mod session; mod srs; mod stats; mod store; @@ -51,10 +50,6 @@ pub use model::{ Repertoire, RepertoireError, RepertoireId, }; pub use scope::{TrainingScope, TrainingScopeKey}; -pub use session::{ - FirstMoveChooser, MoveChooser, PlayedMove, PreparedNextPath, SessionAttempt, SessionError, - TrainingSession, TrainingVerdict, -}; pub use srs::{ DEFAULT_GROWTH_FACTOR, FIRST_CORRECT_DELAY_SECONDS, MIN_PRACTICAL_INTERVAL_SECONDS, MISTAKE_DELAY_SECONDS, PREVIEW_DELAY_SECONDS, SRS_MAX_INTERVAL_SECONDS, SrsSettings, @@ -62,16 +57,15 @@ pub use srs::{ apply_independent_correct, apply_independent_wrong, apply_preview, }; pub use stats::{ - AttemptRecord, INITIAL_INTERVAL_SECONDS, INTRODUCTION_BATCH_SIZE, MAX_INTERVAL_SECONDS, - MISTAKE_INTERVAL_SECONDS, MoveKey, MoveStats, PathKey, PathStats, QueueMode, RunRecord, - RunStats, STATS_VERSION, SrsPolicy, StatsData, TrainingMode, + AttemptRecord, MoveKey, MoveStats, PathKey, PathStats, QueueMode, RunRecord, RunStats, + STATS_VERSION, StatsData, TrainingMode, }; pub use store::{ LEARNING_STORE_VERSION, LearningSession, LearningStore, LearningStoreData, LibraryStore, MigrationReport, PersistedAttempt, PersistedLearningReset, PersistedLearningSnapshot, PersistedSessionAttempt, StatsStore, StoreError, }; -pub use tree::{Candidate, RepertoireTree, TrainingPath, TrainingTarget, fen4}; +pub use tree::{Candidate, RepertoireTree, fen4}; #[cfg(test)] mod acceptance_tests; diff --git a/crates/trainer/src/repertoire/scope.rs b/crates/trainer/src/repertoire/scope.rs index 353505e..38e788d 100644 --- a/crates/trainer/src/repertoire/scope.rs +++ b/crates/trainer/src/repertoire/scope.rs @@ -16,33 +16,6 @@ impl TrainingScope { Self::default() } - pub fn from_prefix(prefix: Vec) -> Self { - Self { - prefix, - ..Self::default() - } - } - - pub fn between(prefix: Vec, end_prefix: Vec) -> Self { - Self { - prefix, - end_prefix: Some(end_prefix), - ..Self::default() - } - } - - pub fn with_context(mut self, include_context: bool) -> Self { - self.include_context = include_context; - self - } - - pub fn key(&self) -> TrainingScopeKey { - TrainingScopeKey { - prefix: self.prefix.clone(), - end_prefix: self.end_prefix.clone(), - } - } - pub(crate) fn parent_prefix(&self) -> &[String] { self.prefix .get(..self.prefix.len().saturating_sub(1)) diff --git a/crates/trainer/src/repertoire/session.rs b/crates/trainer/src/repertoire/session.rs deleted file mode 100644 index 490c5e0..0000000 --- a/crates/trainer/src/repertoire/session.rs +++ /dev/null @@ -1,1162 +0,0 @@ -use std::collections::BTreeSet; - -use chess_core::shakmaty::{CastlingMode, Chess, Move, Position, uci::UciMove}; -use chess_core::{Game, NodeId}; - -use super::model::{Repertoire, RepertoireId}; -use super::scope::TrainingScope; -use super::stats::{MoveKey, PathKey, QueueMode, RunRecord, SrsPolicy, StatsData, TrainingMode}; -use super::tree::{Candidate, RepertoireTree, TrainingPath, TrainingTarget, fen4}; - -pub trait MoveChooser: Send { - fn choose(&mut self, candidates: &[Candidate]) -> Option; -} - -#[derive(Clone, Copy, Debug, Default)] -pub struct FirstMoveChooser; - -impl MoveChooser for FirstMoveChooser { - fn choose(&mut self, candidates: &[Candidate]) -> Option { - (!candidates.is_empty()).then_some(0) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PlayedMove { - pub uci: String, - pub san: String, - pub automatic: bool, - pub position_before: String, - pub position_after: String, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct SessionAttempt { - pub position_fen4: String, - pub expected_uci: String, - pub actual_uci: String, - pub correct: bool, - pub hinted: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum TrainingVerdict { - Right, - Finished, - Wrong, - TryAgain, - Done, -} - -#[derive(Debug)] -pub enum SessionError { - InvalidUci(String), - IllegalMove(String), - Chooser, - MissingTargetPath, - InvalidScope(String), - InvalidSrsPolicy, - InvalidQueueMode(&'static str), -} - -impl std::fmt::Display for SessionError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::InvalidUci(uci) => write!(f, "invalid UCI move: {uci}"), - Self::IllegalMove(uci) => write!(f, "illegal move in the current position: {uci}"), - Self::Chooser => f.write_str("the continuation chooser returned no valid candidate"), - Self::MissingTargetPath => { - f.write_str("the target path is no longer present in the repertoire") - } - Self::InvalidScope(message) => write!(f, "invalid training scope: {message}"), - Self::InvalidSrsPolicy => { - f.write_str("SRS policies apply only to White/Black spaced repetition") - } - Self::InvalidQueueMode(message) => f.write_str(message), - } - } -} - -impl std::error::Error for SessionError {} - -/// A live tree-training state machine. Statistics are owned by the session so callers -/// can persist them after each accepted event or at a lifecycle boundary they choose. -pub struct TrainingSession { - repertoire_id: RepertoireId, - mode: TrainingMode, - queue_mode: QueueMode, - scope: TrainingScope, - base_scope: TrainingScope, - random_practice_seed: Option, - repertoire_fingerprint: u64, - srs_policy: SrsPolicy, - tree: RepertoireTree, - stats: StatsData, - chooser: Box, - current: NodeId, - position: Chess, - target: Option, - suggested_path: Option, - seen_positions: BTreeSet, - actual_path: Vec, - done: bool, - completion_recorded: bool, - current_wrong: u32, - current_hinted: bool, - hint_visible: bool, - run_hinted: bool, - mistakes: u32, - hints: u32, - path: Vec, - attempts: Vec, - completed_targets: BTreeSet, - deferred_targets: BTreeSet, -} - -pub struct PreparedNextPath { - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - random_practice_seed: Option, -} - -impl PreparedNextPath { - pub fn run(self, repertoire: &Repertoire, now: i64) -> Result { - let Self { - scope, - mode, - queue_mode, - stats, - random_practice_seed, - } = self; - if let Some(seed) = random_practice_seed { - TrainingSession::scoped_random_seeded(repertoire, scope, mode, stats, now, seed) - } else { - TrainingSession::scoped_with_chooser( - repertoire, - scope, - mode, - queue_mode, - stats, - now, - Box::::default(), - ) - } - } -} - -impl TrainingSession { - pub fn new( - repertoire: &Repertoire, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - now: i64, - ) -> Result { - Self::with_chooser( - repertoire, - mode, - queue_mode, - stats, - now, - Box::::default(), - ) - } - - pub fn new_random( - repertoire: &Repertoire, - mode: TrainingMode, - stats: StatsData, - now: i64, - ) -> Result { - Self::scoped_random(repertoire, TrainingScope::whole(), mode, stats, now) - } - - pub fn scoped_random( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - stats: StatsData, - now: i64, - ) -> Result { - Self::scoped_random_seeded(repertoire, scope, mode, stats, now, random_seed()) - } - - #[cfg(test)] - pub(crate) fn scoped_random_with_seed( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - stats: StatsData, - now: i64, - seed: u64, - ) -> Result { - Self::scoped_random_seeded(repertoire, scope, mode, stats, now, seed) - } - - fn scoped_random_seeded( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - stats: StatsData, - now: i64, - seed: u64, - ) -> Result { - Self::build( - repertoire, - scope, - mode, - QueueMode::Practice, - stats, - now, - (None, Box::::default(), Some(seed)), - ) - } - - pub fn with_chooser( - repertoire: &Repertoire, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - now: i64, - chooser: Box, - ) -> Result { - Self::scoped_with_chooser( - repertoire, - TrainingScope::whole(), - mode, - queue_mode, - stats, - now, - chooser, - ) - } - - pub fn scoped( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - now: i64, - ) -> Result { - Self::scoped_with_chooser( - repertoire, - scope, - mode, - queue_mode, - stats, - now, - Box::::default(), - ) - } - - pub fn new_srs( - repertoire: &Repertoire, - mode: TrainingMode, - stats: StatsData, - now: i64, - policy: SrsPolicy, - ) -> Result { - Self::scoped_srs(repertoire, TrainingScope::whole(), mode, stats, now, policy) - } - - pub fn scoped_srs( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - stats: StatsData, - now: i64, - policy: SrsPolicy, - ) -> Result { - Self::scoped_srs_with_chooser( - repertoire, - scope, - mode, - stats, - now, - policy, - Box::::default(), - ) - } - - pub fn scoped_with_chooser( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - now: i64, - chooser: Box, - ) -> Result { - Self::build( - repertoire, - scope, - mode, - queue_mode, - stats, - now, - (None, chooser, None), - ) - } - - pub fn scoped_srs_with_chooser( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - stats: StatsData, - now: i64, - policy: SrsPolicy, - chooser: Box, - ) -> Result { - Self::build( - repertoire, - scope, - mode, - QueueMode::SpacedRepetition, - stats, - now, - (Some(policy), chooser, None), - ) - } - - fn build( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - now: i64, - options: (Option, Box, Option), - ) -> Result { - let (policy, chooser, random_practice_seed) = options; - if policy.is_some() - && (mode == TrainingMode::Both || queue_mode != QueueMode::SpacedRepetition) - { - return Err(SessionError::InvalidSrsPolicy); - } - let tree = if random_practice_seed.is_some() { - let mut full = repertoire.clone(); - full.max_plies = u32::MAX; - RepertoireTree::new(&full) - } else { - RepertoireTree::new(repertoire) - }; - let current = tree - .scope_anchor(&scope) - .map_err(SessionError::InvalidScope)?; - let srs_policy = policy.unwrap_or(SrsPolicy::Due); - let mut session = Self { - repertoire_id: repertoire.id.clone(), - mode, - queue_mode, - base_scope: scope.clone(), - scope, - random_practice_seed, - repertoire_fingerprint: super::model::stable_hash(repertoire.pgn.as_bytes()), - srs_policy, - stats, - chooser, - position: tree - .position(current) - .cloned() - .unwrap_or_else(|| tree.game().start().position().clone()), - current, - tree, - target: None, - suggested_path: None, - seen_positions: BTreeSet::new(), - actual_path: Vec::new(), - done: false, - completion_recorded: false, - current_wrong: 0, - current_hinted: false, - hint_visible: false, - run_hinted: false, - mistakes: 0, - hints: 0, - path: Vec::new(), - attempts: Vec::new(), - completed_targets: BTreeSet::new(), - deferred_targets: BTreeSet::new(), - }; - session.initialize(now, true)?; - Ok(session) - } - - pub fn game(&self) -> &Game { - self.tree.game() - } - - pub fn stats(&self) -> &StatsData { - &self.stats - } - - pub fn stats_mut(&mut self) -> &mut StatsData { - &mut self.stats - } - - pub fn into_stats(self) -> StatsData { - self.stats - } - - pub fn mode(&self) -> TrainingMode { - self.mode - } - - pub fn queue_mode(&self) -> QueueMode { - self.queue_mode - } - - pub fn scope(&self) -> &TrainingScope { - &self.scope - } - - pub fn srs_policy(&self) -> SrsPolicy { - self.srs_policy - } - - pub fn suggested_path(&self) -> Option<&[String]> { - self.suggested_path - .as_ref() - .map(|path| path.moves.as_slice()) - } - - pub fn current_node(&self) -> NodeId { - self.current - } - - pub fn position(&self) -> &Chess { - &self.position - } - - /// Full position at the scope anchor, before any automatic opponent move. - /// Unlike FEN4 this retains the counters needed for faithful UI replay. - pub fn scope_start_position(&self) -> &Chess { - self.tree - .scope_anchor(&self.scope) - .ok() - .and_then(|anchor| self.tree.position(anchor)) - .unwrap_or_else(|| self.tree.game().start().position()) - } - - pub fn position_key(&self) -> String { - fen4(self.position()) - } - - pub fn target(&self) -> Option<&TrainingTarget> { - self.target.as_ref() - } - - pub fn candidates(&self) -> Vec { - if self.done || self.at_depth_boundary() { - Vec::new() - } else { - self.tree.scoped_candidates(self.current, &self.scope) - } - } - - pub fn path(&self) -> &[PlayedMove] { - &self.path - } - - pub fn attempts(&self) -> &[SessionAttempt] { - &self.attempts - } - - pub fn errors(&self) -> impl Iterator { - self.attempts.iter().filter(|attempt| !attempt.correct) - } - - pub fn total_mistakes(&self) -> u32 { - self.mistakes - } - - pub fn hinted(&self) -> bool { - self.run_hinted - } - - pub fn is_done(&self) -> bool { - self.done - } - - pub fn may_hint(&self) -> bool { - !self.done && (self.queue_mode == QueueMode::Practice || self.current_wrong >= 3) - } - - /// Practice offers a hint immediately; scheduled repetition unlocks it after three - /// wrong attempts. Practice follows its proposed branch while the actual path - /// matches it, then falls back to the first enabled continuation. Every enabled - /// move remains a valid answer. - pub fn hint(&mut self, now: i64) -> Option { - if !self.may_hint() { - return None; - } - let candidate = match &self.target { - Some(target) => { - self.tree - .scoped_candidate(self.current, &target.expected_uci, &self.scope) - } - None => { - let candidates = self.tree.scoped_candidates(self.current, &self.scope); - let proposed = self - .suggested_path - .as_ref() - .filter(|path| { - self.queue_mode == QueueMode::Practice - && path.moves.starts_with(&self.actual_path) - }) - .and_then(|path| path.moves.get(self.actual_path.len())); - proposed - .and_then(|uci| candidates.iter().find(|candidate| &candidate.uci == uci)) - .cloned() - .or_else(|| candidates.into_iter().next()) - } - }?; - if self.hint_visible { - return Some(candidate); - } - let key = self.key_for(&candidate.uci); - self.stats.record_hint(key, now); - self.hints = self.hints.saturating_add(1); - self.current_hinted = true; - self.run_hinted = true; - self.hint_visible = true; - Some(candidate) - } - - pub fn play_uci(&mut self, uci: &str, now: i64) -> Result { - if self.done { - return Ok(TrainingVerdict::Done); - } - let parsed = uci - .parse::() - .map_err(|_| SessionError::InvalidUci(uci.to_owned()))?; - let mv = parsed - .to_move(self.position()) - .map_err(|_| SessionError::IllegalMove(uci.to_owned()))?; - self.play(mv, now) - } - - pub fn play(&mut self, mv: Move, now: i64) -> Result { - if self.done { - return Ok(TrainingVerdict::Done); - } - if !self.position().is_legal(mv) { - return Err(SessionError::IllegalMove( - mv.to_uci(CastlingMode::Standard).to_string(), - )); - } - let actual_uci = mv.to_uci(CastlingMode::Standard).to_string(); - let candidates = self.candidates(); - if self.queue_mode == QueueMode::Practice { - if let Some(candidate) = candidates - .iter() - .find(|candidate| candidate.mv == mv) - .cloned() - { - return self.accept_practice(candidate, now); - } - if let Some(expected) = candidates.first() { - self.reject(expected, &actual_uci, now); - } - return Ok(TrainingVerdict::Wrong); - } - if self.mode == TrainingMode::Both { - if let Some(candidate) = candidates - .iter() - .find(|candidate| candidate.mv == mv) - .cloned() - { - return Ok(self.accept_both(candidate, now)); - } - if let Some(expected) = candidates.first() { - self.reject(expected, &actual_uci, now); - } - return Ok(TrainingVerdict::Wrong); - } - - let Some(target) = self.target.clone() else { - return Ok(TrainingVerdict::Done); - }; - if target.expected_uci == actual_uci { - let candidate = candidates - .iter() - .find(|candidate| candidate.uci == actual_uci) - .cloned() - .ok_or(SessionError::MissingTargetPath)?; - return self.accept_one_side(candidate, now); - } - if let Some(candidate) = candidates - .iter() - .find(|candidate| candidate.mv == mv) - .cloned() - { - return self.accept_one_side(candidate, now); - } - let expected = candidates - .iter() - .find(|candidate| candidate.uci == target.expected_uci) - .cloned() - .ok_or(SessionError::MissingTargetPath)?; - self.reject(&expected, &actual_uci, now); - Ok(TrainingVerdict::Wrong) - } - - /// Repeats the same proposed path (or restarts the current one-side queue). It does - /// not advance a path cursor and never counts an unfinished run as complete. - pub fn restart(&mut self, now: i64) -> Result<(), SessionError> { - if self.queue_mode == QueueMode::Practice && !self.actual_path.is_empty() { - self.suggested_path = Some(TrainingPath { - moves: self.actual_path.clone(), - }); - } - self.reset_run()?; - self.initialize(now, false) - } - - /// Captures the inputs for a next-path run without changing this session. The - /// expensive tree traversal happens only when `PreparedNextPath::run` is called. - pub fn prepare_next_path(&self) -> Result { - if self.mode != TrainingMode::Both && self.queue_mode != QueueMode::Practice { - return Err(SessionError::InvalidQueueMode( - "next_path is available in branch practice or Both mode", - )); - } - let scope = if self.random_practice_seed.is_some() { - &self.base_scope - } else { - &self.scope - }; - Ok(PreparedNextPath { - scope: scope.clone(), - mode: self.mode, - queue_mode: self.queue_mode, - stats: self.stats.clone(), - random_practice_seed: self.random_practice_seed, - }) - } - - /// Selects the next proposed root/scope-to-boundary path. Enabled deviations remain - /// free; the actual path, rather than this proposal, receives completion statistics. - pub fn next_path(&mut self, now: i64) -> Result<(), SessionError> { - if self.mode != TrainingMode::Both && self.queue_mode != QueueMode::Practice { - return Err(SessionError::InvalidQueueMode( - "next_path is available in branch practice or Both mode", - )); - } - if self.random_practice_seed.is_some() { - self.scope = self.base_scope.clone(); - } - self.reset_run()?; - self.suggested_path = None; - self.initialize(now, true) - } - - pub fn restart_with_policy(&mut self, now: i64, policy: SrsPolicy) -> Result<(), SessionError> { - if self.mode == TrainingMode::Both { - return Err(SessionError::InvalidSrsPolicy); - } - self.queue_mode = QueueMode::SpacedRepetition; - self.srs_policy = policy; - self.reset_run()?; - self.initialize(now, true) - } - - fn reset_run(&mut self) -> Result<(), SessionError> { - self.current = self - .tree - .scope_anchor(&self.scope) - .map_err(SessionError::InvalidScope)?; - self.target = None; - self.done = false; - self.completion_recorded = false; - self.current_wrong = 0; - self.current_hinted = false; - self.hint_visible = false; - self.run_hinted = false; - self.mistakes = 0; - self.hints = 0; - self.path.clear(); - self.attempts.clear(); - self.actual_path.clear(); - self.seen_positions.clear(); - self.completed_targets.clear(); - self.deferred_targets.clear(); - Ok(()) - } - - fn initialize(&mut self, now: i64, select_path: bool) -> Result<(), SessionError> { - if self.queue_mode == QueueMode::Practice { - if select_path { - if self.random_practice_seed.is_some() { - self.select_random_path()?; - } else { - self.suggested_path = self - .stats - .next_practice_path(&self.tree, &self.repertoire_id, self.mode, &self.scope) - .map_err(SessionError::InvalidScope)?; - } - } - self.prepare_scope_start()?; - if self.suggested_path.is_none() { - self.done = true; - return Ok(()); - } - self.advance_practice_opponent(now)?; - return Ok(()); - } - if self.mode == TrainingMode::Both { - if select_path { - self.suggested_path = self - .stats - .next_training_path( - &self.tree, - &self.repertoire_id, - &self.scope, - self.queue_mode, - ) - .map_err(SessionError::InvalidScope)?; - if self.suggested_path.is_some() { - self.stats - .path_presented(&self.repertoire_id, &self.scope, self.queue_mode); - } - } - self.prepare_scope_start()?; - if self.suggested_path.is_none() - || self - .tree - .scoped_candidates(self.current, &self.scope) - .is_empty() - { - self.done = true; - } - Ok(()) - } else { - self.prepare_next_target(now).map(|_| ()) - } - } - - fn select_random_path(&mut self) -> Result<(), SessionError> { - let seed = self - .random_practice_seed - .ok_or(SessionError::InvalidQueueMode( - "random practice seed is missing", - ))?; - let selected = self - .stats - .next_random_practice_path( - &self.tree, - &self.repertoire_id, - self.mode, - &self.base_scope, - self.repertoire_fingerprint, - seed, - ) - .map_err(SessionError::InvalidScope)?; - let Some(selected) = selected else { - self.scope = self.base_scope.clone(); - self.suggested_path = None; - return Ok(()); - }; - let prefix_moves = selected - .path - .moves - .get(..=selected.start) - .ok_or(SessionError::MissingTargetPath)?; - let suggested = selected - .path - .moves - .get(selected.start..) - .ok_or(SessionError::MissingTargetPath)? - .to_vec(); - let mut prefix = self.base_scope.parent_prefix().to_vec(); - prefix.extend(prefix_moves.iter().cloned()); - let end_prefix = self.base_scope.end_prefix.as_ref().map(|_| { - let mut end = self.base_scope.parent_prefix().to_vec(); - end.extend(selected.path.moves.iter().cloned()); - end - }); - self.scope = TrainingScope { - prefix, - end_prefix, - include_context: true, - }; - self.suggested_path = Some(TrainingPath { moves: suggested }); - Ok(()) - } - - fn prepare_scope_start(&mut self) -> Result<(), SessionError> { - let anchor = self - .tree - .scope_anchor(&self.scope) - .map_err(SessionError::InvalidScope)?; - if self.scope.include_context { - let context = self - .tree - .path(anchor) - .map(<[String]>::to_vec) - .ok_or(SessionError::MissingTargetPath)?; - self.current = self.tree.root(); - self.position = self.tree.game().start().position().clone(); - for uci in context { - let candidate = self - .tree - .candidate(self.current, &uci) - .ok_or(SessionError::MissingTargetPath)?; - self.advance(candidate, true); - } - } else { - self.current = anchor; - self.position = self - .tree - .position(anchor) - .cloned() - .ok_or(SessionError::MissingTargetPath)?; - } - self.seen_positions.insert(self.position_key()); - Ok(()) - } - - fn at_depth_boundary(&self) -> bool { - if self.mode != TrainingMode::Both && self.queue_mode != QueueMode::Practice { - return false; - } - let start = self.scope.parent_prefix().len(); - start.saturating_add(self.actual_path.len()) >= self.tree.max_plies() as usize - } - - fn practice_boundary(&self) -> bool { - self.at_depth_boundary() - || self - .tree - .scoped_candidates(self.current, &self.scope) - .is_empty() - } - - fn advance_practice_opponent(&mut self, now: i64) -> Result<(), SessionError> { - if self.practice_boundary() { - self.finish(now); - return Ok(()); - } - while self - .mode - .user_color() - .is_some_and(|color| self.position.turn() != color) - { - let candidates = self.candidates(); - let suggested = self - .suggested_path - .as_ref() - .filter(|path| path.moves.starts_with(&self.actual_path)) - .and_then(|path| path.moves.get(self.actual_path.len())); - let selected = suggested - .and_then(|uci| candidates.iter().find(|c| &c.uci == uci)) - .cloned(); - let selected = match selected { - Some(selected) => selected, - None => { - let index = self - .chooser - .choose(&candidates) - .filter(|index| *index < candidates.len()) - .ok_or(SessionError::Chooser)?; - candidates[index].clone() - } - }; - self.actual_path.push(selected.uci.clone()); - self.advance(selected, true); - let repeated = !self.seen_positions.insert(self.position_key()); - if repeated || self.practice_boundary() { - self.finish(now); - return Ok(()); - } - } - Ok(()) - } - - fn accept_practice( - &mut self, - candidate: Candidate, - now: i64, - ) -> Result { - let key = self.key_for(&candidate.uci); - self.stats - .record_correct(key, now, &candidate.uci, self.current_hinted, false); - self.push_attempt(candidate.uci.clone(), candidate.uci.clone(), true); - self.actual_path.push(candidate.uci.clone()); - self.advance(candidate, false); - self.reset_target_state(); - if !self.seen_positions.insert(self.position_key()) || self.practice_boundary() { - self.finish(now); - } else { - self.advance_practice_opponent(now)?; - } - Ok(if self.done { - TrainingVerdict::Finished - } else { - TrainingVerdict::Right - }) - } - - fn accept_both(&mut self, candidate: Candidate, now: i64) -> TrainingVerdict { - let hinted = self.current_hinted; - let key = self.key_for(&candidate.uci); - self.stats - .record_correct(key, now, &candidate.uci, hinted, false); - self.push_attempt(candidate.uci.clone(), candidate.uci.clone(), true); - self.actual_path.push(candidate.uci.clone()); - self.advance(candidate, false); - self.reset_target_state(); - let repeated = !self.seen_positions.insert(self.position_key()); - if repeated - || self.at_depth_boundary() - || self - .tree - .scoped_candidates(self.current, &self.scope) - .is_empty() - { - self.finish(now); - TrainingVerdict::Finished - } else { - TrainingVerdict::Right - } - } - - fn accept_one_side( - &mut self, - candidate: Candidate, - now: i64, - ) -> Result { - let hinted = self.current_hinted; - let key = self.key_for(&candidate.uci); - if let Some(target) = &self.target - && target.expected_uci != candidate.uci - { - self.deferred_targets.insert(self.target_key(target)); - } - self.stats.record_correct( - key.clone(), - now, - &candidate.uci, - hinted, - self.queue_mode == QueueMode::SpacedRepetition - && self.srs_policy != SrsPolicy::EarlyReview, - ); - if self - .target - .as_ref() - .is_some_and(|target| target.expected_uci == candidate.uci) - { - self.stats.target_completed( - &self.repertoire_id, - self.mode, - self.queue_mode, - &self.scope, - ); - } - self.completed_targets.insert(key); - self.push_attempt(candidate.uci.clone(), candidate.uci.clone(), true); - self.advance(candidate, false); - - let user_color = self.mode.user_color(); - if self.tree.position(self.current).map(|p| p.turn()) != user_color { - let candidates = self.tree.scoped_candidates(self.current, &self.scope); - if !candidates.is_empty() { - let index = self - .chooser - .choose(&candidates) - .filter(|index| *index < candidates.len()) - .ok_or(SessionError::Chooser)?; - let selected = candidates[index].clone(); - self.advance(selected, true); - } - } - - if self.prepare_next_target(now)? { - Ok(TrainingVerdict::Right) - } else { - self.finish(now); - Ok(TrainingVerdict::Finished) - } - } - - fn reject(&mut self, expected: &Candidate, actual_uci: &str, now: i64) { - let key = self.key_for(&expected.uci); - self.stats.record_wrong( - key, - now, - actual_uci, - self.mode != TrainingMode::Both - && self.queue_mode == QueueMode::SpacedRepetition - && self.srs_policy != SrsPolicy::EarlyReview, - ); - self.mistakes = self.mistakes.saturating_add(1); - self.current_wrong = self.current_wrong.saturating_add(1); - self.push_attempt(expected.uci.clone(), actual_uci.to_owned(), false); - } - - fn key_for(&self, expected_uci: &str) -> MoveKey { - MoveKey { - repertoire_id: self.repertoire_id.clone(), - mode: self.mode, - position_fen4: self.position_key(), - expected_uci: if self.mode == TrainingMode::Both { - String::new() - } else { - expected_uci.to_owned() - }, - } - } - - fn push_attempt(&mut self, expected_uci: String, actual_uci: String, correct: bool) { - self.attempts.push(SessionAttempt { - position_fen4: self.position_key(), - expected_uci: if self.mode == TrainingMode::Both { - String::new() - } else { - expected_uci - }, - actual_uci, - correct, - hinted: self.current_hinted, - }); - } - - fn advance(&mut self, candidate: Candidate, automatic: bool) { - let before = self.position_key(); - self.position.play_unchecked(candidate.mv); - self.current = candidate.node; - let after = self.position_key(); - self.path.push(PlayedMove { - uci: candidate.uci, - san: candidate.san, - automatic, - position_before: before, - position_after: after, - }); - } - - fn prepare_next_target(&mut self, now: i64) -> Result { - if self.queue_mode == QueueMode::SpacedRepetition - && self.srs_policy == SrsPolicy::Introduce - && self.completed_targets.len() >= super::stats::INTRODUCTION_BATCH_SIZE - { - self.done = true; - self.target = None; - return Ok(false); - } - let queued = if self.queue_mode == QueueMode::SpacedRepetition { - self.stats.srs_queue( - &self.tree, - &self.repertoire_id, - self.mode, - now, - &self.scope, - self.srs_policy, - ) - } else { - self.stats.scoped_queue( - &self.tree, - &self.repertoire_id, - self.mode, - self.queue_mode, - now, - &self.scope, - ) - }; - let next = queued.into_iter().find(|target| { - !self.completed_targets.contains(&self.target_key(target)) - && !self.deferred_targets.contains(&self.target_key(target)) - }); - let Some(target) = next else { - self.done = true; - self.target = None; - return Ok(false); - }; - if self.scope.include_context { - self.current = self.tree.root(); - self.position = self.tree.game().start().position().clone(); - for uci in &target.path { - let candidate = self - .tree - .candidate(self.current, uci) - .ok_or(SessionError::MissingTargetPath)?; - self.advance(candidate, true); - } - } else { - self.current = self - .tree - .node_at_path(&target.path) - .ok_or(SessionError::MissingTargetPath)?; - self.position = self - .tree - .position(self.current) - .cloned() - .ok_or(SessionError::MissingTargetPath)?; - } - self.target = Some(target); - self.reset_target_state(); - Ok(true) - } - - fn target_key(&self, target: &TrainingTarget) -> MoveKey { - MoveKey { - repertoire_id: self.repertoire_id.clone(), - mode: self.mode, - position_fen4: target.position_fen4.clone(), - expected_uci: target.expected_uci.clone(), - } - } - - fn reset_target_state(&mut self) { - self.current_wrong = 0; - self.current_hinted = false; - self.hint_visible = false; - } - - fn finish(&mut self, now: i64) { - self.done = true; - self.target = None; - self.hint_visible = false; - if self.completion_recorded || self.attempts.is_empty() { - return; - } - self.completion_recorded = true; - let path = if self.mode == TrainingMode::Both || self.queue_mode == QueueMode::Practice { - self.actual_path.clone() - } else { - self.path.iter().map(|mv| mv.uci.clone()).collect() - }; - let record = RunRecord { - at: now, - mistakes: self.mistakes, - hints: self.hints, - hinted: self.run_hinted, - path, - user_attempts: u32::try_from(self.attempts.len()).unwrap_or(u32::MAX), - automatic_moves: u32::try_from(self.path.iter().filter(|mv| mv.automatic).count()) - .unwrap_or(u32::MAX), - scope: self.scope.key(), - }; - self.stats - .record_run(&self.repertoire_id, self.mode, record.clone()); - if self.mode == TrainingMode::Both && !self.actual_path.is_empty() { - self.stats.record_path_run( - PathKey { - repertoire_id: self.repertoire_id.clone(), - scope: self.scope.key(), - path: self.actual_path.clone(), - }, - record, - ); - } - } -} - -fn random_seed() -> u64 { - use std::hash::BuildHasher; - - std::collections::hash_map::RandomState::new().hash_one(0u8) -} diff --git a/crates/trainer/src/repertoire/stats.rs b/crates/trainer/src/repertoire/stats.rs index 737c691..68ca588 100644 --- a/crates/trainer/src/repertoire/stats.rs +++ b/crates/trainer/src/repertoire/stats.rs @@ -1,14 +1,11 @@ -use chess_core::shakmaty::{Color, Position}; +use chess_core::shakmaty::Color; use serde::{Deserialize, Serialize}; use super::model::RepertoireId; -use super::scope::{TrainingScope, TrainingScopeKey}; -use super::tree::{RepertoireTree, TrainingPath, TrainingTarget}; +use super::scope::TrainingScopeKey; pub const STATS_VERSION: u32 = 2; -pub const INITIAL_INTERVAL_SECONDS: i64 = 24 * 60 * 60; -pub const MISTAKE_INTERVAL_SECONDS: i64 = 10 * 60; -pub const MAX_INTERVAL_SECONDS: i64 = 365 * 24 * 60 * 60; +/// Recent attempts kept per move in a v2 file. const RECENT: usize = 10; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -36,15 +33,6 @@ pub enum QueueMode { LeastRecent, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum SrsPolicy { - Due, - Introduce, - EarlyReview, -} - -pub const INTRODUCTION_BATCH_SIZE: usize = 10; - #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct MoveKey { pub repertoire_id: RepertoireId, @@ -103,6 +91,7 @@ impl Default for MoveStats { } } +#[cfg(test)] impl MoveStats { pub fn new(key: MoveKey) -> Self { Self { @@ -110,88 +99,6 @@ impl MoveStats { ..Self::default() } } - - pub fn unseen(&self) -> bool { - self.attempts == 0 - } - - pub fn is_due(&self, now: i64) -> bool { - self.due.is_some_and(|due| due <= now) - } - - fn push_recent(&mut self, attempt: AttemptRecord) { - self.recent.push(attempt); - if self.recent.len() > RECENT { - self.recent.remove(0); - } - } - - fn wrong(&mut self, now: i64, actual_uci: &str, schedule: bool) { - self.attempts = self.attempts.saturating_add(1); - self.wrong = self.wrong.saturating_add(1); - self.streak = if self.streak < 0 { - self.streak.saturating_sub(1) - } else { - -1 - }; - self.last_attempt = Some(now); - self.last_seen = Some(now); - if schedule { - self.due = Some(now.saturating_add(MISTAKE_INTERVAL_SECONDS)); - self.interval_seconds = Some(MISTAKE_INTERVAL_SECONDS); - } - self.push_recent(AttemptRecord { - at: now, - correct: false, - hinted: false, - actual_uci: actual_uci.to_owned(), - }); - } - - fn correct(&mut self, now: i64, actual_uci: &str, hinted: bool, schedule: bool) { - let previous_interval = - self.interval_seconds - .unwrap_or_else(|| match (self.due, self.last_seen) { - (Some(due), Some(last)) if due > last => due.saturating_sub(last), - _ => INITIAL_INTERVAL_SECONDS, - }); - let clean_streak = self.streak; - let retry = hinted || clean_streak < 0; - self.attempts = self.attempts.saturating_add(1); - self.correct = self.correct.saturating_add(1); - self.streak = if retry { - 0 - } else { - clean_streak.saturating_add(1).max(1) - }; - if schedule { - let interval = if retry { - MISTAKE_INTERVAL_SECONDS - } else if clean_streak > 0 { - previous_interval - .saturating_mul(2) - .clamp(INITIAL_INTERVAL_SECONDS, MAX_INTERVAL_SECONDS) - } else { - INITIAL_INTERVAL_SECONDS - }; - self.due = Some(now.saturating_add(interval)); - self.interval_seconds = Some(interval); - } - self.last_attempt = Some(now); - self.last_seen = Some(now); - self.push_recent(AttemptRecord { - at: now, - correct: true, - hinted, - actual_uci: actual_uci.to_owned(), - }); - } - - fn hint(&mut self, now: i64) { - self.streak = 0; - self.hints = self.hints.saturating_add(1); - self.last_seen = Some(now); - } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -275,11 +182,6 @@ struct RandomPracticeCursor { fingerprint: Option, } -pub(crate) struct RandomPracticePath { - pub path: TrainingPath, - pub start: usize, -} - #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct StatsData { @@ -314,616 +216,6 @@ impl Default for StatsData { } impl StatsData { - /// Removes modern statistics and queue positions for one repertoire. Legacy line - /// aggregates have independent identities and remain untouched. - pub fn remove_repertoire(&mut self, repertoire_id: &RepertoireId) { - self.move_stats - .retain(|entry| &entry.key.repertoire_id != repertoire_id); - self.runs - .retain(|entry| &entry.repertoire_id != repertoire_id); - self.path_stats - .retain(|entry| &entry.key.repertoire_id != repertoire_id); - self.review_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id); - self.path_review_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id); - self.practice_path_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id); - self.random_practice_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id); - } - - pub fn remove_repertoire_mode(&mut self, repertoire_id: &RepertoireId, mode: TrainingMode) { - self.move_stats - .retain(|entry| &entry.key.repertoire_id != repertoire_id || entry.key.mode != mode); - self.runs - .retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode); - self.review_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode); - self.practice_path_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode); - self.random_practice_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode); - if mode == TrainingMode::Both { - self.path_stats - .retain(|entry| &entry.key.repertoire_id != repertoire_id); - self.path_review_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id); - } - } - - pub fn get(&self, key: &MoveKey) -> Option<&MoveStats> { - self.move_stats.iter().find(|stats| &stats.key == key) - } - - pub fn runs(&self, repertoire_id: &RepertoireId, mode: TrainingMode) -> Option<&RunStats> { - self.runs - .iter() - .find(|runs| &runs.repertoire_id == repertoire_id && runs.mode == mode) - } - - /// Compatibility queue used by the existing desktop summary. SRS sessions use the - /// more specific `srs_queue` policies below and never automatically exhaust this list. - pub fn queue( - &self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - mode: TrainingMode, - queue_mode: QueueMode, - now: i64, - ) -> Vec { - self.scoped_queue( - tree, - repertoire_id, - mode, - queue_mode, - now, - &TrainingScope::whole(), - ) - } - - pub fn scoped_queue( - &self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - mode: TrainingMode, - queue_mode: QueueMode, - now: i64, - scope: &TrainingScope, - ) -> Vec { - let Some(color) = mode.user_color() else { - return Vec::new(); - }; - let targets = tree.scoped_targets(color, scope); - let key = |target: &TrainingTarget| MoveKey { - repertoire_id: repertoire_id.clone(), - mode, - position_fen4: target.position_fen4.clone(), - expected_uci: target.expected_uci.clone(), - }; - let mut indexed: Vec<(usize, TrainingTarget)> = targets.into_iter().enumerate().collect(); - match queue_mode { - QueueMode::SpacedRepetition => { - let mut due = Vec::new(); - let mut unseen = Vec::new(); - let mut unscheduled = Vec::new(); - for (order, target) in indexed { - match self.get(&key(&target)) { - Some(stats) if stats.is_due(now) => due.push((stats.due, order, target)), - Some(stats) if stats.due.is_none() => { - unscheduled.push((order, target)); - } - Some(_) => {} - None => unseen.push((order, target)), - } - } - due.sort_by_key(|(due, order, _)| (*due, *order)); - due.into_iter() - .map(|(_, _, target)| target) - .chain(unseen.into_iter().map(|(_, target)| target)) - .chain(unscheduled.into_iter().map(|(_, target)| target)) - .collect() - } - QueueMode::LeastRecent => { - indexed.sort_by_key(|(order, target)| { - let stats = self.get(&key(target)); - ( - !stats.is_none_or(MoveStats::unseen), - stats.and_then(|stats| stats.last_seen).unwrap_or(i64::MIN), - *order, - ) - }); - indexed.into_iter().map(|(_, target)| target).collect() - } - QueueMode::Practice | QueueMode::ReviewInOrder => { - let scope_key = scope.key(); - let cursor = self - .review_cursors - .iter() - .find(|cursor| { - &cursor.repertoire_id == repertoire_id - && cursor.mode == mode - && cursor.scope == scope_key - }) - .map_or(0, |cursor| cursor.next); - if indexed.is_empty() { - return Vec::new(); - } - let offset = cursor % indexed.len(); - indexed.rotate_left(offset); - indexed.into_iter().map(|(_, target)| target).collect() - } - } - } - - pub fn srs_queue( - &self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - mode: TrainingMode, - now: i64, - scope: &TrainingScope, - policy: SrsPolicy, - ) -> Vec { - let Some(color) = mode.user_color() else { - return Vec::new(); - }; - let key = |target: &TrainingTarget| MoveKey { - repertoire_id: repertoire_id.clone(), - mode, - position_fen4: target.position_fen4.clone(), - expected_uci: target.expected_uci.clone(), - }; - let mut due = Vec::new(); - let mut future = Vec::new(); - let mut unseen = Vec::new(); - let mut unscheduled = Vec::new(); - for (order, target) in tree.scoped_targets(color, scope).into_iter().enumerate() { - match self.get(&key(&target)) { - Some(stats) if stats.is_due(now) => due.push((stats.due, order, target)), - Some(stats) if stats.due.is_some() => future.push((stats.due, order, target)), - Some(stats) if stats.unseen() => unseen.push((order, target)), - Some(_) => unscheduled.push((order, target)), - None => unseen.push((order, target)), - } - } - due.sort_by_key(|(due, order, _)| (*due, *order)); - future.sort_by_key(|(due, order, _)| (*due, *order)); - match policy { - SrsPolicy::Due => due.into_iter().map(|(_, _, target)| target).collect(), - SrsPolicy::Introduce => unseen - .into_iter() - .chain(unscheduled) - .take(INTRODUCTION_BATCH_SIZE) - .map(|(_, target)| target) - .collect(), - SrsPolicy::EarlyReview => future.into_iter().map(|(_, _, target)| target).collect(), - } - } - - pub fn path_stats(&self, key: &PathKey) -> Option<&PathStats> { - self.path_stats.iter().find(|stats| &stats.key == key) - } - - pub fn path_queue( - &self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - scope: &TrainingScope, - queue_mode: QueueMode, - ) -> Result, String> { - let scope_key = scope.key(); - let mut paths = tree.training_paths(scope)?; - if queue_mode == QueueMode::LeastRecent { - paths.sort_by_key(|path| { - let key = PathKey { - repertoire_id: repertoire_id.clone(), - scope: scope_key.clone(), - path: path.moves.clone(), - }; - let stats = self.path_stats(&key); - ( - stats.is_some_and(|stats| stats.completions > 0), - stats - .and_then(|stats| stats.last_completion) - .unwrap_or(i64::MIN), - ) - }); - return Ok(paths); - } - if paths.is_empty() { - return Ok(paths); - } - let cursor = self - .path_review_cursors - .iter() - .find(|cursor| &cursor.repertoire_id == repertoire_id && cursor.scope == scope_key) - .map_or(0, |cursor| cursor.next); - let offset = cursor % paths.len(); - paths.rotate_left(offset); - Ok(paths) - } - - pub(crate) fn next_practice_path( - &mut self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - mode: TrainingMode, - scope: &TrainingScope, - ) -> Result, String> { - use std::ops::ControlFlow; - let scope_key = scope.key(); - let index = match self.practice_path_cursors.iter().position(|c| { - &c.repertoire_id == repertoire_id && c.mode == mode && c.scope == scope_key - }) { - Some(index) => index, - None => { - self.practice_path_cursors.push(ReviewCursor { - repertoire_id: repertoire_id.clone(), - mode, - scope: scope_key, - next: 0, - }); - self.practice_path_cursors.len() - 1 - } - }; - let cursor = self.practice_path_cursors[index].next; - let mut count = 0usize; - let mut chosen = None; - tree.visit_training_paths(scope, |moves| { - if count == cursor { - chosen = Some(TrainingPath { - moves: moves.to_vec(), - }); - return ControlFlow::Break(()); - } - count += 1; - ControlFlow::Continue(()) - })?; - if chosen.is_none() && count > 0 { - let offset = cursor % count; - let mut order = 0; - tree.visit_training_paths(scope, |moves| { - if order == offset { - chosen = Some(TrainingPath { - moves: moves.to_vec(), - }); - return ControlFlow::Break(()); - } - order += 1; - ControlFlow::Continue(()) - })?; - self.practice_path_cursors[index].next = offset; - } - if chosen.is_some() { - self.practice_path_cursors[index].next = - self.practice_path_cursors[index].next.saturating_add(1); - } - Ok(chosen) - } - - pub(crate) fn next_random_practice_path( - &mut self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - mode: TrainingMode, - scope: &TrainingScope, - repertoire_fingerprint: u64, - initial_seed: u64, - ) -> Result, String> { - use std::ops::ControlFlow; - - let anchor = tree.scope_anchor(scope)?; - let start_turn = tree - .position(anchor) - .map(|position| position.turn()) - .ok_or_else(|| "scope start position is missing".to_owned())?; - let mut count = Some(0usize); - tree.visit_source_paths(scope, |moves| { - if eligible_target_count(mode, start_turn, moves.len()) == 0 { - return ControlFlow::Continue(()); - } - count = count.and_then(|count| count.checked_add(1)); - if count.is_none() { - ControlFlow::Break(()) - } else { - ControlFlow::Continue(()) - } - })?; - let count = - count.ok_or_else(|| "training path count exceeds the platform limit".to_owned())?; - let scope_key = scope.key(); - let existing = self.random_practice_cursors.iter().position(|cursor| { - &cursor.repertoire_id == repertoire_id - && cursor.mode == mode - && cursor.scope == scope_key - }); - let is_new = existing.is_none(); - let index = existing.unwrap_or_else(|| { - self.random_practice_cursors.push(RandomPracticeCursor { - repertoire_id: repertoire_id.clone(), - mode, - scope: scope_key, - seed: initial_seed, - position: 0, - count: 0, - fingerprint: Some(repertoire_fingerprint), - }); - self.random_practice_cursors.len() - 1 - }); - let cursor = &mut self.random_practice_cursors[index]; - if !is_new - && (cursor.fingerprint != Some(repertoire_fingerprint) - || cursor.count != count - || cursor.position >= count) - { - cursor.seed = next_cycle_seed(cursor.seed); - cursor.position = 0; - } - cursor.fingerprint = Some(repertoire_fingerprint); - cursor.count = count; - if count == 0 { - cursor.position = 0; - return Ok(None); - } - if cursor.position >= count { - cursor.position = 0; - } - - let position = cursor.position; - let seed = cursor.seed; - let step = coprime_step(seed ^ 0xa076_1d64_78bd_642f, count); - let offset = (mix64(seed ^ 0xe703_7ed1_a0b4_28db) as u128 % count as u128) as usize; - let selected_index = - ((step as u128 * position as u128 + offset as u128) % count as u128) as usize; - let start_seed = mix64(seed ^ (position as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15)); - let mut order = 0usize; - let mut chosen = None; - tree.visit_source_paths(scope, |moves| { - let eligible = eligible_target_count(mode, start_turn, moves.len()); - if eligible == 0 { - return ControlFlow::Continue(()); - } - if order == selected_index { - let start_order = (start_seed as usize) % eligible; - chosen = eligible_target_index(mode, start_turn, moves.len(), start_order).map( - |start| RandomPracticePath { - path: TrainingPath { - moves: moves.to_vec(), - }, - start, - }, - ); - return ControlFlow::Break(()); - } - order += 1; - ControlFlow::Continue(()) - })?; - if chosen.is_some() { - cursor.position = cursor.position.saturating_add(1); - Ok(chosen) - } else { - Err("random training path selection is inconsistent".to_owned()) - } - } - - /// Selects one route without materializing the complete path queue. Ordered - /// review stops as soon as its cursor is reached; only wrapping needs a second pass. - pub fn next_training_path( - &self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - scope: &TrainingScope, - queue_mode: QueueMode, - ) -> Result, String> { - use std::ops::ControlFlow; - let scope_key = scope.key(); - if queue_mode == QueueMode::LeastRecent { - let mut best = None; - let mut best_rank = None; - tree.visit_training_paths(scope, |moves| { - let stats = self.path_stats.iter().find(|stats| { - &stats.key.repertoire_id == repertoire_id - && stats.key.scope == scope_key - && stats.key.path == moves - }); - let rank = ( - stats.is_some_and(|stats| stats.completions > 0), - stats - .and_then(|stats| stats.last_completion) - .unwrap_or(i64::MIN), - ); - if best_rank.is_none_or(|old| rank < old) { - best_rank = Some(rank); - best = Some(TrainingPath { - moves: moves.to_vec(), - }); - } - // This is the minimum possible rank. Keeping its first occurrence - // preserves the stable PGN order used by path_queue's sort. - if rank == (false, i64::MIN) { - ControlFlow::Break(()) - } else { - ControlFlow::Continue(()) - } - })?; - return Ok(best); - } - let cursor = self - .path_review_cursors - .iter() - .find(|cursor| &cursor.repertoire_id == repertoire_id && cursor.scope == scope_key) - .map_or(0, |cursor| cursor.next); - let mut count = 0usize; - let mut selected = None; - tree.visit_training_paths(scope, |moves| { - if count == cursor { - selected = Some(TrainingPath { - moves: moves.to_vec(), - }); - return ControlFlow::Break(()); - } - count += 1; - ControlFlow::Continue(()) - })?; - if selected.is_some() || count == 0 { - return Ok(selected); - } - let offset = cursor % count; - let mut index = 0; - tree.visit_training_paths(scope, |moves| { - if index == offset { - selected = Some(TrainingPath { - moves: moves.to_vec(), - }); - return ControlFlow::Break(()); - } - index += 1; - ControlFlow::Continue(()) - })?; - Ok(selected) - } - - pub(crate) fn record_wrong( - &mut self, - key: MoveKey, - now: i64, - actual_uci: &str, - schedule: bool, - ) { - self.entry(key).wrong(now, actual_uci, schedule); - } - - pub(crate) fn record_correct( - &mut self, - key: MoveKey, - now: i64, - actual_uci: &str, - hinted: bool, - schedule: bool, - ) { - self.entry(key).correct(now, actual_uci, hinted, schedule); - } - - pub(crate) fn record_hint(&mut self, key: MoveKey, now: i64) { - self.entry(key).hint(now); - } - - pub(crate) fn target_completed( - &mut self, - repertoire_id: &RepertoireId, - mode: TrainingMode, - queue_mode: QueueMode, - scope: &TrainingScope, - ) { - if queue_mode != QueueMode::ReviewInOrder { - return; - } - let scope = scope.key(); - let index = match self.review_cursors.iter().position(|cursor| { - &cursor.repertoire_id == repertoire_id && cursor.mode == mode && cursor.scope == scope - }) { - Some(index) => index, - None => { - self.review_cursors.push(ReviewCursor { - repertoire_id: repertoire_id.clone(), - mode, - scope, - next: 0, - }); - self.review_cursors.len() - 1 - } - }; - self.review_cursors[index].next = self.review_cursors[index].next.saturating_add(1); - } - - pub(crate) fn path_presented( - &mut self, - repertoire_id: &RepertoireId, - scope: &TrainingScope, - queue_mode: QueueMode, - ) { - if queue_mode == QueueMode::LeastRecent { - return; - } - let scope = scope.key(); - let index = match self - .path_review_cursors - .iter() - .position(|cursor| &cursor.repertoire_id == repertoire_id && cursor.scope == scope) - { - Some(index) => index, - None => { - self.path_review_cursors.push(PathReviewCursor { - repertoire_id: repertoire_id.clone(), - scope, - next: 0, - }); - self.path_review_cursors.len() - 1 - } - }; - self.path_review_cursors[index].next = - self.path_review_cursors[index].next.saturating_add(1); - } - - pub(crate) fn record_run( - &mut self, - repertoire_id: &RepertoireId, - mode: TrainingMode, - record: RunRecord, - ) { - let index = match self - .runs - .iter() - .position(|runs| &runs.repertoire_id == repertoire_id && runs.mode == mode) - { - Some(index) => index, - None => { - self.runs.push(RunStats { - repertoire_id: repertoire_id.clone(), - mode, - ..RunStats::default() - }); - self.runs.len() - 1 - } - }; - let runs = &mut self.runs[index]; - runs.completions = runs.completions.saturating_add(1); - runs.last = Some(record.at); - runs.recent.push(record); - if runs.recent.len() > RECENT { - runs.recent.remove(0); - } - } - - pub(crate) fn record_path_run(&mut self, key: PathKey, record: RunRecord) { - let index = match self.path_stats.iter().position(|stats| stats.key == key) { - Some(index) => index, - None => { - self.path_stats.push(PathStats { - key, - completions: 0, - mistakes: 0, - hints: 0, - last_seen: None, - last_completion: None, - recent: Vec::new(), - }); - self.path_stats.len() - 1 - } - }; - let stats = &mut self.path_stats[index]; - stats.completions = stats.completions.saturating_add(1); - stats.mistakes = stats.mistakes.saturating_add(record.mistakes); - stats.hints = stats.hints.saturating_add(record.hints); - stats.last_seen = Some(record.at); - stats.last_completion = Some(record.at); - stats.recent.push(record); - if stats.recent.len() > RECENT { - stats.recent.remove(0); - } - } - pub(crate) fn migrate_position_stats(&mut self) { let mut merged: Vec = Vec::new(); for mut entry in self.move_stats.drain(..) { @@ -980,91 +272,4 @@ impl StatsData { self.path_review_cursors .sort_by(|a, b| (&a.repertoire_id, &a.scope).cmp(&(&b.repertoire_id, &b.scope))); } - - fn entry(&mut self, key: MoveKey) -> &mut MoveStats { - let index = match self.move_stats.iter().position(|stats| stats.key == key) { - Some(index) => index, - None => { - self.move_stats.push(MoveStats::new(key)); - self.move_stats.len() - 1 - } - }; - &mut self.move_stats[index] - } -} - -pub(crate) const MIN_RANDOM_CONTINUATION_PLIES: usize = 7; - -fn random_max_start(plies: usize) -> usize { - plies.saturating_sub(MIN_RANDOM_CONTINUATION_PLIES) -} - -fn eligible_target_count(mode: TrainingMode, start_turn: Color, plies: usize) -> usize { - if plies == 0 { - return 0; - } - let max_start = random_max_start(plies); - let Some(user_color) = mode.user_color() else { - return usize::from(plies > 0) * (max_start + 1); - }; - let first = usize::from(start_turn != user_color); - if max_start < first { - 0 - } else { - (max_start - first) / 2 + 1 - } -} - -fn eligible_target_index( - mode: TrainingMode, - start_turn: Color, - plies: usize, - order: usize, -) -> Option { - let mut remaining = order; - for index in 0..=random_max_start(plies) { - let turn = if index % 2 == 0 { - start_turn - } else { - start_turn.other() - }; - if mode.user_color().is_none_or(|color| color == turn) { - if remaining == 0 { - return Some(index); - } - remaining -= 1; - } - } - None -} - -fn coprime_step(seed: u64, count: usize) -> usize { - if count == 1 { - return 0; - } - let mut step = (mix64(seed) % count as u64) as usize; - while gcd(step, count) != 1 { - step = (step + 1) % count; - } - step -} - -fn gcd(mut left: usize, mut right: usize) -> usize { - while right != 0 { - let remainder = left % right; - left = right; - right = remainder; - } - left -} - -fn next_cycle_seed(seed: u64) -> u64 { - mix64(seed ^ 0x8ebc_6af0_9c88_c6e3) -} - -fn mix64(mut value: u64) -> u64 { - value = value.wrapping_add(0x9e37_79b9_7f4a_7c15); - value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - value ^ (value >> 31) } diff --git a/crates/trainer/src/repertoire/tests.rs b/crates/trainer/src/repertoire/tests.rs index f64c7c2..2e2516e 100644 --- a/crates/trainer/src/repertoire/tests.rs +++ b/crates/trainer/src/repertoire/tests.rs @@ -13,12 +13,6 @@ fn game(pgn: &str) -> Game { chess_core::parse_str(pgn).game } -fn repertoire(pgn: &str) -> Repertoire { - let mut library = Library::default(); - let id = library.create("Test", &game(pgn)).unwrap(); - library.repertoire(&id).unwrap().clone() -} - fn play(game: &Game, line: &[&str]) -> Vec { let mut position = game.start().position().clone(); line.iter() @@ -258,348 +252,6 @@ fn library_crud_depth_and_disable_are_persistent_data() { assert!(library.repertoire(&id).is_none()); } -#[test] -fn both_accepts_every_enabled_branch_and_rejects_outside_disabled_and_depth() { - let rep = repertoire("1. e4 (1. d4 d5) e5 (1... c5) 2. Nf3 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - assert!(session.play_uci("not-a-move", 0).is_err()); - assert!(session.play_uci("e2e5", 0).is_err()); - assert!(session.attempts().is_empty()); - assert_eq!(session.play_uci("c2c4", 1).unwrap(), TrainingVerdict::Wrong); - assert_eq!(session.current_node(), NodeId::ROOT); - assert_eq!(session.total_mistakes(), 1); - assert_eq!(session.play_uci("d2d4", 2).unwrap(), TrainingVerdict::Right); - assert_eq!( - session.play_uci("d7d5", 3).unwrap(), - TrainingVerdict::Finished - ); - let completions = session - .stats() - .runs(&rep.id, TrainingMode::Both) - .unwrap() - .completions; - assert_eq!(completions, 1); - assert_eq!(session.play_uci("d2d4", 4).unwrap(), TrainingVerdict::Done); - assert_eq!( - session - .stats() - .runs(&rep.id, TrainingMode::Both) - .unwrap() - .completions, - 1 - ); - - session.restart(10).unwrap(); - assert_eq!( - session.play_uci("e2e4", 10).unwrap(), - TrainingVerdict::Right - ); - assert_eq!( - session.play_uci("c7c5", 11).unwrap(), - TrainingVerdict::Finished - ); - - let mut disabled = rep.clone(); - disabled - .set_prefix_disabled(&["e2e4".into(), "e7e5".into()], true) - .unwrap(); - let mut session = TrainingSession::new( - &disabled, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 20, - ) - .unwrap(); - session.play_uci("e2e4", 20).unwrap(); - assert_eq!( - session.play_uci("e7e5", 21).unwrap(), - TrainingVerdict::Wrong - ); - assert_eq!( - session.play_uci("c7c5", 22).unwrap(), - TrainingVerdict::Finished - ); - - let mut shallow = rep.clone(); - shallow.set_max_plies(1); - let mut session = TrainingSession::new( - &shallow, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 30, - ) - .unwrap(); - assert_eq!( - session.play_uci("e2e4", 30).unwrap(), - TrainingVerdict::Finished - ); -} - -#[test] -fn both_hint_after_three_errors_and_completion_are_recorded_once() { - let rep = repertoire("1. e4 e5 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::SpacedRepetition, - StatsData::default(), - 0, - ) - .unwrap(); - for now in 1..=3 { - assert_eq!( - session.play_uci("d2d4", now).unwrap(), - TrainingVerdict::Wrong - ); - assert_eq!(session.current_node(), NodeId::ROOT); - } - assert!(session.may_hint()); - assert_eq!(session.hint(4).unwrap().uci, "e2e4"); - assert!(session.hinted()); - assert_eq!(session.play_uci("e2e4", 5).unwrap(), TrainingVerdict::Right); - assert_eq!( - session.play_uci("e7e5", 6).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.play_uci("e7e5", 7).unwrap(), TrainingVerdict::Done); - let stats = &session.stats().move_stats; - let e4 = stats - .iter() - .find(|entry| entry.key.position_fen4 == fen4(Game::new().start().position())) - .unwrap(); - assert_eq!((e4.attempts, e4.correct, e4.wrong, e4.hints), (4, 1, 3, 1)); - assert_eq!(e4.streak, 0); - assert_eq!(e4.recent.len(), 4); - assert_eq!(e4.recent[0].actual_uci, "d2d4"); - let runs = session.stats().runs(&rep.id, TrainingMode::Both).unwrap(); - assert_eq!(runs.completions, 1); - assert_eq!(runs.recent[0].mistakes, 3); - assert!(runs.recent[0].hinted); - assert_eq!(session.errors().count(), 3); -} - -#[test] -fn both_continues_through_a_canonical_transposition_and_shares_stats() { - let mut library = Library::default(); - let id = library.create_empty("Transpositions").unwrap(); - library - .add_game(&id, &game("1. d4 d5 2. Nf3 Nf6 3. g3 *")) - .unwrap(); - library - .add_game(&id, &game("1. Nf3 d5 2. d4 Nf6 *")) - .unwrap(); - let rep = library.repertoire(&id).unwrap().clone(); - let mut first = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for (now, mv) in ["d2d4", "d7d5", "g1f3", "g8f6", "g2g3"] - .into_iter() - .enumerate() - { - first.play_uci(mv, now as i64).unwrap(); - } - let mut second = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - first.into_stats(), - 10, - ) - .unwrap(); - second.play_uci("g1f3", 10).unwrap(); - second.play_uci("d7d5", 11).unwrap(); - second.play_uci("d2d4", 12).unwrap(); - second.play_uci("g8f6", 13).unwrap(); - assert!(second.candidates().iter().any(|c| c.uci == "g2g3")); - assert_eq!( - second.play_uci("g2g3", 14).unwrap(), - TrainingVerdict::Finished - ); - let shared = second - .stats() - .move_stats - .iter() - .filter(|entry| { - entry - .recent - .iter() - .any(|attempt| attempt.actual_uci == "g2g3") - }) - .collect::>(); - assert_eq!(shared.len(), 1); - assert_eq!(shared[0].attempts, 2); - assert_eq!(shared[0].correct, 2); -} - -struct SecondChooser; - -impl MoveChooser for SecondChooser { - fn choose(&mut self, candidates: &[Candidate]) -> Option { - (candidates.len() > 1).then_some(1).or(Some(0)) - } -} - -#[test] -fn one_side_alternative_and_injectable_chooser_do_not_count_auto_moves() { - let rep = repertoire("1. e4 (1. d4 d5) e5 (1... c5) 2. Nf3 *"); - let mut session = TrainingSession::with_chooser( - &rep, - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - Box::new(SecondChooser), - ) - .unwrap(); - assert_eq!(session.target().unwrap().expected_uci, "e2e4"); - assert_eq!(session.play_uci("e2e4", 2).unwrap(), TrainingVerdict::Right); - assert_eq!(session.path()[0].uci, "e2e4"); - assert!(!session.path()[0].automatic); - assert_eq!(session.path()[1].uci, "c7c5"); - assert!(session.path()[1].automatic); - assert_eq!(session.attempts().len(), 1); - assert_eq!(session.stats().move_stats.len(), 1); - - let black = repertoire("1. e4 e5 2. Nf3 *"); - let mut black_session = TrainingSession::new( - &black, - TrainingMode::Black, - QueueMode::ReviewInOrder, - StatsData::default(), - 10, - ) - .unwrap(); - assert_eq!(black_session.target().unwrap().expected_uci, "e7e5"); - assert_eq!(black_session.path()[0].uci, "e2e4"); - assert!(black_session.path()[0].automatic); - assert_eq!( - black_session.play_uci("e7e5", 11).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(black_session.attempts().len(), 1); - assert!( - black_session - .path() - .iter() - .any(|mv| mv.uci == "g1f3" && mv.automatic) - ); -} - -#[test] -fn srs_dates_unseen_review_order_and_least_recent_work() { - let rep = repertoire("1. e4 *"); - let mut first = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - assert_eq!( - first.play_uci("e2e4", 1_000).unwrap(), - TrainingVerdict::Finished - ); - let stats = &first.stats().move_stats[0]; - assert_eq!(stats.due, Some(1_000 + INITIAL_INTERVAL_SECONDS)); - assert_eq!(stats.streak, 1); - - let second_now = 1_000 + INITIAL_INTERVAL_SECONDS; - let mut second = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::SpacedRepetition, - first.into_stats(), - second_now, - ) - .unwrap(); - assert_eq!( - second.play_uci("e2e4", second_now).unwrap(), - TrainingVerdict::Finished - ); - let stats = &second.stats().move_stats[0]; - assert_eq!(stats.due, Some(1_000 + 3 * INITIAL_INTERVAL_SECONDS)); - assert_eq!(stats.streak, 2); - assert!( - second - .stats() - .queue( - &RepertoireTree::new(&rep), - &rep.id, - TrainingMode::White, - QueueMode::SpacedRepetition, - 3_000, - ) - .is_empty() - ); - - let wrong_rep = repertoire("1. e4 *"); - let mut wrong = TrainingSession::new_srs( - &wrong_rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - wrong.play_uci("d2d4", 100).unwrap(); - let key = wrong - .target() - .map(|target| MoveKey { - repertoire_id: wrong_rep.id.clone(), - mode: TrainingMode::White, - position_fen4: target.position_fen4.clone(), - expected_uci: target.expected_uci.clone(), - }) - .unwrap(); - assert_eq!(wrong.stats().get(&key).unwrap().due, Some(700)); - wrong.play_uci("e2e4", 101).unwrap(); - assert_eq!(wrong.stats().get(&key).unwrap().due, Some(701)); - assert_eq!(wrong.stats().get(&key).unwrap().streak, 0); - - let branches = repertoire("1. e4 (1. d4 d5) e5 2. Nf3 *"); - let mut training = TrainingSession::new( - &branches, - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - training.play_uci("e2e4", 10).unwrap(); - let queue = training.stats().queue( - &RepertoireTree::new(&branches), - &branches.id, - TrainingMode::White, - QueueMode::LeastRecent, - 20, - ); - assert_eq!(queue[0].expected_uci, "d2d4"); - assert_eq!(queue.last().unwrap().expected_uci, "e2e4"); - let review = training.stats().queue( - &RepertoireTree::new(&branches), - &branches.id, - TrainingMode::White, - QueueMode::ReviewInOrder, - 20, - ); - assert_eq!(review[0].expected_uci, "d2d4"); -} - #[test] fn prefix_ignores_unparsed_tail_after_the_selected_node() { let source = game("1. e4 e4 2. d4 *"); @@ -617,146 +269,6 @@ fn prefix_ignores_unparsed_tail_after_the_selected_node() { assert_eq!(library.repertoire(&id).unwrap().pgn, before); } -#[test] -fn review_queues_record_attempts_without_changing_srs_due() { - let rep = repertoire("1. e4 *"); - let mut srs = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - srs.play_uci("e2e4", 100).unwrap(); - let original_due = srs.stats().move_stats[0].due; - assert_eq!(original_due, Some(100 + INITIAL_INTERVAL_SECONDS)); - - for queue_mode in [QueueMode::ReviewInOrder, QueueMode::LeastRecent] { - let mut review = TrainingSession::new( - &rep, - TrainingMode::White, - queue_mode, - srs.stats().clone(), - 0, - ) - .unwrap(); - review.play_uci("e2e4", 200).unwrap(); - let stats = &review.stats().move_stats[0]; - assert_eq!(stats.attempts, 2); - assert_eq!(stats.last_seen, Some(200)); - assert_eq!(stats.due, original_due); - - review.restart(201).unwrap(); - review.play_uci("d2d4", 201).unwrap(); - assert_eq!(review.stats().move_stats[0].due, original_due); - } -} - -#[test] -fn srs_retry_is_kept_until_the_next_clean_success() { - let rep = repertoire("1. e4 *"); - let mut session = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - session.play_uci("d2d4", 100).unwrap(); - session.play_uci("e2e4", 101).unwrap(); - let stats = &session.stats().move_stats[0]; - assert_eq!(stats.due, Some(101 + MISTAKE_INTERVAL_SECONDS)); - assert_eq!(stats.streak, 0); - - session.restart_with_policy(701, SrsPolicy::Due).unwrap(); - session.play_uci("e2e4", 701).unwrap(); - let stats = &session.stats().move_stats[0]; - assert_eq!(stats.due, Some(701 + INITIAL_INTERVAL_SECONDS)); - assert_eq!(stats.streak, 1); - - session.restart(701 + INITIAL_INTERVAL_SECONDS).unwrap(); - session - .play_uci("e2e4", 701 + INITIAL_INTERVAL_SECONDS) - .unwrap(); - let stats = &session.stats().move_stats[0]; - assert_eq!(stats.due, Some(701 + 3 * INITIAL_INTERVAL_SECONDS)); - assert_eq!(stats.streak, 2); -} - -#[test] -fn both_attempts_never_create_srs_due() { - let rep = repertoire("1. e4 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - session.play_uci("d2d4", 100).unwrap(); - session.play_uci("e2e4", 101).unwrap(); - assert!( - session - .stats() - .move_stats - .iter() - .all(|stats| stats.due.is_none()) - ); -} - -#[test] -fn stats_are_isolated_by_mode_and_repertoire() { - let first_rep = repertoire("1. e4 *"); - let second_rep = repertoire("1. e4 *"); - let mut white = TrainingSession::new( - &first_rep, - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - white.play_uci("e2e4", 1).unwrap(); - let mut both = TrainingSession::new( - &first_rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - white.into_stats(), - 2, - ) - .unwrap(); - both.play_uci("e2e4", 2).unwrap(); - let mut other = TrainingSession::new( - &second_rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - both.into_stats(), - 3, - ) - .unwrap(); - other.play_uci("e2e4", 3).unwrap(); - assert_eq!(other.stats().move_stats.len(), 3); - assert!( - other - .stats() - .move_stats - .iter() - .any(|entry| entry.key.mode == TrainingMode::White) - ); - assert_eq!( - other - .stats() - .move_stats - .iter() - .filter(|entry| entry.key.mode == TrainingMode::Both) - .count(), - 2 - ); -} - #[test] fn library_store_roundtrip_errors_and_conflicts_are_visible() { let dir = temp_dir("library-store"); @@ -866,39 +378,7 @@ fn stats_store_write_failure_does_not_replace_legacy_or_report_success() { } #[test] -fn session_stats_can_be_saved_after_every_run() { - let dir = temp_dir("session-save"); - let store = StatsStore::new(dir.join("stats.json")); - let rep = repertoire("1. e4 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::ReviewInOrder, - store.load().unwrap(), - 0, - ) - .unwrap(); - session.play_uci("e2e4", 10).unwrap(); - store.save(session.stats_mut()).unwrap(); - assert_eq!(session.stats().revision, 1); - session.restart(20).unwrap(); - session.play_uci("e2e4", 20).unwrap(); - store.save(session.stats_mut()).unwrap(); - assert_eq!(session.stats().revision, 2); - assert_eq!( - store - .load() - .unwrap() - .runs(&rep.id, TrainingMode::White) - .unwrap() - .completions, - 2 - ); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn adding_training_and_deleting_never_touches_the_source_file() { +fn adding_and_deleting_never_touches_the_source_file() { let dir = temp_dir("source-file"); let source_path = dir.join("legacy.pgn"); let bytes = b"[Event \"Legacy\"]\n\n1. e4 c5 2. Nf3 d6 *\n\xff"; @@ -908,19 +388,21 @@ fn adding_training_and_deleting_never_touches_the_source_file() { let id = library.create_empty("Snapshot").unwrap(); let at = source.mainline()[3]; library.add_prefix(&id, &source, at).unwrap(); - let rep = library.repertoire(&id).unwrap().clone(); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for (now, mv) in ["e2e4", "c7c5", "g1f3", "d7d6"].into_iter().enumerate() { - session.play_uci(mv, now as i64).unwrap(); - } library.delete(&id).unwrap(); assert_eq!(std::fs::read(&source_path).unwrap(), bytes); let _ = std::fs::remove_dir_all(dir); } + +#[test] +fn v2_stats_without_the_random_cursor_field_still_read_and_save() { + let mut old = serde_json::to_value(StatsData::default()).unwrap(); + assert!( + old.as_object_mut() + .unwrap() + .remove("random_practice_cursors") + .is_some() + ); + let stats: StatsData = serde_json::from_value(old).unwrap(); + let saved = serde_json::to_value(&stats).unwrap(); + assert!(saved["random_practice_cursors"].is_array()); +} diff --git a/crates/trainer/src/repertoire/tree.rs b/crates/trainer/src/repertoire/tree.rs index 70d25a0..ffeab12 100644 --- a/crates/trainer/src/repertoire/tree.rs +++ b/crates/trainer/src/repertoire/tree.rs @@ -1,7 +1,7 @@ use std::collections::{BTreeMap, BTreeSet}; use chess_core::shakmaty::fen::Fen; -use chess_core::shakmaty::{CastlingMode, Chess, Color, EnPassantMode, Move, Position}; +use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Position}; use chess_core::{Game, MoveKind, NodeId}; use super::model::Repertoire; @@ -20,25 +20,7 @@ pub fn fen4(position: &Chess) -> String { #[derive(Clone, Debug)] pub struct Candidate { - pub mv: Move, pub uci: String, - pub san: String, - /// The selected PGN path. Other paths to the same move remain in the tree. - pub node: NodeId, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct TrainingTarget { - pub position_fen4: String, - pub expected_uci: String, - /// One deterministic PGN path used to reach the target as context. - pub path: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct TrainingPath { - /// Actual moves from the beginning of the scope through its boundary, inclusive. - pub moves: Vec, } #[derive(Clone, Debug)] @@ -88,10 +70,6 @@ impl RepertoireTree { } } - pub(crate) fn max_plies(&self) -> u32 { - self.max_plies - } - pub fn game(&self) -> &Game { &self.game } @@ -137,21 +115,6 @@ impl RepertoireTree { self.candidates_impl(at, None) } - pub fn scoped_candidates(&self, at: NodeId, scope: &TrainingScope) -> Vec { - self.candidates_impl(at, Some(scope)) - } - - pub fn scoped_candidate( - &self, - at: NodeId, - uci: &str, - scope: &TrainingScope, - ) -> Option { - self.scoped_candidates(at, scope) - .into_iter() - .find(|candidate| candidate.uci == uci) - } - fn candidates_impl(&self, at: NodeId, scope: Option<&TrainingScope>) -> Vec { if !self.is_trainable_path(at) || self @@ -193,12 +156,7 @@ impl RepertoireTree { } let uci = mv.to_uci(CastlingMode::Standard).to_string(); if seen.insert(uci.clone()) { - out.push(Candidate { - mv, - uci, - san: game_move.san.clone(), - node: *child, - }); + out.push(Candidate { uci }); } } } @@ -211,48 +169,6 @@ impl RepertoireTree { .find(|candidate| candidate.uci == uci) } - /// All one-side targets in deterministic PGN order, deduplicated by FEN4/UCI. - pub fn targets(&self, side: Color) -> Vec { - self.targets_impl(side, None) - } - - pub fn scoped_targets(&self, side: Color, scope: &TrainingScope) -> Vec { - self.targets_impl(side, Some(scope)) - } - - fn targets_impl(&self, side: Color, scope: Option<&TrainingScope>) -> Vec { - let mut seen = BTreeSet::new(); - let mut out = Vec::new(); - for node in self.game.attached_nodes() { - if !self.scope_allows_parent(node, scope) { - continue; - } - if self.game.position(node).is_none_or(|p| p.turn() != side) { - continue; - } - let Some(path) = self.path(node).map(<[String]>::to_vec) else { - continue; - }; - let Some(position_fen4) = self.position_key(node).map(str::to_owned) else { - continue; - }; - let candidates = match scope { - Some(scope) => self.scoped_candidates(node, scope), - None => self.candidates(node), - }; - for candidate in candidates { - if seen.insert((position_fen4.clone(), candidate.uci.clone())) { - out.push(TrainingTarget { - position_fen4: position_fen4.clone(), - expected_uci: candidate.uci, - path: path.clone(), - }); - } - } - } - out - } - /// Follows a normal UCI path on the actual PGN tree. No transposition jump is made /// while replaying context, so the selected target path remains exact. pub fn node_at_path(&self, path: &[String]) -> Option { @@ -295,35 +211,6 @@ impl RepertoireTree { Ok(anchor) } - /// Generates actual scope-to-boundary routes in PGN depth-first order. Repeated FEN4 - /// positions are included as the final move and never expanded again. - pub fn training_paths(&self, scope: &TrainingScope) -> Result, String> { - let mut paths = Vec::new(); - self.visit_training_paths(scope, |moves| { - paths.push(TrainingPath { - moves: moves.to_vec(), - }); - std::ops::ControlFlow::Continue(()) - })?; - Ok(paths) - } - - /// Streams routes in the same order as `training_paths`, retaining only the active - /// route and its position history. A visitor may stop without expanding the rest. - pub fn visit_training_paths( - &self, - scope: &TrainingScope, - mut visit: impl FnMut(&[String]) -> std::ops::ControlFlow<()>, - ) -> Result<(), String> { - let anchor = self.scope_anchor(scope)?; - let mut positions = BTreeSet::new(); - if let Some(key) = self.position_key(anchor) { - positions.insert(key.to_owned()); - } - let _ = self.visit_paths(anchor, scope, &mut Vec::new(), &mut positions, &mut visit); - Ok(()) - } - /// Streams the routes explicitly present in PGN, without importing continuations /// from other paths that reach the same position. pub fn visit_source_paths( @@ -370,63 +257,6 @@ impl RepertoireTree { } } - pub fn training_path_count(&self, scope: &TrainingScope) -> Result { - let mut count = Some(0usize); - self.visit_training_paths(scope, |_| { - count = count.and_then(|count| count.checked_add(1)); - if count.is_none() { - std::ops::ControlFlow::Break(()) - } else { - std::ops::ControlFlow::Continue(()) - } - })?; - count.ok_or_else(|| "training path count exceeds the platform limit".to_owned()) - } - - fn visit_paths( - &self, - at: NodeId, - scope: &TrainingScope, - current: &mut Vec, - positions: &mut BTreeSet, - visit: &mut impl FnMut(&[String]) -> std::ops::ControlFlow<()>, - ) -> std::ops::ControlFlow<()> { - let candidates = if scope.parent_prefix().len() + current.len() >= self.max_plies as usize { - Vec::new() - } else { - self.scoped_candidates(at, scope) - }; - if candidates.is_empty() { - return if current.is_empty() { - std::ops::ControlFlow::Continue(()) - } else { - visit(current) - }; - } - // Each position has distinct UCI candidates, so each complete UCI route is - // unique even when its continuation crosses a transposition. - for candidate in candidates { - current.push(candidate.uci.clone()); - let key = self.position_key(candidate.node); - let repeated = key.is_some_and(|key| positions.contains(key)); - let result = if repeated { - visit(current) - } else { - if let Some(key) = key { - positions.insert(key.to_owned()); - } - let result = self.visit_paths(candidate.node, scope, current, positions, visit); - if let Some(key) = key { - positions.remove(key); - } - result - }; - current.pop(); - result?; - } - std::ops::ControlFlow::Continue(()) - } - fn scope_allows_parent(&self, at: NodeId, scope: Option<&TrainingScope>) -> bool { let Some(scope) = scope else { return true;