diskann-benchmark-runner 0.55.0

DiskANN3 is a composable library for bringing scalable, accurate and cost-effective vector indexing to multiple databases.
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
/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 */

use serde::{Deserialize, Serialize};

use crate::{Checkpoint, Input, Output};

///////////////
// Benchmark //
///////////////

/// A registered benchmark.
///
/// Benchmarks consist of an [`Input`] and a corresponding serialized `Output`. Inputs will
/// first be validated with the benchmark using [`try_match`](Self::try_match). Only
/// successful matches will be passed to [`run`](Self::run).
pub trait Benchmark: 'static {
    /// The [`Input`] type this benchmark matches against.
    type Input: Input + 'static;

    /// The concrete type of the results generated by this benchmark.
    type Output: Serialize;

    /// Return whether or not this benchmark is compatible with `input`.
    ///
    /// Use [`MatchContext::success`] to create an initial [`Score`], then progressively
    /// refine it with [`Score::penalize`] and [`Score::fail`].
    ///
    /// Among successful matches, the benchmark with the lowest score wins. Ties are broken
    /// by an unspecified procedure.
    ///
    /// When no successful match exists, failure scores rank the "nearest misses".
    /// Implementations should use [`Score::fail`] with descriptive reasons to aid
    /// diagnostics.
    fn try_match(&self, input: &Self::Input, context: &MatchContext) -> Score;

    /// Return descriptive information about the benchmark.
    fn description(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;

    /// Run the benchmark with `input`.
    ///
    /// All prints should be directed to `output`. The `checkpoint` is provided so
    /// long-running benchmarks can periodically save output to prevent data loss due to
    /// an early error.
    ///
    /// Implementors may assume that [`Self::try_match`] returned a successful [`Score`]
    /// for `input`.
    fn run(
        &self,
        input: &Self::Input,
        checkpoint: Checkpoint<'_>,
        output: &mut dyn Output,
    ) -> anyhow::Result<Self::Output>;
}

/// A refinement of [`Benchmark`], that supports before/after comparison of generated results.
///
/// Benchmarks are associated with a "tolerance" input, which may contain runtime values
/// controlling the amount of slack a benchmark is allowed to have between runs before failing.
///
/// The semantics of pass or failure are left solely to the discretion of the [`Regression`]
/// implementation.
///
/// See: [`register_regression`](crate::Registry::register_regression).
pub trait Regression: Benchmark<Output: for<'a> Deserialize<'a>> {
    /// The tolerance [`Input`] associated with this regression check.
    type Tolerances: Input + 'static;

    /// The report summary used to describe a successful regression check.
    type Pass: Serialize + std::fmt::Display + 'static;

    /// The report summary used to describe an unsuccessful regression check.
    type Fail: Serialize + std::fmt::Display + 'static;

    /// Run any regression checks necessary for two benchmark runs `before` and `after`.
    /// Argument `tolerances` contain any tuned runtime tolerances to use when determining
    /// whether or not a regression is detected.
    ///
    /// The `input` is the raw input that would have been provided to [`Benchmark::run`]
    /// when generating the `before` and `after` outputs.
    ///
    /// Implementations of `check` should not attempt to print to `stdout` or any other
    /// stream. Instead, all diagnostics should be encoded in the returned [`PassFail`] type
    /// for reporting upstream.
    fn check(
        &self,
        tolerances: &Self::Tolerances,
        input: &Self::Input,
        before: &Self::Output,
        after: &Self::Output,
    ) -> anyhow::Result<PassFail<Self::Pass, Self::Fail>>;
}

/// Describe whether or not a [`Regression`] passed or failed.
#[derive(Debug, Clone, Copy)]
pub enum PassFail<P, F> {
    Pass(P),
    Fail(F),
}

//////////////
// Matching //
//////////////

/// Context for [`Benchmark::try_match`].
///
/// This is used to create matching [`Score`]s via [`Self::success`] and [`Self::fail`].
/// Users can test their [`Benchmark::try_match`] implementations using [`Self::test`].
///
/// Internally, the [`MatchContext`] decides whether or not failure reasons are evaluated,
/// eliding formatting in situations where the results will not be used.
#[derive(Debug)]
pub struct MatchContext {
    record_failure_reasons: bool,
}

impl MatchContext {
    /// Create a new [`Score`] configured for "success" with the given `score`.
    ///
    /// Lower scores indicate better successful matches.
    pub fn success(&self, score: u32) -> Score {
        Score {
            inner: ScoreInner::Success(SuccessScore(score)),
            context: self.hidden_clone(),
        }
    }

    /// Create a new [`Score`] configured for "failure" with the given `score`.
    ///
    /// Lower scores indicate better "near misses".
    pub fn fail(&self, score: u32, reason: &dyn std::fmt::Display) -> Score {
        let mut s = self.success(u32::MAX);
        s.fail(score, reason);
        s
    }

    /// Test a [`Benchmark::try_match`] implementation, returning a [`TestScore`] with
    /// full failure reasons (if applicable).
    pub fn test<T>(benchmark: &T, input: &T::Input) -> TestScore
    where
        T: Benchmark,
    {
        benchmark
            .try_match(input, &Self::with_reasons())
            .into_test()
    }

    fn hidden_clone(&self) -> Self {
        Self {
            record_failure_reasons: self.record_failure_reasons,
        }
    }

    /// Create a new [`MatchContext`] that does not evaluate failure reasons.
    pub(crate) fn new() -> Self {
        Self {
            record_failure_reasons: false,
        }
    }

    /// Create a new [`MatchContext`] that evaluates failure reasons.
    pub(crate) fn with_reasons() -> Self {
        Self {
            record_failure_reasons: true,
        }
    }
}

/// The result of [`MatchContext::test`], providing low-level access to the final match
/// scoring and failure reasons.
#[derive(Debug)]
pub enum TestScore {
    Success(u32),
    Failure {
        score: u32,
        reasons: Option<Vec<String>>,
    },
}

/// A score for [`Benchmark::try_match`].
///
/// A [`Score`] is in one of two states: success or failure. Lower scores indicate better
/// matches in both states. In the failure case, scores rank "near misses" for diagnostics.
///
/// - [`Score::penalize`] increases the score of a successful match.
/// - [`Score::fail`] transitions to (or worsens) the failure state.
///
/// The current state can be queried with [`Score::is_success`].
#[derive(Debug)]
pub struct Score {
    inner: ScoreInner,
    context: MatchContext,
}

impl Score {
    /// If the score is in the "success" state, penalize it by `by`.
    ///
    /// Has no effect if the score is already in the "failure" state.
    pub fn penalize(&mut self, by: u32) {
        match self.inner {
            ScoreInner::Success(ref mut v) => v.0 = v.0.saturating_add(by),
            ScoreInner::Failure(..) => {}
        }
    }

    /// Transition the score to the "failure" state with penalty `by` and a `reason`.
    ///
    /// If the score is already in the "failure" state, `by` is added to the existing
    /// failure score and `reason` is appended to the list of failure reasons.
    pub fn fail(&mut self, by: u32, reason: &dyn std::fmt::Display) {
        match &mut self.inner {
            ScoreInner::Success(_) => {
                self.inner = ScoreInner::Failure(
                    FailureScore(by),
                    self.context
                        .record_failure_reasons
                        .then(|| vec![reason.to_string()]),
                );
            }
            ScoreInner::Failure(score, reasons) => {
                score.0 = (score.0).saturating_add(by);
                if self.context.record_failure_reasons {
                    reasons
                        .get_or_insert_with(|| Vec::with_capacity(1))
                        .push(reason.to_string())
                }
            }
        }
    }

    /// Return `true` if `self` is in the "success" state. Returning `false` implies the
    /// "failure" state.
    #[must_use = "this function has no side-effects"]
    pub fn is_success(&self) -> bool {
        matches!(self.inner, ScoreInner::Success(_))
    }

    fn into_test(self) -> TestScore {
        match self.inner {
            ScoreInner::Success(score) => TestScore::Success(score.0),
            ScoreInner::Failure(score, reasons) => TestScore::Failure {
                score: score.0,
                reasons,
            },
        }
    }

    pub(crate) fn match_score(&self) -> Option<SuccessScore> {
        match self.inner {
            ScoreInner::Success(score) => Some(score),
            ScoreInner::Failure(..) => None,
        }
    }

    pub(crate) fn as_raw(&self) -> RawScore {
        match self.inner {
            ScoreInner::Success(s) => RawScore::Success(s),
            ScoreInner::Failure(s, _) => RawScore::Failure(s),
        }
    }

    pub(crate) fn reason(&self) -> Reason<'_> {
        match &self.inner {
            ScoreInner::Success(_) => Reason::none(),
            ScoreInner::Failure(_, reasons) => Reason::new(reasons.as_deref()),
        }
    }
}

#[derive(Debug)]
enum ScoreInner {
    Success(SuccessScore),
    Failure(FailureScore, Option<Vec<String>>),
}

pub(crate) struct Reason<'a>(Option<&'a [String]>);

impl<'a> Reason<'a> {
    fn new(reasons: Option<&'a [String]>) -> Self {
        Self(reasons)
    }

    fn none() -> Self {
        Self(None)
    }
}

impl std::fmt::Display for Reason<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0 {
            None => f.write_str("<missing>"),
            Some(reasons) => {
                let mut first = true;
                for reason in reasons.iter() {
                    if !first {
                        writeln!(f)?;
                    }
                    write!(f, "- {}", reason)?;
                    first = false;
                }
                Ok(())
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum RawScore {
    Success(SuccessScore),
    Failure(FailureScore),
}

impl RawScore {
    #[cfg(test)]
    fn success(score: u32) -> Self {
        Self::Success(SuccessScore(score))
    }

    #[cfg(test)]
    fn failure(score: u32) -> Self {
        Self::Failure(FailureScore(score))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct SuccessScore(pub(crate) u32);

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct FailureScore(pub(crate) u32);

//////////////
// Internal //
//////////////

pub(crate) mod internal {
    use super::*;

    use crate::input::internal::Any;

    use anyhow::Context;
    use thiserror::Error;

    /// Object-safe trait for type-erased benchmarks stored in the registry.
    pub(crate) trait Benchmark {
        fn try_match(&self, input: &Any, context: &MatchContext) -> Score;

        fn description(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;

        fn run(
            &self,
            input: &Any,
            checkpoint: Checkpoint<'_>,
            output: &mut dyn Output,
        ) -> anyhow::Result<serde_json::Value>;

        /// If supported, return an object capable of running regression checks on this benchmark.
        fn as_regression(&self) -> Option<&dyn Regression>;

        fn as_string(&self) -> String {
            Description(self).to_string()
        }
    }

    struct Description<'a, T: ?Sized>(&'a T);

    impl<T> std::fmt::Display for Description<'_, T>
    where
        T: Benchmark + ?Sized,
    {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            self.0.description(f)
        }
    }

    pub(crate) struct Checked {
        pub(crate) json: serde_json::Value,
        pub(crate) display: Box<dyn std::fmt::Display>,
    }

    impl Checked {
        /// Serialize `value` to `serde_json::Value` and box it for future display.
        fn new<T>(value: T) -> Result<Self, serde_json::Error>
        where
            T: Serialize + std::fmt::Display + 'static,
        {
            Ok(Self {
                json: serde_json::to_value(&value)?,
                display: Box::new(value),
            })
        }
    }

    pub(crate) type CheckedPassFail = PassFail<Checked, Checked>;

    pub(crate) trait Regression {
        fn tolerance(&self) -> &dyn crate::input::internal::DynInput;
        fn input_tag(&self) -> &'static str;
        fn check(
            &self,
            tolerances: &Any,
            input: &Any,
            before: &serde_json::Value,
            after: &serde_json::Value,
        ) -> anyhow::Result<CheckedPassFail>;
    }

    impl std::fmt::Debug for dyn Regression + '_ {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("dyn Regression")
                .field("tolerance", &self.tolerance().tag())
                .field("input_tag", &self.input_tag())
                .finish()
        }
    }

    pub(crate) trait AsRegression<T> {
        fn as_regression(benchmark: &T) -> Option<&dyn Regression>;
    }

    #[derive(Debug, Clone, Copy)]
    pub(crate) struct NoRegression;

    impl<T> AsRegression<T> for NoRegression {
        fn as_regression(_benchmark: &T) -> Option<&dyn Regression> {
            None
        }
    }

    #[derive(Debug, Clone, Copy)]
    pub(crate) struct WithRegression;

    impl<T> AsRegression<T> for WithRegression
    where
        T: super::Regression,
    {
        fn as_regression(benchmark: &T) -> Option<&dyn Regression> {
            Some(benchmark)
        }
    }

    impl<T> Regression for T
    where
        T: super::Regression,
    {
        fn tolerance(&self) -> &dyn crate::input::internal::DynInput {
            &crate::input::internal::Wrapper::<T::Tolerances>::INSTANCE
        }

        fn input_tag(&self) -> &'static str {
            T::Input::tag()
        }

        fn check(
            &self,
            tolerance: &Any,
            input: &Any,
            before: &serde_json::Value,
            after: &serde_json::Value,
        ) -> anyhow::Result<CheckedPassFail> {
            let tolerance = tolerance
                .downcast_ref::<T::Tolerances>()
                .ok_or_else(|| BadDownCast::new(T::Tolerances::tag(), tolerance.tag()))
                .context("failed to obtain tolerance")?;

            let input = input
                .downcast_ref::<T::Input>()
                .ok_or_else(|| BadDownCast::new(T::Input::tag(), input.tag()))
                .context("failed to obtain input")?;

            let before = T::Output::deserialize(before)
                .map_err(|err| DeserializationError::new(Kind::Before, err))?;

            let after = T::Output::deserialize(after)
                .map_err(|err| DeserializationError::new(Kind::After, err))?;

            let passfail = match self.check(tolerance, input, &before, &after)? {
                PassFail::Pass(pass) => PassFail::Pass(Checked::new(pass)?),
                PassFail::Fail(fail) => PassFail::Fail(Checked::new(fail)?),
            };

            Ok(passfail)
        }
    }

    #[derive(Debug, Clone, Copy)]
    pub(crate) struct Wrapper<T, R = NoRegression> {
        benchmark: T,
        _regression: R,
    }

    impl<T, R> Wrapper<T, R> {
        pub(crate) const fn new(benchmark: T, regression: R) -> Self {
            Self {
                benchmark,
                _regression: regression,
            }
        }
    }

    const MATCH_FAIL: u32 = 10_000;

    impl<T, R> Benchmark for Wrapper<T, R>
    where
        T: super::Benchmark,
        R: AsRegression<T>,
    {
        fn try_match(&self, input: &Any, context: &MatchContext) -> Score {
            if let Some(cast) = input.downcast_ref::<T::Input>() {
                self.benchmark.try_match(cast, context)
            } else {
                struct TagMismatch<T>(&'static str, std::marker::PhantomData<T>);

                impl<T> std::fmt::Display for TagMismatch<T>
                where
                    T: super::Benchmark,
                {
                    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                        write!(
                            f,
                            "expected tag \"{}\" - instead got \"{}\"",
                            T::Input::tag(),
                            self.0,
                        )
                    }
                }

                context.fail(
                    MATCH_FAIL,
                    &TagMismatch::<T>(input.tag(), std::marker::PhantomData),
                )
            }
        }

        fn description(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            writeln!(f, "tag \"{}\"", <T::Input as Input>::tag())?;
            self.benchmark.description(f)
        }

        fn run(
            &self,
            input: &Any,
            checkpoint: Checkpoint<'_>,
            output: &mut dyn Output,
        ) -> anyhow::Result<serde_json::Value> {
            match input.downcast_ref::<T::Input>() {
                Some(input) => {
                    let result = self.benchmark.run(input, checkpoint, output)?;
                    Ok(serde_json::to_value(result)?)
                }
                None => Err(BadDownCast::new(T::Input::tag(), input.tag()).into()),
            }
        }

        // Extensions
        fn as_regression(&self) -> Option<&dyn Regression> {
            R::as_regression(&self.benchmark)
        }
    }

    //--------//
    // Errors //
    //--------//

    #[derive(Debug, Clone, Copy, Error)]
    #[error(
        "INTERNAL ERROR: bad downcast - expected \"{}\" but got \"{}\"",
        self.expected,
        self.got
    )]
    struct BadDownCast {
        expected: &'static str,
        got: &'static str,
    }

    impl BadDownCast {
        fn new(expected: &'static str, got: &'static str) -> Self {
            Self { expected, got }
        }
    }

    #[derive(Debug, Error)]
    #[error(
        "the \"{}\" results do not match the output schema expected by this benchmark",
        self.kind
    )]
    struct DeserializationError {
        kind: Kind,
        source: serde_json::Error,
    }

    impl DeserializationError {
        fn new(kind: Kind, source: serde_json::Error) -> Self {
            Self { kind, source }
        }
    }

    #[derive(Debug, Clone, Copy)]
    enum Kind {
        Before,
        After,
    }

    impl std::fmt::Display for Kind {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let as_str = match self {
                Self::Before => "before",
                Self::After => "after",
            };

            write!(f, "{}", as_str)
        }
    }
}

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

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

    #[test]
    fn test_score_no_reasons() {
        let context = MatchContext::new();
        let mut score = context.success(0);
        assert!(score.is_success());
        assert_eq!(score.as_raw(), RawScore::success(0));

        score.penalize(10);
        assert!(score.is_success());
        assert_eq!(score.as_raw(), RawScore::success(10));

        score.penalize(10);
        assert!(score.is_success());
        assert_eq!(score.as_raw(), RawScore::success(20));

        // Ensure that we saturate properly.
        score.penalize(u32::MAX);
        assert!(score.is_success());
        assert_eq!(score.as_raw(), RawScore::success(u32::MAX));

        // Switch to failure
        score.fail(5, &"some reason that is not evaluated");
        assert!(!score.is_success());
        assert_eq!(score.as_raw(), RawScore::failure(5));

        score.fail(10, &"another reason that is not evaluated");
        assert!(!score.is_success());
        assert_eq!(score.as_raw(), RawScore::failure(15));

        // Calling `penalize` should have no effect.
        score.penalize(5);
        assert!(!score.is_success());
        assert_eq!(score.as_raw(), RawScore::failure(15));

        // Since we aren't recording reasons - nothing should be returned.
        assert_eq!(score.reason().to_string(), "<missing>");
    }

    #[test]
    fn test_score_with_reasons() {
        let context = MatchContext::with_reasons();
        let mut score = context.success(0);
        assert!(score.is_success());
        assert_eq!(score.as_raw(), RawScore::success(0));

        score.penalize(10);
        assert!(score.is_success());
        assert_eq!(score.as_raw(), RawScore::success(10));

        score.penalize(10);
        assert!(score.is_success());
        assert_eq!(score.as_raw(), RawScore::success(20));
        assert_eq!(score.reason().to_string(), "<missing>");

        // Ensure that we saturate properly.
        score.penalize(u32::MAX);
        assert!(score.is_success());
        assert_eq!(score.as_raw(), RawScore::success(u32::MAX));

        // Switch to failure
        score.fail(5, &"some reason that is evaluated");
        assert!(!score.is_success());
        assert_eq!(score.as_raw(), RawScore::failure(5));

        score.fail(10, &"another reason that is evaluated");
        assert!(!score.is_success());
        assert_eq!(score.as_raw(), RawScore::failure(15));

        // Calling `penalize` should have no effect.
        score.penalize(5);
        assert!(!score.is_success());
        assert_eq!(score.as_raw(), RawScore::failure(15));

        // Reasons are recorded, so both failure reasons should be returned.
        let expected = "- some reason that is evaluated\n\
                        - another reason that is evaluated";
        assert_eq!(score.reason().to_string(), expected);
    }
}