trainer: drop the dead v2 tree session (session.rs), its queues and paths in stats.rs/tree.rs/scope.rs and their tests; v2/legacy formats, StatsStore and the store/migration tests stay

This commit is contained in:
vrubelroman 2026-11-27 08:49:13 +03:00
parent 87e8a6d794
commit 07c6d0cda3
7 changed files with 24 additions and 4229 deletions

File diff suppressed because it is too large Load diff

View file

@ -12,7 +12,6 @@ mod learning_session;
mod line_analytics;
mod model;
mod scope;
mod session;
mod srs;
mod stats;
mod store;
@ -51,10 +50,6 @@ pub use model::{
Repertoire, RepertoireError, RepertoireId,
};
pub use scope::{TrainingScope, TrainingScopeKey};
pub use session::{
FirstMoveChooser, MoveChooser, PlayedMove, PreparedNextPath, SessionAttempt, SessionError,
TrainingSession, TrainingVerdict,
};
pub use srs::{
DEFAULT_GROWTH_FACTOR, FIRST_CORRECT_DELAY_SECONDS, MIN_PRACTICAL_INTERVAL_SECONDS,
MISTAKE_DELAY_SECONDS, PREVIEW_DELAY_SECONDS, SRS_MAX_INTERVAL_SECONDS, SrsSettings,
@ -62,16 +57,15 @@ pub use srs::{
apply_independent_correct, apply_independent_wrong, apply_preview,
};
pub use stats::{
AttemptRecord, INITIAL_INTERVAL_SECONDS, INTRODUCTION_BATCH_SIZE, MAX_INTERVAL_SECONDS,
MISTAKE_INTERVAL_SECONDS, MoveKey, MoveStats, PathKey, PathStats, QueueMode, RunRecord,
RunStats, STATS_VERSION, SrsPolicy, StatsData, TrainingMode,
AttemptRecord, MoveKey, MoveStats, PathKey, PathStats, QueueMode, RunRecord, RunStats,
STATS_VERSION, StatsData, TrainingMode,
};
pub use store::{
LEARNING_STORE_VERSION, LearningSession, LearningStore, LearningStoreData, LibraryStore,
MigrationReport, PersistedAttempt, PersistedLearningReset, PersistedLearningSnapshot,
PersistedSessionAttempt, StatsStore, StoreError,
};
pub use tree::{Candidate, RepertoireTree, TrainingPath, TrainingTarget, fen4};
pub use tree::{Candidate, RepertoireTree, fen4};
#[cfg(test)]
mod acceptance_tests;

View file

@ -16,33 +16,6 @@ impl TrainingScope {
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))

File diff suppressed because it is too large Load diff

View file

@ -1,14 +1,11 @@
use chess_core::shakmaty::{Color, Position};
use chess_core::shakmaty::Color;
use serde::{Deserialize, Serialize};
use super::model::RepertoireId;
use super::scope::{TrainingScope, TrainingScopeKey};
use super::tree::{RepertoireTree, TrainingPath, TrainingTarget};
use super::scope::TrainingScopeKey;
pub const STATS_VERSION: u32 = 2;
pub const INITIAL_INTERVAL_SECONDS: i64 = 24 * 60 * 60;
pub const MISTAKE_INTERVAL_SECONDS: i64 = 10 * 60;
pub const MAX_INTERVAL_SECONDS: i64 = 365 * 24 * 60 * 60;
/// Recent attempts kept per move in a v2 file.
const RECENT: usize = 10;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
@ -36,15 +33,6 @@ pub enum QueueMode {
LeastRecent,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SrsPolicy {
Due,
Introduce,
EarlyReview,
}
pub const INTRODUCTION_BATCH_SIZE: usize = 10;
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MoveKey {
pub repertoire_id: RepertoireId,
@ -103,6 +91,7 @@ impl Default for MoveStats {
}
}
#[cfg(test)]
impl MoveStats {
pub fn new(key: MoveKey) -> Self {
Self {
@ -110,88 +99,6 @@ impl MoveStats {
..Self::default()
}
}
pub fn unseen(&self) -> bool {
self.attempts == 0
}
pub fn is_due(&self, now: i64) -> bool {
self.due.is_some_and(|due| due <= now)
}
fn push_recent(&mut self, attempt: AttemptRecord) {
self.recent.push(attempt);
if self.recent.len() > RECENT {
self.recent.remove(0);
}
}
fn wrong(&mut self, now: i64, actual_uci: &str, schedule: bool) {
self.attempts = self.attempts.saturating_add(1);
self.wrong = self.wrong.saturating_add(1);
self.streak = if self.streak < 0 {
self.streak.saturating_sub(1)
} else {
-1
};
self.last_attempt = Some(now);
self.last_seen = Some(now);
if schedule {
self.due = Some(now.saturating_add(MISTAKE_INTERVAL_SECONDS));
self.interval_seconds = Some(MISTAKE_INTERVAL_SECONDS);
}
self.push_recent(AttemptRecord {
at: now,
correct: false,
hinted: false,
actual_uci: actual_uci.to_owned(),
});
}
fn correct(&mut self, now: i64, actual_uci: &str, hinted: bool, schedule: bool) {
let previous_interval =
self.interval_seconds
.unwrap_or_else(|| match (self.due, self.last_seen) {
(Some(due), Some(last)) if due > last => due.saturating_sub(last),
_ => INITIAL_INTERVAL_SECONDS,
});
let clean_streak = self.streak;
let retry = hinted || clean_streak < 0;
self.attempts = self.attempts.saturating_add(1);
self.correct = self.correct.saturating_add(1);
self.streak = if retry {
0
} else {
clean_streak.saturating_add(1).max(1)
};
if schedule {
let interval = if retry {
MISTAKE_INTERVAL_SECONDS
} else if clean_streak > 0 {
previous_interval
.saturating_mul(2)
.clamp(INITIAL_INTERVAL_SECONDS, MAX_INTERVAL_SECONDS)
} else {
INITIAL_INTERVAL_SECONDS
};
self.due = Some(now.saturating_add(interval));
self.interval_seconds = Some(interval);
}
self.last_attempt = Some(now);
self.last_seen = Some(now);
self.push_recent(AttemptRecord {
at: now,
correct: true,
hinted,
actual_uci: actual_uci.to_owned(),
});
}
fn hint(&mut self, now: i64) {
self.streak = 0;
self.hints = self.hints.saturating_add(1);
self.last_seen = Some(now);
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -275,11 +182,6 @@ struct RandomPracticeCursor {
fingerprint: Option<u64>,
}
pub(crate) struct RandomPracticePath {
pub path: TrainingPath,
pub start: usize,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct StatsData {
@ -314,616 +216,6 @@ impl Default for StatsData {
}
impl StatsData {
/// Removes modern statistics and queue positions for one repertoire. Legacy line
/// aggregates have independent identities and remain untouched.
pub fn remove_repertoire(&mut self, repertoire_id: &RepertoireId) {
self.move_stats
.retain(|entry| &entry.key.repertoire_id != repertoire_id);
self.runs
.retain(|entry| &entry.repertoire_id != repertoire_id);
self.path_stats
.retain(|entry| &entry.key.repertoire_id != repertoire_id);
self.review_cursors
.retain(|entry| &entry.repertoire_id != repertoire_id);
self.path_review_cursors
.retain(|entry| &entry.repertoire_id != repertoire_id);
self.practice_path_cursors
.retain(|entry| &entry.repertoire_id != repertoire_id);
self.random_practice_cursors
.retain(|entry| &entry.repertoire_id != repertoire_id);
}
pub fn remove_repertoire_mode(&mut self, repertoire_id: &RepertoireId, mode: TrainingMode) {
self.move_stats
.retain(|entry| &entry.key.repertoire_id != repertoire_id || entry.key.mode != mode);
self.runs
.retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode);
self.review_cursors
.retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode);
self.practice_path_cursors
.retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode);
self.random_practice_cursors
.retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode);
if mode == TrainingMode::Both {
self.path_stats
.retain(|entry| &entry.key.repertoire_id != repertoire_id);
self.path_review_cursors
.retain(|entry| &entry.repertoire_id != repertoire_id);
}
}
pub fn get(&self, key: &MoveKey) -> Option<&MoveStats> {
self.move_stats.iter().find(|stats| &stats.key == key)
}
pub fn runs(&self, repertoire_id: &RepertoireId, mode: TrainingMode) -> Option<&RunStats> {
self.runs
.iter()
.find(|runs| &runs.repertoire_id == repertoire_id && runs.mode == mode)
}
/// Compatibility queue used by the existing desktop summary. SRS sessions use the
/// more specific `srs_queue` policies below and never automatically exhaust this list.
pub fn queue(
&self,
tree: &RepertoireTree,
repertoire_id: &RepertoireId,
mode: TrainingMode,
queue_mode: QueueMode,
now: i64,
) -> Vec<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)
}
pub(crate) fn next_random_practice_path(
&mut self,
tree: &RepertoireTree,
repertoire_id: &RepertoireId,
mode: TrainingMode,
scope: &TrainingScope,
repertoire_fingerprint: u64,
initial_seed: u64,
) -> Result<Option<RandomPracticePath>, String> {
use std::ops::ControlFlow;
let anchor = tree.scope_anchor(scope)?;
let start_turn = tree
.position(anchor)
.map(|position| position.turn())
.ok_or_else(|| "scope start position is missing".to_owned())?;
let mut count = Some(0usize);
tree.visit_source_paths(scope, |moves| {
if eligible_target_count(mode, start_turn, moves.len()) == 0 {
return ControlFlow::Continue(());
}
count = count.and_then(|count| count.checked_add(1));
if count.is_none() {
ControlFlow::Break(())
} else {
ControlFlow::Continue(())
}
})?;
let count =
count.ok_or_else(|| "training path count exceeds the platform limit".to_owned())?;
let scope_key = scope.key();
let existing = self.random_practice_cursors.iter().position(|cursor| {
&cursor.repertoire_id == repertoire_id
&& cursor.mode == mode
&& cursor.scope == scope_key
});
let is_new = existing.is_none();
let index = existing.unwrap_or_else(|| {
self.random_practice_cursors.push(RandomPracticeCursor {
repertoire_id: repertoire_id.clone(),
mode,
scope: scope_key,
seed: initial_seed,
position: 0,
count: 0,
fingerprint: Some(repertoire_fingerprint),
});
self.random_practice_cursors.len() - 1
});
let cursor = &mut self.random_practice_cursors[index];
if !is_new
&& (cursor.fingerprint != Some(repertoire_fingerprint)
|| cursor.count != count
|| cursor.position >= count)
{
cursor.seed = next_cycle_seed(cursor.seed);
cursor.position = 0;
}
cursor.fingerprint = Some(repertoire_fingerprint);
cursor.count = count;
if count == 0 {
cursor.position = 0;
return Ok(None);
}
if cursor.position >= count {
cursor.position = 0;
}
let position = cursor.position;
let seed = cursor.seed;
let step = coprime_step(seed ^ 0xa076_1d64_78bd_642f, count);
let offset = (mix64(seed ^ 0xe703_7ed1_a0b4_28db) as u128 % count as u128) as usize;
let selected_index =
((step as u128 * position as u128 + offset as u128) % count as u128) as usize;
let start_seed = mix64(seed ^ (position as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15));
let mut order = 0usize;
let mut chosen = None;
tree.visit_source_paths(scope, |moves| {
let eligible = eligible_target_count(mode, start_turn, moves.len());
if eligible == 0 {
return ControlFlow::Continue(());
}
if order == selected_index {
let start_order = (start_seed as usize) % eligible;
chosen = eligible_target_index(mode, start_turn, moves.len(), start_order).map(
|start| RandomPracticePath {
path: TrainingPath {
moves: moves.to_vec(),
},
start,
},
);
return ControlFlow::Break(());
}
order += 1;
ControlFlow::Continue(())
})?;
if chosen.is_some() {
cursor.position = cursor.position.saturating_add(1);
Ok(chosen)
} else {
Err("random training path selection is inconsistent".to_owned())
}
}
/// Selects one route without materializing the complete path queue. Ordered
/// review stops as soon as its cursor is reached; only wrapping needs a second pass.
pub fn next_training_path(
&self,
tree: &RepertoireTree,
repertoire_id: &RepertoireId,
scope: &TrainingScope,
queue_mode: QueueMode,
) -> Result<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(..) {
@ -980,91 +272,4 @@ impl StatsData {
self.path_review_cursors
.sort_by(|a, b| (&a.repertoire_id, &a.scope).cmp(&(&b.repertoire_id, &b.scope)));
}
fn entry(&mut self, key: MoveKey) -> &mut MoveStats {
let index = match self.move_stats.iter().position(|stats| stats.key == key) {
Some(index) => index,
None => {
self.move_stats.push(MoveStats::new(key));
self.move_stats.len() - 1
}
};
&mut self.move_stats[index]
}
}
pub(crate) const MIN_RANDOM_CONTINUATION_PLIES: usize = 7;
fn random_max_start(plies: usize) -> usize {
plies.saturating_sub(MIN_RANDOM_CONTINUATION_PLIES)
}
fn eligible_target_count(mode: TrainingMode, start_turn: Color, plies: usize) -> usize {
if plies == 0 {
return 0;
}
let max_start = random_max_start(plies);
let Some(user_color) = mode.user_color() else {
return usize::from(plies > 0) * (max_start + 1);
};
let first = usize::from(start_turn != user_color);
if max_start < first {
0
} else {
(max_start - first) / 2 + 1
}
}
fn eligible_target_index(
mode: TrainingMode,
start_turn: Color,
plies: usize,
order: usize,
) -> Option<usize> {
let mut remaining = order;
for index in 0..=random_max_start(plies) {
let turn = if index % 2 == 0 {
start_turn
} else {
start_turn.other()
};
if mode.user_color().is_none_or(|color| color == turn) {
if remaining == 0 {
return Some(index);
}
remaining -= 1;
}
}
None
}
fn coprime_step(seed: u64, count: usize) -> usize {
if count == 1 {
return 0;
}
let mut step = (mix64(seed) % count as u64) as usize;
while gcd(step, count) != 1 {
step = (step + 1) % count;
}
step
}
fn gcd(mut left: usize, mut right: usize) -> usize {
while right != 0 {
let remainder = left % right;
left = right;
right = remainder;
}
left
}
fn next_cycle_seed(seed: u64) -> u64 {
mix64(seed ^ 0x8ebc_6af0_9c88_c6e3)
}
fn mix64(mut value: u64) -> u64 {
value = value.wrapping_add(0x9e37_79b9_7f4a_7c15);
value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
value ^ (value >> 31)
}

View file

@ -13,12 +13,6 @@ fn game(pgn: &str) -> Game {
chess_core::parse_str(pgn).game
}
fn repertoire(pgn: &str) -> Repertoire {
let mut library = Library::default();
let id = library.create("Test", &game(pgn)).unwrap();
library.repertoire(&id).unwrap().clone()
}
fn play(game: &Game, line: &[&str]) -> Vec<Move> {
let mut position = game.start().position().clone();
line.iter()
@ -258,348 +252,6 @@ fn library_crud_depth_and_disable_are_persistent_data() {
assert!(library.repertoire(&id).is_none());
}
#[test]
fn both_accepts_every_enabled_branch_and_rejects_outside_disabled_and_depth() {
let rep = repertoire("1. e4 (1. d4 d5) e5 (1... c5) 2. Nf3 *");
let mut session = TrainingSession::new(
&rep,
TrainingMode::Both,
QueueMode::ReviewInOrder,
StatsData::default(),
0,
)
.unwrap();
assert!(session.play_uci("not-a-move", 0).is_err());
assert!(session.play_uci("e2e5", 0).is_err());
assert!(session.attempts().is_empty());
assert_eq!(session.play_uci("c2c4", 1).unwrap(), TrainingVerdict::Wrong);
assert_eq!(session.current_node(), NodeId::ROOT);
assert_eq!(session.total_mistakes(), 1);
assert_eq!(session.play_uci("d2d4", 2).unwrap(), TrainingVerdict::Right);
assert_eq!(
session.play_uci("d7d5", 3).unwrap(),
TrainingVerdict::Finished
);
let completions = session
.stats()
.runs(&rep.id, TrainingMode::Both)
.unwrap()
.completions;
assert_eq!(completions, 1);
assert_eq!(session.play_uci("d2d4", 4).unwrap(), TrainingVerdict::Done);
assert_eq!(
session
.stats()
.runs(&rep.id, TrainingMode::Both)
.unwrap()
.completions,
1
);
session.restart(10).unwrap();
assert_eq!(
session.play_uci("e2e4", 10).unwrap(),
TrainingVerdict::Right
);
assert_eq!(
session.play_uci("c7c5", 11).unwrap(),
TrainingVerdict::Finished
);
let mut disabled = rep.clone();
disabled
.set_prefix_disabled(&["e2e4".into(), "e7e5".into()], true)
.unwrap();
let mut session = TrainingSession::new(
&disabled,
TrainingMode::Both,
QueueMode::ReviewInOrder,
StatsData::default(),
20,
)
.unwrap();
session.play_uci("e2e4", 20).unwrap();
assert_eq!(
session.play_uci("e7e5", 21).unwrap(),
TrainingVerdict::Wrong
);
assert_eq!(
session.play_uci("c7c5", 22).unwrap(),
TrainingVerdict::Finished
);
let mut shallow = rep.clone();
shallow.set_max_plies(1);
let mut session = TrainingSession::new(
&shallow,
TrainingMode::Both,
QueueMode::ReviewInOrder,
StatsData::default(),
30,
)
.unwrap();
assert_eq!(
session.play_uci("e2e4", 30).unwrap(),
TrainingVerdict::Finished
);
}
#[test]
fn both_hint_after_three_errors_and_completion_are_recorded_once() {
let rep = repertoire("1. e4 e5 *");
let mut session = TrainingSession::new(
&rep,
TrainingMode::Both,
QueueMode::SpacedRepetition,
StatsData::default(),
0,
)
.unwrap();
for now in 1..=3 {
assert_eq!(
session.play_uci("d2d4", now).unwrap(),
TrainingVerdict::Wrong
);
assert_eq!(session.current_node(), NodeId::ROOT);
}
assert!(session.may_hint());
assert_eq!(session.hint(4).unwrap().uci, "e2e4");
assert!(session.hinted());
assert_eq!(session.play_uci("e2e4", 5).unwrap(), TrainingVerdict::Right);
assert_eq!(
session.play_uci("e7e5", 6).unwrap(),
TrainingVerdict::Finished
);
assert_eq!(session.play_uci("e7e5", 7).unwrap(), TrainingVerdict::Done);
let stats = &session.stats().move_stats;
let e4 = stats
.iter()
.find(|entry| entry.key.position_fen4 == fen4(Game::new().start().position()))
.unwrap();
assert_eq!((e4.attempts, e4.correct, e4.wrong, e4.hints), (4, 1, 3, 1));
assert_eq!(e4.streak, 0);
assert_eq!(e4.recent.len(), 4);
assert_eq!(e4.recent[0].actual_uci, "d2d4");
let runs = session.stats().runs(&rep.id, TrainingMode::Both).unwrap();
assert_eq!(runs.completions, 1);
assert_eq!(runs.recent[0].mistakes, 3);
assert!(runs.recent[0].hinted);
assert_eq!(session.errors().count(), 3);
}
#[test]
fn both_continues_through_a_canonical_transposition_and_shares_stats() {
let mut library = Library::default();
let id = library.create_empty("Transpositions").unwrap();
library
.add_game(&id, &game("1. d4 d5 2. Nf3 Nf6 3. g3 *"))
.unwrap();
library
.add_game(&id, &game("1. Nf3 d5 2. d4 Nf6 *"))
.unwrap();
let rep = library.repertoire(&id).unwrap().clone();
let mut first = TrainingSession::new(
&rep,
TrainingMode::Both,
QueueMode::ReviewInOrder,
StatsData::default(),
0,
)
.unwrap();
for (now, mv) in ["d2d4", "d7d5", "g1f3", "g8f6", "g2g3"]
.into_iter()
.enumerate()
{
first.play_uci(mv, now as i64).unwrap();
}
let mut second = TrainingSession::new(
&rep,
TrainingMode::Both,
QueueMode::ReviewInOrder,
first.into_stats(),
10,
)
.unwrap();
second.play_uci("g1f3", 10).unwrap();
second.play_uci("d7d5", 11).unwrap();
second.play_uci("d2d4", 12).unwrap();
second.play_uci("g8f6", 13).unwrap();
assert!(second.candidates().iter().any(|c| c.uci == "g2g3"));
assert_eq!(
second.play_uci("g2g3", 14).unwrap(),
TrainingVerdict::Finished
);
let shared = second
.stats()
.move_stats
.iter()
.filter(|entry| {
entry
.recent
.iter()
.any(|attempt| attempt.actual_uci == "g2g3")
})
.collect::<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 *");
@ -617,146 +269,6 @@ fn prefix_ignores_unparsed_tail_after_the_selected_node() {
assert_eq!(library.repertoire(&id).unwrap().pgn, before);
}
#[test]
fn review_queues_record_attempts_without_changing_srs_due() {
let rep = repertoire("1. e4 *");
let mut srs = TrainingSession::new_srs(
&rep,
TrainingMode::White,
StatsData::default(),
0,
SrsPolicy::Introduce,
)
.unwrap();
srs.play_uci("e2e4", 100).unwrap();
let original_due = srs.stats().move_stats[0].due;
assert_eq!(original_due, Some(100 + INITIAL_INTERVAL_SECONDS));
for queue_mode in [QueueMode::ReviewInOrder, QueueMode::LeastRecent] {
let mut review = TrainingSession::new(
&rep,
TrainingMode::White,
queue_mode,
srs.stats().clone(),
0,
)
.unwrap();
review.play_uci("e2e4", 200).unwrap();
let stats = &review.stats().move_stats[0];
assert_eq!(stats.attempts, 2);
assert_eq!(stats.last_seen, Some(200));
assert_eq!(stats.due, original_due);
review.restart(201).unwrap();
review.play_uci("d2d4", 201).unwrap();
assert_eq!(review.stats().move_stats[0].due, original_due);
}
}
#[test]
fn srs_retry_is_kept_until_the_next_clean_success() {
let rep = repertoire("1. e4 *");
let mut session = TrainingSession::new_srs(
&rep,
TrainingMode::White,
StatsData::default(),
0,
SrsPolicy::Introduce,
)
.unwrap();
session.play_uci("d2d4", 100).unwrap();
session.play_uci("e2e4", 101).unwrap();
let stats = &session.stats().move_stats[0];
assert_eq!(stats.due, Some(101 + MISTAKE_INTERVAL_SECONDS));
assert_eq!(stats.streak, 0);
session.restart_with_policy(701, SrsPolicy::Due).unwrap();
session.play_uci("e2e4", 701).unwrap();
let stats = &session.stats().move_stats[0];
assert_eq!(stats.due, Some(701 + INITIAL_INTERVAL_SECONDS));
assert_eq!(stats.streak, 1);
session.restart(701 + INITIAL_INTERVAL_SECONDS).unwrap();
session
.play_uci("e2e4", 701 + INITIAL_INTERVAL_SECONDS)
.unwrap();
let stats = &session.stats().move_stats[0];
assert_eq!(stats.due, Some(701 + 3 * INITIAL_INTERVAL_SECONDS));
assert_eq!(stats.streak, 2);
}
#[test]
fn both_attempts_never_create_srs_due() {
let rep = repertoire("1. e4 *");
let mut session = TrainingSession::new(
&rep,
TrainingMode::Both,
QueueMode::ReviewInOrder,
StatsData::default(),
0,
)
.unwrap();
session.play_uci("d2d4", 100).unwrap();
session.play_uci("e2e4", 101).unwrap();
assert!(
session
.stats()
.move_stats
.iter()
.all(|stats| stats.due.is_none())
);
}
#[test]
fn stats_are_isolated_by_mode_and_repertoire() {
let first_rep = repertoire("1. e4 *");
let second_rep = repertoire("1. e4 *");
let mut white = TrainingSession::new(
&first_rep,
TrainingMode::White,
QueueMode::ReviewInOrder,
StatsData::default(),
0,
)
.unwrap();
white.play_uci("e2e4", 1).unwrap();
let mut both = TrainingSession::new(
&first_rep,
TrainingMode::Both,
QueueMode::ReviewInOrder,
white.into_stats(),
2,
)
.unwrap();
both.play_uci("e2e4", 2).unwrap();
let mut other = TrainingSession::new(
&second_rep,
TrainingMode::Both,
QueueMode::ReviewInOrder,
both.into_stats(),
3,
)
.unwrap();
other.play_uci("e2e4", 3).unwrap();
assert_eq!(other.stats().move_stats.len(), 3);
assert!(
other
.stats()
.move_stats
.iter()
.any(|entry| entry.key.mode == TrainingMode::White)
);
assert_eq!(
other
.stats()
.move_stats
.iter()
.filter(|entry| entry.key.mode == TrainingMode::Both)
.count(),
2
);
}
#[test]
fn library_store_roundtrip_errors_and_conflicts_are_visible() {
let dir = temp_dir("library-store");
@ -866,39 +378,7 @@ fn stats_store_write_failure_does_not_replace_legacy_or_report_success() {
}
#[test]
fn session_stats_can_be_saved_after_every_run() {
let dir = temp_dir("session-save");
let store = StatsStore::new(dir.join("stats.json"));
let rep = repertoire("1. e4 *");
let mut session = TrainingSession::new(
&rep,
TrainingMode::White,
QueueMode::ReviewInOrder,
store.load().unwrap(),
0,
)
.unwrap();
session.play_uci("e2e4", 10).unwrap();
store.save(session.stats_mut()).unwrap();
assert_eq!(session.stats().revision, 1);
session.restart(20).unwrap();
session.play_uci("e2e4", 20).unwrap();
store.save(session.stats_mut()).unwrap();
assert_eq!(session.stats().revision, 2);
assert_eq!(
store
.load()
.unwrap()
.runs(&rep.id, TrainingMode::White)
.unwrap()
.completions,
2
);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn adding_training_and_deleting_never_touches_the_source_file() {
fn adding_and_deleting_never_touches_the_source_file() {
let dir = temp_dir("source-file");
let source_path = dir.join("legacy.pgn");
let bytes = b"[Event \"Legacy\"]\n\n1. e4 c5 2. Nf3 d6 *\n\xff";
@ -908,19 +388,21 @@ fn adding_training_and_deleting_never_touches_the_source_file() {
let id = library.create_empty("Snapshot").unwrap();
let at = source.mainline()[3];
library.add_prefix(&id, &source, at).unwrap();
let rep = library.repertoire(&id).unwrap().clone();
let mut session = TrainingSession::new(
&rep,
TrainingMode::Both,
QueueMode::ReviewInOrder,
StatsData::default(),
0,
)
.unwrap();
for (now, mv) in ["e2e4", "c7c5", "g1f3", "d7d6"].into_iter().enumerate() {
session.play_uci(mv, now as i64).unwrap();
}
library.delete(&id).unwrap();
assert_eq!(std::fs::read(&source_path).unwrap(), bytes);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn v2_stats_without_the_random_cursor_field_still_read_and_save() {
let mut old = serde_json::to_value(StatsData::default()).unwrap();
assert!(
old.as_object_mut()
.unwrap()
.remove("random_practice_cursors")
.is_some()
);
let stats: StatsData = serde_json::from_value(old).unwrap();
let saved = serde_json::to_value(&stats).unwrap();
assert!(saved["random_practice_cursors"].is_array());
}

View file

@ -1,7 +1,7 @@
use std::collections::{BTreeMap, BTreeSet};
use chess_core::shakmaty::fen::Fen;
use chess_core::shakmaty::{CastlingMode, Chess, Color, EnPassantMode, Move, Position};
use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Position};
use chess_core::{Game, MoveKind, NodeId};
use super::model::Repertoire;
@ -20,25 +20,7 @@ pub fn fen4(position: &Chess) -> String {
#[derive(Clone, Debug)]
pub struct Candidate {
pub mv: Move,
pub uci: String,
pub san: String,
/// The selected PGN path. Other paths to the same move remain in the tree.
pub node: NodeId,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TrainingTarget {
pub position_fen4: String,
pub expected_uci: String,
/// One deterministic PGN path used to reach the target as context.
pub path: Vec<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)]
@ -88,10 +70,6 @@ impl RepertoireTree {
}
}
pub(crate) fn max_plies(&self) -> u32 {
self.max_plies
}
pub fn game(&self) -> &Game {
&self.game
}
@ -137,21 +115,6 @@ impl RepertoireTree {
self.candidates_impl(at, None)
}
pub fn scoped_candidates(&self, at: NodeId, scope: &TrainingScope) -> Vec<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
@ -193,12 +156,7 @@ impl RepertoireTree {
}
let uci = mv.to_uci(CastlingMode::Standard).to_string();
if seen.insert(uci.clone()) {
out.push(Candidate {
mv,
uci,
san: game_move.san.clone(),
node: *child,
});
out.push(Candidate { uci });
}
}
}
@ -211,48 +169,6 @@ impl RepertoireTree {
.find(|candidate| candidate.uci == uci)
}
/// All one-side targets in deterministic PGN order, deduplicated by FEN4/UCI.
pub fn targets(&self, side: Color) -> Vec<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> {
@ -295,35 +211,6 @@ impl RepertoireTree {
Ok(anchor)
}
/// Generates actual scope-to-boundary routes in PGN depth-first order. Repeated FEN4
/// positions are included as the final move and never expanded again.
pub fn training_paths(&self, scope: &TrainingScope) -> Result<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(())
}
/// Streams the routes explicitly present in PGN, without importing continuations
/// from other paths that reach the same position.
pub fn visit_source_paths(
@ -370,63 +257,6 @@ impl RepertoireTree {
}
}
pub fn training_path_count(&self, scope: &TrainingScope) -> Result<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;