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
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
//! TCP replication receiver (replica side).
//!
//! Connects to the primary, authenticates, performs catch-up / snapshot
//! recovery, and runs the streaming receive loop via [`streaming_loop`].
//! Builds the replica's local pipeline (journal + matching engine + drain
//! stages) to apply incoming events and ack durable batches back to the
//! primary.
use std::io::{self, Write};
use std::net::{SocketAddr, TcpStream};
use std::os::unix::io::RawFd;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tracing::{info, warn};
use melin_app::Application;
use melin_journal::BufferedWriter;
use super::auth::authenticate_with_primary;
use super::receiver_transport::{
ControlFrameSource, ReceiverTransport, SessionExit, streaming_loop,
};
use super::{
AfterSession, ReplicaPipelineHandles, ResyncDecision, build_replica_pipeline_with_threads,
handle_resync_verdict, handle_session_exit, recover_replica_state, sleep_then_double_backoff,
take_pipeline_for_promotion, teardown_replica_pipeline,
};
use crate::uring_teardown::{DrainBackoff, wake_pending_ops};
use melin_transport_core::replication::protocol::{
Ack, Handshake, MAX_CONTROL_FRAME, MAX_DATA_FRAME, PrimaryMessage, decode_primary_message,
encode_ack, encode_handshake, read_frame,
};
/// Force the kernel to send a TCP ACK immediately rather than holding
/// it in the delayed-ACK timer (~40 ms on Linux). Linux clears
/// `TCP_QUICKACK` after each ACK it sends, so it has to be re-armed.
///
/// A `setsockopt` is ~0.5–1 µs on the receive path's critical section,
/// so the re-arm is not unconditional: an outgoing ack frame already
/// carries the TCP ACK, and the replica sends one per receive cycle in
/// steady state. Only a cycle that produced no ack re-arms — see
/// `UringTransport::acked_since_recv`.
#[inline]
fn arm_tcp_quickack(fd: RawFd) {
let on: libc::c_int = 1;
// SAFETY: fd is a live socket fd owned by the caller for the
// lifetime of this call; the option pointer is to a stack-local
// i32 with the right size.
let rc = unsafe {
libc::setsockopt(
fd,
libc::IPPROTO_TCP,
libc::TCP_QUICKACK,
&on as *const libc::c_int as *const libc::c_void,
std::mem::size_of::<libc::c_int>() as libc::socklen_t,
)
};
if rc != 0 {
// Best-effort tuning: a kernel that refuses TCP_QUICKACK (or a
// socket that just went away) costs delayed-ACK latency, not
// correctness, and the caller has no better recovery than
// continuing. Nothing to log per cycle either — it would fire on
// every receive.
debug_assert!(
std::io::Error::last_os_error().raw_os_error() != Some(libc::EFAULT),
"TCP_QUICKACK setsockopt got EFAULT — bad option pointer"
);
}
}
// ---------------------------------------------------------------------------
// io_uring ReceiverTransport implementation
// ---------------------------------------------------------------------------
const TOKEN_RECV: u64 = 0;
const TOKEN_SEND: u64 = 1;
const TOKEN_PROVIDE: u64 = 2;
// Multishot RECV buffer pool. 16 buffers × MAX_DATA_FRAME each.
const NUM_RECV_BUFFERS: u16 = 16;
const RECV_BUF_SIZE: usize = MAX_DATA_FRAME;
const RECV_BUF_GROUP_ID: u16 = 0;
// CQE flag bits (io_uring ABI).
const IORING_CQE_F_BUFFER: u32 = 1 << 0;
const IORING_CQE_F_MORE: u32 = 1 << 1;
const IORING_CQE_BUFFER_SHIFT: u32 = 16;
/// io_uring–backed receiver transport for kernel TCP.
///
/// Uses `IORING_OP_RECV_MULTI` against a provided buffer pool for
/// incoming frames, and single-shot SEND for acks. Owns the io_uring
/// ring, buffer pool, and ack send state.
struct UringTransport {
ring: io_uring::IoUring,
/// Raw socket fd, also used for the `shutdown(2)` wake in `Drop`.
/// Always outlives the transport: the owning `TcpStream` lives in
/// the reconnect loop, while the transport is a local of the scoped
/// receiver thread that borrows it.
tcp_fd: RawFd,
// Backing storage for the io_uring provided-buffer pool. Never read
// through this handle — the kernel accesses it via raw pointers
// registered in ProvideBuffers, and reads go through `pool_ptr`.
// Owned here so it outlives every RECV the kernel may land in it;
// `Drop` quiesces the ring before letting it go.
recv_pool: Vec<u8>,
pool_ptr: *mut u8,
multishot_active: bool,
connected: bool,
ack_buf: Vec<u8>,
ack_offset: usize,
ack_in_flight: bool,
/// Newest ack accepted while a SEND was in flight — sent the moment
/// the in-flight SEND's CQE is reaped (send-latest-on-completion).
/// `Option<Ack>` rather than a queue: ack cursors are cumulative
/// and monotonic, so when several acks arrive while one send is in
/// flight only the newest pair needs the wire — intermediate values
/// are subsumed. Exactly one SEND is ever outstanding, which keeps
/// the TCP byte stream ordered (io_uring gives no ordering between
/// independent SQEs, and interleaved partial sends would corrupt
/// the frame stream).
pending_ack: Option<Ack>,
/// Whether an ack frame has been handed to the kernel since the last
/// receive cycle. An outgoing data segment carries the TCP ACK with
/// it, so an acking cycle needs no `TCP_QUICKACK` re-arm — only a
/// silent one does. See [`arm_tcp_quickack`].
acked_since_recv: bool,
}
impl UringTransport {
fn new(tcp_stream: &TcpStream) -> io::Result<Self> {
use io_uring::{IoUring, opcode, types};
use std::os::unix::io::AsRawFd;
let tcp_fd = tcp_stream.as_raw_fd();
let mut ring: IoUring = IoUring::builder()
.setup_single_issuer()
.build(64)
.map_err(|e| io::Error::other(format!("io_uring init failed: {e}")))?;
ring.submitter()
.register_files(&[tcp_fd])
.map_err(|e| io::Error::other(format!("io_uring register_files failed: {e}")))?;
arm_tcp_quickack(tcp_fd);
// Pin io-wq workers to core 0.
{
let mut cpuset: libc::cpu_set_t = unsafe { std::mem::zeroed() };
unsafe { libc::CPU_SET(0, &mut cpuset) };
let _ = ring.submitter().register_iowq_aff(&cpuset);
}
let mut recv_pool: Vec<u8> = vec![0u8; NUM_RECV_BUFFERS as usize * RECV_BUF_SIZE];
let pool_ptr = recv_pool.as_mut_ptr();
// Provide the buffer pool to io_uring.
{
let sqe = opcode::ProvideBuffers::new(
pool_ptr,
RECV_BUF_SIZE as i32,
NUM_RECV_BUFFERS,
RECV_BUF_GROUP_ID,
0,
)
.build()
.user_data(TOKEN_PROVIDE);
unsafe { ring.submission().push(&sqe).expect("SQ full") };
ring.submit_and_wait(1)?;
let cqe = ring
.completion()
.next()
.ok_or_else(|| io::Error::other("no cqe after ProvideBuffers"))?;
if cqe.result() < 0 {
return Err(io::Error::other(format!(
"ProvideBuffers failed: {}",
cqe.result()
)));
}
}
// Submit the initial multishot RECV.
let sqe = opcode::RecvMulti::new(types::Fd(tcp_fd), RECV_BUF_GROUP_ID)
.build()
.user_data(TOKEN_RECV);
unsafe { ring.submission().push(&sqe).expect("SQ full") };
Ok(UringTransport {
ring,
tcp_fd,
recv_pool,
pool_ptr,
multishot_active: true,
connected: true,
ack_buf: Vec::with_capacity(64),
ack_offset: 0,
ack_in_flight: false,
pending_ack: None,
acked_since_recv: false,
})
}
/// Encode `ack` into the send buffer and push its SEND SQE. The
/// caller is responsible for submitting (next `ring.submit()` —
/// either `poll_recv`'s top-of-call submit or the eager submit
/// after a chained send). Must only be called with no SEND in
/// flight: the buffer is pinned by `ack_in_flight` until the CQE.
fn push_ack_send(&mut self, ack: &Ack) {
use io_uring::{opcode, types};
debug_assert!(!self.ack_in_flight);
self.ack_buf.clear();
encode_ack(ack, &mut self.ack_buf);
let sqe = opcode::Send::new(
types::Fixed(0),
self.ack_buf.as_ptr(),
self.ack_buf.len() as u32,
)
.build()
.user_data(TOKEN_SEND);
// SAFETY: `ack_buf` is owned by this transport and pinned by
// `ack_in_flight = true` until the matching CQE is reaped. The
// ring is single-threaded.
unsafe { self.ring.submission().push(&sqe).expect("SQ full") };
self.ack_in_flight = true;
self.ack_offset = 0;
self.acked_since_recv = true;
}
/// Settle the kernel-ownership flags from CQEs that were reaped out
/// of the completion queue but will not be processed, because
/// [`Self::poll_recv`] is bailing out on a failed session.
///
/// Only the flags — the payloads are deliberately discarded, and
/// nothing is resubmitted, since the session is over. Skipping this
/// would leave `ack_in_flight` set for a SEND the kernel has
/// already returned, and [`Self::drain`] would then wait out its
/// whole deadline on a completion that can never arrive again.
fn settle_unprocessed(&mut self, rest: &[(u64, i32, u32)]) {
for &(token, _result, flags) in rest {
match token {
TOKEN_RECV if (flags & IORING_CQE_F_MORE) == 0 => self.multishot_active = false,
TOKEN_SEND => self.ack_in_flight = false,
_ => {}
}
}
}
/// Reap completions until the kernel holds neither buffer, bounded
/// by [`crate::uring_teardown::DRAIN_TIMEOUT`]. `true` means the
/// multishot RECV has terminated and any SEND has settled, so both
/// buffers are provably free of kernel references.
///
/// Unlike the sender's ring there is no in-flight *count* to drive
/// this: multishot RECV is a single SQE that yields many CQEs and
/// only settles on the one without `IORING_CQE_F_MORE`. So the two
/// existing flags are the drain condition, and CQEs are classified
/// here rather than reusing `poll_recv` — during teardown the
/// payloads are discarded, consumed buffers are not re-provided,
/// and neither the multishot nor a partial send is resubmitted.
fn drain(&mut self) -> bool {
// Flush SQEs pushed but never submitted — notably the initial
// multishot RECV and any resubmission queued by the last
// `poll_recv`. Until they reach the kernel no CQE is coming,
// but the kernel takes the buffer pointers the moment it sees
// them, so they cannot simply be abandoned in the SQ either.
loop {
match self.ring.submit() {
Ok(_) => break,
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(_) => return false,
}
}
let mut backoff = DrainBackoff::new();
while self.multishot_active || self.ack_in_flight {
for cqe in self.ring.completion() {
match cqe.user_data() {
// The kernel stops writing into the pool only once
// the multishot arm is retired, which it signals by
// clearing F_MORE. A CQE that still carries F_MORE
// is data landing mid-teardown: discard it and keep
// waiting for the terminal one.
TOKEN_RECV if (cqe.flags() & IORING_CQE_F_MORE) == 0 => {
self.multishot_active = false;
}
// Settles whether the send completed, errored, or
// went partial: either way the kernel is done
// reading `ack_buf` for this operation.
TOKEN_SEND => self.ack_in_flight = false,
// ProvideBuffers only hands the kernel addresses;
// it never touches pool contents, so a pending one
// is not a reason to keep waiting.
_ => {}
}
}
if (self.multishot_active || self.ack_in_flight) && !backoff.wait() {
return false;
}
}
true
}
}
impl Drop for UringTransport {
fn drop(&mut self) {
wake_pending_ops(self.tcp_fd);
if !self.drain() {
// The drain could not be proven complete, so the kernel may
// still land a RECV in the buffer pool or read `ack_buf`
// for an in-flight SEND. Leak both rather than hand the
// allocator memory the kernel still touches — a session
// that is tearing down anyway pays a bounded one-off cost.
std::mem::forget(std::mem::take(&mut self.recv_pool));
std::mem::forget(std::mem::take(&mut self.ack_buf));
tracing::warn!(
multishot_active = self.multishot_active,
ack_in_flight = self.ack_in_flight,
"io_uring teardown drain did not complete; leaking receiver buffers"
);
}
}
}
impl ReceiverTransport for UringTransport {
fn poll_recv(&mut self, recv_buf: &mut Vec<u8>) -> io::Result<bool> {
use io_uring::{opcode, types};
if !self.connected {
return Err(io::Error::other("not connected"));
}
// Submit pending SQEs (ProvideBuffers re-provisions, Send
// remainders, multishot resubmissions).
let pending = self.ring.submission().len();
if pending > 0 {
self.ring.submit()?;
}
// Drain CQEs.
let mut cqes: [(u64, i32, u32); 16] = [(0, 0, 0); 16];
let mut cqe_count = 0;
{
let mut cq = self.ring.completion();
while cqe_count < cqes.len() {
match cq.next() {
Some(cqe) => {
cqes[cqe_count] = (cqe.user_data(), cqe.result(), cqe.flags());
cqe_count += 1;
}
None => break,
}
}
}
let mut any_recv = false;
// Set when a queued ack is chained onto a completed SEND below —
// it must hit the wire within THIS call, not ride the next
// poll_recv's top-of-call submit one loop iteration later.
let mut submit_chained_ack = false;
for (idx, &(token, result, flags)) in cqes[..cqe_count].iter().enumerate() {
// Every early return below abandons the CQEs after `idx`,
// which have already been reaped out of the CQ — hence the
// `settle_unprocessed` calls: without them teardown would
// wait on a completion that has come and gone.
match token {
TOKEN_RECV => {
if (flags & IORING_CQE_F_MORE) == 0 {
self.multishot_active = false;
}
if result < 0 {
if result == -libc::ENOBUFS {
tracing::debug!("recv multishot ENOBUFS — pool exhausted");
continue;
}
self.connected = false;
self.settle_unprocessed(&cqes[idx + 1..cqe_count]);
return Err(io::Error::other(format!(
"primary disconnected (recv returned {result})"
)));
}
if result == 0 {
self.connected = false;
self.settle_unprocessed(&cqes[idx + 1..cqe_count]);
return Err(io::Error::other("primary disconnected (recv returned 0)"));
}
if (flags & IORING_CQE_F_BUFFER) == 0 {
self.connected = false;
self.settle_unprocessed(&cqes[idx + 1..cqe_count]);
return Err(io::Error::other("recv cqe missing F_BUFFER flag"));
}
let n = result as usize;
let buf_id = (flags >> IORING_CQE_BUFFER_SHIFT) as usize;
// SAFETY: buf_id from kernel CQE for a buffer we
// provided from recv_pool; kernel wrote n bytes.
let buf_ptr = unsafe { self.pool_ptr.add(buf_id * RECV_BUF_SIZE) };
let slice = unsafe { std::slice::from_raw_parts(buf_ptr, n) };
recv_buf.extend_from_slice(slice);
any_recv = true;
// Re-provide the consumed buffer.
let provide_sqe = opcode::ProvideBuffers::new(
buf_ptr,
RECV_BUF_SIZE as i32,
1,
RECV_BUF_GROUP_ID,
buf_id as u16,
)
.build()
.user_data(TOKEN_PROVIDE);
unsafe { self.ring.submission().push(&provide_sqe).expect("SQ full") };
}
TOKEN_PROVIDE if result < 0 => {
tracing::debug!("ProvideBuffers re-provision failed: {result}");
}
TOKEN_SEND => {
if result < 0 {
self.connected = false;
// This CQE is the kernel handing `ack_buf` back,
// failure or not — record that before bailing.
self.ack_in_flight = false;
self.settle_unprocessed(&cqes[idx + 1..cqe_count]);
return Err(io::Error::other(format!(
"ack send error (returned {result})"
)));
}
let sent = result as usize;
self.ack_offset += sent;
if self.ack_offset >= self.ack_buf.len() {
self.ack_buf.clear();
self.ack_offset = 0;
self.ack_in_flight = false;
// Send-latest-on-completion: an ack accepted
// while this send was in flight goes out now
// instead of waiting a full loop iteration for
// the next flush. Chained only after FULL
// completion — a partial send's remainder keeps
// exclusive ownership of the byte stream.
if let Some(ack) = self.pending_ack.take() {
self.push_ack_send(&ack);
submit_chained_ack = true;
}
} else {
// Partial send — resubmit remainder.
let sqe = opcode::Send::new(
types::Fixed(0),
self.ack_buf[self.ack_offset..].as_ptr(),
(self.ack_buf.len() - self.ack_offset) as u32,
)
.build()
.user_data(TOKEN_SEND);
unsafe { self.ring.submission().push(&sqe).expect("SQ full") };
}
}
_ => {}
}
}
// Resubmit multishot if terminated.
if !self.multishot_active {
let sqe = opcode::RecvMulti::new(types::Fd(self.tcp_fd), RECV_BUF_GROUP_ID)
.build()
.user_data(TOKEN_RECV);
unsafe { self.ring.submission().push(&sqe).expect("SQ full") };
self.multishot_active = true;
}
// Flush a chained ack to the kernel before returning (also
// carries any multishot resubmission pushed above).
if submit_chained_ack {
self.ring.submit()?;
}
if any_recv {
// One decision per receive cycle rather than a setsockopt per
// RECV CQE — and none at all while the replica is acking,
// since each ack frame is an outgoing segment that carries
// the TCP ACK. A cycle that produces no ack re-arms, so a
// stream that goes app-level silent waits at most one cycle
// (not a delayed-ACK timer) for its next immediate ACK.
if self.acked_since_recv {
self.acked_since_recv = false;
} else {
arm_tcp_quickack(self.tcp_fd);
}
}
Ok(any_recv)
}
fn send_ack(&mut self, ack: &Ack) -> io::Result<bool> {
if self.ack_in_flight {
// Coalesce: overwrite any previously queued value — the
// cursors are cumulative, so the newest pair subsumes
// everything before it. Sent on the in-flight SEND's CQE.
self.pending_ack = Some(*ack);
return Ok(true);
}
self.push_ack_send(ack);
Ok(true)
}
fn ack_in_flight(&self) -> bool {
// Pending counts as in flight: the drain paths use this to mean
// "everything offered has reached the wire", and the flush gate
// in `streaming_loop` recomputes a fresh ack next iteration
// anyway.
self.ack_in_flight || self.pending_ack.is_some()
}
fn is_connected(&mut self) -> bool {
self.connected
}
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/// Kernel-TCP control-frame source: a blocking `read_frame` on the
/// replication stream. Drives the shared [`receive_chunked_body`] (and,
/// later, the rest of the resync transfer). See [`ControlFrameSource`].
struct TcpFrameSource<'a> {
reader: &'a mut TcpStream,
}
impl ControlFrameSource for TcpFrameSource<'_> {
fn next_frame(
&mut self,
max_size: usize,
) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
Ok(read_frame(self.reader, max_size)?)
}
}
/// Outcome of `run_receiver`: `None` = clean shutdown, `Some` = promotion.
pub type ReceiverResult<A, W> = Result<Option<(A, W)>, Box<dyn std::error::Error>>;
#[allow(clippy::too_many_arguments)]
pub fn run_receiver<A>(
primary_addr: SocketAddr,
journal_path: &std::path::Path,
signing_key: &ed25519_dalek::SigningKey,
shutdown: &AtomicBool,
// The handles this loop shares with the admin endpoint and the
// control-plane raft driver — see [`super::ReplicaControlPlane`]
// for each field's contract.
control: &super::ReplicaControlPlane,
snapshot_interval_ms: u64,
snapshot_path: std::path::PathBuf,
cores: crate::layout::PipelineCores,
// Passed straight to the replica's journal stage; see
// `build_replica_pipeline_with_threads`.
staging_mode: melin_journal::StagingMode,
group_commit_delay: std::time::Duration,
pipeline_depth: usize,
factory: std::sync::Arc<dyn melin_app::app_factory::AppFactory<App = A>>,
fence_state: std::sync::Arc<melin_transport_core::fence::FenceState>,
) -> ReceiverResult<A, BufferedWriter<A::Event>>
where
A: Application + Send + 'static,
A::Event: Send + Sync + 'static,
A::Report: Send + 'static,
A::QueryResponse: Send + 'static,
{
let super::ReplicaControlPlane {
promote,
tip_ready,
journal_tip,
primary_link_up,
primary_ack_policy,
pipeline_healthy,
} = control;
// Recover whenever any journal segment survives — live OR archived;
// fresh replicas get `(None, None, 0, zeros)`. See
// `recover_replica_state` for the lineage rules.
let (mut exchange, mut journal_writer, mut last_sequence, mut chain_hash) =
recover_replica_state::<A, BufferedWriter<A::Event>>(
journal_path,
&snapshot_path,
factory.as_ref(),
&fence_state,
)?;
// The fence epoch now reflects the recovered journal (a fresh replica
// legitimately recovers epoch 0). Seed the advertised sequence from
// the same recovery before releasing the flag, so the first tip the
// raft driver trusts is already the recovered high-water mark.
// Release-store so the driver's Acquire-load sees both.
journal_tip.advance(melin_transport_core::WireSeq::new(last_sequence));
tip_ready.store(true, Ordering::Release);
let mut backoff = std::time::Duration::from_secs(1);
// Consecutive mid-stream divergence resyncs this process has
// attempted — see `MAX_INPROCESS_DIVERGENCE_RESYNCS`.
let mut divergence_resyncs: u32 = 0;
let mut send_buf = Vec::with_capacity(64);
let mut pipeline: Option<ReplicaPipelineHandles<A, BufferedWriter<A::Event>>> = None;
// --- Outer reconnect loop ---
loop {
// No authenticated session while (re)connecting — the raft
// driver may auto-promote from here on if it wins an election.
primary_link_up.store(false, Ordering::Release);
if let Some(p) = pipeline.as_ref() {
// The handshake pair (last_sequence, chain_hash) must come
// from ONE FsyncState snapshot — the journal stage keeps
// flushing while we reconnect, and the primary's handshake
// validation recomputes its chain at exactly the sequence
// we claim. Reading the sequence and the hash from two
// separate sources would tear under load, and a torn pair
// is indistinguishable from divergence (false resync of a
// healthy replica).
if let Some(ref lock) = p.chain_hash_lock {
let fsync_state = lock.load();
last_sequence = fsync_state.journal_seq.get();
chain_hash = fsync_state.chain_hash;
} else {
last_sequence = p.last_seq.load().get();
}
}
// Sole authority for shutdown/promote while disconnected: every
// backoff arm just sleeps (the sleep observes both flags) and
// continues back here, so teardown/promotion handling exists
// exactly once.
if shutdown.load(Ordering::Relaxed) {
if let Some(p) = pipeline.take() {
let _ = teardown_replica_pipeline::<A, BufferedWriter<A::Event>>(p);
}
return Ok(None);
}
if promote.is_requested() {
info!("promotion triggered while disconnected");
return take_pipeline_for_promotion(&mut pipeline, &mut exchange, &mut journal_writer);
}
// --- Connect and authenticate ---
info!(primary = %primary_addr, "connecting to primary as replica");
let stream = match TcpStream::connect(primary_addr) {
Ok(s) => s,
Err(e) => {
warn!(
error = %e,
backoff_secs = backoff.as_secs(),
"failed to connect to primary — retrying"
);
sleep_then_double_backoff(&mut backoff, shutdown, promote);
continue;
}
};
if let Err(e) = stream.set_nodelay(true) {
warn!(error = %e, "failed to set TCP_NODELAY on replica receive socket");
}
{
use std::os::unix::io::AsRawFd;
let busy_poll: libc::c_int = 50;
let rc = unsafe {
libc::setsockopt(
stream.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_BUSY_POLL,
&busy_poll as *const libc::c_int as *const libc::c_void,
std::mem::size_of::<libc::c_int>() as libc::socklen_t,
)
};
if rc != 0 {
let err = std::io::Error::last_os_error();
warn!(error = %err, "failed to set SO_BUSY_POLL on replica receive socket");
}
}
stream.set_read_timeout(Some(std::time::Duration::from_secs(5)))?;
let mut reader = stream.try_clone()?;
let mut tcp_writer = stream;
// `reader`/`tcp_writer` are clones of one socket; auth is sequential so
// a single handle works. Use `reader` (carries the read timeout above).
if let Err(e) = authenticate_with_primary(&mut reader, signing_key) {
// A read timeout means no challenge arrived: the target
// holds the port but is not serving — typically a
// not-yet-promoted replica (the listener is bound from boot)
// or a primary mid-start. Only other errors suggest a real
// credential problem. SO_RCVTIMEO surfaces as WouldBlock on
// Linux; match TimedOut too for portability.
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
) {
warn!(error = %e, "no auth challenge from primary (not serving yet?) — retrying");
} else {
warn!(error = %e, "authentication failed — retrying");
}
// Drop the socket before sleeping — held through the
// backoff it would sit in the target's accept backlog, and
// a just-promoted primary would waste a replica slot (and
// its 10s auth timeout) on the zombie.
drop(reader);
drop(tcp_writer);
// Back off before redialing — without the sleep this loop
// hammers a primary that keeps refusing us.
sleep_then_double_backoff(&mut backoff, shutdown, promote);
continue;
}
info!("authenticated with primary");
// The primary is demonstrably alive from here until this
// session ends — the raft driver must not auto-promote past it.
primary_link_up.store(true, Ordering::Release);
// --- Handshake ---
// Advertise our fencing epoch. If we are ahead of the primary it
// sees this and self-demotes (it's a stale ex-primary); see
// `crate::fence` and the sender's handshake handling.
let handshake = Handshake {
last_sequence,
chain_hash,
epoch: fence_state.epoch(),
};
send_buf.clear();
encode_handshake(&handshake, &mut send_buf);
tcp_writer.write_all(&send_buf)?;
tcp_writer.flush()?;
send_buf.clear();
// --- Protocol negotiation ---
// `session_start` is the resume point this streaming session
// continues from — the value that anchors the receiver's
// sequence-contiguity gate. Derived from local knowledge (our
// own handshake, or the verified snapshot), never from the
// wire.
let response_frame = read_frame(&mut reader, MAX_CONTROL_FRAME)?;
let response = decode_primary_message(&response_frame)?;
let (stream_lineage, session_start) = match response {
PrimaryMessage::StreamStart {
start_sequence,
segment_start_sequence,
anchor_hash,
epoch,
ack_policy,
} => {
// Fence: refuse to follow a primary whose epoch is behind
// ours — following its (divergent) lineage on top of our
// more-current state would corrupt the journal. Disconnect
// and retry with backoff; the operator's logs flag the
// misdirected `--replica-of`. Our handshake (already sent)
// carries our higher epoch, so the stale primary also fences
// itself on its side.
let our_epoch = fence_state.epoch();
if fence_state.refuses_primary(epoch) {
warn!(
primary_epoch = epoch,
our_epoch,
"primary is behind our fencing epoch — refusing to follow stale primary"
);
// Drop the socket before sleeping — see the auth
// failure arm above.
drop(reader);
drop(tcp_writer);
sleep_then_double_backoff(&mut backoff, shutdown, promote);
continue;
}
// Adopt the primary's epoch immediately; streamed `EpochBump`s
// keep it current thereafter. Likewise the ack policy
// (heartbeats keep it current mid-session).
fence_state.observe_epoch(epoch);
primary_ack_policy.store(ack_policy, Ordering::Release);
info!(start_sequence, epoch, ack_policy, "streaming started");
((segment_start_sequence, anchor_hash), last_sequence)
}
ref resync @ (PrimaryMessage::NeedSnapshot | PrimaryMessage::HashMismatch) => {
let divergent = matches!(resync, PrimaryMessage::HashMismatch);
// `map_err` drops `Send + Sync` by coercion — the `?` `From`
// bridge doesn't apply directly across the two boxed trait
// objects (`Box<dyn Error + Send + Sync>` → `Box<dyn Error>`).
let decision = handle_resync_verdict(
divergent,
&mut TcpFrameSource {
reader: &mut reader,
},
&mut pipeline,
&mut exchange,
&mut journal_writer,
journal_path,
&snapshot_path,
&fence_state,
control,
&mut last_sequence,
&mut chain_hash,
)
.map_err(|e| -> Box<dyn std::error::Error> { e })?;
match decision {
ResyncDecision::Ready {
segment_start_sequence,
anchor_hash,
resume_sequence,
} => ((segment_start_sequence, anchor_hash), resume_sequence),
ResyncDecision::Retry => {
sleep_then_double_backoff(&mut backoff, shutdown, promote);
continue;
}
}
}
_ => {
return Err(format!("unexpected response: {response:?}").into());
}
};
// --- Create journal for fresh replica ---
// The StreamStart lineage gives the segment header identity
// (starting sequence + chain anchor) the primary's own journal
// lineage began with; creating the local segment from the same
// identity makes the replica's segment byte-identical to the
// primary's, and adopted `Rotate` boundaries keep it that way
// across rotations (bitwise mirror).
if pipeline.is_none() && journal_writer.is_none() {
let (lineage_start, lineage_anchor) = stream_lineage;
let writer =
BufferedWriter::create_continuing(journal_path, lineage_start, lineage_anchor)?;
let mut fresh = factory.empty();
factory.apply_operator_policy(&mut fresh);
exchange = Some(fresh);
journal_writer = Some(writer);
}
// --- Build pipeline if absent ---
if pipeline.is_none() {
let cur_exchange = exchange.take().expect("exchange initialized");
let cur_writer = journal_writer.take().expect("journal_writer initialized");
pipeline = Some(build_replica_pipeline_with_threads::<A>(
cur_exchange,
cur_writer,
cores,
staging_mode,
snapshot_interval_ms,
snapshot_path.clone(),
group_commit_delay,
Arc::clone(&fence_state),
Arc::clone(pipeline_healthy),
)?);
}
// --- Streaming session ---
let result = {
let p = pipeline.as_mut().expect("pipeline must exist by here");
let input_producer = &mut p.input_producer;
let journal_cursor = p.journal_cursor.as_ref();
let stream_marks = &p.stream_marks;
let journal_failed = &p.journal_failed;
std::thread::scope(|s| {
let handle = std::thread::Builder::new()
.name("replica-receiver".into())
.spawn_scoped(s, || {
melin_app::affinity::pin_thread("replica-receiver", cores.reader.core);
let mut transport = match UringTransport::new(&tcp_writer) {
Ok(t) => t,
Err(e) => {
tracing::error!(error = %e, "UringTransport init failed");
// Synthetic result: streaming never started,
// so `heard_from_primary` stays false and the
// reconnect keeps its escalated backoff — this
// failure is local (io_uring setup), and a
// persistent one must not redial at 1 Hz.
return super::receiver_transport::StreamingResult {
exit: SessionExit::Disconnected,
heard_from_primary: false,
};
}
};
streaming_loop::<UringTransport, A::Event>(
&mut transport,
input_producer,
journal_cursor,
shutdown,
control,
pipeline_depth,
cores.reader.wait,
session_start,
Vec::with_capacity(MAX_DATA_FRAME + 4),
None,
stream_marks,
journal_failed,
)
})
.expect("spawn replica-receiver thread");
handle.join().expect("replica-receiver thread panicked")
})
};
primary_link_up.store(false, Ordering::Release);
match handle_session_exit(
result,
&mut pipeline,
&mut divergence_resyncs,
&mut backoff,
last_sequence,
journal_path,
&snapshot_path,
factory.as_ref(),
&fence_state,
shutdown,
promote,
// Kernel TCP needs no explicit close — the `TcpStream` is
// dropped on the next loop turn when a fresh connection
// replaces it.
|| {},
) {
AfterSession::Return(r) => return r,
AfterSession::Resync {
exchange: ex,
journal_writer: wr,
last_sequence: seq,
chain_hash: hash,
} => {
exchange = ex;
journal_writer = wr;
last_sequence = seq;
chain_hash = hash;
continue;
}
AfterSession::Reconnect => {}
}
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use crate::uring_teardown::DRAIN_TIMEOUT;
use std::io::Read;
use std::net::TcpListener;
use std::time::{Duration, Instant};
use melin_transport_core::replication::protocol::{ReplicaMessage, decode_replica_message};
/// Connected localhost pair: (transport side, peer side).
fn socket_pair() -> (TcpStream, TcpStream) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let client = TcpStream::connect(addr).unwrap();
let (server, _) = listener.accept().unwrap();
(client, server)
}
fn ack(seq: u64) -> Ack {
Ack {
acked_sequence: seq,
in_memory_sequence: seq,
}
}
/// Drive `poll_recv` until every accepted ack has reached the wire.
fn flush_acks(transport: &mut UringTransport) {
let mut recv_buf = Vec::new();
let deadline = Instant::now() + Duration::from_secs(5);
while transport.ack_in_flight() {
transport.poll_recv(&mut recv_buf).unwrap();
assert!(Instant::now() < deadline, "ack send never completed");
std::hint::spin_loop();
}
}
/// Read `expect` length-prefixed ack frames from the peer socket.
fn read_acks(peer: &mut TcpStream, expect: usize) -> Vec<Ack> {
peer.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut buf = Vec::new();
let mut chunk = [0u8; 256];
let mut acks = Vec::new();
while acks.len() < expect {
let n = peer.read(&mut chunk).expect("peer read");
assert!(n > 0, "peer closed before all acks arrived");
buf.extend_from_slice(&chunk[..n]);
// Parse complete frames.
loop {
if buf.len() < 4 {
break;
}
let len = u32::from_le_bytes(buf[0..4].try_into().unwrap()) as usize;
if buf.len() < 4 + len {
break;
}
match decode_replica_message(&buf[4..4 + len]).expect("decodable frame") {
ReplicaMessage::Ack(a) => acks.push(a),
other => panic!("expected Ack frame, got {other:?}"),
}
buf.drain(..4 + len);
}
}
assert!(buf.is_empty(), "trailing bytes after expected acks");
acks
}
#[test]
fn coalesces_to_latest_ack_while_send_in_flight() {
let (client, mut peer) = socket_pair();
let mut transport = UringTransport::new(&client).unwrap();
// First ack goes straight onto the wire path; the next two are
// accepted while it is in flight (the flag clears only when the
// CQE is reaped in poll_recv, so this is deterministic) and
// coalesce — only the newest survives.
assert!(transport.send_ack(&ack(1)).unwrap());
assert!(transport.ack_in_flight());
assert!(transport.send_ack(&ack(2)).unwrap());
assert!(transport.send_ack(&ack(3)).unwrap());
flush_acks(&mut transport);
// Exactly two frames, in cursor order: ack(2) was subsumed.
let acks = read_acks(&mut peer, 2);
let seqs: Vec<u64> = acks.iter().map(|a| a.acked_sequence).collect();
assert_eq!(seqs, vec![1, 3]);
}
#[test]
fn sequential_acks_all_reach_the_wire_in_order() {
let (client, mut peer) = socket_pair();
let mut transport = UringTransport::new(&client).unwrap();
for seq in 1..=3 {
assert!(transport.send_ack(&ack(seq)).unwrap());
flush_acks(&mut transport);
}
let acks = read_acks(&mut peer, 3);
let seqs: Vec<u64> = acks.iter().map(|a| a.acked_sequence).collect();
assert_eq!(seqs, vec![1, 2, 3]);
}
/// The multishot RECV armed at construction stays armed for the
/// whole session, so every ordinary session exit drops the
/// transport with the kernel still holding pointers into the buffer
/// pool. `Drop` has to quiesce it — and promptly: a drain that
/// cannot settle only gives up on the deadline, so finishing well
/// inside it is what proves the buffers were released rather than
/// leaked.
#[test]
fn drop_quiesces_the_multishot_recv() {
let (client, _peer) = socket_pair();
let mut transport = UringTransport::new(&client).unwrap();
// `new` only pushes the multishot RECV; the first poll submits
// it. Teardown from that state is what a real session does.
let mut recv_buf = Vec::new();
transport.poll_recv(&mut recv_buf).unwrap();
assert!(transport.multishot_active);
let started = Instant::now();
drop(transport);
let elapsed = started.elapsed();
assert!(
elapsed < DRAIN_TIMEOUT / 4,
"teardown took {elapsed:?}, close to the {DRAIN_TIMEOUT:?} deadline"
);
}
/// A failing session bails out of `poll_recv` part-way through a
/// batch, abandoning CQEs that were already reaped out of the
/// completion queue. Their kernel-ownership flags still have to be
/// recorded: otherwise teardown waits out its whole deadline for a
/// SEND completion that was consumed here and can never arrive
/// again, and then leaks the buffer pool.
#[test]
fn abandoned_cqes_still_settle_kernel_ownership() {
let (client, _peer) = socket_pair();
let mut transport = UringTransport::new(&client).unwrap();
let mut recv_buf = Vec::new();
transport.poll_recv(&mut recv_buf).unwrap();
// Stands in for a SEND whose CQE landed in the batch behind a
// RECV CQE that failed the session.
transport.ack_in_flight = true;
transport.settle_unprocessed(&[(TOKEN_SEND, 13, 0)]);
assert!(
!transport.ack_in_flight,
"an abandoned SEND completion must release `ack_buf`"
);
// A RECV that still carries F_MORE leaves the arm live — the
// kernel may write into the pool again, so teardown must wait.
transport.settle_unprocessed(&[(TOKEN_RECV, 128, IORING_CQE_F_MORE)]);
assert!(
transport.multishot_active,
"F_MORE must leave the multishot armed"
);
// Only the terminal completion retires it.
transport.settle_unprocessed(&[(TOKEN_RECV, 0, 0)]);
assert!(!transport.multishot_active);
// The real arm submitted by `poll_recv` above is still live in
// the kernel; restore the flag the assertion just cleared so
// `Drop` drains it instead of freeing the pool underneath it.
transport.multishot_active = true;
}
/// Same, for the other kernel-visible buffer: an ack SEND pushed
/// but never submitted, so the drain has to flush the SQ before it
/// can wait for anything.
#[test]
fn drop_quiesces_a_pending_ack_send() {
let (client, _peer) = socket_pair();
let mut transport = UringTransport::new(&client).unwrap();
assert!(transport.send_ack(&ack(7)).unwrap());
assert!(transport.ack_in_flight());
let started = Instant::now();
drop(transport);
let elapsed = started.elapsed();
assert!(
elapsed < DRAIN_TIMEOUT / 4,
"teardown took {elapsed:?}, close to the {DRAIN_TIMEOUT:?} deadline"
);
}
/// Scripted-primary scaffolding shared by the end-to-end receiver
/// tests below: a no-op application over a trivial event, the
/// primary-side frame helpers, and common fixtures. Gated like its
/// consumers so a `no-persist` build carries no dead test code.
#[cfg(not(feature = "no-persist"))]
mod scripted {
use super::*;
use melin_app::app_factory::AppFactory;
use melin_app::{AppEvent, Application, ApplyCtx, CodecError, RejectReason};
// Re-export so the sibling test modules can name the generic
// slot type without reaching into transport-core themselves.
pub(super) use melin_transport_core::pipeline::InputSlot;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct EvtAdd(pub(super) u64);
impl AppEvent for EvtAdd {
const MAX_ENCODED_SIZE: usize = 8;
fn encoded_size(&self) -> usize {
8
}
fn encode(&self, buf: &mut [u8]) -> usize {
buf[..8].copy_from_slice(&self.0.to_le_bytes());
8
}
fn decode(buf: &[u8]) -> Result<Self, CodecError> {
if buf.len() < 8 {
return Err(CodecError::Truncated);
}
Ok(EvtAdd(u64::from_le_bytes(buf[..8].try_into().expect("8"))))
}
fn is_query(&self) -> bool {
false
}
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Rpt;
pub(super) struct App;
impl Application for App {
type Event = EvtAdd;
type Report = Rpt;
type QueryResponse = Rpt;
const APP_VERSION: u16 = 1;
fn apply(&mut self, _e: EvtAdd, _ctx: &ApplyCtx, _out: &mut Vec<Rpt>) -> Option<Rpt> {
None
}
fn tick(&mut self, _now_ns: u64, _out: &mut Vec<Rpt>) {}
fn check_request_seq(&mut self, _key_hash: u64, _seq: u64) -> bool {
true
}
fn build_reject(_e: &EvtAdd, _r: RejectReason) -> Rpt {
Rpt
}
fn snapshot<W: std::io::Write>(&self, _w: &mut W) -> std::io::Result<()> {
Ok(())
}
fn restore<R: std::io::Read>(_r: &mut R) -> std::io::Result<Self> {
Ok(App)
}
}
pub(super) struct Factory;
impl AppFactory for Factory {
type App = App;
fn empty(&self) -> App {
App
}
fn prefault(&self, _app: &mut App) {}
}
/// Deterministic replica signing-key bytes; [`replica_auth`]
/// builds the matching authorized-keys table.
pub(super) const REPLICA_KEY: [u8; 32] = [0xFC; 32];
/// The authorized-keys table listing [`REPLICA_KEY`]'s public
/// half.
pub(super) fn replica_auth() -> melin_app::auth::AuthorizedKeys {
let key = ed25519_dalek::SigningKey::from_bytes(&REPLICA_KEY);
let pub_b64 = base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
key.verifying_key().to_bytes(),
);
melin_app::auth::AuthorizedKeys::parse(&format!("replication {pub_b64} test-replica\n"))
.expect("parse keys")
}
/// Read one length-prefixed `ReplicaMessage` frame.
pub(super) fn read_replica_msg(stream: &mut TcpStream) -> ReplicaMessage {
let mut len_buf = [0u8; 4];
stream.read_exact(&mut len_buf).expect("frame length");
let len = u32::from_le_bytes(len_buf) as usize;
let mut payload = vec![0u8; len];
stream.read_exact(&mut payload).expect("frame payload");
decode_replica_message(&payload).expect("decodable replica frame")
}
/// Skip frames until an `Ack` at or past `seq` arrives.
pub(super) fn wait_for_ack(stream: &mut TcpStream, seq: u64) {
loop {
if let ReplicaMessage::Ack(a) = read_replica_msg(stream)
&& a.acked_sequence >= seq
{
return;
}
}
}
/// Accept with a deadline so a replica that fails to (re)connect
/// fails the test instead of hanging it.
pub(super) fn accept_within(listener: &std::net::TcpListener, secs: u64) -> TcpStream {
let deadline = Instant::now() + Duration::from_secs(secs);
loop {
match listener.accept() {
Ok((s, _)) => {
s.set_read_timeout(Some(Duration::from_secs(10)))
.expect("read timeout");
return s;
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
assert!(Instant::now() < deadline, "replica never connected");
std::thread::sleep(Duration::from_millis(10));
}
Err(e) => panic!("accept failed: {e}"),
}
}
}
}
// -----------------------------------------------------------------
// In-process divergence resync — end to end against a scripted
// primary. Needs hash-chain (divergence is a chain verdict) and
// real persistence (the resync re-derives state from disk).
// -----------------------------------------------------------------
#[cfg(all(feature = "hash-chain", not(feature = "no-persist")))]
mod divergence_resync {
use super::super::super::auth::authenticate_replica;
use super::scripted::*;
use super::*;
use melin_journal::{BufferedWriter, JournalEvent, JournalWrite};
use melin_transport_core::cursors::WireSeq;
use melin_transport_core::replication::catchup::{lineage_origin, snapshot_transfer_with};
use melin_transport_core::replication::protocol::{
encode_hash_mismatch, encode_rotate, encode_stream_start,
};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
/// A scripted primary brings a fresh replica up, streams one
/// event, then announces a rotation with a deliberately wrong
/// tail hash. The replica's journal stage detects divergence —
/// `run_receiver` must repair it WITHOUT exiting: tear the
/// pipeline down, re-derive its handshake position from disk,
/// reconnect, take the HashMismatch verdict, archive the forked
/// lineage, and complete the snapshot + segment-seed resync,
/// then resume streaming on the rebased lineage.
#[test]
fn mid_stream_divergence_resyncs_in_process() {
let dir = tempfile::tempdir().expect("tempdir");
// --- The scripted primary's journal + snapshot, served by
// the real sender-side transfer code in session 2. Entries
// 1..=5, rotation after 2, snapshot at 4 (mid-live-segment).
let primary_journal = dir.path().join("primary.journal");
let mut w = BufferedWriter::<EvtAdd>::create(&primary_journal).expect("create");
let mut chain_at_4 = [0u8; 32];
for v in 1..=5u64 {
w.append(&JournalEvent::App(EvtAdd(v))).expect("append");
if v == 2 {
w.rotate_segment().expect("rotate");
}
if v == 4 {
chain_at_4 = w.chain_hash().expect("chain");
}
}
drop(w);
melin_transport_core::snapshot::save::<App>(
&App,
WireSeq::new(4),
chain_at_4,
0,
&primary_journal.with_extension("snapshot"),
)
.expect("save snapshot");
let (lineage_start, lineage_anchor) =
lineage_origin(&primary_journal).expect("lineage");
// --- Auth: one replica key, authorized.
let authorized_keys = replica_auth();
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
listener.set_nonblocking(true).expect("nonblocking");
let addr = listener.local_addr().expect("addr");
// --- Replica under test.
let replica_journal = dir.path().join("replica.journal");
let replica_snapshot = dir.path().join("replica.snapshot");
let shutdown = Arc::new(AtomicBool::new(false));
let control = crate::replication::ReplicaControlPlane::new();
let cores = crate::layout::PipelineCores::unpinned();
let replica = {
let journal = replica_journal.clone();
let shutdown = Arc::clone(&shutdown);
let control = control.clone();
std::thread::spawn(move || -> Result<bool, String> {
run_receiver::<App>(
addr,
&journal,
&ed25519_dalek::SigningKey::from_bytes(&REPLICA_KEY),
&shutdown,
&control,
3_600_000,
replica_snapshot,
cores,
melin_journal::StagingMode::ZeroFill,
Duration::ZERO,
64,
Arc::new(Factory),
Arc::new(melin_transport_core::fence::FenceState::new(0)),
)
// ReceiverResult's error is !Send — stringify for join().
.map(|state| state.is_none())
.map_err(|e| e.to_string())
})
};
// --- Session 1: fresh sync, one event, then the poisoned
// rotation announce.
let mut s1 = accept_within(&listener, 30);
let mut s1r = s1.try_clone().expect("clone");
authenticate_replica(&mut s1r, &authorized_keys).expect("auth 1");
match read_replica_msg(&mut s1) {
ReplicaMessage::Handshake(h) => {
assert_eq!(h.last_sequence, 0, "fresh replica handshake")
}
other => panic!("expected Handshake, got {other:?}"),
}
let mut buf = Vec::new();
encode_stream_start(0, lineage_start, lineage_anchor, 0, 1, &mut buf);
s1.write_all(&buf).expect("StreamStart 1");
buf.clear();
melin_transport_core::replication_wire::encode_input_batch(
&[InputSlot::<EvtAdd> {
connection_id: 0,
key_hash: 0,
request_seq: 0,
sequence: 1,
timestamp_ns: 1,
event: JournalEvent::App(EvtAdd(1)),
// `()` without latency-trace, a timestamp with it.
publish_ts: Default::default(),
recv_ts: Default::default(),
}],
&mut buf,
);
s1.write_all(&buf).expect("InputBatch");
wait_for_ack(&mut s1, 1);
// Wrong tail hash at the announced boundary — the replica's
// local chain at sequence 1 cannot match this.
buf.clear();
encode_rotate(1, &[0xEE; 32], &mut buf);
s1.write_all(&buf).expect("Rotate");
// --- Session 2: the SAME process reconnects with its
// position re-derived from the forked on-disk journal.
let mut s2 = accept_within(&listener, 30);
let mut s2r = s2.try_clone().expect("clone");
authenticate_replica(&mut s2r, &authorized_keys).expect("auth 2");
match read_replica_msg(&mut s2) {
ReplicaMessage::Handshake(h) => assert_eq!(
h.last_sequence, 1,
"post-divergence handshake must carry the recovered journal position"
),
other => panic!("expected Handshake, got {other:?}"),
}
// The journal stage's divergence failure latched the health
// mirror before the teardown that led to this reconnect, and
// the replacement pipeline is not built until after the resync
// verdict — so at this deterministic point the replica must be
// reporting unhealthy.
assert!(
!control.pipeline_healthy.load(Ordering::Acquire),
"the divergence must have latched the health mirror false"
);
buf.clear();
encode_hash_mismatch(&mut buf);
s2.write_all(&buf).expect("HashMismatch");
let transfer_shutdown = AtomicBool::new(false);
let mut publish = |b: &[u8]| -> std::io::Result<()> {
s2.write_all(b)?;
s2.flush()
};
// Real sender-side resync: SnapshotBegin → chunks →
// SegmentSeedBegin → seed → StreamStart → catch-up (entry 5).
let end = snapshot_transfer_with::<EvtAdd>(
&primary_journal,
&mut publish,
&transfer_shutdown,
1,
)
.expect("snapshot transfer");
assert_eq!(
end,
melin_transport_core::replication::catchup::CatchUpResult::Ok(5)
);
let mut s2_acks = s2.try_clone().expect("clone");
wait_for_ack(&mut s2_acks, 5);
// Streaming resumed on the rebuilt pipeline — the rebuild
// must have reset the health mirror.
assert!(
control.pipeline_healthy.load(Ordering::Acquire),
"the resync rebuild must reset the health mirror true"
);
// --- Clean shutdown; the receiver must return Ok(None) —
// the divergence never escaped as a process-fatal error.
shutdown.store(true, Ordering::Relaxed);
let result = replica.join().expect("replica thread panicked");
assert_eq!(result, Ok(true), "receiver must exit cleanly via shutdown");
// The forked lineage was archived (never deleted), and the
// live journal is the re-seeded one.
assert!(
dir.path().join("replica.journal.divergent.0").exists(),
"divergent lineage must be archived"
);
assert!(replica_journal.exists(), "re-seeded live journal");
}
/// A resync whose snapshot transfer drops mid-flight must retry
/// as a fresh replica with NO leftover in-memory state. On the
/// in-process divergence repair path `recover_replica_state`
/// leaves `exchange`/`journal_writer` populated; the resync arm
/// archives the live journal (renaming it aside) before the
/// transfer. If the transfer then fails and those handles are not
/// nulled, the stale writer — its backing file now under the
/// `.divergent.<n>` archive — survives the fresh-replica create
/// gate (`journal_writer.is_none()` false) and is rebuilt into the
/// next pipeline, so the live journal is never recreated and the
/// new session streams onto an archived-away inode. This pins the
/// fix (mirrors the DPDK receiver): after the failed transfer the
/// retry creates a fresh live journal from the StreamStart lineage.
#[test]
fn resync_transfer_failure_rebuilds_clean_not_over_stale_writer() {
let dir = tempfile::tempdir().expect("tempdir");
// Minimal scripted primary — only its lineage identity is used
// (session 3 streams from genesis; the dropped session 2 never
// reaches the snapshot body).
let primary_journal = dir.path().join("primary.journal");
let mut w = BufferedWriter::<EvtAdd>::create(&primary_journal).expect("create");
for v in 1..=2u64 {
w.append(&JournalEvent::App(EvtAdd(v))).expect("append");
}
drop(w);
let (lineage_start, lineage_anchor) =
lineage_origin(&primary_journal).expect("lineage");
let authorized_keys = replica_auth();
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
listener.set_nonblocking(true).expect("nonblocking");
let addr = listener.local_addr().expect("addr");
let replica_journal = dir.path().join("replica.journal");
let replica_snapshot = dir.path().join("replica.snapshot");
let shutdown = Arc::new(AtomicBool::new(false));
let control = crate::replication::ReplicaControlPlane::new();
let cores = crate::layout::PipelineCores::unpinned();
let replica = {
let journal = replica_journal.clone();
let shutdown = Arc::clone(&shutdown);
let control = control.clone();
std::thread::spawn(move || -> Result<bool, String> {
run_receiver::<App>(
addr,
&journal,
&ed25519_dalek::SigningKey::from_bytes(&REPLICA_KEY),
&shutdown,
&control,
3_600_000,
replica_snapshot,
cores,
melin_journal::StagingMode::ZeroFill,
Duration::ZERO,
64,
Arc::new(Factory),
Arc::new(melin_transport_core::fence::FenceState::new(0)),
)
.map(|state| state.is_none())
.map_err(|e| e.to_string())
})
};
// Helper: stream a single event (seq 1) over an established
// session and wait for its ack.
let stream_one = |s: &mut TcpStream, buf: &mut Vec<u8>| {
buf.clear();
encode_stream_start(0, lineage_start, lineage_anchor, 0, 1, buf);
s.write_all(buf).expect("StreamStart");
buf.clear();
melin_transport_core::replication_wire::encode_input_batch(
&[InputSlot::<EvtAdd> {
connection_id: 0,
key_hash: 0,
request_seq: 0,
sequence: 1,
timestamp_ns: 1,
event: JournalEvent::App(EvtAdd(1)),
publish_ts: Default::default(),
recv_ts: Default::default(),
}],
buf,
);
s.write_all(buf).expect("InputBatch");
};
// --- Session 1: fresh sync, event 1, poisoned rotation —
// the journal stage detects divergence and the receiver
// repairs in-process (`recover_replica_state` repopulates
// `exchange`/`journal_writer`).
let mut buf = Vec::new();
let mut s1 = accept_within(&listener, 30);
let mut s1r = s1.try_clone().expect("clone");
authenticate_replica(&mut s1r, &authorized_keys).expect("auth 1");
match read_replica_msg(&mut s1) {
ReplicaMessage::Handshake(h) => assert_eq!(h.last_sequence, 0, "fresh"),
other => panic!("expected Handshake, got {other:?}"),
}
stream_one(&mut s1, &mut buf);
wait_for_ack(&mut s1, 1);
buf.clear();
encode_rotate(1, &[0xEE; 32], &mut buf);
s1.write_all(&buf).expect("Rotate");
// --- Session 2: reconnect at the recovered position (seq 1),
// verdict HashMismatch (archives the live journal aside), then
// DROP the connection before SnapshotBegin — the transfer
// fails and the receiver must retry as a fresh replica.
let mut s2 = accept_within(&listener, 30);
let mut s2r = s2.try_clone().expect("clone");
authenticate_replica(&mut s2r, &authorized_keys).expect("auth 2");
match read_replica_msg(&mut s2) {
ReplicaMessage::Handshake(h) => assert_eq!(
h.last_sequence, 1,
"reconnect carries the recovered forked position"
),
other => panic!("expected Handshake, got {other:?}"),
}
buf.clear();
encode_hash_mismatch(&mut buf);
s2.write_all(&buf).expect("HashMismatch");
s2.flush().expect("flush");
// Both fds reference the same socket (try_clone dups) — drop
// both to send FIN so the replica's SnapshotBegin read hits EOF.
drop(s2);
drop(s2r);
// --- Session 3: the receiver reconnects as a FRESH replica
// (the archived lineage's position is meaningless, so
// `last_sequence` is 0). It must recreate a live journal from
// the StreamStart lineage, NOT rebuild over the stale writer.
let mut s3 = accept_within(&listener, 30);
let mut s3r = s3.try_clone().expect("clone");
authenticate_replica(&mut s3r, &authorized_keys).expect("auth 3");
match read_replica_msg(&mut s3) {
ReplicaMessage::Handshake(h) => assert_eq!(
h.last_sequence, 0,
"after a failed transfer the retry handshakes as fresh"
),
other => panic!("expected Handshake, got {other:?}"),
}
stream_one(&mut s3, &mut buf);
wait_for_ack(&mut s3, 1);
shutdown.store(true, Ordering::Relaxed);
let result = replica.join().expect("replica thread panicked");
assert_eq!(result, Ok(true), "receiver exits cleanly via shutdown");
// The forked lineage stays archived, and a fresh live journal
// was recreated from the lineage. With the bug, the stale
// writer would be reused and this path would not exist (its
// inode stranded under `.divergent.0`).
assert!(
dir.path().join("replica.journal.divergent.0").exists(),
"forked lineage archived, never deleted"
);
assert!(
replica_journal.exists(),
"fresh live journal recreated after the failed transfer"
);
}
/// The in-process repair budget is one per process lifetime: a
/// second mid-stream divergence is systematic (corruption or a
/// serious bug that the first re-seed did not cure) and the
/// receiver must exit hard instead of looping — each repair
/// cycle archives a full journal copy, and a repair loop would
/// fill the disk while masking the underlying fault.
#[test]
fn second_mid_stream_divergence_exits_hard() {
let dir = tempfile::tempdir().expect("tempdir");
let primary_journal = dir.path().join("primary.journal");
let mut w = BufferedWriter::<EvtAdd>::create(&primary_journal).expect("create");
let mut chain_at_4 = [0u8; 32];
for v in 1..=5u64 {
w.append(&JournalEvent::App(EvtAdd(v))).expect("append");
if v == 2 {
w.rotate_segment().expect("rotate");
}
if v == 4 {
chain_at_4 = w.chain_hash().expect("chain");
}
}
drop(w);
melin_transport_core::snapshot::save::<App>(
&App,
WireSeq::new(4),
chain_at_4,
0,
&primary_journal.with_extension("snapshot"),
)
.expect("save snapshot");
let (lineage_start, lineage_anchor) =
lineage_origin(&primary_journal).expect("lineage");
let authorized_keys = replica_auth();
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
listener.set_nonblocking(true).expect("nonblocking");
let addr = listener.local_addr().expect("addr");
let replica_journal = dir.path().join("replica.journal");
let replica_snapshot = dir.path().join("replica.snapshot");
let shutdown = Arc::new(AtomicBool::new(false));
let control = crate::replication::ReplicaControlPlane::new();
let cores = crate::layout::PipelineCores::unpinned();
let replica = {
let journal = replica_journal.clone();
let shutdown = Arc::clone(&shutdown);
let control = control.clone();
std::thread::spawn(move || -> Result<bool, String> {
run_receiver::<App>(
addr,
&journal,
&ed25519_dalek::SigningKey::from_bytes(&REPLICA_KEY),
&shutdown,
&control,
3_600_000,
replica_snapshot,
cores,
melin_journal::StagingMode::ZeroFill,
Duration::ZERO,
64,
Arc::new(Factory),
Arc::new(melin_transport_core::fence::FenceState::new(0)),
)
.map(|state| state.is_none())
.map_err(|e| e.to_string())
})
};
// Session 1: fresh sync, one event, poisoned rotation.
let mut s1 = accept_within(&listener, 30);
let mut s1r = s1.try_clone().expect("clone");
authenticate_replica(&mut s1r, &authorized_keys).expect("auth 1");
match read_replica_msg(&mut s1) {
ReplicaMessage::Handshake(h) => assert_eq!(h.last_sequence, 0),
other => panic!("expected Handshake, got {other:?}"),
}
let mut buf = Vec::new();
encode_stream_start(0, lineage_start, lineage_anchor, 0, 1, &mut buf);
s1.write_all(&buf).expect("StreamStart 1");
buf.clear();
melin_transport_core::replication_wire::encode_input_batch(
&[InputSlot::<EvtAdd> {
connection_id: 0,
key_hash: 0,
request_seq: 0,
sequence: 1,
timestamp_ns: 1,
event: JournalEvent::App(EvtAdd(1)),
publish_ts: Default::default(),
recv_ts: Default::default(),
}],
&mut buf,
);
s1.write_all(&buf).expect("InputBatch");
wait_for_ack(&mut s1, 1);
buf.clear();
encode_rotate(1, &[0xEE; 32], &mut buf);
s1.write_all(&buf).expect("Rotate 1");
// Session 2: in-process repair (the one allowed), then a
// SECOND poisoned rotation after streaming resumes.
let mut s2 = accept_within(&listener, 30);
let mut s2r = s2.try_clone().expect("clone");
authenticate_replica(&mut s2r, &authorized_keys).expect("auth 2");
match read_replica_msg(&mut s2) {
ReplicaMessage::Handshake(h) => assert_eq!(h.last_sequence, 1),
other => panic!("expected Handshake, got {other:?}"),
}
buf.clear();
encode_hash_mismatch(&mut buf);
s2.write_all(&buf).expect("HashMismatch");
let transfer_shutdown = AtomicBool::new(false);
{
let mut publish = |b: &[u8]| -> std::io::Result<()> {
s2.write_all(b)?;
s2.flush()
};
snapshot_transfer_with::<EvtAdd>(
&primary_journal,
&mut publish,
&transfer_shutdown,
1,
)
.expect("snapshot transfer");
}
buf.clear();
melin_transport_core::replication_wire::encode_input_batch(
&[InputSlot::<EvtAdd> {
connection_id: 0,
key_hash: 0,
request_seq: 0,
sequence: 6,
timestamp_ns: 6,
event: JournalEvent::App(EvtAdd(6)),
publish_ts: Default::default(),
recv_ts: Default::default(),
}],
&mut buf,
);
s2.write_all(&buf).expect("InputBatch 6");
let mut s2_acks = s2.try_clone().expect("clone");
wait_for_ack(&mut s2_acks, 6);
buf.clear();
encode_rotate(6, &[0xEE; 32], &mut buf);
s2.write_all(&buf).expect("Rotate 2");
// No third connection: the receiver must give up and exit
// with an error naming the recurrence.
let result = replica.join().expect("replica thread panicked");
let err = result.expect_err("second divergence must exit hard");
assert!(
err.contains("divergence recurred"),
"error must name the recurrence: {err}"
);
}
// -------------------------------------------------------------
// Promotion teardown helper (`take_pipeline_for_promotion`) — the
// no-live-pipeline decision branches. With no pipeline to tear
// down it hands back the warm state held in the receiver's locals
// (a clean promotion) or errors when none is present. Colocated
// here for the `App` + `BufferedWriter` fixtures above; the
// Clean-pipeline branch needs a live pipeline (failover IT).
// -------------------------------------------------------------
type PromoteHandles =
crate::replication::ReplicaPipelineHandles<App, BufferedWriter<EvtAdd>>;
#[test]
fn promotion_hands_back_local_state_when_present() {
let dir = tempfile::tempdir().unwrap();
let mut pipeline: Option<PromoteHandles> = None;
let mut exchange = Some(App);
let mut journal_writer =
Some(BufferedWriter::<EvtAdd>::create(&dir.path().join("p.journal")).unwrap());
let result = crate::replication::take_pipeline_for_promotion(
&mut pipeline,
&mut exchange,
&mut journal_writer,
);
assert!(matches!(result, Ok(Some(_))), "warm state must be promoted");
assert!(
exchange.is_none() && journal_writer.is_none(),
"state must be moved into the result"
);
}
#[test]
fn promotion_errs_when_no_local_state() {
let mut pipeline: Option<PromoteHandles> = None;
let mut exchange: Option<App> = None;
let mut journal_writer: Option<BufferedWriter<EvtAdd>> = None;
let result = crate::replication::take_pipeline_for_promotion(
&mut pipeline,
&mut exchange,
&mut journal_writer,
);
// Not `expect_err` — the Ok payload (App) isn't `Debug`.
let err = match result {
Err(e) => e,
Ok(_) => panic!("a promote with nothing to promote must error"),
};
assert!(
err.to_string().contains("no local state available"),
"{err}"
);
}
#[test]
fn promotion_errs_on_partial_state() {
// Exchange present, writer missing — not a usable hand-off.
let mut pipeline: Option<PromoteHandles> = None;
let mut exchange = Some(App);
let mut journal_writer: Option<BufferedWriter<EvtAdd>> = None;
let result = crate::replication::take_pipeline_for_promotion(
&mut pipeline,
&mut exchange,
&mut journal_writer,
);
assert!(result.is_err(), "partial state is not a valid promotion");
}
}
// -----------------------------------------------------------------
// Shutdown during reconnect backoff — end to end against a scripted
// primary. Needs real persistence (the pipeline journals the one
// streamed event); no chain verdicts involved, so no hash-chain.
// -----------------------------------------------------------------
#[cfg(not(feature = "no-persist"))]
mod backoff_shutdown {
use super::super::super::auth::authenticate_replica;
use super::scripted::*;
use super::*;
use melin_journal::{BufferedWriter, JournalEvent, JournalWrite};
use melin_transport_core::replication::catchup::lineage_origin;
use melin_transport_core::replication::protocol::encode_stream_start;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
/// Names of every live thread in this process, via
/// `/proc/self/task` (Linux-only, like the runtime itself).
fn live_thread_names() -> Vec<String> {
std::fs::read_dir("/proc/self/task")
.expect("read /proc/self/task")
.filter_map(|entry| {
// A thread may exit between readdir and the comm
// read — skipping it is the correct outcome.
let entry = entry.ok()?;
let name = std::fs::read_to_string(entry.path().join("comm")).ok()?;
Some(name.trim().to_string())
})
.collect()
}
/// Shutdown while the receiver waits out a reconnect backoff must
/// tear the live pipeline down — join every stage thread — rather
/// than abandon it. Pins the fix for the connect-failure arm that
/// returned without teardown (stages left detached mid-run, the
/// journal writer never closed).
#[test]
fn shutdown_during_reconnect_backoff_joins_pipeline_threads() {
let dir = tempfile::tempdir().expect("tempdir");
// Minimal primary journal — only its lineage identity is
// needed for the StreamStart the fresh replica accepts.
let primary_journal = dir.path().join("primary.journal");
let mut w = BufferedWriter::<EvtAdd>::create(&primary_journal).expect("create");
w.append(&JournalEvent::App(EvtAdd(1))).expect("append");
drop(w);
let (lineage_start, lineage_anchor) =
lineage_origin(&primary_journal).expect("lineage");
let authorized_keys = replica_auth();
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
listener.set_nonblocking(true).expect("nonblocking");
let addr = listener.local_addr().expect("addr");
let shutdown = Arc::new(AtomicBool::new(false));
let control = crate::replication::ReplicaControlPlane::new();
let replica = {
let journal = dir.path().join("replica.journal");
let snapshot = dir.path().join("replica.snapshot");
let shutdown = Arc::clone(&shutdown);
let control = control.clone();
std::thread::spawn(move || -> Result<bool, String> {
run_receiver::<App>(
addr,
&journal,
&ed25519_dalek::SigningKey::from_bytes(&REPLICA_KEY),
&shutdown,
&control,
3_600_000,
snapshot,
crate::layout::PipelineCores::unpinned(),
melin_journal::StagingMode::ZeroFill,
Duration::ZERO,
64,
Arc::new(Factory),
Arc::new(melin_transport_core::fence::FenceState::new(0)),
)
// ReceiverResult's error is !Send — stringify for join().
.map(|state| state.is_none())
.map_err(|e| e.to_string())
})
};
// Session 1: bring the pipeline up for real — stream one
// event and wait for its ack (acked ⇒ journaled ⇒ the stage
// threads exist).
let mut s1 = accept_within(&listener, 30);
let mut s1r = s1.try_clone().expect("clone");
authenticate_replica(&mut s1r, &authorized_keys).expect("auth");
match read_replica_msg(&mut s1) {
ReplicaMessage::Handshake(h) => {
assert_eq!(h.last_sequence, 0, "fresh replica handshake")
}
other => panic!("expected Handshake, got {other:?}"),
}
let mut buf = Vec::new();
encode_stream_start(0, lineage_start, lineage_anchor, 0, 1, &mut buf);
s1.write_all(&buf).expect("StreamStart");
buf.clear();
melin_transport_core::replication_wire::encode_input_batch(
&[InputSlot::<EvtAdd> {
connection_id: 0,
key_hash: 0,
request_seq: 0,
sequence: 1,
timestamp_ns: 1,
event: JournalEvent::App(EvtAdd(1)),
publish_ts: Default::default(),
recv_ts: Default::default(),
}],
&mut buf,
);
s1.write_all(&buf).expect("InputBatch");
wait_for_ack(&mut s1, 1);
// Kill the primary completely — both socket halves and the
// listener — so every reconnect attempt is refused and the
// receiver settles into the connect-failure backoff.
drop(s1);
drop(s1r);
drop(listener);
// Past the 1s post-disconnect backoff, inside the 2s
// connect-failure backoff sleep. (Any other point in the
// reconnect loop must satisfy the assertions too — this
// timing just targets the arm that historically leaked.)
std::thread::sleep(Duration::from_millis(1500));
shutdown.store(true, Ordering::Relaxed);
let deadline = Instant::now() + Duration::from_secs(10);
while !replica.is_finished() {
assert!(
Instant::now() < deadline,
"receiver did not exit after shutdown"
);
std::thread::sleep(Duration::from_millis(20));
}
let result = replica.join().expect("replica thread panicked");
assert_eq!(result, Ok(true), "receiver must exit cleanly via shutdown");
// The stage threads are named at spawn, and a leaked stage
// spins forever — absence within the deadline proves the
// teardown joined them. Deadline-poll rather than one-shot:
// under plain `cargo test`, concurrent tests' stages may be
// momentarily alive, but those exit on their own.
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let names = live_thread_names();
if !names
.iter()
.any(|n| n == "journal-seq" || n == "matching" || n == "drain")
{
break;
}
assert!(
Instant::now() < deadline,
"pipeline threads still alive after shutdown: {names:?}"
);
std::thread::sleep(Duration::from_millis(50));
}
}
}
// -----------------------------------------------------------------
// Boundary adoption under both staging modes — end to end against a
// scripted primary. Needs hash-chain (the boundary announce carries
// a chain value the replica verifies before rotating) and real
// persistence (the rotation archives the on-disk segment).
// -----------------------------------------------------------------
#[cfg(all(feature = "hash-chain", not(feature = "no-persist")))]
mod rotation_adoption {
use super::super::super::auth::authenticate_replica;
use super::scripted::*;
use super::*;
use melin_journal::{BufferedWriter, JournalEvent, JournalWrite};
use melin_transport_core::replication::catchup::lineage_origin;
use melin_transport_core::replication::protocol::{encode_rotate, encode_stream_start};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
/// Payloads of every entry in the journal at `path`, in order.
fn payloads(path: &std::path::Path) -> Vec<u64> {
let mut reader = melin_journal::JournalReader::<EvtAdd>::open(path).expect("open");
let mut out = Vec::new();
while let Some(entry) = reader.next_entry().expect("read entry") {
if let JournalEvent::App(EvtAdd(v)) = entry.event {
out.push(v);
}
}
out
}
/// A scripted primary streams two events, announces the rotation
/// boundary with the *correct* tail hash, and streams two more.
/// The replica must verify the boundary, rotate — adopting the
/// segment its preparer staged in `mode` — and keep acking on
/// the new segment, leaving the sealed one archived.
///
/// Run under both modes: everything observable (archive layout,
/// entry placement across the boundary, acks, clean shutdown)
/// must be identical, or the staging mode is not a tuning knob
/// but a behaviour change.
fn boundary_adoption_rotates_and_streams_on(mode: melin_journal::StagingMode) {
// Shrink the prealloc chunk so the replica's preparer stages
// a few MiB (chunk + margin) instead of 256 MiB per test.
// The guard holds a process-wide lock, so the two mode
// variants serialise rather than race the global override.
let _prealloc_guard =
melin_journal::test_utils::PreallocOverrideGuard::new(1024 * 1024);
let dir = tempfile::tempdir().expect("tempdir");
// Scripted primary journal: entries 1..=2 carrying the same
// stamps as the InputSlots below (deterministic timestamps,
// zero key-hash/request-seq), so its chain value at the
// boundary equals the replica's — journals are byte-for-byte
// mirrors, and `append`'s wall-clock stamp would fork them.
let primary_journal = dir.path().join("primary.journal");
let mut w = BufferedWriter::<EvtAdd>::create(&primary_journal).expect("create");
for v in 1..=2u64 {
w.batch_append_with_ts(&JournalEvent::App(EvtAdd(v)), v, 0, 0)
.expect("append");
}
w.flush_batch_sync().expect("flush");
let chain_at_2 = w.chain_hash().expect("chain");
drop(w);
let (lineage_start, lineage_anchor) =
lineage_origin(&primary_journal).expect("lineage");
let authorized_keys = replica_auth();
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
listener.set_nonblocking(true).expect("nonblocking");
let addr = listener.local_addr().expect("addr");
let replica_journal = dir.path().join("replica.journal");
let shutdown = Arc::new(AtomicBool::new(false));
let control = crate::replication::ReplicaControlPlane::new();
let replica = {
let journal = replica_journal.clone();
let snapshot = dir.path().join("replica.snapshot");
let shutdown = Arc::clone(&shutdown);
let control = control.clone();
std::thread::spawn(move || -> Result<bool, String> {
run_receiver::<App>(
addr,
&journal,
&ed25519_dalek::SigningKey::from_bytes(&REPLICA_KEY),
&shutdown,
&control,
3_600_000,
snapshot,
crate::layout::PipelineCores::unpinned(),
mode,
Duration::ZERO,
64,
Arc::new(Factory),
Arc::new(melin_transport_core::fence::FenceState::new(0)),
)
// ReceiverResult's error is !Send — stringify for join().
.map(|state| state.is_none())
.map_err(|e| e.to_string())
})
};
let mut s1 = accept_within(&listener, 30);
let mut s1r = s1.try_clone().expect("clone");
authenticate_replica(&mut s1r, &authorized_keys).expect("auth");
match read_replica_msg(&mut s1) {
ReplicaMessage::Handshake(h) => {
assert_eq!(h.last_sequence, 0, "fresh replica handshake")
}
other => panic!("expected Handshake, got {other:?}"),
}
let mut buf = Vec::new();
encode_stream_start(0, lineage_start, lineage_anchor, 0, 1, &mut buf);
s1.write_all(&buf).expect("StreamStart");
let send_events = |s: &mut TcpStream, range: std::ops::RangeInclusive<u64>| {
let slots: Vec<InputSlot<EvtAdd>> = range
.map(|v| InputSlot {
connection_id: 0,
key_hash: 0,
request_seq: 0,
sequence: v,
timestamp_ns: v,
event: JournalEvent::App(EvtAdd(v)),
// `()` without latency-trace, a timestamp with it.
publish_ts: Default::default(),
recv_ts: Default::default(),
})
.collect();
let mut buf = Vec::new();
melin_transport_core::replication_wire::encode_input_batch(&slots, &mut buf);
s.write_all(&buf).expect("InputBatch");
};
send_events(&mut s1, 1..=2);
wait_for_ack(&mut s1, 2);
// Wait for the preparer's staged segment to reach full size
// (the overridden prealloc chunk + the 8 MiB margin) so the
// boundary below adopts it rather than racing staging into
// the synchronous fallback — adoption is the path under
// test. Both modes must produce it; a preparer that never
// does is itself a failure.
let staging = {
// `<live>.next-staging` — the preparer's sibling-file
// convention (crate-private, so spelled out here the way
// the `.divergent.<n>` archive name is above).
let mut s = replica_journal.clone().into_os_string();
s.push(".next-staging");
std::path::PathBuf::from(s)
};
let staged_len: u64 = (1 + 8) * 1024 * 1024;
let deadline = Instant::now() + Duration::from_secs(10);
loop {
if std::fs::metadata(&staging).is_ok_and(|m| m.len() == staged_len) {
break;
}
assert!(
Instant::now() < deadline,
"preparer produced no full-size staged segment in {mode:?} mode"
);
std::thread::sleep(Duration::from_millis(10));
}
// Length is the last thing staging changes before the final
// sync and the slot hand-off; give those a moment so the
// rotation's `take()` finds the segment parked. (Losing this
// race anyway is not a failure: the rotation falls back to
// the synchronous path and every assertion below still
// holds — the staged segment is then simply adopted at a
// later boundary.)
std::thread::sleep(Duration::from_millis(300));
// The boundary, with the correct tail hash — verified
// against the replica's own chain, then adopted.
buf.clear();
encode_rotate(2, &chain_at_2, &mut buf);
s1.write_all(&buf).expect("Rotate");
// Streaming continues on the new segment. The journal stage
// holds entries past a pending boundary until the rotation
// applies, so this ack proves the adoption completed.
send_events(&mut s1, 3..=4);
wait_for_ack(&mut s1, 4);
shutdown.store(true, Ordering::Relaxed);
let result = replica.join().expect("replica thread panicked");
assert_eq!(result, Ok(true), "receiver must exit cleanly via shutdown");
// The sealed segment was archived at the first archive slot
// holding exactly the pre-boundary entries; the live segment
// carries the stream from the boundary on.
let archived = dir.path().join("replica.journal.000001");
assert!(archived.exists(), "sealed segment must be archived");
assert_eq!(payloads(&archived), vec![1, 2]);
assert_eq!(payloads(&replica_journal), vec![3, 4]);
}
#[test]
fn boundary_adoption_zero_fill() {
boundary_adoption_rotates_and_streams_on(melin_journal::StagingMode::ZeroFill);
}
#[test]
fn boundary_adoption_allocate() {
boundary_adoption_rotates_and_streams_on(melin_journal::StagingMode::Allocate);
}
}
}