primal-barracuda 0.4.0

barraCuda — BARrier-free Rust Abstracted Cross-platform Unified Dimensional Algebra. Vendor-agnostic GPU compute via WGSL.
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
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Validation harness for barracuda validation binaries.
//!
//! Provides [`ValidationHarness`] for structured, machine-readable pass/fail
//! checks with explicit tolerances. Every validation binary uses this to
//! accumulate checks and produce a deterministic exit code.
//!
//! Also provides [`exit_no_gpu`] for graceful GPU-optional handling.
//!
//! # Provenance
//! Absorbed from neuralSpring `src/validation.rs` (Feb 2026), itself adapted
//! from the hotSpring validation pattern.

use std::process;

use crate::env_keys;

/// How a tolerance threshold is applied.
#[derive(Debug, Clone, Copy)]
pub enum ToleranceMode {
    /// |observed - expected| < tolerance
    Absolute,
    /// |observed - expected| / |expected| < tolerance
    Relative,
    /// Pass if absolute *or* relative tolerance holds (see [`ValidationHarness::check_abs_or_rel`]).
    AbsOrRel,
    /// observed < threshold (upper bound only)
    UpperBound,
    /// observed > threshold (lower bound only)
    LowerBound,
}

impl std::fmt::Display for ToleranceMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Absolute => write!(f, "abs"),
            Self::Relative => write!(f, "rel"),
            Self::AbsOrRel => write!(f, "abs|rel"),
            Self::UpperBound => write!(f, "<"),
            Self::LowerBound => write!(f, ">"),
        }
    }
}

/// A single validation check with result tracking.
#[derive(Debug, Clone)]
pub struct Check {
    /// Human-readable label for the check
    pub label: String,
    /// Whether the check passed
    pub passed: bool,
    /// Observed value from the test
    pub observed: f64,
    /// Expected value for comparison
    pub expected: f64,
    /// Tolerance threshold (interpretation depends on `mode`)
    pub tolerance: f64,
    /// Second tolerance for [`ToleranceMode::AbsOrRel`] (`None` otherwise).
    pub rel_tolerance: Option<f64>,
    /// How the tolerance is applied
    pub mode: ToleranceMode,
}

/// Accumulates validation checks and produces a summary with exit code.
#[derive(Debug, Default)]
pub struct ValidationHarness {
    /// Name of the validation suite (e.g. "`matmul_validation`")
    pub name: String,
    /// Accumulated checks
    pub checks: Vec<Check>,
}

impl ValidationHarness {
    /// Create a new validation harness with the given suite name.
    #[must_use]
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            checks: Vec::new(),
        }
    }

    /// Absolute tolerance check: |observed - expected| < tolerance.
    pub fn check_abs(&mut self, label: &str, observed: f64, expected: f64, tolerance: f64) {
        let passed = (observed - expected).abs() < tolerance;
        self.checks.push(Check {
            label: label.to_string(),
            passed,
            observed,
            expected,
            tolerance,
            rel_tolerance: None,
            mode: ToleranceMode::Absolute,
        });
    }

    /// Relative tolerance check: |observed - expected| / |expected| < tolerance.
    pub fn check_rel(&mut self, label: &str, observed: f64, expected: f64, tolerance: f64) {
        let passed = if expected.abs() > f64::EPSILON {
            ((observed - expected) / expected).abs() < tolerance
        } else {
            observed.abs() < tolerance
        };
        self.checks.push(Check {
            label: label.to_string(),
            passed,
            observed,
            expected,
            tolerance,
            rel_tolerance: None,
            mode: ToleranceMode::Relative,
        });
    }

    /// Relative tolerance: `|computed - expected| ≤ rel_tol × |expected|` when `|expected|` is not
    /// near zero; otherwise compares `|computed - expected|` to `rel_tol` (groundSpring V120 /
    /// `tolerance::compare` style).
    pub fn check_relative(&mut self, label: &str, computed: f64, expected: f64, rel_tol: f64) {
        let abs_diff = (computed - expected).abs();
        let rel_err = if expected.abs() > 1e-15 {
            abs_diff / expected.abs()
        } else {
            abs_diff
        };
        let passed = rel_err <= rel_tol;
        self.checks.push(Check {
            label: label.to_string(),
            passed,
            observed: computed,
            expected,
            tolerance: rel_tol,
            rel_tolerance: None,
            mode: ToleranceMode::Relative,
        });
    }

    /// Pass if **either** `|computed - expected| ≤ abs_tol` **or** the relative error (same
    /// semantics as [`Self::check_relative`]) is `≤ rel_tol`.
    pub fn check_abs_or_rel(
        &mut self,
        label: &str,
        computed: f64,
        expected: f64,
        abs_tol: f64,
        rel_tol: f64,
    ) {
        let abs_diff = (computed - expected).abs();
        let abs_ok = abs_diff <= abs_tol;
        let rel_err = if expected.abs() > 1e-15 {
            abs_diff / expected.abs()
        } else {
            abs_diff
        };
        let rel_ok = rel_err <= rel_tol;
        let passed = abs_ok || rel_ok;
        self.checks.push(Check {
            label: label.to_string(),
            passed,
            observed: computed,
            expected,
            tolerance: abs_tol,
            rel_tolerance: Some(rel_tol),
            mode: ToleranceMode::AbsOrRel,
        });
    }

    /// Upper-bound check: observed < threshold.
    pub fn check_upper(&mut self, label: &str, observed: f64, threshold: f64) {
        self.checks.push(Check {
            label: label.to_string(),
            passed: observed < threshold,
            observed,
            expected: threshold,
            tolerance: threshold,
            rel_tolerance: None,
            mode: ToleranceMode::UpperBound,
        });
    }

    /// Lower-bound check: observed > threshold.
    pub fn check_lower(&mut self, label: &str, observed: f64, threshold: f64) {
        self.checks.push(Check {
            label: label.to_string(),
            passed: observed > threshold,
            observed,
            expected: threshold,
            tolerance: threshold,
            rel_tolerance: None,
            mode: ToleranceMode::LowerBound,
        });
    }

    /// Boolean pass/fail check.
    pub fn check_bool(&mut self, label: &str, passed: bool) {
        self.checks.push(Check {
            label: label.to_string(),
            passed,
            observed: f64::from(u8::from(passed)),
            expected: 1.0,
            tolerance: 0.0,
            rel_tolerance: None,
            mode: ToleranceMode::Absolute,
        });
    }

    /// Try to unwrap a `Result`, recording a FAIL check on error.
    ///
    /// Returns `Some(value)` on success, `None` on failure.
    pub fn require<T, E: std::fmt::Display>(
        &mut self,
        label: &str,
        result: Result<T, E>,
    ) -> Option<T> {
        match result {
            Ok(v) => Some(v),
            Err(e) => {
                self.check_bool(&format!("{label}: {e}"), false);
                None
            }
        }
    }

    /// Number of checks that passed.
    #[must_use]
    pub fn passed_count(&self) -> usize {
        self.checks.iter().filter(|c| c.passed).count()
    }

    /// Total number of checks.
    #[must_use]
    pub fn total_count(&self) -> usize {
        self.checks.len()
    }

    /// Returns true if all checks passed.
    #[must_use]
    pub fn all_passed(&self) -> bool {
        self.checks.iter().all(|c| c.passed)
    }

    /// Print summary and exit with appropriate code.
    pub fn finish(&self) -> ! {
        tracing::info!("");
        for check in &self.checks {
            let icon = if check.passed { "PASS" } else { "FAIL" };
            if let Some(rel_tol) = check.rel_tolerance {
                tracing::info!(
                    "[{icon}] {}: observed={:.10e}, expected={:.10e}, abs_tol={:.2e}, rel_tol={:.2e} ({})",
                    check.label,
                    check.observed,
                    check.expected,
                    check.tolerance,
                    rel_tol,
                    check.mode
                );
            } else {
                tracing::info!(
                    "[{icon}] {}: observed={:.10e}, expected={:.10e}, tol={:.2e} ({})",
                    check.label,
                    check.observed,
                    check.expected,
                    check.tolerance,
                    check.mode
                );
            }
        }

        tracing::info!("");
        tracing::info!(
            "=== {}: {}/{} PASS, {} FAIL ===",
            self.name,
            self.passed_count(),
            self.total_count(),
            self.total_count() - self.passed_count(),
        );

        if self.all_passed() {
            process::exit(0);
        } else {
            let failed: Vec<&str> = self
                .checks
                .iter()
                .filter(|c| !c.passed)
                .map(|c| c.label.as_str())
                .collect();
            tracing::info!("FAILED: {}", failed.join(", "));
            process::exit(1);
        }
    }
}

/// Parse a `BARRACUDA_REQUIRE_GPU` value into a boolean.
///
/// Accepts `"1"` or `"true"` (case-insensitive) as truthy.
#[must_use]
fn parse_gpu_required(val: Option<&str>) -> bool {
    val.is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
}

/// Whether `BARRACUDA_REQUIRE_GPU=1` is set.
///
/// When `true`, validation binaries that cannot obtain a GPU adapter must exit 1
/// instead of silently skipping. For CI pipelines with a known-good GPU.
#[must_use]
pub fn gpu_required() -> bool {
    parse_gpu_required(
        std::env::var(env_keys::BARRACUDA_REQUIRE_GPU)
            .ok()
            .as_deref(),
    )
}

/// Handle the absence of a GPU adapter in a validation binary.
///
/// If `BARRACUDA_REQUIRE_GPU=1`, prints an error and exits 1.
/// Otherwise, prints a skip message and exits 0.
pub fn exit_no_gpu() -> ! {
    if gpu_required() {
        tracing::error!("FAIL: no GPU adapter (BARRACUDA_REQUIRE_GPU=1)");
        process::exit(1);
    }
    tracing::info!("0/0 checks — skipping gracefully (no GPU adapter)");
    process::exit(0);
}

/// Unwrap a `Result` or record failure and early-return from the caller.
#[macro_export]
macro_rules! require {
    ($harness:expr, $result:expr, $label:expr) => {
        match $result {
            Ok(v) => v,
            Err(e) => {
                $harness.check_bool(&format!("{}: {}", $label, e), false);
                return;
            }
        }
    };
}

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

    #[test]
    fn harness_tracks_pass_fail() {
        let mut h = ValidationHarness::new("test");
        h.check_abs("good", 1.0, 1.0, 0.01);
        h.check_abs("bad", 1.0, 2.0, 0.01);
        assert_eq!(h.passed_count(), 1);
        assert_eq!(h.total_count(), 2);
        assert!(!h.all_passed());
    }

    #[test]
    fn harness_all_pass() {
        let mut h = ValidationHarness::new("test");
        h.check_abs("a", 1.0, 1.0, 0.01);
        h.check_rel("b", 100.0, 100.0, 0.01);
        h.check_bool("c", true);
        assert!(h.all_passed());
    }

    #[test]
    fn harness_bounds() {
        let mut h = ValidationHarness::new("test");
        h.check_upper("upper ok", 0.5, 1.0);
        h.check_upper("upper fail", 1.5, 1.0);
        h.check_lower("lower ok", 1.5, 1.0);
        h.check_lower("lower fail", 0.5, 1.0);
        assert_eq!(h.passed_count(), 2);
    }

    #[test]
    fn harness_require_success() {
        let mut h = ValidationHarness::new("test");
        let val: Result<i32, String> = Ok(42);
        let result = h.require("op", val);
        assert_eq!(result, Some(42));
        assert!(h.all_passed());
    }

    #[test]
    fn harness_require_failure() {
        let mut h = ValidationHarness::new("test");
        let val: Result<i32, String> = Err("boom".into());
        let result = h.require("op", val);
        assert_eq!(result, None);
        assert!(!h.all_passed());
    }

    #[test]
    fn gpu_required_default_false() {
        assert!(!parse_gpu_required(None));
    }

    #[test]
    fn test_tolerance_mode_display() {
        assert_eq!(ToleranceMode::Absolute.to_string(), "abs");
        assert_eq!(ToleranceMode::Relative.to_string(), "rel");
        assert_eq!(ToleranceMode::AbsOrRel.to_string(), "abs|rel");
        assert_eq!(ToleranceMode::UpperBound.to_string(), "<");
        assert_eq!(ToleranceMode::LowerBound.to_string(), ">");
    }

    #[test]
    fn check_relative_pass_and_fail() {
        let mut h = ValidationHarness::new("test");
        h.check_relative("close", 1.005, 1.0, 0.01);
        h.check_relative("far", 1.5, 1.0, 0.01);
        assert_eq!(h.passed_count(), 1);
        assert_eq!(h.total_count(), 2);
        assert!(h.checks[0].passed);
        assert!(!h.checks[1].passed);
    }

    #[test]
    fn check_relative_near_zero_expected() {
        let mut h = ValidationHarness::new("test");
        h.check_relative("near_zero", 1e-16, 0.0, 1e-10);
        assert!(h.checks[0].passed);
    }

    #[test]
    fn check_abs_or_rel_pass_via_absolute() {
        let mut h = ValidationHarness::new("test");
        h.check_abs_or_rel("abs_wins", 100.001, 100.0, 0.01, 1e-10);
        assert!(h.checks[0].passed);
    }

    #[test]
    fn check_abs_or_rel_pass_via_relative() {
        let mut h = ValidationHarness::new("test");
        h.check_abs_or_rel("rel_wins", 1000.5, 1000.0, 0.001, 0.001);
        assert!(h.checks[0].passed);
    }

    #[test]
    fn check_abs_or_rel_fail_both() {
        let mut h = ValidationHarness::new("test");
        h.check_abs_or_rel("both_fail", 2.0, 1.0, 0.01, 0.01);
        assert!(!h.checks[0].passed);
    }

    #[test]
    fn test_check_rel_with_zero_expected() {
        let mut h = ValidationHarness::new("test");
        h.check_rel("zero_expected_pass", 0.0001, 0.0, 0.01);
        h.check_rel("zero_expected_fail", 1.0, 0.0, 0.01);
        assert!(h.checks[0].passed);
        assert!(!h.checks[1].passed);
    }

    #[test]
    fn test_empty_harness() {
        let h = ValidationHarness::new("empty");
        assert!(h.all_passed());
        assert_eq!(h.passed_count(), 0);
        assert_eq!(h.total_count(), 0);
    }

    #[test]
    fn test_check_bool_false() {
        let mut h = ValidationHarness::new("test");
        h.check_bool("x", false);
        assert_eq!(h.passed_count(), 0);
        assert_eq!(h.total_count(), 1);
        assert!(!h.all_passed());
    }

    #[test]
    fn test_gpu_required_when_set_to_1() {
        assert!(parse_gpu_required(Some("1")));
    }

    #[test]
    fn test_gpu_required_when_set_to_true() {
        assert!(parse_gpu_required(Some("true")));
    }

    #[test]
    fn test_gpu_required_case_insensitive() {
        assert!(parse_gpu_required(Some("TRUE")));
    }

    #[test]
    fn test_gpu_required_false_when_other_value() {
        assert!(!parse_gpu_required(Some("0")));
    }
}