Skip to main content

oa/ml/training/
session.rs

1//! Thread-safe live control and bounded observation for [`super::ItTraining`].
2//!
3//! The public [`TrainingSession`] is a cloneable command and observation handle.
4//! The training iterator remains on its owning engine thread and applies queued
5//! commands only at explicit safe points.
6
7pub use crate::ml::types::{TrainingCommandResult, TrainingSessionConfig};
8use std::{
9	collections::VecDeque,
10	sync::{Arc, Condvar, Mutex, MutexGuard},
11	time::Duration,
12};
13
14use crate::{Error, ErrorKind, Result};
15
16use super::{Optimizer, TrainingSnapshot};
17
18type CommandHandler<'a> = Box<dyn FnMut() -> Result<()> + 'a>;
19type RebuildHandler<'a> = Box<dyn FnMut(&TrainingCommand) -> Result<()> + 'a>;
20type ValueGetter<'a> = Box<dyn Fn() -> TrainingValue + 'a>;
21type ValueSetter<'a> = Box<dyn FnMut(&TrainingValue) -> Result<()> + 'a>;
22
23/// Live state of an attached training lifecycle.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum TrainingState {
26	/// A new step may begin at the next safe point.
27	Running,
28	/// New steps remain blocked until a resume or stop command is applied.
29	Paused,
30	/// A stop was requested and no new step may begin.
31	Stopping,
32	/// Training reached its explicit successful terminal boundary.
33	Completed,
34	/// Training reached an explicit failure boundary.
35	Failed,
36}
37
38impl TrainingState {
39	pub(crate) const fn is_terminal(self) -> bool {
40		matches!(self, Self::Completed | Self::Failed)
41	}
42}
43
44/// Kind of command applied at a training safe point.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum TrainingCommandKind {
47	/// Pause before another step begins.
48	Pause,
49	/// Resume a paused lifecycle.
50	Resume,
51	/// Stop before another step begins.
52	Stop,
53	/// Invoke the attached checkpoint handler.
54	Checkpoint,
55	/// Invoke the attached evaluation handler.
56	Evaluate,
57	/// Change one registered parameter.
58	SetParameter,
59	/// Discard the captured program so the next automatic step recaptures it.
60	RequestRecapture,
61	/// Invoke the attached rebuild handler.
62	RequestRebuild,
63}
64
65/// Whether a processed command changed the training lifecycle.
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum TrainingCommandDisposition {
68	/// The command passed validation and was applied.
69	Applied,
70	/// The command was observed but rejected without mutation.
71	Rejected,
72}
73
74/// Safe-point class of a live training parameter.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum TrainingParameterClass {
77	/// May change at any batch safe point.
78	Hot,
79	/// May change only while paused and requires explicit recapture policy.
80	Recapture,
81	/// May change only while paused and requires explicit rebuild policy.
82	Rebuild,
83	/// May be observed but never changed through the session.
84	Immutable,
85}
86
87/// Discriminant of a [`TrainingValue`].
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub enum TrainingValueKind {
90	/// No payload.
91	Empty,
92	/// Boolean payload.
93	Boolean,
94	/// Signed integer payload.
95	Integer,
96	/// Floating-point payload.
97	Float,
98	/// UTF-8 string payload.
99	String,
100}
101
102/// Typed value carried by a command or exposed parameter.
103#[derive(Clone, Debug, Default, PartialEq)]
104pub enum TrainingValue {
105	/// No payload.
106	#[default]
107	Empty,
108	/// Boolean payload.
109	Boolean(bool),
110	/// Signed integer payload.
111	Integer(i64),
112	/// Floating-point payload.
113	Float(f64),
114	/// UTF-8 string payload.
115	String(String),
116}
117
118impl TrainingValue {
119	/// Return this value's stable discriminant.
120	pub const fn kind(&self) -> TrainingValueKind {
121		match self {
122			Self::Empty => TrainingValueKind::Empty,
123			Self::Boolean(_) => TrainingValueKind::Boolean,
124			Self::Integer(_) => TrainingValueKind::Integer,
125			Self::Float(_) => TrainingValueKind::Float,
126			Self::String(_) => TrainingValueKind::String,
127		}
128	}
129
130	/// Convert an integer or float payload to a common numeric representation.
131	pub fn as_number(&self) -> Option<f64> {
132		match self {
133			Self::Integer(value) => Some(*value as f64),
134			Self::Float(value) => Some(*value),
135			Self::Empty | Self::Boolean(_) | Self::String(_) => None,
136		}
137	}
138}
139
140/// One command submitted by a session client.
141#[derive(Clone, Debug, PartialEq)]
142pub struct TrainingCommand {
143	/// Session-assigned sequence. Input values are overwritten by [`TrainingSession::enqueue`].
144	pub sequence: u64,
145	/// Required live revision, or zero to accept the current revision.
146	pub expected_revision: u64,
147	/// Requested action.
148	pub kind: TrainingCommandKind,
149	/// Parameter name for [`TrainingCommandKind::SetParameter`].
150	pub parameter: String,
151	/// Typed parameter or rebuild payload.
152	pub value: TrainingValue,
153}
154
155impl TrainingCommand {
156	fn new(kind: TrainingCommandKind, expected_revision: u64) -> Self {
157		Self {
158			sequence: 0,
159			expected_revision,
160			kind,
161			parameter: String::new(),
162			value: TrainingValue::Empty,
163		}
164	}
165}
166
167/// Cloneable failure evidence retained in a command result.
168#[derive(Clone, Debug, PartialEq, Eq)]
169pub struct TrainingCommandError {
170	kind: ErrorKind,
171	message: String,
172}
173
174impl TrainingCommandError {
175	/// Return the stable error category.
176	pub const fn kind(&self) -> ErrorKind {
177		self.kind
178	}
179
180	/// Return the contextual rejection message.
181	pub fn message(&self) -> &str {
182		&self.message
183	}
184
185	fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
186		Self {
187			kind,
188			message: message.into(),
189		}
190	}
191
192	fn from_error(error: &Error) -> Self {
193		Self::new(error.kind(), error.message())
194	}
195}
196
197/// One named scalar published with a completed-step snapshot.
198#[derive(Clone, Debug, PartialEq)]
199pub struct TrainingMetricSample {
200	/// Stable metric name.
201	pub name: String,
202	/// Finite scalar value.
203	pub value: f64,
204	/// Completed training step associated with this sample.
205	pub step: u64,
206}
207
208/// Bounded live-control snapshot published by an attached iterator.
209#[derive(Clone, Debug, PartialEq)]
210pub struct TrainingSessionSnapshot {
211	/// Session revision represented by this snapshot.
212	pub revision: u64,
213	/// Lifecycle state represented by this snapshot.
214	pub state: TrainingState,
215	/// Completed training steps.
216	pub step: u64,
217	/// Current one-based epoch, or zero when epochs are disabled.
218	pub epoch: u64,
219	/// Learning rate used by the next optimizer step.
220	pub learning_rate: f32,
221	/// Most recently completed loss, or zero before a loss is available.
222	pub loss: f32,
223	/// Most recent device duration in milliseconds, or zero when untimed.
224	pub gpu_ms: f64,
225	/// Mean wall-clock milliseconds per completed step.
226	pub wall_ms: f64,
227	/// Current named scalar metrics.
228	pub metrics: Vec<TrainingMetricSample>,
229}
230
231impl Default for TrainingSessionConfig {
232	fn default() -> Self {
233		Self {
234			command_capacity: 64,
235			result_capacity: 128,
236			snapshot_capacity: 256,
237		}
238	}
239}
240
241/// Engine-thread handlers invoked for application-owned commands.
242#[derive(Default)]
243pub struct TrainingSessionHandlers<'a> {
244	checkpoint: Option<CommandHandler<'a>>,
245	evaluate: Option<CommandHandler<'a>>,
246	rebuild: Option<RebuildHandler<'a>>,
247}
248
249impl<'a> TrainingSessionHandlers<'a> {
250	/// Install the checkpoint handler.
251	pub fn checkpoint(mut self, handler: impl FnMut() -> Result<()> + 'a) -> Self {
252		self.checkpoint = Some(Box::new(handler));
253		self
254	}
255
256	/// Install the evaluation handler.
257	pub fn evaluate(mut self, handler: impl FnMut() -> Result<()> + 'a) -> Self {
258		self.evaluate = Some(Box::new(handler));
259		self
260	}
261
262	/// Install the rebuild handler.
263	pub fn rebuild(mut self, handler: impl FnMut(&TrainingCommand) -> Result<()> + 'a) -> Self {
264		self.rebuild = Some(Box::new(handler));
265		self
266	}
267}
268
269/// Engine-thread descriptor for one session-visible parameter.
270pub struct TrainingParameterDesc<'a> {
271	name: String,
272	parameter_class: TrainingParameterClass,
273	kind: TrainingValueKind,
274	minimum: Option<f64>,
275	maximum: Option<f64>,
276	get: ValueGetter<'a>,
277	set: Option<ValueSetter<'a>>,
278}
279
280impl<'a> TrainingParameterDesc<'a> {
281	/// Describe a mutable parameter and its engine-thread accessors.
282	pub fn mutable(
283		name: impl Into<String>,
284		parameter_class: TrainingParameterClass,
285		kind: TrainingValueKind,
286		get: impl Fn() -> TrainingValue + 'a,
287		set: impl FnMut(&TrainingValue) -> Result<()> + 'a,
288	) -> Self {
289		Self {
290			name: name.into(),
291			parameter_class,
292			kind,
293			minimum: None,
294			maximum: None,
295			get: Box::new(get),
296			set: Some(Box::new(set)),
297		}
298	}
299
300	/// Describe an immutable observable parameter.
301	pub fn immutable(
302		name: impl Into<String>,
303		kind: TrainingValueKind,
304		get: impl Fn() -> TrainingValue + 'a,
305	) -> Self {
306		Self {
307			name: name.into(),
308			parameter_class: TrainingParameterClass::Immutable,
309			kind,
310			minimum: None,
311			maximum: None,
312			get: Box::new(get),
313			set: None,
314		}
315	}
316
317	/// Declare an inclusive numeric range.
318	pub fn numeric_range(mut self, minimum: f64, maximum: f64) -> Self {
319		self.minimum = Some(minimum);
320		self.maximum = Some(maximum);
321		self
322	}
323}
324
325struct Shared {
326	state: Mutex<SessionState>,
327	wake: Condvar,
328}
329
330struct SessionState {
331	config: TrainingSessionConfig,
332	state: TrainingState,
333	revision: u64,
334	next_sequence: u64,
335	take_sequence: u64,
336	attached: bool,
337	commands: VecDeque<TrainingCommand>,
338	results: VecDeque<TrainingCommandResult>,
339	snapshots: VecDeque<TrainingSessionSnapshot>,
340	parameters: Vec<(String, TrainingValue)>,
341	pending_metrics: Vec<TrainingMetricSample>,
342}
343
344/// Cloneable, thread-safe command and observation handle for one training loop.
345///
346/// Attach it to exactly one [`super::ItTraining`] instance. Clones may enqueue
347/// commands and read bounded evidence from UI, viewer, or service threads.
348#[derive(Clone)]
349pub struct TrainingSession {
350	shared: Arc<Shared>,
351}
352
353impl TrainingSession {
354	/// Construct an unattached live-control handle.
355	pub fn new(mut config: TrainingSessionConfig) -> Self {
356		config.command_capacity = config.command_capacity.max(1);
357		config.result_capacity = config.result_capacity.max(1);
358		config.snapshot_capacity = config.snapshot_capacity.max(1);
359		Self {
360			shared: Arc::new(Shared {
361				state: Mutex::new(SessionState {
362					config,
363					state: TrainingState::Running,
364					revision: 0,
365					next_sequence: 1,
366					take_sequence: 0,
367					attached: false,
368					commands: VecDeque::new(),
369					results: VecDeque::new(),
370					snapshots: VecDeque::new(),
371					parameters: Vec::new(),
372					pending_metrics: Vec::new(),
373				}),
374				wake: Condvar::new(),
375			}),
376		}
377	}
378
379	/// Enqueue one command without blocking.
380	///
381	/// # Errors
382	///
383	/// Returns [`ErrorKind::ResourceExhausted`] when the bounded queue is full.
384	pub fn enqueue(&self, mut command: TrainingCommand) -> Result<u64> {
385		let mut state = self.lock();
386		if state.commands.len() >= state.config.command_capacity {
387			return Err(Error::resource_exhausted(
388				"training session command queue is full",
389			));
390		}
391		let sequence = state.next_sequence;
392		state.next_sequence = state
393			.next_sequence
394			.checked_add(1)
395			.ok_or_else(|| Error::resource_exhausted("training command sequence exhausted"))?;
396		command.sequence = sequence;
397		state.commands.push_back(command);
398		drop(state);
399		self.shared.wake.notify_all();
400		Ok(sequence)
401	}
402
403	/// Enqueue a pause request.
404	pub fn pause(&self, expected_revision: u64) -> Result<u64> {
405		self.enqueue(TrainingCommand::new(
406			TrainingCommandKind::Pause,
407			expected_revision,
408		))
409	}
410
411	/// Enqueue a resume request.
412	pub fn resume(&self, expected_revision: u64) -> Result<u64> {
413		self.enqueue(TrainingCommand::new(
414			TrainingCommandKind::Resume,
415			expected_revision,
416		))
417	}
418
419	/// Enqueue a stop request.
420	pub fn stop(&self, expected_revision: u64) -> Result<u64> {
421		self.enqueue(TrainingCommand::new(
422			TrainingCommandKind::Stop,
423			expected_revision,
424		))
425	}
426
427	/// Enqueue a checkpoint request.
428	pub fn checkpoint(&self, expected_revision: u64) -> Result<u64> {
429		self.enqueue(TrainingCommand::new(
430			TrainingCommandKind::Checkpoint,
431			expected_revision,
432		))
433	}
434
435	/// Enqueue an evaluation request.
436	pub fn evaluate(&self, expected_revision: u64) -> Result<u64> {
437		self.enqueue(TrainingCommand::new(
438			TrainingCommandKind::Evaluate,
439			expected_revision,
440		))
441	}
442
443	/// Enqueue a typed parameter update.
444	pub fn set_parameter(
445		&self,
446		name: impl Into<String>,
447		value: TrainingValue,
448		expected_revision: u64,
449	) -> Result<u64> {
450		let mut command = TrainingCommand::new(TrainingCommandKind::SetParameter, expected_revision);
451		command.parameter = name.into();
452		command.value = value;
453		self.enqueue(command)
454	}
455
456	/// Enqueue a captured-program recapture request.
457	pub fn request_recapture(&self, expected_revision: u64) -> Result<u64> {
458		self.enqueue(TrainingCommand::new(
459			TrainingCommandKind::RequestRecapture,
460			expected_revision,
461		))
462	}
463
464	/// Enqueue an application-owned rebuild request.
465	pub fn request_rebuild(&self, value: TrainingValue, expected_revision: u64) -> Result<u64> {
466		let mut command = TrainingCommand::new(TrainingCommandKind::RequestRebuild, expected_revision);
467		command.value = value;
468		self.enqueue(command)
469	}
470
471	/// Publish or replace a named finite scalar for subsequent snapshots.
472	pub fn publish_metric(&self, name: impl Into<String>, value: f64) {
473		let name = name.into();
474		if name.is_empty() || !value.is_finite() {
475			return;
476		}
477		let mut state = self.lock();
478		if let Some(metric) = state
479			.pending_metrics
480			.iter_mut()
481			.find(|metric| metric.name == name)
482		{
483			metric.value = value;
484		} else {
485			state.pending_metrics.push(TrainingMetricSample {
486				name,
487				value,
488				step: 0,
489			});
490		}
491	}
492
493	/// Return the most recently cached value of a registered parameter.
494	pub fn parameter(&self, name: &str) -> Option<TrainingValue> {
495		self
496			.lock()
497			.parameters
498			.iter()
499			.find_map(|(candidate, value)| (candidate == name).then(|| value.clone()))
500	}
501
502	/// Return the current live state.
503	pub fn state(&self) -> TrainingState {
504		self.lock().state
505	}
506
507	/// Return the current optimistic-concurrency revision.
508	pub fn revision(&self) -> u64 {
509		self.lock().revision
510	}
511
512	/// Combine the live state and revision with the latest published metrics.
513	pub fn current_snapshot(&self) -> TrainingSessionSnapshot {
514		let state = self.lock();
515		let mut snapshot = state
516			.snapshots
517			.back()
518			.cloned()
519			.unwrap_or_else(|| TrainingSessionSnapshot {
520				revision: state.revision,
521				state: state.state,
522				step: 0,
523				epoch: 0,
524				learning_rate: 0.0,
525				loss: 0.0,
526				gpu_ms: 0.0,
527				wall_ms: 0.0,
528				metrics: Vec::new(),
529			});
530		snapshot.revision = state.revision;
531		snapshot.state = state.state;
532		snapshot
533	}
534
535	/// Return the latest published lifecycle snapshot.
536	pub fn latest_snapshot(&self) -> Option<TrainingSessionSnapshot> {
537		self.lock().snapshots.back().cloned()
538	}
539
540	/// Return retained results newer than an observer-owned sequence cursor.
541	pub fn results_after(&self, sequence: u64) -> Vec<TrainingCommandResult> {
542		self
543			.lock()
544			.results
545			.iter()
546			.filter(|result| result.sequence > sequence)
547			.cloned()
548			.collect()
549	}
550
551	/// Return results not previously consumed through this convenience cursor.
552	///
553	/// This does not delete retained results and therefore cannot steal evidence
554	/// from independent observers using [`TrainingSession::results_after`].
555	pub fn take_results(&self) -> Vec<TrainingCommandResult> {
556		let mut state = self.lock();
557		let results = state
558			.results
559			.iter()
560			.filter(|result| result.sequence > state.take_sequence)
561			.cloned()
562			.collect::<Vec<_>>();
563		if let Some(result) = results.last() {
564			state.take_sequence = result.sequence;
565		}
566		results
567	}
568
569	fn lock(&self) -> MutexGuard<'_, SessionState> {
570		self
571			.shared
572			.state
573			.lock()
574			.unwrap_or_else(std::sync::PoisonError::into_inner)
575	}
576
577	pub(crate) fn attach(&self, snapshot: TrainingSessionSnapshot) -> Result<()> {
578		let mut state = self.lock();
579		if state.attached {
580			return Err(Error::already_exists(
581				"training session is already attached to an iterator",
582			));
583		}
584		state.attached = true;
585		state.state = TrainingState::Running;
586		state.revision = state
587			.revision
588			.checked_add(1)
589			.ok_or_else(|| Error::resource_exhausted("training session revision exhausted"))?;
590		let mut snapshot = snapshot;
591		snapshot.revision = state.revision;
592		snapshot.state = state.state;
593		let capacity = state.config.snapshot_capacity;
594		push_bounded(&mut state.snapshots, snapshot, capacity);
595		drop(state);
596		self.shared.wake.notify_all();
597		Ok(())
598	}
599
600	pub(crate) fn drain_commands(&self) -> Vec<TrainingCommand> {
601		self.lock().commands.drain(..).collect()
602	}
603
604	pub(crate) fn command_context(&self) -> (TrainingState, u64) {
605		let state = self.lock();
606		(state.state, state.revision)
607	}
608
609	pub(crate) fn record_result(
610		&self,
611		command: &TrainingCommand,
612		transition: Option<TrainingState>,
613		error: Option<TrainingCommandError>,
614	) {
615		let mut state = self.lock();
616		if error.is_none() {
617			if let Some(next) = transition {
618				state.state = next;
619			}
620			state.revision = state.revision.saturating_add(1);
621		}
622		let result = TrainingCommandResult {
623			sequence: command.sequence,
624			revision: state.revision,
625			disposition: if error.is_none() {
626				TrainingCommandDisposition::Applied
627			} else {
628				TrainingCommandDisposition::Rejected
629			},
630			state: state.state,
631			error,
632		};
633		let capacity = state.config.result_capacity;
634		push_bounded(&mut state.results, result, capacity);
635		drop(state);
636		self.shared.wake.notify_all();
637	}
638
639	pub(crate) fn cache_parameter(&self, name: String, value: TrainingValue) -> Result<()> {
640		let mut state = self.lock();
641		if state
642			.parameters
643			.iter()
644			.any(|(candidate, _)| candidate == &name)
645		{
646			return Err(Error::already_exists(format!(
647				"training session parameter already exists: {name}"
648			)));
649		}
650		state.parameters.push((name, value));
651		Ok(())
652	}
653
654	pub(crate) fn update_parameter(&self, name: &str, value: TrainingValue) {
655		if let Some((_, cached)) = self
656			.lock()
657			.parameters
658			.iter_mut()
659			.find(|(candidate, _)| candidate == name)
660		{
661			*cached = value;
662		}
663	}
664
665	pub(crate) fn publish(
666		&self,
667		snapshot: TrainingSnapshot,
668		learning_rate: f32,
669		terminal: Option<TrainingState>,
670	) {
671		let mut state = self.lock();
672		if let Some(terminal) = terminal {
673			state.state = terminal;
674			state.revision = state.revision.saturating_add(1);
675		}
676		let metrics = state
677			.pending_metrics
678			.iter()
679			.cloned()
680			.map(|mut metric| {
681				metric.step = snapshot.step_count();
682				metric
683			})
684			.collect();
685		let live = TrainingSessionSnapshot {
686			revision: state.revision,
687			state: state.state,
688			step: snapshot.step_count(),
689			epoch: snapshot.epoch(),
690			learning_rate,
691			loss: snapshot.last_loss().unwrap_or(0.0),
692			gpu_ms: snapshot
693				.last_gpu_time()
694				.unwrap_or(Duration::ZERO)
695				.as_secs_f64()
696				* 1000.0,
697			wall_ms: snapshot.wall_ms_per_step(),
698			metrics,
699		};
700		let capacity = state.config.snapshot_capacity;
701		push_bounded(&mut state.snapshots, live, capacity);
702		drop(state);
703		self.shared.wake.notify_all();
704	}
705
706	pub(crate) fn wait_while_paused(&self) {
707		let mut state = self.lock();
708		while state.state == TrainingState::Paused && state.commands.is_empty() {
709			state = self
710				.shared
711				.wake
712				.wait(state)
713				.unwrap_or_else(std::sync::PoisonError::into_inner);
714		}
715	}
716}
717
718impl Default for TrainingSession {
719	fn default() -> Self {
720		Self::new(TrainingSessionConfig::default())
721	}
722}
723
724pub(crate) struct TrainingSessionAttachment<'a> {
725	pub(crate) session: TrainingSession,
726	handlers: TrainingSessionHandlers<'a>,
727	parameters: Vec<TrainingParameterDesc<'a>>,
728}
729
730#[derive(Default)]
731pub(crate) struct SessionActions {
732	pub(crate) stop: bool,
733	pub(crate) recapture: bool,
734}
735
736impl<'a> TrainingSessionAttachment<'a> {
737	pub(crate) fn new(session: TrainingSession, handlers: TrainingSessionHandlers<'a>) -> Self {
738		Self {
739			session,
740			handlers,
741			parameters: Vec::new(),
742		}
743	}
744
745	pub(crate) fn register_parameter(&mut self, desc: TrainingParameterDesc<'a>) -> Result<()> {
746		if desc.name.is_empty() || desc.minimum.zip(desc.maximum).is_some_and(|(a, b)| a > b) {
747			return Err(Error::invalid_argument(
748				"training parameter requires a name and an ordered numeric range",
749			));
750		}
751		if desc.parameter_class != TrainingParameterClass::Immutable && desc.set.is_none() {
752			return Err(Error::invalid_argument(
753				"mutable training parameter requires a setter",
754			));
755		}
756		let value = (desc.get)();
757		if value.kind() != desc.kind {
758			return Err(Error::invalid_argument(
759				"training parameter getter kind does not match its declaration",
760			));
761		}
762		self.session.cache_parameter(desc.name.clone(), value)?;
763		self.parameters.push(desc);
764		Ok(())
765	}
766
767	pub(crate) fn poll(
768		&mut self,
769		optimizer: &mut dyn Optimizer,
770		can_recapture: bool,
771	) -> SessionActions {
772		let mut actions = SessionActions::default();
773		for command in self.session.drain_commands() {
774			let (state, revision) = self.session.command_context();
775			let mut transition = None;
776			let error = if command.expected_revision != 0 && command.expected_revision != revision {
777				Some(TrainingCommandError::new(
778					ErrorKind::Aborted,
779					"training session command revision is stale",
780				))
781			} else {
782				match command.kind {
783					TrainingCommandKind::Pause if state != TrainingState::Running => {
784						Some(TrainingCommandError::new(
785							ErrorKind::FailedPrecondition,
786							"pause requires a running training session",
787						))
788					}
789					TrainingCommandKind::Pause => {
790						transition = Some(TrainingState::Paused);
791						None
792					}
793					TrainingCommandKind::Resume if state != TrainingState::Paused => {
794						Some(TrainingCommandError::new(
795							ErrorKind::FailedPrecondition,
796							"resume requires a paused training session",
797						))
798					}
799					TrainingCommandKind::Resume => {
800						transition = Some(TrainingState::Running);
801						None
802					}
803					TrainingCommandKind::Stop if state.is_terminal() => Some(TrainingCommandError::new(
804						ErrorKind::FailedPrecondition,
805						"stop requires an active training session",
806					)),
807					TrainingCommandKind::Stop => {
808						actions.stop = true;
809						transition = Some(TrainingState::Stopping);
810						None
811					}
812					TrainingCommandKind::Checkpoint => {
813						invoke_handler(self.handlers.checkpoint.as_mut(), "checkpoint")
814					}
815					TrainingCommandKind::Evaluate => {
816						invoke_handler(self.handlers.evaluate.as_mut(), "evaluation")
817					}
818					TrainingCommandKind::SetParameter => self.set_parameter(&command, state, optimizer),
819					TrainingCommandKind::RequestRecapture if state != TrainingState::Paused => {
820						Some(TrainingCommandError::new(
821							ErrorKind::FailedPrecondition,
822							"program recapture requires a paused session",
823						))
824					}
825					TrainingCommandKind::RequestRecapture if !can_recapture => {
826						Some(TrainingCommandError::new(
827							ErrorKind::FailedPrecondition,
828							"training program recapture requires automatic capture",
829						))
830					}
831					TrainingCommandKind::RequestRecapture => {
832						actions.recapture = true;
833						None
834					}
835					TrainingCommandKind::RequestRebuild if state != TrainingState::Paused => {
836						Some(TrainingCommandError::new(
837							ErrorKind::FailedPrecondition,
838							"training rebuild requires a paused session",
839						))
840					}
841					TrainingCommandKind::RequestRebuild => match self.handlers.rebuild.as_mut() {
842						Some(handler) => handler(&command)
843							.err()
844							.as_ref()
845							.map(TrainingCommandError::from_error),
846						None => Some(missing_handler("rebuild")),
847					},
848				}
849			};
850			self.session.record_result(&command, transition, error);
851		}
852		actions
853	}
854
855	fn set_parameter(
856		&mut self,
857		command: &TrainingCommand,
858		state: TrainingState,
859		optimizer: &mut dyn Optimizer,
860	) -> Option<TrainingCommandError> {
861		if command.parameter == "learning_rate" {
862			let Some(value) = command.value.as_number() else {
863				return Some(kind_mismatch());
864			};
865			let result = if !value.is_finite() || value.abs() > f64::from(f32::MAX) {
866				Err(Error::out_of_range("learning rate is outside f32 range"))
867			} else {
868				optimizer.set_learning_rate(value as f32)
869			};
870			return match result {
871				Ok(()) => {
872					self.session.update_parameter(
873						"learning_rate",
874						TrainingValue::Float(f64::from(optimizer.learning_rate())),
875					);
876					None
877				}
878				Err(error) => Some(TrainingCommandError::from_error(&error)),
879			};
880		}
881		let Some(parameter) = self
882			.parameters
883			.iter_mut()
884			.find(|parameter| parameter.name == command.parameter)
885		else {
886			return Some(TrainingCommandError::new(
887				ErrorKind::NotFound,
888				format!("unknown training parameter: {}", command.parameter),
889			));
890		};
891		if parameter.parameter_class == TrainingParameterClass::Immutable {
892			return Some(TrainingCommandError::new(
893				ErrorKind::FailedPrecondition,
894				format!("training parameter is immutable: {}", command.parameter),
895			));
896		}
897		if parameter.parameter_class != TrainingParameterClass::Hot && state != TrainingState::Paused {
898			return Some(TrainingCommandError::new(
899				ErrorKind::FailedPrecondition,
900				"recapture/rebuild parameters require a paused session",
901			));
902		}
903		if command.value.kind() != parameter.kind
904			&& !(parameter.kind == TrainingValueKind::Float
905				&& command.value.kind() == TrainingValueKind::Integer)
906		{
907			return Some(kind_mismatch());
908		}
909		if let Some(number) = command.value.as_number()
910			&& (parameter.minimum.is_some_and(|minimum| number < minimum)
911				|| parameter.maximum.is_some_and(|maximum| number > maximum))
912		{
913			return Some(TrainingCommandError::new(
914				ErrorKind::OutOfRange,
915				"training parameter value is outside its declared range",
916			));
917		}
918		let Some(set) = parameter.set.as_mut() else {
919			return Some(TrainingCommandError::new(
920				ErrorKind::FailedPrecondition,
921				"training parameter does not admit mutation",
922			));
923		};
924		if let Err(error) = set(&command.value) {
925			return Some(TrainingCommandError::from_error(&error));
926		}
927		self
928			.session
929			.update_parameter(&parameter.name, (parameter.get)());
930		None
931	}
932}
933
934fn invoke_handler(
935	handler: Option<&mut CommandHandler<'_>>,
936	name: &'static str,
937) -> Option<TrainingCommandError> {
938	match handler {
939		Some(handler) => handler()
940			.err()
941			.as_ref()
942			.map(TrainingCommandError::from_error),
943		None => Some(missing_handler(name)),
944	}
945}
946
947fn missing_handler(name: &'static str) -> TrainingCommandError {
948	TrainingCommandError::new(
949		ErrorKind::FailedPrecondition,
950		format!("training session has no {name} handler"),
951	)
952}
953
954fn kind_mismatch() -> TrainingCommandError {
955	TrainingCommandError::new(
956		ErrorKind::InvalidArgument,
957		"training parameter value kind does not match its declaration",
958	)
959}
960
961fn push_bounded<T>(queue: &mut VecDeque<T>, value: T, capacity: usize) {
962	while queue.len() >= capacity {
963		queue.pop_front();
964	}
965	queue.push_back(value);
966}