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
use {
    crate::leader_slot_banking_stage_timing_metrics::*,
    solana_poh::poh_recorder::BankStart,
    solana_sdk::{clock::Slot, saturating_add_assign},
    std::time::Instant,
};

/// A summary of what happened to transactions passed to the execution pipeline.
/// Transactions can
/// 1) Did not even make it to execution due to being filtered out by things like AccountInUse
/// lock conflicts or CostModel compute limits. These types of errors are retryable and
/// counted in `Self::retryable_transaction_indexes`.
/// 2) Did not execute due to some fatal error like too old, or duplicate signature. These
/// will be dropped from the transactions queue and not counted in `Self::retryable_transaction_indexes`
/// 3) Were executed and committed, captured by `committed_transactions_count` below.
/// 4) Were executed and failed commit, captured by `failed_commit_count` below.
pub(crate) struct ProcessTransactionsSummary {
    // Returns true if we hit the end of the block/max PoH height for the block before
    // processing all the transactions in the batch.
    pub reached_max_poh_height: bool,

    // Total number of transactions that were passed as candidates for execution. See description
    // of struct above for possible outcomes for these transactions
    pub transactions_attempted_execution_count: usize,

    // Total number of transactions that made it into the block
    pub committed_transactions_count: usize,

    // Total number of transactions that made it into the block where the transactions
    // output from execution was success/no error.
    pub committed_transactions_with_successful_result_count: usize,

    // All transactions that were executed but then failed record because the
    // slot ended
    pub failed_commit_count: usize,

    // Indexes of transactions in the transactions slice that were not committed but are retryable
    pub retryable_transaction_indexes: Vec<usize>,

    // The number of transactions filtered out by the cost model
    pub cost_model_throttled_transactions_count: usize,

    // Total amount of time spent running the cost model
    pub cost_model_us: u64,

    // Breakdown of time spent executing and comitting transactions
    pub execute_and_commit_timings: LeaderExecuteAndCommitTimings,
}

// Metrics describing packets ingested/processed in various parts of BankingStage during this
// validator's leader slot
#[derive(Debug, Default)]
struct LeaderSlotPacketCountMetrics {
    // total number of live packets TPU received from verified receiver for processing.
    total_new_valid_packets: u64,

    // total number of packets TPU received from sigverify that failed signature verification.
    newly_failed_sigverify_count: u64,

    // total number of dropped packet due to the thread's buffered packets capacity being reached.
    exceeded_buffer_limit_dropped_packets_count: u64,

    // total number of packets that got added to the pending buffer after arriving to BankingStage
    newly_buffered_packets_count: u64,

    // total number of transactions in the buffer that were filtered out due to things like age and
    // duplicate signature checks
    retryable_packets_filtered_count: u64,

    // total number of transactions that attempted execution in this slot. Should equal the sum
    // of `committed_transactions_count`, `retryable_errored_transaction_count`, and
    // `nonretryable_errored_transactions_count`.
    transactions_attempted_execution_count: u64,

    // total number of transactions that were executed and committed into the block
    // on this thread
    committed_transactions_count: u64,

    // total number of transactions that were executed, got a successful execution output/no error,
    // and were then committed into the block
    committed_transactions_with_successful_result_count: u64,

    // total number of transactions that were not executed or failed commit, BUT were added back to the buffered
    // queue becaus they were retryable errors
    retryable_errored_transaction_count: u64,

    // total number of transactions that attempted execution due to some fatal error (too old, duplicate signature, etc.)
    // AND were dropped from the buffered queue
    nonretryable_errored_transactions_count: u64,

    // total number of transactions that were executed, but failed to be committed into the Poh stream because
    // the block ended. Some of these may be already counted in `nonretryable_errored_transactions_count` if they
    // then hit the age limit after failing to be comitted.
    executed_transactions_failed_commit_count: u64,

    // total number of transactions that were excluded from the block because they were too expensive
    // according to the cost model. These transactions are added back to the buffered queue and are
    // already counted in `self.retrayble_errored_transaction_count`.
    cost_model_throttled_transactions_count: u64,

    // total number of forwardsable packets that failed forwarding
    failed_forwarded_packets_count: u64,

    // total number of forwardsable packets that were successfully forwarded
    successful_forwarded_packets_count: u64,

    // total number of attempted forwards that failed. Note this is not a count of the number of packets
    // that failed, just the total number of batches of packets that failed forwarding
    packet_batch_forward_failure_count: u64,

    // total number of valid unprocessed packets in the buffer that were removed after being forwarded
    cleared_from_buffer_after_forward_count: u64,

    // total number of packets removed at the end of the slot due to being too old, duplicate, etc.
    end_of_slot_filtered_invalid_count: u64,
}

impl LeaderSlotPacketCountMetrics {
    fn new() -> Self {
        Self { ..Self::default() }
    }

    fn report(&self, id: u32, slot: Slot) {
        datapoint_info!(
            "banking_stage-leader_slot_packet_counts",
            ("id", id as i64, i64),
            ("slot", slot as i64, i64),
            (
                "total_new_valid_packets",
                self.total_new_valid_packets as i64,
                i64
            ),
            (
                "newly_failed_sigverify_count",
                self.newly_failed_sigverify_count as i64,
                i64
            ),
            (
                "exceeded_buffer_limit_dropped_packets_count",
                self.exceeded_buffer_limit_dropped_packets_count as i64,
                i64
            ),
            (
                "newly_buffered_packets_count",
                self.newly_buffered_packets_count as i64,
                i64
            ),
            (
                "retryable_packets_filtered_count",
                self.retryable_packets_filtered_count as i64,
                i64
            ),
            (
                "transactions_attempted_execution_count",
                self.transactions_attempted_execution_count as i64,
                i64
            ),
            (
                "committed_transactions_count",
                self.committed_transactions_count as i64,
                i64
            ),
            (
                "committed_transactions_with_successful_result_count",
                self.committed_transactions_with_successful_result_count as i64,
                i64
            ),
            (
                "retryable_errored_transaction_count",
                self.retryable_errored_transaction_count as i64,
                i64
            ),
            (
                "nonretryable_errored_transactions_count",
                self.nonretryable_errored_transactions_count as i64,
                i64
            ),
            (
                "executed_transactions_failed_commit_count",
                self.executed_transactions_failed_commit_count as i64,
                i64
            ),
            (
                "cost_model_throttled_transactions_count",
                self.cost_model_throttled_transactions_count as i64,
                i64
            ),
            (
                "failed_forwarded_packets_count",
                self.failed_forwarded_packets_count as i64,
                i64
            ),
            (
                "successful_forwarded_packets_count",
                self.successful_forwarded_packets_count as i64,
                i64
            ),
            (
                "packet_batch_forward_failure_count",
                self.packet_batch_forward_failure_count as i64,
                i64
            ),
            (
                "cleared_from_buffer_after_forward_count",
                self.cleared_from_buffer_after_forward_count as i64,
                i64
            ),
            (
                "end_of_slot_filtered_invalid_count",
                self.end_of_slot_filtered_invalid_count as i64,
                i64
            ),
        );
    }
}

#[derive(Debug)]
pub(crate) struct LeaderSlotMetrics {
    // banking_stage creates one QosService instance per working threads, that is uniquely
    // identified by id. This field allows to categorize metrics for gossip votes, TPU votes
    // and other transactions.
    id: u32,

    // aggregate metrics per slot
    slot: Slot,

    packet_count_metrics: LeaderSlotPacketCountMetrics,

    timing_metrics: LeaderSlotTimingMetrics,

    // Used by tests to check if the `self.report()` method was called
    is_reported: bool,
}

impl LeaderSlotMetrics {
    pub(crate) fn new(id: u32, slot: Slot, bank_creation_time: &Instant) -> Self {
        Self {
            id,
            slot,
            packet_count_metrics: LeaderSlotPacketCountMetrics::new(),
            timing_metrics: LeaderSlotTimingMetrics::new(bank_creation_time),
            is_reported: false,
        }
    }

    pub(crate) fn report(&mut self) {
        self.is_reported = true;

        self.timing_metrics.report(self.id, self.slot);
        self.packet_count_metrics.report(self.id, self.slot);
    }

    /// Returns `Some(self.slot)` if the metrics have been reported, otherwise returns None
    fn reported_slot(&self) -> Option<Slot> {
        if self.is_reported {
            Some(self.slot)
        } else {
            None
        }
    }
}

#[derive(Debug)]
pub struct LeaderSlotMetricsTracker {
    // Only `Some` if BankingStage detects it's time to construct our leader slot,
    // otherwise `None`
    leader_slot_metrics: Option<LeaderSlotMetrics>,
    id: u32,
}

impl LeaderSlotMetricsTracker {
    pub fn new(id: u32) -> Self {
        Self {
            leader_slot_metrics: None,
            id,
        }
    }

    // Returns reported slot if metrics were reported
    pub(crate) fn update_on_leader_slot_boundary(
        &mut self,
        bank_start: &Option<BankStart>,
    ) -> Option<Slot> {
        match (self.leader_slot_metrics.as_mut(), bank_start) {
            (None, None) => None,

            (Some(leader_slot_metrics), None) => {
                leader_slot_metrics.report();
                // Ensure tests catch that `report()` method was called
                let reported_slot = leader_slot_metrics.reported_slot();
                // Slot has ended, time to report metrics
                self.leader_slot_metrics = None;
                reported_slot
            }

            (None, Some(bank_start)) => {
                // Our leader slot has begain, time to create a new slot tracker
                self.leader_slot_metrics = Some(LeaderSlotMetrics::new(
                    self.id,
                    bank_start.working_bank.slot(),
                    &bank_start.bank_creation_time,
                ));
                self.leader_slot_metrics.as_ref().unwrap().reported_slot()
            }

            (Some(leader_slot_metrics), Some(bank_start)) => {
                if leader_slot_metrics.slot != bank_start.working_bank.slot() {
                    // Last slot has ended, new slot has began
                    leader_slot_metrics.report();
                    // Ensure tests catch that `report()` method was called
                    let reported_slot = leader_slot_metrics.reported_slot();
                    self.leader_slot_metrics = Some(LeaderSlotMetrics::new(
                        self.id,
                        bank_start.working_bank.slot(),
                        &bank_start.bank_creation_time,
                    ));
                    reported_slot
                } else {
                    leader_slot_metrics.reported_slot()
                }
            }
        }
    }

    pub(crate) fn accumulate_process_transactions_summary(
        &mut self,
        process_transactions_summary: &ProcessTransactionsSummary,
    ) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            let ProcessTransactionsSummary {
                transactions_attempted_execution_count,
                committed_transactions_count,
                committed_transactions_with_successful_result_count,
                failed_commit_count,
                ref retryable_transaction_indexes,
                cost_model_throttled_transactions_count,
                cost_model_us,
                ref execute_and_commit_timings,
                ..
            } = process_transactions_summary;

            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .transactions_attempted_execution_count,
                *transactions_attempted_execution_count as u64
            );

            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .committed_transactions_count,
                *committed_transactions_count as u64
            );

            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .committed_transactions_with_successful_result_count,
                *committed_transactions_with_successful_result_count as u64
            );

            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .executed_transactions_failed_commit_count,
                *failed_commit_count as u64
            );

            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .retryable_errored_transaction_count,
                retryable_transaction_indexes.len() as u64
            );

            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .nonretryable_errored_transactions_count,
                transactions_attempted_execution_count
                    .saturating_sub(*committed_transactions_count)
                    .saturating_sub(retryable_transaction_indexes.len()) as u64
            );

            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .cost_model_throttled_transactions_count,
                *cost_model_throttled_transactions_count as u64
            );

            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .process_packets_timings
                    .cost_model_us,
                *cost_model_us as u64
            );

            leader_slot_metrics
                .timing_metrics
                .execute_and_commit_timings
                .accumulate(execute_and_commit_timings);
        }
    }

    // Packet inflow/outflow/processing metrics
    pub(crate) fn increment_total_new_valid_packets(&mut self, count: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .total_new_valid_packets,
                count
            );
        }
    }

    pub(crate) fn increment_newly_failed_sigverify_count(&mut self, count: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .newly_failed_sigverify_count,
                count
            );
        }
    }

    pub(crate) fn increment_exceeded_buffer_limit_dropped_packets_count(&mut self, count: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .exceeded_buffer_limit_dropped_packets_count,
                count
            );
        }
    }

    pub(crate) fn increment_newly_buffered_packets_count(&mut self, count: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .newly_buffered_packets_count,
                count
            );
        }
    }

    pub(crate) fn increment_retryable_packets_filtered_count(&mut self, count: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .retryable_packets_filtered_count,
                count
            );
        }
    }

    pub(crate) fn increment_failed_forwarded_packets_count(&mut self, count: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .failed_forwarded_packets_count,
                count
            );
        }
    }

    pub(crate) fn increment_successful_forwarded_packets_count(&mut self, count: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .successful_forwarded_packets_count,
                count
            );
        }
    }

    pub(crate) fn increment_packet_batch_forward_failure_count(&mut self, count: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .packet_batch_forward_failure_count,
                count
            );
        }
    }

    pub(crate) fn increment_cleared_from_buffer_after_forward_count(&mut self, count: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .cleared_from_buffer_after_forward_count,
                count
            );
        }
    }

    pub(crate) fn increment_end_of_slot_filtered_invalid_count(&mut self, count: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .packet_count_metrics
                    .end_of_slot_filtered_invalid_count,
                count
            );
        }
    }

    // Outermost banking thread's loop timing metrics
    pub(crate) fn increment_process_buffered_packets_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .outer_loop_timings
                    .process_buffered_packets_us,
                us
            );
        }
    }

    pub(crate) fn increment_slot_metrics_check_slot_boundary_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .outer_loop_timings
                    .slot_metrics_check_slot_boundary_us,
                us
            );
        }
    }

    pub(crate) fn increment_receive_and_buffer_packets_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .outer_loop_timings
                    .receive_and_buffer_packets_us,
                us
            );
        }
    }

    // Processing buffer timing metrics
    pub(crate) fn increment_make_decision_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .process_buffered_packets_timings
                    .make_decision_us,
                us
            );
        }
    }

    pub(crate) fn increment_consume_buffered_packets_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .process_buffered_packets_timings
                    .consume_buffered_packets_us,
                us
            );
        }
    }

    pub(crate) fn increment_forward_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .process_buffered_packets_timings
                    .forward_us,
                us
            );
        }
    }

    pub(crate) fn increment_forward_and_hold_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .process_buffered_packets_timings
                    .forward_and_hold_us,
                us
            );
        }
    }

    // Consuming buffered packets timing metrics
    pub(crate) fn increment_end_of_slot_filtering_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .consume_buffered_packets_timings
                    .end_of_slot_filtering_us,
                us
            );
        }
    }

    pub(crate) fn increment_consume_buffered_packets_poh_recorder_lock_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .consume_buffered_packets_timings
                    .poh_recorder_lock_us,
                us
            );
        }
    }

    pub(crate) fn increment_process_packets_transactions_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .consume_buffered_packets_timings
                    .process_packets_transactions_us,
                us
            );
        }
    }

    // Processing packets timing metrics
    pub(crate) fn increment_transactions_from_packets_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .process_packets_timings
                    .transactions_from_packets_us,
                us
            );
        }
    }

    pub(crate) fn increment_process_transactions_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .process_packets_timings
                    .process_transactions_us,
                us
            );
        }
    }

    pub(crate) fn increment_filter_retryable_packets_us(&mut self, us: u64) {
        if let Some(leader_slot_metrics) = &mut self.leader_slot_metrics {
            saturating_add_assign!(
                leader_slot_metrics
                    .timing_metrics
                    .process_packets_timings
                    .filter_retryable_packets_us,
                us
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        solana_runtime::{bank::Bank, genesis_utils::create_genesis_config},
        solana_sdk::pubkey::Pubkey,
        std::sync::Arc,
    };

    struct TestSlotBoundaryComponents {
        first_bank: Arc<Bank>,
        first_poh_recorder_bank: BankStart,
        next_bank: Arc<Bank>,
        next_poh_recorder_bank: BankStart,
        leader_slot_metrics_tracker: LeaderSlotMetricsTracker,
    }

    fn setup_test_slot_boundary_banks() -> TestSlotBoundaryComponents {
        let genesis = create_genesis_config(10);
        let first_bank = Arc::new(Bank::new_for_tests(&genesis.genesis_config));
        let first_poh_recorder_bank = BankStart {
            working_bank: first_bank.clone(),
            bank_creation_time: Arc::new(Instant::now()),
        };

        // Create a child descended from the first bank
        let next_bank = Arc::new(Bank::new_from_parent(
            &first_bank,
            &Pubkey::new_unique(),
            first_bank.slot() + 1,
        ));
        let next_poh_recorder_bank = BankStart {
            working_bank: next_bank.clone(),
            bank_creation_time: Arc::new(Instant::now()),
        };

        let banking_stage_thread_id = 0;
        let leader_slot_metrics_tracker = LeaderSlotMetricsTracker::new(banking_stage_thread_id);

        TestSlotBoundaryComponents {
            first_bank,
            first_poh_recorder_bank,
            next_bank,
            next_poh_recorder_bank,
            leader_slot_metrics_tracker,
        }
    }

    #[test]
    pub fn test_update_on_leader_slot_boundary_not_leader_to_not_leader() {
        let TestSlotBoundaryComponents {
            mut leader_slot_metrics_tracker,
            ..
        } = setup_test_slot_boundary_banks();
        // Test that with no bank being tracked, and no new bank being tracked, nothing is reported
        assert!(leader_slot_metrics_tracker
            .update_on_leader_slot_boundary(&None)
            .is_none());
        assert!(leader_slot_metrics_tracker.leader_slot_metrics.is_none());
    }

    #[test]
    pub fn test_update_on_leader_slot_boundary_not_leader_to_leader() {
        let TestSlotBoundaryComponents {
            first_poh_recorder_bank,
            mut leader_slot_metrics_tracker,
            ..
        } = setup_test_slot_boundary_banks();

        // Test case where the thread has not detected a leader bank, and now sees a leader bank.
        // Metrics should not be reported because leader slot has not ended
        assert!(leader_slot_metrics_tracker.leader_slot_metrics.is_none());
        assert!(leader_slot_metrics_tracker
            .update_on_leader_slot_boundary(&Some(first_poh_recorder_bank))
            .is_none());
        assert!(leader_slot_metrics_tracker.leader_slot_metrics.is_some());
    }

    #[test]
    pub fn test_update_on_leader_slot_boundary_leader_to_not_leader() {
        let TestSlotBoundaryComponents {
            first_bank,
            first_poh_recorder_bank,
            mut leader_slot_metrics_tracker,
            ..
        } = setup_test_slot_boundary_banks();

        // Test case where the thread has a leader bank, and now detects there's no more leader bank,
        // implying the slot has ended. Metrics should be reported for `first_bank.slot()`,
        // because that leader slot has just ended.
        assert!(leader_slot_metrics_tracker
            .update_on_leader_slot_boundary(&Some(first_poh_recorder_bank))
            .is_none());
        assert_eq!(
            leader_slot_metrics_tracker
                .update_on_leader_slot_boundary(&None)
                .unwrap(),
            first_bank.slot()
        );
        assert!(leader_slot_metrics_tracker.leader_slot_metrics.is_none());
        assert!(leader_slot_metrics_tracker
            .update_on_leader_slot_boundary(&None)
            .is_none());
    }

    #[test]
    pub fn test_update_on_leader_slot_boundary_leader_to_leader_same_slot() {
        let TestSlotBoundaryComponents {
            first_bank,
            first_poh_recorder_bank,
            mut leader_slot_metrics_tracker,
            ..
        } = setup_test_slot_boundary_banks();

        // Test case where the thread has a leader bank, and now detects the same leader bank,
        // implying the slot is still running. Metrics should not be reported
        assert!(leader_slot_metrics_tracker
            .update_on_leader_slot_boundary(&Some(first_poh_recorder_bank.clone()))
            .is_none());
        assert!(leader_slot_metrics_tracker
            .update_on_leader_slot_boundary(&Some(first_poh_recorder_bank))
            .is_none());
        assert_eq!(
            leader_slot_metrics_tracker
                .update_on_leader_slot_boundary(&None)
                .unwrap(),
            first_bank.slot()
        );
        assert!(leader_slot_metrics_tracker.leader_slot_metrics.is_none());
    }

    #[test]
    pub fn test_update_on_leader_slot_boundary_leader_to_leader_bigger_slot() {
        let TestSlotBoundaryComponents {
            first_bank,
            first_poh_recorder_bank,
            next_bank,
            next_poh_recorder_bank,
            mut leader_slot_metrics_tracker,
        } = setup_test_slot_boundary_banks();

        // Test case where the thread has a leader bank, and now detects there's a new leader bank
        // for a bigger slot, implying the slot has ended. Metrics should be reported for the
        // smaller slot
        assert!(leader_slot_metrics_tracker
            .update_on_leader_slot_boundary(&Some(first_poh_recorder_bank))
            .is_none());
        assert_eq!(
            leader_slot_metrics_tracker
                .update_on_leader_slot_boundary(&Some(next_poh_recorder_bank))
                .unwrap(),
            first_bank.slot()
        );
        assert_eq!(
            leader_slot_metrics_tracker
                .update_on_leader_slot_boundary(&None)
                .unwrap(),
            next_bank.slot()
        );
        assert!(leader_slot_metrics_tracker.leader_slot_metrics.is_none());
    }

    #[test]
    pub fn test_update_on_leader_slot_boundary_leader_to_leader_smaller_slot() {
        let TestSlotBoundaryComponents {
            first_bank,
            first_poh_recorder_bank,
            next_bank,
            next_poh_recorder_bank,
            mut leader_slot_metrics_tracker,
        } = setup_test_slot_boundary_banks();
        // Test case where the thread has a leader bank, and now detects there's a new leader bank
        // for a samller slot, implying the slot has ended. Metrics should be reported for the
        // bigger slot
        assert!(leader_slot_metrics_tracker
            .update_on_leader_slot_boundary(&Some(next_poh_recorder_bank))
            .is_none());
        assert_eq!(
            leader_slot_metrics_tracker
                .update_on_leader_slot_boundary(&Some(first_poh_recorder_bank))
                .unwrap(),
            next_bank.slot()
        );
        assert_eq!(
            leader_slot_metrics_tracker
                .update_on_leader_slot_boundary(&None)
                .unwrap(),
            first_bank.slot()
        );
        assert!(leader_slot_metrics_tracker.leader_slot_metrics.is_none());
    }
}