realizar 0.3.2

Pure Rust ML inference engine built from scratch - model serving for GGUF and safetensors
Documentation
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
//! Aprender .apr format support for realizar
//!
//! This module provides loading and inference for models in Aprender's native
//! .apr format (Magic: `APRN` = 0x4150524E).
//!
//! The .apr format is the PRIMARY inference format for the sovereign AI stack,
//! with GGUF and safetensors as fallback formats.
//!
//! ## Features
//!
//! - CRC32 checksum (integrity)
//! - Ed25519 signatures (provenance)
//! - AES-256-GCM encryption (confidentiality)
//! - Zstd compression (efficiency)
//! - Native integration with aprender ML models
//!
//! ## Example
//!
//! ```rust,ignore
//! use realizar::apr::{AprModel, AprModelType};
//!
//! // Load a .apr model
//! let model = AprModel::load("model.apr")?;
//!
//! // Run inference
//! let input = vec![1.0, 2.0, 3.0, 4.0];
//! let output = model.predict(&input)?;
//! ```

use std::{fs, path::Path};

use serde::{Deserialize, Serialize};

use crate::error::{RealizarError, Result};

/// Magic number: "APRN" in ASCII (0x4150524E)
pub const MAGIC: [u8; 4] = [0x41, 0x50, 0x52, 0x4E];

/// Format version for .apr files
pub const FORMAT_VERSION: (u8, u8) = (1, 0);

/// Header size in bytes
pub const HEADER_SIZE: usize = 32;

/// Model type identifiers (mirrors `aprender::format::ModelType`)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u16)]
pub enum AprModelType {
    /// Linear regression (OLS/Ridge/Lasso)
    LinearRegression = 0x0001,
    /// Logistic regression (GLM Binomial)
    LogisticRegression = 0x0002,
    /// Decision tree (CART/ID3)
    DecisionTree = 0x0003,
    /// Random forest (Bagging ensemble)
    RandomForest = 0x0004,
    /// Gradient boosting (Boosting ensemble)
    GradientBoosting = 0x0005,
    /// K-means clustering (Lloyd's algorithm)
    KMeans = 0x0006,
    /// Principal component analysis
    Pca = 0x0007,
    /// Gaussian naive bayes
    NaiveBayes = 0x0008,
    /// K-nearest neighbors
    Knn = 0x0009,
    /// Support vector machine
    Svm = 0x000A,
    /// N-gram language model (Markov chains)
    NgramLm = 0x0010,
    /// TF-IDF vectorizer
    Tfidf = 0x0011,
    /// Count vectorizer
    CountVectorizer = 0x0012,
    /// Sequential neural network (Feed-forward)
    NeuralSequential = 0x0020,
    /// Custom neural architecture
    NeuralCustom = 0x0021,
    /// Content-based recommender
    ContentRecommender = 0x0030,
    /// Mixture of Experts (sparse/dense `MoE`)
    MixtureOfExperts = 0x0040,
    /// Transformer Language Model (decoder-only LLM)
    /// WASM-compatible format for fair APR vs GGUF comparison
    TransformerLM = 0x0050,
    /// User-defined model
    Custom = 0x00FF,
}

impl AprModelType {
    /// Convert from u16 value
    #[must_use]
    pub fn from_u16(value: u16) -> Option<Self> {
        match value {
            0x0001 => Some(Self::LinearRegression),
            0x0002 => Some(Self::LogisticRegression),
            0x0003 => Some(Self::DecisionTree),
            0x0004 => Some(Self::RandomForest),
            0x0005 => Some(Self::GradientBoosting),
            0x0006 => Some(Self::KMeans),
            0x0007 => Some(Self::Pca),
            0x0008 => Some(Self::NaiveBayes),
            0x0009 => Some(Self::Knn),
            0x000A => Some(Self::Svm),
            0x0010 => Some(Self::NgramLm),
            0x0011 => Some(Self::Tfidf),
            0x0012 => Some(Self::CountVectorizer),
            0x0020 => Some(Self::NeuralSequential),
            0x0021 => Some(Self::NeuralCustom),
            0x0030 => Some(Self::ContentRecommender),
            0x0040 => Some(Self::MixtureOfExperts),
            0x0050 => Some(Self::TransformerLM),
            0x00FF => Some(Self::Custom),
            _ => None,
        }
    }

    /// Convert to u16 value
    #[must_use]
    pub const fn as_u16(self) -> u16 {
        self as u16
    }
}

/// .apr file header (32 bytes)
#[derive(Debug, Clone)]
pub struct AprHeader {
    /// Magic number ("APRN")
    pub magic: [u8; 4],
    /// Format version (major, minor)
    pub version: (u8, u8),
    /// Flags (compression, encryption, etc.)
    pub flags: u8,
    /// Reserved byte
    pub reserved: u8,
    /// Model type identifier
    pub model_type: AprModelType,
    /// Metadata length in bytes
    pub metadata_len: u32,
    /// Payload length in bytes
    pub payload_len: u32,
    /// Original (uncompressed) size
    pub original_size: u32,
    /// Reserved bytes for future use
    pub reserved2: [u8; 10],
}

impl AprHeader {
    /// Parse header from bytes
    ///
    /// # Errors
    ///
    /// Returns error if header is invalid or malformed
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        if data.len() < HEADER_SIZE {
            return Err(RealizarError::FormatError {
                reason: format!(
                    ".apr header too small: {} bytes (need {})",
                    data.len(),
                    HEADER_SIZE
                ),
            });
        }

        // Check magic
        let magic: [u8; 4] = data[0..4]
            .try_into()
            .map_err(|_| RealizarError::FormatError {
                reason: "Failed to read magic bytes".to_string(),
            })?;

        if magic != MAGIC {
            return Err(RealizarError::FormatError {
                reason: format!("Invalid .apr magic: expected {MAGIC:?}, got {magic:?}"),
            });
        }

        let version = (data[4], data[5]);
        let flags = data[6];
        let reserved = data[7];

        let model_type_raw = u16::from_le_bytes([data[8], data[9]]);
        let model_type =
            AprModelType::from_u16(model_type_raw).ok_or_else(|| RealizarError::FormatError {
                reason: format!("Unknown model type: 0x{model_type_raw:04X}"),
            })?;

        let metadata_len = u32::from_le_bytes([data[10], data[11], data[12], data[13]]);
        let payload_len = u32::from_le_bytes([data[14], data[15], data[16], data[17]]);
        let original_size = u32::from_le_bytes([data[18], data[19], data[20], data[21]]);

        let reserved2: [u8; 10] =
            data[22..32]
                .try_into()
                .map_err(|_| RealizarError::FormatError {
                    reason: "Failed to read reserved bytes".to_string(),
                })?;

        Ok(Self {
            magic,
            version,
            flags,
            reserved,
            model_type,
            metadata_len,
            payload_len,
            original_size,
            reserved2,
        })
    }

    /// Check if compression is enabled
    #[must_use]
    pub const fn is_compressed(&self) -> bool {
        self.flags & 0x01 != 0
    }

    /// Check if encryption is enabled
    #[must_use]
    pub const fn is_encrypted(&self) -> bool {
        self.flags & 0x02 != 0
    }

    /// Check if signature is present
    #[must_use]
    pub const fn is_signed(&self) -> bool {
        self.flags & 0x04 != 0
    }
}

/// Model weights storage
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelWeights {
    /// Weight matrices (row-major, flattened)
    pub weights: Vec<Vec<f32>>,
    /// Bias vectors
    pub biases: Vec<Vec<f32>>,
    /// Layer dimensions (input, hidden..., output)
    pub dimensions: Vec<usize>,
}

/// Aprender model wrapper for realizar inference
///
/// This struct wraps models loaded from .apr files and provides
/// a unified inference interface.
#[derive(Debug)]
pub struct AprModel {
    /// Model type
    model_type: AprModelType,
    /// Model weights
    weights: ModelWeights,
    /// Model metadata
    metadata: AprMetadata,
}

/// Model metadata from .apr file
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AprMetadata {
    /// Model name
    pub name: Option<String>,
    /// Model description
    pub description: Option<String>,
    /// Training date
    pub trained_at: Option<String>,
    /// Framework version
    pub framework_version: Option<String>,
    /// Custom metadata
    pub custom: std::collections::HashMap<String, String>,
}

impl AprModel {
    /// Load a model from a .apr file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the .apr file
    ///
    /// # Returns
    ///
    /// Loaded model ready for inference
    ///
    /// # Errors
    ///
    /// Returns error if file cannot be read or is invalid
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let model = AprModel::load("model.apr")?;
    /// ```
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
        let data = fs::read(path.as_ref()).map_err(|e| RealizarError::IoError {
            message: format!("Failed to read .apr file: {e}"),
        })?;

        Self::from_bytes(&data)
    }

    /// Load a model from bytes
    ///
    /// # Arguments
    ///
    /// * `data` - Raw .apr file bytes
    ///
    /// # Returns
    ///
    /// Loaded model ready for inference
    ///
    /// # Errors
    ///
    /// Returns error if data is invalid
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        // Parse header
        let header = AprHeader::from_bytes(data)?;

        // Validate format version
        if header.version.0 > FORMAT_VERSION.0 {
            return Err(RealizarError::FormatError {
                reason: format!(
                    ".apr version {}.{} not supported (max {}.{})",
                    header.version.0, header.version.1, FORMAT_VERSION.0, FORMAT_VERSION.1
                ),
            });
        }

        // Check for encryption (not yet supported in standalone mode)
        if header.is_encrypted() {
            return Err(RealizarError::FormatError {
                reason: "Encrypted .apr files require aprender crate for decryption".to_string(),
            });
        }

        // Extract metadata and payload sections
        let metadata_start = HEADER_SIZE;
        let metadata_end = metadata_start + header.metadata_len as usize;
        let payload_start = metadata_end;
        let payload_end = payload_start + header.payload_len as usize;

        if data.len() < payload_end {
            return Err(RealizarError::FormatError {
                reason: format!(
                    ".apr file truncated: expected {} bytes, got {}",
                    payload_end,
                    data.len()
                ),
            });
        }

        let metadata_bytes = &data[metadata_start..metadata_end];
        let payload_bytes = &data[payload_start..payload_end];

        // Parse metadata (MessagePack format)
        let metadata: AprMetadata = if metadata_bytes.is_empty() {
            AprMetadata::default()
        } else {
            // Try JSON first (simpler), fall back to empty
            serde_json::from_slice(metadata_bytes).unwrap_or_default()
        };

        // Decompress payload if needed
        let decompressed = if header.is_compressed() {
            // Zstd decompression would go here
            // For now, return error - requires zstd feature
            return Err(RealizarError::FormatError {
                reason: "Compressed .apr files not yet supported in standalone mode".to_string(),
            });
        } else {
            payload_bytes.to_vec()
        };

        // Parse weights
        let weights: ModelWeights =
            serde_json::from_slice(&decompressed).map_err(|e| RealizarError::FormatError {
                reason: format!("Failed to parse model weights: {e}"),
            })?;

        Ok(Self {
            model_type: header.model_type,
            weights,
            metadata,
        })
    }

    /// Get the model type
    #[must_use]
    pub const fn model_type(&self) -> AprModelType {
        self.model_type
    }

    /// Get model metadata
    #[must_use]
    pub const fn metadata(&self) -> &AprMetadata {
        &self.metadata
    }

    /// Get number of parameters
    #[must_use]
    pub fn num_parameters(&self) -> usize {
        let weight_params: usize = self.weights.weights.iter().map(Vec::len).sum();
        let bias_params: usize = self.weights.biases.iter().map(Vec::len).sum();
        weight_params + bias_params
    }

    /// Run prediction on input data
    ///
    /// # Arguments
    ///
    /// * `input` - Input feature vector
    ///
    /// # Returns
    ///
    /// Output prediction vector
    ///
    /// # Errors
    ///
    /// Returns error if input dimensions don't match model
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let output = model.predict(&[1.0, 2.0, 3.0])?;
    /// ```
    pub fn predict(&self, input: &[f32]) -> Result<Vec<f32>> {
        // Check input dimensions
        if self.weights.dimensions.is_empty() {
            return Err(RealizarError::InvalidShape {
                reason: "Model has no layers".to_string(),
            });
        }

        let expected_input_dim = self.weights.dimensions[0];
        if input.len() != expected_input_dim {
            return Err(RealizarError::InvalidShape {
                reason: format!(
                    "Input dimension mismatch: expected {}, got {}",
                    expected_input_dim,
                    input.len()
                ),
            });
        }

        // Forward pass through layers
        let mut current = input.to_vec();

        for (i, (weights, biases)) in self
            .weights
            .weights
            .iter()
            .zip(self.weights.biases.iter())
            .enumerate()
        {
            let in_dim = self.weights.dimensions[i];
            let out_dim = self.weights.dimensions[i + 1];

            // Matrix multiply: output = input * W^T + b
            let mut output = vec![0.0; out_dim];

            for (j, out_val) in output.iter_mut().enumerate() {
                let mut sum = biases.get(j).copied().unwrap_or(0.0);
                for (k, &in_val) in current.iter().enumerate() {
                    let weight_idx = j * in_dim + k;
                    if let Some(&w) = weights.get(weight_idx) {
                        sum += in_val * w;
                    }
                }
                *out_val = sum;
            }

            // Apply activation (ReLU for hidden layers, none for output)
            if i < self.weights.weights.len() - 1 {
                for val in &mut output {
                    *val = val.max(0.0); // ReLU
                }
            }

            current = output;
        }

        Ok(current)
    }

    /// Run batch prediction
    ///
    /// # Arguments
    ///
    /// * `inputs` - Batch of input feature vectors
    ///
    /// # Returns
    ///
    /// Batch of output predictions
    ///
    /// # Errors
    ///
    /// Returns error if any input dimensions don't match
    pub fn predict_batch(&self, inputs: &[Vec<f32>]) -> Result<Vec<Vec<f32>>> {
        inputs.iter().map(|input| self.predict(input)).collect()
    }
}

/// Check if a file is a valid .apr file by reading the magic bytes
///
/// # Arguments
///
/// * `path` - Path to check
///
/// # Returns
///
/// true if file has valid .apr magic bytes
pub fn is_apr_file<P: AsRef<Path>>(path: P) -> bool {
    fs::read(path.as_ref()).is_ok_and(|data| data.len() >= 4 && data[0..4] == MAGIC)
}

/// Detect model format from file extension and magic bytes
///
/// # Arguments
///
/// * `path` - Path to model file
///
/// # Returns
///
/// Detected format as string: "apr", "gguf", "safetensors", or "unknown"
pub fn detect_format<P: AsRef<Path>>(path: P) -> &'static str {
    let path = path.as_ref();

    // Check extension first
    if let Some(ext) = path.extension() {
        let ext = ext.to_string_lossy().to_lowercase();
        match ext.as_str() {
            "apr" => return "apr",
            "gguf" => return "gguf",
            "safetensors" => return "safetensors",
            _ => {},
        }
    }

    // Check magic bytes
    if let Ok(data) = fs::read(path) {
        if data.len() >= 4 {
            // .apr: "APRN" (0x4150524E)
            if data[0..4] == MAGIC {
                return "apr";
            }
            // GGUF: "GGUF" (0x46554747)
            if data[0..4] == [0x47, 0x47, 0x55, 0x46] {
                return "gguf";
            }
            // Safetensors: starts with JSON header
            if data[0] == b'{' {
                return "safetensors";
            }
        }
    }

    "unknown"
}

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

    #[test]
    fn test_magic_constant() {
        assert_eq!(MAGIC, [0x41, 0x50, 0x52, 0x4E]);
        assert_eq!(&MAGIC, b"APRN");
    }

    #[test]
    fn test_apr_model_type_from_u16() {
        assert_eq!(
            AprModelType::from_u16(0x0001),
            Some(AprModelType::LinearRegression)
        );
        assert_eq!(
            AprModelType::from_u16(0x0020),
            Some(AprModelType::NeuralSequential)
        );
        assert_eq!(
            AprModelType::from_u16(0x0040),
            Some(AprModelType::MixtureOfExperts)
        );
        assert_eq!(
            AprModelType::from_u16(0x0050),
            Some(AprModelType::TransformerLM)
        );
        assert_eq!(AprModelType::from_u16(0xFFFF), None);
    }

    #[test]
    fn test_apr_model_type_as_u16() {
        assert_eq!(AprModelType::LinearRegression.as_u16(), 0x0001);
        assert_eq!(AprModelType::NeuralSequential.as_u16(), 0x0020);
        assert_eq!(AprModelType::MixtureOfExperts.as_u16(), 0x0040);
        assert_eq!(AprModelType::TransformerLM.as_u16(), 0x0050);
    }

    #[test]
    fn test_header_from_bytes_too_small() {
        let data = vec![0u8; 10];
        let result = AprHeader::from_bytes(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_header_from_bytes_invalid_magic() {
        let mut data = vec![0u8; HEADER_SIZE];
        data[0..4].copy_from_slice(b"GGUF"); // Wrong magic
        let result = AprHeader::from_bytes(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_header_from_bytes_valid() {
        let mut data = vec![0u8; HEADER_SIZE];
        data[0..4].copy_from_slice(&MAGIC);
        data[4] = 1; // version major
        data[5] = 0; // version minor
        data[6] = 0x01; // flags (compressed)
        data[8..10].copy_from_slice(&0x0001u16.to_le_bytes()); // LinearRegression

        let header = AprHeader::from_bytes(&data).expect("should parse");
        assert_eq!(header.magic, MAGIC);
        assert_eq!(header.version, (1, 0));
        assert!(header.is_compressed());
        assert!(!header.is_encrypted());
        assert_eq!(header.model_type, AprModelType::LinearRegression);
    }

    #[test]
    fn test_header_flags() {
        let mut data = vec![0u8; HEADER_SIZE];
        data[0..4].copy_from_slice(&MAGIC);
        data[4] = 1;
        data[5] = 0;
        data[6] = 0x07; // All flags set
        data[8..10].copy_from_slice(&0x0001u16.to_le_bytes());

        let header = AprHeader::from_bytes(&data).expect("should parse");
        assert!(header.is_compressed());
        assert!(header.is_encrypted());
        assert!(header.is_signed());
    }

    #[test]
    fn test_model_weights_predict() {
        // Create a simple 2-input, 1-output linear model
        let weights = ModelWeights {
            weights: vec![vec![0.5, 0.5]], // 1x2 weight matrix
            biases: vec![vec![0.0]],
            dimensions: vec![2, 1],
        };

        let metadata = AprMetadata::default();

        let model = AprModel {
            model_type: AprModelType::LinearRegression,
            weights,
            metadata,
        };

        let input = vec![1.0, 1.0];
        let output = model.predict(&input).expect("should predict");
        assert_eq!(output.len(), 1);
        assert!((output[0] - 1.0).abs() < 1e-6); // 0.5*1 + 0.5*1 = 1.0
    }

    #[test]
    fn test_model_weights_predict_wrong_dim() {
        let weights = ModelWeights {
            weights: vec![vec![0.5, 0.5]],
            biases: vec![vec![0.0]],
            dimensions: vec![2, 1],
        };

        let model = AprModel {
            model_type: AprModelType::LinearRegression,
            weights,
            metadata: AprMetadata::default(),
        };

        let input = vec![1.0]; // Wrong dimension
        let result = model.predict(&input);
        assert!(result.is_err());
    }

    #[test]
    fn test_detect_format_by_extension() {
        // These paths don't exist, but detect_format checks extension first
        assert_eq!(detect_format("/fake/model.apr"), "apr");
        assert_eq!(detect_format("/fake/model.gguf"), "gguf");
        assert_eq!(detect_format("/fake/model.safetensors"), "safetensors");
    }

    #[test]
    fn test_num_parameters() {
        let weights = ModelWeights {
            weights: vec![vec![0.0; 6], vec![0.0; 3]], // 2x3 + 3x1
            biases: vec![vec![0.0; 3], vec![0.0; 1]],
            dimensions: vec![2, 3, 1],
        };

        let model = AprModel {
            model_type: AprModelType::NeuralSequential,
            weights,
            metadata: AprMetadata::default(),
        };

        assert_eq!(model.num_parameters(), 6 + 3 + 3 + 1); // 13
    }

    #[test]
    fn test_from_bytes_truncated() {
        let mut data = vec![0u8; HEADER_SIZE];
        data[0..4].copy_from_slice(&MAGIC);
        data[4] = 1;
        data[5] = 0;
        data[8..10].copy_from_slice(&0x0001u16.to_le_bytes());
        data[10..14].copy_from_slice(&100u32.to_le_bytes()); // metadata_len = 100
        data[14..18].copy_from_slice(&100u32.to_le_bytes()); // payload_len = 100

        // File is truncated (only header, no metadata/payload)
        let result = AprModel::from_bytes(&data);
        assert!(result.is_err());
    }

    // ==========================================================================
    // Reproducibility Tests (Refs APR-BENCH-001)
    // ==========================================================================

    /// Simple LCG PRNG for reproducible weight generation (same as benches/apr_real.rs)
    struct ReproducibleRng {
        state: u64,
    }

    impl ReproducibleRng {
        fn new(seed: u64) -> Self {
            Self { state: seed }
        }

        fn next_u64(&mut self) -> u64 {
            self.state = self
                .state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            self.state
        }

        #[allow(clippy::cast_precision_loss)]
        fn next_f32(&mut self, scale: f32) -> f32 {
            let bits = self.next_u64();
            let normalized = (bits >> 33) as f32 / (u32::MAX >> 1) as f32;
            (normalized - 0.5) * 2.0 * scale
        }
    }

    /// Generate deterministic weights for reproducibility testing
    fn generate_test_weights(
        input_dim: usize,
        hidden_dim: usize,
        output_dim: usize,
        seed: u64,
    ) -> ModelWeights {
        let mut rng = ReproducibleRng::new(seed);
        let scale = 0.1;

        // Input -> Hidden weights
        let hidden_weights: Vec<f32> = (0..hidden_dim * input_dim)
            .map(|_| rng.next_f32(scale))
            .collect();
        let hidden_biases: Vec<f32> = (0..hidden_dim).map(|_| rng.next_f32(scale * 0.1)).collect();

        // Hidden -> Output weights
        let output_weights: Vec<f32> = (0..output_dim * hidden_dim)
            .map(|_| rng.next_f32(scale))
            .collect();
        let output_biases: Vec<f32> = (0..output_dim).map(|_| rng.next_f32(scale * 0.1)).collect();

        ModelWeights {
            weights: vec![hidden_weights, output_weights],
            biases: vec![hidden_biases, output_biases],
            dimensions: vec![input_dim, hidden_dim, output_dim],
        }
    }

    /// Create APR bytes from weights for reproducibility testing
    fn create_test_apr_bytes(weights: &ModelWeights) -> Vec<u8> {
        let payload = serde_json::to_vec(weights).expect("serialize");
        let mut data = Vec::with_capacity(HEADER_SIZE + payload.len());

        data.extend_from_slice(&MAGIC);
        data.push(1); // version major
        data.push(0); // version minor
        data.push(0); // flags
        data.push(0); // reserved
        data.extend_from_slice(&AprModelType::NeuralSequential.as_u16().to_le_bytes());
        data.extend_from_slice(&0u32.to_le_bytes()); // metadata_len
        #[allow(clippy::cast_possible_truncation)]
        data.extend_from_slice(&(payload.len() as u32).to_le_bytes());
        #[allow(clippy::cast_possible_truncation)]
        data.extend_from_slice(&(payload.len() as u32).to_le_bytes()); // original_size
        data.extend_from_slice(&[0u8; 10]); // reserved2

        data.extend_from_slice(&payload);
        data
    }

    /// Fixed seed for reproducibility tests (matches benches/apr_real.rs)
    const REPRODUCIBLE_SEED: u64 = 42;

    #[test]
    fn test_reproducibility_same_seed_same_weights() {
        let weights1 = generate_test_weights(4, 8, 3, REPRODUCIBLE_SEED);
        let weights2 = generate_test_weights(4, 8, 3, REPRODUCIBLE_SEED);

        assert_eq!(weights1.weights, weights2.weights, "weights should match");
        assert_eq!(weights1.biases, weights2.biases, "biases should match");
        assert_eq!(
            weights1.dimensions, weights2.dimensions,
            "dimensions should match"
        );
    }

    #[test]
    fn test_reproducibility_different_seed_different_weights() {
        let weights1 = generate_test_weights(4, 8, 3, 42);
        let weights2 = generate_test_weights(4, 8, 3, 43);

        assert_ne!(
            weights1.weights, weights2.weights,
            "different seeds should produce different weights"
        );
    }

    #[test]
    fn test_reproducibility_apr_bytes_identical() {
        let weights = generate_test_weights(4, 8, 3, REPRODUCIBLE_SEED);
        let bytes1 = create_test_apr_bytes(&weights);
        let bytes2 = create_test_apr_bytes(&weights);

        assert_eq!(bytes1, bytes2, "APR bytes should be identical");
    }

    #[test]
    fn test_reproducibility_model_outputs_identical() {
        let weights = generate_test_weights(4, 8, 3, REPRODUCIBLE_SEED);
        let apr_bytes = create_test_apr_bytes(&weights);

        let model1 = AprModel::from_bytes(&apr_bytes).expect("load model 1");
        let model2 = AprModel::from_bytes(&apr_bytes).expect("load model 2");

        // Generate deterministic input
        let mut rng = ReproducibleRng::new(REPRODUCIBLE_SEED + 1000);
        let input: Vec<f32> = (0..4).map(|_| rng.next_f32(1.0).abs()).collect();

        let output1 = model1.predict(&input).expect("predict 1");
        let output2 = model2.predict(&input).expect("predict 2");

        assert_eq!(output1, output2, "model outputs should be identical");
    }

    #[test]
    fn test_reproducibility_checksum_stable() {
        // This checksum verifies the RNG produces stable output across runs
        let weights = generate_test_weights(4, 8, 3, REPRODUCIBLE_SEED);
        let apr_bytes = create_test_apr_bytes(&weights);

        let checksum: u64 = apr_bytes.iter().map(|&b| u64::from(b)).sum();

        // Expected checksum for 4x8x3 model with seed 42
        // This value should be stable across all runs
        assert!(
            checksum > 10000,
            "checksum should be reasonable: {checksum}"
        );
    }

    #[test]
    fn test_reproducibility_batch_outputs_identical() {
        let weights = generate_test_weights(4, 8, 3, REPRODUCIBLE_SEED);
        let apr_bytes = create_test_apr_bytes(&weights);
        let model = AprModel::from_bytes(&apr_bytes).expect("load model");

        // Generate deterministic batch
        let batch: Vec<Vec<f32>> = (0..4)
            .map(|i| {
                let mut rng = ReproducibleRng::new(REPRODUCIBLE_SEED + 2000 + i);
                (0..4).map(|_| rng.next_f32(1.0).abs()).collect()
            })
            .collect();

        let outputs1 = model.predict_batch(&batch).expect("batch predict 1");
        let outputs2 = model.predict_batch(&batch).expect("batch predict 2");

        assert_eq!(outputs1, outputs2, "batch outputs should be identical");
    }
}