spate-core 0.3.0

Engine for the Spate framework: records, operator chains, source/sink abstractions, checkpointing, backpressure, config, metrics, and the pipeline runtime. Applications should depend on the `spate` facade crate instead.
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
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
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
//! Operator-chain tests: combinators, resume semantics, terminal handoff.

use super::*;
use crate::backpressure::InflightBudget;
use crate::checkpoint::{AckMsg, AckRef, AckStatus};
use crate::deser::{BytesPassthrough, Deserializer, EmitRecord, Owned, RecFamily};
use crate::error::{DeserError, ErrorPolicy, SinkError};
use crate::record::{PartitionId, RawPayload, Record};
use crate::sink::{
    EncodedChunk, KeyHashRouter, RecordRouter, RowEncoder, ShardQueues, ShardRouter, shard_queues,
};
use crate::source::PayloadBatch;
use bytes::BytesMut;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

// ---- fixtures --------------------------------------------------------------

/// Borrowed parse type: `key:seg|seg|...` payloads.
#[derive(Debug, PartialEq)]
struct LogEvent<'buf> {
    key: &'buf str,
    body: &'buf [u8],
}

struct LogF;
impl RecFamily for LogF {
    type Rec<'buf> = LogEvent<'buf>;
}

/// Borrowed fan-out type.
#[derive(Debug)]
struct SubEvent<'buf> {
    chunk: &'buf [u8],
}

struct SubF;
impl RecFamily for SubF {
    type Rec<'buf> = SubEvent<'buf>;
}

/// Deserializer for `key:body`; errors on payloads starting `ERR`;
/// emits nothing for payloads starting `SKIP`.
#[derive(Clone, Default)]
struct LogDeser;

impl Deserializer<LogF> for LogDeser {
    fn deserialize<'buf>(
        &mut self,
        raw: &RawPayload<'buf>,
        ack: &AckRef,
        out: &mut dyn EmitRecord<'buf, LogEvent<'buf>>,
    ) -> Result<(), DeserError> {
        if raw.bytes.starts_with(b"ERR") {
            return Err(DeserError::Malformed {
                reason: "poison".into(),
            });
        }
        if raw.bytes.starts_with(b"SKIP") {
            return Ok(());
        }
        let pos =
            raw.bytes
                .iter()
                .position(|&b| b == b':')
                .ok_or_else(|| DeserError::Malformed {
                    reason: "missing key separator".into(),
                })?;
        let key = std::str::from_utf8(&raw.bytes[..pos]).map_err(|_| DeserError::Malformed {
            reason: "non-utf8 key".into(),
        })?;
        let _ = out.emit(Record {
            payload: LogEvent {
                key,
                body: &raw.bytes[pos + 1..],
            },
            meta: raw.meta(),
            ack: ack.clone(),
        });
        Ok(())
    }
}

/// Emits each `|`-separated chunk of the payload as a [`SubEvent`], and fails
/// on reaching an `ERRTAIL` chunk, so one payload emits records and *then*
/// errors.
#[derive(Clone, Default)]
struct EmitThenFailDeser;

impl Deserializer<SubF> for EmitThenFailDeser {
    fn deserialize<'buf>(
        &mut self,
        raw: &RawPayload<'buf>,
        ack: &AckRef,
        out: &mut dyn EmitRecord<'buf, SubEvent<'buf>>,
    ) -> Result<(), DeserError> {
        for chunk in raw.bytes.split(|&b| b == b'|') {
            if chunk == b"ERRTAIL" {
                return Err(DeserError::Malformed {
                    reason: "poison".into(),
                });
            }
            let _ = out.emit(Record {
                payload: SubEvent { chunk },
                meta: raw.meta(),
                ack: ack.clone(),
            });
        }
        Ok(())
    }
}

/// Length-prefixed encoder for `SubEvent`; fails record-level on `BADROW`
/// chunks and fatally on `FATALROW` chunks.
#[derive(Clone, Default)]
struct SubEncoder;

impl RowEncoder<SubF> for SubEncoder {
    fn encode<'buf>(
        &mut self,
        rec: &Record<SubEvent<'buf>>,
        buf: &mut BytesMut,
    ) -> Result<(), SinkError> {
        // Write the prefix first so partial-write rollback is exercised.
        buf.extend_from_slice(&(u32::try_from(rec.payload.chunk.len()).unwrap()).to_le_bytes());
        if rec.payload.chunk == b"BADROW" {
            return Err(SinkError::Client {
                class: crate::error::ErrorClass::RecordLevel,
                reason: "unencodable row".into(),
            });
        }
        if rec.payload.chunk == b"FATALROW" {
            return Err(SinkError::Client {
                class: crate::error::ErrorClass::Fatal,
                reason: "encoder broken".into(),
            });
        }
        buf.extend_from_slice(rec.payload.chunk);
        Ok(())
    }
}

/// A second borrowed destination family for the split-terminal tests: stores
/// the event key. Distinct row type from [`SubEvent`], so the two branches of
/// a split are heterogeneous.
#[derive(Debug)]
struct KeyEvent<'buf> {
    key: &'buf [u8],
}

struct KeyF;
impl RecFamily for KeyF {
    type Rec<'buf> = KeyEvent<'buf>;
}

/// Length-prefixed encoder for [`KeyEvent`].
#[derive(Clone, Default)]
struct KeyEncoder;

impl RowEncoder<KeyF> for KeyEncoder {
    fn encode<'buf>(
        &mut self,
        rec: &Record<KeyEvent<'buf>>,
        buf: &mut BytesMut,
    ) -> Result<(), SinkError> {
        buf.extend_from_slice(&(u32::try_from(rec.payload.key.len()).unwrap()).to_le_bytes());
        buf.extend_from_slice(rec.payload.key);
        Ok(())
    }
}

/// Length-prefixed encoder for owned byte records.
#[derive(Clone, Default)]
struct VecEncoder;

impl RowEncoder<Owned<Vec<u8>>> for VecEncoder {
    fn encode<'buf>(&mut self, rec: &Record<Vec<u8>>, buf: &mut BytesMut) -> Result<(), SinkError> {
        buf.extend_from_slice(&(u32::try_from(rec.payload.len()).unwrap()).to_le_bytes());
        buf.extend_from_slice(&rec.payload);
        Ok(())
    }
}

/// [`VecEncoder`] with a fatal row: encodes owned bytes and fails with an
/// [`ErrorClass::Fatal`](crate::error::ErrorClass::Fatal) error on `FATALROW`.
#[derive(Clone, Default)]
struct FatalVecEncoder;

impl RowEncoder<Owned<Vec<u8>>> for FatalVecEncoder {
    fn encode<'buf>(&mut self, rec: &Record<Vec<u8>>, buf: &mut BytesMut) -> Result<(), SinkError> {
        if rec.payload == b"FATALROW" {
            return Err(SinkError::Client {
                class: crate::error::ErrorClass::Fatal,
                reason: "encoder broken".into(),
            });
        }
        buf.extend_from_slice(&(u32::try_from(rec.payload.len()).unwrap()).to_le_bytes());
        buf.extend_from_slice(&rec.payload);
        Ok(())
    }
}

/// A mock **columnar** encoder: buffers rows inside `self` during `encode`
/// (writing nothing to the per-chunk buffer), then emits one self-describing
/// block (`[u32 row_count]` followed by length-prefixed rows) in
/// `finish_chunk`. Stands in for the ClickHouse Native encoder to prove the
/// terminal stage drives the columnar contract: per-shard buffering, the
/// `buffered_bytes` seal threshold, and `finish_chunk` at every seal.
#[derive(Clone, Default)]
struct ColumnarEncoder {
    buffered: Vec<Vec<u8>>,
}

impl RowEncoder<Owned<Vec<u8>>> for ColumnarEncoder {
    fn encode<'buf>(&mut self, rec: &Record<Vec<u8>>, buf: &mut BytesMut) -> Result<(), SinkError> {
        // A columnar encoder writes NOTHING here; it transposes on finalize.
        assert!(
            buf.is_empty(),
            "columnar encode must not touch the chunk buffer"
        );
        self.buffered.push(rec.payload.clone());
        Ok(())
    }
    fn buffered_bytes(&self) -> usize {
        4 + self.buffered.iter().map(|r| 4 + r.len()).sum::<usize>()
    }
    fn finish_chunk(&mut self, buf: &mut BytesMut) -> Result<(), SinkError> {
        buf.extend_from_slice(&(u32::try_from(self.buffered.len()).unwrap()).to_le_bytes());
        for r in &self.buffered {
            buf.extend_from_slice(&(u32::try_from(r.len()).unwrap()).to_le_bytes());
            buf.extend_from_slice(r);
        }
        self.buffered.clear();
        Ok(())
    }
}

/// A columnar encoder that accepts every row and fails to finalize the block.
#[derive(Clone, Default)]
struct BrokenFinishEncoder;

impl RowEncoder<Owned<Vec<u8>>> for BrokenFinishEncoder {
    fn encode<'buf>(
        &mut self,
        _rec: &Record<Vec<u8>>,
        _buf: &mut BytesMut,
    ) -> Result<(), SinkError> {
        Ok(())
    }
    fn buffered_bytes(&self) -> usize {
        1
    }
    fn finish_chunk(&mut self, _buf: &mut BytesMut) -> Result<(), SinkError> {
        Err(SinkError::Client {
            class: crate::error::ErrorClass::Fatal,
            reason: "cannot finalize the block".into(),
        })
    }
}

/// Length-prefixed encoder whose `finish_chunk` fails after it has encoded a
/// row ending `FATALFINISH`. Each shard owns its own clone, so row content
/// picks the failing shard, and the reason names the row, so a reason
/// identifies which shard raised it.
#[derive(Clone, Default)]
struct SelectiveFinishEncoder {
    doomed: Option<String>,
}

impl RowEncoder<Owned<Vec<u8>>> for SelectiveFinishEncoder {
    fn encode<'buf>(&mut self, rec: &Record<Vec<u8>>, buf: &mut BytesMut) -> Result<(), SinkError> {
        if rec.payload.ends_with(b"FATALFINISH") {
            self.doomed
                .get_or_insert_with(|| String::from_utf8_lossy(&rec.payload).into_owned());
        }
        buf.extend_from_slice(&(u32::try_from(rec.payload.len()).unwrap()).to_le_bytes());
        buf.extend_from_slice(&rec.payload);
        Ok(())
    }
    fn finish_chunk(&mut self, _buf: &mut BytesMut) -> Result<(), SinkError> {
        if let Some(row) = &self.doomed {
            return Err(SinkError::Client {
                class: crate::error::ErrorClass::Fatal,
                reason: format!("cannot finalize the block after {row}"),
            });
        }
        Ok(())
    }
}

/// Appends each row in `encode`, then a trailer in `finish_chunk`: `PARTIAL`
/// with a fatal error the first time, `|END` and success after. The shape of
/// an encoder that writes into the chunk buffer before it fails to finalize
/// and recovers on the next call.
#[derive(Clone, Default)]
struct RecoveringFinishEncoder {
    failed_once: bool,
}

impl RowEncoder<Owned<Vec<u8>>> for RecoveringFinishEncoder {
    fn encode<'buf>(&mut self, rec: &Record<Vec<u8>>, buf: &mut BytesMut) -> Result<(), SinkError> {
        buf.extend_from_slice(&rec.payload);
        Ok(())
    }
    fn finish_chunk(&mut self, buf: &mut BytesMut) -> Result<(), SinkError> {
        if self.failed_once {
            buf.extend_from_slice(b"|END");
            return Ok(());
        }
        self.failed_once = true;
        buf.extend_from_slice(b"PARTIAL");
        Err(SinkError::Client {
            class: crate::error::ErrorClass::Fatal,
            reason: "cannot finalize the block".into(),
        })
    }
}

/// Decode a [`ColumnarEncoder`] block: leading `u32` row count, then rows.
fn decode_block(frame: &[u8]) -> Vec<Vec<u8>> {
    let count = u32::from_le_bytes(frame[0..4].try_into().unwrap()) as usize;
    let mut rows = Vec::with_capacity(count);
    let mut at = 4;
    for _ in 0..count {
        let len = u32::from_le_bytes(frame[at..at + 4].try_into().unwrap()) as usize;
        at += 4;
        rows.push(frame[at..at + len].to_vec());
        at += len;
    }
    rows
}

/// Cloneable owned passthrough for factory tests (the framework's
/// `BytesPassthrough` does not derive `Clone`).
#[derive(Clone, Default)]
struct OwnedPassthrough;

impl Deserializer<Owned<Vec<u8>>> for OwnedPassthrough {
    fn deserialize<'buf>(
        &mut self,
        raw: &RawPayload<'buf>,
        ack: &AckRef,
        out: &mut dyn EmitRecord<'buf, Vec<u8>>,
    ) -> Result<(), DeserError> {
        let _ = out.emit(Record {
            payload: raw.bytes.to_vec(),
            meta: raw.meta(),
            ack: ack.clone(),
        });
        Ok(())
    }
}

/// Route a row whose payload starts `s1:` to shard 1, every other row to
/// shard 0.
#[derive(Clone, Copy)]
struct ByPrefix;
impl RecordRouter<Owned<Vec<u8>>> for ByPrefix {
    fn route_record<'buf>(&self, rec: &Record<Vec<u8>>, n: usize) -> usize {
        usize::from(rec.payload.starts_with(b"s1:")) % n
    }
}

/// Route everything to shard 0 (single-shard tests).
#[derive(Clone, Copy)]
struct ToZero;
impl ShardRouter for ToZero {
    fn route(&self, _meta: &crate::record::RecordMeta, _n: usize) -> usize {
        0
    }
}

/// A test batch over pre-filled payload buffers.
struct TestBatch<'a> {
    payloads: &'a [Vec<u8>],
    idx: usize,
    ack: AckRef,
}

impl<'a> TestBatch<'a> {
    fn new(payloads: &'a [Vec<u8>]) -> (Self, crossbeam_channel::Receiver<AckMsg>) {
        let (ack, rx) = AckRef::test_pair();
        (
            TestBatch {
                payloads,
                idx: 0,
                ack,
            },
            rx,
        )
    }
}

impl<'a> PayloadBatch<'a> for TestBatch<'a> {
    fn next_payload(&mut self) -> Option<RawPayload<'a>> {
        let buf = self.payloads.get(self.idx)?;
        let offset = self.idx as i64;
        self.idx += 1;
        Some(RawPayload {
            bytes: buf,
            key: None,
            partition: PartitionId(0),
            offset,
            timestamp_ms: offset * 10,
        })
    }

    fn ack(&self) -> &AckRef {
        &self.ack
    }
}

fn payloads(specs: &[&str]) -> Vec<Vec<u8>> {
    specs.iter().map(|s| s.as_bytes().to_vec()).collect()
}

fn decode_rows(frame: &[u8]) -> Vec<Vec<u8>> {
    let mut rows = Vec::new();
    let mut at = 0;
    while at < frame.len() {
        let len = u32::from_le_bytes(frame[at..at + 4].try_into().unwrap()) as usize;
        at += 4;
        rows.push(frame[at..at + len].to_vec());
        at += len;
    }
    rows
}

fn drain_rows(rx: &mut tokio::sync::mpsc::Receiver<EncodedChunk>) -> Vec<Vec<u8>> {
    let mut rows = Vec::new();
    while let Ok(chunk) = rx.try_recv() {
        rows.extend(decode_rows(&chunk.frame));
        // These tests play the sink: consuming a chunk here stands in for
        // a durable write, so resolve its acknowledgments as delivered
        // (an AckSet fails them on plain drop, for teardown safety).
        chunk.acks.deliver();
    }
    rows
}

/// Split each body at `|` into sub-events. A fn item: naturally
/// higher-ranked, as the borrowed-family builder tier requires.
fn split_body<'buf>(e: LogEvent<'buf>, em: &mut Emitter<'_, SubF>) {
    for chunk in e.body.split(|&b| b == b'|') {
        em.emit(SubEvent { chunk });
    }
}

fn non_empty(e: &LogEvent<'_>) -> bool {
    !e.body.is_empty()
}

// ---- borrowed end-to-end ---------------------------------------------------

#[test]
fn borrowed_chain_end_to_end() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());
    let mut c = chain(LogDeser)
        .filter(non_empty)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            ToZero,
            ChunkConfig::default(),
            queues,
            Arc::clone(&budget),
        )
        .build();

    let bufs = payloads(&["a:one|two", "b:", "c:three"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Done));

    let rows = drain_rows(&mut rxs[0]);
    assert_eq!(
        rows,
        vec![b"one".to_vec(), b"two".to_vec(), b"three".to_vec()]
    );
    assert!(budget.usage() > 0, "sealed bytes are budgeted");

    drop(batch);
    let msg = ack_rx.try_recv().expect("batch resolved");
    assert_eq!(msg.status, AckStatus::Delivered);
}

#[test]
fn owned_chain_with_closures_end_to_end() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());
    let mut c = chain_owned(BytesPassthrough)
        .map(|mut b: Vec<u8>| {
            b.make_ascii_uppercase();
            b
        })
        .filter(|b: &Vec<u8>| b != b"DROPME")
        .try_map(
            |b: Vec<u8>| -> Result<Vec<u8>, std::string::FromUtf8Error> {
                String::from_utf8(b).map(String::into_bytes)
            },
            ErrorPolicy::Skip,
        )
        .sink(
            VecEncoder,
            KeyHashRouter,
            ChunkConfig::default(),
            queues,
            budget,
        )
        .build();

    let bufs = payloads(&["hello", "dropme", "world"]);
    let (mut batch, _ack_rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Done));
    assert_eq!(
        drain_rows(&mut rxs[0]),
        vec![b"HELLO".to_vec(), b"WORLD".to_vec()]
    );
}

// ---- error policies --------------------------------------------------------

#[test]
fn deser_skip_policy_drops_and_continues() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let mut c = chain(LogDeser)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            ToZero,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let bufs = payloads(&["a:x", "ERR:poison", "b:y"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    let _ = c.flush();
    assert_eq!(drain_rows(&mut rxs[0]), vec![b"x".to_vec(), b"y".to_vec()]);
    drop(batch);
    assert_eq!(
        ack_rx.try_recv().unwrap().status,
        AckStatus::Delivered,
        "skips count as handled"
    );
}

#[test]
fn deser_fail_policy_is_fatal_and_fails_the_batch() {
    let (queues, _rxs) = shard_queues(1, 64);
    let mut c = chain(LogDeser)
        .deser_error_policy(ErrorPolicy::Fail)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            ToZero,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let bufs = payloads(&["a:x", "ERR:poison", "b:y"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    let PushOutcome::Fatal(f) = c.push_batch(&mut batch, 0) else {
        panic!("expected fatal");
    };
    assert!(f.reason.contains("poison"));
    drop(batch);
    // Records buffered in the terminal stage hold ack clones; a failed
    // pipeline releases them when the chain is torn down.
    drop(c);
    assert_eq!(ack_rx.try_recv().unwrap().status, AckStatus::Failed);
}

#[test]
fn try_map_fail_policy_is_fatal() {
    let (queues, _rxs) = shard_queues(1, 64);
    let mut c = chain_owned(BytesPassthrough)
        .try_map(
            |b: Vec<u8>| -> Result<Vec<u8>, &'static str> {
                if b == b"boom" { Err("kaboom") } else { Ok(b) }
            },
            ErrorPolicy::Fail,
        )
        .sink(
            VecEncoder,
            KeyHashRouter,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let bufs = payloads(&["fine", "boom", "after"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    let PushOutcome::Fatal(f) = c.push_batch(&mut batch, 0) else {
        panic!("expected fatal");
    };
    assert!(f.reason.contains("kaboom"));
    assert!(f.component.starts_with("try_map"));
    drop(batch);
    drop(c);
    assert_eq!(ack_rx.try_recv().unwrap().status, AckStatus::Failed);
}

#[test]
fn encoder_skip_policy_rolls_back_partial_rows() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let mut c = chain(LogDeser)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            ToZero,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    // BADROW's length prefix is written before the encoder errors; the
    // rollback must leave the frame decodable.
    let bufs = payloads(&["a:ok|BADROW|also"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    let _ = c.flush();
    assert_eq!(
        drain_rows(&mut rxs[0]),
        vec![b"ok".to_vec(), b"also".to_vec()]
    );
}

#[test]
fn encoder_fail_policy_is_fatal() {
    let (queues, _rxs) = shard_queues(1, 64);
    let cfg = ChunkConfig {
        encode_policy: ErrorPolicy::Fail,
        ..ChunkConfig::default()
    };
    let mut c = chain(LogDeser)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            ToZero,
            cfg,
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let bufs = payloads(&["a:BADROW"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Fatal(_)));
    drop(batch);
    assert_eq!(ack_rx.try_recv().unwrap().status, AckStatus::Failed);
}

#[test]
fn fatal_class_encoder_errors_override_the_skip_policy() {
    // A Fatal-class error says the encoder itself is broken ("processing
    // must stop"); under the default Skip policy it must still stop the
    // pipeline instead of silently dropping every record.
    let (queues, _rxs) = shard_queues(1, 64);
    let mut c = chain(LogDeser)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            ToZero,
            ChunkConfig::default(), // encode_policy: Skip
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let bufs = payloads(&["a:FATALROW"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Fatal(_)));
    drop(batch);
    assert_eq!(ack_rx.try_recv().unwrap().status, AckStatus::Failed);

    // Record-level errors still skip under the same policy.
    let (queues, mut rxs) = shard_queues(1, 64);
    let mut c = chain(LogDeser)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            ToZero,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();
    let bufs = payloads(&["a:ok|BADROW"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    let _ = c.flush();
    assert_eq!(drain_rows(&mut rxs[0]), vec![b"ok".to_vec()]);
}

/// When two records of one payload both fail fatally, the sink handoff reports
/// the first, and the record between them never reaches a shard queue.
/// Reversing the order reverses the reason, so this pins push order rather than
/// a precedence between the two error classes.
#[test]
fn a_sink_handoff_reports_the_first_fatal_of_a_payload() {
    /// The reason one payload reports, and the rows that reached shard 0.
    fn run(payload: &str) -> (String, Vec<Vec<u8>>) {
        let (queues, mut rxs) = shard_queues(1, 64);
        // `Fail` is what lets a record-level `BADROW` error write the slot;
        // under `Skip` it is only counted. A `target_bytes` of 1 seals any
        // row that does encode, so a row pushed after the fatal shows up in
        // the returned rows.
        let cfg = ChunkConfig {
            target_bytes: 1,
            encode_policy: ErrorPolicy::Fail,
        };
        let mut c = chain(LogDeser)
            .flat_map::<SubF, _>(split_body)
            .sink(
                SubEncoder,
                ToZero,
                cfg,
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let bufs = payloads(&[payload]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        let PushOutcome::Fatal(f) = c.push_batch(&mut batch, 0) else {
            panic!("expected fatal");
        };
        (f.reason, drain_rows(&mut rxs[0]))
    }

    let (first, rows) = run("a:FATALROW|ok|BADROW");
    assert!(first.contains("encoder broken"), "{first}");
    assert!(
        rows.is_empty(),
        "a row after the fatal was sealed: {rows:?}"
    );

    let (reversed, rows) = run("a:BADROW|ok|FATALROW");
    assert!(reversed.contains("unencodable row"), "{reversed}");
    assert!(
        rows.is_empty(),
        "a row after the fatal was sealed: {rows:?}"
    );
}

/// When two records of one payload both fail a `try_map` under `Fail`, the
/// stage reports the first, and the record between them never reaches the
/// sink. Reversing the order reverses the reason.
#[test]
fn a_try_map_reports_the_first_fatal_of_a_payload() {
    /// The reason one payload reports, and the rows that reached shard 0.
    fn run(payload: &str) -> (String, Vec<Vec<u8>>) {
        let (queues, mut rxs) = shard_queues(1, 64);
        let mut c = chain(LogDeser)
            .flat_map::<Owned<Vec<u8>>, _>(split_body_owned)
            .try_map(
                |b: Vec<u8>| -> Result<Vec<u8>, &'static str> {
                    match b.as_slice() {
                        b"boom1" => Err("kaboom one"),
                        b"boom2" => Err("kaboom two"),
                        _ => Ok(b),
                    }
                },
                ErrorPolicy::Fail,
            )
            .sink(
                VecEncoder,
                KeyHashRouter,
                // A `target_bytes` of 1 seals any row that gets past the
                // `try_map`, so a record pushed after the fatal shows up in
                // the returned rows.
                ChunkConfig {
                    target_bytes: 1,
                    ..ChunkConfig::default()
                },
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let bufs = payloads(&[payload]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        let PushOutcome::Fatal(f) = c.push_batch(&mut batch, 0) else {
            panic!("expected fatal");
        };
        (f.reason, drain_rows(&mut rxs[0]))
    }

    let (first, rows) = run("a:boom1|ok|boom2");
    assert!(first.contains("kaboom one"), "{first}");
    assert!(
        rows.is_empty(),
        "a row after the fatal was sealed: {rows:?}"
    );

    let (reversed, rows) = run("a:boom2|ok|boom1");
    assert!(reversed.contains("kaboom two"), "{reversed}");
    assert!(
        rows.is_empty(),
        "a row after the fatal was sealed: {rows:?}"
    );
}

/// Split each body at `|` into owned rows, which puts the chain on the owned
/// builder tier where `try_map` takes a plain closure.
fn split_body_owned(e: LogEvent<'_>, em: &mut Emitter<'_, Owned<Vec<u8>>>) {
    for chunk in e.body.split(|&b| b == b'|') {
        em.emit(chunk.to_vec());
    }
}

/// A chain whose `try_map` and sink can each latch within one payload: the
/// `try_map` fails `boom` under `Fail`, the encoder fails `FATALROW` fatally,
/// and a `target_bytes` of 1 seals any row that reaches the shard buffer.
fn try_map_and_sink_chain(queues: ShardQueues) -> Box<dyn RunnableChain> {
    chain(LogDeser)
        .flat_map::<Owned<Vec<u8>>, _>(split_body_owned)
        .try_map(
            |b: Vec<u8>| -> Result<Vec<u8>, &'static str> {
                if b == b"boom" {
                    Err("the try_map latched")
                } else {
                    Ok(b)
                }
            },
            ErrorPolicy::Fail,
        )
        .sink(
            FatalVecEncoder,
            KeyHashRouter,
            ChunkConfig {
                target_bytes: 1,
                encode_policy: ErrorPolicy::Fail,
            },
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build()
}

/// When a `try_map` and the sink each latch within one payload, the chain
/// reports the one recorded first, whichever stage is nearer the source.
/// Regression for #364.
#[test]
fn a_chain_reports_the_fatal_its_stages_recorded_first() {
    /// The reason one payload reports, and the rows that reached shard 0.
    fn run(payload: &str) -> (String, Vec<Vec<u8>>) {
        let (queues, mut rxs) = shard_queues(1, 64);
        let mut c = try_map_and_sink_chain(queues);
        let bufs = payloads(&[payload]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        let PushOutcome::Fatal(f) = c.push_batch(&mut batch, 0) else {
            panic!("expected fatal");
        };
        (f.reason, drain_rows(&mut rxs[0]))
    }

    // The sink latches on row 1 and the `try_map` on row 2, so the reason has
    // to name the sink even though the `try_map` sits upstream of it.
    let (sink_first, rows) = run("a:FATALROW|boom");
    assert!(sink_first.contains("encoder broken"), "{sink_first}");
    assert!(
        rows.is_empty(),
        "a row after the fatal was sealed: {rows:?}"
    );

    // Reversed, the `try_map` latches first and swallows the `FATALROW` that
    // follows, so the sink never latches at all.
    let (try_map_first, rows) = run("a:boom|FATALROW");
    assert!(
        try_map_first.contains("the try_map latched"),
        "{try_map_first}"
    );
    assert!(
        rows.is_empty(),
        "a row after the fatal was sealed: {rows:?}"
    );
}

/// Reporting a fatal drains every stage's slot, so a stage that latched and was
/// passed over does not swallow a later batch's records.
/// Regression for #364.
#[test]
fn reporting_a_fatal_drains_every_stage_that_latched() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let mut c = try_map_and_sink_chain(queues);

    // Latches the sink on row 1 and the `try_map` on row 2.
    let bufs = payloads(&["a:FATALROW|boom"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Fatal(_)));
    drop(batch);
    assert!(drain_rows(&mut rxs[0]).is_empty());

    // A stage still holding its reason swallows these instead.
    let clean = payloads(&["b:one|two"]);
    let (mut batch, _rx) = TestBatch::new(&clean);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert_eq!(
        drain_rows(&mut rxs[0]),
        vec![b"one".to_vec(), b"two".to_vec()]
    );
}

/// A split over two branches whose encoders each fail to finalize once a row of
/// theirs ends `FATALFINISH`. A row prefixed `one` routes to the second branch,
/// and the default target holds every row until the flush, so both branches
/// seal in the same `flush_terminal` pass. The sink names are what the reported
/// `component` distinguishes them by.
fn finish_failing_split(zero_q: ShardQueues, one_q: ShardQueues) -> Box<dyn RunnableChain> {
    let budget = Arc::new(InflightBudget::new());
    let mut split = chain(LogDeser)
        .flat_map::<Owned<Vec<u8>>, _>(split_body_owned)
        .split(ErrorPolicy::Fail);
    let zero = split.add::<Owned<Vec<u8>>, _, _>(
        SelectiveFinishEncoder::default(),
        ToZero,
        SinkCtx::new("zero".into(), zero_q, Arc::clone(&budget)),
    );
    let one = split.add::<Owned<Vec<u8>>, _, _>(
        SelectiveFinishEncoder::default(),
        ToZero,
        SinkCtx::new("one".into(), one_q, budget),
    );
    split
        .route(move |b: Vec<u8>, out| {
            if b.starts_with(b"one") {
                out.emit(one, b);
            } else {
                out.emit(zero, b);
            }
        })
        .build()
}

/// When two split branches each fail to finalize in one flush, the reported
/// reason names the branch the seal loop reached first. A branch that finalizes
/// cleanly after another has failed still ships its chunk.
#[test]
fn a_flush_reports_the_first_branch_that_failed_to_finalize() {
    /// The component and reason one flush reports, and the rows that reached
    /// branch `zero`.
    fn run(rows: &str) -> (String, String, Vec<Vec<u8>>) {
        let (zero_q, mut zero_rx) = shard_queues(1, 64);
        let (one_q, _one_rx) = shard_queues(1, 64);
        let mut c = finish_failing_split(zero_q, one_q);

        let bufs = payloads(&[rows]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
        let PushOutcome::Fatal(f) = c.flush() else {
            panic!("expected fatal");
        };
        (f.component, f.reason, drain_rows(&mut zero_rx[0]))
    }

    // Both branches doomed: the seal loop reaches `zero` first whichever row
    // arrived first, so the row order cannot change the answer.
    let (component, reason, _) = run("a:zeroFATALFINISH|oneFATALFINISH");
    assert_eq!(component, "sink.zero");
    assert!(reason.contains("zeroFATALFINISH"), "{reason}");

    let (component, reason, _) = run("a:oneFATALFINISH|zeroFATALFINISH");
    assert_eq!(component, "sink.zero");
    assert!(reason.contains("zeroFATALFINISH"), "{reason}");

    // Only `one` doomed: it is the branch named, and `zero`'s chunk still ships.
    let (component, reason, shipped) = run("a:zeroOK|oneFATALFINISH");
    assert_eq!(component, "sink.one");
    assert!(reason.contains("oneFATALFINISH"), "{reason}");
    assert_eq!(
        shipped,
        vec![b"zeroOK".to_vec()],
        "a branch that finalized cleanly must still ship its chunk"
    );
}

/// Reporting a flush fatal drains every branch that latched, so a branch that
/// was passed over does not fail a later batch on its reason.
#[test]
fn reporting_a_flush_fatal_drains_every_branch_that_latched() {
    let (zero_q, _zero_rx) = shard_queues(1, 64);
    let (one_q, _one_rx) = shard_queues(1, 64);
    let mut c = finish_failing_split(zero_q, one_q);

    let bufs = payloads(&["a:zeroFATALFINISH|oneFATALFINISH"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Fatal(_)));
    drop(batch);

    // `one` reported nothing, so a slot it still held would surface here.
    let clean = payloads(&["b:oneok"]);
    let (mut batch, _rx) = TestBatch::new(&clean);
    let outcome = c.push_batch(&mut batch, 0);
    assert!(
        matches!(outcome, PushOutcome::Done),
        "a branch passed over by the flush kept its reason: {outcome:?}"
    );
}

/// A record that reaches the split after one branch has latched a fatal reaches
/// no branch, whether it is a later record of the payload or a later emit of
/// the same record. The batch after it is taken normally.
/// Regression for #365.
#[test]
fn a_branch_fatal_stops_the_other_branches() {
    /// The outcome of one payload, the rows that reached the `key` branch, and
    /// the rows a clean batch after it reached. With `fan`, the route closure
    /// emits the `FATALROW` to `key` as well, so the second emit of one record
    /// follows the first emit's latch.
    fn run(payload: &str, fan: bool) -> (PushOutcome, Vec<Vec<u8>>, Vec<Vec<u8>>) {
        let (sub_q, _sub_rx) = shard_queues(1, 64);
        let (key_q, mut key_rx) = shard_queues(1, 64);
        let budget = Arc::new(InflightBudget::new());

        let mut split = chain(LogDeser)
            .flat_map::<SubF, _>(split_body)
            .split(ErrorPolicy::Fail);
        let sub = split.add::<SubF, _, _>(
            SubEncoder,
            ToZero,
            SinkCtx::new("sub".into(), sub_q, Arc::clone(&budget)),
        );
        let key = split.add::<KeyF, _, _>(
            KeyEncoder,
            ToZero,
            SinkCtx::new("key".into(), key_q, budget),
        );
        let mut c = split
            .route(move |e: SubEvent<'_>, out| {
                if e.chunk == b"FATALROW" {
                    out.emit(sub, SubEvent { chunk: e.chunk });
                    if fan {
                        out.emit(key, KeyEvent { key: e.chunk });
                    }
                } else {
                    out.emit(key, KeyEvent { key: e.chunk });
                }
            })
            .build();

        let bufs = payloads(&[payload]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        let outcome = c.push_batch(&mut batch, 0);
        // The branches hold their rows until a flush seals them, so a row that
        // did reach `key` shows up here.
        let _ = c.flush();
        let reached = drain_rows(&mut key_rx[0]);
        drop(batch);

        // A split still holding the latch would swallow this batch instead.
        let clean = payloads(&["b:kafter"]);
        let (mut batch, _rx) = TestBatch::new(&clean);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
        assert!(matches!(c.flush(), PushOutcome::Done));
        (outcome, reached, drain_rows(&mut key_rx[0]))
    }

    /// The reason and rows one arm asserts on.
    fn check(outcome: PushOutcome, rows: &[Vec<u8>], recovered: &[Vec<u8>], what: &str) {
        let PushOutcome::Fatal(f) = outcome else {
            panic!("expected the fatal, got {outcome:?}");
        };
        assert_eq!(f.component, "sink.sub");
        assert!(rows.is_empty(), "{what} reached another branch: {rows:?}");
        assert_eq!(
            recovered,
            [b"kafter".to_vec()],
            "the batch after the fatal was swallowed"
        );
    }

    let (outcome, rows, recovered) = run("a:FATALROW|after", false);
    check(outcome, &rows, &recovered, "a record after the fatal");

    let (outcome, rows, recovered) = run("a:FATALROW", true);
    check(
        outcome,
        &rows,
        &recovered,
        "a second emit of the latching record",
    );
}

/// A deserializer that emits a record and then fails reports the fatal the
/// emitted record latched, not its own error.
/// Regression for #364.
#[test]
fn a_deserializer_failure_does_not_outrank_a_stage_that_latched() {
    let (queues, _rxs) = shard_queues(1, 64);
    let mut c = chain(EmitThenFailDeser)
        .deser_error_policy(ErrorPolicy::Fail)
        .sink(
            SubEncoder,
            ToZero,
            ChunkConfig {
                target_bytes: 1,
                encode_policy: ErrorPolicy::Fail,
            },
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let bufs = payloads(&["FATALROW|ERRTAIL"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    let PushOutcome::Fatal(f) = c.push_batch(&mut batch, 0) else {
        panic!("expected fatal");
    };
    assert!(f.reason.contains("encoder broken"), "{}", f.reason);
}

/// When two shards fail to finalize in one flush, the reported reason names the
/// shard the seal loop reached first, whichever shard's row arrived first. A
/// shard that finalizes cleanly after another has latched still ships its chunk.
/// Regression for #361.
#[test]
fn a_flush_reports_the_first_shard_that_failed_to_finalize() {
    /// The reason one flush reports, and the rows that reached shard 1.
    fn run(rows: &[&str]) -> (String, Vec<Vec<u8>>) {
        // The default 64KiB target holds every row until the flush, so both
        // shards seal in the same `flush_terminal` pass.
        let (queues, mut rxs) = shard_queues(2, 64);
        let mut c = chain_owned(BytesPassthrough)
            .sink(
                SelectiveFinishEncoder::default(),
                ByPrefix,
                ChunkConfig::default(),
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let bufs = payloads(rows);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
        let PushOutcome::Fatal(f) = c.flush() else {
            panic!("expected fatal");
        };
        (f.reason, drain_rows(&mut rxs[1]))
    }

    let (first, _) = run(&["s0:FATALFINISH", "s1:FATALFINISH"]);
    assert!(first.contains("s0:"), "{first}");

    let (reversed, _) = run(&["s1:FATALFINISH", "s0:FATALFINISH"]);
    assert!(reversed.contains("s0:"), "{reversed}");

    let (mixed, shipped) = run(&["s0:FATALFINISH", "s1:ok"]);
    assert!(mixed.contains("s0:"), "{mixed}");
    assert_eq!(
        shipped,
        vec![b"s1:ok".to_vec()],
        "a shard that finalized cleanly must still ship its chunk"
    );
}

/// A finalize that fails after writing into the chunk buffer leaves the rows
/// already encoded there and nothing else, so the frame a later finalize seals
/// holds one complete block. That later chunk also carries the row the chain
/// accepted after the flush drained the fatal.
/// Regression for #366.
#[test]
fn a_failed_finalize_leaves_only_the_encoded_rows_in_the_buffer() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let mut c = chain_owned(BytesPassthrough)
        .sink(
            RecoveringFinishEncoder::default(),
            KeyHashRouter,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let first = payloads(&["one"]);
    let (mut batch, _rx) = TestBatch::new(&first);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Fatal(_)));

    // The driver's flush paths keep the chain alive, so the shard takes another
    // row and seals again before the pipeline stops.
    let second = payloads(&["two"]);
    let (mut batch, _rx2) = TestBatch::new(&second);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Done));

    let chunk = rxs[0].try_recv().expect("the second flush ships a chunk");
    assert_eq!(&chunk.frame[..], b"onetwo|END");
    assert_eq!(chunk.rows, 2);
    chunk.acks.deliver();
}

// ---- backpressure / resume semantics ----------------------------------------

#[test]
fn blocked_resumes_without_rerunning_operators() {
    // Capacity 1 chunk, 1-byte target: every record seals a chunk, so the
    // second in-flight chunk parks and the chain reports Blocked between
    // payloads.
    let (queues, mut rxs) = shard_queues(1, 1);
    let cfg = ChunkConfig {
        target_bytes: 1,
        ..ChunkConfig::default()
    };
    let seen = Arc::new(AtomicUsize::new(0));
    let seen2 = Arc::clone(&seen);
    let mut c = chain_owned(BytesPassthrough)
        .map(move |b: Vec<u8>| {
            seen2.fetch_add(1, Ordering::Relaxed);
            b
        })
        .sink(
            VecEncoder,
            KeyHashRouter,
            cfg,
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let bufs = payloads(&["r0", "r1", "r2", "r3"]);
    let (mut batch, _ack) = TestBatch::new(&bufs);

    let mut rows = Vec::new();
    let mut from = 0;
    let mut pushes = 0;
    loop {
        pushes += 1;
        assert!(pushes < 32, "must converge");
        match c.push_batch(&mut batch, from) {
            PushOutcome::Done => break,
            PushOutcome::Blocked { resume_at, reason } => {
                assert_eq!(reason, BlockReason::Capacity, "full queues are capacity");
                assert!(resume_at >= from);
                from = resume_at;
                rows.extend(drain_rows(&mut rxs[0]));
            }
            PushOutcome::Fatal(f) => panic!("unexpected fatal: {f}"),
        }
    }
    while !matches!(c.flush(), PushOutcome::Done) {
        rows.extend(drain_rows(&mut rxs[0]));
    }
    rows.extend(drain_rows(&mut rxs[0]));

    assert_eq!(
        rows,
        vec![
            b"r0".to_vec(),
            b"r1".to_vec(),
            b"r2".to_vec(),
            b"r3".to_vec()
        ],
        "all rows delivered exactly once, in order"
    );
    assert_eq!(
        seen.load(Ordering::Relaxed),
        4,
        "operators ran exactly once per record"
    );
    assert!(pushes > 1, "the scenario must actually exercise Blocked");
}

#[test]
fn flush_blocked_then_done_after_draining() {
    let (queues, mut rxs) = shard_queues(1, 1);
    let mut c = chain_owned(BytesPassthrough)
        .sink(
            VecEncoder,
            KeyHashRouter,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    // Two payloads accumulate (64KiB target, never sealed inline)...
    let bufs = payloads(&["a", "b"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    // ...then flush seals one chunk into the size-1 queue: Done. Push more
    // and flush again: the queue is full, so the chunk parks → Blocked.
    assert!(matches!(c.flush(), PushOutcome::Done));
    let bufs2 = payloads(&["c"]);
    let (mut batch2, _rx2) = TestBatch::new(&bufs2);
    assert!(matches!(c.push_batch(&mut batch2, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Blocked { .. }));
    let first = drain_rows(&mut rxs[0]);
    assert_eq!(first, vec![b"a".to_vec(), b"b".to_vec()]);
    assert!(matches!(c.flush(), PushOutcome::Done));
    assert_eq!(drain_rows(&mut rxs[0]), vec![b"c".to_vec()]);
}

/// A payload that parks a chunk and latches an encoder fatal in the same pass
/// reports the fatal.
#[test]
fn push_reports_a_fatal_latched_while_the_terminal_is_blocked() {
    /// The outcome of one payload, and the rows that reached the shard queue.
    fn run(third_row: &str) -> (PushOutcome, Vec<Vec<u8>>) {
        // One shard at queue capacity 1 and a `target_bytes` of 1 seal a chunk
        // per row, so the first row's chunk fills the queue and the second
        // parks. Two rows are not enough, since a fatal row seals nothing and
        // leaves the terminal unblocked.
        let (queues, mut rxs) = shard_queues(1, 1);
        let cfg = ChunkConfig {
            target_bytes: 1,
            ..ChunkConfig::default()
        };
        let mut c = chain(LogDeser)
            .flat_map::<SubF, _>(split_body)
            .sink(
                SubEncoder,
                ToZero,
                cfg,
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let spec = format!("a:ok|ok|{third_row}");
        let bufs = payloads(&[&spec]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        let outcome = c.push_batch(&mut batch, 0);
        (outcome, drain_rows(&mut rxs[0]))
    }

    let (outcome, rows) = run("ok");
    let PushOutcome::Blocked { resume_at, reason } = outcome else {
        panic!("with no fatal the same payload reports backpressure, got {outcome:?}");
    };
    assert_eq!(resume_at, 1);
    assert_eq!(reason, BlockReason::Capacity);
    assert_eq!(
        rows,
        vec![b"ok".to_vec()],
        "the queue took one chunk and the rest parked"
    );

    let (outcome, rows) = run("FATALROW");
    let PushOutcome::Fatal(f) = outcome else {
        panic!("expected the fatal, got {outcome:?}");
    };
    assert!(f.reason.contains("encoder broken"), "{}", f.reason);
    assert_eq!(
        rows,
        vec![b"ok".to_vec()],
        "the queue took one chunk and the rest parked"
    );
}

/// A flush that parks a chunk and latches a `finish_chunk` fatal in the same
/// pass returns the fatal.
#[test]
fn flush_reports_a_fatal_latched_while_the_terminal_is_blocked() {
    // Two shards, queue capacity 1, the default 64KiB target so nothing seals
    // inline. The second flush seals shard 0 into a full queue, which parks
    // the chunk, and then fails to finalize shard 1.
    fn run(second_row: &str) -> PushOutcome {
        let (queues, _rxs) = shard_queues(2, 1);
        let mut c = chain_owned(BytesPassthrough)
            .sink(
                SelectiveFinishEncoder::default(),
                ByPrefix,
                ChunkConfig::default(),
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let bufs = payloads(&["s0:a"]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
        // Fills shard 0's queue. Asserted rather than discarded, so that
        // dropping `_rxs` fails here instead of parking this chunk and
        // blocking the second flush for a different reason.
        assert!(matches!(c.flush(), PushOutcome::Done));

        let bufs2 = payloads(&["s0:b", second_row]);
        let (mut batch2, _rx2) = TestBatch::new(&bufs2);
        assert!(matches!(c.push_batch(&mut batch2, 0), PushOutcome::Done));
        c.flush()
    }

    assert!(
        matches!(
            run("s1:ok"),
            PushOutcome::Blocked {
                reason: BlockReason::Capacity,
                ..
            }
        ),
        "with shard 1 finalizing cleanly the same flush reports backpressure"
    );
    assert!(matches!(run("s1:FATALFINISH"), PushOutcome::Fatal(_)));
}

// ---- handoff details ---------------------------------------------------------

#[test]
fn chunk_acks_are_deduped_per_source_batch() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let mut c = chain(LogDeser)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            ToZero,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let bufs = payloads(&["a:1|2|3|4|5"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    let _ = c.flush();
    let chunk = rxs[0].try_recv().unwrap();
    assert_eq!(chunk.rows, 5);
    assert_eq!(
        chunk.acks.len(),
        1,
        "five records of one source batch share one ack handle"
    );
}

#[test]
fn budget_grows_by_sealed_frame_bytes() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());
    let mut c = chain_owned(BytesPassthrough)
        .sink(
            VecEncoder,
            KeyHashRouter,
            ChunkConfig::default(),
            queues,
            Arc::clone(&budget),
        )
        .build();

    let bufs = payloads(&["0123456789"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    let _ = c.push_batch(&mut batch, 0);
    let _ = c.flush();
    let chunk = rxs[0].try_recv().unwrap();
    assert_eq!(budget.usage(), chunk.frame.len());
}

#[test]
fn multi_shard_routing_by_key_hash() {
    #[derive(Clone, Copy)]
    struct ByLen;
    impl ShardRouter for ByLen {
        fn route(&self, meta: &crate::record::RecordMeta, n: usize) -> usize {
            usize::try_from(meta.offset).unwrap() % n
        }
    }
    let (queues, mut rxs) = shard_queues(2, 64);
    let mut c = chain_owned(BytesPassthrough)
        .sink(
            VecEncoder,
            ByLen,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();
    let bufs = payloads(&["even", "odd", "even2", "odd2"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    let _ = c.push_batch(&mut batch, 0);
    let _ = c.flush();
    assert_eq!(
        drain_rows(&mut rxs[0]),
        vec![b"even".to_vec(), b"even2".to_vec()]
    );
    assert_eq!(
        drain_rows(&mut rxs[1]),
        vec![b"odd".to_vec(), b"odd2".to_vec()]
    );
}

#[test]
fn record_router_routes_flat_map_children_independently_by_payload() {
    /// Record-aware: routes on the child's own payload, which no meta-only
    /// router can see (flat_map children share the parent's meta).
    #[derive(Clone, Copy)]
    struct ByChunkLen;
    impl RecordRouter<SubF> for ByChunkLen {
        fn route_record<'buf>(&self, rec: &Record<SubEvent<'buf>>, n: usize) -> usize {
            rec.payload.chunk.len() % n
        }
    }
    let (queues, mut rxs) = shard_queues(2, 64);
    let mut c = chain(LogDeser)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            ByChunkLen,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    // ONE parent record: all four children carry identical RecordMeta, yet
    // route by their own chunk length, with even to shard 0 and odd to
    // shard 1.
    let bufs = payloads(&["k:aa|b|cc|d"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Done));

    assert_eq!(
        drain_rows(&mut rxs[0]),
        vec![b"aa".to_vec(), b"cc".to_vec()],
        "even-length children route to shard 0 by payload"
    );
    assert_eq!(
        drain_rows(&mut rxs[1]),
        vec![b"b".to_vec(), b"d".to_vec()],
        "odd-length children of the SAME parent route to shard 1"
    );
}

#[test]
fn meta_only_router_colocates_flat_map_children() {
    // The tier boundary, and the bridge exercised through the full terminal
    // stage: children inherit the parent's meta, so a meta-only router
    // (keyless here → stable partition hash) sends every child to one shard.
    let (queues, mut rxs) = shard_queues(2, 64);
    let mut c = chain(LogDeser)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            KeyHashRouter,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let bufs = payloads(&["k:aa|b|cc|d"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Done));

    let (zero, one) = (drain_rows(&mut rxs[0]), drain_rows(&mut rxs[1]));
    assert_eq!(
        zero.len() + one.len(),
        4,
        "every child reaches exactly one shard"
    );
    assert!(
        zero.is_empty() || one.is_empty(),
        "a meta-only router colocates all children of one parent"
    );
}

// ---- columnar (block-format) handoff -----------------------------------------

#[test]
fn columnar_encoder_seals_one_block_per_chunk_at_flush() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());
    let mut c = chain_owned(BytesPassthrough)
        .sink(
            ColumnarEncoder::default(),
            ToZero,
            ChunkConfig::default(),
            queues,
            Arc::clone(&budget),
        )
        .build();

    let bufs = payloads(&["aa", "bbb", "c"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    // Nothing sealed yet: a columnar encoder buffers until the block closes.
    assert!(rxs[0].try_recv().is_err(), "no block before flush");
    assert!(matches!(c.flush(), PushOutcome::Done));

    let chunk = rxs[0].try_recv().expect("one columnar block at flush");
    assert_eq!(chunk.rows, 3, "block carries every buffered row");
    assert_eq!(
        decode_block(&chunk.frame),
        vec![b"aa".to_vec(), b"bbb".to_vec(), b"c".to_vec()]
    );
    assert!(rxs[0].try_recv().is_err(), "exactly one block");

    // Delivering the block resolves the buffered rows' acks, never before.
    chunk.acks.deliver();
    drop(batch);
    assert_eq!(ack_rx.try_recv().unwrap().status, AckStatus::Delivered);
}

#[test]
fn columnar_buffered_bytes_seals_before_flush() {
    // A small target: the encoder's `buffered_bytes` crosses it mid-batch and
    // seals a block without waiting for flush (proves the threshold reads the
    // columnar encoder's internal size, not the empty chunk buffer).
    let cfg = ChunkConfig {
        target_bytes: 16,
        ..ChunkConfig::default()
    };
    let (queues, mut rxs) = shard_queues(1, 64);
    let mut c = chain_owned(BytesPassthrough)
        .sink(
            ColumnarEncoder::default(),
            ToZero,
            cfg,
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    // buffered_bytes = 4 header + per row (4 len + 4 bytes). After 2 rows =
    // 4 + 8 + 8 = 20 >= 16 -> seal; the 3rd row seals at flush.
    let bufs = payloads(&["aaaa", "bbbb", "cccc"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    let _ = c.push_batch(&mut batch, 0);
    let _ = c.flush();

    let b1 = rxs[0].try_recv().expect("mid-batch block");
    let b2 = rxs[0].try_recv().expect("flush block");
    assert_eq!(b1.rows, 2, "sealed once the target was reached");
    assert_eq!(b2.rows, 1, "remainder sealed at flush");
    let all: Vec<_> = decode_block(&b1.frame)
        .into_iter()
        .chain(decode_block(&b2.frame))
        .collect();
    assert_eq!(
        all,
        vec![b"aaaa".to_vec(), b"bbbb".to_vec(), b"cccc".to_vec()]
    );
}

#[test]
fn columnar_blocks_are_per_shard_pure_under_interleaving() {
    #[derive(Clone, Copy)]
    struct ByOffset;
    impl ShardRouter for ByOffset {
        fn route(&self, meta: &crate::record::RecordMeta, n: usize) -> usize {
            usize::try_from(meta.offset).unwrap() % n
        }
    }
    let (queues, mut rxs) = shard_queues(2, 64);
    let mut c = chain_owned(BytesPassthrough)
        .sink(
            ColumnarEncoder::default(),
            ByOffset,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    // Offsets 0..6 route 0,1,0,1,0,1, interleaved across two per-shard
    // encoders. A single shared encoder would mix these into one block.
    let bufs = payloads(&["s0a", "s1a", "s0b", "s1b", "s0c", "s1c"]);
    let (mut batch, _rx) = TestBatch::new(&bufs);
    let _ = c.push_batch(&mut batch, 0);
    let _ = c.flush();

    let block0 = rxs[0].try_recv().expect("shard 0 block");
    let block1 = rxs[1].try_recv().expect("shard 1 block");
    assert_eq!(
        decode_block(&block0.frame),
        vec![b"s0a".to_vec(), b"s0b".to_vec(), b"s0c".to_vec()],
        "shard 0's block holds only shard 0's rows, in order"
    );
    assert_eq!(
        decode_block(&block1.frame),
        vec![b"s1a".to_vec(), b"s1b".to_vec(), b"s1c".to_vec()],
    );
    assert_eq!((block0.rows, block1.rows), (3, 3));
}

#[test]
fn columnar_buffered_rows_at_teardown_fail_for_replay() {
    let (queues, _rxs) = shard_queues(1, 64);
    let mut c = chain_owned(BytesPassthrough)
        .sink(
            ColumnarEncoder::default(),
            ToZero,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build();

    let bufs = payloads(&["buffered-but-never-sealed"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    let _ = c.push_batch(&mut batch, 0);
    // No flush: the row is buffered in the encoder and never becomes a block.
    drop(c); // teardown drops the shard (encoder + its captured acks)
    drop(batch);
    assert_eq!(
        ack_rx.try_recv().unwrap().status,
        AckStatus::Failed,
        "buffered-but-unwritten rows must fail so they replay after restart"
    );
}

// ---- factory ----------------------------------------------------------------

#[test]
fn factory_stamps_independent_chains() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let factory = chain_owned(OwnedPassthrough)
        .map(|b: Vec<u8>| b)
        .sink(
            VecEncoder,
            KeyHashRouter,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        )
        .build_factory();

    let mut c1 = factory.make();
    let mut c2 = factory.make();

    let b1 = payloads(&["one"]);
    let b2 = payloads(&["two"]);
    let (mut batch1, _r1) = TestBatch::new(&b1);
    let (mut batch2, _r2) = TestBatch::new(&b2);
    assert!(matches!(c1.push_batch(&mut batch1, 0), PushOutcome::Done));
    assert!(matches!(c2.push_batch(&mut batch2, 0), PushOutcome::Done));
    let _ = c1.flush();
    let _ = c2.flush();
    let rows = drain_rows(&mut rxs[0]);
    assert_eq!(rows.len(), 2);
    assert!(rows.contains(&b"one".to_vec()));
    assert!(rows.contains(&b"two".to_vec()));
}

// ---- split terminal ----------------------------------------------------------

#[test]
fn split_routes_records_to_their_typed_branch() {
    // One borrowed source stream fans into two heterogeneously-typed branches:
    // `a*` keys route their body to the SubEvent branch, `k*` keys route their
    // key to the KeyEvent branch. `z*` matches neither (unmatched Skip).
    let (sub_q, mut sub_rx) = shard_queues(1, 64);
    let (key_q, mut key_rx) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());

    let mut split = chain(LogDeser).split(ErrorPolicy::Skip);
    let sub = split.add::<SubF, _, _>(
        SubEncoder,
        ToZero,
        SinkCtx::new("sub".into(), sub_q, Arc::clone(&budget)),
    );
    let key = split.add::<KeyF, _, _>(
        KeyEncoder,
        ToZero,
        SinkCtx::new("key".into(), key_q, Arc::clone(&budget)),
    );
    let mut c = split
        .route(move |e: LogEvent<'_>, out| {
            if e.key.starts_with('a') {
                out.emit(sub, SubEvent { chunk: e.body });
            } else if e.key.starts_with('k') {
                out.emit(
                    key,
                    KeyEvent {
                        key: e.key.as_bytes(),
                    },
                );
            }
            // else: matches no branch -> `unmatched` (Skip here)
        })
        .build();

    let bufs = payloads(&["a1:body-a", "k1:body-k", "z9:dropme"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Done));

    assert_eq!(
        drain_rows(&mut sub_rx[0]),
        vec![b"body-a".to_vec()],
        "the a-keyed record's body reached the SubEvent branch"
    );
    assert_eq!(
        drain_rows(&mut key_rx[0]),
        vec![b"k1".to_vec()],
        "the k-keyed record's key reached the KeyEvent branch"
    );

    // The unmatched `z9` record was dropped by the Skip policy; its ack share
    // releases as success, so the batch resolves Delivered.
    drop(batch);
    assert_eq!(ack_rx.try_recv().unwrap().status, AckStatus::Delivered);
}

#[test]
fn split_unmatched_fail_stops_the_pipeline() {
    let (sub_q, _rx) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());

    let mut split = chain(LogDeser).split(ErrorPolicy::Fail);
    let sub = split.add::<SubF, _, _>(
        SubEncoder,
        ToZero,
        SinkCtx::new("sub".into(), sub_q, budget),
    );
    let mut c = split
        .route(move |e: LogEvent<'_>, out| {
            if e.key.starts_with('a') {
                out.emit(sub, SubEvent { chunk: e.body });
            }
        })
        .build();

    let bufs = payloads(&["z9:nomatch"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    let PushOutcome::Fatal(f) = c.push_batch(&mut batch, 0) else {
        panic!("unmatched record under Fail policy must stop the pipeline");
    };
    assert!(f.reason.contains("no split branch"));
    drop(batch);
    drop(c);
    assert_eq!(ack_rx.try_recv().unwrap().status, AckStatus::Failed);
}

#[test]
fn split_holds_watermark_until_every_branch_is_written() {
    // A single source batch fans across two branches; the batch resolves
    // Delivered only once BOTH branches' chunks are durably written, the
    // multi-sink at-least-once contract, straight out of the shared AckRef.
    let (sub_q, mut sub_rx) = shard_queues(1, 64);
    let (key_q, mut key_rx) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());

    let mut split = chain(LogDeser).split(ErrorPolicy::Fail);
    let sub = split.add::<SubF, _, _>(
        SubEncoder,
        ToZero,
        SinkCtx::new("sub".into(), sub_q, Arc::clone(&budget)),
    );
    let key = split.add::<KeyF, _, _>(
        KeyEncoder,
        ToZero,
        SinkCtx::new("key".into(), key_q, Arc::clone(&budget)),
    );
    let mut c = split
        .route(move |e: LogEvent<'_>, out| {
            if e.key.starts_with('a') {
                out.emit(sub, SubEvent { chunk: e.body });
            } else {
                out.emit(
                    key,
                    KeyEvent {
                        key: e.key.as_bytes(),
                    },
                );
            }
        })
        .build();

    let bufs = payloads(&["a:xa", "k:xk"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Done));
    drop(batch);

    // Deliver only the SubEvent branch: the KeyEvent branch still holds an ack
    // clone of the same source batch, so the watermark must NOT advance.
    while let Ok(chunk) = sub_rx[0].try_recv() {
        chunk.acks.deliver();
    }
    assert!(
        ack_rx.try_recv().is_err(),
        "batch stays unresolved while a branch has not written"
    );

    // Deliver the KeyEvent branch too: the last clone drops and it resolves.
    while let Ok(chunk) = key_rx[0].try_recv() {
        chunk.acks.deliver();
    }
    assert_eq!(
        ack_rx
            .try_recv()
            .expect("batch resolves once all branches wrote")
            .status,
        AckStatus::Delivered
    );
}

#[test]
fn split_one_branch_failure_fails_the_whole_batch() {
    // Worst-status merge: if any branch's write is abandoned (its chunk's
    // AckSet drops undelivered), the source batch resolves Failed so its
    // offsets never commit, even though the other branch wrote successfully.
    let (sub_q, mut sub_rx) = shard_queues(1, 64);
    let (key_q, mut key_rx) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());

    let mut split = chain(LogDeser).split(ErrorPolicy::Fail);
    let sub = split.add::<SubF, _, _>(
        SubEncoder,
        ToZero,
        SinkCtx::new("sub".into(), sub_q, Arc::clone(&budget)),
    );
    let key = split.add::<KeyF, _, _>(
        KeyEncoder,
        ToZero,
        SinkCtx::new("key".into(), key_q, Arc::clone(&budget)),
    );
    let mut c = split
        .route(move |e: LogEvent<'_>, out| {
            if e.key.starts_with('a') {
                out.emit(sub, SubEvent { chunk: e.body });
            } else {
                out.emit(
                    key,
                    KeyEvent {
                        key: e.key.as_bytes(),
                    },
                );
            }
        })
        .build();

    let bufs = payloads(&["a:xa", "k:xk"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Done));
    drop(batch);

    // The SubEvent branch writes durably...
    while let Ok(chunk) = sub_rx[0].try_recv() {
        chunk.acks.deliver();
    }
    // ...but the KeyEvent branch's write is abandoned (chunk dropped undelivered).
    while let Ok(chunk) = key_rx[0].try_recv() {
        drop(chunk);
    }
    assert_eq!(
        ack_rx.try_recv().expect("batch resolves").status,
        AckStatus::Failed,
        "a single branch's abandoned write must fail the whole batch"
    );
}

// ---- metrics ------------------------------------------------------------------

#[test]
fn stages_flush_batch_metrics() {
    let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder();
    let handle = recorder.handle();
    metrics::with_local_recorder(&recorder, || {
        let (queues, _rxs) = shard_queues(1, 64);
        let mut c = chain(LogDeser)
            .with_metrics("testpipe", "main")
            .filter(non_empty)
            .flat_map::<SubF, _>(split_body)
            .sink(
                SubEncoder,
                ToZero,
                ChunkConfig::default(),
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let bufs = payloads(&["a:1|2", "b:", "ERR:x"]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    });
    let rendered = handle.render();
    assert!(
        rendered.contains("spate_operator_records_in_total"),
        "operator counters exported: {rendered}"
    );
    assert!(
        rendered.contains(r#"component="main.0_filter""#),
        "filter stage labeled: {rendered}"
    );
    assert!(
        rendered.contains(r#"reason="filtered""#),
        "filtered drop counted: {rendered}"
    );
    assert!(
        rendered.contains(r#"component="main.deserializer""#),
        "deser metrics present: {rendered}"
    );
    assert!(
        rendered.contains(r#"component="main.1_flat_map""#),
        "flat_map stage present: {rendered}"
    );
}

/// Every `spate_operator_errors_total` series in `rendered`, sorted.
fn error_series(rendered: &str) -> Vec<String> {
    let mut out: Vec<String> = rendered
        .lines()
        .filter(|l| {
            l.starts_with(&format!(
                "{}{{",
                crate::metrics::names::OPERATOR_ERRORS_TOTAL
            ))
        })
        .map(str::to_owned)
        .collect();
    out.sort();
    out
}

/// The labels a stage of this index and kind publishes under.
fn stage_labels(idx: usize, kind: &str) -> String {
    format!(r#"pipeline="errtest",component="main.{idx}_{kind}",component_type="{kind}""#)
}

/// The labels a split branch's terminal publishes under.
fn branch_labels(sink: &str) -> String {
    format!(r#"pipeline="errtest",component="main.sink.{sink}",component_type="sink_handoff""#)
}

/// The `spate_operator_errors_total` series one stage publishes, in
/// [`error_series`] order. Handles register eagerly, so a stage that has not
/// erred still renders both values at `0`.
fn stage_errors(labels: &str, record_level: u64, fatal: u64) -> Vec<String> {
    let name = crate::metrics::names::OPERATOR_ERRORS_TOTAL;
    vec![
        format!(r#"{name}{{{labels},error_type="fatal"}} {fatal}"#),
        format!(r#"{name}{{{labels},error_type="record_level"}} {record_level}"#),
    ]
}

fn sorted(mut v: Vec<String>) -> Vec<String> {
    v.sort();
    v
}

/// A `try_map` stopping the pipeline is counted on the stage that stopped it,
/// and no stage carries a `retryable` series. Regression for #335.
#[test]
fn a_try_map_fail_trip_counts_a_fatal_on_its_own_stage() {
    let rendered = crate::metrics::render_local(|| {
        let (queues, _rxs) = shard_queues(1, 64);
        let mut c = chain_owned(OwnedPassthrough)
            .with_metrics("errtest", "main")
            .try_map(
                |b: Vec<u8>| -> Result<Vec<u8>, &'static str> {
                    if b == b"boom" { Err("kaboom") } else { Ok(b) }
                },
                ErrorPolicy::Fail,
            )
            .sink(
                VecEncoder,
                KeyHashRouter,
                ChunkConfig::default(),
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let bufs = payloads(&["fine", "boom", "after"]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Fatal(_)));
    });

    let mut expected = stage_errors(&stage_labels(0, "try_map"), 0, 1);
    expected.extend(stage_errors(&stage_labels(1, "sink_handoff"), 0, 0));
    assert_eq!(
        error_series(&rendered),
        sorted(expected),
        "the try_map stage is the only one that erred, and no stage carries a \
         retryable series:\n{rendered}"
    );
}

/// An encoder error counts under the `error_type` naming its disposition. A
/// `Fatal` class overrides the Skip policy and counts as fatal.
#[test]
fn encoder_error_classes_land_on_their_own_error_type() {
    let record_level = crate::metrics::render_local(|| {
        let (queues, mut rxs) = shard_queues(1, 64);
        let mut c = chain(LogDeser)
            .with_metrics("errtest", "main")
            .flat_map::<SubF, _>(split_body)
            .sink(
                SubEncoder,
                ToZero,
                ChunkConfig::default(),
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();
        let bufs = payloads(&["a:ok|BADROW"]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
        let _ = c.flush();
        drain_rows(&mut rxs[0]);
    });
    let mut expected = stage_errors(&stage_labels(0, "flat_map"), 0, 0);
    expected.extend(stage_errors(&stage_labels(1, "sink_handoff"), 1, 0));
    assert_eq!(
        error_series(&record_level),
        sorted(expected),
        "a skipped row is record-level:\n{record_level}"
    );

    let fatal = crate::metrics::render_local(|| {
        let (queues, _rxs) = shard_queues(1, 64);
        let mut c = chain(LogDeser)
            .with_metrics("errtest", "main")
            .flat_map::<SubF, _>(split_body)
            .sink(
                SubEncoder,
                ToZero,
                ChunkConfig::default(), // encode_policy: Skip, which Fatal overrides
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();
        let bufs = payloads(&["a:FATALROW|FATALROW|ok"]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Fatal(_)));
    });
    let mut expected = stage_errors(&stage_labels(0, "flat_map"), 0, 0);
    expected.extend(stage_errors(&stage_labels(1, "sink_handoff"), 0, 1));
    assert_eq!(
        error_series(&fatal),
        sorted(expected),
        "a Fatal-class encoder error overrides Skip and counts a fatal:\n{fatal}"
    );
}

/// A record matching no split branch counts a fatal under `Fail`, and under
/// `Skip` counts a drop and no error.
#[test]
fn split_unmatched_counts_a_fatal_only_under_the_fail_policy() {
    let fail = crate::metrics::render_local(|| {
        let (sub_q, _rx) = shard_queues(1, 64);
        let mut split = chain(LogDeser)
            .with_metrics("errtest", "main")
            .split(ErrorPolicy::Fail);
        let sub = split.add::<SubF, _, _>(
            SubEncoder,
            ToZero,
            SinkCtx::new("sub".into(), sub_q, Arc::new(InflightBudget::new())),
        );
        let mut c = split
            .route(move |e: LogEvent<'_>, out| {
                if e.key.starts_with('a') {
                    out.emit(sub, SubEvent { chunk: e.body });
                }
            })
            .build();
        let bufs = payloads(&["z9:nomatch"]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Fatal(_)));
    });
    let mut expected = stage_errors(&stage_labels(0, "split"), 0, 1);
    expected.extend(stage_errors(&branch_labels("sub"), 0, 0));
    assert_eq!(
        error_series(&fail),
        sorted(expected),
        "the split stage stopped the pipeline:\n{fail}"
    );

    let skip = crate::metrics::render_local(|| {
        let (sub_q, _rx) = shard_queues(1, 64);
        let mut split = chain(LogDeser)
            .with_metrics("errtest", "main")
            .split(ErrorPolicy::Skip);
        let sub = split.add::<SubF, _, _>(
            SubEncoder,
            ToZero,
            SinkCtx::new("sub".into(), sub_q, Arc::new(InflightBudget::new())),
        );
        let mut c = split
            .route(move |e: LogEvent<'_>, out| {
                if e.key.starts_with('a') {
                    out.emit(sub, SubEvent { chunk: e.body });
                }
            })
            .build();
        let bufs = payloads(&["z9:nomatch"]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    });
    let mut expected = stage_errors(&stage_labels(0, "split"), 0, 0);
    expected.extend(stage_errors(&branch_labels("sub"), 0, 0));
    assert_eq!(
        error_series(&skip),
        sorted(expected),
        "an unrouted record under Skip is a drop, not an error:\n{skip}"
    );
    assert!(
        skip.contains(r#"reason="unrouted""#),
        "it is counted as a drop:\n{skip}"
    );
}

/// A `finish_chunk` failure is returned by the `flush` that latched it and
/// counts one fatal, however many times the stage is flushed afterwards.
/// Regression for #351.
#[test]
fn a_finish_chunk_failure_counts_a_fatal_on_the_stage_that_raised_it() {
    let rendered = crate::metrics::render_local(|| {
        let (queues, mut rxs) = shard_queues(1, 64);
        let mut c = chain_owned(OwnedPassthrough)
            .with_metrics("errtest", "main")
            .sink(
                BrokenFinishEncoder,
                KeyHashRouter,
                ChunkConfig::default(),
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let bufs = payloads(&["row"]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
        assert!(matches!(c.flush(), PushOutcome::Fatal(_)));
        // The drain flushes again over the same rows.
        let _ = c.flush();
        let _ = c.flush();
        assert!(
            rxs[0].try_recv().is_err(),
            "a chunk whose finalize failed must not be shipped"
        );
    });

    assert_eq!(
        error_series(&rendered),
        stage_errors(&stage_labels(0, "sink_handoff"), 0, 1),
        "a broken finalize is one fatal for the stage that raised it:\n{rendered}"
    );
}

/// A record the Skip policy drops counts a record-level error and no fatal.
#[test]
fn a_skipped_record_counts_no_fatal() {
    let rendered = crate::metrics::render_local(|| {
        let (queues, _rxs) = shard_queues(1, 64);
        let mut c = chain_owned(OwnedPassthrough)
            .with_metrics("errtest", "main")
            .try_map(
                |b: Vec<u8>| -> Result<Vec<u8>, &'static str> {
                    if b == b"boom" { Err("kaboom") } else { Ok(b) }
                },
                ErrorPolicy::Skip,
            )
            .sink(
                VecEncoder,
                KeyHashRouter,
                ChunkConfig::default(),
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let bufs = payloads(&["fine", "boom"]);
        let (mut batch, _rx) = TestBatch::new(&bufs);
        assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    });

    let mut expected = stage_errors(&stage_labels(0, "try_map"), 1, 0);
    expected.extend(stage_errors(&stage_labels(1, "sink_handoff"), 0, 0));
    assert_eq!(
        error_series(&rendered),
        sorted(expected),
        "a Skip trip is record-level and stops nothing:\n{rendered}"
    );
}

/// `ChainFactory` promises `Send + Sync` when its parts are, so no stage may
/// hold a non-`Sync` field.
#[test]
fn a_chain_factory_of_sync_parts_is_sync() {
    fn assert_send_sync<T: Send + Sync>(_: &T) {}
    let (queues, _rxs) = shard_queues(1, 64);
    let factory = chain_owned(OwnedPassthrough)
        .try_map(
            |b: Vec<u8>| -> Result<Vec<u8>, &'static str> { Ok(b) },
            ErrorPolicy::Fail,
        )
        .sink(
            VecEncoder,
            KeyHashRouter,
            ChunkConfig::default(),
            queues,
            Arc::new(InflightBudget::new()),
        );
    assert_send_sync(&factory);
}

// ---- teardown safety --------------------------------------------------------

#[test]
fn dropping_a_blocked_chain_fails_unsent_acks() {
    // Queue capacity 1 and per-row chunk sealing: the first chunk fills the
    // queue, the second parks. Tearing the chain down without draining must
    // resolve the batch Failed, never Delivered, or offsets would commit
    // for rows that no sink ever wrote.
    let (queues, rxs) = shard_queues(1, 1);
    let budget = Arc::new(InflightBudget::new());
    let cfg = ChunkConfig {
        target_bytes: 1,
        ..ChunkConfig::default()
    };
    let c = chain(LogDeser)
        .filter(non_empty)
        .flat_map::<SubF, _>(split_body)
        .sink(SubEncoder, ToZero, cfg, queues, Arc::clone(&budget));
    let mut c = c.build();

    let bufs = payloads(&["a:one", "b:two"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    let _ = c.push_batch(&mut batch, 0);
    let _ = c.flush();
    drop(batch);
    drop(c);
    // The successfully-queued first chunk still holds an ack clone; the
    // batch resolves once the sink side lets go of it too.
    drop(rxs);
    let msg = ack_rx.try_recv().expect("batch resolves at teardown");
    assert_eq!(
        msg.status,
        AckStatus::Failed,
        "unsent output must fail the batch so its offsets never commit"
    );
}

#[test]
fn dropping_a_chain_with_partial_buffers_fails_their_acks() {
    // Default chunk config: rows accumulate in the shard buffer and are
    // never sealed. Dropping the chain without flush() must fail the batch.
    let (queues, _rxs) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());
    let mut c = chain(LogDeser)
        .filter(non_empty)
        .flat_map::<SubF, _>(split_body)
        .sink(
            SubEncoder,
            ToZero,
            ChunkConfig::default(),
            queues,
            Arc::clone(&budget),
        )
        .build();

    let bufs = payloads(&["a:one|two"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);
    assert!(matches!(c.push_batch(&mut batch, 0), PushOutcome::Done));
    drop(batch);
    drop(c); // no flush: rows still buffered
    let msg = ack_rx.try_recv().expect("batch resolves at teardown");
    assert_eq!(msg.status, AckStatus::Failed);
}

// ---- not-ready replay -------------------------------------------------------

/// Wraps LogDeser; payloads whose body starts with `wait:` return NotReady
/// a fixed number of times before decoding normally.
struct FlakyDeser {
    inner: LogDeser,
    not_ready_remaining: u32,
    attempts_on_flaky: u32,
}

impl Deserializer<LogF> for FlakyDeser {
    fn deserialize<'buf>(
        &mut self,
        raw: &RawPayload<'buf>,
        ack: &AckRef,
        out: &mut dyn EmitRecord<'buf, LogEvent<'buf>>,
    ) -> Result<(), DeserError> {
        if raw.bytes.ends_with(b"|wait") {
            self.attempts_on_flaky += 1;
            if self.not_ready_remaining > 0 {
                self.not_ready_remaining -= 1;
                return Err(DeserError::NotReady {
                    reason: "schema fetch in flight".into(),
                });
            }
        }
        self.inner.deserialize(raw, ack, out)
    }
}

#[test]
fn not_ready_blocks_then_replays_without_loss_or_duplication() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());
    let mut c = chain(FlakyDeser {
        inner: LogDeser,
        not_ready_remaining: 2,
        attempts_on_flaky: 0,
    })
    .filter(non_empty)
    .flat_map::<SubF, _>(split_body)
    .sink(
        SubEncoder,
        ToZero,
        ChunkConfig::default(),
        queues,
        Arc::clone(&budget),
    )
    .build();

    // Payload 1 is the flaky one; payloads 0 and 2 decode immediately.
    let bufs = payloads(&["a:one", "b:two|wait", "c:three"]);
    let (mut batch, ack_rx) = TestBatch::new(&bufs);

    // First push: payload 0 flows, payload 1 reports NotReady → Blocked at
    // index 1, and the payload is stashed for replay.
    let PushOutcome::Blocked { resume_at, reason } = c.push_batch(&mut batch, 0) else {
        panic!("expected Blocked while the schema is not ready");
    };
    assert_eq!(resume_at, 1);
    assert_eq!(
        reason,
        BlockReason::NotReady,
        "a dependency wait must not read as sink backpressure"
    );

    // Still not ready: Blocked again at the same index.
    let PushOutcome::Blocked { resume_at, .. } = c.push_batch(&mut batch, 1) else {
        panic!("expected Blocked on second attempt");
    };
    assert_eq!(resume_at, 1);

    // Ready now: the replayed payload decodes and the rest of the batch
    // completes.
    assert!(matches!(c.push_batch(&mut batch, 1), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Done));

    let rows = drain_rows(&mut rxs[0]);
    assert_eq!(
        rows,
        vec![
            b"one".to_vec(),
            b"two".to_vec(),
            b"wait".to_vec(),
            b"three".to_vec()
        ],
        "every record exactly once, in order"
    );

    // NotReady is not an error: the batch resolves Delivered.
    drop(batch);
    drop(c);
    let msg = ack_rx.try_recv().expect("batch resolved");
    assert_eq!(msg.status, AckStatus::Delivered);
}

/// After the driver abandons a batch blocked mid-push at shutdown,
/// `abandon_batch` must clear the chain's mid-batch cursor and not-ready
/// stash so a fresh batch pushed from index 0 neither trips the resume
/// asserts (debug) nor replays the stale payload under the new ack
/// (release). Terminal chunks already parked from the abandoned batch keep
/// their own (now failed) acks.
#[test]
fn abandon_batch_resets_mid_batch_state_for_the_next_batch() {
    let (queues, mut rxs) = shard_queues(1, 64);
    let budget = Arc::new(InflightBudget::new());
    let mut c = chain(FlakyDeser {
        inner: LogDeser,
        // Never becomes ready during this test: the flaky payload always
        // reports NotReady and stays stashed until we abandon it.
        not_ready_remaining: 9,
        attempts_on_flaky: 0,
    })
    .flat_map::<SubF, _>(split_body)
    .sink(
        SubEncoder,
        ToZero,
        ChunkConfig::default(),
        queues,
        Arc::clone(&budget),
    )
    .build();

    // Batch 1: payload 0 ("a:one") flows into the terminal, payload 1
    // ("b:two|wait") reports NotReady → blocked mid-batch at cursor 1 with
    // the payload stashed.
    let b1 = payloads(&["a:one", "b:two|wait"]);
    let (mut batch1, _ack1_rx) = TestBatch::new(&b1);
    let PushOutcome::Blocked { resume_at, reason } = c.push_batch(&mut batch1, 0) else {
        panic!("expected Blocked NotReady");
    };
    assert_eq!(resume_at, 1);
    assert_eq!(reason, BlockReason::NotReady);

    // The driver's shutdown-abandon path: fail the ack, then discard the
    // chain's per-batch state.
    batch1.ack().fail();
    c.abandon_batch();
    drop(batch1);

    // A fresh batch from index 0. Without abandon_batch this would panic on
    // `debug_assert_eq!(from, self.cursor)` (0 != 1) or replay "b:two|wait".
    let b2 = payloads(&["c:three", "d:four"]);
    let (mut batch2, ack2_rx) = TestBatch::new(&b2);
    assert!(matches!(c.push_batch(&mut batch2, 0), PushOutcome::Done));
    assert!(matches!(c.flush(), PushOutcome::Done));

    let rows = drain_rows(&mut rxs[0]);
    // "one" is batch 1's already-parked terminal row (kept, with its failed
    // ack); the stashed "two"/"wait" is gone; batch 2's rows follow. No
    // duplication, no misattributed replay.
    assert_eq!(
        rows,
        vec![b"one".to_vec(), b"three".to_vec(), b"four".to_vec()]
    );
    drop(batch2);
    assert_eq!(ack2_rx.try_recv().unwrap().status, AckStatus::Delivered);
}

// ---- fatal deserializer -----------------------------------------------------

/// Wraps LogDeser; payloads ending in `|fatal` report NotReady
/// `not_ready_first` times, then `DeserError::Fatal`.
struct FatalDeser {
    not_ready_first: u32,
}

impl Deserializer<LogF> for FatalDeser {
    fn deserialize<'buf>(
        &mut self,
        raw: &RawPayload<'buf>,
        ack: &AckRef,
        out: &mut dyn EmitRecord<'buf, LogEvent<'buf>>,
    ) -> Result<(), DeserError> {
        if raw.bytes.ends_with(b"|fatal") {
            if self.not_ready_first > 0 {
                self.not_ready_first -= 1;
                return Err(DeserError::NotReady {
                    reason: "schema fetch in flight".into(),
                });
            }
            return Err(DeserError::Fatal {
                reason: "registry rejected the credentials".into(),
            });
        }
        LogDeser.deserialize(raw, ack, out)
    }
}

/// The value of the one series in `rendered` named `name` whose labels
/// contain `label`, or 0 when none renders.
fn series_value(rendered: &str, name: &str, label: &str) -> u64 {
    rendered
        .lines()
        .find(|l| l.starts_with(&format!("{name}{{")) && l.contains(label))
        .and_then(|l| l.rsplit(' ').next())
        .map_or(0, |v| v.parse().unwrap())
}

/// A fatal deserializer error stops the chain under the Skip policy, fails
/// the batch, and counts the payload as an error but not as a skip drop.
#[test]
fn a_fatal_deser_error_stops_the_chain_under_skip() {
    let mut ack_status = None;
    let rendered = crate::metrics::render_local(|| {
        let (queues, _rxs) = shard_queues(1, 64);
        let mut c = chain(FatalDeser { not_ready_first: 0 })
            .with_metrics("fataltest", "main")
            .flat_map::<SubF, _>(split_body)
            .sink(
                SubEncoder,
                ToZero,
                ChunkConfig::default(),
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let bufs = payloads(&["a:one", "b:two|fatal", "c:three"]);
        let (mut batch, ack_rx) = TestBatch::new(&bufs);
        let PushOutcome::Fatal(f) = c.push_batch(&mut batch, 0) else {
            panic!("expected Fatal whatever the Skip policy");
        };
        assert_eq!(f.component, "deserializer");
        assert!(f.reason.contains("rejected the credentials"), "{f}");
        drop(batch);
        drop(c);
        ack_status = Some(ack_rx.try_recv().expect("batch resolved").status);
    });
    assert_eq!(ack_status, Some(AckStatus::Failed));
    let name = crate::metrics::names::DESER_RECORDS_TOTAL;
    assert_eq!(
        series_value(&rendered, name, r#"outcome="error""#),
        1,
        "{rendered}"
    );
    assert_eq!(
        series_value(
            &rendered,
            crate::metrics::names::DESER_RECORDS_DROPPED_TOTAL,
            r#"reason="skip_policy""#
        ),
        0,
        "{rendered}"
    );
}

/// A payload that reports NotReady and then Fatal on replay fails the batch
/// and clears the stash, so the next batch starts cleanly at index 0.
#[test]
fn a_fatal_on_replay_fails_the_batch_and_clears_the_stash() {
    let mut statuses = Vec::new();
    let rendered = crate::metrics::render_local(|| {
        let (queues, _rxs) = shard_queues(1, 64);
        let mut c = chain(FatalDeser { not_ready_first: 1 })
            .with_metrics("fataltest", "main")
            .flat_map::<SubF, _>(split_body)
            .sink(
                SubEncoder,
                ToZero,
                ChunkConfig::default(),
                queues,
                Arc::new(InflightBudget::new()),
            )
            .build();

        let b1 = payloads(&["a:one", "b:two|fatal"]);
        let (mut batch1, ack1_rx) = TestBatch::new(&b1);
        let PushOutcome::Blocked { resume_at, reason } = c.push_batch(&mut batch1, 0) else {
            panic!("expected Blocked NotReady");
        };
        assert_eq!((resume_at, reason), (1, BlockReason::NotReady));
        assert!(matches!(
            c.push_batch(&mut batch1, 1),
            PushOutcome::Fatal(_)
        ));
        drop(batch1);

        let b2 = payloads(&["c:three"]);
        let (mut batch2, ack2_rx) = TestBatch::new(&b2);
        assert!(matches!(c.push_batch(&mut batch2, 0), PushOutcome::Done));
        drop(batch2);
        drop(c);
        statuses.push(ack1_rx.try_recv().expect("batch 1 resolved").status);
        statuses.push(ack2_rx.try_recv().expect("batch 2 resolved").status);
    });
    assert_eq!(statuses[0], AckStatus::Failed);
    let name = crate::metrics::names::DESER_NOT_READY_TOTAL;
    assert_eq!(series_value(&rendered, name, "fataltest"), 1, "{rendered}");
}