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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use log::trace;
use std::borrow::Borrow;
use std::cmp;
use std::rc::Rc;

mod flakiness_tracker;
use flakiness_tracker::*;
mod range_map;
use range_map::*;

mod dag;

/// Reference to a node in a CompressedDAG.
#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
pub struct CompressedDAGNodeRef {
    /// Index of the segment in the CompressedDAG.
    pub segment: usize,
    /// Index of the expanded node within the segment.
    pub index: usize,
}

/// A segment in a CompressedDAG. This is a node in a DAG but corresponds to a linear sequence of
/// nodes in a conceptual expanded graph. The size is the number of nodes in the expanded graph
/// represented by this segment.
#[derive(Clone, Debug)]
pub struct CompressedDAGSegment {
    len: usize,
}

impl CompressedDAGSegment {
    /// Creates a CompressedDAGSegment of a given size.
    pub fn new(len: usize) -> Self {
        CompressedDAGSegment { len }
    }

    /// Returns the size of the segment.
    pub fn len(&self) -> usize {
        self.len
    }
}

/// A DAG whose nodes are CompressedDAGSegments, which represent sequences of nodes in a conceptual
/// expanded graph. For example, given the graph:
///
/// ```text
///   B-C-D
///  /     \
/// A       G
///  \     /
///   E---F
/// ```
///
/// this can be expressed in a CompressedDAG as:
///
/// ```text
///   B'
///  / \
/// A'  G'
///  \ /
///   E'
/// ```
///
/// where `A'` and `G'` are segments of size 1 corresponding to `A` and `G`, `E'` is a segment of
/// size 2 corresponding to `E` and `F`, and `B'` is a segment of size 3 corresponding to `B`, `C`,
/// and `D`.
///
/// More formally, the nodes represented by a segment must be in a linear formation (i.e. directed,
/// acyclic, connected, with each node having at most one incoming edge from another node in the
/// segment and at most one outgoing edge to another node in the segment), with only the first node
/// allowing edges from outside the segment, and only the last node allowing edges to outside the
/// segment.
///
/// This representation allows many common graphs to be represented in a more compact form than
/// directly as a DAG.
pub type CompressedDAG = dag::DAG<CompressedDAGSegment>;

mod compressed_dag_flakiness_tracker;
use compressed_dag_flakiness_tracker::*;

/// Finds the index such that the sum of values at indices [0, i] (inclusive) is as close as
/// possible to the argument. Returns the index and the sum.
fn confidence_percentile_nearest(range_map: &RangeMap<f64>, percentile: f64) -> (usize, f64) {
    let mut sum = 0.0;
    let mut index = 0;
    let mut best_index = 0;
    let mut best_percentile = f64::NEG_INFINITY;
    for w in range_map.ranges() {
        let delta = w.len() as f64 * w.value();
        trace!(
            "percentile = {}, sum = {}, w.value = {}",
            percentile,
            sum,
            w.value()
        );
        trace!(
            "(percentile - sum) / w.value() - 0.5 = {}",
            (percentile - sum) / w.value() - 0.5
        );
        let ix = index
            + cmp::min(
                w.len() - 1,
                ((percentile - sum) / w.value() - 0.5).max(0.0) as usize,
            );
        let ix_percentile = sum + (ix - index + 1) as f64 * w.value();
        trace!("ix = {} ix_percentile = {}", ix, ix_percentile);
        if (ix_percentile - percentile).abs() < (best_percentile - percentile).abs() {
            best_index = ix;
            best_percentile = ix_percentile;
        }
        sum += delta;
        index += w.len();
    }
    assert!(best_percentile > f64::NEG_INFINITY);
    trace!(
        "confidence_percentile_nearest returning {:?}",
        (best_index, best_percentile)
    );
    (best_index, best_percentile)
}

/// Finds the smallest index such that the sum of values at indices [0, i] (inclusive) is greater
/// than or equal to the argument. Returns the index and the sum. If no sum is greater than or equal
/// to the argument, returns the last index and the sum over all values.
fn confidence_percentile_ceil(range_map: &RangeMap<f64>, percentile: f64) -> (usize, f64) {
    let mut sum = 0.0;
    let mut index = 0;
    for w in range_map.ranges() {
        let delta = w.len() as f64 * w.value();
        if sum + delta >= percentile {
            let ix = index + ((percentile - sum) / w.value() - 1e-9) as usize;
            let ret = (ix, sum + (ix - index + 1) as f64 * w.value());
            trace!("confidence_percentile_ceil returning {:?}", ret);
            return ret;
        }
        sum += delta;
        index += w.len();
    }
    (range_map.len() - 1, sum)
}

// Does not normalize.
fn report_range(weights: &mut RangeMap<f64>, index: usize, heads: bool, stiffness: f64) {
    if heads {
        for w in weights.split(index).0 {
            *w.value_mut() *= 1.0 + stiffness;
        }
        let (left, _right) = weights.split(index + 1);
        *left.rev().next().unwrap().value_mut() *= 1.0 + stiffness;
    } else {
        weights.split(index);
        let (_left, right) = weights.split(index + 1);
        for w in right {
            *w.value_mut() *= 1.0 + stiffness;
        }
    }
}

/// Performs a robust binary search over a linear range.
#[derive(Clone, Debug)]
pub struct Searcher {
    weights: RangeMap<f64>,
    len: usize,
}

impl Searcher {
    /// Creates a new Searcher over a range with the given number of testable indices.
    pub fn new(len: usize) -> Self {
        Searcher {
            weights: RangeMap::new(len + 1, 1.0 / (len as f64 + 1.0)),
            len,
        }
    }

    /// Same as `report` but with a specified stiffness. Only public for use by the tuner, not for
    /// public use.
    ///
    /// # Panics
    ///
    /// Panics if `index >= len`.
    #[doc(hidden)]
    pub fn report_with_stiffness(&mut self, index: usize, heads: bool, stiffness: f64) {
        assert!(index < self.len);
        report_range(&mut self.weights, index, heads, stiffness);
        let weight_sum: f64 = self
            .weights
            .ranges()
            .map(|w| w.value() * w.len() as f64)
            .sum();
        for w in self.weights.ranges_mut() {
            *w.value_mut() /= weight_sum;
        }
    }

    /// Adds a vote to the internal statistics. With low flakiness, false votes are expected to have
    /// smaller indices than true votes.
    ///
    /// # Panics
    ///
    /// Panics if `index >= len`.
    pub fn report(&mut self, index: usize, heads: bool, flakiness: f64) {
        self.report_with_stiffness(index, heads, optimal_stiffness(flakiness));
    }

    /// Returns the next index that should be tested. Can return values in the range 0 to len,
    /// exclusive.
    pub fn next_index(&self) -> usize {
        cmp::min(
            confidence_percentile_nearest(&self.weights, 0.5).0,
            self.len - 1,
        )
    }

    /// Returns the current estimate of the best index. Can return values in the range 0 to len,
    /// inclusive.
    pub fn best_index(&self) -> usize {
        confidence_percentile_ceil(&self.weights, 0.5).0
    }

    /// Only public for use by the tuner, not for public use.
    #[doc(hidden)]
    pub fn confidence_percentile_ceil(&self, percentile: f64) -> usize {
        confidence_percentile_ceil(&self.weights, percentile).0
    }

    /// Returns the likelihood of the given index.
    ///
    /// # Panics
    ///
    /// Panics if `index > len`.
    pub fn likelihood(&self, index: usize) -> f64 {
        *self.weights.range_for_index(index).value()
    }
}

/// Returns the stiffness which should be optimal for the given flakiness.
fn optimal_stiffness(flakiness: f64) -> f64 {
    // Values calculated by tuner.rs
    (2.6 / flakiness.powf(0.37))
        .min(0.58 / flakiness.powf(0.97))
        .min(0.19 / flakiness.powf(2.4))
}

/// Performs a robust binary search over a linear range and automatically infers the flakiness based
/// on the votes.
#[derive(Clone, Debug)]
pub struct AutoSearcher {
    searcher: Searcher,
    flakiness_tracker: FlakinessTracker,
}

impl AutoSearcher {
    /// Creates a new AutoSearcher over a range with the given number of testable indices.
    pub fn new(len: usize) -> Self {
        AutoSearcher {
            searcher: Searcher::new(len),
            flakiness_tracker: FlakinessTracker::default(),
        }
    }

    /// Adds a vote to the internal statistics. With low flakiness, false votes are expected to have
    /// smaller indices than true votes.
    ///
    /// # Panics
    ///
    /// Panics if `index >= len`.
    pub fn report(&mut self, index: usize, heads: bool) {
        self.flakiness_tracker.report(index, heads);
        self.searcher
            .report(index, heads, self.flakiness_tracker.flakiness());
    }

    /// Returns the next index that should be tested. Can return values in the range 0 to len,
    /// exclusive.
    pub fn next_index(&self) -> usize {
        self.searcher.next_index()
    }

    /// Returns the current estimate of the best index. Can return values in the range 0 to len,
    /// inclusive.
    pub fn best_index(&self) -> usize {
        self.searcher.best_index()
    }

    /// Returns the likelihood of the given index.
    ///
    /// # Panics
    ///
    /// Panics if `index > len`.
    pub fn likelihood(&self, index: usize) -> f64 {
        self.searcher.likelihood(index)
    }
}

/// Performs a robust binary search over a CompressedDAG.
#[derive(Clone, Debug)]
pub struct CompressedDAGSearcher {
    graph: Rc<CompressedDAG>,
    segment_range_maps: Vec<RangeMap<f64>>,
}

impl CompressedDAGSearcher {
    /// Creates a new CompressedDAGSearcher.
    pub fn new(graph: Rc<CompressedDAG>) -> Self {
        let n = graph
            .nodes()
            .iter()
            .map(|node| node.value().len())
            .fold(0, |x, y| x + y);
        let segment_range_maps = graph
            .nodes()
            .iter()
            .map(|node| RangeMap::new(node.value().len(), 1.0 / n as f64))
            .collect();
        CompressedDAGSearcher {
            graph,
            segment_range_maps,
        }
    }

    /// Returns the sums at the beginning and end of every segment. Each vector entry corresponds to
    /// a single segment. The first entry in the tuple is the sum of all weights in the segment's
    /// ancestors (i.e. source segments will have a start of 0.0), and the second entry is the sum
    /// of all weights in the segment and its ancestors.
    fn segment_percentile_ranges(&self) -> Vec<(f64, f64)> {
        let mut segment_ranges = Vec::<(f64, f64)>::new();
        let mut segment_sums = Vec::<f64>::new();
        let graph: &CompressedDAG = self.graph.borrow();
        for (i, range_map) in self.segment_range_maps.iter().enumerate() {
            let inputs = graph.node(i).inputs();
            let start = if inputs.is_empty() {
                0.0
            } else {
                let mut start = segment_ranges[inputs[0]].1;
                for ancestor in graph.node(i).remainder_ancestors() {
                    start += segment_sums[*ancestor];
                }
                start
            };
            let mut segment_sum = 0.0;
            for range in range_map.ranges() {
                segment_sum += range.value() * range.len() as f64;
            }
            segment_sums.push(segment_sum);
            let end = start + segment_sum;
            assert!(
                start >= 0.0 && start <= 1.0 + 1e-11 && end >= 0.0 && end <= 1.0 + 1e-11,
                "i = {} of {}, start = {}, end = {}",
                i,
                self.segment_range_maps.len(),
                start,
                end
            );
            segment_ranges.push((start, end));
        }
        segment_ranges
    }

    /// Returns the node whose percentile (i.e. the sum of weights over the node and its ancestors)
    /// is nearest the argument.
    fn confidence_percentile_nearest(&self, percentile: f64) -> CompressedDAGNodeRef {
        let segment_ranges = self.segment_percentile_ranges();
        trace!("segment_ranges = {:?}", segment_ranges);
        let mut best_node = CompressedDAGNodeRef {
            segment: 0,
            index: 0,
        };
        let mut best_value = f64::NEG_INFINITY;
        for (i, range) in segment_ranges.iter().enumerate() {
            let (ix, mut value) =
                confidence_percentile_nearest(&self.segment_range_maps[i], percentile - range.0);
            value += range.0;
            if (percentile - value).abs() < (percentile - best_value).abs() {
                best_node = CompressedDAGNodeRef {
                    segment: i,
                    index: ix,
                };
                best_value = value;
            }
        }
        assert!(best_value > f64::NEG_INFINITY);
        best_node
    }

    /// Returns the node whose percentile (i.e. the sum of weights over the node and its ancestors)
    /// is smallest but greater than or equal to the argument.
    pub fn confidence_percentile_ceil(&self, percentile: f64) -> CompressedDAGNodeRef {
        let segment_ranges = self.segment_percentile_ranges();
        let mut min_end = 0;
        let mut min_end_segment = 0;
        let mut min_end_value = f64::INFINITY;
        for (i, range) in segment_ranges.iter().enumerate() {
            let (ix, mut value) =
                confidence_percentile_ceil(&self.segment_range_maps[i], percentile - range.0);
            value += range.0;
            trace!(
                "i = {}, ix = {}, value = {}, min_end_value = {}",
                i,
                ix,
                value,
                min_end_value
            );
            if value < min_end_value && value >= percentile {
                min_end = ix;
                min_end_segment = i;
                min_end_value = value;
            }
        }
        let ret = CompressedDAGNodeRef {
            segment: min_end_segment,
            index: min_end,
        };
        trace!(
            "CompressedDAGSearcher::confidence_percentile_ceil returning {:?}",
            ret
        );
        ret
    }

    /// Returns the current estimate of the best node.
    pub fn best_node(&self) -> CompressedDAGNodeRef {
        self.confidence_percentile_ceil(0.5)
    }

    /// Returns the next node that should be tested.
    pub fn next_node(&self) -> CompressedDAGNodeRef {
        self.confidence_percentile_nearest(0.5)
    }

    /// Adds a vote to the internal statistics. With low flakiness, nodes with false votes are
    /// expected not to nodes with true votes as ancestors.
    ///
    /// # Panics
    ///
    /// Panics if the node is out of range.
    pub fn report(&mut self, node: CompressedDAGNodeRef, heads: bool, flakiness: f64) {
        let stiffness = optimal_stiffness(flakiness);
        let graph: &CompressedDAG = self.graph.borrow();
        if heads {
            for segment in graph.node(node.segment).ancestors() {
                for w in self.segment_range_maps[*segment].ranges_mut() {
                    *w.value_mut() *= 1.0 + stiffness;
                }
            }
        } else {
            let ancestor_segments = graph.node(node.segment).ancestors();
            for segment in 0..graph.nodes().len() {
                if ancestor_segments.contains(&segment) || segment == node.segment {
                    continue;
                }
                for w in self.segment_range_maps[segment].ranges_mut() {
                    *w.value_mut() *= 1.0 + stiffness;
                }
            }
        }
        report_range(
            &mut self.segment_range_maps[node.segment],
            node.index,
            heads,
            stiffness,
        );
        let weight_sum: f64 = self
            .segment_range_maps
            .iter()
            .map(|range_map| {
                range_map
                    .ranges()
                    .map(|w| w.value() * w.len() as f64)
                    .sum::<f64>()
            })
            .sum();
        for range_map in &mut self.segment_range_maps {
            for w in range_map.ranges_mut() {
                *w.value_mut() /= weight_sum;
            }
        }
    }

    /// Returns the likelihood of the given index.
    ///
    /// # Panics
    ///
    /// Panics if the node is out of range.
    pub fn likelihood(&self, node: CompressedDAGNodeRef) -> f64 {
        *self.segment_range_maps[node.segment]
            .range_for_index(node.index)
            .value()
    }
}

/// Performs a robust binary search over a CompressedDAG and automatically infers the flakiness
/// based on the votes.
#[derive(Clone, Debug)]
pub struct AutoCompressedDAGSearcher {
    searcher: CompressedDAGSearcher,
    flakiness_tracker: CompressedDAGFlakinessTracker,
}

impl AutoCompressedDAGSearcher {
    /// Creates a new AutoCompressedDAGSearcher.
    pub fn new(graph: Rc<CompressedDAG>) -> Self {
        Self {
            searcher: CompressedDAGSearcher::new(graph.clone()),
            flakiness_tracker: CompressedDAGFlakinessTracker::new(graph),
        }
    }

    /// Adds a vote to the internal statistics. With low flakiness, nodes with false votes are
    /// expected not to nodes with true votes as ancestors.
    ///
    /// # Panics
    ///
    /// Panics if the node is out of range.
    pub fn report(&mut self, node: CompressedDAGNodeRef, heads: bool) {
        self.flakiness_tracker.report(node, heads);
        self.searcher
            .report(node, heads, self.flakiness_tracker.flakiness());
    }

    /// Returns the next node that should be tested.
    pub fn next_node(&self) -> CompressedDAGNodeRef {
        self.searcher.next_node()
    }

    /// Returns the current estimate of the best node.
    pub fn best_node(&self) -> CompressedDAGNodeRef {
        self.searcher.best_node()
    }

    /// Returns the likelihood of the given index.
    ///
    /// # Panics
    ///
    /// Panics if the node is out of range.
    pub fn likelihood(&self, index: CompressedDAGNodeRef) -> f64 {
        self.searcher.likelihood(index)
    }

    /// Returns the estimated flakiness.
    pub fn flakiness(&self) -> f64 {
        self.flakiness_tracker.flakiness()
    }
}

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

    const DEFAULT_FLAKINESS: f64 = 0.01;

    macro_rules! assert_index {
        ($searcher:expr, $next:expr, $best:expr, $heads:expr, $flakiness:expr) => {
            assert_eq!($searcher.next_index(), $next, "next_index");
            assert_eq!($searcher.best_index(), $best, "best_index");
            $searcher.report($next, $heads, $flakiness);
        };
    }

    // Each test should run until a cycle repeats itself three times, and the
    // best_index is stable. The cycle may consist of a single element.

    #[test]
    fn one_element_zero() {
        let mut s = Searcher::new(1);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
    }

    #[test]
    fn one_element_one() {
        let mut s = Searcher::new(1);
        assert_index!(s, 0, 0, false, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, false, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, false, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, false, DEFAULT_FLAKINESS);
    }

    #[test]
    fn two_elements_zero() {
        let mut s = Searcher::new(2);
        assert_index!(s, 1, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
    }

    #[test]
    fn two_elements_one() {
        let mut s = Searcher::new(2);
        assert_index!(s, 1, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, false, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, true, DEFAULT_FLAKINESS);
    }

    #[test]
    fn two_elements_two() {
        let mut s = Searcher::new(2);
        assert_index!(s, 1, 1, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 2, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 2, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 2, false, DEFAULT_FLAKINESS);
    }

    #[test]
    fn three_elements_zero() {
        let mut s = Searcher::new(3);
        assert_index!(s, 1, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
    }

    #[test]
    fn three_elements_one() {
        let mut s = Searcher::new(3);
        assert_index!(s, 1, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, false, DEFAULT_FLAKINESS);
    }

    #[test]
    fn three_elements_two() {
        let mut s = Searcher::new(3);
        assert_index!(s, 1, 1, false, DEFAULT_FLAKINESS);
        assert_index!(s, 2, 2, true, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 2, false, DEFAULT_FLAKINESS);
        assert_index!(s, 2, 2, true, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 2, false, DEFAULT_FLAKINESS);
        assert_index!(s, 2, 2, true, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 2, false, DEFAULT_FLAKINESS);
    }

    #[test]
    fn three_elements_three() {
        let mut s = Searcher::new(3);
        assert_index!(s, 1, 1, false, DEFAULT_FLAKINESS);
        assert_index!(s, 2, 2, false, DEFAULT_FLAKINESS);
        assert_index!(s, 2, 3, false, DEFAULT_FLAKINESS);
        assert_index!(s, 2, 3, false, DEFAULT_FLAKINESS);
        assert_index!(s, 2, 3, false, DEFAULT_FLAKINESS);
    }

    #[test]
    fn many_elements_first() {
        let mut s = Searcher::new(1024);
        assert_index!(s, 512, 512, true, DEFAULT_FLAKINESS);
        assert_index!(s, 272, 273, true, DEFAULT_FLAKINESS);
        assert_index!(s, 144, 145, true, DEFAULT_FLAKINESS);
        assert_index!(s, 76, 77, true, DEFAULT_FLAKINESS);
        assert_index!(s, 40, 41, true, DEFAULT_FLAKINESS);
        assert_index!(s, 21, 21, true, DEFAULT_FLAKINESS);
        assert_index!(s, 11, 11, true, DEFAULT_FLAKINESS);
        assert_index!(s, 5, 6, true, DEFAULT_FLAKINESS);
        assert_index!(s, 2, 3, true, DEFAULT_FLAKINESS);
        assert_index!(s, 1, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 1, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
        assert_index!(s, 0, 0, true, DEFAULT_FLAKINESS);
    }

    #[test]
    fn many_elements_last() {
        let mut s = Searcher::new(1024);
        assert_index!(s, 512, 512, false, DEFAULT_FLAKINESS);
        assert_index!(s, 751, 752, false, DEFAULT_FLAKINESS);
        assert_index!(s, 879, 879, false, DEFAULT_FLAKINESS);
        assert_index!(s, 947, 947, false, DEFAULT_FLAKINESS);
        assert_index!(s, 983, 983, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1002, 1003, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1012, 1013, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1018, 1018, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1021, 1021, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1022, 1023, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1023, 1023, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1023, 1024, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1023, 1024, false, DEFAULT_FLAKINESS);
        assert_index!(s, 1023, 1024, false, DEFAULT_FLAKINESS);
    }

    #[test]
    fn graph_confidence_percentile_nearest_singleton() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(1), vec![]);
        let searcher = CompressedDAGSearcher::new(Rc::new(graph));
        assert_eq!(
            searcher.confidence_percentile_nearest(0.5),
            CompressedDAGNodeRef {
                segment: 0,
                index: 0
            }
        );
    }

    #[test]
    fn graph_confidence_percentile_nearest_single_segment() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(10), vec![]);
        let searcher = CompressedDAGSearcher::new(Rc::new(graph));
        assert_eq!(
            searcher.confidence_percentile_nearest(0.5),
            CompressedDAGNodeRef {
                segment: 0,
                index: 4
            }
        );
    }

    #[test]
    fn graph_confidence_percentile_nearest_parallel_segments() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(10), vec![]);
        graph.add_node(CompressedDAGSegment::new(10), vec![]);
        let searcher = CompressedDAGSearcher::new(Rc::new(graph));
        assert_eq!(
            searcher.confidence_percentile_nearest(0.5),
            CompressedDAGNodeRef {
                segment: 0,
                index: 9
            }
        );
    }

    #[test]
    fn graph_confidence_percentile_nearest_parallel_unequal_segments() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        graph.add_node(CompressedDAGSegment::new(10), vec![]);
        let searcher = CompressedDAGSearcher::new(Rc::new(graph));
        assert_eq!(
            searcher.confidence_percentile_nearest(0.5),
            CompressedDAGNodeRef {
                segment: 0,
                index: 54
            }
        );
    }

    #[test]
    fn graph_confidence_percentile_nearest_parallel_unequal_segments2() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(10), vec![]);
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        let searcher = CompressedDAGSearcher::new(Rc::new(graph));
        assert_eq!(
            searcher.confidence_percentile_nearest(0.5),
            CompressedDAGNodeRef {
                segment: 1,
                index: 54
            }
        );
    }

    #[test]
    fn graph_confidence_percentile_nearest_sequential_segments() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(10), vec![]);
        graph.add_node(CompressedDAGSegment::new(10), vec![0]);
        graph.add_node(CompressedDAGSegment::new(10), vec![1]);
        let searcher = CompressedDAGSearcher::new(Rc::new(graph));
        assert_eq!(
            searcher.confidence_percentile_nearest(0.5),
            CompressedDAGNodeRef {
                segment: 1,
                index: 4
            }
        );
    }

    #[test]
    fn graph_confidence_percentile_nearest_fork() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(10), vec![]);
        graph.add_node(CompressedDAGSegment::new(10), vec![0]);
        graph.add_node(CompressedDAGSegment::new(10), vec![0]);
        let searcher = CompressedDAGSearcher::new(Rc::new(graph));
        assert_eq!(
            searcher.confidence_percentile_nearest(0.5),
            CompressedDAGNodeRef {
                segment: 1,
                index: 4
            }
        );
    }

    #[test]
    fn graph_confidence_percentile_nearest_merge() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(10), vec![]);
        graph.add_node(CompressedDAGSegment::new(10), vec![]);
        graph.add_node(CompressedDAGSegment::new(10), vec![0, 1]);
        let searcher = CompressedDAGSearcher::new(Rc::new(graph));
        assert_eq!(
            searcher.confidence_percentile_nearest(0.5),
            CompressedDAGNodeRef {
                segment: 0,
                index: 9
            }
        );
    }

    macro_rules! assert_graph_index {
        ($searcher:expr, $next:expr, $best:expr, $heads:expr, $flakiness:expr) => {
            assert_eq!(
                $searcher.next_node(),
                CompressedDAGNodeRef {
                    segment: $next.0,
                    index: $next.1
                },
                "next_index"
            );
            assert_eq!(
                $searcher.best_node(),
                CompressedDAGNodeRef {
                    segment: $best.0,
                    index: $best.1
                },
                "best_index"
            );
            $searcher.report(
                CompressedDAGNodeRef {
                    segment: $next.0,
                    index: $next.1,
                },
                $heads,
                $flakiness,
            );
        };
    }

    #[test]
    fn graph_two_elements_zero() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(2), vec![]);
        let mut s = CompressedDAGSearcher::new(Rc::new(graph));
        assert_graph_index!(s, (0, 0), (0, 0), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 0), (0, 0), true, DEFAULT_FLAKINESS);
    }

    #[test]
    fn graph_two_elements_one() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(2), vec![]);
        let mut s = CompressedDAGSearcher::new(Rc::new(graph));
        assert_graph_index!(s, (0, 0), (0, 0), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 0), (0, 1), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 0), (0, 1), false, DEFAULT_FLAKINESS);
    }

    #[test]
    fn graph_many_elements_last() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(1024), vec![]);
        let mut s = CompressedDAGSearcher::new(Rc::new(graph));
        assert_graph_index!(s, (0, 511), (0, 511), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 750), (0, 751), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 878), (0, 878), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 946), (0, 946), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 982), (0, 982), false, DEFAULT_FLAKINESS);
    }

    #[test]
    fn graph_parallel_first_first() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        let mut s = CompressedDAGSearcher::new(Rc::new(graph));
        assert_graph_index!(s, (0, 99), (0, 99), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 52), (0, 53), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 27), (0, 28), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 14), (0, 14), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 7), (0, 7), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 3), (0, 4), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 1), (0, 2), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 0), (0, 1), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 0), (0, 0), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 0), (0, 0), true, DEFAULT_FLAKINESS);
    }

    #[test]
    fn graph_parallel_first_last() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        let mut s = CompressedDAGSearcher::new(Rc::new(graph));
        assert_graph_index!(s, (0, 99), (0, 99), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 52), (0, 53), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 77), (0, 78), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 90), (0, 91), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 97), (0, 98), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 68), (1, 69), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 99), (0, 99), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 98), (0, 98), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 99), (0, 99), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 98), (0, 99), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 99), (0, 99), false, DEFAULT_FLAKINESS);
    }

    #[test]
    fn graph_parallel_last_first() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        let mut s = CompressedDAGSearcher::new(Rc::new(graph));
        assert_graph_index!(s, (0, 99), (0, 99), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 52), (1, 53), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 27), (1, 28), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 14), (1, 14), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 7), (1, 7), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 3), (1, 4), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 1), (1, 2), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 0), (1, 1), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 0), (1, 0), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 0), (1, 0), true, DEFAULT_FLAKINESS);
    }

    #[test]
    fn graph_parallel_last_last() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        let mut s = CompressedDAGSearcher::new(Rc::new(graph));
        assert_graph_index!(s, (0, 99), (0, 99), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 52), (1, 53), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 77), (1, 78), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 90), (1, 91), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 97), (1, 98), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 68), (0, 69), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 99), (1, 99), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 98), (1, 98), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 99), (1, 99), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 98), (1, 99), false, DEFAULT_FLAKINESS);
    }

    #[test]
    fn graph_parallel_first_half() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        let mut s = CompressedDAGSearcher::new(Rc::new(graph));
        assert_graph_index!(s, (0, 99), (0, 99), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 52), (0, 53), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 27), (0, 28), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 40), (0, 41), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 47), (0, 48), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 51), (0, 51), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 49), (0, 49), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 50), (0, 51), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 49), (0, 50), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (0, 50), (0, 50), true, DEFAULT_FLAKINESS);
    }

    #[test]
    fn graph_parallel_second_half() {
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        let mut s = CompressedDAGSearcher::new(Rc::new(graph));
        assert_graph_index!(s, (0, 99), (0, 99), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 52), (1, 53), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 27), (1, 28), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 40), (1, 41), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 47), (1, 48), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 51), (1, 51), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 49), (1, 49), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 50), (1, 51), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 49), (1, 50), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (1, 50), (1, 50), true, DEFAULT_FLAKINESS);
    }

    #[test]
    fn graph_fork_join() {
        //      /-1-\
        // *-0-*     *-3-*
        //      \-2-/
        let mut graph = CompressedDAG::new();
        graph.add_node(CompressedDAGSegment::new(100), vec![]);
        graph.add_node(CompressedDAGSegment::new(100), vec![0]);
        graph.add_node(CompressedDAGSegment::new(100), vec![0]);
        graph.add_node(CompressedDAGSegment::new(100), vec![1, 2]);
        let mut s = CompressedDAGSearcher::new(Rc::new(graph));
        assert_graph_index!(s, (1, 99), (1, 99), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (2, 99), (2, 99), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (2, 49), (2, 50), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (2, 76), (2, 76), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (2, 62), (2, 62), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (2, 54), (2, 55), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (2, 50), (2, 50), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (2, 31), (2, 31), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (2, 49), (2, 49), false, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (2, 50), (2, 50), true, DEFAULT_FLAKINESS);
        assert_graph_index!(s, (2, 49), (2, 50), false, DEFAULT_FLAKINESS);
    }
}