zakura-network 7.0.0

Networking code for the Zakura node. Internal crate, published to support cargo install zakura
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
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
//! The Sequencer's own serial task (Sequencer task boundary split).
//!
//! Sequencer task moves the consensus-critical commit pipeline (`Sequencer`: reorder →
//! applying → `SubmitBlock` → apply-finished) off the reactor's single thread
//! and into this spawned serial task. The reactor keeps issuance, peer matching,
//! serving, and the producer; peer routines forward block bodies over a bounded
//! body input channel, while the reactor forwards progress-critical control
//! events over a non-blocking control channel. The reactor learns committed
//! progress back over a non-blocking `watch` ([`SequencerView`]).
//!
//! Each input handler owns one stage of the commit pipeline: the body-acceptance
//! tail (`handle_accept_body`), the verified-tip frontier advance
//! (`handle_frontier_advance`), the chain-tip reset (`handle_frontier_reset`), and
//! the apply completion (`handle_apply_finished`). They mutate the `Sequencer`,
//! byte budget, and work queue directly and emit `SubmitBlock`/`Misbehavior`
//! actions on the same channel the reactor uses.

use super::{
    events::*,
    peer_registry::{retry_deadline_instant, PeerRegistry},
    reorder::BufferedBlockBody,
    sequencer::*,
    state::*,
    work_queue::WorkQueue,
    *,
};
use std::collections::BTreeSet;

mod trace;

/// Delay before retrying a verifier submission that could not enter the shared
/// action channel.
const SUBMISSION_RETRY_DELAY: Duration = Duration::from_millis(100);

/// A received body a peer routine matched (or accepted unmatched) and forwards
/// to the commit pipeline. This is the only bounded Sequencer input: a slow
/// verifier can backpressure body intake, but must not block apply/frontier
/// control events that release budget and drive the next scheduling reaction.
#[derive(Debug)]
pub(super) struct SequencedBody {
    pub(super) owner: zakura_header_chain::BodyWorkOwner,
    pub(super) source: zakura_header_chain::SourceId,
    pub(super) height: block::Height,
    pub(super) hash: block::Hash,
    pub(super) previous_block_hash: block::Hash,
    pub(super) body: BufferedBlockBody,
    pub(super) bytes: u64,
    pub(super) peer: ZakuraPeerId,
    pub(super) received_at: Instant,
    queue_accounting: SequencerInputAccounting,
}

impl SequencedBody {
    #[allow(clippy::too_many_arguments)]
    pub(super) fn new_queued(
        owner: zakura_header_chain::BodyWorkOwner,
        source: zakura_header_chain::SourceId,
        height: block::Height,
        hash: block::Hash,
        previous_block_hash: block::Hash,
        body: BufferedBlockBody,
        bytes: u64,
        peer: ZakuraPeerId,
        received_at: Instant,
        input_bytes: Arc<std::sync::atomic::AtomicU64>,
        input_decoded_attributed_memory_bytes: Arc<std::sync::atomic::AtomicU64>,
    ) -> Self {
        let decoded_attributed_memory_size_bytes = body.decoded_attributed_memory_size_bytes();
        Self {
            owner,
            source,
            height,
            hash,
            previous_block_hash,
            body,
            bytes,
            peer,
            received_at,
            queue_accounting: SequencerInputAccounting::new(
                input_bytes,
                bytes,
                input_decoded_attributed_memory_bytes,
                decoded_attributed_memory_size_bytes,
            ),
        }
    }

    /// Transfer this body out of queue ownership before processing it.
    pub(super) fn leave_queue(&mut self) {
        self.queue_accounting.release();
    }
}

#[derive(Debug)]
struct SequencerInputAccounting {
    input_bytes: Arc<std::sync::atomic::AtomicU64>,
    bytes: u64,
    input_decoded_attributed_memory_bytes: Arc<std::sync::atomic::AtomicU64>,
    decoded_attributed_memory_size_bytes: u64,
    active: bool,
}

impl SequencerInputAccounting {
    fn new(
        input_bytes: Arc<std::sync::atomic::AtomicU64>,
        bytes: u64,
        input_decoded_attributed_memory_bytes: Arc<std::sync::atomic::AtomicU64>,
        decoded_attributed_memory_size_bytes: u64,
    ) -> Self {
        add_atomic_bytes(&input_bytes, bytes);
        add_atomic_bytes(
            &input_decoded_attributed_memory_bytes,
            decoded_attributed_memory_size_bytes,
        );
        Self {
            input_bytes,
            bytes,
            input_decoded_attributed_memory_bytes,
            decoded_attributed_memory_size_bytes,
            active: true,
        }
    }

    fn release(&mut self) {
        if !std::mem::take(&mut self.active) {
            return;
        }
        release_atomic_bytes(&self.input_bytes, self.bytes);
        release_atomic_bytes(
            &self.input_decoded_attributed_memory_bytes,
            self.decoded_attributed_memory_size_bytes,
        );
    }
}

impl Drop for SequencerInputAccounting {
    fn drop(&mut self) {
        self.release();
    }
}

/// Progress-critical Sequencer events forwarded by the reactor.
///
/// These locally-generated events must not sit behind downloaded bodies, so
/// they use a separate prioritized channel.
#[derive(Debug)]
pub(super) enum SequencerControlInput {
    /// Reauthorize compatible body work under the latest exact authority.
    WorkAuthorityRefreshed {
        authority: zakura_header_chain::BodyWorkAuthority,
    },
    /// Retire body work after the header-chain engine invalidates its lineage.
    BodyWorkEpochChanged {
        authority: zakura_header_chain::BodyWorkAuthority,
        frontiers: BlockSyncFrontiers,
    },
    /// Refresh the global CAS coordinate used only by synchronous state writes.
    StateVersionChanged(zakura_header_chain::StateVersion),
    /// A committed transition cleared the persistent alarm for this exact work.
    BodyAlarmCleared {
        scope: zakura_header_chain::BodyWorkAuthority,
        hash: block::Hash,
    },
    /// A verified-tip advance (frontier growth/commit).
    FrontierAdvance {
        frontiers: BlockSyncFrontiers,
        release_applied: bool,
    },
    /// A chain-tip reset (reorg/checkpoint/coalesced update). The two `peer_*`
    /// bools are the peer-outstanding-derived halves of the reset decision,
    /// precomputed by the reactor (which owns peer state); the task ORs them with
    /// its own Sequencer-internal predicates.
    FrontierReset {
        frontiers: BlockSyncFrontiers,
        preserve_active_successors: bool,
        /// `peers.any(outstanding.end_height() >= tip+1)` — half of
        /// `has_active_successor_after`.
        peer_has_successor_after: bool,
        /// `peers.any(outstanding.expected_hash(tip) is Some(h) && h != hash)` —
        /// the peer-outstanding clause of `reset_tip_conflicts_with_local_work`.
        peer_outstanding_conflicts_at_tip: bool,
    },
    /// A verifier apply completion.
    ApplyFinished {
        owner: Box<zakura_header_chain::BodyWorkOwner>,
        source: zakura_header_chain::SourceId,
        token: BlockApplyToken,
        height: block::Height,
        hash: block::Hash,
        outcome: BlockApplyOutcome,
        eligible_sources: BTreeSet<zakura_header_chain::SourceId>,
        persisted_availability: Option<zakura_header_chain::BodyUnavailableSummary>,
        semantic_completion: Option<(
            zakura_header_chain::BodyWorkOwner,
            zakura_header_chain::StateVersion,
        )>,
    },
}

/// The progress view the reactor reacts to. A `watch` (latest-wins) send never
/// blocks, so the task never blocks on the reactor and the bounded input channel
/// cannot deadlock against it.
#[derive(Copy, Clone, Debug, PartialEq)]
pub(super) struct SequencerView {
    pub(super) verified_tip: block::Height,
    pub(super) verified_hash: block::Hash,
    pub(super) download_floor: block::Height,
    pub(super) finalized: block::Height,
    /// Increments only when the task performs a destructive `reset_to`, so the
    /// reactor distinguishes an advance (drop outstanding *through* tip) from a
    /// reset (drop *all* outstanding).
    pub(super) reset_epoch: u64,
    /// Increments once per processed frontier/reset/apply input (NOT per accepted
    /// body). The reactor runs its heavy serving/producer/schedule reaction only
    /// when this advances: a pure body buffer/submit needs nothing but the
    /// forwarding peer's own reschedule, while a frontier advance, reset, or
    /// apply-finished must re-query and reschedule.
    pub(super) reaction_epoch: u64,
    pub(super) reorder_len: u64,
    pub(super) applying_len: u64,
    pub(super) reorder_buffered_bytes: u64,
    pub(super) applying_buffered_bytes: u64,
    pub(super) sequencer_input_decoded_attributed_memory_bytes: u64,
    pub(super) reorder_decoded_attributed_memory_bytes: u64,
    pub(super) applying_decoded_attributed_memory_bytes: u64,
    pub(super) active_pipeline_decoded_attributed_memory_bytes: u64,
    pub(super) unsubmitted_applying_count: u64,
    /// Submitted decoded bodies awaiting matching completion, including entries
    /// detached from `applying` but still retained by the driver.
    pub(super) in_flight_submission_count: u64,
    pub(super) in_flight_submission_bytes: u64,
    pub(super) committed_bytes_per_sec: u64,
    pub(super) committed_blocks_per_sec: u64,
}

/// Build the initial view from the startup frontiers, before the task runs.
pub(super) fn initial_view(frontiers: BlockSyncFrontiers) -> SequencerView {
    SequencerView {
        verified_tip: frontiers.verified_block_tip,
        verified_hash: frontiers.verified_block_hash,
        download_floor: frontiers.verified_block_tip,
        finalized: frontiers.finalized_height,
        reset_epoch: 0,
        reaction_epoch: 0,
        reorder_len: 0,
        applying_len: 0,
        reorder_buffered_bytes: 0,
        applying_buffered_bytes: 0,
        sequencer_input_decoded_attributed_memory_bytes: 0,
        reorder_decoded_attributed_memory_bytes: 0,
        applying_decoded_attributed_memory_bytes: 0,
        active_pipeline_decoded_attributed_memory_bytes: 0,
        unsubmitted_applying_count: 0,
        in_flight_submission_count: 0,
        in_flight_submission_bytes: 0,
        committed_bytes_per_sec: 0,
        committed_blocks_per_sec: 0,
    }
}

/// The serial commit-pipeline task. Owns the `Sequencer` (moved out of state), a
/// `ByteBudget` clone, an `Arc<WorkQueue>` clone, an action sender clone, and the
/// committed throughput meter. Releases bytes directly and emits `SubmitBlock` /
/// `Misbehavior` on the same action channel the reactor uses.
pub(super) struct SequencerTask {
    sequencer: Sequencer,
    budget: ByteBudget,
    work: Arc<WorkQueue>,
    registry: Arc<PeerRegistry>,
    actions: mpsc::Sender<BlockSyncAction>,
    committed_throughput: ThroughputMeter,
    /// Tracks the finalized height so the published view carries it forward; the
    /// reactor folds it into its `finalized_height` mirror with a `max`.
    finalized_height: block::Height,
    verified_block_hash: block::Hash,
    reset_epoch: u64,
    reaction_epoch: u64,
    current_scope: Option<zakura_header_chain::BodyWorkAuthority>,
    /// Global CAS coordinate for synchronous alarm writes, never body-work authority.
    current_state_version: Option<zakura_header_chain::StateVersion>,
    body_retries: crate::zakura::header_sync::BodyRetryQueue,
    retry_jitter: crate::zakura::header_sync::SeededRetryJitter,
    body_input_rx: mpsc::Receiver<SequencedBody>,
    control_input_rx: mpsc::UnboundedReceiver<SequencerControlInput>,
    _body_input_bytes: Arc<std::sync::atomic::AtomicU64>,
    body_input_decoded_attributed_memory_bytes: Arc<std::sync::atomic::AtomicU64>,
    view_tx: watch::Sender<SequencerView>,
    action_send_timeout: Duration,
    submission_retry_at: Option<time::Instant>,
    submission_retry_started_at: Option<time::Instant>,
    submission_retry_attempt: u64,
    trace: ZakuraTrace,
}

impl Drop for SequencerTask {
    fn drop(&mut self) {
        self.body_input_rx.close();
        while self.body_input_rx.try_recv().is_ok() {}

        self.view_tx.send_modify(|view| {
            view.reorder_decoded_attributed_memory_bytes = 0;
            view.applying_decoded_attributed_memory_bytes = 0;
            view.sequencer_input_decoded_attributed_memory_bytes = 0;
            view.active_pipeline_decoded_attributed_memory_bytes = 0;
        });
    }
}

impl SequencerTask {
    #[allow(clippy::too_many_arguments)]
    pub(super) fn new(
        sequencer: Sequencer,
        budget: ByteBudget,
        work: Arc<WorkQueue>,
        registry: Arc<PeerRegistry>,
        actions: mpsc::Sender<BlockSyncAction>,
        committed_throughput: ThroughputMeter,
        frontiers: BlockSyncFrontiers,
        current_scope: Option<zakura_header_chain::BodyWorkAuthority>,
        retry_jitter: crate::zakura::header_sync::SeededRetryJitter,
        body_input_rx: mpsc::Receiver<SequencedBody>,
        control_input_rx: mpsc::UnboundedReceiver<SequencerControlInput>,
        body_input_bytes: Arc<std::sync::atomic::AtomicU64>,
        body_input_decoded_attributed_memory_bytes: Arc<std::sync::atomic::AtomicU64>,
        view_tx: watch::Sender<SequencerView>,
        action_send_timeout: Duration,
        trace: ZakuraTrace,
    ) -> Self {
        Self {
            sequencer,
            budget,
            work,
            registry,
            actions,
            committed_throughput,
            finalized_height: frontiers.finalized_height,
            verified_block_hash: frontiers.verified_block_hash,
            reset_epoch: 0,
            reaction_epoch: 0,
            current_scope,
            current_state_version: current_scope
                .map(|_| zakura_header_chain::StateVersion::default()),
            body_retries: crate::zakura::header_sync::BodyRetryQueue::default(),
            retry_jitter,
            body_input_rx,
            control_input_rx,
            _body_input_bytes: body_input_bytes,
            body_input_decoded_attributed_memory_bytes,
            view_tx,
            action_send_timeout,
            submission_retry_at: None,
            submission_retry_started_at: None,
            submission_retry_attempt: 0,
            trace,
        }
    }

    /// Seed the synchronous state-write coordinate from the startup snapshot.
    pub(super) fn with_initial_state_version(
        mut self,
        state_version: Option<zakura_header_chain::StateVersion>,
    ) -> Self {
        self.current_state_version = state_version.or(self.current_state_version);
        self
    }

    pub(super) async fn run(mut self) {
        // Track input closure explicitly so the loop exits once both inputs close:
        // a `select!` whose arms are all disabled with no `else` panics, so the
        // top-of-loop guard breaks out before the last open channel is gated off.
        let mut control_open = true;
        let mut body_open = true;
        loop {
            if !control_open && !body_open && self.submission_retry_at.is_none() {
                break;
            }
            let submission_retry_at = self.submission_retry_at;
            tokio::select! {
                biased;

                input = self.control_input_rx.recv(), if control_open => {
                    match input {
                        Some(input) => {
                            let needs_reaction = self.handle_control_input(input).await;
                            if needs_reaction {
                                self.reaction_epoch = self.reaction_epoch.saturating_add(1);
                            }
                            self.publish_view();
                        }
                        None => control_open = false,
                    }
                }

                _ = time::sleep_until(submission_retry_at.unwrap_or_else(time::Instant::now)),
                    if submission_retry_at.is_some() =>
                {
                    self.submission_retry_at = None;
                    self.submit_pending_blocks().await;
                    self.publish_view();
                }

                body = self.body_input_rx.recv(), if body_open => {
                    match body {
                        Some(mut body) => {
                            body.leave_queue();
                            self.handle_accept_body(body);
                            // Publish the synchronous queue → reorder/applying ownership
                            // transfer before an action-channel send can await or time out.
                            // This updates observability without waking scheduling watchers.
                            self.publish_decoded_ownership_view();
                            self.submit_pending_blocks().await;
                            self.publish_view();
                        }
                        None => body_open = false,
                    }
                }
            }
        }
    }

    async fn handle_control_input(&mut self, input: SequencerControlInput) -> bool {
        // Each handler reports whether it did work that needs the reactor's heavy
        // serving/producer/schedule tail. Bumping `reaction_epoch` only then keeps
        // the reactor from re-querying/-scheduling on a pure body buffer/submit or
        // a no-op (stale/duplicate) apply completion.
        match input {
            SequencerControlInput::WorkAuthorityRefreshed { authority } => {
                debug_assert!(self
                    .current_scope
                    .is_none_or(|old| { old.body_work_epoch == authority.body_work_epoch }));
                self.current_scope = Some(authority);
                self.registry.refresh_body_retry_scope(authority);
                self.body_retries
                    .refresh_scope(authority.header_generation, authority.branch);
                false
            }
            SequencerControlInput::BodyWorkEpochChanged {
                authority,
                frontiers,
            } => {
                debug_assert!(self
                    .current_scope
                    .is_none_or(|old| { old.body_work_epoch != authority.body_work_epoch }));
                self.current_scope = Some(authority);
                self.registry.retain_body_retry_scope(Some(authority));
                self.body_retries = crate::zakura::header_sync::BodyRetryQueue::default();
                self.finalized_height = frontiers.finalized_height;
                self.verified_block_hash = frontiers.verified_block_hash;
                self.destructive_reset_to(frontiers.verified_block_tip, false);
                self.work.refresh_authority(authority);
                true
            }
            SequencerControlInput::StateVersionChanged(state_version) => {
                self.current_state_version = Some(state_version);
                false
            }
            SequencerControlInput::BodyAlarmCleared { scope, hash } => {
                self.body_retries
                    .remove(scope.header_generation, scope.branch, hash);
                self.registry.clear_body_retry(scope, hash);
                true
            }
            SequencerControlInput::FrontierAdvance {
                frontiers,
                release_applied,
            } => {
                self.handle_frontier_advance(frontiers, release_applied)
                    .await;
                true
            }
            SequencerControlInput::FrontierReset {
                frontiers,
                preserve_active_successors,
                peer_has_successor_after,
                peer_outstanding_conflicts_at_tip,
            } => {
                self.handle_frontier_reset(
                    frontiers,
                    preserve_active_successors,
                    peer_has_successor_after,
                    peer_outstanding_conflicts_at_tip,
                )
                .await;
                true
            }
            SequencerControlInput::ApplyFinished {
                owner,
                source,
                token,
                height,
                hash,
                mut outcome,
                eligible_sources,
                persisted_availability,
                semantic_completion,
            } => {
                let (needs_reaction, allow_submit) = self
                    .handle_apply_finished(
                        *owner,
                        source,
                        token,
                        height,
                        hash,
                        &mut outcome,
                        eligible_sources,
                        persisted_availability,
                        semantic_completion,
                    )
                    .await;
                if allow_submit {
                    self.submit_pending_blocks().await;
                }
                needs_reaction
            }
        }
    }

    /// Body-acceptance tail: offer the body to the reorder buffer, then drain the
    /// ready contiguous prefix into applying.
    fn handle_accept_body(&mut self, mut body: SequencedBody) {
        let scope_is_current = self.current_scope.is_some_and(|current| {
            current.body_work_epoch == body.owner.authority().body_work_epoch
        });
        #[cfg(test)]
        let scope_is_current = scope_is_current || self.current_scope.is_none();
        if !scope_is_current {
            self.trace_body_accepted(body.height, body.received_at.elapsed(), "stale_scope");
            return;
        }
        if let Some(current) = self.current_scope {
            body.owner.authority = current;
        }
        let queued_elapsed = body.received_at.elapsed();
        let outcome = match self.sequencer.accept_buffered_body(
            body.owner,
            body.source,
            body.height,
            body.hash,
            body.previous_block_hash,
            body.body,
            body.bytes,
            body.peer,
        ) {
            AcceptOutcome::Buffered { .. } => "buffered",
            AcceptOutcome::Redundant { .. } => "redundant",
        };
        self.trace_body_accepted(body.height, queued_elapsed, outcome);
        let _ = self.sequencer.drain_ready_into_applying();
    }

    /// Reset the body pipeline and queued work above `tip` under one reset epoch.
    fn destructive_reset_to(&mut self, tip: block::Height, keep_submitted_applies: bool) {
        let _ = self.sequencer.reset_to(tip, keep_submitted_applies);
        let released = self.work.reset_above(tip);
        self.budget.release(released);
        self.reset_epoch = self.reset_epoch.saturating_add(1);
    }

    /// Apply a verified-tip frontier advance: fold finalized height forward, drop
    /// stale updates, then advance the verified tip and floor and drain the newly
    /// contiguous prefix.
    async fn handle_frontier_advance(
        &mut self,
        frontiers: BlockSyncFrontiers,
        release_applied: bool,
    ) {
        // Fold the finalized height forward unconditionally, then drop a stale
        // update. The verified tip is monotonic: an advance whose target is below
        // our verified tip must be a no-op, never a regression. Without this guard
        // the second growth-reset path (`< floor`, which permits `< verified_tip`)
        // would call `advance_verified_tip` with a lower tip and regress it.
        self.finalized_height = self.finalized_height.max(frontiers.finalized_height);
        if frontiers.verified_block_tip < self.sequencer.verified_tip() {
            return;
        }
        self.verified_block_hash = frontiers.verified_block_hash;
        let advance = self
            .sequencer
            .advance_verified_tip(frontiers.verified_block_tip, release_applied);
        if advance.changed {
            let released = self.work.advance_floor(frontiers.verified_block_tip);
            self.budget.release(released);
            self.release_contiguous_blocks().await;
        }
    }

    /// Handle a chain-tip reset: classify it as growth (treat as an advance) or a
    /// destructive reorg (pin tip/floor to the target, clear successor buffers, and
    /// bump the reset epoch). The peer-outstanding clauses of the decision arrive as
    /// the precomputed `peer_*` bools, since the reactor owns peer state.
    async fn handle_frontier_reset(
        &mut self,
        frontiers: BlockSyncFrontiers,
        preserve_active_successors: bool,
        peer_has_successor_after: bool,
        peer_outstanding_conflicts_at_tip: bool,
    ) {
        let reset_tip_matches_local_work = !self.reset_tip_conflicts_with_local_work(
            &frontiers,
            frontiers.verified_block_tip <= self.sequencer.floor(),
            peer_outstanding_conflicts_at_tip,
        );

        // State can report a forward `Reset` while checkpoint commits advance
        // under already-submitted or still-downloading successor bodies. Treat
        // that as verified growth once it is inside our submitted/downloaded
        // floor, or when we already have successor work in flight. Keep fork
        // resets destructive when they are not anchored by active successor
        // work.
        if frontiers.verified_block_tip > self.sequencer.verified_tip()
            && (frontiers.verified_block_tip <= self.sequencer.floor()
                || self.has_active_successor_after(
                    frontiers.verified_block_tip,
                    peer_has_successor_after,
                ))
            && reset_tip_matches_local_work
        {
            self.trace_frontier_reset_classified(
                "growth",
                &frontiers,
                preserve_active_successors,
                peer_has_successor_after,
                peer_outstanding_conflicts_at_tip,
                reset_tip_matches_local_work,
            );
            // Growth-classified reset: treat it as a frontier advance, releasing
            // applied bodies.
            self.handle_frontier_advance(frontiers, true).await;
            return;
        }

        metrics::counter!("sync.block.reorg.reset").increment(1);

        // A `Reset` can also be a stale or coalesced state update for a tip
        // already inside our contiguous submitted/downloaded body floor. Do not
        // destructively clear successor bodies in that case: a stale reset
        // snapshot can otherwise erase `applying`/covered state and re-request
        // the same bodies while their first apply is still in flight.
        if preserve_active_successors
            && frontiers.verified_block_tip < self.sequencer.floor()
            && reset_tip_matches_local_work
            && self
                .has_active_successor_after(frontiers.verified_block_tip, peer_has_successor_after)
            && self.active_successor_links_to_anchor(
                frontiers.verified_block_tip,
                frontiers.verified_block_hash,
            )
        {
            self.trace_frontier_reset_classified(
                "preserved_stale",
                &frontiers,
                preserve_active_successors,
                peer_has_successor_after,
                peer_outstanding_conflicts_at_tip,
                reset_tip_matches_local_work,
            );
            self.handle_frontier_advance(frontiers, true).await;
            return;
        }

        self.trace_frontier_reset_classified(
            "destructive",
            &frontiers,
            preserve_active_successors,
            peer_has_successor_after,
            peer_outstanding_conflicts_at_tip,
            reset_tip_matches_local_work,
        );
        let remember_released_applies = frontiers.verified_block_tip > frontiers.finalized_height
            && frontiers.verified_block_tip <= self.sequencer.floor();

        self.finalized_height = frontiers.finalized_height;
        self.verified_block_hash = frontiers.verified_block_hash;

        self.destructive_reset_to(frontiers.verified_block_tip, remember_released_applies);
    }

    /// Handle a verifier apply completion.
    /// Release the verifier slot.
    /// After a rejection, move the floor below the bad block so peers can request its range again.
    /// The authoritative snapshot watch supplies committed frontier changes.
    #[allow(clippy::too_many_arguments)]
    async fn handle_apply_finished(
        &mut self,
        owner: zakura_header_chain::BodyWorkOwner,
        source: zakura_header_chain::SourceId,
        token: BlockApplyToken,
        height: block::Height,
        hash: block::Hash,
        outcome: &mut BlockApplyOutcome,
        mut eligible_sources: BTreeSet<zakura_header_chain::SourceId>,
        persisted_availability: Option<zakura_header_chain::BodyUnavailableSummary>,
        semantic_completion: Option<(
            zakura_header_chain::BodyWorkOwner,
            zakura_header_chain::StateVersion,
        )>,
    ) -> (bool, bool) {
        let result = outcome.result();
        // A stale completion (no live applying entry, or token/hash mismatch)
        // releases only its exact token-aware in-flight-submission charge and
        // returns; there is no query/schedule tail here, so it needs no reaction.
        let Some((applying_owner, applying_source, applying_token, applying_hash)) =
            self.sequencer.applying_identity(height)
        else {
            let released = self
                .sequencer
                .finish_submission(owner, source, token, height, hash);
            let verified = matches!(
                outcome.verification(),
                zakura_header_chain::BodyVerificationOutcome::Verified(_)
            );
            return (false, released && verified && semantic_completion.is_some());
        };
        if applying_owner != owner
            || applying_source != source
            || applying_hash != hash
            || applying_token != token
        {
            let released = self
                .sequencer
                .finish_submission(owner, source, token, height, hash);
            // A scope transition can detach an older checkpoint submission and
            // install a newer submission for the same height. When the newer
            // request makes the old verifier call finish as a duplicate, the
            // exact old token frees a submission slot without removing the
            // current applying body. Refill that slot or the checkpoint window
            // can shrink below the range needed to resolve the next checkpoint.
            return (false, released);
        }
        let Some((semantic_owner, semantic_state_version)) = semantic_completion else {
            let _ = self.sequencer.remove_applying(height);
            self.sequencer
                .finish_submission(owner, source, token, height, hash);
            return (false, false);
        };
        let attribution_matches = outcome
            .attributed_source()
            .is_none_or(|attributed| attributed == source);
        if attribution_matches {
            if let zakura_header_chain::BodyVerificationOutcome::ConsensusInvalid(invalid) =
                outcome.verification()
            {
                self.send_action(BlockSyncAction::RecordBodyInvalid {
                    expected_version: semantic_state_version,
                    invalid: invalid.clone(),
                })
                .await;
            }
        }
        self.record_body_retry(
            semantic_owner,
            source,
            zakura_header_chain::Frontier::new(height, hash),
            outcome,
            &mut eligible_sources,
            persisted_availability,
        );
        if let zakura_header_chain::BodyVerificationOutcome::Retryable(failure) =
            outcome.verification()
        {
            self.send_action(BlockSyncAction::RecordBodyUnavailable {
                expected_version: semantic_state_version,
                failure: *failure,
            })
            .await;
        }
        if matches!(result, BlockApplyResult::Duplicate) && self.sequencer.verified_tip() < height {
            // Keep a duplicate attached until the committed snapshot includes its height.
            // The driver already released its decoded copy.
            // Release the token-aware decode-window charge now.
            self.sequencer
                .finish_attached_submission(owner, source, token, height, hash);
            return (false, true);
        }
        let applying = self
            .sequencer
            .remove_applying(height)
            .expect("applying entry exists because it was just checked");

        // A `Committed` result is a body that newly extended the chain; count it
        // toward commit throughput (the apply rate the download path is racing).
        if matches!(result, BlockApplyResult::Committed) {
            self.committed_throughput.record(applying.bytes);
        }
        self.sequencer
            .finish_submission(owner, source, token, height, hash);
        match result {
            BlockApplyResult::Committed | BlockApplyResult::Duplicate => {}
            BlockApplyResult::Rejected
            | BlockApplyResult::Unavailable
            | BlockApplyResult::TimedOut
                if height > self.sequencer.verified_tip() =>
            {
                // Drop the failed body and every successor (in applying and
                // reorder), roll the floor back below it, and drop the WorkQueue
                // entries above the rolled-back floor so the heights are
                // re-requestable (the reactor's `query_needed_blocks` re-fills).
                let _ = self.sequencer.release_applying_blocks_from(height);
                self.sequencer.reset_floor_below(height);
                let released = self.work.reset_above(self.sequencer.floor());
                self.budget.release(released);
                let _ = self.sequencer.drop_reorder_from(height);
                // A `Rejected` result identifies a bad body from a peer.
                // Attribute it to the delivering peer.
                // Do not score local `Unavailable` or `TimedOut` failures.
                if matches!(result, BlockApplyResult::Rejected) && attribution_matches {
                    let reason = match outcome.verification() {
                        zakura_header_chain::BodyVerificationOutcome::PayloadMismatch(mismatch) => {
                            BlockSyncMisbehavior::BodyPayloadMismatch(*mismatch)
                        }
                        zakura_header_chain::BodyVerificationOutcome::ConsensusInvalid(invalid) => {
                            BlockSyncMisbehavior::ConsensusBodyInvalid(invalid.clone())
                        }
                        zakura_header_chain::BodyVerificationOutcome::Verified(_)
                        | zakura_header_chain::BodyVerificationOutcome::Retryable(_) => {
                            unreachable!("only rejected outcomes reach peer scoring")
                        }
                    };
                    self.send_action(BlockSyncAction::Misbehavior {
                        peer: applying.source_peer.clone(),
                        reason,
                    })
                    .await;
                }
            }
            BlockApplyResult::Rejected
            | BlockApplyResult::Unavailable
            | BlockApplyResult::TimedOut => {}
        }
        self.release_contiguous_blocks().await;
        (true, true)
    }

    fn record_body_retry(
        &mut self,
        owner: zakura_header_chain::BodyWorkOwner,
        source: zakura_header_chain::SourceId,
        header: zakura_header_chain::Frontier,
        outcome: &mut BlockApplyOutcome,
        eligible_sources: &mut BTreeSet<zakura_header_chain::SourceId>,
        persisted_availability: Option<zakura_header_chain::BodyUnavailableSummary>,
    ) {
        let hash = header.hash;
        let Some(failure) = outcome.retryable_mut() else {
            self.body_retries
                .remove(owner.header_generation, owner.branch, hash);
            self.registry.clear_body_retry(owner.authority(), hash);
            return;
        };
        eligible_sources.insert(source);
        if self
            .body_retries
            .get_mut(owner.header_generation, owner.branch, hash)
            .is_none()
        {
            let episode = persisted_availability
                .filter(|summary| summary.alarmed)
                .map(|summary| {
                    crate::zakura::header_sync::BodyRetryEpisode::restore(
                        owner.branch,
                        owner.header_generation,
                        header,
                        eligible_sources.clone(),
                        summary,
                    )
                })
                .unwrap_or_else(|| {
                    crate::zakura::header_sync::BodyRetryEpisode::new(
                        owner.branch,
                        owner.header_generation,
                        header,
                        eligible_sources.clone(),
                        &zakura_header_chain::SystemClock,
                    )
                });
            self.body_retries.insert(episode);
        }
        let episode = self
            .body_retries
            .get_mut(owner.header_generation, owner.branch, hash)
            .expect("the exact retry episode exists because it was inserted above");
        episode.refresh_suppliers(eligible_sources.clone());
        let update = episode.record_failure(
            source,
            &zakura_header_chain::SystemClock,
            &self.retry_jitter,
        );
        let deferred_sources = if episode.alarmed {
            eligible_sources.clone()
        } else {
            episode.tried_suppliers.clone()
        };
        let retry_at = match update {
            crate::zakura::header_sync::RetryUpdate::TooEarly => episode.next_probe_at,
            crate::zakura::header_sync::RetryUpdate::RetryAt(retry_at)
            | crate::zakura::header_sync::RetryUpdate::ProbeAt(retry_at) => retry_at,
            crate::zakura::header_sync::RetryUpdate::Alarmed { probe_at } => probe_at,
        };
        failure.availability = episode.summary();
        if let Some(persisted) = persisted_availability.filter(|summary| summary.alarmed) {
            if persisted.suppliers > failure.availability.suppliers {
                failure.availability.suppliers = persisted.suppliers;
                failure.availability.supplier_set_digest = persisted.supplier_set_digest;
            }
        }
        self.registry.defer_body_retry(
            deferred_sources,
            owner.authority(),
            hash,
            retry_deadline_instant(retry_at),
        );
    }

    /// Drain the contiguous reorder prefix into applying, then submit it.
    async fn release_contiguous_blocks(&mut self) {
        let _ = self.sequencer.drain_ready_into_applying();
        self.submit_pending_blocks().await;
    }

    async fn submit_pending_blocks(&mut self) {
        let submittable_heights = self.sequencer.submittable_heights();
        if submittable_heights.is_empty() {
            if self.sequencer.unsubmitted_applying_count() == 0 {
                self.submission_retry_at = None;
                self.submission_retry_started_at = None;
                self.submission_retry_attempt = 0;
            } else if self.submission_retry_started_at.is_some()
                && self.submission_retry_at.is_none()
                && !self.actions.is_closed()
            {
                self.submission_retry_at = Some(time::Instant::now() + SUBMISSION_RETRY_DELAY);
            }
            return;
        }

        self.submission_retry_at = None;
        for height in submittable_heights {
            let Some(item) = self.sequencer.prepare_submit(height) else {
                continue;
            };

            metrics::counter!("sync.block.submit.sent").increment(1);
            let queue_depth = self
                .actions
                .max_capacity()
                .saturating_sub(self.actions.capacity());
            // Metrics accepts f64 samples; this lossy conversion is observability-only.
            metrics::histogram!(
                "sync.block.action.queue.depth",
                "action" => "submit_block"
            )
            .record(queue_depth as f64);
            let send_started = time::Instant::now();
            let sent = self
                .send_action(BlockSyncAction::SubmitBlock {
                    owner: item.owner,
                    source: item.source,
                    token: item.token,
                    block: item.block,
                })
                .await;
            metrics::histogram!("sync.block.submit.queue_wait_seconds")
                .record(send_started.elapsed().as_secs_f64());
            if !sent {
                self.sequencer.unsubmit(item.height, item.token);
                if !self.actions.is_closed() {
                    let now = time::Instant::now();
                    self.submission_retry_started_at.get_or_insert(now);
                    self.submission_retry_attempt = self.submission_retry_attempt.saturating_add(1);
                    self.submission_retry_at = Some(now + SUBMISSION_RETRY_DELAY);
                    metrics::counter!("sync.block.submit.retry.scheduled").increment(1);
                    self.trace_submission_retry_scheduled(item.height);
                }
                return;
            }
            if let Some(started_at) = self.submission_retry_started_at.take() {
                metrics::counter!("sync.block.submit.retry.succeeded").increment(1);
                metrics::histogram!("sync.block.submit.retry.delay_seconds")
                    .record(started_at.elapsed().as_secs_f64());
                self.submission_retry_attempt = 0;
            }
            self.sequencer
                .record_submitted_apply(item.height, item.hash);
            self.trace_body_submitted(item.height, item.token);
        }
    }

    /// `reset_tip_conflicts_with_local_work`'s Sequencer-internal predicates,
    /// with the peer-outstanding clause supplied by the reactor.
    fn reset_tip_conflicts_with_local_work(
        &self,
        frontiers: &BlockSyncFrontiers,
        ignore_non_material_conflicts: bool,
        peer_outstanding_conflicts_at_tip: bool,
    ) -> bool {
        let height = frontiers.verified_block_tip;
        let hash = frontiers.verified_block_hash;

        if self
            .sequencer
            .reorder_hash(height)
            .is_some_and(|buffered_hash| buffered_hash != hash)
        {
            return true;
        }
        if self
            .sequencer
            .applying_hash(height)
            .is_some_and(|applying_hash| applying_hash != hash)
        {
            return true;
        }
        if !ignore_non_material_conflicts
            && self.sequencer.submitted_has_only_other_hashes(height, hash)
        {
            return true;
        }
        if !ignore_non_material_conflicts && peer_outstanding_conflicts_at_tip {
            return true;
        }
        false
    }

    fn has_active_successor_after(
        &self,
        height: block::Height,
        peer_has_successor_after: bool,
    ) -> bool {
        let Some(next) = next_height(height) else {
            return false;
        };

        self.sequencer.has_buffered_at_or_above(next) || peer_has_successor_after
    }

    fn active_successor_links_to_anchor(
        &self,
        height: block::Height,
        anchor_hash: block::Hash,
    ) -> bool {
        let Some(next) = next_height(height) else {
            return true;
        };

        direct_successor_links_to_anchor(
            self.sequencer.applying_previous_block_hash(next),
            anchor_hash,
        )
    }

    async fn send_action(&self, action: BlockSyncAction) -> bool {
        // `SubmitBlock` is the intended verifier-backpressure point: a slow
        // verifier blocks the task here, stopping it from draining `input`. The
        // timeout matches the reactor's `dispatch_action` so a permanently
        // stalled driver does not wedge the pipeline forever.
        let action_label = action.metric_label();
        match time::timeout(self.action_send_timeout, self.actions.send(action)).await {
            Ok(Ok(())) => true,
            Ok(Err(_)) => false,
            Err(_) => {
                metrics::counter!(
                    "sync.block.action.send_timeout",
                    "action" => action_label
                )
                .increment(1);
                false
            }
        }
    }

    fn publish_view(&mut self) {
        self.committed_throughput.sample(Instant::now());
        let reorder_buffered_bytes = self.sequencer.reorder_buffered_bytes();
        let applying_buffered_bytes = self.sequencer.applying_buffered_bytes();
        let sequencer_input_decoded_attributed_memory_bytes = self
            .body_input_decoded_attributed_memory_bytes
            .load(std::sync::atomic::Ordering::Relaxed);
        let reorder_decoded_attributed_memory_bytes =
            self.sequencer.reorder_decoded_attributed_memory_bytes();
        let applying_decoded_attributed_memory_bytes =
            self.sequencer.applying_decoded_attributed_memory_bytes();
        let active_pipeline_decoded_attributed_memory_bytes =
            sequencer_input_decoded_attributed_memory_bytes
                .saturating_add(reorder_decoded_attributed_memory_bytes)
                .saturating_add(applying_decoded_attributed_memory_bytes);
        // Retained bodies do not charge the request budget.
        self.budget
            .audit(self.work.reserved_bytes(), "block-sync sequencer view");
        let next = SequencerView {
            verified_tip: self.sequencer.verified_tip(),
            verified_hash: self.verified_block_hash,
            download_floor: self.sequencer.floor(),
            finalized: self.finalized_height,
            reset_epoch: self.reset_epoch,
            reaction_epoch: self.reaction_epoch,
            reorder_len: self.sequencer.reorder_len() as u64,
            applying_len: self.sequencer.applying_len() as u64,
            reorder_buffered_bytes,
            applying_buffered_bytes,
            sequencer_input_decoded_attributed_memory_bytes,
            reorder_decoded_attributed_memory_bytes,
            applying_decoded_attributed_memory_bytes,
            active_pipeline_decoded_attributed_memory_bytes,
            unsubmitted_applying_count: self.sequencer.unsubmitted_applying_count() as u64,
            in_flight_submission_count: self.sequencer.in_flight_submission_count() as u64,
            in_flight_submission_bytes: self.sequencer.in_flight_submission_bytes(),
            committed_bytes_per_sec: self.committed_throughput.bytes_per_sec(),
            committed_blocks_per_sec: self.committed_throughput.blocks_per_sec(),
        };
        // Only wake watchers (the reactor + every per-peer routine) when a field
        // they schedule against actually changed. The two committed_*_per_sec rates
        // are observability-only; without this guard a stale or duplicate
        // `ApplyFinished` input can publish an otherwise-identical view and re-wake
        // every routine's `sequencer_view.changed()` arm into an immediate refill
        // retry.
        // That is a timer-free reactor<->sequencer<->routine busy-spin: it wastes a
        // core (and starves progress under CI load) on a real clock and fully wedges
        // a `start_paused` test clock, which auto-advances only once every task
        // parks. Keep the stored rates fresh, but notify only on a schedulable change.
        publish_sequencer_view(&self.view_tx, next);
    }

    fn publish_decoded_ownership_view(&self) {
        let sequencer_input_decoded_attributed_memory_bytes = self
            .body_input_decoded_attributed_memory_bytes
            .load(std::sync::atomic::Ordering::Relaxed);
        let reorder_decoded_attributed_memory_bytes =
            self.sequencer.reorder_decoded_attributed_memory_bytes();
        let applying_decoded_attributed_memory_bytes =
            self.sequencer.applying_decoded_attributed_memory_bytes();
        let active_pipeline_decoded_attributed_memory_bytes =
            sequencer_input_decoded_attributed_memory_bytes
                .saturating_add(reorder_decoded_attributed_memory_bytes)
                .saturating_add(applying_decoded_attributed_memory_bytes);
        self.view_tx.send_if_modified(|view| {
            view.sequencer_input_decoded_attributed_memory_bytes =
                sequencer_input_decoded_attributed_memory_bytes;
            view.reorder_decoded_attributed_memory_bytes = reorder_decoded_attributed_memory_bytes;
            view.applying_decoded_attributed_memory_bytes =
                applying_decoded_attributed_memory_bytes;
            view.active_pipeline_decoded_attributed_memory_bytes =
                active_pipeline_decoded_attributed_memory_bytes;
            false
        });
    }
}

fn add_atomic_bytes(counter: &std::sync::atomic::AtomicU64, bytes: u64) {
    let mut current = counter.load(std::sync::atomic::Ordering::Relaxed);
    loop {
        let next = current.saturating_add(bytes);
        match counter.compare_exchange_weak(
            current,
            next,
            std::sync::atomic::Ordering::Relaxed,
            std::sync::atomic::Ordering::Relaxed,
        ) {
            Ok(_) => break,
            Err(observed) => current = observed,
        }
    }
}

fn release_atomic_bytes(counter: &std::sync::atomic::AtomicU64, bytes: u64) {
    let mut current = counter.load(std::sync::atomic::Ordering::Relaxed);
    loop {
        let next = current.saturating_sub(bytes);
        match counter.compare_exchange_weak(
            current,
            next,
            std::sync::atomic::Ordering::Relaxed,
            std::sync::atomic::Ordering::Relaxed,
        ) {
            Ok(_) => break,
            Err(observed) => current = observed,
        }
    }
}

fn direct_successor_links_to_anchor(
    previous_block_hash: Option<block::Hash>,
    anchor_hash: block::Hash,
) -> bool {
    previous_block_hash.is_some_and(|hash| hash == anchor_hash)
}

fn publish_sequencer_view(view_tx: &watch::Sender<SequencerView>, next: SequencerView) {
    view_tx.send_if_modified(|current| {
        let schedulable_changed = view_schedulable_ne(current, &next);
        *current = next;
        schedulable_changed
    });
}

/// True when two views differ in any field the reactor or per-peer routines
/// schedule against. Ignores the observability-only committed throughput rates,
/// which move on nearly every sample and must not, on their own, wake — or under a
/// paused test clock, spin — the whole fleet of watchers.
fn view_schedulable_ne(a: &SequencerView, b: &SequencerView) -> bool {
    let strip_rates = |v: &SequencerView| {
        let mut v = *v;
        v.committed_bytes_per_sec = 0;
        v.committed_blocks_per_sec = 0;
        v.sequencer_input_decoded_attributed_memory_bytes = 0;
        v.reorder_decoded_attributed_memory_bytes = 0;
        v.applying_decoded_attributed_memory_bytes = 0;
        v.active_pipeline_decoded_attributed_memory_bytes = 0;
        v
    };
    strip_rates(a) != strip_rates(b)
}

#[cfg(test)]
mod tests {
    use zakura_chain::serialization::ZcashDeserializeInto;
    use zakura_test::vectors::BLOCK_MAINNET_1_BYTES;

    use super::*;

    #[test]
    fn missing_direct_successor_cannot_prove_reset_anchor() {
        let anchor_hash = block::Hash([1; 32]);

        assert!(direct_successor_links_to_anchor(
            Some(anchor_hash),
            anchor_hash
        ));
        assert!(!direct_successor_links_to_anchor(
            Some(block::Hash([2; 32])),
            anchor_hash
        ));
        assert!(!direct_successor_links_to_anchor(None, anchor_hash));
    }

    fn test_view() -> SequencerView {
        SequencerView {
            verified_tip: block::Height(1),
            verified_hash: block::Hash([1; 32]),
            download_floor: block::Height(1),
            finalized: block::Height(1),
            reset_epoch: 0,
            reaction_epoch: 0,
            reorder_len: 0,
            applying_len: 0,
            reorder_buffered_bytes: 0,
            applying_buffered_bytes: 0,
            sequencer_input_decoded_attributed_memory_bytes: 0,
            reorder_decoded_attributed_memory_bytes: 0,
            applying_decoded_attributed_memory_bytes: 0,
            active_pipeline_decoded_attributed_memory_bytes: 0,
            unsubmitted_applying_count: 0,
            in_flight_submission_count: 0,
            in_flight_submission_bytes: 0,
            committed_bytes_per_sec: 0,
            committed_blocks_per_sec: 0,
        }
    }

    fn test_block() -> Arc<block::Block> {
        Arc::new(
            BLOCK_MAINNET_1_BYTES
                .zcash_deserialize_into()
                .expect("block test vector parses"),
        )
    }

    fn queued_test_body(
        input_bytes: Arc<std::sync::atomic::AtomicU64>,
        input_decoded_attributed_memory_bytes: Arc<std::sync::atomic::AtomicU64>,
    ) -> SequencedBody {
        let block = test_block();
        let previous_block_hash = block.header.previous_block_hash;
        SequencedBody::new_queued(
            super::super::test_work_owner(),
            zakura_header_chain::SourceId::from_digest([1; 32]),
            block::Height(1),
            block.hash(),
            previous_block_hash,
            BufferedBlockBody::from_decoded_block(block, None),
            123,
            ZakuraPeerId::new(vec![1; 32]).expect("test peer id is valid"),
            Instant::now(),
            input_bytes,
            input_decoded_attributed_memory_bytes,
        )
    }

    #[test]
    fn sequenced_body_leave_and_drop_release_queue_counters_once() {
        let input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let input_decoded_attributed_memory_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let mut body = queued_test_body(
            input_bytes.clone(),
            input_decoded_attributed_memory_bytes.clone(),
        );

        assert_eq!(input_bytes.load(std::sync::atomic::Ordering::Relaxed), 123);
        assert!(
            input_decoded_attributed_memory_bytes.load(std::sync::atomic::Ordering::Relaxed) > 0
        );

        body.leave_queue();
        assert_eq!(input_bytes.load(std::sync::atomic::Ordering::Relaxed), 0);
        assert_eq!(
            input_decoded_attributed_memory_bytes.load(std::sync::atomic::Ordering::Relaxed),
            0
        );

        drop(body);
        assert_eq!(input_bytes.load(std::sync::atomic::Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn cancelled_send_drops_its_queue_accounting() {
        let input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let input_decoded_attributed_memory_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let (body_tx, mut body_rx) = mpsc::channel(1);
        body_tx
            .try_send(queued_test_body(
                input_bytes.clone(),
                input_decoded_attributed_memory_bytes.clone(),
            ))
            .expect("body channel has capacity");
        let blocked_body = queued_test_body(
            input_bytes.clone(),
            input_decoded_attributed_memory_bytes.clone(),
        );
        let blocked_send = tokio::spawn(async move { body_tx.send(blocked_body).await });
        tokio::task::yield_now().await;
        assert!(!blocked_send.is_finished());

        blocked_send.abort();
        let _ = blocked_send.await;
        assert_eq!(
            input_bytes.load(std::sync::atomic::Ordering::Relaxed),
            123,
            "only the body already queued remains charged"
        );

        let mut queued = body_rx.recv().await.expect("first body remains queued");
        queued.leave_queue();
        assert_eq!(input_bytes.load(std::sync::atomic::Ordering::Relaxed), 0);
        assert_eq!(
            input_decoded_attributed_memory_bytes.load(std::sync::atomic::Ordering::Relaxed),
            0
        );
    }

    #[tokio::test]
    async fn closed_receiver_with_live_permit_drops_queue_accounting() {
        let input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let input_decoded_attributed_memory_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let (body_tx, body_rx) = mpsc::channel(1);
        let permit = body_tx
            .reserve_owned()
            .await
            .expect("receiver is initially open");
        drop(body_rx);

        permit.send(queued_test_body(
            input_bytes.clone(),
            input_decoded_attributed_memory_bytes.clone(),
        ));

        assert_eq!(input_bytes.load(std::sync::atomic::Ordering::Relaxed), 0);
        assert_eq!(
            input_decoded_attributed_memory_bytes.load(std::sync::atomic::Ordering::Relaxed),
            0
        );
    }

    #[tokio::test]
    async fn state_version_refresh_does_not_retire_body_authority() {
        let frontiers = BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        };
        let scope = super::test_work_scope();
        let (_body_tx, body_rx) = mpsc::channel(1);
        let (_control_tx, control_rx) = mpsc::unbounded_channel();
        let (actions, _actions_rx) = mpsc::channel(1);
        let (view_tx, _view_rx) = watch::channel(initial_view(frontiers));
        let mut task = SequencerTask::new(
            Sequencer::new(block::Height(0), 1),
            ByteBudget::new(123),
            Arc::new(WorkQueue::new(block::Height(0))),
            Arc::new(PeerRegistry::new()),
            actions,
            ThroughputMeter::new(Instant::now()),
            frontiers,
            Some(scope),
            crate::zakura::header_sync::SeededRetryJitter::new([0; 32]),
            body_rx,
            control_rx,
            Arc::new(std::sync::atomic::AtomicU64::new(0)),
            Arc::new(std::sync::atomic::AtomicU64::new(0)),
            view_tx,
            Duration::from_secs(1),
            ZakuraTrace::noop(),
        );

        assert!(
            !task
                .handle_control_input(SequencerControlInput::StateVersionChanged(
                    zakura_header_chain::StateVersion::new(9),
                ))
                .await,
            "a CAS-coordinate refresh does not require a scheduling reaction"
        );
        assert_eq!(task.current_scope, Some(scope));
        assert_eq!(
            task.current_state_version,
            Some(zakura_header_chain::StateVersion::new(9))
        );
    }

    #[tokio::test]
    async fn same_target_scope_advance_preserves_downloaded_bodies() {
        let frontiers = BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        };
        let old_scope = super::test_work_scope();
        let input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let input_decoded_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let (_body_tx, body_rx) = mpsc::channel(1);
        let (_control_tx, control_rx) = mpsc::unbounded_channel();
        let (actions, _actions_rx) = mpsc::channel(1);
        let (view_tx, _view_rx) = watch::channel(initial_view(frontiers));
        let mut task = SequencerTask::new(
            Sequencer::new(block::Height(0), 1),
            ByteBudget::new(123),
            Arc::new(WorkQueue::new(block::Height(0))),
            Arc::new(PeerRegistry::new()),
            actions,
            ThroughputMeter::new(Instant::now()),
            frontiers,
            Some(old_scope),
            crate::zakura::header_sync::SeededRetryJitter::new([0; 32]),
            body_rx,
            control_rx,
            input_bytes.clone(),
            input_decoded_bytes.clone(),
            view_tx,
            Duration::from_secs(1),
            ZakuraTrace::noop(),
        );
        let mut advanced_scope = old_scope;
        advanced_scope.header.header_generation = zakura_header_chain::HeaderGeneration::new(8);
        advanced_scope.verified_generation = zakura_header_chain::VerifiedGeneration::new(9);
        advanced_scope.header.branch.anchor_hash = block::Hash([8; 32]);

        assert!(
            !task
                .handle_control_input(SequencerControlInput::WorkAuthorityRefreshed {
                    authority: advanced_scope,
                })
                .await,
            "a same-target authority advance does not require a destructive reaction"
        );
        assert_eq!(task.current_scope, Some(advanced_scope));
        assert_eq!(task.reset_epoch, 0);

        let mut body = queued_test_body(input_bytes, input_decoded_bytes);
        body.leave_queue();
        task.handle_accept_body(body);

        assert_eq!(task.sequencer.applying_len(), 1);
        assert_eq!(task.sequencer.reorder_len(), 0);
    }

    #[tokio::test]
    async fn body_invalid_reselection_resets_block_pipeline() {
        let frontiers = BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        };
        let old_authority = super::test_work_scope();
        let work = Arc::new(WorkQueue::new(block::Height(0)));
        work.extend(
            old_authority,
            [(
                block::Height(2),
                block::Hash([2; 32]),
                BlockSizeEstimate::Advertised(123),
            )],
        );
        let input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let input_decoded_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let (_body_tx, body_rx) = mpsc::channel(1);
        let (_control_tx, control_rx) = mpsc::unbounded_channel();
        let (actions, _actions_rx) = mpsc::channel(1);
        let (view_tx, _view_rx) = watch::channel(initial_view(frontiers));
        let mut task = SequencerTask::new(
            Sequencer::new(block::Height(0), 1),
            ByteBudget::new(123),
            work.clone(),
            Arc::new(PeerRegistry::new()),
            actions,
            ThroughputMeter::new(Instant::now()),
            frontiers,
            Some(old_authority),
            crate::zakura::header_sync::SeededRetryJitter::new([0; 32]),
            body_rx,
            control_rx,
            input_bytes.clone(),
            input_decoded_bytes.clone(),
            view_tx,
            Duration::from_secs(1),
            ZakuraTrace::noop(),
        );

        let mut body = queued_test_body(input_bytes, input_decoded_bytes);
        body.leave_queue();
        task.handle_accept_body(body);
        assert_eq!(task.sequencer.applying_len(), 1);
        assert_eq!(work.pending_len(), 1);

        let mut new_authority = old_authority;
        new_authority.body_work_epoch = zakura_header_chain::BodyWorkEpoch::new(1);
        assert!(
            task.handle_control_input(SequencerControlInput::BodyWorkEpochChanged {
                authority: new_authority,
                frontiers,
            })
            .await
        );

        assert_eq!(task.sequencer.floor(), frontiers.verified_block_tip);
        assert_eq!(task.sequencer.applying_len(), 0);
        assert_eq!(task.sequencer.reorder_len(), 0);
        assert_eq!(work.pending_len(), 0);
        assert_eq!(work.in_flight_len(), 0);
        assert_eq!(task.reset_epoch, 1);
    }

    #[tokio::test]
    async fn stale_retry_completion_releases_only_exact_infrastructure() {
        let frontiers = BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        };
        let input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let input_decoded_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let (_body_tx, body_rx) = mpsc::channel(1);
        let (_control_tx, control_rx) = mpsc::unbounded_channel();
        let (actions, mut actions_rx) = mpsc::channel(4);
        let (view_tx, _view_rx) = watch::channel(initial_view(frontiers));
        let mut task = SequencerTask::new(
            Sequencer::new(block::Height(0), 1),
            ByteBudget::new(123),
            Arc::new(WorkQueue::new(block::Height(0))),
            Arc::new(PeerRegistry::new()),
            actions,
            ThroughputMeter::new(Instant::now()),
            frontiers,
            Some(super::test_work_scope()),
            crate::zakura::header_sync::SeededRetryJitter::new([0; 32]),
            body_rx,
            control_rx,
            input_bytes.clone(),
            input_decoded_bytes.clone(),
            view_tx,
            Duration::from_secs(1),
            ZakuraTrace::noop(),
        );

        let mut body = queued_test_body(input_bytes.clone(), input_decoded_bytes.clone());
        body.leave_queue();
        task.handle_accept_body(body);
        task.submit_pending_blocks().await;
        let BlockSyncAction::SubmitBlock {
            owner,
            source,
            token,
            block,
        } = actions_rx.recv().await.expect("body is submitted")
        else {
            panic!("expected a body submission");
        };
        let height = block.coinbase_height().expect("test block has height");
        let hash = block.hash();
        let mut outcome = super::test_block_apply_outcome(BlockApplyResult::Unavailable);

        assert_eq!(
            task.handle_apply_finished(
                owner,
                source,
                token,
                height,
                hash,
                &mut outcome,
                BTreeSet::new(),
                None,
                None,
            )
            .await,
            (false, false),
            "a stale transient completion cannot trigger scheduling or reaction"
        );
        assert!(!task.sequencer.applying_contains(height));
        assert_eq!(task.sequencer.in_flight_submission_count(), 0);
        assert!(
            task.body_retries.is_empty(),
            "stale transient completion cannot create a retry episode"
        );
        assert!(
            actions_rx.try_recv().is_err(),
            "stale completion emits no action"
        );

        let mut current_scope = super::test_work_scope();
        current_scope.verified_generation = zakura_header_chain::VerifiedGeneration::new(9);
        current_scope.body_work_epoch = zakura_header_chain::BodyWorkEpoch::new(1);
        assert!(
            task.handle_control_input(SequencerControlInput::BodyWorkEpochChanged {
                authority: current_scope,
                frontiers,
            })
            .await
        );
        assert_eq!(task.sequencer.floor(), block::Height(0));

        let mut old_body = queued_test_body(input_bytes, input_decoded_bytes);
        old_body.leave_queue();
        task.handle_accept_body(old_body);
        assert_eq!(task.sequencer.reorder_len(), 0);
        assert_eq!(task.sequencer.applying_len(), 0);
    }

    #[tokio::test]
    // IN-02: enumerate every commitment mismatch so each proves body-only
    // attribution while preserving the independently valid header.
    async fn each_commitment_mismatch_scores_only_body_delivery() {
        let kinds = [
            zakura_header_chain::BodyCommitmentKind::HeaderHash,
            zakura_header_chain::BodyCommitmentKind::TransactionMerkleRoot,
            zakura_header_chain::BodyCommitmentKind::AuthDataRoot,
            zakura_header_chain::BodyCommitmentKind::Other("test.other_commitment"),
        ];
        for (index, kind) in kinds.into_iter().enumerate() {
            for attribution_matches in [true, false] {
                let frontiers = BlockSyncFrontiers {
                    finalized_height: block::Height(0),
                    verified_block_tip: block::Height(0),
                    verified_block_hash: block::Hash([0; 32]),
                };
                let input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
                let input_decoded_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
                let (_body_tx, body_rx) = mpsc::channel(1);
                let (_control_tx, control_rx) = mpsc::unbounded_channel();
                let (actions, mut actions_rx) = mpsc::channel(4);
                let (view_tx, _view_rx) = watch::channel(initial_view(frontiers));
                let mut task = SequencerTask::new(
                    Sequencer::new(block::Height(0), 1),
                    ByteBudget::new(123),
                    Arc::new(WorkQueue::new(block::Height(0))),
                    Arc::new(PeerRegistry::new()),
                    actions,
                    ThroughputMeter::new(Instant::now()),
                    frontiers,
                    Some(super::test_work_scope()),
                    crate::zakura::header_sync::SeededRetryJitter::new([0; 32]),
                    body_rx,
                    control_rx,
                    input_bytes.clone(),
                    input_decoded_bytes.clone(),
                    view_tx,
                    Duration::from_secs(1),
                    ZakuraTrace::noop(),
                );

                let mut body = queued_test_body(input_bytes, input_decoded_bytes);
                body.leave_queue();
                task.handle_accept_body(body);
                task.submit_pending_blocks().await;
                let BlockSyncAction::SubmitBlock {
                    owner,
                    source,
                    token,
                    block,
                } = actions_rx.recv().await.expect("body is submitted")
                else {
                    panic!("expected a body submission");
                };
                let height = block.coinbase_height().expect("test block has height");
                let hash = block.hash();
                let attributed_source = if attribution_matches {
                    source
                } else {
                    zakura_header_chain::SourceId::from_digest([9; 32])
                };
                let marker = u8::try_from(index).expect("the mismatch matrix fits in u8");
                let mismatch = zakura_header_chain::BodyPayloadMismatch {
                    evidence: zakura_header_chain::EvidenceId::from_digest(
                        [marker.wrapping_add(0x80); 32],
                    ),
                    requested: hash,
                    delivered: block::Hash([marker.wrapping_add(0x40); 32]),
                    kind,
                    source: attributed_source,
                };
                let mut outcome = BlockApplyOutcome::payload_mismatch(mismatch);

                assert_eq!(
                    task.handle_apply_finished(
                        owner,
                        source,
                        token,
                        height,
                        hash,
                        &mut outcome,
                        BTreeSet::new(),
                        None,
                        Some((owner, zakura_header_chain::StateVersion::default())),
                    )
                    .await,
                    (true, true),
                    "a current mismatch retires the bad body and requests more work"
                );
                assert!(!task.sequencer.applying_contains(height));
                assert_eq!(task.sequencer.in_flight_submission_count(), 0);

                if attribution_matches {
                    assert!(matches!(
                        actions_rx.recv().await,
                        Some(BlockSyncAction::Misbehavior {
                            peer,
                            reason: BlockSyncMisbehavior::BodyPayloadMismatch(actual),
                        }) if peer == ZakuraPeerId::new(vec![1; 32])
                            .expect("test peer ID is valid")
                            && actual == mismatch
                    ));
                }
                assert!(
                    actions_rx.try_recv().is_err(),
                    "payload mismatch can emit only exact-supplier scoring, never eligibility state"
                );
            }
        }
    }

    #[tokio::test]
    // IN-02: persist a consensus-invalid result.
    // Attribute it only to the authenticated supplier.
    async fn body_invalid_after_header_extension_reaches_header_dag() {
        for attribution_matches in [true, false] {
            let frontiers = BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: block::Height(0),
                verified_block_hash: block::Hash([0; 32]),
            };
            let input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
            let input_decoded_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
            let (_body_tx, body_rx) = mpsc::channel(1);
            let (_control_tx, control_rx) = mpsc::unbounded_channel();
            let (actions, mut actions_rx) = mpsc::channel(4);
            let (view_tx, _view_rx) = watch::channel(initial_view(frontiers));
            let mut task = SequencerTask::new(
                Sequencer::new(block::Height(0), 1),
                ByteBudget::new(123),
                Arc::new(WorkQueue::new(block::Height(0))),
                Arc::new(PeerRegistry::new()),
                actions,
                ThroughputMeter::new(Instant::now()),
                frontiers,
                Some(super::test_work_scope()),
                crate::zakura::header_sync::SeededRetryJitter::new([0; 32]),
                body_rx,
                control_rx,
                input_bytes.clone(),
                input_decoded_bytes.clone(),
                view_tx,
                Duration::from_secs(1),
                ZakuraTrace::noop(),
            );

            let mut body = queued_test_body(input_bytes, input_decoded_bytes);
            body.leave_queue();
            task.handle_accept_body(body);
            task.submit_pending_blocks().await;
            let BlockSyncAction::SubmitBlock {
                owner,
                source,
                token,
                block,
            } = actions_rx.recv().await.expect("body is submitted")
            else {
                panic!("expected a body submission");
            };
            let height = block.coinbase_height().expect("test block has height");
            let hash = block.hash();
            let attributed_source = if attribution_matches {
                source
            } else {
                zakura_header_chain::SourceId::from_digest([9; 32])
            };
            let invalid = zakura_header_chain::ConsensusBodyInvalid {
                hash,
                evidence: zakura_header_chain::EvidenceId::from_digest([8; 32]),
                rule: zakura_header_chain::BodyRuleId::new("test.consensus_invalid"),
                source: attributed_source,
            };
            let mut outcome = BlockApplyOutcome::consensus_invalid(invalid.clone());
            let mut refreshed_authority = owner.authority();
            refreshed_authority.header.header_generation =
                zakura_header_chain::HeaderGeneration::new(8);
            refreshed_authority.header.branch.target_tip_hash = block::Hash([8; 32]);
            assert!(
                !task
                    .handle_control_input(SequencerControlInput::WorkAuthorityRefreshed {
                        authority: refreshed_authority,
                    })
                    .await
            );
            let semantic_owner = refreshed_authority.bind(owner.session_id(), owner.request_id());

            assert_eq!(
                task.handle_apply_finished(
                    owner,
                    source,
                    token,
                    height,
                    hash,
                    &mut outcome,
                    BTreeSet::new(),
                    None,
                    Some((semantic_owner, zakura_header_chain::StateVersion::default(),)),
                )
                .await,
                (true, true)
            );
            assert!(!task.sequencer.applying_contains(height));
            assert_eq!(task.sequencer.in_flight_submission_count(), 0);

            if attribution_matches {
                assert!(matches!(
                    actions_rx.recv().await,
                    Some(BlockSyncAction::RecordBodyInvalid {
                        expected_version,
                        invalid: actual,
                    }) if expected_version == zakura_header_chain::StateVersion::default()
                        && actual == invalid
                ));
                assert!(matches!(
                    actions_rx.recv().await,
                    Some(BlockSyncAction::Misbehavior {
                        peer,
                        reason: BlockSyncMisbehavior::ConsensusBodyInvalid(actual),
                    }) if peer == ZakuraPeerId::new(vec![1; 32]).expect("test peer ID is valid")
                        && actual == invalid
                ));
            } else {
                assert!(
                    actions_rx.try_recv().is_err(),
                    "mismatched body attribution can neither mutate state nor score a peer"
                );
            }
        }
    }

    #[tokio::test(start_paused = true)]
    async fn submission_retries_after_action_channel_capacity_returns() {
        let frontiers = BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        };
        let body_input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let body_input_decoded_attributed_memory_bytes =
            Arc::new(std::sync::atomic::AtomicU64::new(0));
        let (body_tx, body_rx) = mpsc::channel(1);
        let (_control_tx, control_rx) = mpsc::unbounded_channel();
        let (actions, mut actions_rx) = mpsc::channel(1);
        actions
            .try_send(BlockSyncAction::QueryNeededBlocks {
                query_id: std::num::NonZeroU64::new(1).expect("one is nonzero"),
                from: block::Height(1),
                limit: 1,
                best_header_tip: block::Height(1),
                scope: super::test_work_scope(),
            })
            .expect("test fills the action channel");
        let (view_tx, mut view_rx) = watch::channel(initial_view(frontiers));
        let task = SequencerTask::new(
            Sequencer::new(block::Height(0), 1),
            ByteBudget::new(123),
            Arc::new(WorkQueue::new(block::Height(0))),
            Arc::new(PeerRegistry::new()),
            actions,
            ThroughputMeter::new(Instant::now()),
            frontiers,
            Some(super::test_work_scope()),
            crate::zakura::header_sync::SeededRetryJitter::new([0; 32]),
            body_rx,
            control_rx,
            body_input_bytes.clone(),
            body_input_decoded_attributed_memory_bytes.clone(),
            view_tx,
            Duration::from_secs(1),
            ZakuraTrace::noop(),
        );
        let task = tokio::spawn(task.run());

        body_tx
            .send(queued_test_body(
                body_input_bytes,
                body_input_decoded_attributed_memory_bytes,
            ))
            .await
            .expect("body queues");

        time::timeout(Duration::from_secs(2), async {
            while view_rx.borrow_and_update().unsubmitted_applying_count == 0 {
                view_rx
                    .changed()
                    .await
                    .expect("sequencer view remains live");
            }
        })
        .await
        .expect("initial submission times out");

        assert!(matches!(
            actions_rx.recv().await,
            Some(BlockSyncAction::QueryNeededBlocks { .. })
        ));

        let retried = time::timeout(Duration::from_secs(1), actions_rx.recv())
            .await
            .expect("submission is retried after capacity returns")
            .expect("action channel remains live");
        assert!(matches!(
            retried,
            BlockSyncAction::SubmitBlock { owner, source, .. }
                if owner == super::super::test_work_owner()
                    && source == zakura_header_chain::SourceId::from_digest([1; 32])
        ));

        task.abort();
    }

    #[test]
    fn handoff_publishes_applying_decoded_bytes_before_submission() {
        let frontiers = BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        };
        let body_input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let body_input_decoded_attributed_memory_bytes =
            Arc::new(std::sync::atomic::AtomicU64::new(0));
        let mut body = queued_test_body(
            body_input_bytes.clone(),
            body_input_decoded_attributed_memory_bytes.clone(),
        );
        let (_body_tx, body_rx) = mpsc::channel(1);
        let (_control_tx, control_rx) = mpsc::unbounded_channel();
        let (actions, _actions_rx) = mpsc::channel(1);
        let (view_tx, view_rx) = watch::channel(initial_view(frontiers));
        let mut task = SequencerTask::new(
            Sequencer::new(block::Height(0), 1),
            ByteBudget::new(123),
            Arc::new(WorkQueue::new(block::Height(0))),
            Arc::new(PeerRegistry::new()),
            actions,
            ThroughputMeter::new(Instant::now()),
            frontiers,
            Some(super::test_work_scope()),
            crate::zakura::header_sync::SeededRetryJitter::new([0; 32]),
            body_rx,
            control_rx,
            body_input_bytes,
            body_input_decoded_attributed_memory_bytes,
            view_tx,
            Duration::from_secs(60),
            ZakuraTrace::noop(),
        );

        body.leave_queue();
        task.handle_accept_body(body);
        task.publish_decoded_ownership_view();

        let handoff = *view_rx.borrow();
        assert_eq!(handoff.sequencer_input_decoded_attributed_memory_bytes, 0);
        assert!(handoff.applying_decoded_attributed_memory_bytes > 0);
        assert_eq!(handoff.reorder_decoded_attributed_memory_bytes, 0);
        assert_eq!(
            handoff.active_pipeline_decoded_attributed_memory_bytes,
            handoff.applying_decoded_attributed_memory_bytes
        );
    }

    #[test]
    fn dropping_task_releases_queue_and_publishes_terminal_decoded_view() {
        let frontiers = BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        };
        let (body_tx, body_rx) = mpsc::channel(1);
        let body_input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let body_input_decoded_attributed_memory_bytes =
            Arc::new(std::sync::atomic::AtomicU64::new(0));
        body_tx
            .try_send(queued_test_body(
                body_input_bytes.clone(),
                body_input_decoded_attributed_memory_bytes.clone(),
            ))
            .expect("body channel has capacity");
        let (_control_tx, control_rx) = mpsc::unbounded_channel();
        let (actions, _actions_rx) = mpsc::channel(1);
        let mut initial = initial_view(frontiers);
        initial.reorder_decoded_attributed_memory_bytes = 10;
        initial.applying_decoded_attributed_memory_bytes = 20;
        initial.active_pipeline_decoded_attributed_memory_bytes =
            body_input_decoded_attributed_memory_bytes
                .load(std::sync::atomic::Ordering::Relaxed)
                .saturating_add(30);
        let (view_tx, view_rx) = watch::channel(initial);
        let task = SequencerTask::new(
            Sequencer::new(block::Height(0), 1),
            ByteBudget::new(1),
            Arc::new(WorkQueue::new(block::Height(0))),
            Arc::new(PeerRegistry::new()),
            actions,
            ThroughputMeter::new(Instant::now()),
            frontiers,
            Some(super::test_work_scope()),
            crate::zakura::header_sync::SeededRetryJitter::new([0; 32]),
            body_rx,
            control_rx,
            body_input_bytes.clone(),
            body_input_decoded_attributed_memory_bytes.clone(),
            view_tx,
            Duration::from_secs(1),
            ZakuraTrace::noop(),
        );

        drop(task);

        assert_eq!(
            body_input_bytes.load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        assert_eq!(
            body_input_decoded_attributed_memory_bytes.load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        let terminal = *view_rx.borrow();
        assert_eq!(terminal.sequencer_input_decoded_attributed_memory_bytes, 0);
        assert_eq!(terminal.reorder_decoded_attributed_memory_bytes, 0);
        assert_eq!(terminal.applying_decoded_attributed_memory_bytes, 0);
        assert_eq!(terminal.active_pipeline_decoded_attributed_memory_bytes, 0);
    }

    #[tokio::test(start_paused = true)]
    async fn sequencer_view_rate_refresh_does_not_wake_watchers() {
        let initial = test_view();
        let (view_tx, mut view_rx) = watch::channel(initial);

        let rate_only = SequencerView {
            committed_bytes_per_sec: 1024,
            committed_blocks_per_sec: 3,
            ..initial
        };
        publish_sequencer_view(&view_tx, rate_only);

        assert_eq!(*view_rx.borrow(), rate_only);
        assert!(
            time::timeout(Duration::from_millis(1), view_rx.changed())
                .await
                .is_err(),
            "throughput-only view refresh must not wake watchers"
        );

        let schedulable = SequencerView {
            reaction_epoch: 1,
            ..rate_only
        };
        publish_sequencer_view(&view_tx, schedulable);

        view_rx
            .changed()
            .await
            .expect("sequencer view sender is still live");
        assert_eq!(*view_rx.borrow(), schedulable);
    }
}