feat: add opening repertoire training

This commit is contained in:
vrubelroman 2026-11-03 00:03:51 +03:00
parent 4eb0822ec6
commit f49aab68fa
36 changed files with 13389 additions and 90 deletions

View file

@ -9,6 +9,8 @@
//! position and moves), so they survive edits of the game and are shared between games
//! with the same line, in the file the app names ([`set_file`]).
pub mod repertoire;
use std::path::PathBuf;
use std::sync::Mutex;
use std::time::Duration;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,32 @@
//! Versioned opening repertoires, tree training and their persistent stores.
//!
//! This module is independent from the legacy line trainer in the crate root.
mod model;
mod scope;
mod session;
mod stats;
mod store;
mod tree;
pub use model::{
DEFAULT_MAX_PLIES, LIBRARY_VERSION, LegacyMigrationReport, Library, MergeReport, Repertoire,
RepertoireError, RepertoireId,
};
pub use scope::{TrainingScope, TrainingScopeKey};
pub use session::{
FirstMoveChooser, MoveChooser, PlayedMove, SessionAttempt, SessionError, TrainingSession,
TrainingVerdict,
};
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,
};
pub use store::{LibraryStore, StatsStore, StoreError};
pub use tree::{Candidate, RepertoireTree, TrainingPath, TrainingTarget, fen4};
#[cfg(test)]
mod advanced_tests;
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,661 @@
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use chess_core::shakmaty::uci::UciMove;
use chess_core::{EditError, Game, MoveKind, NodeId, StartPosition, paste};
use serde::{Deserialize, Serialize};
use web_time::{SystemTime, UNIX_EPOCH};
use super::tree::fen4;
pub const LIBRARY_VERSION: u32 = 1;
pub const DEFAULT_MAX_PLIES: u32 = 20;
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RepertoireId(String);
impl RepertoireId {
pub fn as_str(&self) -> &str {
&self.0
}
fn new() -> Self {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
let sequence = NEXT_ID.fetch_add(1, Ordering::Relaxed);
Self(format!("r-{nanos:x}-{}-{sequence:x}", std::process::id()))
}
pub(crate) fn legacy(start: &str) -> Self {
Self(format!("legacy-{:016x}", stable_hash(start.as_bytes())))
}
}
impl fmt::Display for RepertoireId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Repertoire {
pub id: RepertoireId,
pub name: String,
pub pgn: String,
pub max_plies: u32,
pub disabled_prefixes: Vec<Vec<String>>,
pub path: Option<PathBuf>,
pub detached: bool,
}
impl Default for Repertoire {
fn default() -> Self {
Self {
id: RepertoireId::new(),
name: String::new(),
pgn: Game::new().to_pgn(),
max_plies: DEFAULT_MAX_PLIES,
disabled_prefixes: Vec::new(),
path: None,
detached: false,
}
}
}
impl Repertoire {
pub fn game(&self) -> Game {
chess_core::parse_str(&self.pgn).game
}
pub fn set_max_plies(&mut self, max_plies: u32) {
self.max_plies = max_plies;
}
pub fn set_prefix_disabled(
&mut self,
prefix: &[String],
disabled: bool,
) -> Result<(), RepertoireError> {
if prefix.is_empty() || prefix.iter().any(|m| m.is_empty()) {
return Err(RepertoireError::EmptyDisabledPrefix);
}
self.disabled_prefixes
.retain(|existing| existing.as_slice() != prefix);
if disabled {
self.disabled_prefixes.push(prefix.to_vec());
}
self.disabled_prefixes.sort();
self.disabled_prefixes.dedup();
Ok(())
}
pub fn is_prefix_disabled(&self, path: &[String]) -> bool {
self.disabled_prefixes
.iter()
.any(|prefix| path.starts_with(prefix))
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Library {
pub version: u32,
pub revision: u64,
pub repertoires: Vec<Repertoire>,
}
impl Default for Library {
fn default() -> Self {
Self {
version: LIBRARY_VERSION,
revision: 0,
repertoires: Vec::new(),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MergeReport {
pub added_nodes: usize,
pub merged_nodes: usize,
pub annotation_changes: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LegacyMigrationReport {
pub repertoires: usize,
pub lines: usize,
pub skipped: Vec<String>,
}
#[derive(Debug)]
pub enum RepertoireError {
EmptyName,
NotFound(RepertoireId),
DuplicateId(RepertoireId),
EmptyDisabledPrefix,
DifferentStart { expected: String, actual: String },
UnparsedMerge,
Merge(String),
Edit(EditError),
}
impl fmt::Display for RepertoireError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyName => f.write_str("repertoire name must not be empty"),
Self::NotFound(id) => write!(f, "repertoire not found: {id}"),
Self::DuplicateId(id) => write!(f, "repertoire id is already present: {id}"),
Self::EmptyDisabledPrefix => f.write_str("disabled UCI prefix must not be empty"),
Self::DifferentStart { expected, actual } => write!(
f,
"different starting positions: repertoire has {expected}, imported game has {actual}"
),
Self::UnparsedMerge => {
f.write_str("cannot merge an unparsed PGN tail into an existing move")
}
Self::Merge(message) => write!(f, "PGN merge failed: {message}"),
Self::Edit(error) => error.fmt(f),
}
}
}
impl std::error::Error for RepertoireError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Edit(error) => Some(error),
_ => None,
}
}
}
impl From<EditError> for RepertoireError {
fn from(error: EditError) -> Self {
Self::Edit(error)
}
}
impl Library {
pub fn validate(&self) -> Result<(), RepertoireError> {
let mut ids = BTreeSet::new();
for repertoire in &self.repertoires {
if !ids.insert(repertoire.id.clone()) {
return Err(RepertoireError::DuplicateId(repertoire.id.clone()));
}
}
Ok(())
}
pub fn repertoire(&self, id: &RepertoireId) -> Option<&Repertoire> {
self.repertoires.iter().find(|r| &r.id == id)
}
pub fn repertoire_mut(&mut self, id: &RepertoireId) -> Option<&mut Repertoire> {
self.repertoires.iter_mut().find(|r| &r.id == id)
}
pub fn create_empty(
&mut self,
name: impl Into<String>,
) -> Result<RepertoireId, RepertoireError> {
self.create(name, &Game::new())
}
pub fn create(
&mut self,
name: impl Into<String>,
game: &Game,
) -> Result<RepertoireId, RepertoireError> {
let name = checked_name(name.into())?;
let id = RepertoireId::new();
self.repertoires.push(Repertoire {
id: id.clone(),
name,
pgn: game.to_pgn(),
max_plies: DEFAULT_MAX_PLIES,
disabled_prefixes: Vec::new(),
path: None,
detached: false,
});
Ok(id)
}
pub fn rename(
&mut self,
id: &RepertoireId,
name: impl Into<String>,
) -> Result<(), RepertoireError> {
let name = checked_name(name.into())?;
self.repertoire_mut(id)
.ok_or_else(|| RepertoireError::NotFound(id.clone()))?
.name = name;
Ok(())
}
pub fn delete(&mut self, id: &RepertoireId) -> Result<Repertoire, RepertoireError> {
let index = self
.repertoires
.iter()
.position(|r| &r.id == id)
.ok_or_else(|| RepertoireError::NotFound(id.clone()))?;
Ok(self.repertoires.remove(index))
}
/// Merges the complete source tree. The source game is never modified; an error
/// leaves the repertoire at its previous PGN snapshot.
pub fn add_game(
&mut self,
id: &RepertoireId,
source: &Game,
) -> Result<MergeReport, RepertoireError> {
let repertoire = self
.repertoire_mut(id)
.ok_or_else(|| RepertoireError::NotFound(id.clone()))?;
let mut target = repertoire.game();
check_start(&target, source)?;
let target_is_empty = target.children(NodeId::ROOT).is_empty()
&& target.node(NodeId::ROOT).is_some_and(|root| {
root.nags().is_empty()
&& root.comments_before().is_empty()
&& root.comments_after().is_empty()
&& root.unparsed().is_empty()
});
if target_is_empty {
repertoire.pgn = source.to_pgn();
return Ok(MergeReport {
added_nodes: source.attached_nodes().len().saturating_sub(1),
merged_nodes: 1,
annotation_changes: 0,
});
}
let mut report = MergeReport::default();
merge_annotations(&mut target, NodeId::ROOT, source, NodeId::ROOT, &mut report)?;
report.merged_nodes += 1;
merge_children(
&mut target,
NodeId::ROOT,
source,
NodeId::ROOT,
true,
&mut report,
)?;
repertoire.pgn = target.to_pgn();
Ok(report)
}
/// Adds exactly the path from the source root through `at`, without siblings or
/// descendants of `at`. Node comments and NAGs on the selected path are merged.
pub fn add_prefix(
&mut self,
id: &RepertoireId,
source: &Game,
at: NodeId,
) -> Result<MergeReport, RepertoireError> {
if !source.is_attached(at) {
return Err(RepertoireError::Merge(
"selected source node is not attached".into(),
));
}
let repertoire = self
.repertoire_mut(id)
.ok_or_else(|| RepertoireError::NotFound(id.clone()))?;
let mut target = repertoire.game();
check_start(&target, source)?;
let mut report = MergeReport::default();
merge_annotations(&mut target, NodeId::ROOT, source, NodeId::ROOT, &mut report)?;
report.merged_nodes += 1;
let mut target_parent = NodeId::ROOT;
for source_node in source.path(at).into_iter().skip(1) {
target_parent = merge_node(
&mut target,
target_parent,
source,
source_node,
false,
&mut report,
)?;
}
repertoire.pgn = target.to_pgn();
Ok(report)
}
/// Deterministically reconstructs playable lines stored in legacy line keys. The
/// legacy aggregates remain in `StatsData::legacy_lines`; no per-move history is
/// inferred from them.
pub fn migrate_legacy_lines(
&mut self,
legacy: &serde_json::Map<String, serde_json::Value>,
) -> LegacyMigrationReport {
let mut groups: BTreeMap<String, Vec<Vec<String>>> = BTreeMap::new();
let mut report = LegacyMigrationReport::default();
for key in legacy.keys() {
let Some((start, moves)) = key.split_once(" | ") else {
report.skipped.push(key.clone());
continue;
};
let line: Vec<String> = moves
.split_whitespace()
.filter(|m| !m.is_empty())
.map(str::to_owned)
.collect();
if line.is_empty() || line.iter().any(|m| m.parse::<UciMove>().is_err()) {
report.skipped.push(key.clone());
continue;
}
groups.entry(start.to_owned()).or_default().push(line);
}
for (start, mut lines) in groups {
lines.sort();
lines.dedup();
let id = RepertoireId::legacy(&start);
if self.repertoire(&id).is_none() {
let Ok(position) = StartPosition::from_fen(&format!("{start} 0 1")) else {
report
.skipped
.extend(lines.into_iter().map(|line| line.join(" ")));
continue;
};
let number = self
.repertoires
.iter()
.filter(|r| r.id.as_str().starts_with("legacy-"))
.count()
+ 1;
self.repertoires.push(Repertoire {
id: id.clone(),
name: format!("Перенесённые линии {number}"),
pgn: Game::from_start(position).to_pgn(),
max_plies: DEFAULT_MAX_PLIES,
disabled_prefixes: Vec::new(),
path: None,
detached: false,
});
report.repertoires += 1;
}
let Some(mut game) = self.repertoire(&id).map(Repertoire::game) else {
continue;
};
for line in lines {
match game.add_uci_line(NodeId::ROOT, &line) {
Ok(_) => report.lines += 1,
Err(_) => report.skipped.push(line.join(" ")),
}
}
if let Some(repertoire) = self.repertoire_mut(&id) {
repertoire.pgn = game.to_pgn();
}
}
report
}
}
fn checked_name(name: String) -> Result<String, RepertoireError> {
let name = name.trim();
if name.is_empty() {
Err(RepertoireError::EmptyName)
} else {
Ok(name.to_owned())
}
}
fn check_start(target: &Game, source: &Game) -> Result<(), RepertoireError> {
let expected = fen4(target.start().position());
let actual = fen4(source.start().position());
if expected == actual {
Ok(())
} else {
Err(RepertoireError::DifferentStart { expected, actual })
}
}
fn merge_children(
target: &mut Game,
target_parent: NodeId,
source: &Game,
source_parent: NodeId,
recursive: bool,
report: &mut MergeReport,
) -> Result<(), RepertoireError> {
for source_child in source.children(source_parent) {
merge_node(
target,
target_parent,
source,
*source_child,
recursive,
report,
)?;
}
Ok(())
}
fn merge_node(
target: &mut Game,
target_parent: NodeId,
source: &Game,
source_node: NodeId,
recursive: bool,
report: &mut MergeReport,
) -> Result<NodeId, RepertoireError> {
let kind = source
.game_move(source_node)
.map(|m| m.kind)
.ok_or_else(|| RepertoireError::Merge("source node has no move".into()))?;
if let Some(existing) = target
.children(target_parent)
.iter()
.copied()
.find(|child| target.game_move(*child).is_some_and(|m| m.kind == kind))
{
report.merged_nodes += 1;
merge_annotations(target, existing, source, source_node, report)?;
if recursive {
merge_unparsed(target, existing, source, source_node)?;
}
if recursive {
merge_children(target, existing, source, source_node, true, report)?;
}
return Ok(existing);
}
let plain = matches!(kind, MoveKind::Normal(_))
&& source
.node(source_node)
.is_some_and(|n| n.unparsed().is_empty());
let target_node = if plain {
let MoveKind::Normal(mv) = kind else {
return Err(RepertoireError::Merge("invalid normal move".into()));
};
let id = target.add_line(target_parent, &[mv])?;
merge_annotations(target, id, source, source_node, report)?;
report.added_nodes += 1;
id
} else {
let text = subtree_pgn(source, source_node, recursive, recursive);
// Clipboard matching searches the entire target for a matching position and
// may choose another occurrence. An empty local target makes the graft exact:
// no matched prefix, transposition or extra branch can redirect the insertion.
let fen = target
.fen(target_parent)
.ok_or_else(|| RepertoireError::Merge("missing target parent position".into()))?;
let start = StartPosition::from_fen(&fen)
.map_err(|error| RepertoireError::Merge(error.to_string()))?;
let local = Game::from_start(start);
let mut plan = paste::plan(&local, NodeId::ROOT, &text)
.map_err(|e| RepertoireError::Merge(format!("{e:?}")))?;
if plan.at != NodeId::ROOT {
return Err(RepertoireError::Merge(
"PGN graft did not start at its root".into(),
));
}
plan.at = target_parent;
plan.continuation = target.children(target_parent).is_empty();
let id = target.apply_paste(&plan)?;
let count = if recursive {
subtree_len(source, source_node)
} else {
1
};
report.added_nodes += count;
id
};
if plain && recursive {
merge_children(target, target_node, source, source_node, true, report)?;
}
Ok(target_node)
}
fn merge_unparsed(
target: &Game,
target_node: NodeId,
source: &Game,
source_node: NodeId,
) -> Result<(), RepertoireError> {
let Some(source_node) = source.node(source_node) else {
return Ok(());
};
if source_node.unparsed().is_empty() {
return Ok(());
}
if target
.node(target_node)
.is_some_and(|node| node.unparsed() == source_node.unparsed())
{
Ok(())
} else {
Err(RepertoireError::UnparsedMerge)
}
}
fn subtree_len(game: &Game, root: NodeId) -> usize {
let mut stack = vec![root];
let mut count = 0;
while let Some(node) = stack.pop() {
count += 1;
stack.extend(game.children(node));
}
count
}
fn merge_annotations(
target: &mut Game,
target_node: NodeId,
source: &Game,
source_node: NodeId,
report: &mut MergeReport,
) -> Result<(), RepertoireError> {
let (Some(source_node), Some(current)) = (source.node(source_node), target.node(target_node))
else {
return Err(RepertoireError::Merge("missing annotation node".into()));
};
let nags = union(current.nags().to_vec(), source_node.nags().to_vec());
let before = union(
current.comments_before().to_vec(),
source_node.comments_before().to_vec(),
);
let after = union(
current.comments_after().to_vec(),
source_node.comments_after().to_vec(),
);
let changed = nags.len() != current.nags().len()
|| before.len() != current.comments_before().len()
|| after.len() != current.comments_after().len();
target.annotate(target_node, nags, after)?;
target.set_comments_before(target_node, before)?;
report.annotation_changes += usize::from(changed);
Ok(())
}
fn union<T: Clone + PartialEq>(mut target: Vec<T>, source: Vec<T>) -> Vec<T> {
for value in source {
if !target.contains(&value) {
target.push(value);
}
}
target
}
fn subtree_pgn(source: &Game, node: NodeId, recursive: bool, raw: bool) -> String {
let fen = source
.position_before(node)
.map(|p| {
chess_core::shakmaty::fen::Fen::from_position(
p,
chess_core::shakmaty::EnPassantMode::Legal,
)
})
.map(|f| f.to_string())
.unwrap_or_else(|| source.start().fen());
let mut out = format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n");
write_move(source, node, &mut out, raw);
if recursive {
write_line(source, node, &mut out);
}
out.push_str(" *\n");
out
}
fn write_line(game: &Game, parent: NodeId, out: &mut String) {
let mut current = parent;
while let Some(main) = game.children(current).first().copied() {
write_move(game, main, out, true);
for alternative in game.children(current).iter().skip(1) {
out.push_str(" (");
write_move(game, *alternative, out, true);
write_line(game, *alternative, out);
out.push(')');
}
current = main;
}
}
fn write_move(game: &Game, node: NodeId, out: &mut String, raw: bool) {
let Some(data) = game.node(node) else {
return;
};
for comment in data.comments_before() {
write_comment(comment, out);
}
if let Some(mv) = data.game_move() {
out.push(' ');
out.push_str(&mv.san);
}
for nag in data.nags() {
out.push_str(&format!(" ${}", nag.0));
}
for comment in data.comments_after() {
write_comment(comment, out);
}
if raw {
for text in data.unparsed() {
out.push(' ');
out.push_str(text);
}
}
}
fn write_comment(comment: &str, out: &mut String) {
if comment.contains('}') {
for line in comment.lines() {
out.push_str(&format!("\n;{}\n", line.trim()));
}
} else {
out.push_str(&format!(" {{{comment}}}"));
}
}
fn stable_hash(bytes: &[u8]) -> u64 {
let mut hash = 0xcbf29ce484222325_u64;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}

View file

@ -0,0 +1,70 @@
use serde::{Deserialize, Serialize};
/// A durable training area. The selected move is included; `end_prefix`, when present,
/// is also included and forms an early boundary. Node IDs never participate.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(default)]
pub struct TrainingScope {
pub prefix: Vec<String>,
pub end_prefix: Option<Vec<String>>,
/// Replay the path before the selected move/target as automatic context.
pub include_context: bool,
}
impl TrainingScope {
pub fn whole() -> Self {
Self::default()
}
pub fn from_prefix(prefix: Vec<String>) -> Self {
Self {
prefix,
..Self::default()
}
}
pub fn between(prefix: Vec<String>, end_prefix: Vec<String>) -> 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))
.unwrap_or(&[])
}
}
impl Default for TrainingScope {
fn default() -> Self {
Self {
prefix: Vec::new(),
end_prefix: None,
include_context: true,
}
}
}
/// Identity of a training area for queues and history. Context presentation deliberately
/// does not split learning data.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(default)]
pub struct TrainingScopeKey {
pub prefix: Vec<String>,
pub end_prefix: Option<Vec<String>>,
}

View file

@ -0,0 +1,983 @@
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<usize>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct FirstMoveChooser;
impl MoveChooser for FirstMoveChooser {
fn choose(&mut self, candidates: &[Candidate]) -> Option<usize> {
(!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,
srs_policy: SrsPolicy,
tree: RepertoireTree,
stats: StatsData,
chooser: Box<dyn MoveChooser>,
current: NodeId,
position: Chess,
target: Option<TrainingTarget>,
suggested_path: Option<TrainingPath>,
seen_positions: BTreeSet<String>,
actual_path: Vec<String>,
done: bool,
completion_recorded: bool,
current_wrong: u32,
current_hinted: bool,
hint_visible: bool,
run_hinted: bool,
mistakes: u32,
hints: u32,
path: Vec<PlayedMove>,
attempts: Vec<SessionAttempt>,
completed_targets: BTreeSet<MoveKey>,
deferred_targets: BTreeSet<MoveKey>,
}
impl TrainingSession {
pub fn new(
repertoire: &Repertoire,
mode: TrainingMode,
queue_mode: QueueMode,
stats: StatsData,
now: i64,
) -> Result<Self, SessionError> {
Self::with_chooser(
repertoire,
mode,
queue_mode,
stats,
now,
Box::<FirstMoveChooser>::default(),
)
}
pub fn with_chooser(
repertoire: &Repertoire,
mode: TrainingMode,
queue_mode: QueueMode,
stats: StatsData,
now: i64,
chooser: Box<dyn MoveChooser>,
) -> Result<Self, SessionError> {
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, SessionError> {
Self::scoped_with_chooser(
repertoire,
scope,
mode,
queue_mode,
stats,
now,
Box::<FirstMoveChooser>::default(),
)
}
pub fn new_srs(
repertoire: &Repertoire,
mode: TrainingMode,
stats: StatsData,
now: i64,
policy: SrsPolicy,
) -> Result<Self, SessionError> {
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, SessionError> {
Self::scoped_srs_with_chooser(
repertoire,
scope,
mode,
stats,
now,
policy,
Box::<FirstMoveChooser>::default(),
)
}
pub fn scoped_with_chooser(
repertoire: &Repertoire,
scope: TrainingScope,
mode: TrainingMode,
queue_mode: QueueMode,
stats: StatsData,
now: i64,
chooser: Box<dyn MoveChooser>,
) -> Result<Self, SessionError> {
Self::build(
repertoire,
scope,
mode,
queue_mode,
stats,
now,
(None, chooser),
)
}
pub fn scoped_srs_with_chooser(
repertoire: &Repertoire,
scope: TrainingScope,
mode: TrainingMode,
stats: StatsData,
now: i64,
policy: SrsPolicy,
chooser: Box<dyn MoveChooser>,
) -> Result<Self, SessionError> {
Self::build(
repertoire,
scope,
mode,
QueueMode::SpacedRepetition,
stats,
now,
(Some(policy), chooser),
)
}
fn build(
repertoire: &Repertoire,
scope: TrainingScope,
mode: TrainingMode,
queue_mode: QueueMode,
stats: StatsData,
now: i64,
options: (Option<SrsPolicy>, Box<dyn MoveChooser>),
) -> Result<Self, SessionError> {
let (policy, chooser) = options;
if policy.is_some()
&& (mode == TrainingMode::Both || queue_mode != QueueMode::SpacedRepetition)
{
return Err(SessionError::InvalidSrsPolicy);
}
let tree = 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,
scope,
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<Candidate> {
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<Item = &SessionAttempt> {
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<Candidate> {
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<TrainingVerdict, SessionError> {
if self.done {
return Ok(TrainingVerdict::Done);
}
let parsed = uci
.parse::<UciMove>()
.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<TrainingVerdict, SessionError> {
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 the Both 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)
}
/// 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",
));
}
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 {
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 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<TrainingVerdict, SessionError> {
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<TrainingVerdict, SessionError> {
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<bool, SessionError> {
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,
);
}
}
}

View file

@ -0,0 +1,846 @@
use chess_core::shakmaty::Color;
use serde::{Deserialize, Serialize};
use super::model::RepertoireId;
use super::scope::{TrainingScope, TrainingScopeKey};
use super::tree::{RepertoireTree, TrainingPath, TrainingTarget};
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;
const RECENT: usize = 10;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum TrainingMode {
White,
Black,
Both,
}
impl TrainingMode {
pub fn user_color(self) -> Option<Color> {
match self {
Self::White => Some(Color::White),
Self::Black => Some(Color::Black),
Self::Both => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum QueueMode {
Practice,
SpacedRepetition,
ReviewInOrder,
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,
pub mode: TrainingMode,
pub position_fen4: String,
pub expected_uci: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttemptRecord {
pub at: i64,
pub correct: bool,
pub hinted: bool,
/// The actual legal input, including a wrong move outside the repertoire.
pub actual_uci: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct MoveStats {
pub key: MoveKey,
pub attempts: u32,
pub correct: u32,
pub wrong: u32,
pub hints: u32,
/// Positive: clean correct answers in a row. Negative: wrong answers in a row.
pub streak: i32,
pub recent: Vec<AttemptRecord>,
pub last_attempt: Option<i64>,
pub last_seen: Option<i64>,
pub due: Option<i64>,
/// Scheduled interval, independent of observations during non-scheduling reviews.
pub interval_seconds: Option<i64>,
}
impl Default for MoveStats {
fn default() -> Self {
Self {
key: MoveKey {
repertoire_id: RepertoireId::legacy(""),
mode: TrainingMode::Both,
position_fen4: String::new(),
expected_uci: String::new(),
},
attempts: 0,
correct: 0,
wrong: 0,
hints: 0,
streak: 0,
recent: Vec::new(),
last_attempt: None,
last_seen: None,
due: None,
interval_seconds: None,
}
}
}
impl MoveStats {
pub fn new(key: MoveKey) -> Self {
Self {
key,
..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)]
pub struct RunRecord {
pub at: i64,
pub mistakes: u32,
pub hints: u32,
pub hinted: bool,
pub path: Vec<String>,
pub user_attempts: u32,
pub automatic_moves: u32,
#[serde(default)]
pub scope: TrainingScopeKey,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct RunStats {
pub repertoire_id: RepertoireId,
pub mode: TrainingMode,
pub completions: u32,
pub last: Option<i64>,
pub recent: Vec<RunRecord>,
}
impl Default for RunStats {
fn default() -> Self {
Self {
repertoire_id: RepertoireId::legacy(""),
mode: TrainingMode::Both,
completions: 0,
last: None,
recent: Vec::new(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PathKey {
pub repertoire_id: RepertoireId,
pub scope: TrainingScopeKey,
pub path: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PathStats {
pub key: PathKey,
pub completions: u32,
pub mistakes: u32,
pub hints: u32,
pub last_seen: Option<i64>,
pub last_completion: Option<i64>,
pub recent: Vec<RunRecord>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct ReviewCursor {
repertoire_id: RepertoireId,
mode: TrainingMode,
#[serde(default)]
scope: TrainingScopeKey,
next: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct PathReviewCursor {
repertoire_id: RepertoireId,
scope: TrainingScopeKey,
next: usize,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct StatsData {
pub version: u32,
pub revision: u64,
/// Original legacy values, retained verbatim. They are not per-move attempts.
pub legacy_lines: serde_json::Map<String, serde_json::Value>,
pub move_stats: Vec<MoveStats>,
pub runs: Vec<RunStats>,
pub path_stats: Vec<PathStats>,
review_cursors: Vec<ReviewCursor>,
path_review_cursors: Vec<PathReviewCursor>,
practice_path_cursors: Vec<ReviewCursor>,
}
impl Default for StatsData {
fn default() -> Self {
Self {
version: STATS_VERSION,
revision: 0,
legacy_lines: serde_json::Map::new(),
move_stats: Vec::new(),
runs: Vec::new(),
path_stats: Vec::new(),
review_cursors: Vec::new(),
path_review_cursors: Vec::new(),
practice_path_cursors: Vec::new(),
}
}
}
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);
}
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<TrainingTarget> {
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<TrainingTarget> {
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<TrainingTarget> {
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<Vec<TrainingPath>, 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<Option<TrainingPath>, 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)
}
/// 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<Option<TrainingPath>, 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<MoveStats> = Vec::new();
for mut entry in self.move_stats.drain(..) {
if entry.key.mode != TrainingMode::Both {
if entry.interval_seconds.is_none() {
entry.interval_seconds = match (entry.due, entry.last_seen) {
(Some(due), Some(last)) if due > last => Some(due.saturating_sub(last)),
_ => None,
};
}
merged.push(entry);
continue;
}
entry.key.expected_uci.clear();
entry.due = None;
entry.interval_seconds = None;
if let Some(old) = merged.iter_mut().find(|old| old.key == entry.key) {
old.attempts = old.attempts.saturating_add(entry.attempts);
old.correct = old.correct.saturating_add(entry.correct);
old.wrong = old.wrong.saturating_add(entry.wrong);
old.hints = old.hints.saturating_add(entry.hints);
if entry.last_attempt > old.last_attempt {
old.streak = entry.streak;
}
old.last_attempt = old.last_attempt.max(entry.last_attempt);
old.last_seen = old.last_seen.max(entry.last_seen);
old.recent.extend(entry.recent);
old.recent.sort_by_key(|attempt| attempt.at);
if old.recent.len() > RECENT {
old.recent.drain(..old.recent.len() - RECENT);
}
} else {
merged.push(entry);
}
}
self.move_stats = merged;
}
pub(crate) fn normalize(&mut self) {
self.move_stats.sort_by(|a, b| a.key.cmp(&b.key));
self.move_stats.dedup_by(|a, b| a.key == b.key);
self.runs
.sort_by(|a, b| (&a.repertoire_id, &a.mode).cmp(&(&b.repertoire_id, &b.mode)));
self.path_stats.sort_by(|a, b| a.key.cmp(&b.key));
self.review_cursors.sort_by(|a, b| {
(&a.repertoire_id, &a.mode, &a.scope).cmp(&(&b.repertoire_id, &b.mode, &b.scope))
});
self.practice_path_cursors.sort_by(|a, b| {
(&a.repertoire_id, &a.mode, &a.scope).cmp(&(&b.repertoire_id, &b.mode, &b.scope))
});
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]
}
}

View file

@ -0,0 +1,384 @@
use std::collections::BTreeSet;
use std::io;
use std::path::{Path, PathBuf};
use chess_core::pgn::store::write_atomic;
use serde::de::DeserializeOwned;
use super::model::{LIBRARY_VERSION, Library, RepertoireError};
use super::stats::{STATS_VERSION, StatsData};
#[derive(Debug)]
pub enum StoreError {
Io {
path: PathBuf,
source: io::Error,
},
Json {
path: PathBuf,
source: serde_json::Error,
},
UnsupportedVersion {
kind: &'static str,
version: u32,
path: PathBuf,
},
MissingVersion {
kind: &'static str,
path: PathBuf,
},
DuplicateStats(PathBuf),
Conflict {
path: PathBuf,
expected: u64,
actual: u64,
},
LegacyPath(PathBuf),
Repertoire(RepertoireError),
}
impl std::fmt::Display for StoreError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io { path, source } => write!(f, "I/O error at {}: {source}", path.display()),
Self::Json { path, source } => {
write!(f, "invalid JSON at {}: {source}", path.display())
}
Self::UnsupportedVersion {
kind,
version,
path,
} => write!(
f,
"unsupported {kind} schema version {version} at {}",
path.display()
),
Self::MissingVersion { kind, path } => {
write!(f, "{kind} at {} has no schema version", path.display())
}
Self::DuplicateStats(path) => {
write!(f, "duplicate training keys in {}", path.display())
}
Self::Conflict {
path,
expected,
actual,
} => write!(
f,
"concurrent modification of {}: loaded revision {expected}, disk revision {actual}; reload and retry",
path.display()
),
Self::LegacyPath(path) => write!(
f,
"legacy training file must be different from the new statistics file: {}",
path.display()
),
Self::Repertoire(error) => error.fmt(f),
}
}
}
impl std::error::Error for StoreError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Json { source, .. } => Some(source),
Self::Repertoire(error) => Some(error),
_ => None,
}
}
}
impl From<RepertoireError> for StoreError {
fn from(error: RepertoireError) -> Self {
Self::Repertoire(error)
}
}
fn io(path: &Path, source: io::Error) -> StoreError {
StoreError::Io {
path: path.to_owned(),
source,
}
}
fn json(path: &Path, source: serde_json::Error) -> StoreError {
StoreError::Json {
path: path.to_owned(),
source,
}
}
// Lock a stable sidecar: the data file itself is replaced by atomic rename. Keeping
// the lock file avoids unlink/open races and the OS releases its lock after a crash.
fn lock_store(path: &Path) -> Result<std::fs::File, StoreError> {
let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned());
if let Some(parent) = target.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
}
let mut lock_name = target.file_name().unwrap_or_default().to_os_string();
lock_name.push(".lock");
let lock_path = target.with_file_name(lock_name);
let lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.read(true)
.open(&lock_path)
.map_err(|e| io(&lock_path, e))?;
lock.lock().map_err(|e| io(&lock_path, e))?;
Ok(lock)
}
fn read_optional(path: &Path) -> Result<Option<Vec<u8>>, StoreError> {
match std::fs::read(path) {
Ok(bytes) => Ok(Some(bytes)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(io(path, error)),
}
}
fn decode_versioned<T: DeserializeOwned>(
path: &Path,
bytes: &[u8],
kind: &'static str,
supported: u32,
) -> Result<T, StoreError> {
let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| json(path, e))?;
let version = value
.get("version")
.and_then(serde_json::Value::as_u64)
.ok_or_else(|| StoreError::MissingVersion {
kind,
path: path.to_owned(),
})?;
let version = u32::try_from(version).unwrap_or(u32::MAX);
if version != supported {
return Err(StoreError::UnsupportedVersion {
kind,
version,
path: path.to_owned(),
});
}
serde_json::from_value(value).map_err(|e| json(path, e))
}
#[derive(Clone, Debug)]
pub struct LibraryStore {
path: PathBuf,
}
impl LibraryStore {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into() }
}
pub fn path(&self) -> &Path {
&self.path
}
/// A missing new library is empty. Existing unreadable or unsupported data is an
/// error, never silently replaced by an empty library.
pub fn load(&self) -> Result<Library, StoreError> {
let Some(bytes) = read_optional(&self.path)? else {
return Ok(Library::default());
};
let library: Library =
decode_versioned(&self.path, &bytes, "repertoire library", LIBRARY_VERSION)?;
library.validate()?;
Ok(library)
}
/// Optimistic concurrency: a stale in-memory snapshot is rejected rather than
/// overwriting another process's additions. The caller reloads and reapplies its edit.
pub fn save(&self, library: &mut Library) -> Result<(), StoreError> {
library.validate()?;
let _lock = lock_store(&self.path)?;
let current = self.load()?;
if current.revision != library.revision {
return Err(StoreError::Conflict {
path: self.path.clone(),
expected: library.revision,
actual: current.revision,
});
}
let previous = library.revision;
library.version = LIBRARY_VERSION;
library.revision = current.revision.saturating_add(1);
let bytes = serde_json::to_vec_pretty(library).map_err(|e| json(&self.path, e))?;
if let Err(error) = write_atomic(&self.path, &bytes) {
library.revision = previous;
return Err(io(&self.path, error));
}
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct StatsStore {
path: PathBuf,
legacy_path: Option<PathBuf>,
}
impl StatsStore {
/// A store for the new versioned format. It does not implicitly read or replace the
/// legacy global `training.json`.
pub fn new(path: impl Into<PathBuf>) -> Self {
Self {
path: path.into(),
legacy_path: None,
}
}
/// A new file plus an optional legacy source. Saving always writes `path`; the legacy
/// source is copied once to `.before-repertoire-v2` and is never renamed or overwritten.
pub fn with_legacy(path: impl Into<PathBuf>, legacy_path: impl Into<PathBuf>) -> Self {
Self {
path: path.into(),
legacy_path: Some(legacy_path.into()),
}
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn legacy_path(&self) -> Option<&Path> {
self.legacy_path.as_deref()
}
pub fn load(&self) -> Result<StatsData, StoreError> {
if let Some(bytes) = read_optional(&self.path)? {
let mut stats: StatsData =
decode_versioned(&self.path, &bytes, "repertoire statistics", STATS_VERSION)?;
validate_stats(&self.path, &stats)?;
stats.migrate_position_stats();
return Ok(stats);
}
let Some(legacy_path) = self.legacy_path.as_deref() else {
return Ok(StatsData::default());
};
let Some(bytes) = read_optional(legacy_path)? else {
return Ok(StatsData::default());
};
let legacy_lines: serde_json::Map<String, serde_json::Value> =
serde_json::from_slice(&bytes).map_err(|e| json(legacy_path, e))?;
let mut stats = StatsData::default();
stats.legacy_lines = legacy_lines;
Ok(stats)
}
pub fn save(&self, stats: &mut StatsData) -> Result<(), StoreError> {
if self.legacy_path.as_ref() == Some(&self.path) {
return Err(StoreError::LegacyPath(self.path.clone()));
}
validate_stats(&self.path, stats)?;
let _lock = lock_store(&self.path)?;
let current = self.load()?;
if current.revision != stats.revision {
return Err(StoreError::Conflict {
path: self.path.clone(),
expected: stats.revision,
actual: current.revision,
});
}
self.backup_legacy_once()?;
let previous = stats.revision;
stats.version = STATS_VERSION;
stats.revision = current.revision.saturating_add(1);
stats.normalize();
let bytes = serde_json::to_vec_pretty(stats).map_err(|e| json(&self.path, e))?;
if let Err(error) = write_atomic(&self.path, &bytes) {
stats.revision = previous;
return Err(io(&self.path, error));
}
Ok(())
}
fn backup_legacy_once(&self) -> Result<(), StoreError> {
let Some(legacy) = self.legacy_path.as_deref() else {
return Ok(());
};
let Some(bytes) = read_optional(legacy)? else {
return Ok(());
};
let backup = legacy_backup_path(legacy);
if backup.exists() {
return Ok(());
}
write_atomic(&backup, &bytes).map_err(|e| io(&backup, e))
}
}
fn legacy_backup_path(legacy: &Path) -> PathBuf {
let mut name = legacy.file_name().unwrap_or_default().to_os_string();
name.push(".before-repertoire-v2");
legacy.with_file_name(name)
}
fn validate_stats(path: &Path, stats: &StatsData) -> Result<(), StoreError> {
let mut moves = BTreeSet::new();
let mut runs = BTreeSet::new();
let mut paths = BTreeSet::new();
let valid = stats
.move_stats
.iter()
.all(|entry| moves.insert(&entry.key))
&& stats
.runs
.iter()
.all(|entry| runs.insert((&entry.repertoire_id, &entry.mode)))
&& stats
.path_stats
.iter()
.all(|entry| paths.insert(&entry.key));
if valid {
Ok(())
} else {
Err(StoreError::DuplicateStats(path.to_owned()))
}
}
#[cfg(test)]
mod lock_tests {
use super::*;
#[test]
fn child_exits_while_holding_store_lock() {
let Some(path) = std::env::var_os("CP_TRAINER_LOCK_EXIT_TEST") else {
return;
};
let _lock = lock_store(Path::new(&path)).unwrap();
// process::exit skips Rust destructors, as does abrupt process termination.
std::process::exit(0);
}
#[test]
fn store_lock_is_released_on_drop_and_process_exit() {
let path =
std::env::temp_dir().join(format!("cp-store-lock-exit-{}.json", std::process::id()));
let lock_path = path.with_file_name(format!(
"{}.lock",
path.file_name().unwrap().to_string_lossy()
));
drop(lock_store(&path).unwrap());
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(&lock_path)
.unwrap();
file.try_lock().unwrap();
file.unlock().unwrap();
let status = std::process::Command::new(std::env::current_exe().unwrap())
.arg("--exact")
.arg("repertoire::store::lock_tests::child_exits_while_holding_store_lock")
.env("CP_TRAINER_LOCK_EXIT_TEST", &path)
.status()
.unwrap();
assert!(status.success());
assert!(lock_path.exists());
file.try_lock().unwrap();
file.unlock().unwrap();
std::fs::remove_file(lock_path).unwrap();
}
}

View file

@ -0,0 +1,926 @@
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use chess_core::shakmaty::{Chess, Move, Position};
use chess_core::{Game, MoveKind, NodeId, StartPosition};
use serde_json::json;
use super::*;
static TEST_DIR: AtomicU64 = AtomicU64::new(1);
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<Move> {
let mut position = game.start().position().clone();
line.iter()
.map(|text| {
let mv = text
.parse::<chess_core::shakmaty::uci::UciMove>()
.unwrap()
.to_move(&position)
.unwrap();
position.play_unchecked(mv);
mv
})
.collect()
}
fn temp_dir(name: &str) -> PathBuf {
let sequence = TEST_DIR.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"cp-repertoire-{}-{sequence}-{name}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
path
}
#[test]
fn prefix_branch_dedup_and_annotations_merge_without_touching_source() {
let source = game("1. e4 {old} $1 c5 2. Nf3 d6 3. Bb5+ (3. d4 cxd4 4. Nxd4 (4. Qxd4)) *");
let original = source.to_pgn();
let canonical = source.canonical_tree();
let mut library = Library::default();
let id = library.create_empty("Sicilian").unwrap();
let prefix_end = source.mainline()[3];
let report = library.add_prefix(&id, &source, prefix_end).unwrap();
assert_eq!(report.added_nodes, 4);
let snapshot = library.repertoire(&id).unwrap().game();
assert_eq!(snapshot.mainline().len(), 4);
assert_eq!(
snapshot.game_move(snapshot.mainline()[2]).unwrap().san,
"Nf3"
);
assert!(!snapshot.to_pgn().contains("Bb5"));
assert!(!snapshot.to_pgn().contains("cxd4"));
let annotated = game("1. e4 {new} $2 c5 2. Nf3 Nc6 3. d4 *");
library.add_game(&id, &annotated).unwrap();
library.add_game(&id, &annotated).unwrap();
library.add_game(&id, &source).unwrap();
let merged = library.repertoire(&id).unwrap().game();
let e4 = merged.main_child(NodeId::ROOT).unwrap();
assert_eq!(merged.node(e4).unwrap().comments_after(), ["old", "new"]);
assert_eq!(
merged
.node(e4)
.unwrap()
.nags()
.iter()
.map(|n| n.0)
.collect::<Vec<_>>(),
[1, 2]
);
let moves = play(&merged, &["e2e4", "c7c5", "g1f3"]);
let c5 = merged.find_child(e4, moves[1]).unwrap();
let nf3 = merged.find_child(c5, moves[2]).unwrap();
assert_eq!(merged.children(nf3).len(), 2);
assert_eq!(
library
.repertoire(&id)
.unwrap()
.game()
.attached_nodes()
.len(),
12
);
let before = library.repertoire(&id).unwrap().pgn.clone();
let repeat = library.add_game(&id, &source).unwrap();
assert_eq!(repeat.added_nodes, 0);
assert_eq!(library.repertoire(&id).unwrap().pgn, before);
assert_eq!(source.to_pgn(), original);
assert_eq!(source.canonical_tree(), canonical);
}
#[test]
fn different_starts_are_rejected_and_fullmove_zero_is_preserved() {
let fen_game =
game("[SetUp \"1\"]\n[FEN \"4k3/8/8/8/8/8/4P3/4K2R b - - 0 0\"]\n\n1... Ke7 2. e4 *");
let mut library = Library::default();
let id = library.create("Black to move", &fen_game).unwrap();
assert_eq!(
library
.repertoire(&id)
.unwrap()
.game()
.start()
.original_fen(),
Some("4k3/8/8/8/8/8/4P3/4K2R b - - 0 0")
);
let before = library.repertoire(&id).unwrap().pgn.clone();
assert!(matches!(
library.add_game(&id, &game("1. e4 *")),
Err(RepertoireError::DifferentStart { .. })
));
assert_eq!(library.repertoire(&id).unwrap().pgn, before);
}
#[test]
fn null_and_unparsed_segments_survive_but_are_not_candidates() {
let source = game("1. e4 -- (1... e5) 2. d4 *");
let mut library = Library::default();
let id = library.create("Teaching", &game("1. e4 e5 *")).unwrap();
library.add_game(&id, &source).unwrap();
let stored = library.repertoire(&id).unwrap();
assert!(stored.pgn.contains("--"));
let tree = RepertoireTree::new(stored);
let stored_game = tree.game();
let e4 = stored_game.main_child(NodeId::ROOT).unwrap();
let null = stored_game
.children(e4)
.iter()
.copied()
.find(|node| {
stored_game
.game_move(*node)
.is_some_and(|mv| mv.kind == MoveKind::Null)
})
.unwrap();
assert!(tree.candidates(null).is_empty());
assert!(tree.candidates(e4).iter().any(|c| c.uci == "e7e5"));
assert!(tree.candidates(e4).iter().all(|c| c.uci != "0000"));
let illegal = game("1. e4 e5 2. e5 *");
assert!(illegal.canonical_tree().contains("U["));
let mut illegal_library = Library::default();
let illegal_id = illegal_library.create("Raw", &illegal).unwrap();
let roundtrip = illegal_library.repertoire(&illegal_id).unwrap().game();
assert_eq!(roundtrip.canonical_tree(), illegal.canonical_tree());
assert!(
illegal_library
.add_game(&illegal_id, &game("1. e4 e5 2. Nf3 *"))
.is_ok()
);
let mut target = Library::default();
let target_id = target.create("Target", &game("1. e4 e5 *")).unwrap();
let target_before = target.repertoire(&target_id).unwrap().pgn.clone();
assert!(target.add_game(&target_id, &illegal).is_err());
assert_eq!(target.repertoire(&target_id).unwrap().pgn, target_before);
let mut empty = Library::default();
let empty_id = empty.create_empty("Empty").unwrap();
empty.add_game(&empty_id, &illegal).unwrap();
assert_eq!(
empty.repertoire(&empty_id).unwrap().game().canonical_tree(),
illegal.canonical_tree()
);
let mut prefixes = Library::default();
let prefix_id = prefixes.create("Prefix", &game("1. e4 *")).unwrap();
let null_node = source.mainline()[1];
prefixes.add_prefix(&prefix_id, &source, null_node).unwrap();
let prefix_pgn = &prefixes.repertoire(&prefix_id).unwrap().pgn;
assert!(prefix_pgn.contains("--"));
assert!(!prefix_pgn.contains("d4"));
}
#[test]
fn transpositions_share_candidates_but_keep_both_pgn_paths() {
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 stored = library.repertoire(&id).unwrap();
let tree = RepertoireTree::new(stored);
let game = tree.game();
let first_path = ["d2d4", "d7d5", "g1f3", "g8f6"];
let second_path = ["g1f3", "d7d5", "d2d4", "g8f6"];
let first = tree.node_at_path(&first_path.map(str::to_owned)).unwrap();
let second = tree.node_at_path(&second_path.map(str::to_owned)).unwrap();
assert_ne!(first, second);
assert_eq!(tree.position_key(first), tree.position_key(second));
assert!(tree.transpositions(first).contains(&second));
assert!(tree.candidates(second).iter().any(|c| c.uci == "g2g3"));
let pgn = stored.pgn.clone();
assert!(pgn.contains("d4"));
assert!(pgn.contains("Nf3"));
assert_eq!(game.attached_nodes().len(), 10);
}
#[test]
fn fen4_ignores_counters_but_distinguishes_side_castling_and_legal_ep() {
let position = |fen: &str| StartPosition::from_fen(fen).unwrap().position().clone();
let a = position("4k3/8/8/8/8/8/4P3/4K2R w K - 0 1");
let counters = position("4k3/8/8/8/8/8/4P3/4K2R w K - 37 91");
let black = position("4k3/8/8/8/8/8/4P3/4K2R b K - 0 1");
let no_rights = position("4k3/8/8/8/8/8/4P3/4K2R w - - 0 1");
assert_eq!(fen4(&a), fen4(&counters));
assert_ne!(fen4(&a), fen4(&black));
assert_ne!(fen4(&a), fen4(&no_rights));
let legal_ep = position("4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 2");
let no_ep = position("4k3/8/8/3pP3/8/8/8/4K3 w - - 0 2");
let illegal_ep = position("4k3/8/8/3p4/8/8/8/4K3 w - d6 0 2");
let illegal_no_ep = position("4k3/8/8/3p4/8/8/8/4K3 w - - 0 2");
assert_ne!(fen4(&legal_ep), fen4(&no_ep));
assert_eq!(fen4(&illegal_ep), fen4(&illegal_no_ep));
}
#[test]
fn library_crud_depth_and_disable_are_persistent_data() {
let mut library = Library::default();
let id = library.create(" Name ", &game("1. e4 e5 *")).unwrap();
assert_eq!(library.repertoire(&id).unwrap().name, "Name");
assert_eq!(library.repertoire(&id).unwrap().max_plies, 20);
library.rename(&id, "Renamed").unwrap();
assert!(library.rename(&id, " ").is_err());
let repertoire = library.repertoire_mut(&id).unwrap();
repertoire.set_max_plies(1);
repertoire
.set_prefix_disabled(&["e2e4".into()], true)
.unwrap();
repertoire
.set_prefix_disabled(&["e2e4".into()], true)
.unwrap();
assert_eq!(repertoire.disabled_prefixes.len(), 1);
assert!(
RepertoireTree::new(repertoire)
.candidates(NodeId::ROOT)
.is_empty()
);
assert_eq!(library.delete(&id).unwrap().name, "Renamed");
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::<Vec<_>>();
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<usize> {
(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 *");
assert_eq!(source.mainline().len(), 1);
assert!(!source.mainline().is_empty());
let mut library = Library::default();
let id = library.create("Target", &game("1. e4 c5 *")).unwrap();
let before = library.repertoire(&id).unwrap().pgn.clone();
let report = library
.add_prefix(&id, &source, source.mainline()[0])
.unwrap();
assert_eq!(report.added_nodes, 0);
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");
let path = dir.join("repertoires.json");
let store = LibraryStore::new(&path);
let mut first = store.load().unwrap();
let id = first.create("One", &game("1. e4 *")).unwrap();
store.save(&mut first).unwrap();
assert_eq!(first.revision, 1);
assert_eq!(store.load().unwrap().repertoire(&id).unwrap().name, "One");
let mut stale = Library::default();
stale.create("Stale", &game("1. d4 *")).unwrap();
assert!(matches!(
store.save(&mut stale),
Err(StoreError::Conflict { .. })
));
let disk = store.load().unwrap();
assert_eq!(disk.repertoires.len(), 1);
assert_eq!(disk.repertoires[0].name, "One");
std::fs::write(&path, b"{broken").unwrap();
assert!(store.load().is_err());
std::fs::write(
&path,
serde_json::to_vec(&json!({"version": 99, "repertoires": []})).unwrap(),
)
.unwrap();
assert!(matches!(
store.load(),
Err(StoreError::UnsupportedVersion { .. })
));
let blocker = dir.join("not-a-directory");
std::fs::write(&blocker, b"file").unwrap();
let blocked = LibraryStore::new(blocker.join("library.json"));
let mut library = Library::default();
assert!(blocked.save(&mut library).is_err());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn legacy_roundtrip_backup_migration_and_stats_conflict_preserve_data() {
let dir = temp_dir("legacy-store");
let legacy_path = dir.join("training.json");
let new_path = dir.join("repertoire-training.json");
let start = crate::line_key(&Chess::default(), &play(&Game::new(), &["e2e4", "c7c5"]));
let other = crate::line_key(&Chess::default(), &play(&Game::new(), &["e2e4", "e7e5"]));
let legacy_bytes = serde_json::to_vec_pretty(&json!({
(start.clone()): {"runs": 4, "last": 2, "best": 0, "clean_streak": 0, "recent": [[2, false]], "last_date": "2026-10-01", "unknown": 7},
(other): {"runs": 2, "last": 0, "best": 0, "clean_streak": 2, "recent": [], "last_date": "2026-10-02"},
"future-key": {"arbitrary": [1, 2, 3]}
}))
.unwrap();
std::fs::write(&legacy_path, &legacy_bytes).unwrap();
let store = StatsStore::with_legacy(&new_path, &legacy_path);
let mut stats = store.load().unwrap();
assert_eq!(stats.legacy_lines.len(), 3);
assert!(stats.move_stats.is_empty());
assert_eq!(stats.legacy_lines[&start]["runs"], 4);
assert_eq!(stats.legacy_lines[&start]["unknown"], 7);
let mut library = Library::default();
let report = library.migrate_legacy_lines(&stats.legacy_lines);
assert_eq!(report.repertoires, 1);
assert_eq!(report.lines, 2);
assert_eq!(report.skipped, ["future-key"]);
let after_first = library.repertoires[0].pgn.clone();
let id = library.repertoires[0].id.clone();
library.migrate_legacy_lines(&stats.legacy_lines);
assert_eq!(library.repertoires.len(), 1);
assert_eq!(library.repertoires[0].id, id);
assert_eq!(library.repertoires[0].pgn, after_first);
let mut stale = stats.clone();
store.save(&mut stats).unwrap();
assert_eq!(std::fs::read(&legacy_path).unwrap(), legacy_bytes);
let backup = dir.join("training.json.before-repertoire-v2");
assert_eq!(std::fs::read(backup).unwrap(), legacy_bytes);
assert!(matches!(
store.save(&mut stale),
Err(StoreError::Conflict { .. })
));
let reopened = store.load().unwrap();
assert_eq!(reopened.legacy_lines, stats.legacy_lines);
assert!(reopened.move_stats.is_empty());
std::fs::write(&legacy_path, b"{bad").unwrap();
let missing_new = StatsStore::with_legacy(dir.join("other.json"), &legacy_path);
assert!(missing_new.load().is_err());
assert_eq!(std::fs::read(&legacy_path).unwrap(), b"{bad");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn stats_store_write_failure_does_not_replace_legacy_or_report_success() {
let dir = temp_dir("write-error");
let legacy = dir.join("training.json");
std::fs::write(&legacy, b"{}").unwrap();
let blocker = dir.join("blocked");
std::fs::write(&blocker, b"file").unwrap();
let store = StatsStore::with_legacy(blocker.join("stats.json"), &legacy);
let mut stats = StatsData::default();
assert!(store.save(&mut stats).is_err());
assert_eq!(std::fs::read(&legacy).unwrap(), b"{}");
let _ = std::fs::remove_dir_all(dir);
}
#[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() {
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";
std::fs::write(&source_path, bytes).unwrap();
let source = game("1. e4 c5 2. Nf3 d6 3. Bb5+ *");
let mut library = Library::default();
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);
}

View file

@ -0,0 +1,430 @@
use std::collections::{BTreeMap, BTreeSet};
use chess_core::shakmaty::fen::Fen;
use chess_core::shakmaty::{CastlingMode, Chess, Color, EnPassantMode, Move, Position};
use chess_core::{Game, MoveKind, NodeId};
use super::model::Repertoire;
use super::scope::TrainingScope;
/// The position identity used by opening training: board, side, castling rights and
/// legal en passant. Halfmove and fullmove counters deliberately do not participate.
pub fn fen4(position: &Chess) -> String {
Fen::from_position(position, EnPassantMode::Legal)
.to_string()
.split(' ')
.take(4)
.collect::<Vec<_>>()
.join(" ")
}
#[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<String>,
}
#[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<String>,
}
#[derive(Clone, Debug)]
struct IndexedNode {
fen4: String,
path: Option<Vec<String>>,
}
/// A PGN tree plus derived position/transposition information. Node IDs are used only
/// while this value is alive and are never persisted in statistics or settings.
#[derive(Clone, Debug)]
pub struct RepertoireTree {
game: Game,
max_plies: u32,
disabled_prefixes: Vec<Vec<String>>,
indexed: BTreeMap<NodeId, IndexedNode>,
positions: BTreeMap<String, Vec<NodeId>>,
}
impl RepertoireTree {
pub fn new(repertoire: &Repertoire) -> Self {
Self::from_game(
repertoire.game(),
repertoire.max_plies,
repertoire.disabled_prefixes.clone(),
)
}
pub fn from_game(game: Game, max_plies: u32, disabled_prefixes: Vec<Vec<String>>) -> Self {
let mut indexed = BTreeMap::new();
let mut positions: BTreeMap<String, Vec<NodeId>> = BTreeMap::new();
for id in game.attached_nodes() {
let Some(position) = game.position(id) else {
continue;
};
let key = fen4(position);
let path = normal_path(&game, id);
positions.entry(key.clone()).or_default().push(id);
indexed.insert(id, IndexedNode { fen4: key, path });
}
Self {
game,
max_plies,
disabled_prefixes,
indexed,
positions,
}
}
pub(crate) fn max_plies(&self) -> u32 {
self.max_plies
}
pub fn game(&self) -> &Game {
&self.game
}
pub fn root(&self) -> NodeId {
self.game.root()
}
pub fn position(&self, at: NodeId) -> Option<&Chess> {
self.game.position(at)
}
pub fn position_key(&self, at: NodeId) -> Option<&str> {
self.indexed.get(&at).map(|n| n.fen4.as_str())
}
pub fn path(&self, at: NodeId) -> Option<&[String]> {
self.indexed.get(&at)?.path.as_deref()
}
pub fn transpositions(&self, at: NodeId) -> &[NodeId] {
self.position_key(at)
.and_then(|key| self.positions.get(key))
.map(Vec::as_slice)
.unwrap_or(&[])
}
pub fn is_trainable_path(&self, at: NodeId) -> bool {
let Some(node) = self.game.node(at) else {
return false;
};
let Some(path) = self.path(at) else {
return false;
};
node.ply() <= self.max_plies && !self.disabled(path)
}
/// Enabled children of the current path and all its FEN4 transpositions. A direct
/// child is preferred so ordinary paths stay on their own PGN branch; otherwise the
/// first PGN path is the canonical continuation. Null and unparsed-after-null paths
/// never contribute candidates.
pub fn candidates(&self, at: NodeId) -> Vec<Candidate> {
self.candidates_impl(at, None)
}
pub fn scoped_candidates(&self, at: NodeId, scope: &TrainingScope) -> Vec<Candidate> {
self.candidates_impl(at, Some(scope))
}
pub fn scoped_candidate(
&self,
at: NodeId,
uci: &str,
scope: &TrainingScope,
) -> Option<Candidate> {
self.scoped_candidates(at, scope)
.into_iter()
.find(|candidate| candidate.uci == uci)
}
fn candidates_impl(&self, at: NodeId, scope: Option<&TrainingScope>) -> Vec<Candidate> {
if !self.is_trainable_path(at)
|| self
.game
.node(at)
.is_none_or(|node| node.ply() >= self.max_plies)
{
return Vec::new();
}
let mut nodes = Vec::new();
nodes.push(at);
nodes.extend(
self.transpositions(at)
.iter()
.copied()
.filter(|node| *node != at),
);
let mut seen = BTreeSet::new();
let mut out = Vec::new();
for parent in nodes {
let Some(parent_node) = self.game.node(parent) else {
continue;
};
if !self.is_trainable_path(parent)
|| parent_node.ply() >= self.max_plies
|| !self.scope_allows_parent(parent, scope)
{
continue;
}
for child in self.game.children(parent) {
let Some(game_move) = self.game.game_move(*child) else {
continue;
};
let MoveKind::Normal(mv) = game_move.kind else {
continue;
};
if !self.is_trainable_path(*child) || !self.scope_allows_child(*child, scope) {
continue;
}
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
}
pub fn candidate(&self, at: NodeId, uci: &str) -> Option<Candidate> {
self.candidates(at)
.into_iter()
.find(|candidate| candidate.uci == uci)
}
/// All one-side targets in deterministic PGN order, deduplicated by FEN4/UCI.
pub fn targets(&self, side: Color) -> Vec<TrainingTarget> {
self.targets_impl(side, None)
}
pub fn scoped_targets(&self, side: Color, scope: &TrainingScope) -> Vec<TrainingTarget> {
self.targets_impl(side, Some(scope))
}
fn targets_impl(&self, side: Color, scope: Option<&TrainingScope>) -> Vec<TrainingTarget> {
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<NodeId> {
let mut current = self.root();
let mut position = self.game.position(current)?.clone();
for uci in path {
let mv = uci
.parse::<chess_core::shakmaty::uci::UciMove>()
.ok()?
.to_move(&position)
.ok()?;
current = self.game.find_child(current, mv)?;
position.play_unchecked(mv);
}
self.is_trainable_path(current).then_some(current)
}
pub fn scope_anchor(&self, scope: &TrainingScope) -> Result<NodeId, String> {
if let Some(end) = &scope.end_prefix
&& (end.len() < scope.prefix.len() || !end.starts_with(&scope.prefix))
{
return Err("scope end must extend the selected prefix".into());
}
let anchor = if scope.prefix.is_empty() {
self.root()
} else {
self.node_at_path(scope.parent_prefix())
.ok_or_else(|| "scope parent is missing, disabled, or beyond depth".to_owned())?
};
if let Some(selected) = scope.prefix.last()
&& self.candidate(anchor, selected).is_none()
{
return Err("scope move is missing, disabled, or beyond depth".into());
}
if let Some(end) = &scope.end_prefix
&& self.node_at_path(end).is_none()
{
return Err("scope end is missing, disabled, or beyond depth".into());
}
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<Vec<TrainingPath>, 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(())
}
pub fn training_path_count(&self, scope: &TrainingScope) -> Result<usize, String> {
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<String>,
positions: &mut BTreeSet<String>,
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;
};
let Some(path) = self.path(at) else {
return false;
};
path == scope.parent_prefix() || self.path_in_scope(path, scope)
}
fn scope_allows_child(&self, at: NodeId, scope: Option<&TrainingScope>) -> bool {
let Some(scope) = scope else {
return true;
};
self.path(at)
.is_some_and(|path| self.path_in_scope(path, scope))
}
fn path_in_scope(&self, path: &[String], scope: &TrainingScope) -> bool {
if !path.starts_with(&scope.prefix) {
return false;
}
scope
.end_prefix
.as_ref()
.is_none_or(|end| path.len() <= end.len())
}
fn disabled(&self, path: &[String]) -> bool {
self.disabled_prefixes
.iter()
.any(|prefix| path.starts_with(prefix))
}
}
fn normal_path(game: &Game, at: NodeId) -> Option<Vec<String>> {
let mut path = Vec::new();
for node in game.path(at).into_iter().skip(1) {
match game.game_move(node).map(|m| m.kind) {
Some(MoveKind::Normal(mv)) => {
path.push(mv.to_uci(CastlingMode::Standard).to_string());
}
Some(MoveKind::Null) | None => return None,
}
}
Some(path)
}