1#![allow(clippy::module_name_repetitions)]
7
8use std::{error::Error, fmt};
9
10use serde_json::{Value, json};
11
12use crate::{DataError, FailureMetadata};
13
14const MODULE: &str = "dataexcept::ml";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct ModelTrainingError {
19 pub model_type: String,
21 pub epoch: Option<u64>,
23 message: String,
24}
25
26impl ModelTrainingError {
27 #[must_use]
29 pub fn new(model_type: impl Into<String>, epoch: Option<u64>, message: Option<String>) -> Self {
30 let model_type = model_type.into();
31 let default = epoch.map_or_else(
32 || format!("Training failed for model '{model_type}'"),
33 |epoch| format!("Training failed for model '{model_type}' at epoch {epoch}"),
34 );
35
36 Self {
37 model_type,
38 epoch,
39 message: message.unwrap_or(default),
40 }
41 }
42
43 #[must_use]
45 pub fn message(&self) -> &str {
46 &self.message
47 }
48}
49
50impl fmt::Display for ModelTrainingError {
51 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52 formatter.write_str(&self.message)
53 }
54}
55
56impl Error for ModelTrainingError {}
57
58impl From<ModelTrainingError> for DataError {
59 fn from(value: ModelTrainingError) -> Self {
60 let mut error = Self::new("ModelTrainingError", value.message)
61 .with_module(MODULE)
62 .with_attribute("model_type", json!(value.model_type))
63 .with_failure(FailureMetadata::unknown());
64
65 if let Some(epoch) = value.epoch {
66 error = error.with_attribute("epoch", json!(epoch));
67 }
68
69 error
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct ConvergenceError {
76 pub model_type: String,
78 pub iterations: u64,
80 message: String,
81}
82
83impl ConvergenceError {
84 #[must_use]
86 pub fn new(model_type: impl Into<String>, iterations: u64, message: Option<String>) -> Self {
87 let model_type = model_type.into();
88 let default =
89 format!("Model '{model_type}' failed to converge after {iterations} iterations");
90
91 Self {
92 model_type,
93 iterations,
94 message: message.unwrap_or(default),
95 }
96 }
97}
98
99impl fmt::Display for ConvergenceError {
100 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
101 formatter.write_str(&self.message)
102 }
103}
104
105impl Error for ConvergenceError {}
106
107impl From<ConvergenceError> for DataError {
108 fn from(value: ConvergenceError) -> Self {
109 Self::new("ConvergenceError", value.message)
110 .with_module(MODULE)
111 .with_attribute("model_type", json!(value.model_type))
112 .with_attribute("iterations", json!(value.iterations))
113 .with_failure(FailureMetadata::unknown())
114 }
115}
116
117#[derive(Debug, Clone, PartialEq)]
119pub struct TrainingTimeoutError {
120 pub model_type: String,
122 pub timeout: f64,
124}
125
126impl TrainingTimeoutError {
127 #[must_use]
129 pub fn new(model_type: impl Into<String>, timeout: f64) -> Self {
130 Self {
131 model_type: model_type.into(),
132 timeout,
133 }
134 }
135}
136
137impl fmt::Display for TrainingTimeoutError {
138 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
139 write!(
140 formatter,
141 "Training '{}' exceeded timeout of {} seconds",
142 self.model_type, self.timeout
143 )
144 }
145}
146
147impl Error for TrainingTimeoutError {}
148
149impl From<TrainingTimeoutError> for DataError {
150 fn from(value: TrainingTimeoutError) -> Self {
151 let message = value.to_string();
152
153 Self::new("TrainingTimeoutError", message)
154 .with_module(MODULE)
155 .with_attribute("model_type", json!(value.model_type))
156 .with_attribute("timeout", json!(value.timeout))
157 .with_failure(FailureMetadata::unknown())
158 }
159}
160
161#[derive(Debug, Clone, PartialEq)]
163pub struct HyperparameterError {
164 pub param: String,
166 pub value: Value,
168 message: String,
169}
170
171impl HyperparameterError {
172 #[must_use]
174 pub fn new(param: impl Into<String>, value: Value, message: Option<String>) -> Self {
175 let param = param.into();
176 let default = format!("Invalid hyperparameter '{param}': {value}");
177
178 Self {
179 param,
180 value,
181 message: message.unwrap_or(default),
182 }
183 }
184}
185
186impl fmt::Display for HyperparameterError {
187 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
188 formatter.write_str(&self.message)
189 }
190}
191
192impl Error for HyperparameterError {}
193
194impl From<HyperparameterError> for DataError {
195 fn from(value: HyperparameterError) -> Self {
196 Self::new("HyperparameterError", value.message)
197 .with_module(MODULE)
198 .with_attribute("param", json!(value.param))
199 .with_attribute("value", value.value)
200 .with_failure(FailureMetadata::unknown())
201 }
202}
203
204#[derive(Debug, Clone, PartialEq)]
206pub struct ModelEvaluationError {
207 pub metric: String,
209 pub value: f64,
211 message: String,
212}
213
214impl ModelEvaluationError {
215 #[must_use]
217 pub fn new(metric: impl Into<String>, value: f64, message: Option<String>) -> Self {
218 let metric = metric.into();
219 let default = format!("Failed to compute metric '{metric}', got {value}");
220
221 Self {
222 metric,
223 value,
224 message: message.unwrap_or(default),
225 }
226 }
227}
228
229impl fmt::Display for ModelEvaluationError {
230 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
231 formatter.write_str(&self.message)
232 }
233}
234
235impl Error for ModelEvaluationError {}
236
237impl From<ModelEvaluationError> for DataError {
238 fn from(value: ModelEvaluationError) -> Self {
239 Self::new("ModelEvaluationError", value.message)
240 .with_module(MODULE)
241 .with_attribute("metric", json!(value.metric))
242 .with_attribute("value", json!(value.value))
243 .with_failure(FailureMetadata::unknown())
244 }
245}
246
247#[derive(Debug, Clone, PartialEq)]
249pub struct PredictionError {
250 pub model_type: String,
252 pub inputs: Value,
254 message: String,
255}
256
257impl PredictionError {
258 #[must_use]
260 pub fn new(model_type: impl Into<String>, inputs: Value, message: Option<String>) -> Self {
261 let model_type = model_type.into();
262 let default = format!("Prediction failed for model '{model_type}' with inputs {inputs}");
263
264 Self {
265 model_type,
266 inputs,
267 message: message.unwrap_or(default),
268 }
269 }
270}
271
272impl fmt::Display for PredictionError {
273 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
274 formatter.write_str(&self.message)
275 }
276}
277
278impl Error for PredictionError {}
279
280impl From<PredictionError> for DataError {
281 fn from(value: PredictionError) -> Self {
282 Self::new("PredictionError", value.message)
283 .with_module(MODULE)
284 .with_attribute("model_type", json!(value.model_type))
285 .with_attribute("inputs", value.inputs)
286 .with_failure(FailureMetadata::unknown())
287 }
288}
289
290#[derive(Debug, Clone, PartialEq, Eq)]
292pub struct ModelInferenceError {
293 pub model_type: String,
295 pub original: String,
297}
298
299impl ModelInferenceError {
300 #[must_use]
302 pub fn new(model_type: impl Into<String>, original: impl Into<String>) -> Self {
303 Self {
304 model_type: model_type.into(),
305 original: original.into(),
306 }
307 }
308
309 #[must_use]
311 pub fn from_error(model_type: impl Into<String>, error: &(impl Error + ?Sized)) -> Self {
312 Self::new(model_type, error.to_string())
313 }
314}
315
316impl fmt::Display for ModelInferenceError {
317 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
318 write!(
319 formatter,
320 "Inference failed for model '{}': {}",
321 self.model_type, self.original
322 )
323 }
324}
325
326impl Error for ModelInferenceError {}
327
328impl From<ModelInferenceError> for DataError {
329 fn from(value: ModelInferenceError) -> Self {
330 let message = value.to_string();
331
332 Self::new("ModelInferenceError", message)
333 .with_module(MODULE)
334 .with_attribute("model_type", json!(value.model_type))
335 .with_attribute("original", json!(value.original))
336 .with_failure(FailureMetadata::unknown())
337 }
338}
339
340#[derive(Debug, Clone, PartialEq, Eq)]
342pub struct CrossValidationError {
343 pub folds: u32,
345 pub cause: Option<String>,
347}
348
349impl CrossValidationError {
350 #[must_use]
352 pub fn new(folds: u32, cause: Option<String>) -> Self {
353 Self { folds, cause }
354 }
355}
356
357impl fmt::Display for CrossValidationError {
358 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
359 write!(formatter, "Cross-validation failed on {} folds", self.folds)?;
360 if let Some(cause) = &self.cause {
361 write!(formatter, ": {cause}")?;
362 }
363 Ok(())
364 }
365}
366
367impl Error for CrossValidationError {}
368
369impl From<CrossValidationError> for DataError {
370 fn from(value: CrossValidationError) -> Self {
371 let message = value.to_string();
372 let mut error = Self::new("CrossValidationError", message)
373 .with_module(MODULE)
374 .with_attribute("folds", json!(value.folds))
375 .with_failure(FailureMetadata::unknown());
376
377 if let Some(cause) = value.cause {
378 error = error.with_attribute("cause", json!(cause));
379 }
380
381 error
382 }
383}
384
385#[cfg(test)]
386mod tests {
387 use serde_json::json;
388
389 use super::{
390 ConvergenceError, CrossValidationError, HyperparameterError, ModelEvaluationError,
391 ModelInferenceError, ModelTrainingError, PredictionError, TrainingTimeoutError,
392 };
393 use crate::DataError;
394
395 #[test]
396 fn training_error_includes_epoch() {
397 let error = ModelTrainingError::new("XGBoost", Some(12), None);
398
399 assert_eq!(
400 error.to_string(),
401 "Training failed for model 'XGBoost' at epoch 12"
402 );
403
404 let envelope = DataError::from(error).to_envelope();
405 let attributes = envelope.attributes.expect("attributes should exist");
406
407 assert_eq!(attributes["model_type"], "XGBoost");
408 assert_eq!(attributes["epoch"], 12);
409 }
410
411 #[test]
412 fn convergence_error_preserves_iterations() {
413 let error = ConvergenceError::new("LogisticRegression", 1000, None);
414 let envelope = DataError::from(error).to_envelope();
415
416 assert_eq!(envelope.error_type, "ConvergenceError");
417 assert_eq!(
418 envelope.attributes.expect("attributes should exist")["iterations"],
419 1000
420 );
421 }
422
423 #[test]
424 fn training_timeout_has_stable_message() {
425 let error = TrainingTimeoutError::new("RandomForest", 30.0);
426
427 assert_eq!(
428 error.to_string(),
429 "Training 'RandomForest' exceeded timeout of 30 seconds"
430 );
431 }
432
433 #[test]
434 fn hyperparameter_error_preserves_json_value() {
435 let error = HyperparameterError::new("max_depth", json!(-1), None);
436 let envelope = DataError::from(error).to_envelope();
437 let attributes = envelope.attributes.expect("attributes should exist");
438
439 assert_eq!(attributes["param"], "max_depth");
440 assert_eq!(attributes["value"], -1);
441 }
442
443 #[test]
444 fn evaluation_error_preserves_metric_name() {
445 let error = ModelEvaluationError::new("roc_auc", 0.51, None);
446 let envelope = DataError::from(error).to_envelope();
447
448 assert_eq!(
449 envelope.attributes.expect("attributes should exist")["metric"],
450 "roc_auc"
451 );
452 }
453
454 #[test]
455 fn prediction_error_carries_input_snapshot() {
456 let error = PredictionError::new(
457 "LinearRegression",
458 json!({"age": 42, "income": 51000}),
459 None,
460 );
461 let envelope = DataError::from(error).to_envelope();
462
463 assert_eq!(
464 envelope.attributes.expect("attributes should exist")["inputs"]["age"],
465 42
466 );
467 }
468
469 #[test]
470 fn inference_error_preserves_original_message() {
471 let error = ModelInferenceError::new("Transformer", "tensor shape mismatch");
472
473 assert_eq!(
474 error.to_string(),
475 "Inference failed for model 'Transformer': tensor shape mismatch"
476 );
477 }
478
479 #[test]
480 fn cross_validation_error_preserves_folds_and_cause() {
481 let error = CrossValidationError::new(5, Some("stratification impossible".to_owned()));
482 let envelope = DataError::from(error).to_envelope();
483 let attributes = envelope.attributes.expect("attributes should exist");
484
485 assert_eq!(attributes["folds"], 5);
486 assert_eq!(attributes["cause"], "stratification impossible");
487 }
488}