diffai-core 0.5.1

Core library for AI/ML diff analysis - PyTorch, Safetensors, tensor statistics
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
use diffai_core::*;
use serde_json::json;
use std::path::Path;

#[path = "fixtures.rs"]
mod fixtures;
use fixtures::{ml_generators, TestFixtures};

// ============================================================================
// UNIFIED API CORE TESTS - Basic Functionality
// ============================================================================

#[test]
fn test_diff_basic_modification() {
    let old = json!({"name": "Alice", "age": 30});
    let new = json!({"name": "Alice", "age": 31});

    let results = diff(&old, &new, None).unwrap();

    // ML analysis may add extra results, so check for at least one Modified
    let modified_results: Vec<_> = results
        .iter()
        .filter(|r| matches!(r, DiffResult::Modified(path, _, _) if path == "age"))
        .collect();
    assert!(
        !modified_results.is_empty(),
        "Should have at least one Modified result for 'age'"
    );

    match &modified_results[0] {
        DiffResult::Modified(path, old_val, new_val) => {
            assert_eq!(path, "age");
            assert_eq!(old_val, &json!(30));
            assert_eq!(new_val, &json!(31));
        }
        _ => panic!("Expected Modified result"),
    }
}

#[test]
fn test_diff_added_removed() {
    let old = json!({"name": "Alice"});
    let new = json!({"name": "Alice", "age": 30});

    let results = diff(&old, &new, None).unwrap();

    let added_results: Vec<_> = results
        .iter()
        .filter(|r| matches!(r, DiffResult::Added(path, _) if path == "age"))
        .collect();
    assert!(
        !added_results.is_empty(),
        "Should have Added result for 'age'"
    );

    match &added_results[0] {
        DiffResult::Added(path, value) => {
            assert_eq!(path, "age");
            assert_eq!(value, &json!(30));
        }
        _ => panic!("Expected Added result"),
    }

    // Test removal
    let results = diff(&new, &old, None).unwrap();
    let removed_results: Vec<_> = results
        .iter()
        .filter(|r| matches!(r, DiffResult::Removed(path, _) if path == "age"))
        .collect();
    assert!(
        !removed_results.is_empty(),
        "Should have Removed result for 'age'"
    );

    match &removed_results[0] {
        DiffResult::Removed(path, value) => {
            assert_eq!(path, "age");
            assert_eq!(value, &json!(30));
        }
        _ => panic!("Expected Removed result"),
    }
}

#[test]
fn test_diff_type_changed() {
    let old = json!({"value": "30"});
    let new = json!({"value": 30});

    let results = diff(&old, &new, None).unwrap();

    let type_changed_results: Vec<_> = results
        .iter()
        .filter(|r| matches!(r, DiffResult::TypeChanged(path, _, _) if path == "value"))
        .collect();
    assert!(
        !type_changed_results.is_empty(),
        "Should have TypeChanged result for 'value'"
    );

    match &type_changed_results[0] {
        DiffResult::TypeChanged(path, old_val, new_val) => {
            assert_eq!(path, "value");
            assert_eq!(old_val, &json!("30"));
            assert_eq!(new_val, &json!(30));
        }
        _ => panic!("Expected TypeChanged result"),
    }
}

#[test]
fn test_diff_no_changes() {
    let old = json!({"name": "Alice", "age": 30});
    let new = json!({"name": "Alice", "age": 30});

    let results = diff(&old, &new, None).unwrap();
    // Filter out ML analysis results to check base diff
    let base_diffs: Vec<_> = results
        .iter()
        .filter(|r| {
            matches!(
                r,
                DiffResult::Added(_, _)
                    | DiffResult::Removed(_, _)
                    | DiffResult::Modified(_, _, _)
                    | DiffResult::TypeChanged(_, _, _)
            )
        })
        .collect();
    assert_eq!(
        base_diffs.len(),
        0,
        "Should have no base diff results for identical data"
    );
}

// ============================================================================
// ML ANALYSIS FEATURES TESTS - Automatic Detection
// ============================================================================

#[test]
fn test_tensor_stats_changed_detection() {
    let old = json!({
        "layers": {
            "conv1.weight": {
                "shape": [64, 3, 7, 7],
                "data": [0.1, 0.2, 0.15, 0.18],
                "dtype": "float32"
            }
        }
    });

    let new = json!({
        "layers": {
            "conv1.weight": {
                "shape": [64, 3, 7, 7],
                "data": [0.2, 0.3, 0.25, 0.28],
                "dtype": "float32"
            }
        }
    });

    let results = diff(&old, &new, None).unwrap();

    // Should contain TensorStatsChanged result for weight changes
    let tensor_stats_changes = results
        .iter()
        .filter(|r| matches!(r, DiffResult::TensorStatsChanged(_, _, _)))
        .count();

    assert!(
        tensor_stats_changes > 0,
        "Should detect tensor statistics changes"
    );
}

#[test]
fn test_model_architecture_changed_detection() {
    let old = json!({
        "model_info": {
            "architecture": "ResNet18",
            "layers": ["conv1", "bn1", "relu", "maxpool", "layer1"]
        }
    });

    let new = json!({
        "model_info": {
            "architecture": "ResNet50",
            "layers": ["conv1", "bn1", "relu", "maxpool", "layer1", "layer2", "layer3", "layer4"]
        }
    });

    let results = diff(&old, &new, None).unwrap();

    let architecture_changes = results
        .iter()
        .filter(|r| matches!(r, DiffResult::ModelArchitectureChanged(_, _, _)))
        .count();

    assert!(
        architecture_changes > 0,
        "Should detect model architecture changes"
    );
}

#[test]
fn test_learning_rate_changed_detection() {
    let old = json!({
        "optimizer": {
            "type": "Adam",
            "learning_rate": 0.001
        }
    });

    let new = json!({
        "optimizer": {
            "type": "Adam",
            "learning_rate": 0.01
        }
    });

    let results = diff(&old, &new, None).unwrap();

    let lr_changes = results
        .iter()
        .filter(|r| matches!(r, DiffResult::LearningRateChanged(_, _, _)))
        .count();

    assert!(lr_changes > 0, "Should detect learning rate changes");
}

#[test]
fn test_weight_significant_change_detection() {
    let old = json!({
        "weights": {
            "layer1": 0.1,
            "layer2": 0.05
        }
    });

    let new = json!({
        "weights": {
            "layer1": 0.2,   // 0.1 change - significant
            "layer2": 0.051  // 0.001 change - not significant
        }
    });

    let results = diff(&old, &new, None).unwrap();

    let significant_changes = results
        .iter()
        .filter(|r| matches!(r, DiffResult::WeightSignificantChange(_, _)))
        .count();

    assert!(
        significant_changes > 0,
        "Should detect significant weight changes"
    );
}

// ============================================================================
// TENSOR STATISTICS TESTS
// ============================================================================

#[test]
fn test_tensor_stats_calculation() {
    let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
    let shape = vec![5];
    let dtype = "float32".to_string();

    let stats = TensorStats::new(&data, shape.clone(), dtype.clone());

    assert_eq!(stats.mean, 3.0);
    assert_eq!(stats.min, 1.0);
    assert_eq!(stats.max, 5.0);
    assert_eq!(stats.shape, shape);
    assert_eq!(stats.dtype, dtype);
    assert_eq!(stats.element_count, 5);

    // Standard deviation should be sqrt(2) = ~1.414
    assert!((stats.std - 1.414).abs() < 0.01);
}

#[test]
fn test_tensor_stats_empty_data() {
    let data = vec![];
    let shape = vec![0];
    let dtype = "float32".to_string();

    let stats = TensorStats::new(&data, shape.clone(), dtype.clone());

    assert_eq!(stats.mean, 0.0);
    assert_eq!(stats.std, 0.0);
    assert_eq!(stats.min, 0.0);
    assert_eq!(stats.max, 0.0);
    assert_eq!(stats.element_count, 0);
}

// ============================================================================
// OUTPUT FORMAT TESTS
// ============================================================================

#[test]
fn test_output_format_parsing() {
    assert_eq!(
        OutputFormat::parse_format("diffai").unwrap(),
        OutputFormat::Diffai
    );
    assert_eq!(
        OutputFormat::parse_format("json").unwrap(),
        OutputFormat::Json
    );
    assert_eq!(
        OutputFormat::parse_format("yaml").unwrap(),
        OutputFormat::Yaml
    );

    assert!(OutputFormat::parse_format("invalid").is_err());
}

#[test]
fn test_format_output_basic() {
    let results = vec![
        DiffResult::Modified("name".to_string(), json!("old"), json!("new")),
        DiffResult::Added("age".to_string(), json!(30)),
    ];

    // Test all supported formats
    for format in OutputFormat::value_variants() {
        let output = format_output(&results, *format).unwrap();
        assert!(
            !output.is_empty(),
            "Output should not be empty for format: {format:?}"
        );
    }
}

// ============================================================================
// DIFF OPTIONS TESTS
// ============================================================================

#[test]
fn test_diff_options_default() {
    let options = DiffOptions::default();

    assert_eq!(options.epsilon, None);
    assert!(options.ignore_keys_regex.is_none());
    assert_eq!(options.output_format, None);
    // Memory optimization is handled automatically by diffx-core
}

#[test]
fn test_diff_with_epsilon() {
    let old = json!({"value": 1.0001});
    let new = json!({"value": 1.0002});

    // Without epsilon - should detect change
    let results = diff(&old, &new, None).unwrap();
    let base_diffs: Vec<_> = results
        .iter()
        .filter(|r| matches!(r, DiffResult::Modified(path, _, _) if path == "value"))
        .collect();
    assert!(
        !base_diffs.is_empty(),
        "Should detect value change without epsilon"
    );

    // With epsilon - should ignore small change
    let options = DiffOptions {
        epsilon: Some(0.001),
        ..Default::default()
    };
    let results = diff(&old, &new, Some(&options)).unwrap();
    let base_diffs: Vec<_> = results
        .iter()
        .filter(|r| matches!(r, DiffResult::Modified(path, _, _) if path == "value"))
        .collect();
    assert!(
        base_diffs.is_empty(),
        "Small changes within epsilon should be ignored"
    );
}

// ============================================================================
// FILE FORMAT HANDLING TESTS (Basic Path Extension Check)
// ============================================================================

#[test]
fn test_path_extension_recognition() {
    let pytorch_files = vec!["model.pt", "checkpoint.pth"];
    let safetensors_files = vec!["model.safetensors"];
    let numpy_files = vec!["data.npy", "arrays.npz"];
    let matlab_files = vec!["network.mat"];

    // Test that we can distinguish file types by extension
    for filename in pytorch_files {
        let path = Path::new(filename);
        assert!(path.extension().is_some());
        assert!(matches!(
            path.extension().unwrap().to_str(),
            Some("pt") | Some("pth")
        ));
    }

    for filename in safetensors_files {
        let path = Path::new(filename);
        assert_eq!(path.extension().unwrap().to_str(), Some("safetensors"));
    }

    for filename in numpy_files {
        let path = Path::new(filename);
        assert!(matches!(
            path.extension().unwrap().to_str(),
            Some("npy") | Some("npz")
        ));
    }

    for filename in matlab_files {
        let path = Path::new(filename);
        assert_eq!(path.extension().unwrap().to_str(), Some("mat"));
    }
}

#[test]
fn test_path_without_extension() {
    let path = Path::new("test_file");
    assert!(
        path.extension().is_none(),
        "File without extension should return None"
    );
}

// ============================================================================
// MEMORY OPTIMIZATION TESTS
// ============================================================================

#[test]
fn test_memory_handling() {
    let old = json!({"data": [1, 2, 3, 4, 5]});
    let new = json!({"data": [1, 2, 3, 4, 6]});

    let options = DiffOptions {
        epsilon: Some(0.001),
        ..Default::default()
    };

    let results = diff(&old, &new, Some(&options)).unwrap();
    assert!(!results.is_empty());
}

// ============================================================================
// COMPLEX NESTED STRUCTURE TESTS
// ============================================================================

#[test]
fn test_nested_structure_diff() {
    let old = json!({
        "model": {
            "layers": {
                "conv1": {
                    "weights": {"mean": 0.1, "std": 0.05},
                    "bias": {"mean": 0.0, "std": 0.01}
                },
                "fc": {
                    "weights": {"mean": 0.0, "std": 0.02}
                }
            },
            "optimizer": {
                "type": "Adam",
                "lr": 0.001
            }
        }
    });

    let new = json!({
        "model": {
            "layers": {
                "conv1": {
                    "weights": {"mean": 0.12, "std": 0.06},  // Changed
                    "bias": {"mean": 0.0, "std": 0.01}
                },
                "fc": {
                    "weights": {"mean": 0.0, "std": 0.02}
                },
                "dropout": {  // Added layer
                    "rate": 0.5
                }
            },
            "optimizer": {
                "type": "SGD",  // Changed
                "lr": 0.01      // Changed
            }
        }
    });

    let results = diff(&old, &new, None).unwrap();

    assert!(!results.is_empty());

    // Should detect multiple types of changes
    let change_types: std::collections::HashSet<_> = results
        .iter()
        .map(|r| match r {
            DiffResult::Modified(_, _, _) => "modified",
            DiffResult::Added(_, _) => "added",
            DiffResult::LearningRateChanged(_, _, _) => "lr_changed",
            _ => "other",
        })
        .collect();

    assert!(
        change_types.len() >= 2,
        "Should detect multiple types of changes"
    );
}

// ============================================================================
// PYTORCH SPECIFIC TESTS USING FIXTURES
// ============================================================================

#[test]
fn test_pytorch_model_fixture_comparison() {
    let old_model = TestFixtures::pytorch_model_old();
    let new_model = TestFixtures::pytorch_model_new();

    let results = diff(&old_model, &new_model, None).unwrap();
    assert!(!results.is_empty());

    // Should detect optimizer change (Adam -> SGD)
    let optimizer_changes = results
        .iter()
        .filter(
            |r| matches!(r, DiffResult::Modified(path, _, _) if path.contains("optimizer.type")),
        )
        .count();
    assert!(optimizer_changes > 0);

    // Should detect learning rate change
    let lr_changes = results
        .iter()
        .filter(|r| matches!(r, DiffResult::LearningRateChanged(_, _, _)))
        .count();
    assert!(lr_changes > 0);
}

// ============================================================================
// SAFETENSORS SPECIFIC TESTS USING FIXTURES
// ============================================================================

#[test]
fn test_safetensors_model_fixture_comparison() {
    let old_model = TestFixtures::safetensors_model_old();
    let new_model = TestFixtures::safetensors_model_new();

    let results = diff(&old_model, &new_model, None).unwrap();
    assert!(!results.is_empty());

    // Should detect tensor shape changes
    let shape_changes = results
        .iter()
        .filter(|r| matches!(r, DiffResult::Modified(path, _, _) if path.contains("shape")))
        .count();
    assert!(shape_changes > 0);

    // Should detect new tensors
    let added_tensors = results
        .iter()
        .filter(|r| matches!(r, DiffResult::Added(path, _) if path.contains("new_layer")))
        .count();
    assert!(added_tensors > 0);
}

// ============================================================================
// NUMPY SPECIFIC TESTS USING FIXTURES
// ============================================================================

#[test]
fn test_numpy_array_fixture_comparison() {
    let old_array = TestFixtures::numpy_array_old();
    let new_array = TestFixtures::numpy_array_new();

    let results = diff(&old_array, &new_array, None).unwrap();
    assert!(!results.is_empty());

    // Should detect array shape changes
    let shape_changes = results
        .iter()
        .filter(|r| matches!(r, DiffResult::Modified(path, _, _) if path.contains("shape")))
        .count();
    assert!(shape_changes > 0);

    // Should detect new arrays
    let added_arrays = results
        .iter()
        .filter(|r| matches!(r, DiffResult::Added(path, _) if path.contains("weights")))
        .count();
    assert!(added_arrays > 0);
}

// ============================================================================
// MATLAB SPECIFIC TESTS USING FIXTURES
// ============================================================================

#[test]
fn test_matlab_file_fixture_comparison() {
    let old_file = TestFixtures::matlab_file_old();
    let new_file = TestFixtures::matlab_file_new();

    let results = diff(&old_file, &new_file, None).unwrap();
    assert!(!results.is_empty());

    // Should detect network type change
    let network_changes = results
        .iter()
        .filter(|r| {
            matches!(r, DiffResult::Modified(path, old_val, new_val)
                if path.contains("network.type")
                    && old_val == &json!("feedforward")
                    && new_val == &json!("convolutional"))
        })
        .count();
    assert!(network_changes > 0);
}

// ============================================================================
// PERFORMANCE TESTS
// ============================================================================

#[test]
fn test_large_model_performance() {
    let large_old = ml_generators::generate_model_weights(vec![1000, 500, 100]);
    let large_new = ml_generators::generate_model_weights(vec![1000, 600, 100]);

    let start = std::time::Instant::now();
    let results = diff(&large_old, &large_new, None).unwrap();
    let duration = start.elapsed();

    assert!(!results.is_empty());
    assert!(duration.as_secs() < 5, "Should complete within 5 seconds");
}

#[test]
fn test_deep_nested_structure_performance() {
    let mut deep_old = json!({});
    let mut deep_new = json!({});

    // Create 20 levels of nesting
    let mut current_old = &mut deep_old;
    let mut current_new = &mut deep_new;

    for i in 0..20 {
        let layer_name = format!("layer_{i}");
        current_old[&layer_name] = json!({
            "weights": {"mean": 0.01 * i as f64},
            "next": {}
        });
        current_new[&layer_name] = json!({
            "weights": {"mean": 0.011 * i as f64}, // Slightly different
            "next": {}
        });

        current_old = &mut current_old[&layer_name]["next"];
        current_new = &mut current_new[&layer_name]["next"];
    }

    let start = std::time::Instant::now();
    let results = diff(&deep_old, &deep_new, None).unwrap();
    let duration = start.elapsed();

    assert!(!results.is_empty());
    assert!(
        duration.as_secs() < 3,
        "Should handle deep nesting efficiently"
    );
}

// ============================================================================
// COMPREHENSIVE WORKFLOW TESTS
// ============================================================================

#[test]
fn test_comprehensive_ml_workflow() {
    let old_model = TestFixtures::pytorch_model_old();
    let new_model = TestFixtures::pytorch_model_new();

    let results = diff(&old_model, &new_model, None).unwrap();
    assert!(!results.is_empty());

    // Should detect multiple types of ML changes
    let change_types: std::collections::HashSet<_> = results
        .iter()
        .map(|r| match r {
            DiffResult::LearningRateChanged(_, _, _) => "learning_rate",
            DiffResult::WeightSignificantChange(_, _) => "weight",
            DiffResult::Modified(_, _, _) => "modified",
            DiffResult::Added(_, _) => "added",
            _ => "other",
        })
        .collect();

    assert!(
        change_types.len() >= 2,
        "Should detect multiple types of changes"
    );
}