diskann-benchmark-runner 0.50.1

DiskANN is a fast approximate nearest neighbor search library for high dimensional data
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
/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 */

//! This module contains the tolerance parsing, matching, and running logic.
//!
//! ## Loading/Parsing/Matching
//!
//! There are a whole host of things that can go wrong during this process, and we're
//! obligated to provide at least somewhat reasonable error messages at each stage.
//!
//! The logic here follows process of continually refining the state of parsed inputs,
//! tolerances, and benchmarks. This is outlined as follows:
//!
//! 1. Deserialize a raw tolerances JSON file into [`Raw`] via [`Raw::load`]. This parses
//!    the tolerance skeleton into a sequence of [`RawInner`].
//!
//!    At this stage, we've:
//!    * Verified the structure of the tolerances file.
//!
//! 2. Parse each [`RawInner`] into a [`ParsedInner`] via [`Raw::parse`].
//!    This attempts to match each [`RawInner`] with a [`registry::RegisteredTolerance`]
//!    and uses said regression to attempt to parse the raw value into a concrete type.
//!
//!    After this stage, each [`ParsedInner`] has the following invariants:
//!    * The tolerance input has been properly deserialized into a concrete struct.
//!    * It has been matched with a [`registry::RegisteredTolerance`], which contains the
//!      collection of inputs and benchmarks that compatible with the parsed tolerance.
//!    * Verified that the `input` associated with the tolerance has a proper association
//!      in the registry.
//!
//! 3. Convert each [`ParsedInner`] into a [`Check`]. This works by matching the raw input
//!    associated with each [`ParsedInner`] to an actual registered input, and then finding
//!    the registered benchmark this is the best match for the input.
//!
//!    For ergonomics, we allow an "input/tolerance" pair to match multiple positional
//!    "inputs" in the input JSON. A "tolerance input" matches with an "actual input" if its
//!    raw JSON passes [`is_subset`] of the actual input's raw JSON. At this step, we need
//!    to work on raw JSON because a parsed input will have deserialization checks run and
//!    can thus look different.
//!
//!    However, matching only succeeds if the above process is complete and unambiguous:
//!    1. Each "input/tolerance" pair gets matched with at least one "actual input".
//!    2. All "actual inputs" have exactly one "input/tolerance" pair that matches them.
//!
//!    At this step, we have the invariants:
//!    * The tolerance is parsed to a concrete type.
//!    * Its associated input has been verified to be consistent with the registry and has
//!      been unambiguously selected from the "actual inputs".
//!    * The selected "actual input" has then been successfully matched with a valid
//!      regression benchmark using the normal matching flow.
//!
//! 4. Finally, [`Checks`] gets converted into [`Jobs`]. During this process, we also verify
//!    the structure of the before/after JSON files and ensure that the number of results mostly
//!    lines up. At this stage, each [`Job`] has the invariants associated with a [`Check`]
//!    with the addition:
//!
//!    * We've been paired with raw before/after JSON that we expect to have the dynamic type
//!      of the output of the associated [`registry::RegisteredBenchmark`].
//!
//!      This gets verified during the actual check runs.
//!
//! The entry points here are:
//!
//! * [`Checks::new`]: Do everything up to step 3. This enables preflight validation checks.
//! * [`Checks::jobs`]: Perform step 4. This prepares us to run all the checks.
//!
//! ## Running Checks
//!
//! Running checks simply involves running each [`Job`] and aggregating the results.
//! Each executed job can end up in one of three states:
//!
//! * Success (yay).
//! * Graceful Failure: Everything looked right in terms of deserialization, but the actual
//!   check failed.
//! * Error: Something went wrong. This could either be because the output JSON could not be
//!   deserialized properly, or for another critical reason.
//!
//! To provide better diagnostics, we wait until all checks have run before beginning a report.
//! The report is triaged in reverse order:
//!
//! * If any check fails with an error, we report all such errors and propagate an error to the top.
//! * If any check gracefully fails, report all such failures and propagate an error to the top.
//! * Otherwise, report the diagnostics from all successes and propagate `Ok(())`.
//!
//! The entry point here is:
//!
//! * [`Jobs::run`]: Run each job, prepare the report, and return a meaningful `Result`.
//!
//! ## Testing
//!
//! Testing is largely facilitated by the crate level UX framework.

use std::{collections::HashMap, io::Write, path::Path, rc::Rc};

use anyhow::Context;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{
    benchmark::{internal::CheckedPassFail, PassFail},
    internal::load_from_disk,
    jobs, registry, result, Any, Checker,
};

////////////
// Checks //
////////////

/// See module level documentation for invariants.
///
/// A `tolerance` can be mapped to multiple inputs and is thus shared behind an [`Rc`].
struct Check<'a> {
    regression: registry::RegressionBenchmark<'a>,
    tolerance: Rc<Any>,
    input: Any,
}

/// See module level documentation for invariants.
pub(crate) struct Checks<'a> {
    checks: Vec<Check<'a>>,
}

impl<'a> Checks<'a> {
    pub(crate) fn new(
        tolerances: &Path,
        input_file: &Path,
        inputs: &registry::Inputs,
        entries: &'a HashMap<&'static str, registry::RegisteredTolerance<'a>>,
    ) -> anyhow::Result<Self> {
        // Load the raw input file.
        let partial = jobs::Partial::load(input_file)?;

        // Parse and validate the raw jobs against the registered inputs.
        //
        // This preserves the ordering of the jobs.
        let inputs = jobs::Jobs::parse(&partial, inputs)?;

        // Now that the inputs have been fully parsed and validated, we then check that we
        // can load the raw tolerance file.
        let parsed = Raw::load(tolerances)?.parse(entries)?;
        Self::match_all(parsed, partial, inputs)
    }

    pub(crate) fn jobs(self, before: &Path, after: &Path) -> anyhow::Result<Jobs<'a>> {
        let (before_path, after_path) = (before, after);

        let before = result::RawResult::load(before_path)?;
        let after = result::RawResult::load(after_path)?;

        let expected = self.checks.len();
        anyhow::ensure!(
            before.len() == expected,
            "\"before\" file \"{}\" has {} entries but expected {}",
            before_path.display(),
            before.len(),
            expected,
        );

        anyhow::ensure!(
            after.len() == expected,
            "\"after\" file \"{}\" has {} entries but expected {}",
            after_path.display(),
            after.len(),
            expected,
        );

        // At this point, `before` and `after` have been deserialized (though not parsed)
        // and we know that the lengths of everything are consistent. We can finally
        // formulate the final list of jobs.
        let jobs = std::iter::zip(self.checks, std::iter::zip(before, after))
            .map(|(check, (before, after))| {
                let Check {
                    regression,
                    tolerance,
                    input,
                } = check;
                Job {
                    regression,
                    tolerance,
                    input,
                    before,
                    after,
                }
            })
            .collect();

        Ok(Jobs { jobs })
    }

    fn match_all(
        parsed: Parsed<'a>,
        partial: jobs::Partial,
        inputs: jobs::Jobs,
    ) -> anyhow::Result<Self> {
        debug_assert_eq!(
            partial.jobs().len(),
            inputs.jobs().len(),
            "expected \"inputs\" to be the parsed representation of \"partial\""
        );

        // Map each `ParsedInner` entry to all `partial` inputs they map to.
        //
        // Each `ParsedInner` unfortunately needs to get compared with every `partial` so we can
        // detect overlapping matches and reject them.
        let mut parsed_to_input: Vec<Vec<usize>> = vec![Vec::default(); parsed.inner.len()];
        let mut input_to_parsed: Vec<Vec<usize>> = vec![Vec::default(); inputs.jobs().len()];

        parsed.inner.iter().enumerate().for_each(|(i, t)| {
            partial.jobs().iter().enumerate().for_each(|(j, raw)| {
                if raw.tag == t.input.tag && is_subset(&raw.content, &t.input.content) {
                    parsed_to_input[i].push(j);
                    input_to_parsed[j].push(i);
                }
            })
        });

        // Validate the whole matching process.
        let input_to_parsed = check_matches(parsed_to_input, input_to_parsed)?;

        // At this point:
        //
        // - `parsed` is known to contain parsed tolerances.
        // - `inputs` is known to contain parsed benchmark inputs.
        // - We've verified that all the parsed tolerances unambiguously match with a
        //   tolerance input.
        //
        // We can now package everything together!
        debug_assert_eq!(input_to_parsed.len(), inputs.jobs().len());

        let checks = std::iter::zip(inputs.into_inner(), input_to_parsed.into_iter())
            .map(|(input, index)| {
                // This index should always be inbounds.
                let inner = &parsed.inner[index];
                assert_eq!(inner.input.tag, input.tag());

                // Within the parsed tolerance, we should be able to find the best-matching
                // regression benchmark for this concrete input. This benchmark should exist,
                // but it's possible that code changes between when the results were generated
                // and now has led to the input no longer being matchable with anything.
                let regression = inner
                    .entry
                    .regressions
                    .iter()
                    .filter_map(|r| r.try_match(&input).ok().map(|score| (*r, score)))
                    .min_by_key(|(_, score)| *score)
                    .map(|(r, _)| r)
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "Could not match input tag \"{}\" and tolerance tag \"{}\" to \
                             a valid benchmark. This likely means file or code changes \
                             between when the input file was last used. If the normal \
                             benchmark flow succeeds, please report this issue.",
                            inner.input.tag,
                            inner.tolerance.tag(),
                        )
                    })?;

                Ok(Check {
                    regression,
                    tolerance: inner.tolerance.clone(),
                    input,
                })
            })
            .collect::<anyhow::Result<Vec<_>>>()?;

        Ok(Self { checks })
    }
}

//---------//
// Helpers //
//---------//

/// A raw unprocessed tolerance job.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct RawInner {
    input: jobs::Unprocessed,
    tolerance: jobs::Unprocessed,
}

impl RawInner {
    pub(crate) fn new(input: jobs::Unprocessed, tolerance: jobs::Unprocessed) -> Self {
        Self { input, tolerance }
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub(crate) struct Raw {
    checks: Vec<RawInner>,
}

impl Raw {
    pub(crate) fn load(path: &Path) -> anyhow::Result<Self> {
        load_from_disk(path)
    }

    fn parse<'a>(
        self,
        entries: &'a HashMap<&'static str, registry::RegisteredTolerance<'a>>,
    ) -> anyhow::Result<Parsed<'a>> {
        // Attempt to parse raw tolerances into registered tolerance inputs.
        let num_checks = self.checks.len();
        let mut checker = Checker::new(vec![], None);
        let inner = self
            .checks
            .into_iter()
            .enumerate()
            .map(|(i, unprocessed)| {
                let context = || {
                    format!(
                        "while processing tolerance input {} of {}",
                        i.wrapping_add(1),
                        num_checks,
                    )
                };

                // Does this tolerance tag matched a registered tolerance?
                let entry = entries
                    .get(&*unprocessed.tolerance.tag)
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "Unrecognized tolerance tag: \"{}\"",
                            unprocessed.tolerance.tag
                        )
                    })
                    .with_context(context)?;

                // Verify that the accompanying input tag is accepted by at least one
                // benchmark registered under this tolerance.
                if !entry
                    .regressions
                    .iter()
                    .any(|r| r.input_tag() == unprocessed.input.tag)
                {
                    let valid: Vec<_> = entry
                        .regressions
                        .iter()
                        .map(|pair| pair.input_tag())
                        .collect();
                    return Err(anyhow::anyhow!(
                        "input tag \"{}\" is not compatible with tolerance tag \"{}\". \
                         Valid input tags are: {:?}",
                        unprocessed.input.tag,
                        unprocessed.tolerance.tag,
                        valid,
                    ))
                    .with_context(context);
                }

                checker.set_tag(entry.tolerance.tag());
                let tolerance = entry
                    .tolerance
                    .try_deserialize(&unprocessed.tolerance.content, &mut checker)
                    .with_context(context)?;

                Ok(ParsedInner {
                    entry,
                    tolerance: Rc::new(tolerance),
                    input: unprocessed.input,
                })
            })
            .collect::<anyhow::Result<_>>()?;

        Ok(Parsed { inner })
    }

    pub(crate) fn example() -> String {
        #[expect(
            clippy::expect_used,
            reason = "we control the concrete struct and its serialization implementation"
        )]
        serde_json::to_string_pretty(&Self::default())
            .expect("built-in serialization should succeed")
    }
}

/// Invariants:
///
/// * `tolerance` is parsed to the dynamic type of the associated tolerance in `entry`.
/// * The tag in `input` exists within at least one of the regressions in `entry`.
#[derive(Debug)]
struct ParsedInner<'a> {
    entry: &'a registry::RegisteredTolerance<'a>,
    tolerance: Rc<Any>,
    input: jobs::Unprocessed,
}

#[derive(Debug)]
struct Parsed<'a> {
    inner: Vec<ParsedInner<'a>>,
}

/// Return `true` only `needle` is a structural subset of `haystack`. This is defined as:
///
/// 1. All flattened paths of `needle` are flattened paths of `haystack`.
/// 2. The values at the end of all flattened paths are equal.
///
/// When matching arrays, `needle` is matched as a potential prefix of the corresponding
/// entry in `haystack`.
#[must_use]
pub(crate) fn is_subset(mut haystack: &Value, mut needle: &Value) -> bool {
    macro_rules! false_if {
        ($expr:expr) => {
            if $expr {
                return false;
            }
        };
    }

    // Note that we use a `do-while` style loop to short-circuit situations where we
    // match/mismatch immediately, saving an allocation.
    //
    // If we exit on the first iteration, the vector stays empty and thus doesn't allocate.
    let mut stack = Vec::new();
    loop {
        match (haystack, needle) {
            (Value::Null, Value::Null) => {
                // Null always matches
            }
            (Value::Bool(h), Value::Bool(n)) => false_if!(h != n),
            (Value::Number(h), Value::Number(n)) => false_if!(h != n),
            (Value::String(h), Value::String(n)) => false_if!(h != n),
            (Value::Array(h), Value::Array(n)) => {
                // If `n` is longer, then it cannot possibly be a subset of `h`.
                // On the flip side, if `n` is shorter, then we can at least try to match
                // the prefix.
                false_if!(h.len() < n.len());
                std::iter::zip(h.iter(), n.iter()).for_each(|(h, n)| stack.push((h, n)));
            }
            (Value::Object(h), Value::Object(n)) => {
                for (k, v) in n.iter() {
                    match h.get(k) {
                        Some(h) => stack.push((h, v)),
                        None => return false,
                    }
                }
            }
            // If the two enums are not the same, then we have a fundamental mismatch.
            _ => return false,
        }

        if let Some((h, n)) = stack.pop() {
            (haystack, needle) = (h, n);
        } else {
            break;
        }
    }

    true
}

/// A single problem detected during bipartite tolerance-to-input matching.
#[derive(Debug, PartialEq)]
enum MatchProblem {
    /// Tolerance at this index matched no inputs.
    OrphanedTolerance(usize),
    /// Input at this index matched no tolerances.
    UncoveredInput(usize),
    /// Input at this index matched multiple tolerances.
    AmbiguousInput(usize, Vec<usize>),
}

/// Error returned when the bipartite matching between tolerance entries and inputs is
/// invalid.
#[derive(Debug)]
struct AmbiguousMatch(Vec<MatchProblem>);

impl std::fmt::Display for AmbiguousMatch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "tolerance matching failed:")?;
        for problem in &self.0 {
            match problem {
                MatchProblem::OrphanedTolerance(i) => {
                    write!(f, "\n  tolerance {} matched no inputs", i + 1)?;
                }
                MatchProblem::UncoveredInput(i) => {
                    write!(f, "\n  input {} matched no tolerances", i + 1)?;
                }
                MatchProblem::AmbiguousInput(i, tolerances) => {
                    write!(f, "\n  input {} matched tolerances ", i + 1)?;
                    for (j, &t) in tolerances.iter().enumerate() {
                        if j > 0 {
                            write!(f, ", ")?;
                        }
                        write!(f, "{}", t + 1)?;
                    }
                }
            }
        }
        Ok(())
    }
}

impl std::error::Error for AmbiguousMatch {}

/// Validate that every entry in `parsed_to_input` has at least one match and that all
/// entries in `input_to_parsed` have exactly one match.
///
/// Return unique matches from `input_to_parsed` on success. Otherwise, return a
/// descriptive error.
fn check_matches(
    parsed_to_input: Vec<Vec<usize>>,
    input_to_parsed: Vec<Vec<usize>>,
) -> Result<Vec<usize>, AmbiguousMatch> {
    let mut problems = Vec::new();

    for (i, matches) in parsed_to_input.iter().enumerate() {
        if matches.is_empty() {
            problems.push(MatchProblem::OrphanedTolerance(i));
        }
    }

    let mut result = Vec::with_capacity(input_to_parsed.len());
    for (i, matches) in input_to_parsed.into_iter().enumerate() {
        match matches.len() {
            0 => problems.push(MatchProblem::UncoveredInput(i)),
            1 => result.push(matches[0]),
            _ => problems.push(MatchProblem::AmbiguousInput(i, matches)),
        }
    }

    if problems.is_empty() {
        Ok(result)
    } else {
        Err(AmbiguousMatch(problems))
    }
}

//////////
// Jobs //
//////////

/// A fully parsed and (hopefully) ready to run regression check.
#[derive(Debug)]
pub(crate) struct Job<'a> {
    /// The executor for the actual check we wish to run.
    regression: registry::RegressionBenchmark<'a>,

    /// The [`crate::benchmark::Regression::Tolerance`] associated with `regression`.
    tolerance: Rc<Any>,

    /// The [`crate::Benchmark::Input`] associated with `benchmark`.
    input: Any,

    /// The [`result::RawResult`] from the "before" comparison.
    ///
    /// Payload should be deserializable to [`crate::Benchmark::Output`].
    before: result::RawResult,

    /// The [`result::RawResult`] from the "after" comparison.
    ///
    /// Payload should be deserializable to [`crate::Benchmark::Output`].
    after: result::RawResult,
}

impl Job<'_> {
    /// Actually run the jobs.
    ///
    /// As long as the chain of custody throughout this module is correct, at least the
    /// `tolerance` and `input` fields should match the associated regression capable
    /// `benchmark`.
    ///
    /// The associated outputs may still fail to deserialize properly and the check could
    /// still fail. This is why the [`Jobs`] struct aggregates together all results before
    /// deciding how they should be displayed.
    fn run(&self) -> anyhow::Result<CheckedPassFail> {
        self.regression.check(
            &self.tolerance,
            &self.input,
            &self.before.results,
            &self.after.results,
        )
    }
}

#[derive(Debug)]
pub(crate) struct Jobs<'a> {
    jobs: Vec<Job<'a>>,
}

impl Jobs<'_> {
    /// Run regression checks by comparing before/after output files against the matched
    /// tolerances.
    ///
    /// The priority cascade for terminal output is:
    ///
    /// 1. If any checks produce an infrastructure error, report **all** errors and return
    ///    `Err`. Pass/fail results are suppressed so errors stay front-and-center.
    /// 2. Otherwise, if any checks fail, report **all** failures and return `Err`.
    ///    Successes are suppressed for the same reason.
    /// 3. Otherwise, all checks passed — report them and return `Ok`.
    ///
    /// The JSON output (if `output_file` is provided) is always written regardless of
    /// outcome, so downstream tooling can inspect all results.
    ///
    /// TODO: We could consider a `--verbose` flag to record all outcomes regardless of
    /// priority, but for now the hierarchy of reporting seems the most pragmatic.
    pub(crate) fn run(
        &self,
        mut output: &mut dyn crate::output::Output,
        output_file: Option<&Path>,
    ) -> anyhow::Result<()> {
        // Step 1: Run all checks, collecting results.
        let results: Vec<_> = self.jobs.iter().map(|job| job.run()).collect();

        // Step 2: Build the JSON output array (always, even on errors).
        let check_outputs: Vec<CheckOutput<'_>> = std::iter::zip(self.jobs.iter(), results.iter())
            .map(|(job, result)| -> anyhow::Result<_> {
                let tolerance = job.tolerance.serialize()?;
                let o = match result {
                    Ok(PassFail::Pass(checked)) => CheckOutput::pass(tolerance, &checked.json),
                    Ok(PassFail::Fail(checked)) => CheckOutput::fail(tolerance, &checked.json),
                    Err(err) => CheckOutput::error(tolerance, err),
                };

                Ok(o)
            })
            .collect::<anyhow::Result<_>>()?;

        // Write JSON output before the cascade so it's available even on failure.
        if let Some(path) = output_file {
            let json = serde_json::to_string_pretty(&check_outputs)?;
            std::fs::write(path, json)
                .with_context(|| format!("failed to write output to \"{}\"", path.display()))?;
        }

        // Step 3: If any errors, report all of them and bail.
        let mut has_errors = false;
        for (i, result) in results.iter().enumerate() {
            if let Err(err) = result {
                let job = &self.jobs[i];
                writeln!(
                    output,
                    "Check {} of {} ({:?}) encountered an error:\n{:?}\n",
                    i + 1,
                    self.jobs.len(),
                    job.regression.name(),
                    err,
                )?;
                has_errors = true;
            }
        }
        if has_errors {
            return Err(anyhow::anyhow!("one or more checks failed with errors"));
        }

        // Step 4: All checks completed. Report any failures.
        // (Safe to unwrap since we've handled all Err cases above.)
        let mut has_failures = false;
        for (i, result) in results.iter().enumerate() {
            #[expect(
                clippy::expect_used,
                reason = "we would have ready returned if errors were present"
            )]
            let outcome = result
                .as_ref()
                .expect("no errors should be present any more");
            if let PassFail::Fail(checked) = outcome {
                let job = &self.jobs[i];
                writeln!(
                    output,
                    "Check {} of {} ({:?}) FAILED:",
                    i + 1,
                    self.jobs.len(),
                    job.regression.name(),
                )?;
                writeln!(output, "{}", checked.display)?;
                writeln!(output)?;
                has_failures = true;
            }
        }
        if has_failures {
            return Err(anyhow::anyhow!("one or more regression checks failed"));
        }

        // Step 5: Everything passed.
        for (i, result) in results.iter().enumerate() {
            #[expect(
                clippy::expect_used,
                reason = "we would have returned if errors were present"
            )]
            let outcome = result
                .as_ref()
                .expect("no errors should be present any more");
            let PassFail::Pass(checked) = outcome else {
                unreachable!("all failures handled above");
            };
            let job = &self.jobs[i];
            writeln!(
                output,
                "Check {} of {} ({:?}) PASSED:",
                i + 1,
                self.jobs.len(),
                job.regression.name(),
            )?;
            writeln!(output, "{}", checked.display)?;
            writeln!(output)?;
        }

        Ok(())
    }
}

/// Serialized output for a single regression check, suitable for downstream tooling.
///
/// Positional index in the output array corresponds to the input/tolerance files.
#[derive(Serialize)]
struct CheckOutput<'a> {
    status: &'static str,
    tolerance: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    result: Option<&'a Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

impl<'a> CheckOutput<'a> {
    fn pass(tolerance: Value, result: &'a Value) -> Self {
        Self {
            status: "pass",
            tolerance,
            result: Some(result),
            error: None,
        }
    }

    fn fail(tolerance: Value, result: &'a Value) -> Self {
        Self {
            status: "fail",
            tolerance,
            result: Some(result),
            error: None,
        }
    }

    fn error(tolerance: Value, err: &anyhow::Error) -> Self {
        let error = err
            .chain()
            .map(|e| e.to_string())
            .collect::<Vec<_>>()
            .join(": ");
        Self {
            status: "error",
            tolerance,
            result: None,
            error: Some(error),
        }
    }
}

///////////
// Tests //
///////////

// Note: much of the functionality in this file is related to error handling and relies on
// having a fully functional registry.
//
// To that end, the UX tests are the primary test vessel for much of parsing code.
// The unit tests here stay focused on the bits that are actually feasibly unit testable.
#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// Construct a vector of `serde_json::Values` with all possible variants.
    ///
    /// Aggregates `Array` and `Map` are empty.
    fn empty_values() -> Vec<Value> {
        vec![
            Value::Null,
            Value::Bool(false),
            Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
            Value::String(String::new()),
            Value::Array(Vec::new()),
            Value::Object(serde_json::Map::new()),
        ]
    }

    #[test]
    fn test_is_subset() {
        // Null
        for v in empty_values() {
            if matches!(v, Value::Null) {
                assert!(is_subset(&Value::Null, &v));
            } else {
                assert!(!is_subset(&Value::Null, &v));
            }
        }

        // Bool / Number / String require exact equality and type matches.
        assert!(is_subset(&json!(true), &json!(true)));
        assert!(!is_subset(&json!(true), &json!(false)));
        assert!(!is_subset(&json!(true), &json!(0)));

        assert!(is_subset(&json!(7), &json!(7)));
        assert!(!is_subset(&json!(7), &json!(8)));
        assert!(!is_subset(&json!(7), &json!("7")));

        assert!(is_subset(&json!("abc"), &json!("abc")));
        assert!(!is_subset(&json!("abc"), &json!("def")));

        // Arrays match by prefix.
        assert!(is_subset(&json!([1, 2, 3]), &json!([])));
        assert!(is_subset(&json!([1, 2, 3]), &json!([1])));
        assert!(is_subset(&json!([1, 2, 3]), &json!([1, 2])));
        assert!(is_subset(&json!([1, 2, 3]), &json!([1, 2, 3])));
        assert!(!is_subset(&json!([1, 2]), &json!([1, 2, 3])));
        assert!(!is_subset(&json!([1, 2, 3]), &json!([1, 3])));

        // Objects match by recursive structural subset.
        assert!(is_subset(&json!({"a": 1, "b": 2}), &json!({"a": 1})));
        assert!(is_subset(&json!({"a": 1, "b": 2}), &json!({})));
        assert!(is_subset(
            &json!({"a": {"b": 1, "c": 2}, "d": 3}),
            &json!({"a": {"b": 1}}),
        ));
        assert!(!is_subset(&json!({"a": 1}), &json!({"a": 1, "b": 2}),));
        assert!(!is_subset(&json!({"a": {"b": 1}}), &json!({"a": {"b": 2}}),));

        // Nested array/object combinations use the same recursive rules.
        assert!(is_subset(
            &json!({"ops": [{"kind": "l2", "dim": 128}, {"kind": "cosine", "dim": 256}]}),
            &json!({"ops": [{"kind": "l2"}]}),
        ));
        assert!(is_subset(
            &json!({"ops": [{"kind": "l2", "dim": 128}, {"kind": "cosine", "dim": 256}]}),
            &json!({"ops": [{"kind": "l2", "dim": 128}, {"kind": "cosine"}]}),
        ));
        assert!(!is_subset(
            &json!({"ops": [{"kind": "l2", "dim": 128}, {"kind": "cosine", "dim": 256}]}),
            &json!({"ops": [{"kind": "cosine"}]}),
        ));
    }

    #[test]
    fn test_check_matches_success() {
        let result = check_matches(vec![vec![0], vec![1]], vec![vec![0], vec![1]]).unwrap();
        assert_eq!(result, vec![0, 1]);
    }

    #[test]
    fn test_check_matches_reports_problems_in_stable_order() {
        let err = check_matches(
            vec![vec![0], vec![], vec![2, 3]],
            vec![vec![0], vec![], vec![2, 3]],
        )
        .unwrap_err();

        assert_eq!(
            &err.0,
            &[
                MatchProblem::OrphanedTolerance(1),
                MatchProblem::UncoveredInput(1),
                MatchProblem::AmbiguousInput(2, vec![2, 3]),
            ]
        )
    }
}