tape-core 0.4.7

A decentralized object store using Solana.
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
//! What one owner remembers about a peer's answers.
//!
//! Local and private, never anything the network agrees on. A missing answer is
//! a local miss, not proof of failure, so only a sustained pattern means
//! anything. Never reset at a boundary, or a rule could never fire across one.
//!
//! Outcomes arrive out of round order, since a certificate folds when it forms
//! and a miss folds when the next round opens. A late certificate replaces a
//! recorded miss, which the paper requires. Nothing replaces a success.

use serde::{Deserialize, Serialize};

#[cfg(feature = "wincode")]
use wincode_derive::{SchemaRead, SchemaWrite};

use super::EvictionPolicy;
use crate::types::{BasisPoints, EpochNumber, RoundNumber};

/// What folding one outcome did to the record.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Fold {
    /// Nothing new: the outcome repeats what is recorded, or a success stands.
    Ignored,
    /// Folded in round order, counters and recency both updated here.
    Advanced,
    /// Counted, but the recency fields must be rebuilt from the stored rounds.
    Rebuild,
}

/// One peer's challenge history, as step 5 of the mechanism keeps it.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "wincode", derive(SchemaRead, SchemaWrite))]
pub struct PeerRecord {
    /// Rounds this peer was challenged in and an answer was expected.
    pub opportunities: u64,
    /// Rounds it answered with a valid proof.
    pub successes: u64,
    /// Misses since its last success.
    pub consecutive_misses: u64,
    /// Epoch of the newest outcome folded in.
    pub last_epoch: EpochNumber,
    /// Round of the newest outcome folded in.
    pub last_round: RoundNumber,
    /// Whether any outcome has been folded in at all.
    pub started: bool,
    /// The most recent judged rounds, newest in the low bit, set for a success.
    ///
    /// One row of the challenge record grid: rounds across, spools down. Only
    /// rounds this peer was actually judged in take a bit, so a void round leaves
    /// the strip alone rather than reading as a miss against everyone.
    pub recent: u64,
    /// Bits of `recent` that stand for a round, rather than for nothing yet.
    ///
    /// Not `opportunities`: that counts every round for the peer's whole life,
    /// while a rebuild can only see the rounds the store still holds. Reading the
    /// strip off the lifetime count draws the pruned ones as misses.
    pub recent_len: u64,
}

/// Judged rounds the recent strip remembers.
pub const RECENT_ROUNDS: u32 = u64::BITS;

impl PeerRecord {
    /// Fold in one round's outcome, given what is already recorded for it.
    ///
    /// `prior` is the outcome the caller has stored for this exact round, so a
    /// repeat never counts twice and a peer cannot be talked into an eviction by
    /// repetition alone. A success is never downgraded. A recorded miss is
    /// upgraded when its certificate arrives late. A fold behind the newest
    /// round still counts, but the caller must rebuild recency from the stored
    /// rounds, since only they know the order.
    pub fn record(
        &mut self,
        epoch: EpochNumber,
        round: RoundNumber,
        proved: bool,
        prior: Option<bool>,
    ) -> Fold {
        match prior {
            Some(true) => return Fold::Ignored,
            Some(false) if !proved => return Fold::Ignored,
            Some(false) => {
                self.successes += 1;
                return Fold::Rebuild;
            }
            None => {}
        }

        self.opportunities += 1;
        if proved {
            self.successes += 1;
        }

        if self.started && (epoch, round) <= (self.last_epoch, self.last_round) {
            return Fold::Rebuild;
        }

        if proved {
            self.consecutive_misses = 0;
        } else {
            self.consecutive_misses += 1;
        }
        self.recent = (self.recent << 1) | u64::from(proved);
        self.recent_len = (self.recent_len + 1).min(RECENT_ROUNDS as u64);
        self.last_epoch = epoch;
        self.last_round = round;
        self.started = true;
        Fold::Advanced
    }

    /// Re-derive the order-sensitive fields from the rounds as stored.
    ///
    /// `rounds` is the retained tail, oldest first. `preceding_misses` preserves
    /// the known streak before that tail when older outcomes have been pruned.
    /// The 64-bit display strip does not bound the eviction evidence.
    pub fn rebuild_recency(
        &mut self,
        rounds: &[(EpochNumber, RoundNumber, bool)],
        preceding_misses: u64,
    ) {
        let trailing_misses = rounds
            .iter()
            .rev()
            .take_while(|(_, _, proved)| !proved)
            .count() as u64;
        self.consecutive_misses = trailing_misses
            + if trailing_misses == rounds.len() as u64 {
                preceding_misses
            } else {
                0
            };

        self.recent = 0;
        let tail = rounds.len().saturating_sub(RECENT_ROUNDS as usize);
        for (_, _, proved) in &rounds[tail..] {
            self.recent = (self.recent << 1) | u64::from(*proved);
        }
        self.recent_len = (rounds.len() - tail) as u64;

        if let Some((epoch, round, _)) = rounds.last() {
            self.last_epoch = *epoch;
            self.last_round = *round;
            self.started = true;
        }
    }

    /// Share of opportunities the peer answered, in basis points.
    ///
    /// A peer never asked reads as a full rate, so a fresh record never trips the
    /// rate arm before it has been asked anything.
    pub fn success_rate(&self) -> BasisPoints {
        if self.opportunities == 0 {
            return BasisPoints(BasisPoints::MAX);
        }
        BasisPoints(self.successes * BasisPoints::MAX / self.opportunities)
    }

    /// Whether a run of consecutive misses has reached the fast arm.
    ///
    /// This arm makes a claim about reachability: the peer has stopped answering.
    /// It is the one a live probe can speak to, and the record cannot check it
    /// for itself, since a run only grows while the peer is being judged and
    /// clearing it needs a success the peer has no chance to earn once the rounds
    /// have stopped.
    pub fn run_fires(&self, policy: &EvictionPolicy) -> bool {
        self.consecutive_misses >= policy.max_consecutive_misses
    }

    /// Whether the lifetime rate has fallen through the floor.
    ///
    /// This arm makes no claim about reachability. A peer answering every round
    /// with an invalid proof trips it while staying perfectly reachable, so no
    /// amount of answering a probe clears it.
    pub fn rate_fires(&self, policy: &EvictionPolicy) -> bool {
        self.opportunities >= policy.min_opportunities
            && self.success_rate() < policy.minimum_success_rate_bps
    }

    /// Whether this history is enough to propose an eviction.
    ///
    /// Two arms, both from the paper's repeated-local-misses rule: a run of
    /// consecutive misses catches a node that stopped answering, and a rate floor
    /// over enough opportunities catches one that answers erratically.
    pub fn eviction_fires(&self, policy: &EvictionPolicy) -> bool {
        self.run_fires(policy) || self.rate_fires(policy)
    }

    /// The recent strip oldest-first, for drawing one row of the grid.
    ///
    /// Only the rounds still remembered, so a fresh peer reads as a short row
    /// rather than a wall of misses, and so does one whose older rounds have
    /// been pruned out from under a rebuild.
    pub fn recent_rounds(&self) -> Vec<bool> {
        let judged = self.recent_len.min(RECENT_ROUNDS as u64) as u32;
        (0..judged)
            .rev()
            .map(|bit| self.recent & (1 << bit) != 0)
            .collect()
    }
}

/// What a node's spools say about it, as one answer.
///
/// The record is per spool but a proposal is against the node, so the arms are
/// read across every spool it answers for. Kept here rather than at each caller:
/// the eviction judge, the observe board and the dashboard were each deriving
/// their own, and had already drifted apart.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NodeVerdict {
    /// No spool has been judged enough times to mean anything.
    Unproven,
    /// A spool's lifetime rate is through the floor. It says nothing about
    /// reachability, so answering a probe cannot clear it.
    RateFailed,
    /// A spool has stopped answering. A live probe can clear it.
    RunFailed,
    /// Nothing has fired.
    Healthy,
}

/// Judge a node on every spool it still answers for.
///
/// The rate arm outranks the run arm because only the run arm makes a claim a
/// probe can settle, so a node failing both is not let off by answering.
pub fn node_verdict<'a>(
    records: impl IntoIterator<Item = &'a PeerRecord>,
    policy: &EvictionPolicy,
) -> NodeVerdict {
    let mut judged = 0;
    let mut rate = false;
    let mut run = false;
    for record in records {
        judged = judged.max(record.opportunities);
        rate |= record.rate_fires(policy);
        run |= record.run_fires(policy);
    }

    if rate {
        NodeVerdict::RateFailed
    } else if run {
        NodeVerdict::RunFailed
    } else if judged < policy.min_opportunities {
        NodeVerdict::Unproven
    } else {
        NodeVerdict::Healthy
    }
}

/// A node's spools counted together, for reporting rather than for judging.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NodeTally {
    /// Spools this node keeps a record for.
    pub spools: u64,
    /// Rounds judged, summed over them.
    pub opportunities: u64,
    /// Rounds answered, summed the same way.
    pub successes: u64,
    /// The longest run any one spool is on, which is the one that would fire.
    pub worst_run: u64,
}

impl NodeTally {
    /// Answered over judged, pooled across the spools.
    ///
    /// For display only. No arm of the rule reads a pooled rate: a node failing
    /// one spool of five still shows four fifths here while `node_verdict` has
    /// already failed it.
    pub fn rate(&self) -> BasisPoints {
        if self.opportunities == 0 {
            return BasisPoints(BasisPoints::MAX);
        }
        BasisPoints(self.successes * BasisPoints::MAX / self.opportunities)
    }
}

/// Count a node's spools together.
pub fn node_tally<'a>(records: impl IntoIterator<Item = &'a PeerRecord>) -> NodeTally {
    let mut tally = NodeTally::default();
    for record in records {
        tally.spools += 1;
        tally.opportunities += record.opportunities;
        tally.successes += record.successes;
        tally.worst_run = tally.worst_run.max(record.consecutive_misses);
    }
    tally
}

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

    const POLICY: EvictionPolicy = EvictionPolicy {
        max_consecutive_misses: 20,
        min_opportunities: 4,
        minimum_success_rate_bps: BasisPoints(5_000),
    };

    #[test]
    fn policies_are_independent_and_do_not_need_initialization() {
        let record = spool(10, 7, 3);
        let sensitive = EvictionPolicy {
            max_consecutive_misses: 3,
            ..POLICY
        };

        for _ in 0..3 {
            assert_eq!(node_verdict(&[record], &POLICY), NodeVerdict::Healthy);
            assert_eq!(node_verdict(&[record], &sensitive), NodeVerdict::RunFailed);
        }
    }

    #[test]
    fn minimum_rate_sample_does_not_override_the_consecutive_miss_rule() {
        let policy = EvictionPolicy {
            max_consecutive_misses: 30,
            min_opportunities: 60,
            ..POLICY
        };
        let record = spool(30, 0, 30);
        assert!(record.eviction_fires(&policy));
        assert!(!record.rate_fires(&policy));
        assert_eq!(node_verdict(&[record], &policy), NodeVerdict::RunFailed);
    }

    #[test]
    fn rate_rule_waits_for_its_configured_evidence() {
        let policy = EvictionPolicy {
            min_opportunities: 60,
            ..POLICY
        };
        assert!(!spool(59, 10, 1).rate_fires(&policy));
        assert!(spool(60, 10, 1).rate_fires(&policy));
        assert!(!spool(60, 30, 1).rate_fires(&policy));
    }

    fn spool(opportunities: u64, successes: u64, run: u64) -> PeerRecord {
        PeerRecord {
            opportunities,
            successes,
            consecutive_misses: run,
            ..PeerRecord::default()
        }
    }

    #[test]
    fn one_dead_spool_fails_the_node() {
        let healthy = spool(20, 20, 0);
        let dead = spool(20, 0, POLICY.max_consecutive_misses);
        let records = [healthy, healthy, healthy, healthy, dead];

        assert_eq!(node_verdict(&records, &POLICY), NodeVerdict::RateFailed);

        // The pooled rate the board shows is comfortably above the floor, which
        // is why it must never be what the rule reads.
        let tally = node_tally(&records);
        assert_eq!(tally.spools, 5);
        assert!(tally.rate() > POLICY.minimum_success_rate_bps);
        assert_eq!(tally.worst_run, POLICY.max_consecutive_misses);
    }

    #[test]
    fn rate_outranks_run() {
        let both = spool(POLICY.min_opportunities, 0, POLICY.max_consecutive_misses);
        assert!(both.rate_fires(&POLICY) && both.run_fires(&POLICY));
        assert_eq!(node_verdict(&[both], &POLICY), NodeVerdict::RateFailed);
    }

    #[test]
    fn too_few_rounds_is_unproven() {
        let short = spool(
            POLICY.min_opportunities - 1,
            0,
            POLICY.min_opportunities - 1,
        );
        assert!(
            !short.rate_fires(&POLICY),
            "too few rounds for the rate arm"
        );
        assert!(!short.run_fires(&POLICY), "too few rounds to be a run");
        assert_eq!(node_verdict(&[short], &POLICY), NodeVerdict::Unproven);
    }

    #[test]
    fn a_long_run_fails_the_node() {
        let stalled = spool(
            POLICY.min_opportunities + 4,
            POLICY.min_opportunities + 1,
            POLICY.max_consecutive_misses,
        );
        assert!(!stalled.rate_fires(&POLICY));
        assert_eq!(node_verdict(&[stalled], &POLICY), NodeVerdict::RunFailed);
    }

    #[test]
    fn no_records_is_unproven() {
        assert_eq!(node_verdict(&[], &POLICY), NodeVerdict::Unproven);
        assert_eq!(node_tally(&[]).rate(), BasisPoints(BasisPoints::MAX));
    }

    #[test]
    fn every_spool_answering_is_healthy() {
        let good = spool(
            POLICY.min_opportunities + 2,
            POLICY.min_opportunities + 2,
            0,
        );
        assert_eq!(
            node_verdict(&[good, good, good], &POLICY),
            NodeVerdict::Healthy
        );
    }

    fn at(round: u64) -> (EpochNumber, RoundNumber) {
        (EpochNumber(1), RoundNumber(round))
    }

    #[test]
    fn fresh_record() {
        let record = PeerRecord::default();
        assert!(!record.eviction_fires(&POLICY));
        assert_eq!(record.success_rate(), BasisPoints(BasisPoints::MAX));
    }

    #[test]
    fn always_answers() {
        let mut record = PeerRecord::default();
        for round in 0..500 {
            let (epoch, round) = at(round);
            assert_eq!(record.record(epoch, round, true, None), Fold::Advanced);
        }
        assert_eq!(record.success_rate(), BasisPoints(BasisPoints::MAX));
        assert!(!record.eviction_fires(&POLICY));
    }

    #[test]
    fn run_of_misses() {
        let mut record = PeerRecord::default();
        for round in 0..100 {
            record.record(EpochNumber(1), RoundNumber(round), true, None);
        }
        for round in 100..100 + POLICY.max_consecutive_misses {
            record.record(EpochNumber(1), RoundNumber(round), false, None);
        }

        assert!(record.success_rate() > POLICY.minimum_success_rate_bps);
        assert!(record.eviction_fires(&POLICY));
    }

    #[test]
    fn single_miss() {
        let mut record = PeerRecord::default();
        for round in 0..10 {
            record.record(EpochNumber(1), RoundNumber(round), round != 5, None);
        }
        assert!(!record.eviction_fires(&POLICY));
    }

    #[test]
    fn erratic_peer() {
        let mut record = PeerRecord::default();
        for round in 0..40 {
            record.record(EpochNumber(1), RoundNumber(round), round % 2 == 0, None);
        }
        assert_eq!(record.consecutive_misses, 1);
        assert_eq!(record.success_rate(), BasisPoints(5_000));
        assert!(!record.eviction_fires(&POLICY));

        // One more miss tips it under the floor.
        record.record(EpochNumber(1), RoundNumber(40), false, None);
        assert!(record.success_rate() < POLICY.minimum_success_rate_bps);
        assert!(record.eviction_fires(&POLICY));
    }

    #[test]
    fn recent_strip() {
        let mut record = PeerRecord::default();
        assert!(record.recent_rounds().is_empty());

        for (round, proved) in [true, true, false, true].into_iter().enumerate() {
            record.record(EpochNumber(1), RoundNumber(round as u64), proved, None);
        }
        assert_eq!(record.recent_rounds(), vec![true, true, false, true]);
    }

    #[test]
    fn strip_ages_out() {
        let mut record = PeerRecord::default();
        for round in 0..(RECENT_ROUNDS as u64 + 10) {
            // Miss only the very first round, which falls off the end.
            record.record(EpochNumber(1), RoundNumber(round), round != 0, None);
        }

        let strip = record.recent_rounds();
        assert_eq!(strip.len(), RECENT_ROUNDS as usize);
        assert!(
            strip.iter().all(|proved| *proved),
            "an aged-out miss lingered"
        );
        assert_eq!(record.opportunities, RECENT_ROUNDS as u64 + 10);
    }

    #[test]
    fn strip_survives_pruned_rounds() {
        let mut record = PeerRecord::default();
        for round in 0..5 {
            record.record(EpochNumber(1), RoundNumber(round), true, None);
        }

        // A late outcome behind the newest round, with everything before epoch 2
        // already swept out of the round store.
        let fold = record.record(EpochNumber(1), RoundNumber(4), true, None);
        assert_eq!(fold, Fold::Rebuild);
        record.rebuild_recency(&[at_round(2, 0, true), at_round(2, 1, true)], 0);

        assert_eq!(record.opportunities, 6);
        assert_eq!(record.recent_rounds(), vec![true, true]);
    }

    fn at_round(epoch: u64, round: u64, proved: bool) -> (EpochNumber, RoundNumber, bool) {
        (EpochNumber(epoch), RoundNumber(round), proved)
    }

    fn run(pattern: &[bool], rounds: u64) -> PeerRecord {
        let mut record = PeerRecord::default();
        for round in 0..rounds {
            let answered = pattern[(round as usize) % pattern.len()];
            record.record(EpochNumber(1), RoundNumber(round), answered, None);
        }
        record
    }

    #[test]
    fn stops_partway() {
        let mut record = run(&[true], 40);
        assert!(!record.eviction_fires(&POLICY));

        let last = 40 + POLICY.max_consecutive_misses - 1;
        for round in 40..last {
            record.record(EpochNumber(1), RoundNumber(round), false, None);
            assert!(
                !record.eviction_fires(&POLICY),
                "fired after {} misses",
                round - 39
            );
        }
        record.record(EpochNumber(1), RoundNumber(last), false, None);
        assert!(
            record.eviction_fires(&POLICY),
            "a full run of misses should fire"
        );
    }

    #[test]
    fn flapping_survives() {
        let record = run(&[true, false], 400);

        assert_eq!(record.consecutive_misses, 1);
        assert_eq!(record.success_rate(), POLICY.minimum_success_rate_bps);
        assert!(!record.eviction_fires(&POLICY));
    }

    #[test]
    fn arms_apart() {
        let mut stopped = run(&[true], 40);
        for round in 40..40 + POLICY.max_consecutive_misses {
            stopped.record(EpochNumber(1), RoundNumber(round), false, None);
        }
        assert!(stopped.run_fires(&POLICY));
        assert!(
            !stopped.rate_fires(&POLICY),
            "a stopped peer's lifetime rate is still good"
        );

        let erratic = run(&[true, false, false], 60);
        assert!(
            !erratic.run_fires(&POLICY),
            "one answer in three never reaches a full run"
        );
        assert!(erratic.rate_fires(&POLICY));
    }

    #[test]
    fn under_half() {
        let record = run(&[true, false, false], 60);

        assert!(record.consecutive_misses < POLICY.max_consecutive_misses);
        assert!(record.success_rate() < POLICY.minimum_success_rate_bps);
        assert!(record.eviction_fires(&POLICY));
    }

    #[test]
    fn recovers() {
        let mut record = run(&[true], 20);
        record.record(EpochNumber(1), RoundNumber(20), false, None);
        record.record(EpochNumber(1), RoundNumber(21), false, None);
        record.record(EpochNumber(1), RoundNumber(22), true, None);

        assert_eq!(record.consecutive_misses, 0);
        assert!(!record.eviction_fires(&POLICY));
    }

    #[test]
    fn resets_the_run() {
        let record = run(&[true, false, false], 300);
        assert!(record.eviction_fires(&POLICY));
    }

    #[test]
    fn replayed_round() {
        let mut record = PeerRecord::default();
        assert_eq!(
            record.record(EpochNumber(1), RoundNumber(7), false, None),
            Fold::Advanced
        );
        assert_eq!(
            record.record(EpochNumber(1), RoundNumber(7), false, Some(false)),
            Fold::Ignored
        );

        assert_eq!(record.opportunities, 1);
        assert_eq!(record.consecutive_misses, 1);
    }

    #[test]
    fn success_stands() {
        let mut record = PeerRecord::default();
        record.record(EpochNumber(1), RoundNumber(7), true, None);
        assert_eq!(
            record.record(EpochNumber(1), RoundNumber(7), false, Some(true)),
            Fold::Ignored
        );

        assert_eq!(record.opportunities, 1);
        assert_eq!(record.successes, 1);
        assert_eq!(record.consecutive_misses, 0);
    }

    #[test]
    fn late_certificate() {
        let mut record = PeerRecord::default();
        record.record(EpochNumber(1), RoundNumber(7), false, None);
        record.record(EpochNumber(1), RoundNumber(8), false, None);
        assert_eq!(record.consecutive_misses, 2);

        assert_eq!(
            record.record(EpochNumber(1), RoundNumber(7), true, Some(false)),
            Fold::Rebuild
        );
        record.rebuild_recency(
            &[
                (EpochNumber(1), RoundNumber(7), true),
                (EpochNumber(1), RoundNumber(8), false),
            ],
            0,
        );

        assert_eq!(record.opportunities, 2);
        assert_eq!(record.successes, 1);
        assert_eq!(record.consecutive_misses, 1);
        assert_eq!(record.recent_rounds(), vec![true, false]);
    }

    #[test]
    fn late_miss() {
        let mut record = PeerRecord::default();
        record.record(EpochNumber(1), RoundNumber(8), true, None);

        assert_eq!(
            record.record(EpochNumber(1), RoundNumber(7), false, None),
            Fold::Rebuild
        );
        record.rebuild_recency(
            &[
                (EpochNumber(1), RoundNumber(7), false),
                (EpochNumber(1), RoundNumber(8), true),
            ],
            0,
        );

        assert_eq!(record.opportunities, 2);
        assert_eq!(record.successes, 1);
        assert_eq!(
            record.consecutive_misses, 0,
            "a later success already broke the run"
        );
        assert_eq!(record.recent_rounds(), vec![false, true]);
    }

    #[test]
    fn rebuild_matches() {
        let rounds: Vec<(EpochNumber, RoundNumber, bool)> = (0..100)
            .map(|round| (EpochNumber(1), RoundNumber(round), round % 3 != 0))
            .collect();

        let mut folded = PeerRecord::default();
        for (epoch, round, proved) in &rounds {
            folded.record(*epoch, *round, *proved, None);
        }

        let mut rebuilt = folded;
        rebuilt.rebuild_recency(&rounds, 0);

        assert_eq!(rebuilt, folded);
    }

    #[test]
    fn across_epochs() {
        let mut record = PeerRecord::default();
        record.record(EpochNumber(1), RoundNumber(9), false, None);
        for round in 0..POLICY.max_consecutive_misses - 1 {
            record.record(EpochNumber(2), RoundNumber(round), false, None);
        }

        assert_eq!(record.consecutive_misses, POLICY.max_consecutive_misses);
        assert!(record.eviction_fires(&POLICY));
    }
}