Skip to main content

oa/ml/training/
session.rs

1//! Thread-safe live control and bounded observation for [`super::Training`].
2//!
3//! The public [`TrainingSession`] is a cloneable command and observation handle.
4//! The training iterator remains on its owning runtime 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/// Runtime-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	/// Construct an empty set of application command handlers.
251	#[inline]
252	#[must_use]
253	pub fn new() -> Self {
254		Self::default()
255	}
256
257	/// Install the checkpoint handler.
258	pub fn checkpoint(mut self, handler: impl FnMut() -> Result<()> + 'a) -> Self {
259		self.checkpoint = Some(Box::new(handler));
260		self
261	}
262
263	/// Install the evaluation handler.
264	pub fn evaluate(mut self, handler: impl FnMut() -> Result<()> + 'a) -> Self {
265		self.evaluate = Some(Box::new(handler));
266		self
267	}
268
269	/// Install the rebuild handler.
270	pub fn rebuild(mut self, handler: impl FnMut(&TrainingCommand) -> Result<()> + 'a) -> Self {
271		self.rebuild = Some(Box::new(handler));
272		self
273	}
274}
275
276/// Runtime-thread descriptor for one session-visible parameter.
277pub struct TrainingParameterDesc<'a> {
278	name: String,
279	parameter_class: TrainingParameterClass,
280	kind: TrainingValueKind,
281	minimum: Option<f64>,
282	maximum: Option<f64>,
283	get: ValueGetter<'a>,
284	set: Option<ValueSetter<'a>>,
285}
286
287impl<'a> TrainingParameterDesc<'a> {
288	/// Describe a mutable parameter and its runtime-thread accessors.
289	pub fn mutable(
290		name: impl Into<String>,
291		parameter_class: TrainingParameterClass,
292		kind: TrainingValueKind,
293		get: impl Fn() -> TrainingValue + 'a,
294		set: impl FnMut(&TrainingValue) -> Result<()> + 'a,
295	) -> Self {
296		Self {
297			name: name.into(),
298			parameter_class,
299			kind,
300			minimum: None,
301			maximum: None,
302			get: Box::new(get),
303			set: Some(Box::new(set)),
304		}
305	}
306
307	/// Describe an immutable observable parameter.
308	pub fn immutable(
309		name: impl Into<String>,
310		kind: TrainingValueKind,
311		get: impl Fn() -> TrainingValue + 'a,
312	) -> Self {
313		Self {
314			name: name.into(),
315			parameter_class: TrainingParameterClass::Immutable,
316			kind,
317			minimum: None,
318			maximum: None,
319			get: Box::new(get),
320			set: None,
321		}
322	}
323
324	/// Declare an inclusive numeric range.
325	pub fn numeric_range(mut self, minimum: f64, maximum: f64) -> Self {
326		self.minimum = Some(minimum);
327		self.maximum = Some(maximum);
328		self
329	}
330}
331
332struct Shared {
333	state: Mutex<SessionState>,
334	wake: Condvar,
335}
336
337struct SessionState {
338	config: TrainingSessionConfig,
339	state: TrainingState,
340	revision: u64,
341	next_sequence: u64,
342	take_sequence: u64,
343	attached: bool,
344	commands: VecDeque<TrainingCommand>,
345	results: VecDeque<TrainingCommandResult>,
346	snapshots: VecDeque<TrainingSessionSnapshot>,
347	parameters: Vec<(String, TrainingValue)>,
348	pending_metrics: Vec<TrainingMetricSample>,
349}
350
351/// Cloneable, thread-safe command and observation handle for one training loop.
352///
353/// Attach it to exactly one [`super::Training`] instance. Clones may enqueue
354/// commands and read bounded evidence from UI, viewer, or service threads.
355#[derive(Clone)]
356pub struct TrainingSession {
357	shared: Arc<Shared>,
358}
359
360impl TrainingSession {
361	/// Construct an unattached live-control handle.
362	pub fn new(mut config: TrainingSessionConfig) -> Self {
363		config.command_capacity = config.command_capacity.max(1);
364		config.result_capacity = config.result_capacity.max(1);
365		config.snapshot_capacity = config.snapshot_capacity.max(1);
366		Self {
367			shared: Arc::new(Shared {
368				state: Mutex::new(SessionState {
369					config,
370					state: TrainingState::Running,
371					revision: 0,
372					next_sequence: 1,
373					take_sequence: 0,
374					attached: false,
375					commands: VecDeque::new(),
376					results: VecDeque::new(),
377					snapshots: VecDeque::new(),
378					parameters: Vec::new(),
379					pending_metrics: Vec::new(),
380				}),
381				wake: Condvar::new(),
382			}),
383		}
384	}
385
386	/// Enqueue one command without blocking.
387	///
388	/// # Errors
389	///
390	/// Returns [`ErrorKind::ResourceExhausted`] when the bounded queue is full.
391	pub fn enqueue(&self, mut command: TrainingCommand) -> Result<u64> {
392		let mut state = self.lock();
393		if state.commands.len() >= state.config.command_capacity {
394			return Err(Error::resource_exhausted(
395				"training session command queue is full",
396			));
397		}
398		let sequence = state.next_sequence;
399		state.next_sequence = state
400			.next_sequence
401			.checked_add(1)
402			.ok_or_else(|| Error::resource_exhausted("training command sequence exhausted"))?;
403		command.sequence = sequence;
404		state.commands.push_back(command);
405		drop(state);
406		self.shared.wake.notify_all();
407		Ok(sequence)
408	}
409
410	/// Enqueue a pause request.
411	pub fn pause(&self, expected_revision: u64) -> Result<u64> {
412		self.enqueue(TrainingCommand::new(
413			TrainingCommandKind::Pause,
414			expected_revision,
415		))
416	}
417
418	/// Enqueue a resume request.
419	pub fn resume(&self, expected_revision: u64) -> Result<u64> {
420		self.enqueue(TrainingCommand::new(
421			TrainingCommandKind::Resume,
422			expected_revision,
423		))
424	}
425
426	/// Enqueue a stop request.
427	pub fn stop(&self, expected_revision: u64) -> Result<u64> {
428		self.enqueue(TrainingCommand::new(
429			TrainingCommandKind::Stop,
430			expected_revision,
431		))
432	}
433
434	/// Enqueue a checkpoint request.
435	pub fn checkpoint(&self, expected_revision: u64) -> Result<u64> {
436		self.enqueue(TrainingCommand::new(
437			TrainingCommandKind::Checkpoint,
438			expected_revision,
439		))
440	}
441
442	/// Enqueue an evaluation request.
443	pub fn evaluate(&self, expected_revision: u64) -> Result<u64> {
444		self.enqueue(TrainingCommand::new(
445			TrainingCommandKind::Evaluate,
446			expected_revision,
447		))
448	}
449
450	/// Enqueue a typed parameter update.
451	pub fn set_parameter(
452		&self,
453		name: impl Into<String>,
454		value: TrainingValue,
455		expected_revision: u64,
456	) -> Result<u64> {
457		let mut command = TrainingCommand::new(TrainingCommandKind::SetParameter, expected_revision);
458		command.parameter = name.into();
459		command.value = value;
460		self.enqueue(command)
461	}
462
463	/// Enqueue a captured-program recapture request.
464	pub fn request_recapture(&self, expected_revision: u64) -> Result<u64> {
465		self.enqueue(TrainingCommand::new(
466			TrainingCommandKind::RequestRecapture,
467			expected_revision,
468		))
469	}
470
471	/// Enqueue an application-owned rebuild request.
472	pub fn request_rebuild(&self, value: TrainingValue, expected_revision: u64) -> Result<u64> {
473		let mut command = TrainingCommand::new(TrainingCommandKind::RequestRebuild, expected_revision);
474		command.value = value;
475		self.enqueue(command)
476	}
477
478	/// Publish or replace a named finite scalar for subsequent snapshots.
479	pub fn publish_metric(&self, name: impl Into<String>, value: f64) {
480		let name = name.into();
481		if name.is_empty() || !value.is_finite() {
482			return;
483		}
484		let mut state = self.lock();
485		if let Some(metric) = state
486			.pending_metrics
487			.iter_mut()
488			.find(|metric| metric.name == name)
489		{
490			metric.value = value;
491		} else {
492			state.pending_metrics.push(TrainingMetricSample {
493				name,
494				value,
495				step: 0,
496			});
497		}
498	}
499
500	/// Return the most recently cached value of a registered parameter.
501	pub fn parameter(&self, name: &str) -> Option<TrainingValue> {
502		self
503			.lock()
504			.parameters
505			.iter()
506			.find_map(|(candidate, value)| (candidate == name).then(|| value.clone()))
507	}
508
509	/// Return the current live state.
510	pub fn state(&self) -> TrainingState {
511		self.lock().state
512	}
513
514	/// Return the current optimistic-concurrency revision.
515	pub fn revision(&self) -> u64 {
516		self.lock().revision
517	}
518
519	/// Combine the live state and revision with the latest published metrics.
520	pub fn current_snapshot(&self) -> TrainingSessionSnapshot {
521		let state = self.lock();
522		let mut snapshot = state
523			.snapshots
524			.back()
525			.cloned()
526			.unwrap_or_else(|| TrainingSessionSnapshot {
527				revision: state.revision,
528				state: state.state,
529				step: 0,
530				epoch: 0,
531				learning_rate: 0.0,
532				loss: 0.0,
533				gpu_ms: 0.0,
534				wall_ms: 0.0,
535				metrics: Vec::new(),
536			});
537		snapshot.revision = state.revision;
538		snapshot.state = state.state;
539		snapshot
540	}
541
542	/// Return the latest published lifecycle snapshot.
543	pub fn latest_snapshot(&self) -> Option<TrainingSessionSnapshot> {
544		self.lock().snapshots.back().cloned()
545	}
546
547	/// Return retained results newer than an observer-owned sequence cursor.
548	pub fn results_after(&self, sequence: u64) -> Vec<TrainingCommandResult> {
549		self
550			.lock()
551			.results
552			.iter()
553			.filter(|result| result.sequence > sequence)
554			.cloned()
555			.collect()
556	}
557
558	/// Return results not previously consumed through this convenience cursor.
559	///
560	/// This does not delete retained results and therefore cannot steal evidence
561	/// from independent observers using [`TrainingSession::results_after`].
562	pub fn take_results(&self) -> Vec<TrainingCommandResult> {
563		let mut state = self.lock();
564		let results = state
565			.results
566			.iter()
567			.filter(|result| result.sequence > state.take_sequence)
568			.cloned()
569			.collect::<Vec<_>>();
570		if let Some(result) = results.last() {
571			state.take_sequence = result.sequence;
572		}
573		results
574	}
575
576	fn lock(&self) -> MutexGuard<'_, SessionState> {
577		self
578			.shared
579			.state
580			.lock()
581			.unwrap_or_else(std::sync::PoisonError::into_inner)
582	}
583
584	pub(crate) fn attach(&self, snapshot: TrainingSessionSnapshot) -> Result<()> {
585		let mut state = self.lock();
586		if state.attached {
587			return Err(Error::already_exists(
588				"training session is already attached to an iterator",
589			));
590		}
591		state.attached = true;
592		state.state = TrainingState::Running;
593		state.revision = state
594			.revision
595			.checked_add(1)
596			.ok_or_else(|| Error::resource_exhausted("training session revision exhausted"))?;
597		let mut snapshot = snapshot;
598		snapshot.revision = state.revision;
599		snapshot.state = state.state;
600		let capacity = state.config.snapshot_capacity;
601		push_bounded(&mut state.snapshots, snapshot, capacity);
602		drop(state);
603		self.shared.wake.notify_all();
604		Ok(())
605	}
606
607	pub(crate) fn drain_commands(&self) -> Vec<TrainingCommand> {
608		self.lock().commands.drain(..).collect()
609	}
610
611	pub(crate) fn command_context(&self) -> (TrainingState, u64) {
612		let state = self.lock();
613		(state.state, state.revision)
614	}
615
616	pub(crate) fn record_result(
617		&self,
618		command: &TrainingCommand,
619		transition: Option<TrainingState>,
620		error: Option<TrainingCommandError>,
621	) {
622		let mut state = self.lock();
623		if error.is_none() {
624			if let Some(next) = transition {
625				state.state = next;
626			}
627			state.revision = state.revision.saturating_add(1);
628		}
629		let result = TrainingCommandResult {
630			sequence: command.sequence,
631			revision: state.revision,
632			disposition: if error.is_none() {
633				TrainingCommandDisposition::Applied
634			} else {
635				TrainingCommandDisposition::Rejected
636			},
637			state: state.state,
638			error,
639		};
640		let capacity = state.config.result_capacity;
641		push_bounded(&mut state.results, result, capacity);
642		drop(state);
643		self.shared.wake.notify_all();
644	}
645
646	pub(crate) fn cache_parameter(&self, name: String, value: TrainingValue) -> Result<()> {
647		let mut state = self.lock();
648		if state
649			.parameters
650			.iter()
651			.any(|(candidate, _)| candidate == &name)
652		{
653			return Err(Error::already_exists(format!(
654				"training session parameter already exists: {name}"
655			)));
656		}
657		state.parameters.push((name, value));
658		Ok(())
659	}
660
661	pub(crate) fn update_parameter(&self, name: &str, value: TrainingValue) {
662		if let Some((_, cached)) = self
663			.lock()
664			.parameters
665			.iter_mut()
666			.find(|(candidate, _)| candidate == name)
667		{
668			*cached = value;
669		}
670	}
671
672	pub(crate) fn publish(
673		&self,
674		snapshot: TrainingSnapshot,
675		learning_rate: f32,
676		terminal: Option<TrainingState>,
677	) {
678		let mut state = self.lock();
679		if let Some(terminal) = terminal {
680			state.state = terminal;
681			state.revision = state.revision.saturating_add(1);
682		}
683		let metrics = state
684			.pending_metrics
685			.iter()
686			.cloned()
687			.map(|mut metric| {
688				metric.step = snapshot.step_count();
689				metric
690			})
691			.collect();
692		let live = TrainingSessionSnapshot {
693			revision: state.revision,
694			state: state.state,
695			step: snapshot.step_count(),
696			epoch: snapshot.epoch(),
697			learning_rate,
698			loss: snapshot.last_loss().unwrap_or(0.0),
699			gpu_ms: snapshot
700				.last_gpu_time()
701				.unwrap_or(Duration::ZERO)
702				.as_secs_f64()
703				* 1000.0,
704			wall_ms: snapshot.wall_ms_per_step(),
705			metrics,
706		};
707		let capacity = state.config.snapshot_capacity;
708		push_bounded(&mut state.snapshots, live, capacity);
709		drop(state);
710		self.shared.wake.notify_all();
711	}
712
713	pub(crate) fn wait_while_paused(&self) {
714		let mut state = self.lock();
715		while state.state == TrainingState::Paused && state.commands.is_empty() {
716			state = self
717				.shared
718				.wake
719				.wait(state)
720				.unwrap_or_else(std::sync::PoisonError::into_inner);
721		}
722	}
723}
724
725impl Default for TrainingSession {
726	fn default() -> Self {
727		Self::new(TrainingSessionConfig::default())
728	}
729}
730
731pub(crate) struct TrainingSessionAttachment<'a> {
732	pub(crate) session: TrainingSession,
733	handlers: TrainingSessionHandlers<'a>,
734	parameters: Vec<TrainingParameterDesc<'a>>,
735}
736
737#[derive(Default)]
738pub(crate) struct SessionActions {
739	pub(crate) stop: bool,
740	pub(crate) recapture: bool,
741}
742
743impl<'a> TrainingSessionAttachment<'a> {
744	pub(crate) fn new(session: TrainingSession, handlers: TrainingSessionHandlers<'a>) -> Self {
745		Self {
746			session,
747			handlers,
748			parameters: Vec::new(),
749		}
750	}
751
752	pub(crate) fn register_parameter(&mut self, desc: TrainingParameterDesc<'a>) -> Result<()> {
753		if desc.name.is_empty() || desc.minimum.zip(desc.maximum).is_some_and(|(a, b)| a > b) {
754			return Err(Error::invalid_argument(
755				"training parameter requires a name and an ordered numeric range",
756			));
757		}
758		if desc.parameter_class != TrainingParameterClass::Immutable && desc.set.is_none() {
759			return Err(Error::invalid_argument(
760				"mutable training parameter requires a setter",
761			));
762		}
763		let value = (desc.get)();
764		if value.kind() != desc.kind {
765			return Err(Error::invalid_argument(
766				"training parameter getter kind does not match its declaration",
767			));
768		}
769		self.session.cache_parameter(desc.name.clone(), value)?;
770		self.parameters.push(desc);
771		Ok(())
772	}
773
774	pub(crate) fn poll(
775		&mut self,
776		optimizer: &mut dyn Optimizer,
777		can_recapture: bool,
778	) -> SessionActions {
779		let mut actions = SessionActions::default();
780		for command in self.session.drain_commands() {
781			let (state, revision) = self.session.command_context();
782			let mut transition = None;
783			let error = if command.expected_revision != 0 && command.expected_revision != revision {
784				Some(TrainingCommandError::new(
785					ErrorKind::Aborted,
786					"training session command revision is stale",
787				))
788			} else {
789				match command.kind {
790					TrainingCommandKind::Pause if state != TrainingState::Running => {
791						Some(TrainingCommandError::new(
792							ErrorKind::FailedPrecondition,
793							"pause requires a running training session",
794						))
795					}
796					TrainingCommandKind::Pause => {
797						transition = Some(TrainingState::Paused);
798						None
799					}
800					TrainingCommandKind::Resume if state != TrainingState::Paused => {
801						Some(TrainingCommandError::new(
802							ErrorKind::FailedPrecondition,
803							"resume requires a paused training session",
804						))
805					}
806					TrainingCommandKind::Resume => {
807						transition = Some(TrainingState::Running);
808						None
809					}
810					TrainingCommandKind::Stop if state.is_terminal() => Some(TrainingCommandError::new(
811						ErrorKind::FailedPrecondition,
812						"stop requires an active training session",
813					)),
814					TrainingCommandKind::Stop => {
815						actions.stop = true;
816						transition = Some(TrainingState::Stopping);
817						None
818					}
819					TrainingCommandKind::Checkpoint => {
820						invoke_handler(self.handlers.checkpoint.as_mut(), "checkpoint")
821					}
822					TrainingCommandKind::Evaluate => {
823						invoke_handler(self.handlers.evaluate.as_mut(), "evaluation")
824					}
825					TrainingCommandKind::SetParameter => self.set_parameter(&command, state, optimizer),
826					TrainingCommandKind::RequestRecapture if state != TrainingState::Paused => {
827						Some(TrainingCommandError::new(
828							ErrorKind::FailedPrecondition,
829							"program recapture requires a paused session",
830						))
831					}
832					TrainingCommandKind::RequestRecapture if !can_recapture => {
833						Some(TrainingCommandError::new(
834							ErrorKind::FailedPrecondition,
835							"training program recapture requires automatic capture",
836						))
837					}
838					TrainingCommandKind::RequestRecapture => {
839						actions.recapture = true;
840						None
841					}
842					TrainingCommandKind::RequestRebuild if state != TrainingState::Paused => {
843						Some(TrainingCommandError::new(
844							ErrorKind::FailedPrecondition,
845							"training rebuild requires a paused session",
846						))
847					}
848					TrainingCommandKind::RequestRebuild => match self.handlers.rebuild.as_mut() {
849						Some(handler) => handler(&command)
850							.err()
851							.as_ref()
852							.map(TrainingCommandError::from_error),
853						None => Some(missing_handler("rebuild")),
854					},
855				}
856			};
857			self.session.record_result(&command, transition, error);
858		}
859		actions
860	}
861
862	fn set_parameter(
863		&mut self,
864		command: &TrainingCommand,
865		state: TrainingState,
866		optimizer: &mut dyn Optimizer,
867	) -> Option<TrainingCommandError> {
868		if command.parameter == "learning_rate" {
869			let Some(value) = command.value.as_number() else {
870				return Some(kind_mismatch());
871			};
872			let result = if !value.is_finite() || value.abs() > f64::from(f32::MAX) {
873				Err(Error::out_of_range("learning rate is outside f32 range"))
874			} else {
875				optimizer.set_learning_rate(value as f32)
876			};
877			return match result {
878				Ok(()) => {
879					self.session.update_parameter(
880						"learning_rate",
881						TrainingValue::Float(f64::from(optimizer.learning_rate())),
882					);
883					None
884				}
885				Err(error) => Some(TrainingCommandError::from_error(&error)),
886			};
887		}
888		let Some(parameter) = self
889			.parameters
890			.iter_mut()
891			.find(|parameter| parameter.name == command.parameter)
892		else {
893			return Some(TrainingCommandError::new(
894				ErrorKind::NotFound,
895				format!("unknown training parameter: {}", command.parameter),
896			));
897		};
898		if parameter.parameter_class == TrainingParameterClass::Immutable {
899			return Some(TrainingCommandError::new(
900				ErrorKind::FailedPrecondition,
901				format!("training parameter is immutable: {}", command.parameter),
902			));
903		}
904		if parameter.parameter_class != TrainingParameterClass::Hot && state != TrainingState::Paused {
905			return Some(TrainingCommandError::new(
906				ErrorKind::FailedPrecondition,
907				"recapture/rebuild parameters require a paused session",
908			));
909		}
910		if command.value.kind() != parameter.kind
911			&& !(parameter.kind == TrainingValueKind::Float
912				&& command.value.kind() == TrainingValueKind::Integer)
913		{
914			return Some(kind_mismatch());
915		}
916		if let Some(number) = command.value.as_number()
917			&& (parameter.minimum.is_some_and(|minimum| number < minimum)
918				|| parameter.maximum.is_some_and(|maximum| number > maximum))
919		{
920			return Some(TrainingCommandError::new(
921				ErrorKind::OutOfRange,
922				"training parameter value is outside its declared range",
923			));
924		}
925		let Some(set) = parameter.set.as_mut() else {
926			return Some(TrainingCommandError::new(
927				ErrorKind::FailedPrecondition,
928				"training parameter does not admit mutation",
929			));
930		};
931		if let Err(error) = set(&command.value) {
932			return Some(TrainingCommandError::from_error(&error));
933		}
934		self
935			.session
936			.update_parameter(&parameter.name, (parameter.get)());
937		None
938	}
939}
940
941fn invoke_handler(
942	handler: Option<&mut CommandHandler<'_>>,
943	name: &'static str,
944) -> Option<TrainingCommandError> {
945	match handler {
946		Some(handler) => handler()
947			.err()
948			.as_ref()
949			.map(TrainingCommandError::from_error),
950		None => Some(missing_handler(name)),
951	}
952}
953
954fn missing_handler(name: &'static str) -> TrainingCommandError {
955	TrainingCommandError::new(
956		ErrorKind::FailedPrecondition,
957		format!("training session has no {name} handler"),
958	)
959}
960
961fn kind_mismatch() -> TrainingCommandError {
962	TrainingCommandError::new(
963		ErrorKind::InvalidArgument,
964		"training parameter value kind does not match its declaration",
965	)
966}
967
968fn push_bounded<T>(queue: &mut VecDeque<T>, value: T, capacity: usize) {
969	while queue.len() >= capacity {
970		queue.pop_front();
971	}
972	queue.push_back(value);
973}