commonware-consensus 2026.5.0

Order opaque messages in a Byzantine environment.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
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
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
use super::Variant;
use crate::{
    marshal::{
        ancestry::{AncestorStream, Ancestry, BlockProvider},
        Identifier,
    },
    simplex::types::{Activity, Finalization, Notarization},
    types::{Height, Round},
    Reporter,
};
use commonware_actor::{
    mailbox::{Overflow, Policy, Sender},
    Feedback,
};
use commonware_cryptography::{certificate::Scheme, Digestible};
use commonware_p2p::Recipients;
use commonware_runtime::{telemetry::metrics::histogram::Timed, Clock};
use commonware_utils::{channel::oneshot, vec::NonEmptyVec};
use std::{
    collections::{btree_map::Entry, BTreeMap, VecDeque},
    sync::Arc,
};

/// Messages sent to the marshal [Actor](super::Actor).
///
/// These messages are sent from the consensus engine and other parts of the
/// system to drive the state of the marshal.
pub(crate) enum Message<S: Scheme, V: Variant> {
    /// A request to retrieve the `(height, digest)` of a block by its identifier.
    /// The block must be finalized; returns `None` if the block is not finalized.
    GetInfo {
        /// The identifier of the block to get the information of.
        identifier: Identifier<<V::Block as Digestible>::Digest>,
        /// A channel to send the retrieved `(height, digest)`.
        response: oneshot::Sender<Option<(Height, <V::Block as Digestible>::Digest)>>,
    },
    /// A request to retrieve a block by its identifier.
    ///
    /// Requesting by [Identifier::Height] or [Identifier::Latest] will only return finalized
    /// blocks, whereas requesting by [Identifier::Digest] may return non-finalized
    /// or even unverified blocks.
    GetBlock {
        /// The identifier of the block to retrieve.
        identifier: Identifier<<V::Block as Digestible>::Digest>,
        /// A channel to send the retrieved block.
        response: oneshot::Sender<Option<V::Block>>,
    },
    /// A request to retrieve a finalization by height.
    GetFinalization {
        /// The height of the finalization to retrieve.
        height: Height,
        /// A channel to send the retrieved finalization.
        response: oneshot::Sender<Option<Finalization<S, V::Commitment>>>,
    },
    /// A request to retrieve the latest processed height.
    GetProcessedHeight {
        /// A channel to send the latest processed height.
        response: oneshot::Sender<Option<Height>>,
    },
    /// A hint that a finalized block may be available at a given height.
    ///
    /// This triggers a network fetch if the finalization is not available locally.
    /// This is fire-and-forget: the finalization will be stored in marshal and
    /// delivered via the normal finalization flow when available.
    ///
    /// The height must be covered by both the epocher and the provider. If the
    /// epocher cannot map the height to an epoch, or the provider cannot supply
    /// a scheme for that epoch, the hint is silently dropped.
    ///
    /// Targets are required because this is typically called when a peer claims to
    /// be ahead. If a target returns invalid data, the resolver will block them.
    /// Sending this message multiple times with different targets adds to the
    /// target set.
    HintFinalized {
        /// The height of the finalization to fetch.
        height: Height,
        /// Target peers to fetch from. Added to any existing targets for this height.
        targets: NonEmptyVec<S::PublicKey>,
    },
    /// A request to subscribe to a block by its digest.
    SubscribeByDigest {
        /// The digest of the block to retrieve.
        digest: <V::Block as Digestible>::Digest,
        /// How marshal should behave if the block is missing locally.
        fallback: DigestFallback,
        /// A channel to send the retrieved block.
        response: oneshot::Sender<V::Block>,
    },
    /// A request to subscribe to a block by its commitment.
    SubscribeByCommitment {
        /// The commitment of the block to retrieve.
        commitment: V::Commitment,
        /// How marshal should behave if the block is missing locally.
        fallback: CommitmentFallback,
        /// A channel to send the retrieved block.
        response: oneshot::Sender<V::Block>,
    },
    /// A hint to fetch a notarized block by round without adding another local subscriber.
    ///
    /// `commitment` is used as a locality check: if the block is already
    /// available locally, the fetch is skipped.
    HintNotarized {
        /// The notarized round to request.
        round: Round,
        /// The commitment used to short-circuit if the block is already local.
        commitment: V::Commitment,
    },
    /// A request to retrieve the verified block previously persisted for `round`.
    GetVerified {
        /// The round to query.
        round: Round,
        /// A channel to send the retrieved block, if any.
        response: oneshot::Sender<Option<V::Block>>,
    },
    /// A request to forward a block to a set of recipients.
    Forward {
        /// The round in which the block was proposed.
        round: Round,
        /// The commitment of the block to forward.
        commitment: V::Commitment,
        /// The recipients to forward the block to.
        recipients: Recipients<S::PublicKey>,
    },
    /// A notification that a block has been locally proposed by this node.
    Proposed {
        /// The round in which the block was proposed.
        round: Round,
        /// The proposed block.
        block: V::Block,
        /// A channel signaled once the block is durably stored.
        ack: Option<oneshot::Sender<()>>,
    },
    /// A notification that a block has been verified by the application.
    Verified {
        /// The round in which the block was verified.
        round: Round,
        /// The verified block.
        block: V::Block,
        /// A channel signaled once the block is durably stored.
        ack: Option<oneshot::Sender<()>>,
    },
    /// A notification that a block has been certified by the application.
    Certified {
        /// The round in which the block was certified.
        round: Round,
        /// The certified block.
        block: V::Block,
        /// A channel signaled once the block is durably stored.
        ack: Option<oneshot::Sender<()>>,
    },
    /// Attempts to set the sync starting point from a finalized commitment.
    ///
    /// If the verified finalization advances marshal's current floor, marshal
    /// anchors on its block, prunes below it, then syncs and delivers blocks
    /// starting at the floor height. Stale or superseded floors may be ignored.
    ///
    /// To prune data without changing the sync starting point, use
    /// [Message::Prune] instead.
    SetFloor {
        /// The candidate floor finalization, verified by the actor before use.
        finalization: Finalization<S, V::Commitment>,
    },
    /// Requests pruning finalized blocks and certificates below the given height.
    ///
    /// Unlike [Message::SetFloor], this does not affect the sync starting
    /// point. Requests above marshal's current floor are ignored.
    Prune {
        /// The minimum height to keep (blocks below this are pruned).
        height: Height,
    },
    /// A notarization from the consensus engine.
    Notarization {
        /// The notarization.
        notarization: Notarization<S, V::Commitment>,
    },
    /// A finalization from the consensus engine.
    Finalization {
        /// The finalization.
        finalization: Finalization<S, V::Commitment>,
    },
}

/// How a digest-keyed block subscription should behave when the block is missing locally.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DigestFallback {
    /// Wait for local availability only.
    Wait,
    /// Request the notarized proposal for `round` from peers.
    ///
    /// Use this only when the caller has a trusted round for the digest. Digest-keyed
    /// subscriptions intentionally cannot request exact commitment fetches.
    FetchByRound { round: Round },
}

impl From<DigestFallback> for CommitmentFallback {
    fn from(fallback: DigestFallback) -> Self {
        match fallback {
            DigestFallback::Wait => Self::Wait,
            DigestFallback::FetchByRound { round } => Self::FetchByRound { round },
        }
    }
}

/// How a commitment-keyed block subscription should behave when the block is missing locally.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CommitmentFallback {
    /// Wait for local availability only.
    ///
    /// Use this for pending candidate proposal data before notarization.
    Wait,
    /// Request the notarized proposal for `round` from peers.
    ///
    /// Use this when the caller knows a trusted notarized or certified round and
    /// commitment but not the proposal height, such as proposal construction,
    /// verification of a known child, or certification of a notarized candidate. Do not infer
    /// height from the finalized tip or another block: proposals may build on
    /// a certified parent that is not finalized locally yet, and an unverified
    /// child may lie about its height.
    ///
    /// The returned block is heightable once decoded, but that is too late for
    /// the in-flight resolver key or pruning bound.
    FetchByRound { round: Round },
    /// Request the exact commitment from peers and prune the request at
    /// `height`.
    ///
    /// Use this only when no certified parent round is available and the caller
    /// has a locally validated pruning bound, such as repairing a finalized gap
    /// or walking an accepted ancestry stream. Do not use it for a candidate's
    /// immediate parent when the consensus context supplies the parent round.
    ///
    /// The height is not sent to peers. It is a local pruning hint for request
    /// retention, not part of response validity: a fetched block is delivered
    /// if its commitment matches, and certified storage uses the decoded block
    /// height.
    FetchByCommitment { height: Height },
}

impl<S: Scheme, V: Variant> Message<S, V> {
    fn stale(&self, current: Option<Height>) -> bool {
        match self {
            // Height-targeted reads below the floor can never be served
            Self::GetInfo {
                identifier: Identifier::Height(height),
                ..
            }
            | Self::GetBlock {
                identifier: Identifier::Height(height),
                ..
            }
            | Self::GetFinalization { height, .. } => Some(*height) < current,
            // Hints only inform the actor about heights strictly above the floor
            Self::HintFinalized { height, .. } => Some(*height) <= current,
            // Durability acks cannot be dropped: callers depend on them
            Self::Proposed { .. } | Self::Verified { .. } | Self::Certified { .. } => false,
            // Digest and latest lookups are not bound to a specific height
            Self::GetBlock {
                identifier: Identifier::Digest(_) | Identifier::Latest,
                ..
            }
            | Self::GetInfo {
                identifier: Identifier::Digest(_) | Identifier::Latest,
                ..
            }
            | Self::GetProcessedHeight { .. } => false,
            Self::HintNotarized { .. } => false,
            Self::SubscribeByDigest { .. }
            | Self::SubscribeByCommitment { .. }
            | Self::GetVerified { .. }
            | Self::Forward { .. }
            | Self::SetFloor { .. }
            | Self::Prune { .. }
            | Self::Notarization { .. }
            | Self::Finalization { .. } => false,
        }
    }

    pub(crate) fn response_closed(&self) -> bool {
        match self {
            Self::GetInfo { response, .. } => response.is_closed(),
            Self::GetBlock { response, .. } | Self::GetVerified { response, .. } => {
                response.is_closed()
            }
            Self::GetFinalization { response, .. } => response.is_closed(),
            Self::GetProcessedHeight { response } => response.is_closed(),
            Self::SubscribeByDigest { response, .. }
            | Self::SubscribeByCommitment { response, .. } => response.is_closed(),
            Self::HintNotarized { .. } => false,
            Self::HintFinalized { .. }
            | Self::Forward { .. }
            | Self::Proposed { .. }
            | Self::Verified { .. }
            | Self::Certified { .. }
            | Self::SetFloor { .. }
            | Self::Prune { .. }
            | Self::Notarization { .. }
            | Self::Finalization { .. } => false,
        }
    }
}

pub(crate) struct Pending<S: Scheme, V: Variant> {
    floor: Option<Finalization<S, V::Commitment>>,
    prune: Option<Height>,
    hints: BTreeMap<Height, NonEmptyVec<S::PublicKey>>,
    messages: VecDeque<PendingMessage<S, V>>,
}

enum PendingMessage<S: Scheme, V: Variant> {
    Message(Message<S, V>),
    HintFinalized(Height),
}

impl<S: Scheme, V: Variant> Default for Pending<S, V> {
    fn default() -> Self {
        Self {
            floor: None,
            prune: None,
            hints: BTreeMap::new(),
            messages: VecDeque::new(),
        }
    }
}

impl<S: Scheme, V: Variant> Pending<S, V> {
    // Only prune advances are usable for height staleness checks. A pending
    // floor finalization does not carry the block height until the block is decoded.
    const fn height(&self) -> Option<Height> {
        self.prune
    }

    fn retain(&mut self) {
        let current = self.height();
        self.hints.retain(|height, _| Some(*height) > current);

        let hints = &self.hints;
        self.messages.retain(|message| match message {
            PendingMessage::Message(message) => {
                !message.response_closed() && !message.stale(current)
            }
            PendingMessage::HintFinalized(height) => hints.contains_key(height),
        });
    }

    fn set_floor(&mut self, finalization: Finalization<S, V::Commitment>) {
        let round = finalization.round();
        if self
            .floor
            .as_ref()
            .is_some_and(|floor| floor.round() >= round)
        {
            return;
        }

        self.floor = Some(finalization);
    }

    fn prune(&mut self, height: Height) {
        let current = self.height();
        let prune = Some(height);
        if self.prune >= prune {
            return;
        }

        self.prune = self.prune.max(prune);
        if self.height() > current {
            self.retain();
        }
    }

    fn extend_hint_targets(
        pending: &mut NonEmptyVec<S::PublicKey>,
        targets: NonEmptyVec<S::PublicKey>,
    ) {
        for target in targets {
            if !pending.contains(&target) {
                pending.push(target);
            }
        }
    }

    fn hint_finalized(&mut self, height: Height, targets: NonEmptyVec<S::PublicKey>) {
        // The finalized height is already covered by the floor or prune point.
        let current = self.height();
        if current.is_some_and(|current| height <= current) {
            return;
        }

        match self.hints.entry(height) {
            Entry::Vacant(entry) => {
                entry.insert(targets);
                self.messages
                    .push_back(PendingMessage::HintFinalized(height));
            }
            Entry::Occupied(mut entry) => {
                Self::extend_hint_targets(entry.get_mut(), targets);
            }
        }
    }

    fn restore_hint(&mut self, height: Height, targets: NonEmptyVec<S::PublicKey>) {
        match self.hints.entry(height) {
            Entry::Vacant(entry) => {
                entry.insert(targets);
            }
            Entry::Occupied(mut entry) => {
                Self::extend_hint_targets(entry.get_mut(), targets);
            }
        }
        self.messages
            .push_front(PendingMessage::HintFinalized(height));
    }

    fn drain_one<F>(&mut self, message: Message<S, V>, push: &mut F) -> bool
    where
        F: FnMut(Message<S, V>) -> Option<Message<S, V>>,
    {
        // Receiver accepted; the message is consumed
        let Some(message) = push(message) else {
            return true;
        };

        // Receiver rejected; restore so the next drain retries from the same point
        match message {
            Message::SetFloor { finalization } => self.set_floor(finalization),
            Message::Prune { height } => self.prune(height),
            Message::HintFinalized { height, targets } => self.restore_hint(height, targets),
            message => self.messages.push_front(PendingMessage::Message(message)),
        }
        false
    }
}

impl<S: Scheme, V: Variant> Overflow<Message<S, V>> for Pending<S, V> {
    fn is_empty(&self) -> bool {
        self.floor.is_none()
            && self.prune.is_none()
            && self.hints.is_empty()
            && self.messages.is_empty()
    }

    fn drain<F>(&mut self, mut push: F)
    where
        F: FnMut(Message<S, V>) -> Option<Message<S, V>>,
    {
        // Drain floor and prune first so the actor advances its floor before
        // it sees the height-bounded reads that follow
        if let Some(finalization) = self.floor.take() {
            if !self.drain_one(Message::SetFloor { finalization }, &mut push) {
                return;
            }
        }
        if let Some(height) = self.prune.take() {
            if !self.drain_one(Message::Prune { height }, &mut push) {
                return;
            }
        }

        // Drain the remaining queued messages in FIFO order
        while let Some(pending) = self.messages.pop_front() {
            match pending {
                PendingMessage::Message(message) => {
                    if message.response_closed() {
                        continue;
                    }
                    if !self.drain_one(message, &mut push) {
                        break;
                    }
                }
                PendingMessage::HintFinalized(hint_height) => {
                    let Some(targets) = self.hints.remove(&hint_height) else {
                        continue;
                    };
                    let message = Message::HintFinalized {
                        height: hint_height,
                        targets,
                    };
                    if !self.drain_one(message, &mut push) {
                        break;
                    }
                }
            }
        }
    }
}

impl<S: Scheme, V: Variant> Policy for Message<S, V> {
    type Overflow = Pending<S, V>;

    fn handle(overflow: &mut Self::Overflow, message: Self) {
        // A closed responder cannot be served
        if message.response_closed() {
            return;
        }
        match message {
            // Coalesce hints: a single entry per height with a unioned target set
            Self::HintFinalized { height, targets } => {
                overflow.hint_finalized(height, targets);
            }
            // Floors collapse to the highest round seen; prune collapses to
            // the highest height seen.
            Self::SetFloor { finalization } => {
                overflow.set_floor(finalization);
            }
            Self::Prune { height } => {
                overflow.prune(height);
            }
            // Queue if the new message is still useful
            message => {
                if message.stale(overflow.height()) {
                    return;
                }
                overflow
                    .messages
                    .push_back(PendingMessage::Message(message));
            }
        }
    }
}

/// A mailbox for sending messages to the marshal [Actor](super::Actor).
#[derive(Clone)]
pub struct Mailbox<S: Scheme, V: Variant> {
    sender: Sender<Message<S, V>>,
}

impl<S: Scheme, V: Variant> Mailbox<S, V> {
    /// Creates a new mailbox.
    pub(crate) const fn new(sender: Sender<Message<S, V>>) -> Self {
        Self { sender }
    }

    /// Create an ancestor stream that fetches missing parents by commitment.
    ///
    /// This stream is always a fetching stream. Callers must only use it after
    /// they already have a block that is safe to verify, certify, build on, or
    /// repair from. From that point, every parent walked by the stream is part of
    /// a certified ancestry chain, and the stream can derive each missing
    /// parent's height from its child before issuing a height-bound request.
    ///
    /// Do not use this to wait for pending candidate proposal data.
    pub(crate) fn ancestor_stream<I, C>(
        &self,
        clock: Arc<C>,
        initial: I,
        fetch_duration: Timed,
    ) -> impl Ancestry<V::ApplicationBlock> + use<S, V, I, C>
    where
        Self: BlockProvider<Block = V::ApplicationBlock>,
        I: IntoIterator<Item = V::Block>,
        C: Clock,
    {
        AncestorStream::new(
            clock,
            self.clone(),
            initial.into_iter().map(V::into_inner),
            fetch_duration,
        )
    }

    /// Retrieve `(height, digest)` for a finalized block by height, digest, or latest.
    pub async fn get_info(
        &self,
        identifier: impl Into<Identifier<<V::Block as Digestible>::Digest>>,
    ) -> Option<(Height, <V::Block as Digestible>::Digest)> {
        let identifier = identifier.into();
        let (response, receiver) = oneshot::channel();
        let _ = self.sender.enqueue(Message::GetInfo {
            identifier,
            response,
        });
        receiver.await.ok().flatten()
    }

    /// A best-effort attempt to retrieve a given block from local
    /// storage. It is not an indication to go fetch the block from the network.
    pub async fn get_block(
        &self,
        identifier: impl Into<Identifier<<V::Block as Digestible>::Digest>>,
    ) -> Option<V::Block> {
        let identifier = identifier.into();
        let (response, receiver) = oneshot::channel();
        let _ = self.sender.enqueue(Message::GetBlock {
            identifier,
            response,
        });
        receiver.await.ok().flatten()
    }

    /// A best-effort attempt to retrieve a given [Finalization] from local
    /// storage. It is not an indication to go fetch the [Finalization] from the network.
    pub async fn get_finalization(&self, height: Height) -> Option<Finalization<S, V::Commitment>> {
        let (response, receiver) = oneshot::channel();
        let _ = self
            .sender
            .enqueue(Message::GetFinalization { height, response });
        receiver.await.ok().flatten()
    }

    /// Retrieve the latest processed height.
    pub async fn get_processed_height(&self) -> Option<Height> {
        let (response, receiver) = oneshot::channel();
        let _ = self
            .sender
            .enqueue(Message::GetProcessedHeight { response });
        receiver.await.ok().flatten()
    }

    /// Hints that a finalized block may be available at the given height.
    ///
    /// This method will request the finalization from the network via the resolver
    /// if it is not available locally.
    ///
    /// Targets are required because this is typically called when a peer claims to be
    /// ahead. By targeting only those peers, we limit who we ask. If a target returns
    /// invalid data, they will be blocked by the resolver. If targets don't respond
    /// or return "no data", they effectively rate-limit themselves.
    ///
    /// Calling this multiple times for the same height with different targets will
    /// add to the target set if there is an ongoing fetch, allowing more peers to be tried.
    ///
    /// This is fire-and-forget: the finalization will be stored in marshal and delivered
    /// via the normal finalization flow when available.
    ///
    /// The height must be covered by both the epocher and the provider. If the
    /// epocher cannot map the height to an epoch, or the provider cannot supply
    /// a scheme for that epoch, the hint is silently dropped.
    pub fn hint_finalized(&self, height: Height, targets: NonEmptyVec<S::PublicKey>) {
        let _ = self
            .sender
            .enqueue(Message::HintFinalized { height, targets });
    }

    /// Subscribe to a block by its digest.
    ///
    /// If the block is found available locally, the block will be returned immediately.
    ///
    /// If the block is not available locally, the subscription will be registered and the caller
    /// will be notified when the block is available. If the block is not finalized, it's possible
    /// that it may never become available.
    ///
    /// The `fallback` parameter controls whether marshal also asks peers for the missing block.
    /// Digest-keyed subscriptions only support waiting locally or fetching by round.
    ///
    /// The oneshot receiver should be dropped to cancel the subscription.
    pub fn subscribe_by_digest(
        &self,
        digest: <V::Block as Digestible>::Digest,
        fallback: DigestFallback,
    ) -> oneshot::Receiver<V::Block> {
        let (tx, rx) = oneshot::channel();
        let _ = self.sender.enqueue(Message::SubscribeByDigest {
            digest,
            fallback,
            response: tx,
        });
        rx
    }

    /// Subscribe to a block by its commitment.
    ///
    /// If the block is found available locally, the block will be returned immediately.
    ///
    /// If the block is not available locally, the subscription will be registered and the caller
    /// will be notified when the block is available. If the block is not finalized, it's possible
    /// that it may never become available.
    ///
    /// The `fallback` parameter controls whether marshal also asks peers for the missing block.
    ///
    /// The oneshot receiver should be dropped to cancel the subscription.
    pub fn subscribe_by_commitment(
        &self,
        commitment: V::Commitment,
        fallback: CommitmentFallback,
    ) -> oneshot::Receiver<V::Block> {
        let (tx, rx) = oneshot::channel();
        let _ = self.sender.enqueue(Message::SubscribeByCommitment {
            fallback,
            commitment,
            response: tx,
        });
        rx
    }

    /// Hint that peers may have the block notarized at `round`.
    ///
    /// This issues a round-bound resolver request without registering a new
    /// block subscriber. The `commitment` is only used to skip the request when
    /// the block is already available locally.
    ///
    /// This is useful when a local-only waiter already exists and later
    /// certification makes a network fetch by notarized round valid.
    pub fn hint_notarized(&self, round: Round, commitment: V::Commitment) {
        let _ = self
            .sender
            .enqueue(Message::HintNotarized { round, commitment });
    }

    /// Returns a stream over the ancestry of a given block, leading up to genesis.
    ///
    /// This stream may fetch missing parents because callers should only request
    /// ancestry for data they already have locally and are willing to build on,
    /// verify, certify, or repair from. It is not a candidate fetch path.
    ///
    /// If the starting block is not found, `None` is returned.
    pub async fn ancestry<C>(
        &self,
        clock: Arc<C>,
        (fallback, start_digest): (DigestFallback, <V::Block as Digestible>::Digest),
        fetch_duration: Timed,
    ) -> Option<impl Ancestry<V::ApplicationBlock> + use<S, V, C>>
    where
        Self: BlockProvider<Block = V::ApplicationBlock>,
        C: Clock,
    {
        let receiver = self.subscribe_by_digest(start_digest, fallback);
        receiver
            .await
            .ok()
            .map(|block| self.ancestor_stream(clock, [block], fetch_duration))
    }

    /// Returns the verified block previously persisted for `round`, if any.
    pub async fn get_verified(&self, round: Round) -> Option<V::Block> {
        let (response, receiver) = oneshot::channel();
        let _ = self
            .sender
            .enqueue(Message::GetVerified { round, response });
        receiver.await.ok().flatten()
    }

    /// Notifies the actor that a block has been locally proposed.
    ///
    /// Returns after the block is durably persisted.
    #[must_use = "callers must consider block durability before proceeding"]
    pub async fn proposed(&self, round: Round, block: V::Block) -> bool {
        let (ack, receiver) = oneshot::channel();
        let _ = self.sender.enqueue(Message::Proposed {
            round,
            block,
            ack: Some(ack),
        });
        receiver.await.is_ok()
    }

    /// Notifies the actor that a block has been verified.
    ///
    /// Returns after the block is durably persisted.
    #[must_use = "callers must consider block durability before proceeding"]
    pub async fn verified(&self, round: Round, block: V::Block) -> bool {
        let (ack, receiver) = oneshot::channel();
        let _ = self.sender.enqueue(Message::Verified {
            round,
            block,
            ack: Some(ack),
        });
        receiver.await.is_ok()
    }

    /// Notifies the actor that a block has been certified.
    ///
    /// Returns after the block is durably persisted.
    #[must_use = "callers must consider block durability before proceeding"]
    pub async fn certified(&self, round: Round, block: V::Block) -> bool {
        let (ack, receiver) = oneshot::channel();
        let _ = self.sender.enqueue(Message::Certified {
            round,
            block,
            ack: Some(ack),
        });
        receiver.await.is_ok()
    }

    /// Attempts to set the sync starting point from a finalized commitment.
    ///
    /// If the verified finalization advances marshal's current floor, marshal
    /// anchors on its block, prunes below it, then syncs and delivers blocks
    /// starting at the floor height. Stale or superseded floors may be ignored.
    ///
    /// To prune data without changing the sync starting point, use
    /// [Self::prune] instead.
    /// Use [`crate::marshal::Config::start`] to provide the startup anchor.
    pub fn set_floor(&self, finalization: Finalization<S, V::Commitment>) {
        let _ = self.sender.enqueue(Message::SetFloor { finalization });
    }

    /// Requests pruning finalized blocks and certificates below the given height.
    ///
    /// Unlike [Self::set_floor], this does not affect the sync starting point.
    /// Requests above marshal's current floor are ignored.
    pub fn prune(&self, height: Height) {
        let _ = self.sender.enqueue(Message::Prune { height });
    }

    /// Forward a block to a set of recipients.
    pub fn forward(
        &self,
        round: Round,
        commitment: V::Commitment,
        recipients: Recipients<S::PublicKey>,
    ) -> Feedback {
        self.sender.enqueue(Message::Forward {
            round,
            commitment,
            recipients,
        })
    }
}

impl<S: Scheme, V: Variant> Reporter for Mailbox<S, V> {
    type Activity = Activity<S, V::Commitment>;

    fn report(&mut self, activity: Self::Activity) -> Feedback {
        let message = match activity {
            Activity::Notarization(notarization) => Message::Notarization { notarization },
            Activity::Finalization(finalization) => Message::Finalization { finalization },
            _ => return Feedback::Ok,
        };
        self.sender.enqueue(message)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        marshal::{mocks::harness, standard::Standard},
        simplex::{scheme::bls12381_threshold::vrf as bls12381_threshold_vrf, types::Proposal},
        types::{Epoch, View},
        Heightable,
    };
    use commonware_cryptography::{
        certificate::mocks::Fixture, ed25519::PrivateKey, Digest as _, Signer as _,
    };
    use commonware_utils::{channel::oneshot::error::TryRecvError, test_rng_seeded};

    type TestMessage = Message<harness::S, Standard<harness::B>>;
    type TestPending = Pending<harness::S, Standard<harness::B>>;

    fn public_key(seed: u64) -> harness::K {
        PrivateKey::from_seed(seed).public_key()
    }

    fn round(height: u64) -> Round {
        Round::new(Epoch::zero(), View::new(height))
    }

    fn block(height: u64) -> harness::B {
        harness::make_raw_block(harness::D::EMPTY, Height::new(height), height)
    }

    fn commitment(height: u64) -> harness::D {
        <Standard<harness::B> as Variant>::commitment(&block(height))
    }

    fn finalization(height: u64) -> Finalization<harness::S, harness::D> {
        let mut rng = test_rng_seeded(height);
        let Fixture { schemes, .. } = bls12381_threshold_vrf::fixture::<harness::V, _>(
            &mut rng,
            harness::NAMESPACE,
            harness::NUM_VALIDATORS,
        );
        let proposal = Proposal::new(round(height), View::zero(), commitment(height));
        <harness::StandardHarness as harness::TestHarness>::make_finalization(
            proposal,
            &schemes,
            harness::QUORUM,
        )
    }

    fn get_info(height: u64) -> (TestMessage, oneshot::Receiver<Option<(Height, harness::D)>>) {
        let (response, receiver) = oneshot::channel();
        (
            TestMessage::GetInfo {
                identifier: Identifier::Height(Height::new(height)),
                response,
            },
            receiver,
        )
    }

    fn proposed(height: u64) -> (TestMessage, oneshot::Receiver<()>) {
        let (ack, receiver) = oneshot::channel();
        (
            TestMessage::Proposed {
                round: round(height),
                block: block(height),
                ack: Some(ack),
            },
            receiver,
        )
    }

    fn verified(height: u64) -> (TestMessage, oneshot::Receiver<()>) {
        let (ack, receiver) = oneshot::channel();
        (
            TestMessage::Verified {
                round: round(height),
                block: block(height),
                ack: Some(ack),
            },
            receiver,
        )
    }

    fn certified(height: u64) -> (TestMessage, oneshot::Receiver<()>) {
        let (ack, receiver) = oneshot::channel();
        (
            TestMessage::Certified {
                round: round(height),
                block: block(height),
                ack: Some(ack),
            },
            receiver,
        )
    }

    fn get_block(height: u64) -> (TestMessage, oneshot::Receiver<Option<harness::B>>) {
        let (response, receiver) = oneshot::channel();
        (
            TestMessage::GetBlock {
                identifier: Identifier::Height(Height::new(height)),
                response,
            },
            receiver,
        )
    }

    fn get_finalization(
        height: u64,
    ) -> (
        TestMessage,
        oneshot::Receiver<Option<Finalization<harness::S, harness::D>>>,
    ) {
        let (response, receiver) = oneshot::channel();
        (
            TestMessage::GetFinalization {
                height: Height::new(height),
                response,
            },
            receiver,
        )
    }

    fn subscribe_by_digest(height: u64) -> (TestMessage, oneshot::Receiver<harness::B>) {
        let (response, receiver) = oneshot::channel();
        (
            TestMessage::SubscribeByDigest {
                digest: block(height).digest(),
                fallback: DigestFallback::FetchByRound {
                    round: round(height),
                },
                response,
            },
            receiver,
        )
    }

    fn subscribe_by_commitment_message(
        height: u64,
        fallback: CommitmentFallback,
    ) -> (TestMessage, oneshot::Receiver<harness::B>) {
        let (response, receiver) = oneshot::channel();
        (
            TestMessage::SubscribeByCommitment {
                commitment: commitment(height),
                fallback,
                response,
            },
            receiver,
        )
    }

    fn hint_finalized(height: u64, target: harness::K) -> TestMessage {
        TestMessage::HintFinalized {
            height: Height::new(height),
            targets: NonEmptyVec::new(target),
        }
    }

    fn set_floor(height: u64) -> TestMessage {
        TestMessage::SetFloor {
            finalization: finalization(height),
        }
    }

    fn prune(height: u64) -> TestMessage {
        TestMessage::Prune {
            height: Height::new(height),
        }
    }

    fn pending() -> TestPending {
        TestPending::default()
    }

    fn drain(overflow: &mut TestPending) -> VecDeque<TestMessage> {
        let mut drained = VecDeque::new();
        overflow.drain(|message| {
            drained.push_back(message);
            None
        });
        drained
    }

    fn has_get_info(overflow: &TestPending, height: u64) -> bool {
        overflow.messages.iter().any(|message| {
            matches!(
                message,
                PendingMessage::Message(TestMessage::GetInfo {
                    identifier: Identifier::Height(found),
                    response,
                    ..
                }) if *found == Height::new(height) && !response.is_closed()
            )
        })
    }

    fn has_get_block(overflow: &TestPending, height: u64) -> bool {
        overflow.messages.iter().any(|message| {
            matches!(
                message,
                PendingMessage::Message(TestMessage::GetBlock {
                    identifier: Identifier::Height(found),
                    response,
                    ..
                }) if *found == Height::new(height) && !response.is_closed()
            )
        })
    }

    fn has_get_finalization(overflow: &TestPending, height: u64) -> bool {
        overflow.messages.iter().any(|message| {
            matches!(
                message,
                PendingMessage::Message(TestMessage::GetFinalization {
                    height: found,
                    response,
                }) if *found == Height::new(height) && !response.is_closed()
            )
        })
    }

    fn hint_targets(overflow: &TestPending, height: u64) -> Option<&NonEmptyVec<harness::K>> {
        overflow.hints.get(&Height::new(height))
    }

    fn has_block_message(overflow: &TestPending, height: u64) -> bool {
        overflow.messages.iter().any(|message| {
            matches!(
                message,
                PendingMessage::Message(
                    TestMessage::Proposed { block, .. }
                        | TestMessage::Verified { block, .. }
                        | TestMessage::Certified { block, .. }
                )
                    if block.height() == Height::new(height)
            )
        })
    }

    fn has_prune(overflow: &TestPending, height: u64) -> bool {
        overflow.prune == Some(Height::new(height))
    }

    fn has_subscription(overflow: &TestPending, height: u64) -> bool {
        let expected_digest = block(height).digest();
        let expected_commitment = commitment(height);
        overflow.messages.iter().any(|message| {
            matches!(
                message,
                PendingMessage::Message(TestMessage::SubscribeByDigest { digest, response, .. })
                    if *digest == expected_digest && !response.is_closed()
            ) || matches!(
                message,
                PendingMessage::Message(TestMessage::SubscribeByCommitment {
                    commitment,
                    response,
                    ..
                }) if *commitment == expected_commitment && !response.is_closed()
            )
        })
    }

    #[test]
    fn policy_coalesces_hint_targets() {
        let mut overflow = pending();
        let first = public_key(1);
        let second = public_key(2);

        <TestMessage as Policy>::handle(&mut overflow, hint_finalized(10, first.clone()));
        <TestMessage as Policy>::handle(&mut overflow, hint_finalized(10, first.clone()));
        <TestMessage as Policy>::handle(&mut overflow, hint_finalized(10, second.clone()));

        assert_eq!(overflow.messages.len(), 1);
        let targets = hint_targets(&overflow, 10).expect("expected hint");
        assert_eq!(targets.len().get(), 2);
        assert!(targets.contains(&first));
        assert!(targets.contains(&second));
    }

    #[test]
    fn policy_preserves_commitment_subscription_fallbacks() {
        let mut overflow = pending();

        let (wait, _wait_rx) = subscribe_by_commitment_message(1, CommitmentFallback::Wait);
        let (by_round, _by_round_rx) = subscribe_by_commitment_message(
            2,
            CommitmentFallback::FetchByRound { round: round(2) },
        );
        let (by_commitment, _by_commitment_rx) = subscribe_by_commitment_message(
            3,
            CommitmentFallback::FetchByCommitment {
                height: Height::new(3),
            },
        );

        <TestMessage as Policy>::handle(&mut overflow, wait);
        <TestMessage as Policy>::handle(&mut overflow, by_round);
        <TestMessage as Policy>::handle(&mut overflow, by_commitment);

        let drained = drain(&mut overflow);
        assert_eq!(drained.len(), 3);
        assert!(matches!(
            &drained[0],
            TestMessage::SubscribeByCommitment {
                fallback: CommitmentFallback::Wait,
                ..
            }
        ));
        assert!(matches!(
            &drained[1],
            TestMessage::SubscribeByCommitment {
                fallback: CommitmentFallback::FetchByRound { round: found },
                ..
            } if *found == round(2)
        ));
        assert!(matches!(
            &drained[2],
            TestMessage::SubscribeByCommitment {
                fallback: CommitmentFallback::FetchByCommitment { height },
                ..
            } if *height == Height::new(3)
        ));
    }

    #[test]
    fn policy_handles_closed_subscriptions() {
        let mut overflow = pending();

        let (pending_closed, pending_closed_rx) = subscribe_by_digest(1);
        drop(pending_closed_rx);
        overflow
            .messages
            .push_back(PendingMessage::Message(pending_closed));

        let (pending_open, mut pending_open_rx) = subscribe_by_commitment_message(
            2,
            CommitmentFallback::FetchByRound { round: round(2) },
        );
        overflow
            .messages
            .push_back(PendingMessage::Message(pending_open));

        let (current_closed, current_closed_rx) = subscribe_by_digest(3);
        drop(current_closed_rx);
        <TestMessage as Policy>::handle(&mut overflow, current_closed);

        assert!(!has_subscription(&overflow, 1));
        assert!(has_subscription(&overflow, 2));
        assert!(!has_subscription(&overflow, 3));
        assert!(matches!(
            pending_open_rx.try_recv(),
            Err(TryRecvError::Empty)
        ));
    }

    #[test]
    fn policy_handles_closed_responses() {
        let mut overflow = pending();

        let (pending_closed, pending_closed_rx) = get_block(1);
        drop(pending_closed_rx);
        overflow
            .messages
            .push_back(PendingMessage::Message(pending_closed));

        let (pending_open, mut pending_open_rx) = get_info(2);
        overflow
            .messages
            .push_back(PendingMessage::Message(pending_open));

        let (current_closed, current_closed_rx) = get_finalization(3);
        drop(current_closed_rx);
        <TestMessage as Policy>::handle(&mut overflow, current_closed);

        assert!(!has_get_block(&overflow, 1));
        assert!(has_get_info(&overflow, 2));
        assert!(!has_get_finalization(&overflow, 3));
        assert!(matches!(
            pending_open_rx.try_recv(),
            Err(TryRecvError::Empty)
        ));
    }

    #[test]
    fn policy_drain_stops_after_returned_response_closes() {
        let mut overflow = pending();
        let (first, first_rx) = get_block(1);
        let (second, mut second_rx) = get_info(2);
        overflow.messages.push_back(PendingMessage::Message(first));
        overflow.messages.push_back(PendingMessage::Message(second));

        let mut first_rx = Some(first_rx);
        let mut attempts = 0;
        overflow.drain(|message| {
            attempts += 1;
            drop(first_rx.take());
            Some(message)
        });
        assert_eq!(attempts, 1);

        let drained = drain(&mut overflow);
        assert_eq!(drained.len(), 1);
        assert!(matches!(
            &drained[0],
            TestMessage::GetInfo {
                identifier: Identifier::Height(height),
                response,
            } if *height == Height::new(2) && !response.is_closed()
        ));
        assert!(matches!(second_rx.try_recv(), Err(TryRecvError::Empty)));
    }

    #[test]
    fn policy_keeps_coalesced_hints_in_fifo_position() {
        let mut overflow = pending();
        let first = public_key(1);
        let second = public_key(2);
        let (get_block_9, _get_block_9_rx) = get_block(9);
        let (get_info_11, _get_info_11_rx) = get_info(11);

        <TestMessage as Policy>::handle(&mut overflow, get_block_9);
        <TestMessage as Policy>::handle(&mut overflow, hint_finalized(10, first.clone()));
        <TestMessage as Policy>::handle(&mut overflow, get_info_11);
        <TestMessage as Policy>::handle(&mut overflow, hint_finalized(10, second.clone()));

        let drained = drain(&mut overflow);
        assert_eq!(drained.len(), 3);
        assert!(matches!(
            &drained[0],
            TestMessage::GetBlock {
                identifier: Identifier::Height(height),
                ..
            } if *height == Height::new(9)
        ));
        assert!(matches!(
            &drained[2],
            TestMessage::GetInfo {
                identifier: Identifier::Height(height),
                ..
            } if *height == Height::new(11)
        ));
        let TestMessage::HintFinalized { height, targets } = &drained[1] else {
            panic!("expected hint");
        };
        assert_eq!(*height, Height::new(10));
        assert_eq!(targets.len().get(), 2);
        assert!(targets.contains(&first));
        assert!(targets.contains(&second));
    }

    #[test]
    fn policy_keeps_highest_floor_and_prune() {
        let mut overflow = pending();

        <TestMessage as Policy>::handle(&mut overflow, set_floor(5));
        <TestMessage as Policy>::handle(&mut overflow, set_floor(3));
        <TestMessage as Policy>::handle(&mut overflow, set_floor(8));
        <TestMessage as Policy>::handle(&mut overflow, prune(4));
        <TestMessage as Policy>::handle(&mut overflow, prune(2));
        <TestMessage as Policy>::handle(&mut overflow, prune(7));

        assert_eq!(
            overflow.floor.as_ref().map(Finalization::round),
            Some(round(8))
        );
        assert_eq!(overflow.prune, Some(Height::new(7)));
        assert!(overflow.messages.is_empty());

        let drained = drain(&mut overflow);
        assert_eq!(drained.len(), 2);
        assert!(matches!(
            &drained[0],
            TestMessage::SetFloor { finalization } if finalization.round() == round(8)
        ));
        assert!(matches!(
            &drained[1],
            TestMessage::Prune { height } if *height == Height::new(7)
        ));
    }

    #[test]
    fn policy_replaces_floor_and_prune_and_drops_stale_pending_on_drain() {
        let mut overflow = pending();

        overflow.floor = Some(finalization(5));
        let (get_info_4, _get_info_4_rx) = get_info(4);
        let (get_block_7, _get_block_7_rx) = get_block(7);
        let (get_block_8, _get_block_8_rx) = get_block(8);
        overflow
            .messages
            .push_back(PendingMessage::Message(get_info_4));
        overflow
            .messages
            .push_back(PendingMessage::Message(get_block_7));
        overflow.hint_finalized(Height::new(8), NonEmptyVec::new(public_key(1)));
        overflow
            .messages
            .push_back(PendingMessage::Message(get_block_8));
        <TestMessage as Policy>::handle(&mut overflow, set_floor(8));
        <TestMessage as Policy>::handle(&mut overflow, prune(8));
        assert_eq!(
            overflow.floor.as_ref().map(Finalization::round),
            Some(round(8))
        );
        assert_eq!(overflow.messages.len(), 1);
        assert!(!has_get_info(&overflow, 4));
        assert!(!has_get_block(&overflow, 7));
        assert!(has_get_block(&overflow, 8));
        assert!(hint_targets(&overflow, 8).is_none());
        let drained = drain(&mut overflow);
        assert_eq!(drained.len(), 3);
        assert!(matches!(
            &drained[0],
            TestMessage::SetFloor { finalization } if finalization.round() == round(8)
        ));
        assert!(matches!(
            &drained[1],
            TestMessage::Prune { height } if *height == Height::new(8)
        ));
        assert!(matches!(
            &drained[2],
            TestMessage::GetBlock {
                identifier: Identifier::Height(height),
                ..
            } if *height == Height::new(8)
        ));

        let mut overflow = pending();
        overflow.prune = Some(Height::new(5));
        let (get_finalization_4, _get_finalization_4_rx) = get_finalization(4);
        let (get_block_6, _get_block_6_rx) = get_block(6);
        let (get_block_7, _get_block_7_rx) = get_block(7);
        overflow
            .messages
            .push_back(PendingMessage::Message(get_finalization_4));
        overflow
            .messages
            .push_back(PendingMessage::Message(get_block_6));
        overflow.hint_finalized(Height::new(6), NonEmptyVec::new(public_key(2)));
        overflow
            .messages
            .push_back(PendingMessage::Message(get_block_7));
        <TestMessage as Policy>::handle(&mut overflow, prune(7));
        assert_eq!(overflow.prune, Some(Height::new(7)));
        assert_eq!(overflow.messages.len(), 1);
        assert!(!has_get_finalization(&overflow, 4));
        assert!(!has_get_block(&overflow, 6));
        assert!(has_get_block(&overflow, 7));
        assert!(hint_targets(&overflow, 6).is_none());
        let drained = drain(&mut overflow);
        assert_eq!(drained.len(), 2);
        assert!(matches!(
            &drained[0],
            TestMessage::Prune { height } if *height == Height::new(7)
        ));
        assert!(matches!(
            &drained[1],
            TestMessage::GetBlock {
                identifier: Identifier::Height(height),
                ..
            } if *height == Height::new(7)
        ));
    }

    #[test]
    fn policy_prune_drops_closed_pending() {
        let mut overflow = pending();
        let (closed_message, closed_rx) = get_block(8);
        drop(closed_rx);
        let (open_message, mut open_rx) = get_block(8);

        overflow
            .messages
            .push_back(PendingMessage::Message(closed_message));
        overflow
            .messages
            .push_back(PendingMessage::Message(open_message));

        <TestMessage as Policy>::handle(&mut overflow, prune(7));
        assert_eq!(overflow.messages.len(), 1);
        assert!(has_get_block(&overflow, 8));
        assert!(matches!(open_rx.try_recv(), Err(TryRecvError::Empty)));

        let mut overflow = pending();
        let (closed_message, closed_rx) = get_finalization(8);
        drop(closed_rx);
        let (open_message, mut open_rx) = get_finalization(8);

        overflow
            .messages
            .push_back(PendingMessage::Message(closed_message));
        overflow
            .messages
            .push_back(PendingMessage::Message(open_message));

        <TestMessage as Policy>::handle(&mut overflow, prune(7));
        assert_eq!(overflow.messages.len(), 1);
        assert!(has_get_finalization(&overflow, 8));
        assert!(matches!(open_rx.try_recv(), Err(TryRecvError::Empty)));
    }

    #[test]
    fn policy_skips_retain_when_prune_height_does_not_increase() {
        let mut overflow = pending();
        <TestMessage as Policy>::handle(&mut overflow, prune(10));

        let (closed_message, closed_rx) = get_block(11);
        drop(closed_rx);
        overflow
            .messages
            .push_back(PendingMessage::Message(closed_message));

        <TestMessage as Policy>::handle(&mut overflow, set_floor(9));
        assert_eq!(overflow.messages.len(), 1);

        <TestMessage as Policy>::handle(&mut overflow, prune(9));
        assert_eq!(overflow.messages.len(), 1);

        <TestMessage as Policy>::handle(&mut overflow, prune(12));
        assert!(overflow.messages.is_empty());
    }

    #[test]
    fn policy_drops_stale_requests_against_pending_floor_and_prune() {
        let mut overflow = pending();
        let (get_info_4, _get_info_4_rx) = get_info(4);
        let (get_info_5, _get_info_5_rx) = get_info(5);
        let (get_info_6, _get_info_6_rx) = get_info(6);
        let (get_info_7, _get_info_7_rx) = get_info(7);
        let (get_block_4, _get_block_4_rx) = get_block(4);
        let (get_block_5, _get_block_5_rx) = get_block(5);
        let (get_block_6, _get_block_6_rx) = get_block(6);
        let (get_block_7, _get_block_7_rx) = get_block(7);
        let (get_finalization_4, _get_finalization_4_rx) = get_finalization(4);
        let (get_finalization_6, _get_finalization_6_rx) = get_finalization(6);

        <TestMessage as Policy>::handle(&mut overflow, set_floor(5));
        <TestMessage as Policy>::handle(&mut overflow, get_info_4);
        <TestMessage as Policy>::handle(&mut overflow, get_info_5);
        <TestMessage as Policy>::handle(&mut overflow, get_block_4);
        <TestMessage as Policy>::handle(&mut overflow, get_block_5);
        <TestMessage as Policy>::handle(&mut overflow, get_finalization_4);
        <TestMessage as Policy>::handle(&mut overflow, hint_finalized(5, public_key(1)));
        <TestMessage as Policy>::handle(&mut overflow, hint_finalized(6, public_key(2)));

        <TestMessage as Policy>::handle(&mut overflow, prune(7));
        assert!(has_prune(&overflow, 7));
        <TestMessage as Policy>::handle(&mut overflow, get_info_6);
        <TestMessage as Policy>::handle(&mut overflow, get_finalization_6);
        assert!(!has_get_finalization(&overflow, 6));
        <TestMessage as Policy>::handle(&mut overflow, get_block_6);
        <TestMessage as Policy>::handle(&mut overflow, get_info_7);
        assert!(has_get_info(&overflow, 7));
        <TestMessage as Policy>::handle(&mut overflow, get_block_7);
        assert!(has_get_block(&overflow, 7));

        let drained = drain(&mut overflow);
        assert_eq!(drained.len(), 4);
        assert!(matches!(
            &drained[0],
            TestMessage::SetFloor { finalization } if finalization.round() == round(5)
        ));
        assert!(matches!(
            &drained[1],
            TestMessage::Prune { height } if *height == Height::new(7)
        ));
        assert!(matches!(
            &drained[2],
            TestMessage::GetInfo {
                identifier: Identifier::Height(height),
                ..
            } if *height == Height::new(7)
        ));
        assert!(matches!(
            &drained[3],
            TestMessage::GetBlock {
                identifier: Identifier::Height(height),
                ..
            } if *height == Height::new(7)
        ));
    }

    #[test]
    fn policy_keeps_block_messages_and_waiters() {
        let mut overflow = pending();

        let (proposed_message, mut proposed_ack) = proposed(4);
        let (verified_message, mut verified_ack) = verified(6);
        let (certified_message, mut certified_ack) = certified(8);
        overflow
            .messages
            .push_back(PendingMessage::Message(proposed_message));
        overflow
            .messages
            .push_back(PendingMessage::Message(verified_message));
        overflow
            .messages
            .push_back(PendingMessage::Message(certified_message));

        <TestMessage as Policy>::handle(&mut overflow, set_floor(7));
        assert!(has_block_message(&overflow, 4));
        assert!(has_block_message(&overflow, 6));
        assert!(has_block_message(&overflow, 8));
        assert!(matches!(proposed_ack.try_recv(), Err(TryRecvError::Empty)));
        assert!(matches!(verified_ack.try_recv(), Err(TryRecvError::Empty)));
        assert!(matches!(certified_ack.try_recv(), Err(TryRecvError::Empty)));

        <TestMessage as Policy>::handle(&mut overflow, prune(9));
        assert!(has_block_message(&overflow, 8));
        assert!(matches!(certified_ack.try_recv(), Err(TryRecvError::Empty)));

        let (stale, mut stale_ack) = proposed(8);
        <TestMessage as Policy>::handle(&mut overflow, stale);
        assert!(has_block_message(&overflow, 8));
        assert!(matches!(stale_ack.try_recv(), Err(TryRecvError::Empty)));

        let (current, mut current_ack) = verified(9);
        <TestMessage as Policy>::handle(&mut overflow, current);
        assert!(has_block_message(&overflow, 9));
        assert!(matches!(current_ack.try_recv(), Err(TryRecvError::Empty)));

        let drained = drain(&mut overflow);
        assert!(matches!(drained[0], TestMessage::SetFloor { .. }));
        assert!(matches!(drained[1], TestMessage::Prune { .. }));
    }
}