oxiphysics 0.1.0

Unified physics engine - Bullet/OpenFOAM/LAMMPS/CalculiX replacement
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
// Copyright 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! Performance regression testing infrastructure.
//!
//! Provides a lightweight microbenchmark runner, baseline serialization
//! (JSON, no external dependency), and regression detection with
//! configurable thresholds.

use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
use std::time::{Instant, SystemTime, UNIX_EPOCH};

// ─────────────────────────────────────────────────────────────────────────────
// Error type
// ─────────────────────────────────────────────────────────────────────────────

/// Errors that can occur during performance-regression workflows.
#[derive(Debug)]
pub enum PerfError {
    /// An I/O error (file read/write).
    Io(io::Error),
    /// JSON parsing / formatting error.
    Parse(String),
}

impl fmt::Display for PerfError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PerfError::Io(e) => write!(f, "I/O error: {e}"),
            PerfError::Parse(msg) => write!(f, "parse error: {msg}"),
        }
    }
}

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

impl From<io::Error> for PerfError {
    fn from(e: io::Error) -> Self {
        PerfError::Io(e)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Data structures
// ─────────────────────────────────────────────────────────────────────────────

/// A single benchmark result with timing data.
#[derive(Debug, Clone)]
pub struct BenchmarkResult {
    /// Human-readable benchmark name.
    pub name: String,
    /// Mean elapsed time in nanoseconds.
    pub mean_ns: f64,
    /// Standard deviation of elapsed time in nanoseconds.
    pub std_dev_ns: f64,
    /// Number of iterations executed.
    pub iterations: usize,
    /// Unix timestamp (seconds) when the benchmark was recorded.
    pub timestamp: u64,
}

/// Collection of benchmark results forming a baseline snapshot.
#[derive(Debug, Clone)]
pub struct BenchmarkBaseline {
    /// Individual results in this baseline.
    pub results: Vec<BenchmarkResult>,
    /// Git commit hash (or any identifier) for reproducibility.
    pub commit_hash: String,
    /// Human-readable date string (e.g. "2026-03-30").
    pub date: String,
}

/// Configuration knobs for regression detection.
#[derive(Debug, Clone)]
pub struct RegressionConfig {
    /// A percentage threshold: if a benchmark slows down by more than this
    /// percentage it is flagged as a regression.  For example `10.0` means
    /// a 10 % slowdown triggers an alert.
    pub threshold_pct: f64,
    /// Minimum number of iterations required for a result to be considered
    /// statistically meaningful.
    pub min_iterations: usize,
}

/// The full regression report produced by [`compare_baselines`].
#[derive(Debug, Clone)]
pub struct RegressionReport {
    /// Per-benchmark comparison entries.
    pub comparisons: Vec<BenchmarkComparison>,
    /// `true` if **any** comparison exceeds the configured threshold.
    pub has_regression: bool,
}

/// Side-by-side comparison of one benchmark between baseline and current.
#[derive(Debug, Clone)]
pub struct BenchmarkComparison {
    /// Benchmark name.
    pub name: String,
    /// Baseline mean in nanoseconds.
    pub baseline_ns: f64,
    /// Current mean in nanoseconds.
    pub current_ns: f64,
    /// Percentage change: positive means slower (regression).
    pub change_pct: f64,
    /// Whether this particular comparison constitutes a regression.
    pub is_regression: bool,
}

// ─────────────────────────────────────────────────────────────────────────────
// BenchmarkResult
// ─────────────────────────────────────────────────────────────────────────────

impl BenchmarkResult {
    /// Create a new benchmark result.  The timestamp is set to the current
    /// Unix time (seconds since epoch).
    pub fn new(name: &str, mean_ns: f64, std_dev_ns: f64, iterations: usize) -> Self {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        Self {
            name: name.to_string(),
            mean_ns,
            std_dev_ns,
            iterations,
            timestamp,
        }
    }

    /// Create a result with an explicit timestamp (useful for tests).
    pub fn with_timestamp(
        name: &str,
        mean_ns: f64,
        std_dev_ns: f64,
        iterations: usize,
        timestamp: u64,
    ) -> Self {
        Self {
            name: name.to_string(),
            mean_ns,
            std_dev_ns,
            iterations,
            timestamp,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// BenchmarkBaseline – construction
// ─────────────────────────────────────────────────────────────────────────────

impl BenchmarkBaseline {
    /// Create a new empty baseline.
    pub fn new(commit_hash: &str, date: &str) -> Self {
        Self {
            results: Vec::new(),
            commit_hash: commit_hash.to_string(),
            date: date.to_string(),
        }
    }

    /// Append a single result.
    pub fn add_result(&mut self, result: BenchmarkResult) {
        self.results.push(result);
    }

    // ── JSON serialization (manual, no serde) ────────────────────────────

    /// Serialize this baseline to a JSON string.
    pub fn to_json(&self) -> String {
        let mut buf = String::with_capacity(512);
        buf.push_str("{\n");
        buf.push_str(&format!(
            "  \"commit_hash\": \"{}\",\n",
            escape_json(&self.commit_hash)
        ));
        buf.push_str(&format!("  \"date\": \"{}\",\n", escape_json(&self.date)));
        buf.push_str("  \"results\": [\n");
        for (i, r) in self.results.iter().enumerate() {
            buf.push_str("    {\n");
            buf.push_str(&format!("      \"name\": \"{}\",\n", escape_json(&r.name)));
            buf.push_str(&format!("      \"mean_ns\": {},\n", format_f64(r.mean_ns)));
            buf.push_str(&format!(
                "      \"std_dev_ns\": {},\n",
                format_f64(r.std_dev_ns)
            ));
            buf.push_str(&format!("      \"iterations\": {},\n", r.iterations));
            buf.push_str(&format!("      \"timestamp\": {}\n", r.timestamp));
            buf.push_str("    }");
            if i + 1 < self.results.len() {
                buf.push(',');
            }
            buf.push('\n');
        }
        buf.push_str("  ]\n");
        buf.push('}');
        buf
    }

    /// Deserialize a baseline from a JSON string previously produced by
    /// [`to_json`](Self::to_json).
    pub fn from_json(s: &str) -> Result<Self, PerfError> {
        let trimmed = s.trim();
        let commit_hash = extract_string_field(trimmed, "commit_hash")?;
        let date = extract_string_field(trimmed, "date")?;

        let results = parse_results_array(trimmed)?;

        Ok(Self {
            results,
            commit_hash,
            date,
        })
    }

    // ── File I/O ─────────────────────────────────────────────────────────

    /// Write the JSON representation to a file, creating parent
    /// directories if necessary.
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), PerfError> {
        let path = path.as_ref();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(path, self.to_json())?;
        Ok(())
    }

    /// Read and parse a baseline from a JSON file.
    pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self, PerfError> {
        let contents = fs::read_to_string(path)?;
        Self::from_json(&contents)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// RegressionConfig
// ─────────────────────────────────────────────────────────────────────────────

impl Default for RegressionConfig {
    fn default() -> Self {
        Self {
            threshold_pct: 10.0,
            min_iterations: 100,
        }
    }
}

impl RegressionConfig {
    /// Create a config with custom values.
    pub fn new(threshold_pct: f64, min_iterations: usize) -> Self {
        Self {
            threshold_pct,
            min_iterations,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Comparison logic
// ─────────────────────────────────────────────────────────────────────────────

/// Compare two baselines and produce a regression report.
///
/// For every benchmark that appears in **both** `current` and `baseline`
/// (matched by `name`), the percentage change is computed as:
///
/// ```text
/// change_pct = (current.mean_ns - baseline.mean_ns) / baseline.mean_ns * 100
/// ```
///
/// A positive `change_pct` means the current run is **slower** (potential
/// regression).  If the absolute change exceeds `config.threshold_pct` in
/// the positive direction **and** both results have at least
/// `config.min_iterations`, the comparison is marked as a regression.
pub fn compare_baselines(
    current: &BenchmarkBaseline,
    baseline: &BenchmarkBaseline,
    config: &RegressionConfig,
) -> RegressionReport {
    let mut comparisons = Vec::new();
    let mut has_regression = false;

    for cur in &current.results {
        if let Some(base) = baseline.results.iter().find(|b| b.name == cur.name) {
            let change_pct = if base.mean_ns.abs() < f64::EPSILON {
                0.0
            } else {
                (cur.mean_ns - base.mean_ns) / base.mean_ns * 100.0
            };

            let enough_iterations =
                cur.iterations >= config.min_iterations && base.iterations >= config.min_iterations;

            let is_regression = enough_iterations && change_pct > config.threshold_pct;

            if is_regression {
                has_regression = true;
            }

            comparisons.push(BenchmarkComparison {
                name: cur.name.clone(),
                baseline_ns: base.mean_ns,
                current_ns: cur.mean_ns,
                change_pct,
                is_regression,
            });
        }
    }

    RegressionReport {
        comparisons,
        has_regression,
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// RegressionReport – human-readable summary
// ─────────────────────────────────────────────────────────────────────────────

impl RegressionReport {
    /// Produce a human-readable, multi-line summary of the report.
    pub fn summary(&self) -> String {
        let mut buf = String::with_capacity(256);
        buf.push_str("=== Performance Regression Report ===\n\n");

        if self.comparisons.is_empty() {
            buf.push_str("No benchmarks compared.\n");
            return buf;
        }

        for cmp in &self.comparisons {
            let direction = if cmp.change_pct > 0.0 {
                "slower"
            } else if cmp.change_pct < 0.0 {
                "faster"
            } else {
                "same"
            };

            let marker = if cmp.is_regression {
                " [REGRESSION]"
            } else {
                ""
            };

            buf.push_str(&format!(
                "  {}: {:.2} ns -> {:.2} ns ({:+.2}% {}){}",
                cmp.name, cmp.baseline_ns, cmp.current_ns, cmp.change_pct, direction, marker,
            ));
            buf.push('\n');
        }

        buf.push('\n');
        if self.has_regression {
            buf.push_str("RESULT: REGRESSION DETECTED\n");
        } else {
            buf.push_str("RESULT: No regression detected.\n");
        }

        buf
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Microbenchmark runner
// ─────────────────────────────────────────────────────────────────────────────

/// Run a closure `iterations` times and return a [`BenchmarkResult`] with
/// mean and standard-deviation timing data.
///
/// The runner performs a short warm-up (10 % of `iterations`, clamped to
/// 1..=1000) before timing begins.
pub fn microbench<F: FnMut()>(name: &str, iterations: usize, mut f: F) -> BenchmarkResult {
    // Warm-up
    let warmup = (iterations / 10).clamp(1, 1000);
    for _ in 0..warmup {
        f();
    }

    // Timed runs – collect individual durations
    let mut durations_ns: Vec<f64> = Vec::with_capacity(iterations);
    for _ in 0..iterations {
        let start = Instant::now();
        f();
        let elapsed = start.elapsed();
        durations_ns.push(elapsed.as_nanos() as f64);
    }

    let n = durations_ns.len() as f64;
    let mean = durations_ns.iter().sum::<f64>() / n;

    let variance = if durations_ns.len() > 1 {
        durations_ns.iter().map(|d| (d - mean).powi(2)).sum::<f64>() / (n - 1.0)
    } else {
        0.0
    };
    let std_dev = variance.sqrt();

    BenchmarkResult::new(name, mean, std_dev, iterations)
}

// ─────────────────────────────────────────────────────────────────────────────
// Internal helpers – JSON
// ─────────────────────────────────────────────────────────────────────────────

fn escape_json(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c => out.push(c),
        }
    }
    out
}

fn unescape_json(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(ch) = chars.next() {
        if ch == '\\' {
            match chars.next() {
                Some('"') => out.push('"'),
                Some('\\') => out.push('\\'),
                Some('n') => out.push('\n'),
                Some('r') => out.push('\r'),
                Some('t') => out.push('\t'),
                Some(other) => {
                    out.push('\\');
                    out.push(other);
                }
                None => out.push('\\'),
            }
        } else {
            out.push(ch);
        }
    }
    out
}

/// Format an f64 for JSON output, ensuring it always has a decimal point.
fn format_f64(v: f64) -> String {
    let s = format!("{v}");
    if s.contains('.') || s.contains('e') || s.contains('E') {
        s
    } else {
        format!("{v}.0")
    }
}

/// Extract a JSON string field value by key (simple, non-nested).
fn extract_string_field(json: &str, key: &str) -> Result<String, PerfError> {
    let pattern = format!("\"{}\"", key);
    let key_pos = json
        .find(&pattern)
        .ok_or_else(|| PerfError::Parse(format!("missing field \"{key}\"")))?;
    let after_key = &json[key_pos + pattern.len()..];
    // skip optional whitespace and the colon
    let after_colon = after_key
        .find(':')
        .map(|i| &after_key[i + 1..])
        .ok_or_else(|| PerfError::Parse(format!("expected ':' after \"{key}\"")))?;
    let after_colon = after_colon.trim_start();
    if !after_colon.starts_with('"') {
        return Err(PerfError::Parse(format!(
            "expected string value for \"{key}\""
        )));
    }
    let value_start = 1; // skip opening quote
    let rest = &after_colon[value_start..];
    let mut end = 0;
    let mut escaped = false;
    for ch in rest.chars() {
        if escaped {
            escaped = false;
            end += ch.len_utf8();
            continue;
        }
        if ch == '\\' {
            escaped = true;
            end += 1;
            continue;
        }
        if ch == '"' {
            break;
        }
        end += ch.len_utf8();
    }
    Ok(unescape_json(&rest[..end]))
}

/// Extract a JSON number (f64) field.
fn extract_f64_field(json: &str, key: &str) -> Result<f64, PerfError> {
    let pattern = format!("\"{}\"", key);
    let key_pos = json
        .find(&pattern)
        .ok_or_else(|| PerfError::Parse(format!("missing field \"{key}\"")))?;
    let after_key = &json[key_pos + pattern.len()..];
    let after_colon = after_key
        .find(':')
        .map(|i| &after_key[i + 1..])
        .ok_or_else(|| PerfError::Parse(format!("expected ':' after \"{key}\"")))?;
    let after_colon = after_colon.trim_start();
    // read until comma, '}', or whitespace
    let end = after_colon
        .find([',', '}', ']', '\n'])
        .unwrap_or(after_colon.len());
    let num_str = after_colon[..end].trim();
    num_str
        .parse::<f64>()
        .map_err(|e| PerfError::Parse(format!("invalid f64 for \"{key}\": {e}")))
}

/// Extract a JSON integer (usize) field.
fn extract_usize_field(json: &str, key: &str) -> Result<usize, PerfError> {
    let pattern = format!("\"{}\"", key);
    let key_pos = json
        .find(&pattern)
        .ok_or_else(|| PerfError::Parse(format!("missing field \"{key}\"")))?;
    let after_key = &json[key_pos + pattern.len()..];
    let after_colon = after_key
        .find(':')
        .map(|i| &after_key[i + 1..])
        .ok_or_else(|| PerfError::Parse(format!("expected ':' after \"{key}\"")))?;
    let after_colon = after_colon.trim_start();
    let end = after_colon
        .find([',', '}', ']', '\n'])
        .unwrap_or(after_colon.len());
    let num_str = after_colon[..end].trim();
    num_str
        .parse::<usize>()
        .map_err(|e| PerfError::Parse(format!("invalid usize for \"{key}\": {e}")))
}

/// Extract a JSON u64 field.
fn extract_u64_field(json: &str, key: &str) -> Result<u64, PerfError> {
    let pattern = format!("\"{}\"", key);
    let key_pos = json
        .find(&pattern)
        .ok_or_else(|| PerfError::Parse(format!("missing field \"{key}\"")))?;
    let after_key = &json[key_pos + pattern.len()..];
    let after_colon = after_key
        .find(':')
        .map(|i| &after_key[i + 1..])
        .ok_or_else(|| PerfError::Parse(format!("expected ':' after \"{key}\"")))?;
    let after_colon = after_colon.trim_start();
    let end = after_colon
        .find([',', '}', ']', '\n'])
        .unwrap_or(after_colon.len());
    let num_str = after_colon[..end].trim();
    num_str
        .parse::<u64>()
        .map_err(|e| PerfError::Parse(format!("invalid u64 for \"{key}\": {e}")))
}

/// Parse the `"results"` array from the top-level JSON object.
fn parse_results_array(json: &str) -> Result<Vec<BenchmarkResult>, PerfError> {
    let results_key = json
        .find("\"results\"")
        .ok_or_else(|| PerfError::Parse("missing \"results\" array".to_string()))?;
    let after_key = &json[results_key + "\"results\"".len()..];
    let bracket_start = after_key
        .find('[')
        .ok_or_else(|| PerfError::Parse("expected '[' after \"results\"".to_string()))?;
    let array_content = &after_key[bracket_start + 1..];

    // Find matching ']'
    let bracket_end = find_matching_bracket(array_content)?;
    let array_str = &array_content[..bracket_end];

    // Split by top-level objects (simple brace matching)
    let objects = split_json_objects(array_str);

    let mut results = Vec::new();
    for obj in &objects {
        let name = extract_string_field(obj, "name")?;
        let mean_ns = extract_f64_field(obj, "mean_ns")?;
        let std_dev_ns = extract_f64_field(obj, "std_dev_ns")?;
        let iterations = extract_usize_field(obj, "iterations")?;
        let timestamp = extract_u64_field(obj, "timestamp")?;
        results.push(BenchmarkResult {
            name,
            mean_ns,
            std_dev_ns,
            iterations,
            timestamp,
        });
    }

    Ok(results)
}

/// Find the position of the matching ']' for content that starts right
/// after an opening '\['.
fn find_matching_bracket(s: &str) -> Result<usize, PerfError> {
    let mut depth: i32 = 0;
    let mut in_string = false;
    let mut escaped = false;
    for (i, ch) in s.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        if ch == '\\' && in_string {
            escaped = true;
            continue;
        }
        if ch == '"' {
            in_string = !in_string;
            continue;
        }
        if in_string {
            continue;
        }
        if ch == '[' {
            depth += 1;
        } else if ch == ']' {
            if depth == 0 {
                return Ok(i);
            }
            depth -= 1;
        }
    }
    Err(PerfError::Parse("unmatched '['".to_string()))
}

/// Split a JSON array body into individual object strings.
fn split_json_objects(s: &str) -> Vec<String> {
    let mut objects = Vec::new();
    let mut depth: i32 = 0;
    let mut in_string = false;
    let mut escaped = false;
    let mut start: Option<usize> = None;

    for (i, ch) in s.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        if ch == '\\' && in_string {
            escaped = true;
            continue;
        }
        if ch == '"' {
            in_string = !in_string;
            continue;
        }
        if in_string {
            continue;
        }
        if ch == '{' {
            if depth == 0 {
                start = Some(i);
            }
            depth += 1;
        } else if ch == '}' {
            depth -= 1;
            if depth == 0
                && let Some(s_idx) = start
            {
                objects.push(s[s_idx..=i].to_string());
                start = None;
            }
        }
    }
    objects
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_serialize_deserialize_roundtrip() {
        let mut baseline = BenchmarkBaseline::new("abc123", "2026-03-30");
        baseline.add_result(BenchmarkResult::with_timestamp(
            "broadphase_100",
            1500.5,
            120.3,
            200,
            1711800000,
        ));
        baseline.add_result(BenchmarkResult::with_timestamp(
            "gjk_intersect",
            850.0,
            45.2,
            500,
            1711800001,
        ));

        let json = baseline.to_json();
        let restored =
            BenchmarkBaseline::from_json(&json).expect("round-trip deserialization failed");

        assert_eq!(restored.commit_hash, "abc123");
        assert_eq!(restored.date, "2026-03-30");
        assert_eq!(restored.results.len(), 2);
        assert_eq!(restored.results[0].name, "broadphase_100");
        assert!((restored.results[0].mean_ns - 1500.5).abs() < 1e-9);
        assert!((restored.results[0].std_dev_ns - 120.3).abs() < 1e-9);
        assert_eq!(restored.results[0].iterations, 200);
        assert_eq!(restored.results[0].timestamp, 1711800000);
        assert_eq!(restored.results[1].name, "gjk_intersect");
    }

    #[test]
    fn test_regression_detected() {
        let mut baseline = BenchmarkBaseline::new("old", "2026-01-01");
        baseline.add_result(BenchmarkResult::with_timestamp(
            "bench_a", 1000.0, 10.0, 200, 0,
        ));

        let mut current = BenchmarkBaseline::new("new", "2026-03-30");
        // 15 % slower -> should regress at 10 % threshold
        current.add_result(BenchmarkResult::with_timestamp(
            "bench_a", 1150.0, 12.0, 200, 1,
        ));

        let config = RegressionConfig::default();
        let report = compare_baselines(&current, &baseline, &config);

        assert!(report.has_regression);
        assert_eq!(report.comparisons.len(), 1);
        assert!(report.comparisons[0].is_regression);
        assert!((report.comparisons[0].change_pct - 15.0).abs() < 1e-9);
    }

    #[test]
    fn test_no_regression_identical_results() {
        let mut baseline = BenchmarkBaseline::new("v1", "2026-01-01");
        baseline.add_result(BenchmarkResult::with_timestamp(
            "bench_x", 500.0, 5.0, 200, 0,
        ));

        let mut current = BenchmarkBaseline::new("v2", "2026-03-30");
        current.add_result(BenchmarkResult::with_timestamp(
            "bench_x", 500.0, 5.0, 200, 1,
        ));

        let config = RegressionConfig::default();
        let report = compare_baselines(&current, &baseline, &config);

        assert!(!report.has_regression);
        assert_eq!(report.comparisons.len(), 1);
        assert!(!report.comparisons[0].is_regression);
        assert!(report.comparisons[0].change_pct.abs() < 1e-9);
    }

    #[test]
    fn test_improvement_detected() {
        let mut baseline = BenchmarkBaseline::new("old", "2026-01-01");
        baseline.add_result(BenchmarkResult::with_timestamp(
            "bench_fast",
            2000.0,
            20.0,
            300,
            0,
        ));

        let mut current = BenchmarkBaseline::new("new", "2026-03-30");
        // 25 % faster
        current.add_result(BenchmarkResult::with_timestamp(
            "bench_fast",
            1500.0,
            15.0,
            300,
            1,
        ));

        let config = RegressionConfig::default();
        let report = compare_baselines(&current, &baseline, &config);

        assert!(!report.has_regression);
        assert_eq!(report.comparisons.len(), 1);
        assert!(!report.comparisons[0].is_regression);
        assert!(report.comparisons[0].change_pct < 0.0); // negative = improvement
    }

    #[test]
    fn test_microbench_returns_valid_data() {
        let mut counter = 0u64;
        let result = microbench("counter_test", 100, || {
            counter += 1;
        });

        assert_eq!(result.name, "counter_test");
        assert_eq!(result.iterations, 100);
        assert!(result.mean_ns >= 0.0);
        assert!(result.std_dev_ns >= 0.0);
        assert!(result.timestamp > 0);
        // The closure should have run iterations + warmup times
        assert!(counter >= 100);
    }

    #[test]
    fn test_report_summary_formatting() {
        let report = RegressionReport {
            has_regression: true,
            comparisons: vec![
                BenchmarkComparison {
                    name: "bench_a".to_string(),
                    baseline_ns: 1000.0,
                    current_ns: 1150.0,
                    change_pct: 15.0,
                    is_regression: true,
                },
                BenchmarkComparison {
                    name: "bench_b".to_string(),
                    baseline_ns: 800.0,
                    current_ns: 750.0,
                    change_pct: -6.25,
                    is_regression: false,
                },
            ],
        };

        let summary = report.summary();
        assert!(summary.contains("Performance Regression Report"));
        assert!(summary.contains("bench_a"));
        assert!(summary.contains("[REGRESSION]"));
        assert!(summary.contains("bench_b"));
        assert!(summary.contains("REGRESSION DETECTED"));
    }

    #[test]
    fn test_report_summary_no_regression() {
        let report = RegressionReport {
            has_regression: false,
            comparisons: vec![BenchmarkComparison {
                name: "ok_bench".to_string(),
                baseline_ns: 100.0,
                current_ns: 105.0,
                change_pct: 5.0,
                is_regression: false,
            }],
        };

        let summary = report.summary();
        assert!(summary.contains("No regression detected"));
        assert!(!summary.contains("[REGRESSION]"));
    }

    #[test]
    fn test_file_roundtrip() {
        let dir = std::env::temp_dir().join("oxiphysics_perf_test");
        let path = dir.join("baseline.json");

        let mut baseline = BenchmarkBaseline::new("deadbeef", "2026-03-30");
        baseline.add_result(BenchmarkResult::with_timestamp(
            "file_bench",
            999.9,
            11.1,
            150,
            1711800000,
        ));

        baseline
            .save_to_file(&path)
            .expect("failed to save baseline");
        let loaded = BenchmarkBaseline::load_from_file(&path).expect("failed to load baseline");

        assert_eq!(loaded.commit_hash, "deadbeef");
        assert_eq!(loaded.results.len(), 1);
        assert_eq!(loaded.results[0].name, "file_bench");
        assert!((loaded.results[0].mean_ns - 999.9).abs() < 1e-9);

        // Cleanup
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_regression_below_min_iterations() {
        // Even though the slowdown is large, insufficient iterations should
        // not flag a regression.
        let mut baseline = BenchmarkBaseline::new("old", "2026-01-01");
        baseline.add_result(BenchmarkResult::with_timestamp(
            "small_bench",
            100.0,
            5.0,
            10,
            0,
        ));

        let mut current = BenchmarkBaseline::new("new", "2026-03-30");
        current.add_result(BenchmarkResult::with_timestamp(
            "small_bench",
            200.0,
            10.0,
            10,
            1,
        ));

        let config = RegressionConfig::default(); // min_iterations = 100
        let report = compare_baselines(&current, &baseline, &config);

        assert!(!report.has_regression);
        assert!(!report.comparisons[0].is_regression);
    }

    #[test]
    fn test_json_escape_roundtrip() {
        let mut baseline = BenchmarkBaseline::new("hash\"with\\special", "2026-03-30");
        baseline.add_result(BenchmarkResult::with_timestamp(
            "bench\tnewline\ntest",
            100.0,
            1.0,
            100,
            0,
        ));

        let json = baseline.to_json();
        let restored = BenchmarkBaseline::from_json(&json).expect("escaped round-trip failed");

        assert_eq!(restored.commit_hash, "hash\"with\\special");
        assert_eq!(restored.results[0].name, "bench\tnewline\ntest");
    }

    #[test]
    fn test_empty_baseline_serialization() {
        let baseline = BenchmarkBaseline::new("empty", "2026-03-30");
        let json = baseline.to_json();
        let restored =
            BenchmarkBaseline::from_json(&json).expect("empty baseline round-trip failed");

        assert_eq!(restored.commit_hash, "empty");
        assert!(restored.results.is_empty());
    }

    #[test]
    fn test_compare_mismatched_names() {
        let mut baseline = BenchmarkBaseline::new("old", "2026-01-01");
        baseline.add_result(BenchmarkResult::with_timestamp("alpha", 100.0, 1.0, 200, 0));

        let mut current = BenchmarkBaseline::new("new", "2026-03-30");
        current.add_result(BenchmarkResult::with_timestamp("beta", 100.0, 1.0, 200, 1));

        let config = RegressionConfig::default();
        let report = compare_baselines(&current, &baseline, &config);

        // No matching names -> no comparisons
        assert!(report.comparisons.is_empty());
        assert!(!report.has_regression);
    }

    #[test]
    fn test_compare_zero_baseline_mean() {
        // Guard against division by zero.
        let mut baseline = BenchmarkBaseline::new("old", "2026-01-01");
        baseline.add_result(BenchmarkResult::with_timestamp(
            "zero_mean",
            0.0,
            0.0,
            200,
            0,
        ));

        let mut current = BenchmarkBaseline::new("new", "2026-03-30");
        current.add_result(BenchmarkResult::with_timestamp(
            "zero_mean",
            10.0,
            1.0,
            200,
            1,
        ));

        let config = RegressionConfig::default();
        let report = compare_baselines(&current, &baseline, &config);

        assert_eq!(report.comparisons.len(), 1);
        assert!((report.comparisons[0].change_pct).abs() < 1e-9);
    }

    #[test]
    fn test_multiple_benchmarks_mixed() {
        let mut baseline = BenchmarkBaseline::new("old", "2026-01-01");
        baseline.add_result(BenchmarkResult::with_timestamp(
            "fast_one", 100.0, 2.0, 200, 0,
        ));
        baseline.add_result(BenchmarkResult::with_timestamp(
            "slow_one", 500.0, 10.0, 200, 0,
        ));
        baseline.add_result(BenchmarkResult::with_timestamp(
            "stable", 300.0, 5.0, 200, 0,
        ));

        let mut current = BenchmarkBaseline::new("new", "2026-03-30");
        // Improved
        current.add_result(BenchmarkResult::with_timestamp(
            "fast_one", 80.0, 1.5, 200, 1,
        ));
        // Regressed (20 %)
        current.add_result(BenchmarkResult::with_timestamp(
            "slow_one", 600.0, 12.0, 200, 1,
        ));
        // Within threshold (3.3 %)
        current.add_result(BenchmarkResult::with_timestamp(
            "stable", 310.0, 5.0, 200, 1,
        ));

        let config = RegressionConfig::default();
        let report = compare_baselines(&current, &baseline, &config);

        assert!(report.has_regression);
        assert_eq!(report.comparisons.len(), 3);

        let slow = report
            .comparisons
            .iter()
            .find(|c| c.name == "slow_one")
            .expect("slow_one missing");
        assert!(slow.is_regression);

        let fast = report
            .comparisons
            .iter()
            .find(|c| c.name == "fast_one")
            .expect("fast_one missing");
        assert!(!fast.is_regression);

        let stable = report
            .comparisons
            .iter()
            .find(|c| c.name == "stable")
            .expect("stable missing");
        assert!(!stable.is_regression);
    }

    #[test]
    fn test_custom_threshold() {
        let mut baseline = BenchmarkBaseline::new("old", "2026-01-01");
        baseline.add_result(BenchmarkResult::with_timestamp(
            "tight", 1000.0, 10.0, 200, 0,
        ));

        let mut current = BenchmarkBaseline::new("new", "2026-03-30");
        // 3 % slowdown
        current.add_result(BenchmarkResult::with_timestamp(
            "tight", 1030.0, 11.0, 200, 1,
        ));

        // Default 10 % -> no regression
        let default_report = compare_baselines(&current, &baseline, &RegressionConfig::default());
        assert!(!default_report.has_regression);

        // Strict 2 % -> regression
        let strict = RegressionConfig::new(2.0, 100);
        let strict_report = compare_baselines(&current, &baseline, &strict);
        assert!(strict_report.has_regression);
    }
}