aprender-core 0.30.0

Next-generation machine learning library in pure Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Error types for Aprender operations.
//!
//! Provides rich error context for library consumers.

use std::fmt;

/// Main error type for Aprender operations.
///
/// Provides detailed context about failures including dimension mismatches,
/// singular matrices, convergence issues, and invalid hyperparameters.
///
/// # Examples
///
/// ```
/// use aprender::error::AprenderError;
///
/// let err = AprenderError::DimensionMismatch {
///     expected: "100x10".to_string(),
///     actual: "100x5".to_string(),
/// };
/// assert!(err.to_string().contains("dimension mismatch"));
/// ```
#[derive(Debug)]
pub enum AprenderError {
    /// Matrix/vector dimensions don't match for the operation.
    DimensionMismatch {
        /// Expected dimensions description
        expected: String,
        /// Actual dimensions found
        actual: String,
    },

    /// Matrix is singular (non-invertible).
    SingularMatrix {
        /// Determinant value (close to zero)
        det: f64,
    },

    /// Optimization failed to converge within iteration limit.
    ConvergenceFailure {
        /// Number of iterations attempted
        iterations: usize,
        /// Final loss value
        final_loss: f64,
    },

    /// Invalid hyperparameter value provided.
    InvalidHyperparameter {
        /// Parameter name
        param: String,
        /// Provided value
        value: String,
        /// Constraint description
        constraint: String,
    },

    /// Requested compute backend is not available.
    BackendUnavailable {
        /// Backend name (e.g., "GPU", "AVX-512")
        backend: String,
    },

    /// I/O error (file not found, permission denied, etc.).
    Io(std::io::Error),

    /// Serialization/deserialization error.
    Serialization(String),

    /// Generic error with string message.
    Other(String),

    /// Invalid or corrupt model format.
    FormatError {
        /// Error description
        message: String,
    },

    /// Unsupported format version.
    UnsupportedVersion {
        /// Version found
        found: (u8, u8),
        /// Maximum supported version
        supported: (u8, u8),
    },

    /// Checksum verification failed.
    ChecksumMismatch {
        /// Expected checksum
        expected: u32,
        /// Actual checksum
        actual: u32,
    },

    /// Signature verification failed.
    SignatureInvalid {
        /// Reason for failure
        reason: String,
    },

    /// Decryption failed (wrong password or corrupt data).
    DecryptionFailed {
        /// Error details
        message: String,
    },

    /// Poka-yoke validation failed (APR-POKA-001 - Jidoka gate).
    ValidationError {
        /// Validation failure message
        message: String,
    },
}

impl fmt::Display for AprenderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AprenderError::DimensionMismatch { expected, actual } => {
                write!(
                    f,
                    "Matrix dimension mismatch: expected {expected}, got {actual}"
                )
            }
            AprenderError::SingularMatrix { det } => {
                write!(
                    f,
                    "Singular matrix detected: determinant = {det}, cannot invert"
                )
            }
            AprenderError::ConvergenceFailure {
                iterations,
                final_loss,
            } => {
                write!(
                    f,
                    "Convergence failure after {iterations} iterations, loss = {final_loss}"
                )
            }
            AprenderError::InvalidHyperparameter {
                param,
                value,
                constraint,
            } => {
                write!(
                    f,
                    "Invalid hyperparameter: {param} = {value}, expected {constraint}"
                )
            }
            AprenderError::BackendUnavailable { backend } => {
                write!(f, "Backend not available: {backend}")
            }
            AprenderError::Io(e) => write!(f, "I/O error: {e}"),
            AprenderError::Serialization(msg) => write!(f, "Serialization error: {msg}"),
            AprenderError::Other(msg) => write!(f, "{msg}"),
            AprenderError::FormatError { message } => {
                write!(f, "Invalid model format: {message}")
            }
            AprenderError::UnsupportedVersion { found, supported } => {
                write!(
                    f,
                    "Unsupported format version: found {}.{}, max supported {}.{}",
                    found.0, found.1, supported.0, supported.1
                )
            }
            AprenderError::ChecksumMismatch { expected, actual } => {
                write!(
                    f,
                    "Checksum mismatch: expected 0x{expected:08X}, got 0x{actual:08X}"
                )
            }
            AprenderError::SignatureInvalid { reason } => {
                write!(f, "Invalid signature: {reason}")
            }
            AprenderError::DecryptionFailed { message } => {
                write!(f, "Decryption failed: {message}")
            }
            AprenderError::ValidationError { message } => {
                write!(f, "Validation failed: {message}")
            }
        }
    }
}

impl std::error::Error for AprenderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            AprenderError::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<std::io::Error> for AprenderError {
    fn from(err: std::io::Error) -> Self {
        AprenderError::Io(err)
    }
}

impl From<&str> for AprenderError {
    fn from(msg: &str) -> Self {
        AprenderError::Other(msg.to_string())
    }
}

impl From<String> for AprenderError {
    fn from(msg: String) -> Self {
        AprenderError::Other(msg)
    }
}

impl AprenderError {
    /// Create a dimension mismatch error with descriptive context
    #[must_use]
    pub fn dimension_mismatch(context: &str, expected: usize, actual: usize) -> Self {
        Self::DimensionMismatch {
            expected: format!("{context}={expected}"),
            actual: format!("{actual}"),
        }
    }

    /// Create an index out of bounds error
    #[must_use]
    pub fn index_out_of_bounds(index: usize, len: usize) -> Self {
        Self::Other(format!("index {index} out of bounds (len={len})"))
    }

    /// Create an empty input error
    #[must_use]
    pub fn empty_input(context: &str) -> Self {
        Self::Other(format!("empty input: {context}"))
    }
}

#[allow(clippy::cmp_owned)]
impl PartialEq<&str> for AprenderError {
    fn eq(&self, other: &&str) -> bool {
        self.to_string() == *other
    }
}

#[allow(clippy::cmp_owned)]
impl PartialEq<AprenderError> for &str {
    fn eq(&self, other: &AprenderError) -> bool {
        *self == other.to_string()
    }
}

/// Convenience type alias for Results.
pub type Result<T> = std::result::Result<T, AprenderError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dimension_mismatch_display() {
        let err = AprenderError::DimensionMismatch {
            expected: "100x10".to_string(),
            actual: "100x5".to_string(),
        };
        assert!(err.to_string().contains("dimension mismatch"));
        assert!(err.to_string().contains("100x10"));
        assert!(err.to_string().contains("100x5"));
    }

    #[test]
    fn test_singular_matrix_display() {
        let err = AprenderError::SingularMatrix { det: 1e-15 };
        let msg = err.to_string();
        assert!(msg.contains("Singular matrix"));
        assert!(msg.contains("0.000000000000001") || msg.contains("1e-15"));
    }

    #[test]
    fn test_convergence_failure_display() {
        let err = AprenderError::ConvergenceFailure {
            iterations: 100,
            final_loss: 0.42,
        };
        assert!(err.to_string().contains("Convergence failure"));
        assert!(err.to_string().contains("100"));
        assert!(err.to_string().contains("0.42"));
    }

    #[test]
    fn test_invalid_hyperparameter_display() {
        let err = AprenderError::InvalidHyperparameter {
            param: "learning_rate".to_string(),
            value: "-0.1".to_string(),
            constraint: ">0".to_string(),
        };
        assert!(err.to_string().contains("Invalid hyperparameter"));
        assert!(err.to_string().contains("learning_rate"));
        assert!(err.to_string().contains("-0.1"));
        assert!(err.to_string().contains(">0"));
    }

    #[test]
    fn test_backend_unavailable_display() {
        let err = AprenderError::BackendUnavailable {
            backend: "AVX-512".to_string(),
        };
        assert!(err.to_string().contains("Backend not available"));
        assert!(err.to_string().contains("AVX-512"));
    }

    #[test]
    fn test_from_str() {
        let err: AprenderError = "test error".into();
        assert!(matches!(err, AprenderError::Other(_)));
        assert_eq!(err.to_string(), "test error");
    }

    #[test]
    fn test_from_string() {
        let err: AprenderError = "test error".to_string().into();
        assert!(matches!(err, AprenderError::Other(_)));
        assert_eq!(err.to_string(), "test error");
    }

    // =========================================================================
    // Coverage boost: Additional error variant tests
    // =========================================================================

    #[test]
    fn test_io_error_display() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let err = AprenderError::Io(io_err);
        let msg = err.to_string();
        assert!(msg.contains("I/O error") || msg.contains("file not found"));
    }

    #[test]
    fn test_serialization_error_display() {
        let err = AprenderError::Serialization("invalid JSON".to_string());
        assert!(err.to_string().contains("Serialization"));
        assert!(err.to_string().contains("invalid JSON"));
    }

    #[test]
    fn test_format_error_display() {
        let err = AprenderError::FormatError {
            message: "corrupt header".to_string(),
        };
        assert!(err.to_string().contains("Invalid model format"));
        assert!(err.to_string().contains("corrupt header"));
    }

    #[test]
    fn test_unsupported_version_display() {
        let err = AprenderError::UnsupportedVersion {
            found: (3, 0),
            supported: (2, 0),
        };
        let msg = err.to_string();
        assert!(msg.contains("Unsupported"));
        assert!(msg.contains("3.0") || msg.contains("(3, 0)"));
    }

    #[test]
    fn test_checksum_mismatch_display() {
        let err = AprenderError::ChecksumMismatch {
            expected: 0xDEADBEEF,
            actual: 0xCAFEBABE,
        };
        let msg = err.to_string();
        assert!(msg.contains("Checksum"));
    }

    #[test]
    fn test_signature_invalid_display() {
        let err = AprenderError::SignatureInvalid {
            reason: "key mismatch".to_string(),
        };
        let msg = err.to_string();
        assert!(msg.contains("Signature") || msg.contains("key mismatch"));
    }

    #[test]
    fn test_decryption_failed_display() {
        let err = AprenderError::DecryptionFailed {
            message: "wrong password".to_string(),
        };
        let msg = err.to_string();
        assert!(msg.contains("Decryption") || msg.contains("wrong password"));
    }

    #[test]
    fn test_validation_error_display() {
        let err = AprenderError::ValidationError {
            message: "poka-yoke failed".to_string(),
        };
        let msg = err.to_string();
        assert!(msg.contains("Validation") || msg.contains("poka-yoke"));
    }

    #[test]
    fn test_error_debug_impl() {
        let err = AprenderError::Other("test".to_string());
        let debug_str = format!("{:?}", err);
        assert!(debug_str.contains("Other"));
    }

    #[test]
    fn test_from_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
        let err: AprenderError = io_err.into();
        assert!(matches!(err, AprenderError::Io(_)));
    }

    #[test]
    fn test_error_send_sync() {
        fn _assert_send<T: Send>() {}
        fn _assert_sync<T: Sync>() {}
        // These would fail to compile if AprenderError wasn't Send + Sync
        // (commented out as std::io::Error is not Sync)
        // _assert_send::<AprenderError>();
    }

    // =========================================================================
    // Additional coverage tests for convenience methods and traits
    // =========================================================================

    #[test]
    fn test_dimension_mismatch_helper() {
        let err = AprenderError::dimension_mismatch("rows", 100, 50);
        let msg = err.to_string();
        assert!(msg.contains("rows=100"));
        assert!(msg.contains("50"));
    }

    #[test]
    fn test_index_out_of_bounds_helper() {
        let err = AprenderError::index_out_of_bounds(10, 5);
        let msg = err.to_string();
        assert!(msg.contains("index 10"));
        assert!(msg.contains("len=5"));
    }

    #[test]
    fn test_empty_input_helper() {
        let err = AprenderError::empty_input("training data");
        let msg = err.to_string();
        assert!(msg.contains("empty input"));
        assert!(msg.contains("training data"));
    }

    #[test]
    fn test_error_eq_str() {
        let err = AprenderError::Other("test error".to_string());
        assert!(err == "test error");
        assert!("test error" == err);
    }

    #[test]
    fn test_error_source_io() {
        use std::error::Error;
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let err = AprenderError::Io(io_err);
        assert!(err.source().is_some());
    }

    #[test]
    fn test_error_source_other() {
        use std::error::Error;
        let err = AprenderError::Other("test".to_string());
        assert!(err.source().is_none());
    }

    #[test]
    fn test_error_source_validation() {
        use std::error::Error;
        let err = AprenderError::ValidationError {
            message: "test".to_string(),
        };
        assert!(err.source().is_none());
    }
}