asupersync 0.3.5

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
//! Channel bonding Phase C2 — one receiver-side symbol set for all donors.
//!
//! Donors in a bonded transfer spray authenticated RaptorQ symbols to the same
//! receiver endpoint. Correctness depends on the receiver treating every symbol
//! as part of one fungible decoder input stream keyed only by
//! `(object_id, sbn, esi)`. The donor id is useful for observability, but it must
//! not partition the decoder state. If two donors deliver the same key, the
//! second symbol is duplicate bandwidth and is dropped before decode.

use std::collections::{BTreeMap, BTreeSet};

use crate::cx::Cx;
use crate::types::{ObjectId, Symbol, SymbolId, SymbolKind};

/// Environment variable that enables human-readable bonded receiver trace lines.
pub const ATP_BOND_TRACE_ENV: &str = "ATP_BOND_TRACE";

/// Structured trace event emitted for bonded receiver live progress.
pub const BONDING_RECEIVER_PROGRESS_TRACE_EVENT: &str = "atp_bond.receiver.progress";

/// Decoder identity for one bonded RaptorQ symbol.
///
/// This intentionally omits donor id: the same `(object_id, sbn, esi)` from any
/// donor names the same decoder row and must be deduplicated globally.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BondedSymbolKey {
    object_id: ObjectId,
    sbn: u8,
    esi: u32,
}

impl BondedSymbolKey {
    /// Build a bonded receiver key.
    #[must_use]
    pub const fn new(object_id: ObjectId, sbn: u8, esi: u32) -> Self {
        Self {
            object_id,
            sbn,
            esi,
        }
    }

    /// Build a key from an existing ATP/RaptorQ symbol id.
    #[must_use]
    pub const fn from_symbol_id(symbol_id: SymbolId) -> Self {
        Self {
            object_id: symbol_id.object_id(),
            sbn: symbol_id.sbn(),
            esi: symbol_id.esi(),
        }
    }

    /// Return the object id.
    #[must_use]
    pub const fn object_id(self) -> ObjectId {
        self.object_id
    }

    /// Return the source block number.
    #[must_use]
    pub const fn sbn(self) -> u8 {
        self.sbn
    }

    /// Return the encoding symbol id.
    #[must_use]
    pub const fn esi(self) -> u32 {
        self.esi
    }
}

/// Per-donor ingress counters for C2 observability.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BondedDonorIngressStats {
    /// All authenticated symbols received from this donor.
    pub symbols_received: u64,
    /// Globally novel symbols accepted into the unified receiver set.
    pub symbols_accepted: u64,
    /// Symbols dropped because another donor or retry already provided the key.
    pub duplicate_symbols: u64,
    /// Accepted source symbols.
    pub source_symbols_accepted: u64,
    /// Accepted repair/FEC symbols.
    pub repair_symbols_accepted: u64,
    /// Novel symbols dropped by the bounded receiver-retention policy.
    pub symbols_rejected_by_retention: u64,
}

impl BondedDonorIngressStats {
    fn record_received(&mut self) {
        self.symbols_received = self.symbols_received.saturating_add(1);
    }

    fn record_duplicate(&mut self) {
        self.duplicate_symbols = self.duplicate_symbols.saturating_add(1);
    }

    fn record_retention_reject(&mut self) {
        self.symbols_rejected_by_retention = self.symbols_rejected_by_retention.saturating_add(1);
    }

    fn record_accepted(&mut self, kind: SymbolKind) {
        self.symbols_accepted = self.symbols_accepted.saturating_add(1);
        if kind.is_source() {
            self.source_symbols_accepted = self.source_symbols_accepted.saturating_add(1);
        } else {
            self.repair_symbols_accepted = self.repair_symbols_accepted.saturating_add(1);
        }
    }

    /// Duplicate rate in parts-per-million.
    #[must_use]
    pub fn duplicate_rate_ppm(self) -> u64 {
        duplicate_rate_ppm(self.duplicate_symbols, self.symbols_received)
    }
}

/// Aggregate ingress counters across all donors.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BondedReceiverIngressStats {
    /// All authenticated donor symbols observed.
    pub symbols_received: u64,
    /// Globally novel symbols accepted into the unified receiver set.
    pub symbols_accepted: u64,
    /// Globally duplicate symbols dropped before decode.
    pub duplicate_symbols: u64,
    /// Accepted source symbols.
    pub source_symbols_accepted: u64,
    /// Accepted repair/FEC symbols.
    pub repair_symbols_accepted: u64,
    /// Novel symbols dropped by the bounded receiver-retention policy.
    pub symbols_rejected_by_retention: u64,
    /// Number of donors that have contributed at least one symbol.
    pub donor_count: usize,
}

impl BondedReceiverIngressStats {
    /// Duplicate rate in parts-per-million.
    #[must_use]
    pub fn duplicate_rate_ppm(self) -> u64 {
        duplicate_rate_ppm(self.duplicate_symbols, self.symbols_received)
    }
}

/// Result of recording one bonded donor symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BondedSymbolDisposition {
    /// The key was novel and should be fed to the shared decoder set.
    Accepted(BondedSymbolKey),
    /// The key was already present and should not be decoded again.
    Duplicate(BondedSymbolKey),
    /// The key was novel but rejected before retention would exceed the policy.
    RejectedByRetention {
        /// Symbol that was dropped.
        key: BondedSymbolKey,
        /// Memory-retention limit that rejected the symbol.
        reason: BondedReceiverRetentionRejectReason,
    },
}

/// Bounded receiver-retention policy for the shared bonded symbol set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BondedReceiverRetentionPolicy {
    /// Maximum retained unique symbols for one `(object_id, sbn)` block.
    pub max_symbols_per_block: Option<u32>,
    /// Maximum retained unique symbols across the whole bonded receiver set.
    pub max_total_symbols: Option<usize>,
}

impl BondedReceiverRetentionPolicy {
    /// No retention cap; preserves the original C2 receiver behavior.
    #[must_use]
    pub const fn unbounded() -> Self {
        Self {
            max_symbols_per_block: None,
            max_total_symbols: None,
        }
    }

    /// Build a policy with both per-block and transfer-wide retention caps.
    #[must_use]
    pub const fn bounded(max_symbols_per_block: u32, max_total_symbols: usize) -> Self {
        Self {
            max_symbols_per_block: Some(max_symbols_per_block),
            max_total_symbols: Some(max_total_symbols),
        }
    }
}

/// Why a bounded receiver-retention policy rejected a novel symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BondedReceiverRetentionRejectReason {
    /// Accepting the symbol would exceed the per-block retained-symbol cap.
    BlockSymbolCap,
    /// Accepting the symbol would exceed the transfer-wide retained-symbol cap.
    TransferSymbolCap,
}

/// Receiver coverage for one bonded RaptorQ source block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BondedBlockCoverage {
    /// RaptorQ object id shared by all bonded donors.
    pub object_id: ObjectId,
    /// Source block number within the object.
    pub sbn: u8,
    /// Accepted symbols needed before the block can stop asking for repair.
    pub target_symbols: u32,
    /// Globally novel symbols accepted for this block.
    pub accepted_symbols: u32,
    /// Additional symbols needed to reach `target_symbols`.
    pub deficit_symbols: u32,
}

impl BondedBlockCoverage {
    /// True when the block has reached or exceeded its target.
    #[must_use]
    pub const fn is_complete(self) -> bool {
        self.deficit_symbols == 0
    }
}

/// Receiver-side source-fast-path holes for one bonded RaptorQ source block.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BondedBlockSourceHoles {
    /// RaptorQ object id shared by all bonded donors.
    pub object_id: ObjectId,
    /// Source block number within the object.
    pub sbn: u8,
    /// Number of systematic source ESIs for this block.
    pub source_symbols: u32,
    /// Source ESIs still missing after global cross-donor deduplication.
    pub missing_source_esis: Vec<u32>,
}

impl BondedBlockSourceHoles {
    /// True when the receiver can stay on the source-only memcpy path.
    #[must_use]
    pub fn is_source_complete(&self) -> bool {
        self.missing_source_esis.is_empty()
    }

    /// Count missing systematic source symbols for this block.
    #[must_use]
    pub fn missing_source_count(&self) -> usize {
        self.missing_source_esis.len()
    }
}

/// Live receiver progress summary for a bonded transfer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BondedReceiverProgressSnapshot {
    /// Aggregate symbol ingress counters.
    pub aggregate: BondedReceiverIngressStats,
    /// Number of source blocks included in this snapshot.
    pub total_blocks: usize,
    /// Blocks whose accepted symbols meet their target.
    pub complete_blocks: usize,
    /// Blocks still below their target.
    pub incomplete_blocks: usize,
    /// Sum of all incomplete block deficits.
    pub total_deficit_symbols: u64,
}

impl BondedReceiverProgressSnapshot {
    /// True when every tracked block is complete.
    #[must_use]
    pub const fn is_complete(self) -> bool {
        self.incomplete_blocks == 0
    }

    /// Aggregate duplicate rate in parts-per-million.
    #[must_use]
    pub fn duplicate_rate_ppm(self) -> u64 {
        self.aggregate.duplicate_rate_ppm()
    }
}

/// Broadcast feedback computed from aggregate bonded receiver progress.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BondedReceiverFeedbackPlan {
    /// Donor control connections that should receive every feedback action.
    pub donor_targets: Vec<u32>,
    /// Missing systematic/source ESIs to request before generic repair.
    pub source_first_need_more: Vec<BondedBlockSourceHoles>,
    /// Aggregate block deficits to broadcast as NeedMore.
    pub need_more: Vec<BondedBlockCoverage>,
    /// True when the receiver should broadcast ObjectComplete/Close.
    pub close: bool,
    /// Progress snapshot used to derive the plan.
    pub progress: BondedReceiverProgressSnapshot,
}

/// One control action to send to one bonded donor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BondedReceiverFeedbackAction {
    /// Ask one donor for missing systematic/source ESIs first.
    SourceFirstNeedMore {
        /// Donor control connection that should receive the request.
        donor_index: u32,
        /// Missing source symbols for one source block.
        holes: BondedBlockSourceHoles,
    },
    /// Ask one donor for generic repair symbols for one source block.
    RepairNeedMore {
        /// Donor control connection that should receive the request.
        donor_index: u32,
        /// Aggregate block deficit after cross-donor deduplication.
        coverage: BondedBlockCoverage,
    },
    /// Tell one donor to stop spraying a verified-complete transfer.
    Close {
        /// Donor control connection that should receive the close.
        donor_index: u32,
    },
}

/// Per-donor metrics exposed by the bonded receiver progress snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BondedDonorProgressMetrics {
    /// Donor these counters describe.
    pub donor_index: u32,
    /// Raw ingress counters for this donor.
    pub stats: BondedDonorIngressStats,
    /// Duplicate rate for this donor in parts-per-million.
    pub duplicate_rate_ppm: u64,
}

/// Receiver completion path for one source block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BondedBlockCompletionPath {
    /// The block still needs more symbols before decode/commit.
    Incomplete,
    /// All systematic/source symbols are present; receiver can stay memcpy-only.
    SourceMemcpy,
    /// Enough symbols are present, but repair/FEC decode is needed for source holes.
    RepairDecode,
}

impl BondedBlockCompletionPath {
    /// Stable trace/display token for this completion path.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Incomplete => "incomplete",
            Self::SourceMemcpy => "source_memcpy",
            Self::RepairDecode => "repair_decode",
        }
    }
}

/// Machine-readable per-block receiver progress row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BondedBlockProgressMetrics {
    /// RaptorQ object id shared by all bonded donors.
    pub object_id: ObjectId,
    /// Source block number within the object.
    pub sbn: u8,
    /// Accepted symbols needed before the block can stop asking for repair.
    pub target_symbols: u32,
    /// Globally novel symbols accepted for this block.
    pub accepted_symbols: u32,
    /// Additional symbols needed to reach `target_symbols`.
    pub deficit_symbols: u32,
    /// Number of systematic/source ESIs for this block.
    pub source_symbols: u32,
    /// Source ESIs still missing after global cross-donor deduplication.
    pub missing_source_esis: Vec<u32>,
    /// Completion path implied by aggregate coverage and source holes.
    pub completion_path: BondedBlockCompletionPath,
}

impl BondedBlockProgressMetrics {
    /// Count missing systematic/source symbols for this block.
    #[must_use]
    pub fn missing_source_count(&self) -> usize {
        self.missing_source_esis.len()
    }

    /// True when this row represents a block that still needs receiver feedback.
    #[must_use]
    pub const fn needs_more_symbols(&self) -> bool {
        self.deficit_symbols > 0
    }
}

/// Machine-readable bonded receiver progress snapshot for SDK/CLI/trace consumers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BondedReceiverLiveProgressMetrics {
    /// Aggregate symbol ingress counters.
    pub aggregate: BondedReceiverIngressStats,
    /// Sorted per-donor ingress counters.
    pub donors: Vec<BondedDonorProgressMetrics>,
    /// Per-block coverage and completion-path rows.
    pub blocks: Vec<BondedBlockProgressMetrics>,
    /// Blocks that can complete through source memcpy.
    pub source_memcpy_blocks: usize,
    /// Blocks that are symbol-complete but need repair/FEC decode.
    pub repair_decode_blocks: usize,
    /// Blocks still below their accepted-symbol target.
    pub incomplete_blocks: usize,
    /// Sum of all incomplete block deficits.
    pub total_deficit_symbols: u64,
    /// Sum of all missing systematic/source ESIs.
    pub total_missing_source_symbols: u64,
    /// Per-donor feedback frames materialized by the current aggregate plan.
    pub feedback_action_count: usize,
    /// Per-donor NeedMore frames materialized by the current aggregate plan.
    pub need_more_action_count: usize,
    /// Per-donor Close frames materialized by the current aggregate plan.
    pub close_action_count: usize,
}

impl BondedReceiverLiveProgressMetrics {
    /// Aggregate duplicate rate in parts-per-million.
    #[must_use]
    pub fn duplicate_rate_ppm(&self) -> u64 {
        self.aggregate.duplicate_rate_ppm()
    }

    /// Emit the structured progress event and, when `ATP_BOND_TRACE` is set, a
    /// deterministic human-readable receiver timeline.
    pub fn trace_progress(&self, cx: &Cx, phase: &str) {
        let donors = self.donors.len().to_string();
        let blocks = self.blocks.len().to_string();
        let symbols_received = self.aggregate.symbols_received.to_string();
        let symbols_accepted = self.aggregate.symbols_accepted.to_string();
        let duplicate_symbols = self.aggregate.duplicate_symbols.to_string();
        let duplicate_rate_ppm = self.duplicate_rate_ppm().to_string();
        let source_symbols_accepted = self.aggregate.source_symbols_accepted.to_string();
        let repair_symbols_accepted = self.aggregate.repair_symbols_accepted.to_string();
        let retention_rejects = self.aggregate.symbols_rejected_by_retention.to_string();
        let source_memcpy_blocks = self.source_memcpy_blocks.to_string();
        let repair_decode_blocks = self.repair_decode_blocks.to_string();
        let incomplete_blocks = self.incomplete_blocks.to_string();
        let total_deficit_symbols = self.total_deficit_symbols.to_string();
        let total_missing_source_symbols = self.total_missing_source_symbols.to_string();
        let feedback_action_count = self.feedback_action_count.to_string();
        let need_more_action_count = self.need_more_action_count.to_string();
        let close_action_count = self.close_action_count.to_string();
        cx.trace_with_fields(
            BONDING_RECEIVER_PROGRESS_TRACE_EVENT,
            &[
                ("phase", phase),
                ("donors", donors.as_str()),
                ("blocks", blocks.as_str()),
                ("symbols_received", symbols_received.as_str()),
                ("symbols_accepted", symbols_accepted.as_str()),
                ("duplicate_symbols", duplicate_symbols.as_str()),
                ("duplicate_rate_ppm", duplicate_rate_ppm.as_str()),
                ("source_symbols_accepted", source_symbols_accepted.as_str()),
                ("repair_symbols_accepted", repair_symbols_accepted.as_str()),
                ("retention_rejects", retention_rejects.as_str()),
                ("source_memcpy_blocks", source_memcpy_blocks.as_str()),
                ("repair_decode_blocks", repair_decode_blocks.as_str()),
                ("incomplete_blocks", incomplete_blocks.as_str()),
                ("total_deficit_symbols", total_deficit_symbols.as_str()),
                (
                    "total_missing_source_symbols",
                    total_missing_source_symbols.as_str(),
                ),
                ("feedback_actions", feedback_action_count.as_str()),
                ("need_more_actions", need_more_action_count.as_str()),
                ("close_actions", close_action_count.as_str()),
            ],
        );

        if std::env::var_os(ATP_BOND_TRACE_ENV).is_some() {
            for line in self.trace_lines(phase) {
                eprintln!("[ATP_BOND_TRACE] {line}");
            }
        }
    }

    /// Deterministic human timeline rows for tests, logs, and diagnostic UIs.
    #[must_use]
    pub fn trace_lines(&self, phase: &str) -> Vec<String> {
        let mut lines = Vec::with_capacity(
            1usize
                .saturating_add(self.donors.len())
                .saturating_add(self.blocks.len()),
        );
        lines.push(format!(
            "receiver phase={phase} donors={} blocks={} accepted={}/{} duplicate_rate_ppm={} source={} repair={} retention_rejects={} source_memcpy_blocks={} repair_decode_blocks={} incomplete_blocks={} total_deficit_symbols={} missing_source_symbols={} feedback_actions={} need_more_actions={} close_actions={}",
            self.donors.len(),
            self.blocks.len(),
            self.aggregate.symbols_accepted,
            self.aggregate.symbols_received,
            self.duplicate_rate_ppm(),
            self.aggregate.source_symbols_accepted,
            self.aggregate.repair_symbols_accepted,
            self.aggregate.symbols_rejected_by_retention,
            self.source_memcpy_blocks,
            self.repair_decode_blocks,
            self.incomplete_blocks,
            self.total_deficit_symbols,
            self.total_missing_source_symbols,
            self.feedback_action_count,
            self.need_more_action_count,
            self.close_action_count,
        ));
        for donor in &self.donors {
            lines.push(format!(
                "receiver donor={} received={} accepted={} duplicates={} duplicate_rate_ppm={} source={} repair={} retention_rejects={}",
                donor.donor_index,
                donor.stats.symbols_received,
                donor.stats.symbols_accepted,
                donor.stats.duplicate_symbols,
                donor.duplicate_rate_ppm,
                donor.stats.source_symbols_accepted,
                donor.stats.repair_symbols_accepted,
                donor.stats.symbols_rejected_by_retention,
            ));
        }
        for block in &self.blocks {
            lines.push(format!(
                "receiver block object={:?} sbn={} target={} accepted={} deficit={} source_symbols={} missing_source={} completion_path={}",
                block.object_id,
                block.sbn,
                block.target_symbols,
                block.accepted_symbols,
                block.deficit_symbols,
                block.source_symbols,
                block.missing_source_count(),
                block.completion_path.as_str(),
            ));
        }
        lines
    }
}

impl BondedReceiverFeedbackPlan {
    /// True when there is no feedback to broadcast.
    #[must_use]
    pub fn is_idle(&self) -> bool {
        !self.should_broadcast_need_more() && !self.should_broadcast_close()
    }

    /// True when at least one donor target should receive a NeedMore frame.
    #[must_use]
    pub fn should_broadcast_need_more(&self) -> bool {
        !self.donor_targets.is_empty()
            && (!self.source_first_need_more.is_empty() || !self.need_more.is_empty())
    }

    /// True when NeedMore should ask for missing systematic/source ESIs first.
    #[must_use]
    pub fn should_broadcast_source_first_need_more(&self) -> bool {
        !self.donor_targets.is_empty() && !self.source_first_need_more.is_empty()
    }

    /// True when NeedMore should fall back to generic repair deficits.
    #[must_use]
    pub fn should_broadcast_repair_need_more(&self) -> bool {
        !self.donor_targets.is_empty() && !self.need_more.is_empty()
    }

    /// True when at least one donor target should receive ObjectComplete/Close.
    #[must_use]
    pub fn should_broadcast_close(&self) -> bool {
        self.close && !self.donor_targets.is_empty()
    }

    /// Materialize the per-donor control fan-out for this aggregate plan.
    ///
    /// Close wins over stale deficits: once the object is verified complete,
    /// every donor receives exactly one close action and no donor receives
    /// another `NeedMore`.
    #[must_use]
    pub fn broadcast_actions(&self) -> Vec<BondedReceiverFeedbackAction> {
        if self.should_broadcast_close() {
            return self
                .donor_targets
                .iter()
                .copied()
                .map(|donor_index| BondedReceiverFeedbackAction::Close { donor_index })
                .collect();
        }

        if !self.should_broadcast_need_more() {
            return Vec::new();
        }

        let mut actions = Vec::new();
        for donor_index in self.donor_targets.iter().copied() {
            actions.extend(self.source_first_need_more.iter().cloned().map(|holes| {
                BondedReceiverFeedbackAction::SourceFirstNeedMore { donor_index, holes }
            }));
            actions.extend(self.need_more.iter().copied().map(|coverage| {
                BondedReceiverFeedbackAction::RepairNeedMore {
                    donor_index,
                    coverage,
                }
            }));
        }
        actions
    }
}

/// Receiver-side C2 registry for authenticated donor symbols.
#[derive(Debug, Clone, Default)]
pub struct BondedReceiverSymbolSet {
    seen: BTreeSet<BondedSymbolKey>,
    source_seen: BTreeSet<BondedSymbolKey>,
    donor_stats: BTreeMap<u32, BondedDonorIngressStats>,
    aggregate: BondedReceiverIngressStats,
}

impl BondedReceiverSymbolSet {
    /// Create an empty unified symbol set.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            seen: BTreeSet::new(),
            source_seen: BTreeSet::new(),
            donor_stats: BTreeMap::new(),
            aggregate: BondedReceiverIngressStats {
                symbols_received: 0,
                symbols_accepted: 0,
                duplicate_symbols: 0,
                source_symbols_accepted: 0,
                repair_symbols_accepted: 0,
                symbols_rejected_by_retention: 0,
                donor_count: 0,
            },
        }
    }

    /// Record an authenticated symbol from `donor_index`.
    ///
    /// The returned [`BondedSymbolDisposition::Accepted`] path is the only path
    /// that should feed decode/persistence. Duplicate symbols are counted for
    /// telemetry and then dropped.
    pub fn record_symbol(&mut self, donor_index: u32, symbol: &Symbol) -> BondedSymbolDisposition {
        self.record_symbol_id(donor_index, symbol.id(), symbol.kind())
    }

    /// Record an authenticated symbol id from `donor_index`.
    pub fn record_symbol_id(
        &mut self,
        donor_index: u32,
        symbol_id: SymbolId,
        kind: SymbolKind,
    ) -> BondedSymbolDisposition {
        self.record_key(
            donor_index,
            BondedSymbolKey::from_symbol_id(symbol_id),
            kind,
        )
    }

    /// Record an authenticated bonded key from `donor_index`.
    pub fn record_key(
        &mut self,
        donor_index: u32,
        key: BondedSymbolKey,
        kind: SymbolKind,
    ) -> BondedSymbolDisposition {
        self.record_key_with_retention(
            donor_index,
            key,
            kind,
            BondedReceiverRetentionPolicy::unbounded(),
        )
    }

    /// Record an authenticated bonded key under a bounded retention policy.
    ///
    /// Duplicate keys are detected before retention checks, so duplicate donor
    /// retransmits never consume memory and remain observable as duplicates even
    /// when the block or transfer is at capacity. Novel over-cap symbols are
    /// rejected before they enter `seen`/`source_seen`, preserving a hard bound
    /// for callers that opt into this path.
    pub fn record_key_with_retention(
        &mut self,
        donor_index: u32,
        key: BondedSymbolKey,
        kind: SymbolKind,
        retention: BondedReceiverRetentionPolicy,
    ) -> BondedSymbolDisposition {
        let duplicate = self.seen.contains(&key);
        let retention_reject_reason = if duplicate {
            None
        } else {
            self.retention_reject_reason(key, retention)
        };

        let was_new_donor = !self.donor_stats.contains_key(&donor_index);
        let donor = self.donor_stats.entry(donor_index).or_default();
        if was_new_donor {
            self.aggregate.donor_count += 1;
        }

        donor.record_received();
        self.aggregate.symbols_received = self.aggregate.symbols_received.saturating_add(1);

        if duplicate {
            donor.record_duplicate();
            self.aggregate.duplicate_symbols = self.aggregate.duplicate_symbols.saturating_add(1);
            BondedSymbolDisposition::Duplicate(key)
        } else if let Some(reason) = retention_reject_reason {
            donor.record_retention_reject();
            self.aggregate.symbols_rejected_by_retention = self
                .aggregate
                .symbols_rejected_by_retention
                .saturating_add(1);
            BondedSymbolDisposition::RejectedByRetention { key, reason }
        } else {
            self.seen.insert(key);
            let source_symbol = kind.is_source();
            if source_symbol {
                self.source_seen.insert(key);
            }
            donor.record_accepted(kind);
            self.aggregate.symbols_accepted = self.aggregate.symbols_accepted.saturating_add(1);
            if source_symbol {
                self.aggregate.source_symbols_accepted =
                    self.aggregate.source_symbols_accepted.saturating_add(1);
            } else {
                self.aggregate.repair_symbols_accepted =
                    self.aggregate.repair_symbols_accepted.saturating_add(1);
            }
            BondedSymbolDisposition::Accepted(key)
        }
    }

    fn retention_reject_reason(
        &self,
        key: BondedSymbolKey,
        retention: BondedReceiverRetentionPolicy,
    ) -> Option<BondedReceiverRetentionRejectReason> {
        if retention
            .max_total_symbols
            .is_some_and(|max_total| self.seen.len() >= max_total)
        {
            return Some(BondedReceiverRetentionRejectReason::TransferSymbolCap);
        }

        if retention
            .max_symbols_per_block
            .is_some_and(|max_block| self.block_symbol_count(key.object_id, key.sbn) >= max_block)
        {
            return Some(BondedReceiverRetentionRejectReason::BlockSymbolCap);
        }

        None
    }

    fn block_symbol_count(&self, object_id: ObjectId, sbn: u8) -> u32 {
        self.seen
            .iter()
            .filter(|key| key.object_id == object_id && key.sbn == sbn)
            .count()
            .min(u32::MAX as usize) as u32
    }

    /// Return true if the unified set already contains `key`.
    #[must_use]
    pub fn contains(&self, key: BondedSymbolKey) -> bool {
        self.seen.contains(&key)
    }

    /// Number of globally novel symbols accepted so far.
    #[must_use]
    pub fn len(&self) -> usize {
        self.seen.len()
    }

    /// Return true when no novel symbols have been accepted.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.seen.is_empty()
    }

    /// Aggregate ingress counters.
    #[must_use]
    pub const fn aggregate_stats(&self) -> BondedReceiverIngressStats {
        self.aggregate
    }

    /// Per-donor ingress counters, if that donor has sent at least one symbol.
    #[must_use]
    pub fn donor_stats(&self, donor_index: u32) -> Option<BondedDonorIngressStats> {
        self.donor_stats.get(&donor_index).copied()
    }

    /// Sorted donor indexes that have contributed authenticated symbols.
    #[must_use]
    pub fn donor_targets(&self) -> Vec<u32> {
        self.donor_stats.keys().copied().collect()
    }

    /// Compute aggregate coverage for one source block.
    ///
    /// The count is global across donors and deduplicated by `(object_id, sbn,
    /// esi)`, so duplicate donor retransmits cannot hide a remaining deficit.
    #[must_use]
    pub fn block_coverage(
        &self,
        object_id: ObjectId,
        sbn: u8,
        target_symbols: u32,
    ) -> BondedBlockCoverage {
        let accepted_symbols = self
            .seen
            .iter()
            .filter(|key| key.object_id == object_id && key.sbn == sbn)
            .count()
            .min(u32::MAX as usize) as u32;
        BondedBlockCoverage {
            object_id,
            sbn,
            target_symbols,
            accepted_symbols,
            deficit_symbols: target_symbols.saturating_sub(accepted_symbols),
        }
    }

    /// Return missing systematic/source ESIs for one block.
    ///
    /// B4 source-first feedback uses this before generic repair requests: repair
    /// ESIs can make the block decodable, but only source ESIs preserve the
    /// receiver's memcpy fast path. Duplicate donor retransmits are ignored by
    /// the shared `(object_id, sbn, esi)` set before holes are computed.
    #[must_use]
    pub fn block_source_holes(
        &self,
        object_id: ObjectId,
        sbn: u8,
        source_symbols: u32,
    ) -> BondedBlockSourceHoles {
        let missing_source_esis = (0..source_symbols)
            .filter(|esi| {
                !self
                    .source_seen
                    .contains(&BondedSymbolKey::new(object_id, sbn, *esi))
            })
            .collect();

        BondedBlockSourceHoles {
            object_id,
            sbn,
            source_symbols,
            missing_source_esis,
        }
    }

    /// Return only blocks that still need systematic/source retransmits.
    #[must_use]
    pub fn blocks_with_source_holes(
        &self,
        blocks: impl IntoIterator<Item = (ObjectId, u8, u32)>,
    ) -> Vec<BondedBlockSourceHoles> {
        blocks
            .into_iter()
            .map(|(object_id, sbn, source_symbols)| {
                self.block_source_holes(object_id, sbn, source_symbols)
            })
            .filter(|holes| !holes.is_source_complete())
            .collect()
    }

    /// Return coverage rows only for blocks that still need repair symbols.
    #[must_use]
    pub fn blocks_needing_more(
        &self,
        blocks: impl IntoIterator<Item = (ObjectId, u8, u32)>,
    ) -> Vec<BondedBlockCoverage> {
        blocks
            .into_iter()
            .map(|(object_id, sbn, target_symbols)| {
                self.block_coverage(object_id, sbn, target_symbols)
            })
            .filter(|coverage| !coverage.is_complete())
            .collect()
    }

    /// Build a live progress snapshot over the receiver's expected blocks.
    #[must_use]
    pub fn progress_snapshot(
        &self,
        blocks: impl IntoIterator<Item = (ObjectId, u8, u32)>,
    ) -> BondedReceiverProgressSnapshot {
        let mut total_blocks = 0usize;
        let mut complete_blocks = 0usize;
        let mut total_deficit_symbols = 0u64;

        for (object_id, sbn, target_symbols) in blocks {
            total_blocks = total_blocks.saturating_add(1);
            let coverage = self.block_coverage(object_id, sbn, target_symbols);
            if coverage.is_complete() {
                complete_blocks = complete_blocks.saturating_add(1);
            } else {
                total_deficit_symbols =
                    total_deficit_symbols.saturating_add(u64::from(coverage.deficit_symbols));
            }
        }

        BondedReceiverProgressSnapshot {
            aggregate: self.aggregate,
            total_blocks,
            complete_blocks,
            incomplete_blocks: total_blocks.saturating_sub(complete_blocks),
            total_deficit_symbols,
        }
    }

    /// Build a machine-readable progress row for one source block.
    #[must_use]
    pub fn block_progress_metrics(
        &self,
        object_id: ObjectId,
        sbn: u8,
        target_symbols: u32,
    ) -> BondedBlockProgressMetrics {
        let coverage = self.block_coverage(object_id, sbn, target_symbols);
        let source_holes = self.block_source_holes(object_id, sbn, target_symbols);
        let completion_path = if !coverage.is_complete() {
            BondedBlockCompletionPath::Incomplete
        } else if source_holes.is_source_complete() {
            BondedBlockCompletionPath::SourceMemcpy
        } else {
            BondedBlockCompletionPath::RepairDecode
        };

        BondedBlockProgressMetrics {
            object_id,
            sbn,
            target_symbols: coverage.target_symbols,
            accepted_symbols: coverage.accepted_symbols,
            deficit_symbols: coverage.deficit_symbols,
            source_symbols: source_holes.source_symbols,
            missing_source_esis: source_holes.missing_source_esis,
            completion_path,
        }
    }

    /// Build the bonded receiver's live progress metrics.
    ///
    /// This is the C5 handoff for structured trace/SDK/CLI consumers: one
    /// deterministic snapshot carries sorted per-donor counters, per-block
    /// coverage/source-hole rows, source-vs-repair completion counters, and the
    /// current aggregate feedback fan-out size.
    #[must_use]
    pub fn live_progress_metrics(
        &self,
        blocks: impl IntoIterator<Item = (ObjectId, u8, u32)>,
        object_verified_complete: bool,
    ) -> BondedReceiverLiveProgressMetrics {
        let block_list: Vec<_> = blocks.into_iter().collect();
        let block_metrics: Vec<_> = block_list
            .iter()
            .copied()
            .map(|(object_id, sbn, target_symbols)| {
                self.block_progress_metrics(object_id, sbn, target_symbols)
            })
            .collect();

        let mut source_memcpy_blocks = 0usize;
        let mut repair_decode_blocks = 0usize;
        let mut incomplete_blocks = 0usize;
        let mut total_deficit_symbols = 0u64;
        let mut total_missing_source_symbols = 0u64;
        for block in &block_metrics {
            match block.completion_path {
                BondedBlockCompletionPath::Incomplete => {
                    incomplete_blocks = incomplete_blocks.saturating_add(1);
                }
                BondedBlockCompletionPath::SourceMemcpy => {
                    source_memcpy_blocks = source_memcpy_blocks.saturating_add(1);
                }
                BondedBlockCompletionPath::RepairDecode => {
                    repair_decode_blocks = repair_decode_blocks.saturating_add(1);
                }
            }
            total_deficit_symbols =
                total_deficit_symbols.saturating_add(u64::from(block.deficit_symbols));
            total_missing_source_symbols = total_missing_source_symbols
                .saturating_add(block.missing_source_count().min(u64::MAX as usize) as u64);
        }

        let feedback_actions = self
            .feedback_broadcast_plan(block_list.iter().copied(), object_verified_complete)
            .broadcast_actions();
        let mut need_more_action_count = 0usize;
        let mut close_action_count = 0usize;
        for action in &feedback_actions {
            match action {
                BondedReceiverFeedbackAction::SourceFirstNeedMore { .. }
                | BondedReceiverFeedbackAction::RepairNeedMore { .. } => {
                    need_more_action_count = need_more_action_count.saturating_add(1);
                }
                BondedReceiverFeedbackAction::Close { .. } => {
                    close_action_count = close_action_count.saturating_add(1);
                }
            }
        }

        BondedReceiverLiveProgressMetrics {
            aggregate: self.aggregate,
            donors: self
                .donor_stats
                .iter()
                .map(|(&donor_index, &stats)| BondedDonorProgressMetrics {
                    donor_index,
                    stats,
                    duplicate_rate_ppm: stats.duplicate_rate_ppm(),
                })
                .collect(),
            blocks: block_metrics,
            source_memcpy_blocks,
            repair_decode_blocks,
            incomplete_blocks,
            total_deficit_symbols,
            total_missing_source_symbols,
            feedback_action_count: feedback_actions.len(),
            need_more_action_count,
            close_action_count,
        }
    }

    /// Compute aggregate feedback that should be broadcast to every donor.
    ///
    /// `object_verified_complete` is the receiver's fail-closed byte/object
    /// verification result. Once true, Close wins over any stale per-block
    /// deficit so no donor keeps spraying into a completed transfer.
    ///
    /// Missing systematic/source ESIs are reported separately from generic
    /// repair deficits. Control-plane callers should prefer
    /// `source_first_need_more` before falling back to `need_more` so clean and
    /// near-clean bonded transfers can complete through the memcpy source path
    /// instead of spending receiver CPU on RaptorQ repair decode.
    #[must_use]
    pub fn feedback_broadcast_plan(
        &self,
        blocks: impl IntoIterator<Item = (ObjectId, u8, u32)>,
        object_verified_complete: bool,
    ) -> BondedReceiverFeedbackPlan {
        let block_list: Vec<_> = blocks.into_iter().collect();
        let progress = self.progress_snapshot(block_list.iter().copied());
        let (source_first_need_more, need_more) = if object_verified_complete {
            (Vec::new(), Vec::new())
        } else {
            (
                self.blocks_with_source_holes(block_list.iter().copied()),
                self.blocks_needing_more(block_list.iter().copied()),
            )
        };

        BondedReceiverFeedbackPlan {
            donor_targets: self.donor_targets(),
            source_first_need_more,
            need_more,
            close: object_verified_complete,
            progress,
        }
    }
}

fn duplicate_rate_ppm(duplicates: u64, received: u64) -> u64 {
    if received == 0 {
        return 0;
    }
    duplicates.saturating_mul(1_000_000) / received
}

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

    fn symbol(object: u64, sbn: u8, esi: u32, kind: SymbolKind) -> Symbol {
        Symbol::new(
            SymbolId::new_for_test(object, sbn, esi),
            vec![esi as u8],
            kind,
        )
    }

    #[test]
    fn multiple_donors_feed_one_unified_symbol_set() {
        let mut set = BondedReceiverSymbolSet::new();

        for esi in [0, 2, 4] {
            assert!(matches!(
                set.record_symbol(0, &symbol(7, 0, esi, SymbolKind::Source)),
                BondedSymbolDisposition::Accepted(_)
            ));
        }
        for esi in [1, 3, 5] {
            assert!(matches!(
                set.record_symbol(1, &symbol(7, 0, esi, SymbolKind::Repair)),
                BondedSymbolDisposition::Accepted(_)
            ));
        }

        assert_eq!(set.len(), 6);
        assert!(set.contains(BondedSymbolKey::new(ObjectId::new_for_test(7), 0, 5)));

        let aggregate = set.aggregate_stats();
        assert_eq!(aggregate.donor_count, 2);
        assert_eq!(aggregate.symbols_received, 6);
        assert_eq!(aggregate.symbols_accepted, 6);
        assert_eq!(aggregate.duplicate_symbols, 0);
        assert_eq!(aggregate.source_symbols_accepted, 3);
        assert_eq!(aggregate.repair_symbols_accepted, 3);

        let donor0 = set.donor_stats(0).expect("donor 0 stats");
        let donor1 = set.donor_stats(1).expect("donor 1 stats");
        assert_eq!(donor0.symbols_accepted, 3);
        assert_eq!(donor1.symbols_accepted, 3);
    }

    #[test]
    fn cross_donor_duplicate_esi_is_dropped_before_decode() {
        let mut set = BondedReceiverSymbolSet::new();
        let first = symbol(9, 2, 42, SymbolKind::Repair);
        let duplicate = symbol(9, 2, 42, SymbolKind::Repair);

        assert_eq!(
            set.record_symbol(0, &first),
            BondedSymbolDisposition::Accepted(BondedSymbolKey::from_symbol_id(first.id()))
        );
        assert_eq!(
            set.record_symbol(1, &duplicate),
            BondedSymbolDisposition::Duplicate(BondedSymbolKey::from_symbol_id(duplicate.id()))
        );

        assert_eq!(set.len(), 1);
        let aggregate = set.aggregate_stats();
        assert_eq!(aggregate.donor_count, 2);
        assert_eq!(aggregate.symbols_received, 2);
        assert_eq!(aggregate.symbols_accepted, 1);
        assert_eq!(aggregate.duplicate_symbols, 1);
        assert_eq!(aggregate.duplicate_rate_ppm(), 500_000);

        assert_eq!(
            set.donor_stats(1).expect("donor 1 stats").duplicate_symbols,
            1
        );
    }

    #[test]
    fn duplicate_symbols_do_not_inflate_accepted_kind_counters() {
        let mut set = BondedReceiverSymbolSet::new();
        let source = symbol(11, 0, 3, SymbolKind::Source);
        let repair = symbol(11, 0, 9, SymbolKind::Repair);

        assert!(matches!(
            set.record_symbol(0, &source),
            BondedSymbolDisposition::Accepted(_)
        ));
        assert!(matches!(
            set.record_symbol(0, &repair),
            BondedSymbolDisposition::Accepted(_)
        ));
        assert!(matches!(
            set.record_symbol(1, &source),
            BondedSymbolDisposition::Duplicate(_)
        ));
        assert!(matches!(
            set.record_symbol(1, &repair),
            BondedSymbolDisposition::Duplicate(_)
        ));

        let aggregate = set.aggregate_stats();
        assert_eq!(aggregate.symbols_received, 4);
        assert_eq!(aggregate.symbols_accepted, 2);
        assert_eq!(aggregate.duplicate_symbols, 2);
        assert_eq!(aggregate.source_symbols_accepted, 1);
        assert_eq!(aggregate.repair_symbols_accepted, 1);
        assert_eq!(aggregate.duplicate_rate_ppm(), 500_000);

        let donor1 = set.donor_stats(1).expect("donor 1 stats");
        assert_eq!(donor1.symbols_received, 2);
        assert_eq!(donor1.symbols_accepted, 0);
        assert_eq!(donor1.duplicate_symbols, 2);
        assert_eq!(donor1.source_symbols_accepted, 0);
        assert_eq!(donor1.repair_symbols_accepted, 0);
    }

    #[test]
    fn retention_policy_rejects_novel_symbols_after_block_cap_without_growing_set() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(12);
        let retention = BondedReceiverRetentionPolicy::bounded(2, 16);

        assert!(matches!(
            set.record_key_with_retention(
                0,
                BondedSymbolKey::new(object_id, 0, 0),
                SymbolKind::Source,
                retention,
            ),
            BondedSymbolDisposition::Accepted(_)
        ));
        assert!(matches!(
            set.record_key_with_retention(
                1,
                BondedSymbolKey::new(object_id, 0, 2),
                SymbolKind::Repair,
                retention,
            ),
            BondedSymbolDisposition::Accepted(_)
        ));

        assert_eq!(
            set.record_key_with_retention(
                2,
                BondedSymbolKey::new(object_id, 0, 3),
                SymbolKind::Repair,
                retention,
            ),
            BondedSymbolDisposition::RejectedByRetention {
                key: BondedSymbolKey::new(object_id, 0, 3),
                reason: BondedReceiverRetentionRejectReason::BlockSymbolCap,
            }
        );
        assert_eq!(
            set.record_key_with_retention(
                3,
                BondedSymbolKey::new(object_id, 0, 2),
                SymbolKind::Repair,
                retention,
            ),
            BondedSymbolDisposition::Duplicate(BondedSymbolKey::new(object_id, 0, 2))
        );

        assert_eq!(set.len(), 2);
        let aggregate = set.aggregate_stats();
        assert_eq!(aggregate.symbols_received, 4);
        assert_eq!(aggregate.symbols_accepted, 2);
        assert_eq!(aggregate.duplicate_symbols, 1);
        assert_eq!(aggregate.symbols_rejected_by_retention, 1);
        assert_eq!(
            set.donor_stats(2)
                .expect("donor 2 stats")
                .symbols_rejected_by_retention,
            1
        );
    }

    #[test]
    fn retention_policy_rejects_novel_symbols_after_transfer_cap() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(14);
        let retention = BondedReceiverRetentionPolicy::bounded(8, 2);

        set.record_key_with_retention(
            0,
            BondedSymbolKey::new(object_id, 0, 0),
            SymbolKind::Source,
            retention,
        );
        set.record_key_with_retention(
            1,
            BondedSymbolKey::new(object_id, 1, 0),
            SymbolKind::Source,
            retention,
        );

        assert_eq!(
            set.record_key_with_retention(
                2,
                BondedSymbolKey::new(object_id, 2, 0),
                SymbolKind::Source,
                retention,
            ),
            BondedSymbolDisposition::RejectedByRetention {
                key: BondedSymbolKey::new(object_id, 2, 0),
                reason: BondedReceiverRetentionRejectReason::TransferSymbolCap,
            }
        );
        assert_eq!(set.len(), 2);
        assert_eq!(set.aggregate_stats().symbols_rejected_by_retention, 1);
    }

    #[test]
    fn block_coverage_counts_deduplicated_symbols_across_donors() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(13);

        for (donor, esi) in [(0, 0), (1, 1), (2, 2), (3, 2)] {
            set.record_key(
                donor,
                BondedSymbolKey::new(object_id, 0, esi),
                SymbolKind::Repair,
            );
        }

        let coverage = set.block_coverage(object_id, 0, 4);

        assert_eq!(
            coverage,
            BondedBlockCoverage {
                object_id,
                sbn: 0,
                target_symbols: 4,
                accepted_symbols: 3,
                deficit_symbols: 1,
            }
        );
        assert!(!coverage.is_complete());

        set.record_key(4, BondedSymbolKey::new(object_id, 0, 3), SymbolKind::Repair);
        assert!(set.block_coverage(object_id, 0, 4).is_complete());
    }

    #[test]
    fn blocks_needing_more_reports_only_incomplete_blocks() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(17);
        set.record_key(0, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(1, BondedSymbolKey::new(object_id, 1, 0), SymbolKind::Source);
        set.record_key(1, BondedSymbolKey::new(object_id, 1, 2), SymbolKind::Repair);

        let needs_more = set.blocks_needing_more([(object_id, 0, 2), (object_id, 1, 2)]);

        assert_eq!(
            needs_more,
            vec![BondedBlockCoverage {
                object_id,
                sbn: 0,
                target_symbols: 2,
                accepted_symbols: 1,
                deficit_symbols: 1,
            }]
        );
    }

    #[test]
    fn progress_snapshot_summarizes_block_completion_and_deficit() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(19);
        set.record_key(0, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(1, BondedSymbolKey::new(object_id, 0, 2), SymbolKind::Repair);
        set.record_key(2, BondedSymbolKey::new(object_id, 1, 0), SymbolKind::Source);
        set.record_key(3, BondedSymbolKey::new(object_id, 1, 0), SymbolKind::Source);

        let snapshot = set.progress_snapshot([(object_id, 0, 2), (object_id, 1, 3)]);

        assert_eq!(snapshot.aggregate.symbols_received, 4);
        assert_eq!(snapshot.aggregate.symbols_accepted, 3);
        assert_eq!(snapshot.aggregate.duplicate_symbols, 1);
        assert_eq!(snapshot.duplicate_rate_ppm(), 250_000);
        assert_eq!(snapshot.total_blocks, 2);
        assert_eq!(snapshot.complete_blocks, 1);
        assert_eq!(snapshot.incomplete_blocks, 1);
        assert_eq!(snapshot.total_deficit_symbols, 2);
        assert!(!snapshot.is_complete());
    }

    #[test]
    fn progress_snapshot_with_no_blocks_is_complete() {
        let set = BondedReceiverSymbolSet::new();
        let snapshot = set.progress_snapshot(std::iter::empty::<(ObjectId, u8, u32)>());

        assert_eq!(snapshot.total_blocks, 0);
        assert_eq!(snapshot.complete_blocks, 0);
        assert_eq!(snapshot.incomplete_blocks, 0);
        assert_eq!(snapshot.total_deficit_symbols, 0);
        assert!(snapshot.is_complete());
    }

    #[test]
    fn live_progress_metrics_reports_donors_blocks_paths_and_feedback_counts() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(21);

        set.record_key(0, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(1, BondedSymbolKey::new(object_id, 0, 1), SymbolKind::Source);
        set.record_key(2, BondedSymbolKey::new(object_id, 0, 3), SymbolKind::Repair);
        set.record_key(3, BondedSymbolKey::new(object_id, 0, 1), SymbolKind::Source);
        set.record_key(0, BondedSymbolKey::new(object_id, 1, 0), SymbolKind::Source);

        let metrics = set.live_progress_metrics([(object_id, 0, 3), (object_id, 1, 2)], false);

        assert_eq!(metrics.aggregate.symbols_received, 5);
        assert_eq!(metrics.aggregate.symbols_accepted, 4);
        assert_eq!(metrics.aggregate.duplicate_symbols, 1);
        assert_eq!(metrics.aggregate.source_symbols_accepted, 3);
        assert_eq!(metrics.aggregate.repair_symbols_accepted, 1);
        assert_eq!(
            metrics
                .donors
                .iter()
                .map(|donor| donor.donor_index)
                .collect::<Vec<_>>(),
            vec![0, 1, 2, 3]
        );
        assert_eq!(metrics.donors[3].stats.duplicate_symbols, 1);
        assert_eq!(metrics.donors[3].duplicate_rate_ppm, 1_000_000);

        assert_eq!(metrics.blocks.len(), 2);
        assert_eq!(metrics.blocks[0].accepted_symbols, 3);
        assert_eq!(metrics.blocks[0].deficit_symbols, 0);
        assert_eq!(metrics.blocks[0].missing_source_esis, vec![2]);
        assert_eq!(
            metrics.blocks[0].completion_path,
            BondedBlockCompletionPath::RepairDecode
        );
        assert_eq!(metrics.blocks[1].accepted_symbols, 1);
        assert_eq!(metrics.blocks[1].deficit_symbols, 1);
        assert_eq!(metrics.blocks[1].missing_source_esis, vec![1]);
        assert_eq!(
            metrics.blocks[1].completion_path,
            BondedBlockCompletionPath::Incomplete
        );

        assert_eq!(metrics.source_memcpy_blocks, 0);
        assert_eq!(metrics.repair_decode_blocks, 1);
        assert_eq!(metrics.incomplete_blocks, 1);
        assert_eq!(metrics.total_deficit_symbols, 1);
        assert_eq!(metrics.total_missing_source_symbols, 2);
        assert_eq!(metrics.feedback_action_count, 12);
        assert_eq!(metrics.need_more_action_count, 12);
        assert_eq!(metrics.close_action_count, 0);
    }

    #[test]
    fn completion_paths_have_stable_trace_tokens() {
        assert_eq!(BondedBlockCompletionPath::Incomplete.as_str(), "incomplete");
        assert_eq!(
            BondedBlockCompletionPath::SourceMemcpy.as_str(),
            "source_memcpy"
        );
        assert_eq!(
            BondedBlockCompletionPath::RepairDecode.as_str(),
            "repair_decode"
        );
    }

    #[test]
    fn live_progress_metrics_trace_lines_cover_aggregate_donors_blocks_and_feedback() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(22);

        set.record_key(0, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(1, BondedSymbolKey::new(object_id, 0, 1), SymbolKind::Source);
        set.record_key(2, BondedSymbolKey::new(object_id, 0, 3), SymbolKind::Repair);
        set.record_key(3, BondedSymbolKey::new(object_id, 0, 1), SymbolKind::Source);
        set.record_key(0, BondedSymbolKey::new(object_id, 1, 0), SymbolKind::Source);

        let metrics = set.live_progress_metrics([(object_id, 0, 3), (object_id, 1, 2)], false);
        let lines = metrics.trace_lines("need_more");

        assert!(lines[0].contains("receiver phase=need_more donors=4 blocks=2 accepted=4/5"));
        assert!(lines[0].contains("duplicate_rate_ppm=200000"));
        assert!(lines[0].contains("need_more_actions=12"));
        assert!(lines[0].contains("close_actions=0"));
        assert!(lines.iter().any(|line| line.contains("donor=3")
            && line.contains("duplicates=1")
            && line.contains("duplicate_rate_ppm=1000000")));
        assert!(lines.iter().any(|line| line.contains("block object=")
            && line.contains("sbn=0")
            && line.contains("missing_source=1")
            && line.contains("completion_path=repair_decode")));
        assert!(lines.iter().any(|line| line.contains("block object=")
            && line.contains("sbn=1")
            && line.contains("deficit=1")
            && line.contains("completion_path=incomplete")));
    }

    #[test]
    fn feedback_plan_broadcasts_aggregate_need_more_to_all_donors() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(23);

        set.record_key(2, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(0, BondedSymbolKey::new(object_id, 0, 2), SymbolKind::Repair);
        set.record_key(1, BondedSymbolKey::new(object_id, 1, 0), SymbolKind::Source);
        set.record_key(2, BondedSymbolKey::new(object_id, 1, 0), SymbolKind::Source);

        let plan = set.feedback_broadcast_plan([(object_id, 0, 2), (object_id, 1, 3)], false);

        assert_eq!(plan.donor_targets, vec![0, 1, 2]);
        assert_eq!(
            plan.source_first_need_more,
            vec![
                BondedBlockSourceHoles {
                    object_id,
                    sbn: 0,
                    source_symbols: 2,
                    missing_source_esis: vec![1],
                },
                BondedBlockSourceHoles {
                    object_id,
                    sbn: 1,
                    source_symbols: 3,
                    missing_source_esis: vec![1, 2],
                },
            ]
        );
        assert_eq!(
            plan.need_more,
            vec![BondedBlockCoverage {
                object_id,
                sbn: 1,
                target_symbols: 3,
                accepted_symbols: 1,
                deficit_symbols: 2,
            }]
        );
        assert!(!plan.close);
        assert!(plan.should_broadcast_need_more());
        assert!(plan.should_broadcast_source_first_need_more());
        assert!(plan.should_broadcast_repair_need_more());
        assert!(!plan.should_broadcast_close());
        assert_eq!(plan.progress.total_deficit_symbols, 2);
    }

    #[test]
    fn feedback_plan_materializes_need_more_actions_for_every_donor() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(24);

        set.record_key(2, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(0, BondedSymbolKey::new(object_id, 0, 3), SymbolKind::Repair);

        let plan = set.feedback_broadcast_plan([(object_id, 0, 3)], false);
        let source_holes = BondedBlockSourceHoles {
            object_id,
            sbn: 0,
            source_symbols: 3,
            missing_source_esis: vec![1, 2],
        };
        let repair_deficit = BondedBlockCoverage {
            object_id,
            sbn: 0,
            target_symbols: 3,
            accepted_symbols: 2,
            deficit_symbols: 1,
        };

        assert_eq!(
            plan.broadcast_actions(),
            vec![
                BondedReceiverFeedbackAction::SourceFirstNeedMore {
                    donor_index: 0,
                    holes: source_holes.clone(),
                },
                BondedReceiverFeedbackAction::RepairNeedMore {
                    donor_index: 0,
                    coverage: repair_deficit,
                },
                BondedReceiverFeedbackAction::SourceFirstNeedMore {
                    donor_index: 2,
                    holes: source_holes,
                },
                BondedReceiverFeedbackAction::RepairNeedMore {
                    donor_index: 2,
                    coverage: repair_deficit,
                },
            ]
        );
    }

    #[test]
    fn feedback_plan_prefers_source_holes_even_when_repairs_meet_target() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(27);

        set.record_key(0, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(1, BondedSymbolKey::new(object_id, 0, 3), SymbolKind::Repair);
        set.record_key(2, BondedSymbolKey::new(object_id, 0, 4), SymbolKind::Repair);

        let plan = set.feedback_broadcast_plan([(object_id, 0, 3)], false);

        assert_eq!(plan.donor_targets, vec![0, 1, 2]);
        assert_eq!(
            plan.source_first_need_more,
            vec![BondedBlockSourceHoles {
                object_id,
                sbn: 0,
                source_symbols: 3,
                missing_source_esis: vec![1, 2],
            }]
        );
        assert!(plan.need_more.is_empty());
        assert!(plan.progress.is_complete());
        assert!(plan.should_broadcast_need_more());
        assert!(plan.should_broadcast_source_first_need_more());
        assert!(!plan.should_broadcast_repair_need_more());
        assert!(!plan.is_idle());
    }

    #[test]
    fn feedback_plan_close_suppresses_stale_need_more() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(29);

        set.record_key(1, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(0, BondedSymbolKey::new(object_id, 0, 4), SymbolKind::Repair);

        let plan = set.feedback_broadcast_plan([(object_id, 0, 4)], true);

        assert_eq!(plan.donor_targets, vec![0, 1]);
        assert!(plan.source_first_need_more.is_empty());
        assert!(plan.need_more.is_empty());
        assert!(plan.close);
        assert!(!plan.should_broadcast_need_more());
        assert!(!plan.should_broadcast_source_first_need_more());
        assert!(!plan.should_broadcast_repair_need_more());
        assert!(plan.should_broadcast_close());
        assert_eq!(plan.progress.total_deficit_symbols, 2);
        assert_eq!(
            plan.broadcast_actions(),
            vec![
                BondedReceiverFeedbackAction::Close { donor_index: 0 },
                BondedReceiverFeedbackAction::Close { donor_index: 1 },
            ]
        );

        let metrics = set.live_progress_metrics([(object_id, 0, 4)], true);
        assert_eq!(metrics.feedback_action_count, 2);
        assert_eq!(metrics.need_more_action_count, 0);
        assert_eq!(metrics.close_action_count, 2);
    }

    #[test]
    fn feedback_plan_without_donor_targets_is_not_broadcastable() {
        let set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(31);
        let plan = set.feedback_broadcast_plan([(object_id, 0, 1)], false);

        assert!(plan.donor_targets.is_empty());
        assert_eq!(plan.source_first_need_more.len(), 1);
        assert_eq!(plan.need_more.len(), 1);
        assert!(!plan.should_broadcast_need_more());
        assert!(!plan.should_broadcast_source_first_need_more());
        assert!(!plan.should_broadcast_repair_need_more());
        assert!(!plan.should_broadcast_close());
        assert_eq!(plan.progress.total_deficit_symbols, 1);
    }

    #[test]
    fn duplicate_scope_is_object_block_and_esi_not_just_esi() {
        let mut set = BondedReceiverSymbolSet::new();

        for symbol in [
            symbol(1, 0, 7, SymbolKind::Source),
            symbol(1, 1, 7, SymbolKind::Source),
            symbol(2, 0, 7, SymbolKind::Source),
        ] {
            assert!(matches!(
                set.record_symbol(0, &symbol),
                BondedSymbolDisposition::Accepted(_)
            ));
        }

        assert_eq!(set.len(), 3);
        assert_eq!(set.aggregate_stats().duplicate_symbols, 0);
    }

    #[test]
    fn source_holes_ignore_repair_symbols_and_duplicates() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(37);

        set.record_key(0, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(1, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(2, BondedSymbolKey::new(object_id, 0, 3), SymbolKind::Repair);

        let holes = set.block_source_holes(object_id, 0, 3);

        assert_eq!(
            holes,
            BondedBlockSourceHoles {
                object_id,
                sbn: 0,
                source_symbols: 3,
                missing_source_esis: vec![1, 2],
            }
        );
        assert!(!holes.is_source_complete());
        assert_eq!(holes.missing_source_count(), 2);

        set.record_key(0, BondedSymbolKey::new(object_id, 0, 1), SymbolKind::Source);
        set.record_key(1, BondedSymbolKey::new(object_id, 0, 2), SymbolKind::Source);

        assert!(set.block_source_holes(object_id, 0, 3).is_source_complete());
    }

    #[test]
    fn blocks_with_source_holes_filters_complete_blocks() {
        let mut set = BondedReceiverSymbolSet::new();
        let object_id = ObjectId::new_for_test(41);

        set.record_key(0, BondedSymbolKey::new(object_id, 0, 0), SymbolKind::Source);
        set.record_key(1, BondedSymbolKey::new(object_id, 0, 1), SymbolKind::Source);
        set.record_key(0, BondedSymbolKey::new(object_id, 1, 0), SymbolKind::Source);

        let holes = set.blocks_with_source_holes([(object_id, 0, 2), (object_id, 1, 2)]);

        assert_eq!(
            holes,
            vec![BondedBlockSourceHoles {
                object_id,
                sbn: 1,
                source_symbols: 2,
                missing_source_esis: vec![1],
            }]
        );
    }

    #[test]
    fn empty_set_reports_zero_duplicate_rate() {
        let set = BondedReceiverSymbolSet::new();

        assert!(set.is_empty());
        assert_eq!(set.aggregate_stats().duplicate_rate_ppm(), 0);
        assert_eq!(set.donor_stats(0), None);
    }
}