rypipe-core 0.6.1

Format-agnostic ingestion framework with Arrow export
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
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
#[cfg(test)]
use std::borrow::Cow;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Arc;

#[cfg(feature = "profile")]
use std::sync::atomic::{AtomicUsize, Ordering};

/// Diagnostic: counts resolve_and_put calls across all TableBuilder instances.
#[cfg(feature = "profile")]
pub static RESOLVE_AND_PUT_COUNT: AtomicUsize = AtomicUsize::new(0);
/// Diagnostic: counts predicate evaluations across all TableBuilder instances.
#[cfg(feature = "profile")]
pub static PREDICATE_EVALUATIONS: AtomicUsize = AtomicUsize::new(0);
/// Diagnostic: counts how many times evaluate_predicate_state returns Fail.
#[cfg(feature = "profile")]
pub static PREDICATE_FAILS: AtomicUsize = AtomicUsize::new(0);
/// Diagnostic: counts how many times evaluate_predicate_state returns Undecided.
#[cfg(feature = "profile")]
pub static PREDICATE_UNDECIDED: AtomicUsize = AtomicUsize::new(0);
/// Diagnostic: counts how many times is_predicate_slot returns true.
#[cfg(feature = "profile")]
pub static IS_PRED_TRUE: AtomicUsize = AtomicUsize::new(0);
/// Diagnostic: counts how many times is_predicate_slot returns false.
#[cfg(feature = "profile")]
pub static IS_PRED_FALSE: AtomicUsize = AtomicUsize::new(0);

use arrow::datatypes::{Field as ArrowField, Schema};
use arrow::record_batch::RecordBatch;
use rustc_hash::FxHashMap as HashMap;

use smallvec::SmallVec;

use crate::columnar::ColumnBuilder;
use crate::decoder::ColumnarSink;
use crate::engine::predicate::{PredicateState, RowBuffer};
use crate::plan::{ExecutionPlan, FieldType, FilterPredicate};
use crate::value::Value;
use crate::Result;

mod memory;
mod predicates;

/// Generic columnar table builder.  Implements `ColumnarSink` so any decoder
/// can feed it field/value events; at the end it produces an Arrow
/// `RecordBatch`.
pub struct TableBuilder {
    pub(crate) memory_limit: Option<usize>,
    pub(crate) columns: Vec<ColumnBuilder>,
    pub(crate) field_index: HashMap<String, usize>,
    pub(crate) column_order: Vec<String>,
    pub(crate) row_count: usize,
    pub(crate) estimated_rows: usize,
    pub(crate) plan: Arc<ExecutionPlan>,
    /// Dirty mask for the current row: bit `i` set iff column `i` received a
    /// value in this row. `Vec<u64>` word array so >64 columns work (e.g.,
    /// Crystal Reports exports with >64 fields). One compare `mask != full`
    /// replaces `for col in 0..ncols` loop when every field is present (dense).
    pub(crate) row_dirty: Vec<u64>,
    /// Frozen schema for parallel streaming. When Some, any field not in the
    /// schema is an unknown field and hard-errors on `finish()` (data loss
    /// would otherwise be silent). Discovery samples 16×2 MiB for >128 MiB.
    pub(crate) frozen: Option<std::sync::Arc<crate::schema::FrozenSchema>>,
    pub(crate) unknown_error: Option<String>,
    /// Heap-allocated row buffer for predicate-first deferred materialization.
    /// `None` when `plan.filter` is `None`; unfiltered parses carry zero
    /// overhead from predicate machinery.
    pub(crate) row_buf: Option<Box<RowBuffer>>,
    /// Cached projection mask for `wanted_mask()`/`row_satisfied()`: bit `i`
    /// set iff column `i` is wanted by the schema projection (declared schema
    /// columns plus any extra fields the row filter needs).  Computed once in
    /// `with_plan` after schema columns are pre-declared, so it is complete
    /// from the first row — unlike a mask derived from `field_index` at call
    /// time, which only covers columns already seen in the data.  0 when no
    /// schema projection is active (short-circuit disabled).
    pub(crate) cached_wanted_mask: u64,
    /// Per-ordinal layout expectation: after row 1, each ordinal maps to a
    /// (slot_index, raw_name) pair.  The adapter can memcmp the raw bytes
    /// in-place instead of running the full attribute scan → UTF-8 decode →
    /// hash → lookup path.  `None` after `layout_broken` or before row 1.
    pub(crate) ordinal_expect: Vec<Option<(u32, Vec<u8>)>>,
    /// Current ordinal within the row (incremented per put_field call).
    /// Used to populate `ordinal_expect` on the first row.
    pub(crate) current_ordinal: u32,
    /// First strict-types violation (column, value, row). Recorded during
    /// puts (the `ColumnarSink` trait is infallible) and surfaced by
    /// `finish()` as an error.
    pub(crate) strict_error: Option<crate::Error>,
    /// Rows committed since the last `finish()`/`reset()` (for observer
    /// `on_chunk_finished`). Tracked unconditionally: two usize increments.
    pub(crate) rows_accepted: usize,
    /// Rows rejected by the filter since the last `finish()`/`reset()`.
    pub(crate) rows_rejected: usize,
}

impl TableBuilder {
    pub fn new() -> Self {
        Self {
            memory_limit: None,
            columns: Vec::new(),
            field_index: HashMap::default(),
            column_order: Vec::new(),
            row_count: 0,
            estimated_rows: 0,
            plan: Arc::new(ExecutionPlan::new()),
            row_dirty: Vec::new(),
            frozen: None,
            unknown_error: None,
            row_buf: None,
            cached_wanted_mask: 0,
            ordinal_expect: Vec::new(),
            current_ordinal: 0,
            strict_error: None,
            rows_accepted: 0,
            rows_rejected: 0,
        }
    }

    pub fn with_capacity(cap: usize) -> Self {
        Self {
            memory_limit: None,
            columns: Vec::new(),
            field_index: HashMap::default(),
            column_order: Vec::new(),
            row_count: 0,
            estimated_rows: cap,
            plan: Arc::new(ExecutionPlan::new()),
            row_dirty: Vec::new(),
            frozen: None,
            unknown_error: None,
            row_buf: None,
            cached_wanted_mask: 0,
            ordinal_expect: Vec::new(),
            current_ordinal: 0,
            strict_error: None,
            rows_accepted: 0,
            rows_rejected: 0,
        }
    }

    pub fn with_plan(cap: usize, plan: Arc<ExecutionPlan>) -> Self {
        let mut b = Self {
            memory_limit: None,
            columns: Vec::new(),
            field_index: HashMap::default(),
            column_order: Vec::new(),
            row_count: 0,
            estimated_rows: cap,
            plan: Arc::clone(&plan),
            row_dirty: Vec::new(),
            frozen: None,
            unknown_error: None,
            row_buf: if plan.filter.is_some() {
                Some(Box::new(RowBuffer {
                    fields: SmallVec::new(),
                    state: PredicateState::Undecided,
                    predicate_mask: SmallVec::new(),
                    direct: false,
                    predicate_ordinal: None,
                    buffer_worthwhile: true,
                    pred_names: SmallVec::new(),
                }))
            } else {
                None
            },
            cached_wanted_mask: 0,
            ordinal_expect: Vec::new(),
            current_ordinal: 0,
            strict_error: None,
            rows_accepted: 0,
            rows_rejected: 0,
        };
        b.predeclare_schema_columns();
        b.cached_wanted_mask = b.compute_wanted_mask();
        b
    }

    /// Pre-create the declared schema columns (plus any extra columns the row
    /// filter needs) when `schema_order` is a projection.  This makes the
    /// output layout, per-row null-filling, and `cached_wanted_mask` stable
    /// from the first row, regardless of which fields appear in the data or
    /// in what order.  No-op when no schema projection is declared.
    fn predeclare_schema_columns(&mut self) {
        if self.plan.schema_order.is_empty() {
            return;
        }
        let mut names: Vec<String> = Vec::new();
        for name in &self.plan.schema_order {
            // drop_fields wins over schema: a column listed in both is dropped
            // (dropping is an explicit exclusion; silently null-filling it
            // would resurrect a column the user asked to remove).
            if !self.plan.drop_fields.contains(name) {
                names.push(name.clone());
            }
        }
        // Filter-referenced fields are materialized even when not in the
        // schema so predicates evaluate correctly; finish() projects them out.
        if let Some(ref filter) = self.plan.filter {
            let mut pred_names: SmallVec<[String; 4]> = SmallVec::new();
            Self::collect_predicate_field_names(filter, &self.plan, &mut pred_names);
            names.extend(pred_names);
        }
        for name in names {
            if self.field_index.contains_key(&name) || self.plan.drop_fields.contains(&name) {
                continue;
            }
            let ty = self.plan.column_type(&name);
            let col = ColumnBuilder::with_capacity(self.estimated_rows.max(64), &ty);
            self.columns.push(col);
            self.field_index
                .insert(name.clone(), self.columns.len() - 1);
            self.column_order.push(name);
        }
        let words = self.columns.len().div_ceil(64);
        self.row_dirty.resize(words, 0);
    }

    /// Bitmask of wanted columns for the projection short-circuit.  All
    /// wanted columns are pre-declared by `predeclare_schema_columns`, and
    /// non-wanted fields are rejected by `plan.resolve_field`, so the set of
    /// columns existing at construction time is exactly the wanted set.
    /// Returns 0 (short-circuit disabled) when no projection is declared or
    /// when more than 64 columns are wanted.
    fn compute_wanted_mask(&self) -> u64 {
        if self.plan.schema_order.is_empty() {
            return 0;
        }
        let mut mask = 0u64;
        for &idx in self.field_index.values() {
            if idx >= 64 {
                return 0;
            }
            mask |= 1u64 << idx;
        }
        mask
    }

    /// Pre-size all columns from a `FrozenSchema`.
    ///
    /// Called by parallel streaming workers so that every chunk's
    /// `TableBuilder` has the full column set from construction,
    /// regardless of which fields appear in that chunk.
    pub fn ensure_schema(&mut self, schema: &crate::schema::FrozenSchema) -> Result<()> {
        for (slot, name) in schema.column_names().iter().enumerate() {
            let name_str: &str = name;
            if self.field_index.contains_key(name_str) {
                continue; // already present
            }
            let ty = schema.column_types()[slot].clone();
            let col = ColumnBuilder::with_capacity(self.estimated_rows, &ty);
            self.columns.push(col);
            self.field_index
                .insert(name_str.to_string(), self.columns.len() - 1);
            self.column_order.push(name_str.to_string());
        }
        // Resize row_dirty bitmask to cover all columns.
        let words = self.columns.len().div_ceil(64);
        self.row_dirty.resize(words, 0);
        // Freeze: any later field not in this schema is an unknown field and
        // must hard-error (otherwise data loss would be silent on a default
        // path). Sampling 16×2 MiB covers ~6% of a 533 MB file, so 1% Text21
        // is expected ~280 hits, but 0.05% would be missed.
        self.frozen = Some(std::sync::Arc::new(schema.clone()));
        Ok(())
    }

    /// Lookup a column by resolved name.
    pub(crate) fn get_column(&self, name: &str) -> Option<&ColumnBuilder> {
        self.field_index.get(name).map(|&i| &self.columns[i])
    }

    /// Mutable lookup by resolved name.
    pub(crate) fn get_column_mut(&mut self, name: &str) -> Option<&mut ColumnBuilder> {
        if let Some(&i) = self.field_index.get(name) {
            Some(&mut self.columns[i])
        } else {
            None
        }
    }

    #[allow(dead_code)]
    pub(crate) fn bytes_used(&self) -> usize {
        self.columns.iter().map(|c| c.bytes_used()).sum::<usize>()
            + self.column_order.iter().map(|s| s.len()).sum::<usize>()
            + self.row_dirty.len() * 8
    }

    /// Split off the first `n` rows into a new `TableBuilder`.
    ///
    /// Leaves `n` rows in `self`'s remainder as `self - n`. Used for
    /// 64KB streaming where a single file chunk may contain many more rows
    /// than `rows_per_batch`.
    pub(crate) fn split_off(&mut self, n: usize) -> Self {
        assert!(n <= self.row_count, "split_off beyond row_count");
        assert!(n > 0);
        let mut other = Self {
            memory_limit: self.memory_limit,
            columns: Vec::with_capacity(self.columns.len()),
            field_index: self.field_index.clone(),
            column_order: self.column_order.clone(),
            row_count: n,
            estimated_rows: n,
            plan: Arc::clone(&self.plan),
            row_dirty: vec![0; self.columns.len().div_ceil(64)],
            frozen: self.frozen.clone(),
            unknown_error: None,
            cached_wanted_mask: self.cached_wanted_mask,
            row_buf: if self.plan.filter.is_some() {
                Some(Box::new(RowBuffer {
                    fields: SmallVec::new(),
                    state: PredicateState::Undecided,
                    predicate_mask: self
                        .row_buf
                        .as_ref()
                        .map_or_else(SmallVec::new, |b| b.predicate_mask.clone()),
                    direct: false,
                    predicate_ordinal: None,
                    buffer_worthwhile: true,
                    pred_names: self
                        .row_buf
                        .as_ref()
                        .map_or_else(SmallVec::new, |b| b.pred_names.clone()),
                }))
            } else {
                None
            },
            ordinal_expect: Vec::new(),
            current_ordinal: 0,
            strict_error: None,
            // The split-off batch reports the rows accumulated since the
            // previous split; the remainder starts a fresh delta.
            rows_accepted: std::mem::take(&mut self.rows_accepted),
            rows_rejected: std::mem::take(&mut self.rows_rejected),
        };
        for (idx, col) in self.columns.iter_mut().enumerate() {
            let drain = col.split_off(n);
            other.columns.push(drain);
            // Remainder stays in self.columns[idx]
            let _ = idx;
        }
        self.row_count -= n;
        // row_dirty for self should be all false (no dirty in remainder yet)
        self.row_dirty = vec![0; self.columns.len().div_ceil(64)];
        // row_dirty for other is also false (just finished batch)
        other
    }

    /// Remove and return a column by name, fixing the Vec index map.
    /// Used by `merge::extend` to move builders out of the `other` table.
    pub(crate) fn take_column(&mut self, name: &str) -> Option<ColumnBuilder> {
        let idx = self.field_index.remove(name)?;
        // Keep row_dirty in sync: Vec<u64> bitmask, need to handle bit removal
        // For simplicity, just rebuild row_dirty as all zeros after column removal
        // (row_dirty is per-row, not per-column persistent, so clearing is fine)
        // Rebuild to correct length
        let new_len = self.columns.len().div_ceil(64);
        self.row_dirty.resize(new_len, 0);
        // Clear all bits (no dirty in remainder for take_column case)
        self.row_dirty.fill(0);
        let _ = idx; // suppress unused warning
                     // After removal, columns.len() == old_len; last index = old_len - 1.
                     // swap_remove will move the last element into idx (if not already last).
        let last = self.columns.len() - 1;
        let col = if idx == last {
            self.columns.pop().unwrap()
        } else {
            let col = self.columns.swap_remove(idx);
            // The element that was at `last` is now at `idx`; fix its map entry.
            let old_last = self.columns.len(); // == last, new len after pop/swap
                                               // Find the key that pointed to old_last and repoint it to idx.
                                               // We must not borrow field_index mutably while iterating, so clone the key first.
            let moved_name = self.field_index.iter().find_map(|(k, &v)| {
                if v == old_last {
                    Some(k.clone())
                } else {
                    None
                }
            });
            if let Some(k) = moved_name {
                self.field_index.insert(k, idx);
            }
            col
        };
        Some(col)
    }

    pub fn num_rows(&self) -> usize {
        self.row_count
    }

    pub fn num_columns(&self) -> usize {
        self.column_order.len()
    }

    pub fn column_names(&self) -> &[String] {
        &self.column_order
    }

    /// Diagnostic: (name, bytes_used, bytes_capacity) for each column.
    pub fn column_diagnostics(&self) -> Vec<(String, usize, usize)> {
        self.column_order
            .iter()
            .map(|name| {
                let idx = self.field_index[name];
                let col = &self.columns[idx];
                (name.clone(), col.bytes_used(), col.capacity_bytes())
            })
            .collect()
    }

    /// The estimated_rows capacity hint passed to with_plan.
    pub fn estimated_rows(&self) -> usize {
        self.estimated_rows
    }

    /// Finalize the builder into an Arrow `RecordBatch`.
    ///
    /// This is also available as the `ColumnarSink::finish` trait method.
    pub fn finish(&mut self) -> Result<RecordBatch> {
        ColumnarSink::finish(self)
    }

    pub(crate) fn prepare_finish(&mut self) -> Result<()> {
        if let Some(err) = self.unknown_error.take() {
            return Err(crate::Error::Merge(err));
        }
        if let Some(err) = self.strict_error.take() {
            return Err(err);
        }
        self.check_memory_budget()?;
        if let Some(ref observer) = self.plan.observer {
            let result = catch_unwind(AssertUnwindSafe(|| {
                observer.on_chunk_finished(
                    self.rows_accepted + self.rows_rejected,
                    self.rows_accepted,
                    self.rows_rejected,
                );
            }));
            if let Err(payload) = result {
                let message = payload
                    .downcast_ref::<&str>()
                    .map(|s| (*s).to_string())
                    .or_else(|| payload.downcast_ref::<String>().cloned())
                    .unwrap_or_else(|| "unknown panic".to_string());
                return Err(crate::Error::Parser(format!(
                    "observer panicked at chunk completion: {message}"
                )));
            }
        }
        self.normalize();
        Ok(())
    }

    /// Reset all data while preserving the plan and estimated rows.
    pub fn reset(&mut self) {
        self.columns.clear();
        self.field_index.clear();
        self.column_order.clear();
        self.row_dirty.fill(0);
        self.row_count = 0;
        if let Some(ref mut buf) = self.row_buf {
            buf.fields.clear();
            buf.state = PredicateState::Undecided;
        }
        // Keep frozen/row_buf (per builder, not per row)
        self.unknown_error = None;
        self.strict_error = None;
        self.rows_accepted = 0;
        self.rows_rejected = 0;
    }

    /// Truncate every column back to `row_count`, dropping any partial-row
    /// values from a mid-field EOF.  Idempotent.
    pub fn normalize(&mut self) {
        for b in &mut self.columns {
            while b.len() > self.row_count {
                b.pop();
            }
        }
        // Discard any dirty state for the partial row.
        self.row_dirty.fill(0);
    }

    /// If `auto_dict` is set, upgrade low-cardinality string columns using the
    /// plan's threshold/max-size tuning (defaults: 5% ratio, max size 256).
    pub fn auto_dict_upgrade(&mut self) {
        if self.plan.auto_dict {
            let max_ratio = self.plan.dict_threshold.unwrap_or(0.05);
            let max_size = self.plan.dict_max_size.unwrap_or(256);
            for b in &mut self.columns {
                b.try_upgrade_to_dict(512, max_ratio, max_size);
            }
        }
    }

    /// Sort columns according to `schema_order`.  Columns named in
    /// `schema_order` appear in that order; any other columns keep their
    /// relative first-appearance order after the ordered ones.
    pub fn sort_columns(&mut self) {
        if self.plan.schema_order.is_empty() {
            return;
        }
        let order = &self.plan.schema_order;
        let rank = |name: &String| order.iter().position(|n| n == name).unwrap_or(usize::MAX);
        self.column_order.sort_by_key(rank);
    }

    pub(crate) fn schema_insert_index(&self, name: &str) -> usize {
        let order = &self.plan.schema_order;
        if order.is_empty() {
            return self.column_order.len();
        }
        let pos = order.iter().position(|n| n == name);
        match pos {
            Some(p) => self
                .column_order
                .iter()
                .position(|existing| {
                    order
                        .iter()
                        .position(|n| n == existing)
                        .is_some_and(|ep| ep > p)
                })
                .unwrap_or(self.column_order.len()),
            None => self.column_order.len(),
        }
    }

    /// Ensure the column exists and return its Vec index.
    /// Single hash lookup for the hot path; new columns are created and
    /// inserted into `column_order` via `schema_insert_index`.
    fn ensure_column_idx(&mut self, name: &str) -> usize {
        if let Some(&idx) = self.field_index.get(name) {
            return idx;
        }
        // Frozen schema: any new column not pre-sized by ensure_schema is an
        // unknown field (sampling miss or file has column absent during
        // discovery). Don't silently create it; hard-error on finish().
        // We still return a dummy idx to keep the hot path inlinable, but
        // push_field_resolved will have already early-returned after setting
        // unknown_error, so this path is only for non-frozen builders.
        if self.frozen.is_some() {
            if let Some(frozen) = &self.frozen {
                if frozen.is_exact() {
                    // Exact schema: error on unknown fields
                    if self.unknown_error.is_none() {
                        self.unknown_error = Some(format!(
                            "unknown field {:?} not in frozen schema ({} columns, exact={}); pass schema=[...] with full column list or use full-scan discovery",
                            name,
                            frozen.num_columns(),
                            frozen.is_exact()
                        ));
                    }
                    return 0;
                }
                // Non-exact (partial schema): fall through to create column dynamically
            }
        }
        let est = self.estimated_rows.max(64);
        let col_type = self.plan.column_type(name);
        let mut b = ColumnBuilder::with_capacity(est, &col_type);
        // When the predicate passes mid-row, drain_buffered increments
        // row_count before all fields are pushed. New columns created after
        // that must backfill row_count-1 Nones (for the already-committed
        // rows), not row_count, because the current row's value follows.
        let backfill = if self.row_buf.as_ref().is_some_and(|b| b.direct) {
            self.row_count.saturating_sub(1)
        } else {
            self.row_count
        };
        for _ in 0..backfill {
            b.push(None);
        }
        let idx = self.columns.len();
        self.columns.push(b);
        self.field_index.insert(name.to_owned(), idx);
        // Ensure row_dirty has enough words for new column
        let needed = self.columns.len().div_ceil(64);
        if self.row_dirty.len() < needed {
            self.row_dirty.resize(needed, 0);
        }
        let order_idx = self.schema_insert_index(name);
        self.column_order.insert(order_idx, name.to_owned());
        idx
    }

    /// Strict-types check for the value about to land in column `idx`: when
    /// `plan.strict_types` is set, a non-null string that does not parse into
    /// the declared `field_types` type is recorded as the first strict
    /// violation (surfaced by `finish()`). Nulls and non-string values never
    /// trigger it.
    #[inline]
    fn record_strict_violation_at(&mut self, idx: usize, value: &Value<'_>) {
        if !self.plan.strict_types || self.strict_error.is_some() {
            return;
        }
        let Value::Str(s) = value else {
            return;
        };
        let Some(name) = self.column_order.get(idx) else {
            return;
        };
        let Some(ft) = self.plan.field_types.get(name) else {
            return;
        };
        if crate::columnar::parses_as(s, ft) {
            return;
        }
        let truncated: String = s.chars().take(64).collect();
        self.strict_error = Some(crate::Error::Plan(format!(
            "strict_types: value {truncated:?} in column {name:?} at row {} \
             does not parse as declared type {ft:?}",
            self.row_count
        )));
    }

    /// Notify the plan's observer (if any) that `value` landed in column
    /// `idx`. Not called for buffered values; those fire on drain instead.
    #[inline]
    fn notify_put_field(&self, idx: usize, value: &Value<'_>) {
        if let Some(ref obs) = self.plan.observer {
            if let Some(name) = self.column_order.get(idx) {
                obs.on_put_field(self.row_count, name, idx, value);
            }
        }
    }

    /// Push a field value without resolving renames/drops.
    /// Caller must have already resolved `resolved_name` (or know it is kept).
    #[inline]
    fn push_field_resolved(&mut self, resolved_name: &str, value: Value<'_>) {
        // #[inline]: small hot path, called per-field. ensure_column_idx is not
        // inlined (too large); push_value is the real work and benefits from
        // being in the same compilation unit as its caller.
        // Frozen check: hard error on unknown field when exact schema (data loss
        // would be silent on a default path). Non-exact schemas allow unknown
        // fields to be created dynamically.
        if self.frozen.is_some() && !self.field_index.contains_key(resolved_name) {
            if let Some(frozen) = &self.frozen {
                if frozen.is_exact() {
                    // Exact schema: error on unknown fields
                    if self.unknown_error.is_none() {
                        self.unknown_error = Some(format!(
                            "unknown field {:?} not in frozen schema ({} columns, exact={}); pass schema=[...] with full column list or use full-scan discovery",
                            resolved_name,
                            frozen.num_columns(),
                            frozen.is_exact()
                        ));
                    }
                    return;
                }
                // Non-exact (partial schema): fall through to ensure_column_idx
            }
        }
        let idx = self.ensure_column_idx(resolved_name);
        self.record_strict_violation_at(idx, &value);
        self.notify_put_field(idx, &value);
        // Track ordinal→slot mapping on first row for expect_slot fast path.
        if self.row_count == 0 {
            let ord = self.current_ordinal as usize;
            if ord >= self.ordinal_expect.len() {
                self.ordinal_expect.resize_with(ord + 1, || None);
            }
            self.ordinal_expect[ord] = Some((idx as u32, resolved_name.as_bytes().to_vec()));
        }
        self.current_ordinal += 1;
        let word = idx / 64;
        let bit = idx % 64;
        self.row_dirty[word] |= 1u64 << bit;
        let b = &mut self.columns[idx];
        let row_count = self.row_count;
        if b.len() > row_count {
            b.pop();
        }
        b.push_value(value);
    }

    /// Push a field value, resolving renames/drops and applying last-write-wins
    /// within the current uncommitted row.
    #[inline]
    fn push_field(&mut self, name: &str, value: Value<'_>) {
        // #[inline]: fast-path (no rename/drop) is a single branch + delegate.
        // Fast path: no rename/drop/projection configured; zero allocation.
        if self.plan.field_map.is_empty()
            && self.plan.drop_fields.is_empty()
            && self.plan.schema_order.is_empty()
        {
            self.push_field_resolved(name, value);
            return;
        }
        // Resolve name via plan's field_map (borrows &self.plan).
        // Try the zero-allocation fast path: column already exists.
        if let Some(idx) = Self::resolve_and_slot(&self.plan, &self.field_index, name) {
            self.record_strict_violation_at(idx, &value);
            self.notify_put_field(idx, &value);
            // Track ordinal→slot mapping on first row for expect_slot fast path.
            if self.row_count == 0 {
                let ord = self.current_ordinal as usize;
                if ord >= self.ordinal_expect.len() {
                    self.ordinal_expect.resize_with(ord + 1, || None);
                }
                // Store the resolved name (what plan.resolve_field would return).
                let resolved = self.plan.resolve_field(name).unwrap_or(name);
                self.ordinal_expect[ord] = Some((idx as u32, resolved.as_bytes().to_vec()));
            }
            self.current_ordinal += 1;
            let word = idx / 64;
            let bit = idx % 64;
            self.row_dirty[word] |= 1u64 << bit;
            let b = &mut self.columns[idx];
            let row_count = self.row_count;
            if b.len() > row_count {
                b.pop();
            }
            b.push_value(value);
        } else {
            // Column doesn't exist yet (first row with rename) or field was
            // dropped. Only allocate when the field is kept.
            if let Some(resolved) = self.plan.resolve_field(name) {
                let owned = resolved.to_owned();
                self.push_field_resolved(&owned, value);
            }
        }
    }

    /// Resolve a field name through the plan's field_map and look up its slot
    /// index. Returns `Some(slot)` only if the column already exists in
    /// field_index. Zero allocation; borrows plan and field_index as
    /// separate fields.
    #[inline]
    fn resolve_and_slot(
        plan: &ExecutionPlan,
        field_index: &HashMap<String, usize>,
        name: &str,
    ) -> Option<usize> {
        let resolved = plan.resolve_field(name)?;
        field_index.get(resolved).copied()
    }

    /// Advance the row counter without null-fill, filter, or dirty-mask clear.
    /// For benchmarking only; separates per-field push cost from per-row
    /// finalization.
    #[doc(hidden)]
    pub fn advance_row(&mut self) {
        self.row_count += 1;
    }

    /// Null-fill any column missing this row, then apply the per-row filter.
    /// If the filter rejects the row, undo it by popping values.
    /// Uses the dirty bitmask so only missing columns are touched; fast path
    /// when every column was set (dense data, 10 cols) skips the loop.
    fn finish_row(&mut self) {
        // No #[inline]: 30+ lines with loops; inlining causes code bloat.
        let ncols = self.columns.len();
        // Fast path: check if all bits set
        let full_words = ncols / 64;
        let rem_bits = ncols % 64;
        let is_full = (0..full_words).all(|w| self.row_dirty[w] == u64::MAX)
            && (rem_bits == 0
                || self.row_dirty.get(full_words).copied().unwrap_or(0) == (1u64 << rem_bits) - 1);
        if is_full {
            self.row_dirty.fill(0);
        } else {
            for (i, b) in self.columns.iter_mut().enumerate() {
                let word = i / 64;
                let bit = i % 64;
                let is_set = (self.row_dirty[word] >> bit) & 1 == 1;
                if !is_set {
                    b.push(None);
                }
            }
            self.row_dirty.fill(0);
        }

        if let Some(ref filter) = self.plan.filter {
            if !filter.check(&self.columns, &self.field_index, self.row_count, &self.plan) {
                for b in &mut self.columns {
                    b.pop();
                }
                self.rows_rejected += 1;
                if let Some(ref obs) = self.plan.observer {
                    obs.on_row_rejected(self.row_count);
                }
                return;
            }
        }

        self.row_count += 1;
        self.rows_accepted += 1;
        if let Some(ref obs) = self.plan.observer {
            obs.on_row_accepted(self.row_count - 1);
        }
    }

    /// Null-fill any column missing the current row, then clear row_dirty.
    /// Called when the predicate resolved to Pass mid-row (direct mode).
    fn null_fill_missing(&mut self) {
        let ncols = self.columns.len();
        let full_words = ncols / 64;
        let rem_bits = ncols % 64;
        let is_full = (0..full_words).all(|w| self.row_dirty[w] == u64::MAX)
            && (rem_bits == 0
                || self.row_dirty.get(full_words).copied().unwrap_or(0) == (1u64 << rem_bits) - 1);
        if is_full {
            self.row_dirty.fill(0);
        } else {
            for (i, b) in self.columns.iter_mut().enumerate() {
                let word = i / 64;
                let bit = i % 64;
                let is_set = (self.row_dirty[word] >> bit) & 1 == 1;
                if !is_set {
                    b.push(None);
                }
            }
            self.row_dirty.fill(0);
        }
        // Note: row_count was already incremented by drain_buffered(true)
        // when the predicate resolved to Pass mid-row. Do NOT increment here.
    }
}

impl Default for TableBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl ColumnarSink for TableBuilder {
    #[inline]
    fn begin_row(&mut self) {
        if !self.reserve_memory(0) {
            return;
        }
        if let Some(ref obs) = self.plan.observer {
            obs.on_begin_row(self.row_count);
        }
        self.current_ordinal = 0;
        if let Some(ref mut buf) = self.row_buf {
            // Adaptive strategy: after at least one committed row, decide
            // whether buffering is worthwhile based on the predicate column's
            // ordinal relative to the total number of columns.  We must wait
            // until row_count > 0 because early-rejected rows don't create
            // all columns, making ncols unreliable for the ordinal comparison.
            if buf.predicate_ordinal.is_some() && buf.buffer_worthwhile && self.row_count > 0 {
                // Use the most accurate column count available. self.columns.len()
                // is unreliable for sparse files where not all columns exist yet.
                let ncols = self
                    .frozen
                    .as_ref()
                    .map(|f| f.num_columns() as u32)
                    .or_else(|| {
                        (!self.plan.schema_order.is_empty())
                            .then(|| self.plan.schema_order.len() as u32)
                    })
                    .unwrap_or(self.columns.len() as u32);
                if let Some(ordinal) = buf.predicate_ordinal {
                    if ordinal >= ncols * 4 / 5 {
                        buf.buffer_worthwhile = false;
                    }
                }
            }
            buf.fields.clear();
            buf.state = PredicateState::Undecided;
            buf.direct = false;
        }
    }

    #[inline]
    fn put_field(&mut self, name: &str, value: Value<'_>) {
        if !self.reserve_field_memory(name.len(), &value) {
            return;
        }
        if self.plan.filter.is_none() {
            self.push_field(name, value);
            return;
        }
        // Adaptive: late predicate → push directly, pop-on-reject at end_row.
        let buf_worthwhile = self.row_buf.as_ref().is_none_or(|b| b.buffer_worthwhile);
        if !buf_worthwhile {
            self.push_field(name, value);
            return;
        }
        // Buffered path: resolve name → slot, buffer (slot, value).
        let resolved = match self.plan.resolve_field(name) {
            Some(r) => r.to_owned(),
            None => return,
        };
        // Check frozen unknown (as in push_field_resolved)
        if self.frozen.is_some()
            && !self.field_index.contains_key(&resolved)
            && self.unknown_error.is_none()
        {
            if let Some(ref frozen) = self.frozen {
                if frozen.is_exact()
                    && !frozen.column_names().iter().any(|n| n.as_ref() == resolved)
                {
                    self.unknown_error = Some(format!(
                            "unknown field {:?} not in frozen schema ({} columns, exact={}); pass schema=[...]",
                            resolved,
                            frozen.num_columns(),
                            frozen.is_exact()
                        ));
                    return;
                }
            }
        }
        let slot = self.ensure_column_idx(&resolved) as u32;
        self.record_strict_violation_at(slot as usize, &value);
        self.mark_predicate_slot(slot);
        let val_static: Value<'static> = value.into_static();
        let is_pred = self.is_predicate_slot(slot);
        #[cfg(feature = "profile")]
        if is_pred {
            crate::engine::IS_PRED_TRUE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        } else {
            crate::engine::IS_PRED_FALSE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
        // Push value to buffer BEFORE evaluating predicate (value must be findable).
        if let Some(ref mut buf) = self.row_buf {
            if let Some(pos) = buf.fields.iter().position(|(s, _)| *s == slot) {
                buf.fields[pos].1 = val_static;
            } else {
                buf.fields.push((slot, val_static));
            }
        }
        if is_pred {
            // Record predicate ordinal for adaptive strategy (once)
            if let Some(ref mut buf) = self.row_buf {
                if buf.predicate_ordinal.is_none() {
                    buf.predicate_ordinal = Some(slot);
                }
            }
            let state = self.evaluate_predicate_state();
            if let Some(ref mut buf) = self.row_buf {
                buf.state = state;
            }
        }
    }

    #[inline]
    fn end_row(&mut self) {
        if !self.reserve_memory(0) {
            return;
        }
        if self.plan.filter.is_none() {
            self.finish_row();
            return;
        }
        // Check adaptive strategy: if buffering is not worthwhile (late
        // predicate), use direct push + pop-on-reject (finish_row).
        let buf_worthwhile = self.row_buf.as_ref().is_none_or(|b| b.buffer_worthwhile);
        if !buf_worthwhile {
            // Late predicate: values were pushed directly to columns.
            // finish_row null-fills missing, evaluates filter against columns,
            // and pops on reject; exactly the pre-buffering behavior.
            self.finish_row();
            return;
        }
        // Buffered path
        let (state, direct) = self
            .row_buf
            .as_ref()
            .map_or((PredicateState::Pass, false), |b| (b.state, b.direct));
        if direct {
            // Already flushed to columns; just null-fill missing columns.
            self.null_fill_missing();
            return;
        }
        let state = if state == PredicateState::Undecided {
            self.evaluate_against_null()
        } else {
            state
        };
        let pass = state == PredicateState::Pass;
        self.drain_buffered(pass);
    }

    #[inline]
    fn wants(&self, name: &str) -> bool {
        self.resolve(name).is_some()
    }

    #[inline]
    fn resolve<'a>(&'a self, name: &'a str) -> Option<&'a str> {
        self.plan.resolve_field(name)
    }

    #[inline]
    fn put_field_resolved(&mut self, resolved_name: &str, value: Value<'_>) {
        if !self.reserve_field_memory(resolved_name.len(), &value) {
            return;
        }
        if self.plan.filter.is_none() {
            self.push_field_resolved(resolved_name, value);
            return;
        }
        // Adaptive: late predicate → push directly, pop-on-reject at end_row.
        let buf_worthwhile = self.row_buf.as_ref().is_none_or(|b| b.buffer_worthwhile);
        if !buf_worthwhile {
            self.push_field_resolved(resolved_name, value);
            return;
        }
        // Buffered path for already-resolved name (no rename lookup)
        if self.frozen.is_some() && !self.field_index.contains_key(resolved_name) {
            if let Some(ref frozen) = self.frozen {
                if frozen.is_exact()
                    && !frozen
                        .column_names()
                        .iter()
                        .any(|n| n.as_ref() == resolved_name)
                {
                    if self.unknown_error.is_none() {
                        self.unknown_error = Some(format!(
                            "unknown field {:?} not in frozen schema ({} columns, exact={}); pass schema=[...]",
                            resolved_name,
                            frozen.num_columns(),
                            frozen.is_exact()
                        ));
                    }
                    return;
                }
            }
        }
        let slot = self.ensure_column_idx(resolved_name) as u32;
        self.record_strict_violation_at(slot as usize, &value);
        self.mark_predicate_slot(slot);
        let val_static: Value<'static> = value.into_static();
        let is_pred = self.is_predicate_slot(slot);
        #[cfg(feature = "profile")]
        if is_pred {
            crate::engine::IS_PRED_TRUE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        } else {
            crate::engine::IS_PRED_FALSE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
        if let Some(ref mut buf) = self.row_buf {
            if let Some(pos) = buf.fields.iter().position(|(s, _)| *s == slot) {
                buf.fields[pos].1 = val_static;
            } else {
                buf.fields.push((slot, val_static));
            }
        }
        if is_pred {
            // Record predicate ordinal for adaptive strategy (once)
            if let Some(ref mut buf) = self.row_buf {
                if buf.predicate_ordinal.is_none() {
                    buf.predicate_ordinal = Some(slot);
                }
            }
            let state = self.evaluate_predicate_state();
            if let Some(ref mut buf) = self.row_buf {
                buf.state = state;
            }
        }
    }

    /// Push a value directly to a known slot index, bypassing all name
    /// resolution and hash lookups.  Used by adapters that verified the
    /// field identity via `expect_slot` + memcmp on raw bytes.
    #[inline]
    fn put_field_at(&mut self, slot: u32, value: Value<'_>) {
        if !self.reserve_field_memory(0, &value) {
            return;
        }
        let idx = slot as usize;
        if idx >= self.columns.len() {
            // Slot doesn't exist yet (sparse row). Fall back to ensure.
            // This shouldn't happen after row 1 with a stable layout.
            return;
        }
        self.record_strict_violation_at(idx, &value);
        self.notify_put_field(idx, &value);
        let word = idx / 64;
        let bit = idx % 64;
        self.row_dirty[word] |= 1u64 << bit;
        let b = &mut self.columns[idx];
        let row_count = self.row_count;
        if b.len() > row_count {
            b.pop();
        }
        b.push_value(value);
    }

    /// `put_field_at` specialized for a known `&str` value: skips the `Value`
    /// construction and its match. Used by adapters that know a field is a
    /// plain string (no declared type). Falls back to the general path when a
    /// memory budget or a filter row-buffer is active.
    #[inline]
    fn put_str_at(&mut self, slot: u32, value: &str) {
        if self.memory_limit.is_some() || self.row_buf.is_some() {
            self.put_field_at(slot, Value::Str(std::borrow::Cow::Borrowed(value)));
            return;
        }
        let idx = slot as usize;
        if idx >= self.columns.len() {
            return;
        }
        if self.plan.strict_types {
            self.record_strict_violation_at(idx, &Value::Str(std::borrow::Cow::Borrowed(value)));
        }
        if self.plan.observer.is_some() {
            self.notify_put_field(idx, &Value::Str(std::borrow::Cow::Borrowed(value)));
        }
        let word = idx / 64;
        let bit = idx % 64;
        self.row_dirty[word] |= 1u64 << bit;
        let b = &mut self.columns[idx];
        let row_count = self.row_count;
        if b.len() > row_count {
            b.pop();
        }
        b.push_str(Some(value));
    }

    #[inline]
    fn resolve_and_put(&mut self, name: &str, value: Value<'_>) {
        if !self.reserve_field_memory(name.len(), &value) {
            return;
        }
        #[cfg(feature = "profile")]
        RESOLVE_AND_PUT_COUNT.fetch_add(1, Ordering::Relaxed);
        if self.plan.filter.is_none() {
            if self.plan.field_map.is_empty()
                && self.plan.drop_fields.is_empty()
                && self.plan.schema_order.is_empty()
            {
                self.push_field_resolved(name, value);
            } else {
                if let Some(resolved) = self.plan.resolve_field(name) {
                    let owned = resolved.to_owned();
                    self.push_field_resolved(&owned, value);
                }
            }
            return;
        }
        // Adaptive: late predicate → push directly, pop-on-reject at end_row.
        if self.row_buf.as_ref().is_some_and(|b| !b.buffer_worthwhile) {
            if self.plan.field_map.is_empty()
                && self.plan.drop_fields.is_empty()
                && self.plan.schema_order.is_empty()
            {
                self.push_field_resolved(name, value);
            } else {
                if let Some(resolved) = self.plan.resolve_field(name) {
                    let owned = resolved.to_owned();
                    self.push_field_resolved(&owned, value);
                }
            }
            return;
        }
        // Direct mode: predicate already passed, push directly to columns.
        if let Some(ref buf) = self.row_buf {
            if buf.direct {
                let resolved = match self.plan.resolve_field(name) {
                    Some(r) => r.to_owned(),
                    None => return, // field is dropped
                };
                if self.frozen.is_some() && !self.field_index.contains_key(resolved.as_str()) {
                    if let Some(ref frozen) = self.frozen {
                        if frozen.is_exact()
                            && !frozen
                                .column_names()
                                .iter()
                                .any(|n| n.as_ref() == resolved.as_str())
                        {
                            if self.unknown_error.is_none() {
                                self.unknown_error = Some(format!(
                                    "unknown field {:?} not in frozen schema ({} columns, exact={}); pass schema=[...]",
                                    resolved, frozen.num_columns(), frozen.is_exact()
                                ));
                            }
                            return;
                        }
                    }
                }
                self.push_field_resolved(&resolved, value);
                return;
            }
        }
        // Buffered path: resolve → slot, buffer (slot, value).
        if self.plan.field_map.is_empty()
            && self.plan.drop_fields.is_empty()
            && self.plan.schema_order.is_empty()
        {
            // No rename/drop, raw == resolved
            let resolved = name;
            if self.frozen.is_some() && !self.field_index.contains_key(resolved) {
                if let Some(ref frozen) = self.frozen {
                    if frozen.is_exact()
                        && !frozen.column_names().iter().any(|n| n.as_ref() == resolved)
                    {
                        if self.unknown_error.is_none() {
                            self.unknown_error = Some(format!(
                                "unknown field {:?} not in frozen schema ({} columns, exact={}); pass schema=[...]",
                                resolved,
                                frozen.num_columns(),
                                frozen.is_exact()
                            ));
                        }
                        return;
                    }
                }
            }
            let slot = self.ensure_column_idx(resolved) as u32;
            self.record_strict_violation_at(slot as usize, &value);
            self.mark_predicate_slot(slot);
            let val_static: Value<'static> = value.into_static();
            let is_pred = self.is_predicate_slot(slot);
            #[cfg(feature = "profile")]
            if is_pred {
                crate::engine::IS_PRED_TRUE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            } else {
                crate::engine::IS_PRED_FALSE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            }
            if let Some(ref mut buf) = self.row_buf {
                if let Some(pos) = buf.fields.iter().position(|(s, _)| *s == slot) {
                    buf.fields[pos].1 = val_static;
                } else {
                    buf.fields.push((slot, val_static));
                }
            }
            if is_pred {
                // Record predicate ordinal for adaptive strategy (once)
                if let Some(ref mut buf) = self.row_buf {
                    if buf.predicate_ordinal.is_none() {
                        buf.predicate_ordinal = Some(slot);
                    }
                }
                let state = self.evaluate_predicate_state();
                if let Some(ref mut buf) = self.row_buf {
                    buf.state = state;
                    if state == PredicateState::Pass {
                        buf.direct = true;
                    }
                }
                if state == PredicateState::Pass {
                    // Predicate passed: drain buffered fields, switch to direct mode.
                    self.drain_buffered(true);
                }
            }
        } else {
            if let Some(resolved) = self.plan.resolve_field(name) {
                let owned = resolved.to_owned();
                if self.frozen.is_some() && !self.field_index.contains_key(&owned) {
                    if let Some(ref frozen) = self.frozen {
                        if frozen.is_exact()
                            && !frozen.column_names().iter().any(|n| n.as_ref() == owned)
                        {
                            if self.unknown_error.is_none() {
                                self.unknown_error = Some(format!(
                                    "unknown field {:?} not in frozen schema ({} columns, exact={}); pass schema=[...]",
                                    owned,
                                    frozen.num_columns(),
                                    frozen.is_exact()
                                ));
                            }
                            return;
                        }
                    }
                }
                let slot = self.ensure_column_idx(&owned) as u32;
                self.record_strict_violation_at(slot as usize, &value);
                self.mark_predicate_slot(slot);
                let val_static: Value<'static> = value.into_static();
                let is_pred = self.is_predicate_slot(slot);
                #[cfg(feature = "profile")]
                if is_pred {
                    crate::engine::IS_PRED_TRUE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                } else {
                    crate::engine::IS_PRED_FALSE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                }
                if let Some(ref mut buf) = self.row_buf {
                    if let Some(pos) = buf.fields.iter().position(|(s, _)| *s == slot) {
                        buf.fields[pos].1 = val_static;
                    } else {
                        buf.fields.push((slot, val_static));
                    }
                }
                if is_pred {
                    // Record predicate ordinal for adaptive strategy (once)
                    if let Some(ref mut buf) = self.row_buf {
                        if buf.predicate_ordinal.is_none() {
                            buf.predicate_ordinal = Some(slot);
                        }
                    }
                    let state = self.evaluate_predicate_state();
                    if let Some(ref mut buf) = self.row_buf {
                        buf.state = state;
                    }
                }
            }
        }
    }

    #[inline]
    fn row_rejected(&self) -> bool {
        self.plan.filter.is_some()
            && self
                .row_buf
                .as_ref()
                .is_some_and(|b| b.state == PredicateState::Fail)
    }

    #[inline]
    fn row_satisfied(&self) -> bool {
        let mask = self.wanted_mask();
        if mask == 0 {
            return false;
        }
        // Check that every wanted bit is set in row_dirty.
        let dirty = self
            .row_dirty
            .iter()
            .copied()
            .reduce(|a, b| a | b)
            .unwrap_or(0);
        (dirty & mask) == mask
    }

    #[inline]
    fn wanted_mask(&self) -> u64 {
        // Precomputed in with_plan after schema columns are pre-declared.
        // Complete from the first row; 0 when no projection is active (the
        // short-circuit stays disabled unless the user explicitly declared
        // which columns they want via schema_order).
        self.cached_wanted_mask
    }

    #[inline]
    fn finish(&mut self) -> Result<RecordBatch> {
        self.prepare_finish()?;

        if self.column_order.is_empty() {
            let schema = Arc::new(Schema::empty());
            return Ok(RecordBatch::new_empty(schema));
        }

        self.auto_dict_upgrade();

        // Schema projection: emit exactly the declared columns, in the
        // declared order.  Columns declared but absent from the data are
        // null-filled; materialized non-schema columns (e.g. filter-only
        // fields kept for predicate evaluation) are projected out.
        if !self.plan.schema_order.is_empty() {
            let order = self.plan.schema_order.clone();
            let mut fields = Vec::with_capacity(order.len());
            let mut arrays = Vec::with_capacity(order.len());
            for name in &order {
                // drop_fields wins over schema (see predeclare_schema_columns).
                if self.plan.drop_fields.contains(name) {
                    continue;
                }
                let idx = match self.field_index.get(name.as_str()) {
                    Some(&i) => i,
                    None => {
                        // Declared but never seen: all-null column.
                        let ty = self.plan.column_type(name);
                        let mut b = ColumnBuilder::with_capacity(self.row_count.max(1), &ty);
                        for _ in 0..self.row_count {
                            b.push(None);
                        }
                        let idx = self.columns.len();
                        self.columns.push(b);
                        self.field_index.insert(name.clone(), idx);
                        idx
                    }
                };
                let b = &mut self.columns[idx];
                fields.push(ArrowField::new(name.as_str(), b.arrow_datatype(), true));
                arrays.push(b.to_arrow_array()?);
            }
            let schema = Arc::new(Schema::new(fields));
            return Ok(RecordBatch::try_new(schema, arrays)?);
        }

        self.sort_columns();

        let mut fields = Vec::with_capacity(self.column_order.len());
        let mut arrays = Vec::with_capacity(self.column_order.len());
        // Iterate by index so we can borrow columns mutably for zero-copy export.
        for name in &self.column_order {
            if let Some(&idx) = self.field_index.get(name.as_str()) {
                let b = &mut self.columns[idx];
                fields.push(ArrowField::new(name.as_str(), b.arrow_datatype(), true));
                arrays.push(b.to_arrow_array()?);
            }
        }

        let schema = Arc::new(Schema::new(fields));
        Ok(RecordBatch::try_new(schema, arrays)?)
    }

    #[inline]
    fn expect_slot(&self, ordinal: u32) -> Option<(u32, &[u8])> {
        self.ordinal_expect
            .get(ordinal as usize)
            .and_then(|entry| entry.as_ref())
            .map(|(slot, raw)| (*slot, raw.as_slice()))
    }

    #[inline]
    fn record_slot(&mut self, ordinal: u32, slot: u32, raw_name: &[u8]) {
        let idx = ordinal as usize;
        let growth = idx
            .saturating_add(1)
            .saturating_sub(self.ordinal_expect.capacity())
            .saturating_mul(std::mem::size_of::<Option<(u32, Vec<u8>)>>());
        if !self.reserve_memory(growth.saturating_add(raw_name.len())) {
            return;
        }
        if idx >= self.ordinal_expect.len() {
            self.ordinal_expect.resize_with(idx + 1, || None);
        }
        self.ordinal_expect[idx] = Some((slot, raw_name.to_vec()));
    }

    #[inline]
    fn layout_broken(&mut self, ordinal: u32) {
        if let Some(entry) = self.ordinal_expect.get_mut(ordinal as usize) {
            *entry = None;
        }
    }

    #[inline]
    fn reset_child_ordinal(&mut self) {
        self.current_ordinal = 0;
    }
}

// ---------------------------------------------------------------------------
// LocateOnly sink: walk rows, resolve field names, decode nothing.
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::columnar::ColumnBuilder;
    use crate::decoder::{ColumnarSink, RecordParser, Splitter};
    use crate::plan::{CompareOp, ExecutionPlan, FieldType, FilterPredicate};
    use crate::value::Value;
    use crate::Result;
    use arrow::array::{Array, AsArray};

    /// Simple newline-delimited parser for test data.
    /// Each line is a row; fields are `key=value` separated by spaces.
    #[derive(Clone)]
    struct LineParser;

    impl RecordParser for LineParser {
        fn validate(&self, bytes: &[u8]) -> Result<()> {
            simdutf8::basic::from_utf8(bytes)?;
            Ok(())
        }

        fn parse_chunk(&self, bytes: &[u8], sink: &mut dyn ColumnarSink) -> Result<()> {
            let text = std::str::from_utf8(bytes).map_err(|e| crate::Error::Plan(e.to_string()))?;
            for line in text.lines() {
                if line.is_empty() {
                    continue;
                }
                sink.begin_row();
                for token in line.split_whitespace() {
                    if let Some((k, v)) = token.split_once('=') {
                        sink.put_field(k, Value::Str(Cow::Borrowed(v)));
                    }
                }
                sink.end_row();
            }
            Ok(())
        }
    }

    #[derive(Clone)]
    struct LineSplitter;

    impl Splitter for LineSplitter {
        fn next_record_start(&self, bytes: &[u8], from: usize) -> Option<usize> {
            if from >= bytes.len() {
                return None;
            }
            // If we're at a newline, advance past it.
            let start = if bytes[from] == b'\n' { from + 1 } else { from };
            if start >= bytes.len() {
                return None;
            }
            memchr::memchr(b'\n', &bytes[start..]).map(|rel| start + rel + 1)
        }

        fn find_split_points(&self, bytes: &[u8], max_chunks: usize) -> Vec<usize> {
            if max_chunks <= 1 || bytes.is_empty() {
                return vec![0, bytes.len()];
            }
            let mut points = vec![0usize];
            let mut last = 0;
            for (i, &b) in bytes.iter().enumerate() {
                if b == b'\n' {
                    let next = i + 1;
                    if next > last && points.len() < max_chunks {
                        points.push(next);
                        last = next;
                    }
                }
            }
            if *points.last().unwrap() != bytes.len() {
                points.push(bytes.len());
            }
            points
        }

        fn estimate_bytes_per_row(&self, sample: &[u8]) -> usize {
            let newline_count = sample.iter().filter(|&&b| b == b'\n').count().max(1);
            (sample.len() / newline_count).max(1)
        }
    }

    /// Records every hook call into a shared log, in call order.
    #[derive(Default)]
    struct RecObserver {
        events: std::sync::Mutex<Vec<String>>,
    }

    impl RecObserver {
        fn log(&self, e: String) {
            self.events.lock().unwrap().push(e);
        }
        fn events(&self) -> Vec<String> {
            self.events.lock().unwrap().clone()
        }
    }

    impl crate::RowObserver for RecObserver {
        fn on_begin_row(&self, row_index: usize) {
            self.log(format!("begin:{row_index}"));
        }
        fn on_put_field(&self, row_index: usize, name: &str, _slot: usize, _value: &Value<'_>) {
            self.log(format!("put:{row_index}:{name}"));
        }
        fn on_row_accepted(&self, row_index: usize) {
            self.log(format!("accept:{row_index}"));
        }
        fn on_row_rejected(&self, row_index: usize) {
            self.log(format!("reject:{row_index}"));
        }
        fn on_chunk_finished(&self, total: usize, accepted: usize, rejected: usize) {
            self.log(format!("fin:{total}:{accepted}:{rejected}"));
        }
    }

    #[test]
    fn test_observer_lifecycle() {
        let obs = Arc::new(RecObserver::default());
        let mut plan = ExecutionPlan::new();
        plan.observer = Some(obs.clone());
        let mut engine = parse_bytes(b"X=1 Y=2\nX=3 Y=4\n", plan);
        engine.finish().unwrap();
        assert_eq!(
            obs.events(),
            vec![
                "begin:0",
                "put:0:X",
                "put:0:Y",
                "accept:0",
                "begin:1",
                "put:1:X",
                "put:1:Y",
                "accept:1",
                "fin:2:2:0",
                // finish() a second time re-fires with the same counters.
            ]
        );
    }

    #[test]
    fn test_observer_with_filter() {
        let obs = Arc::new(RecObserver::default());
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Equal {
            field: "X".to_string(),
            value: "keep".to_string(),
        });
        plan.observer = Some(obs.clone());
        let mut engine = parse_bytes(b"X=keep A=1\nX=drop A=2\n", plan);
        engine.finish().unwrap();
        let ev = obs.events();
        // Rejected row: begin + reject, but its buffered fields never fire put.
        assert!(ev.contains(&"reject:1".to_string()), "events: {ev:?}");
        assert_eq!(
            ev.iter().filter(|e| e.starts_with("put:")).count(),
            2,
            "only the accepted row's fields may be observed: {ev:?}"
        );
        assert!(ev.contains(&"fin:2:1:1".to_string()), "events: {ev:?}");
    }

    #[test]
    fn test_observer_parallel_counts_all_rows() {
        use std::sync::atomic::{AtomicUsize, Ordering as AOrd};
        #[derive(Default)]
        struct Counting {
            accepted: AtomicUsize,
            rejected: AtomicUsize,
        }
        impl crate::RowObserver for Counting {
            fn on_row_accepted(&self, _i: usize) {
                self.accepted.fetch_add(1, AOrd::Relaxed);
            }
            fn on_row_rejected(&self, _i: usize) {
                self.rejected.fetch_add(1, AOrd::Relaxed);
            }
        }
        let obs = Arc::new(Counting::default());
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::NotEqual {
            field: "X".to_string(),
            value: "drop".to_string(),
        });
        plan.observer = Some(obs.clone());
        let mut data = Vec::new();
        for i in 0..1000 {
            let v = if i % 3 == 0 { "drop" } else { "keep" };
            data.extend_from_slice(format!("X={v} N={i}\n").as_bytes());
        }
        let pipeline = crate::Pipeline::new(LineSplitter, LineParser).with_plan(plan);
        let batches = pipeline.read_bytes_par(&data, 4).unwrap();
        let total: usize = batches.iter().map(|b| b.num_rows()).sum();
        let accepted = obs.accepted.load(AOrd::Relaxed);
        let rejected = obs.rejected.load(AOrd::Relaxed);
        assert_eq!(accepted + rejected, 1000);
        assert_eq!(accepted, total);
        assert_eq!(rejected, 334);
    }

    #[test]
    fn test_not_wraps_leaf_predicates_predicate_first() {
        // Every leaf under Not must invert its result in the predicate-first
        // (buffered) path used when plan.filter is set.
        let cases: Vec<(FilterPredicate, &[u8], Vec<&str>)> = vec![
            (
                FilterPredicate::not(FilterPredicate::Equal {
                    field: "X".into(),
                    value: "keep".into(),
                }),
                b"X=keep\nX=drop\n",
                vec!["drop"],
            ),
            (
                FilterPredicate::not(FilterPredicate::IsNull { field: "X".into() }),
                b"X=1\nY=2\n",
                vec!["1"],
            ),
            (
                FilterPredicate::not(FilterPredicate::StartsWith {
                    field: "X".into(),
                    value: "ab".into(),
                }),
                b"X=abc\nX=zzz\n",
                vec!["zzz"],
            ),
            (
                FilterPredicate::not(FilterPredicate::In {
                    field: "X".into(),
                    values: vec!["a".into(), "b".into()],
                }),
                b"X=a\nX=b\nX=c\n",
                vec!["c"],
            ),
            (
                FilterPredicate::not(FilterPredicate::Regex {
                    field: "X".into(),
                    re: crate::plan::RegexSpec::new("^ERR").unwrap(),
                }),
                b"X=ERR1\nX=ok\n",
                vec!["ok"],
            ),
            (
                FilterPredicate::not(FilterPredicate::Contains {
                    field: "X".into(),
                    value: "zz".into(),
                }),
                b"X=azza\nX=hello\n",
                vec!["hello"],
            ),
        ];
        for (pred, data, want) in cases {
            let mut plan = ExecutionPlan::new();
            plan.filter = Some(pred);
            let engine = parse_bytes(data, plan);
            let col = engine.get_column("X").unwrap();
            assert_eq!(
                col.as_str_vec().iter().flatten().collect::<Vec<_>>(),
                want,
                "data: {}",
                String::from_utf8_lossy(data)
            );
        }
    }

    #[test]
    fn test_not_wraps_leaf_predicates_batch_check() {
        // The batch path (FilterPredicate::check over finished columns) must
        // agree with the predicate-first path for Not-wrapped leaves.
        let data = b"X=keep N=1\nX=drop N=2\nX=keep N=3\n";
        let engine = parse_bytes(data, ExecutionPlan::new());
        let pred = FilterPredicate::not(FilterPredicate::Equal {
            field: "X".into(),
            value: "keep".into(),
        });
        let kept: Vec<usize> = (0..engine.num_rows())
            .filter(|&r| pred.check(&engine.columns, &engine.field_index, r, &engine.plan))
            .collect();
        assert_eq!(kept, vec![1]);

        let pred = FilterPredicate::not(FilterPredicate::IsNull { field: "X".into() });
        let kept: Vec<usize> = (0..engine.num_rows())
            .filter(|&r| pred.check(&engine.columns, &engine.field_index, r, &engine.plan))
            .collect();
        assert_eq!(kept, vec![0, 1, 2]);

        let pred = FilterPredicate::not(FilterPredicate::Regex {
            field: "X".into(),
            re: crate::plan::RegexSpec::new("ke*p").unwrap(),
        });
        let kept: Vec<usize> = (0..engine.num_rows())
            .filter(|&r| pred.check(&engine.columns, &engine.field_index, r, &engine.plan))
            .collect();
        assert_eq!(kept, vec![1]);
    }

    #[test]
    fn test_regex_predicate() {
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Regex {
            field: "X".into(),
            re: crate::plan::RegexSpec::new("^ERR\\d+$").unwrap(),
        });
        let engine = parse_bytes(b"X=ERR12\nX=ok\nX=ERRx\nX=ERR0\n", plan);
        let col = engine.get_column("X").unwrap();
        assert_eq!(
            col.as_str_vec().iter().flatten().collect::<Vec<_>>(),
            vec!["ERR12", "ERR0"]
        );
        // Missing field never matches.
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Regex {
            field: "X".into(),
            re: crate::plan::RegexSpec::new(".*").unwrap(),
        });
        let engine = parse_bytes(b"X=a\nY=2\n", plan);
        assert_eq!(engine.num_rows(), 1);
        // Invalid pattern is rejected at construction.
        assert!(crate::plan::RegexSpec::new("(").is_err());
        // Equality follows the pattern string.
        assert_eq!(
            crate::plan::RegexSpec::new("^a").unwrap(),
            crate::plan::RegexSpec::new("^a").unwrap()
        );
        assert_ne!(
            crate::plan::RegexSpec::new("^a").unwrap(),
            crate::plan::RegexSpec::new("^b").unwrap()
        );
    }

    #[test]
    fn test_no_observer_smoke() {
        // plan.observer = None: hooks compile to a skipped branch.
        let engine = parse_bytes(b"X=1\nX=2\n", ExecutionPlan::new());
        assert_eq!(engine.num_rows(), 2);
    }

    fn parse_bytes(bytes: &[u8], plan: ExecutionPlan) -> TableBuilder {
        let mut sink = TableBuilder::with_plan((bytes.len() / 16).max(4), Arc::new(plan));
        LineParser.parse_chunk(bytes, &mut sink).unwrap();
        sink
    }

    #[test]
    fn test_extend_no_duplicates() {
        let e1 = parse_bytes(b"A=1 B=2\n", ExecutionPlan::new());
        let mut merged = TableBuilder::new();
        merged.extend(e1).unwrap();
        assert_eq!(merged.num_rows(), 1);
        for col in &merged.columns {
            assert_eq!(col.len(), merged.num_rows(), "column length mismatch");
        }
    }

    #[test]
    fn test_multi_chunk_same_as_single() {
        let data = b"A=1\nA=2\nA=3\n";
        let single = parse_bytes(data, ExecutionPlan::new());
        assert_eq!(single.num_rows(), 3);

        let splitter = LineSplitter;
        let points = splitter.find_split_points(data, 2);
        let mut merged = TableBuilder::new();
        for w in points.windows(2) {
            let chunk = &data[w[0]..w[1]];
            let engine = parse_bytes(chunk, ExecutionPlan::new());
            merged.extend(engine).unwrap();
        }
        assert_eq!(merged.num_rows(), single.num_rows());
    }

    #[test]
    fn test_last_write_wins_duplicate_field() {
        let engine = parse_bytes(b"X=10 X=20\n", ExecutionPlan::new());
        assert_eq!(engine.num_rows(), 1);
        let col = engine.get_column("X").unwrap();
        assert_eq!(col.as_str_vec(), vec![Some("20".into())]);
    }

    #[test]
    fn test_build_plan_rename() {
        let mut plan = ExecutionPlan::new();
        plan.field_map.insert("X".to_string(), "Y".to_string());
        let engine = parse_bytes(b"X=hello\n", plan);
        assert_eq!(engine.num_rows(), 1);
        assert!(engine.get_column("Y").is_some());
        assert!(engine.get_column("X").is_none());
        assert_eq!(
            engine.get_column("Y").unwrap().as_str_vec(),
            vec![Some("hello".into())]
        );
    }

    #[test]
    fn test_build_plan_drop() {
        let mut plan = ExecutionPlan::new();
        plan.drop_fields.insert("X".to_string());
        let engine = parse_bytes(b"X=hello Y=world\n", plan);
        assert_eq!(engine.num_rows(), 1);
        assert!(engine.get_column("X").is_none());
        assert!(engine.get_column("Y").is_some());
    }

    #[test]
    fn test_build_plan_filter_ne() {
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::NotEqual {
            field: "X".to_string(),
            value: "42".to_string(),
        });
        let engine = parse_bytes(b"X=10\nX=42\nX=30\n", plan);
        assert_eq!(engine.num_rows(), 2);
        let col = engine.get_column("X").unwrap();
        assert_eq!(col.as_str_vec(), vec![Some("10".into()), Some("30".into())]);
    }

    #[test]
    fn test_build_plan_filter_eq() {
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Equal {
            field: "X".to_string(),
            value: "10".to_string(),
        });
        let engine = parse_bytes(b"X=10\nX=20\nX=10\n", plan);
        assert_eq!(engine.num_rows(), 2);
        let col = engine.get_column("X").unwrap();
        assert_eq!(col.as_str_vec(), vec![Some("10".into()), Some("10".into())]);
    }

    #[test]
    fn test_build_plan_filter_missing_field() {
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::NotEqual {
            field: "X".to_string(),
            value: "10".to_string(),
        });
        let engine = parse_bytes(b"X=10\nY=99\n", plan);
        assert_eq!(engine.num_rows(), 1);
        let col = engine.get_column("Y").unwrap();
        assert_eq!(col.as_str_vec(), vec![Some("99".into())]);
    }

    #[test]
    fn test_typed_int64_column() {
        let mut plan = ExecutionPlan::new();
        plan.field_types.insert("X".to_string(), FieldType::Int64);
        let engine = parse_bytes(b"X=42\nX=bad\nX=100\n", plan);
        assert_eq!(engine.num_rows(), 3);
        if let ColumnBuilder::Int64(v) = engine.get_column("X").unwrap() {
            assert_eq!(v.get(0), Some(42));
            assert_eq!(v.get(1), None);
            assert_eq!(v.get(2), Some(100));
        } else {
            panic!("expected Int64 builder");
        }
    }

    #[test]
    fn test_typed_float64_column() {
        let mut plan = ExecutionPlan::new();
        plan.field_types.insert("X".to_string(), FieldType::Float64);
        let engine = parse_bytes(b"X=1.5\n", plan);
        if let ColumnBuilder::Float64(v) = engine.get_column("X").unwrap() {
            assert!((v.get(0).unwrap() - 1.5).abs() < 1e-9);
        } else {
            panic!("expected Float64 builder");
        }
    }

    #[test]
    fn test_is_null_filter() {
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::IsNull {
            field: "X".to_string(),
        });
        let engine = parse_bytes(b"X=hello\nY=world\nX=fallback\n", plan);
        assert_eq!(engine.num_rows(), 1);
        let col = engine.get_column("Y").unwrap();
        assert_eq!(col.as_str_vec(), vec![Some("world".into())]);
    }

    #[test]
    fn test_not_is_null_filter_predicate_first() {
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::not(FilterPredicate::IsNull {
            field: "X".to_string(),
        }));
        let engine = parse_bytes(b"X=a\nY=only\nX=b\n", plan);
        assert_eq!(engine.num_rows(), 2);
        let col = engine.get_column("X").unwrap();
        assert_eq!(col.as_str_vec(), vec![Some("a".into()), Some("b".into())]);
    }

    #[test]
    fn test_not_is_null_filter_batch_eval() {
        // Force the late-predicate path (direct push + pop-on-reject at
        // end_row, evaluated via FilterPredicate::check in plan.rs).
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::not(FilterPredicate::IsNull {
            field: "X".to_string(),
        }));
        let mut sink = TableBuilder::with_plan(4, Arc::new(plan));
        sink.row_buf.as_mut().unwrap().buffer_worthwhile = false;
        LineParser
            .parse_chunk(b"X=a\nY=only\nX=b\n", &mut sink)
            .unwrap();
        assert_eq!(sink.num_rows(), 2);
        let col = sink.get_column("X").unwrap();
        assert_eq!(col.as_str_vec(), vec![Some("a".into()), Some("b".into())]);
    }

    #[test]
    fn test_strict_types_errors_on_malformed_int64() {
        let mut plan = ExecutionPlan::new();
        plan.field_types.insert("X".to_string(), FieldType::Int64);
        plan.strict_types = true;
        let mut engine = parse_bytes(b"X=42\nX=abc\n", plan);
        let err = engine.finish().unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("\"abc\""), "message should name value: {msg}");
        assert!(msg.contains("\"X\""), "message should name column: {msg}");
        assert!(msg.contains("Int64"), "message should name type: {msg}");
        assert!(msg.contains("row 1"), "message should name row: {msg}");
    }

    #[test]
    fn test_strict_types_off_yields_null() {
        let mut plan = ExecutionPlan::new();
        plan.field_types.insert("X".to_string(), FieldType::Int64);
        let engine = parse_bytes(b"X=42\nX=abc\n", plan);
        assert!(engine.strict_error.is_none());
        if let ColumnBuilder::Int64(v) = engine.get_column("X").unwrap() {
            assert_eq!(v.get(0), Some(42));
            assert_eq!(v.get(1), None);
        } else {
            panic!("expected Int64 builder");
        }
    }

    #[test]
    fn test_strict_types_missing_field_stays_null() {
        let mut plan = ExecutionPlan::new();
        plan.field_types.insert("X".to_string(), FieldType::Int64);
        plan.strict_types = true;
        let mut engine = parse_bytes(b"X=42\nY=1\n", plan);
        let batch = engine.finish().unwrap();
        let idx = batch.schema().index_of("X").unwrap();
        let arr = batch
            .column(idx)
            .as_primitive::<arrow::datatypes::Int64Type>();
        assert_eq!(arr.value(0), 42);
        assert!(arr.is_null(1));
    }

    #[test]
    fn test_strict_types_buffered_filter_path() {
        // With a filter, values travel through the predicate row buffer; the
        // strict check must fire there too.
        let mut plan = ExecutionPlan::new();
        plan.field_types.insert("X".to_string(), FieldType::Int64);
        plan.strict_types = true;
        plan.filter = Some(FilterPredicate::Equal {
            field: "Y".to_string(),
            value: "1".to_string(),
        });
        let mut engine = parse_bytes(b"Y=1 X=abc\n", plan);
        let err = engine.finish().unwrap_err();
        assert!(err.to_string().contains("strict_types"));
    }

    #[test]
    fn test_is_type_filter_int64() {
        let mut plan = ExecutionPlan::new();
        plan.field_types.insert("X".to_string(), FieldType::Int64);
        plan.filter = Some(FilterPredicate::IsType {
            field: "X".to_string(),
            field_type: FieldType::Int64,
        });
        let engine = parse_bytes(b"X=42\nX=bad\nX=100\n", plan);
        assert_eq!(engine.num_rows(), 2);
        if let ColumnBuilder::Int64(v) = engine.get_column("X").unwrap() {
            assert_eq!(v.get(0), Some(42));
            assert_eq!(v.get(1), Some(100));
        } else {
            panic!("expected Int64 builder");
        }
    }

    #[test]
    fn test_is_type_filter_float64() {
        let mut plan = ExecutionPlan::new();
        plan.field_types.insert("X".to_string(), FieldType::Float64);
        plan.filter = Some(FilterPredicate::IsType {
            field: "X".to_string(),
            field_type: FieldType::Float64,
        });
        let engine = parse_bytes(b"X=1.5\nX=bad\nX=2.5\n", plan);
        assert_eq!(engine.num_rows(), 2);
        if let ColumnBuilder::Float64(v) = engine.get_column("X").unwrap() {
            assert!((v.get(0).unwrap() - 1.5).abs() < 1e-9);
            assert!((v.get(1).unwrap() - 2.5).abs() < 1e-9);
        } else {
            panic!("expected Float64 builder");
        }
    }

    #[test]
    fn test_dictionary_column() {
        let mut plan = ExecutionPlan::new();
        plan.dictionary_columns.insert("P".to_string());
        let engine = parse_bytes(b"P=Widget\nP=Gadget\nP=Widget\n", plan);
        assert_eq!(engine.num_rows(), 3);
        if let ColumnBuilder::Dictionary { codes, offsets, .. } = engine.get_column("P").unwrap() {
            let dict_len = offsets.len() - 1;
            assert_eq!(dict_len, 2);
            assert_eq!(
                codes.iter().map(|o| o.copied()).collect::<Vec<_>>(),
                vec![Some(0), Some(1), Some(0)]
            );
        } else {
            panic!("expected Dictionary builder");
        }
    }

    #[test]
    fn test_ragged_late_chunk_column_debut() {
        let e1 = parse_bytes(b"A=1 B=2\nA=3\n", ExecutionPlan::new());
        let e2 = parse_bytes(b"B=4 C=5\n", ExecutionPlan::new());
        let mut merged = TableBuilder::new();
        merged.extend(e1).unwrap();
        merged.extend(e2).unwrap();

        assert_eq!(
            merged.get_column("A").unwrap().as_str_vec(),
            vec![Some("1".into()), Some("3".into()), None]
        );
        assert_eq!(
            merged.get_column("B").unwrap().as_str_vec(),
            vec![Some("2".into()), None, Some("4".into())]
        );
        assert_eq!(
            merged.get_column("C").unwrap().as_str_vec(),
            vec![None, None, Some("5".into())]
        );
    }

    #[test]
    fn test_auto_dict_upgrade_only_post_merge() {
        let mut plan = ExecutionPlan::new();
        plan.auto_dict = true;
        let a = parse_bytes(b"P=x\nP=y\n", plan.clone());
        let b = parse_bytes(b"P=x\nP=y\n", plan.clone());
        let mut merged = TableBuilder::with_plan(64, Arc::new(plan));
        merged.extend(a).unwrap();
        merged.extend(b).unwrap();
        merged.auto_dict_upgrade();
        assert_eq!(merged.num_rows(), 4);
    }

    #[test]
    fn test_extend_string_dictionary_promotes_not_panics() {
        let mut e1 = parse_bytes(b"P=x\n", ExecutionPlan::new());
        let mut plan = ExecutionPlan::new();
        plan.dictionary_columns.insert("P".to_string());
        let e2 = parse_bytes(b"P=x\n", plan);
        // Safe promotion: string + dictionary reconcile to dictionary.
        e1.extend(e2).expect("String/Dictionary must reconcile");
        assert!(matches!(
            e1.get_column("P").unwrap(),
            crate::columnar::ColumnBuilder::Dictionary { .. }
        ));
    }

    #[test]
    fn test_extend_irreconcilable_variants_error_not_panic() {
        let mut e1 = parse_bytes(b"S=x\n", ExecutionPlan::new());
        let mut plan = ExecutionPlan::new();
        plan.field_types.insert("S".to_string(), FieldType::Int64);
        let e2 = parse_bytes(b"S=7\n", plan);
        let result = e1.extend(e2);
        match result {
            Err(crate::Error::Merge(msg)) => {
                assert!(msg.contains("'S'"), "error should name the column: {msg}");
            }
            other => panic!("String/Int64 mismatch must return Merge error, got {other:?}"),
        }
    }

    #[test]
    fn test_compare_filter_via_arrow_compute() {
        use crate::arrow_export::apply_compare_filter;

        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Compare {
            field_a: "A".to_string(),
            op: CompareOp::Gt,
            field_b: "B".to_string(),
        });
        let mut engine = parse_bytes(b"A=3 B=1\nA=2 B=2\nA=5 B=4\n", plan);
        let batch = engine.finish().unwrap();
        let filtered = apply_compare_filter(
            batch,
            &FilterPredicate::Compare {
                field_a: "A".to_string(),
                op: CompareOp::Gt,
                field_b: "B".to_string(),
            },
        )
        .unwrap();
        assert_eq!(filtered.num_rows(), 2);
        let a = filtered.column_by_name("A").unwrap().as_string::<i32>();
        assert_eq!(a.value(0), "3");
        assert_eq!(a.value(1), "5");
    }

    #[test]
    fn test_row_dirty_is_full_edge_cases() {
        // Directly test the is_full logic for ncols = 1,63,64,65,127,128,129
        // We do this via TableBuilder with varying column counts
        for ncols in [1, 63, 64, 65, 127, 128, 129] {
            let mut tb = TableBuilder::new();
            for i in 0..ncols {
                let name = format!("col{i}");
                tb.field_index.insert(name.clone(), i);
                tb.columns.push(crate::columnar::ColumnBuilder::String(
                    crate::columnar::StrColumn::default(),
                ));
                tb.column_order.push(name);
            }
            // row_dirty should be vec![0; (ncols+63)/64]
            tb.row_dirty = vec![0; ncols.div_ceil(64)];
            // Test is_full when all bits set
            for i in 0..ncols {
                let word = i / 64;
                let bit = i % 64;
                tb.row_dirty[word] |= 1u64 << bit;
            }
            let full_words = ncols / 64;
            let rem = ncols % 64;
            let is_full = (0..full_words).all(|w| tb.row_dirty[w] == u64::MAX)
                && (rem == 0
                    || tb.row_dirty.get(full_words).copied().unwrap_or(0) == (1u64 << rem) - 1);
            assert!(
                is_full,
                "ncols={ncols} should be full, row_dirty={:?}",
                tb.row_dirty
            );
            // Clear one bit and check not full
            if ncols > 0 {
                let word = (ncols - 1) / 64;
                let bit = (ncols - 1) % 64;
                tb.row_dirty[word] &= !(1u64 << bit);
                let is_full2 = (0..full_words).all(|w| tb.row_dirty[w] == u64::MAX)
                    && (rem == 0
                        || tb.row_dirty.get(full_words).copied().unwrap_or(0) == (1u64 << rem) - 1);
                assert!(
                    !is_full2,
                    "ncols={ncols} should not be full after clearing one bit"
                );
            }
        }
    }

    #[test]
    fn test_finish_twice_does_not_panic() {
        // L7: zero-copy export (mem::take) leaves builders empty. Calling
        // finish() twice should return an empty batch, not panic.
        let mut tb = parse_bytes(b"A=1 B=2\nA=3 B=4\n", ExecutionPlan::new());
        let batch1 = tb.finish().unwrap();
        assert_eq!(batch1.num_rows(), 2);
        // Second call: columns are empty after mem::take.
        let batch2 = tb.finish().unwrap();
        assert_eq!(batch2.num_rows(), 0);
    }

    #[test]
    fn test_c2_compound_reorder() {
        // L7: C2 reorder: Field2 == x AND Field1 == y must give the same
        // result as Field1 == y AND Field2 == x.
        let data = b"A=1 B=2\nA=2 B=2\nA=1 B=3\nA=2 B=3\n";
        let make_filter = |a: &str, va: &str, b: &str, vb: &str| -> ExecutionPlan {
            let mut plan = ExecutionPlan::new();
            plan.filter = Some(FilterPredicate::And(
                Box::new(FilterPredicate::Equal {
                    field: a.to_string(),
                    value: va.to_string(),
                }),
                Box::new(FilterPredicate::Equal {
                    field: b.to_string(),
                    value: vb.to_string(),
                }),
            ));
            plan
        };
        let r1 = parse_bytes(data, make_filter("A", "1", "B", "2"));
        let r2 = parse_bytes(data, make_filter("B", "2", "A", "1"));
        assert_eq!(
            r1.num_rows(),
            r2.num_rows(),
            "C2 reorder must produce identical results"
        );
        assert_eq!(r1.num_rows(), 1); // A=1 B=2
    }

    #[test]
    fn test_c2_or_reorder() {
        // L7: Or reorder: same result regardless of operand order.
        // Row 1: A=1 B=2 → A==1 → Pass
        // Row 2: A=2 B=2 → A!=1, B!=3 → Fail
        // Row 3: A=3 B=3 → B==3 → Pass
        let data = b"A=1 B=2\nA=2 B=2\nA=3 B=3\n";
        let make_filter = |a: &str, va: &str, b: &str, vb: &str| -> ExecutionPlan {
            let mut plan = ExecutionPlan::new();
            plan.filter = Some(FilterPredicate::Or(
                Box::new(FilterPredicate::Equal {
                    field: a.to_string(),
                    value: va.to_string(),
                }),
                Box::new(FilterPredicate::Equal {
                    field: b.to_string(),
                    value: vb.to_string(),
                }),
            ));
            plan
        };
        let r1 = parse_bytes(data, make_filter("A", "1", "B", "3"));
        let r2 = parse_bytes(data, make_filter("B", "3", "A", "1"));
        assert_eq!(
            r1.num_rows(),
            r2.num_rows(),
            "Or reorder must produce identical results"
        );
        assert_eq!(r1.num_rows(), 2); // rows 1 and 3
    }

    #[test]
    fn test_predicate_slot_created_after_mask_build() {
        // Regression: when the predicate column appears AFTER other columns
        // in document order, build_predicate_mask runs before the predicate
        // column exists in field_index, so its bit is never set. The old
        // early-return optimization prevented it from being added later.
        //
        // Data: A comes first, B is the predicate column (comes second).
        // Filter: B == "reject" → all rows should be rejected.
        let data = b"A=1 B=ok\nA=2 B=ok\nA=3 B=ok\n";
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Equal {
            field: "B".to_string(),
            value: "reject".to_string(),
        });
        let engine = parse_bytes(data, plan);
        assert_eq!(
            engine.num_rows(),
            0,
            "all rows should be rejected (B != reject)"
        );

        // Positive case: some rows pass
        let data2 = b"A=1 B=ok\nA=2 B=reject\nA=3 B=ok\n";
        let mut plan2 = ExecutionPlan::new();
        plan2.filter = Some(FilterPredicate::Equal {
            field: "B".to_string(),
            value: "ok".to_string(),
        });
        let engine2 = parse_bytes(data2, plan2);
        assert_eq!(engine2.num_rows(), 2, "rows 1 and 3 pass (B == ok)");
        let col = engine2.get_column("A").unwrap();
        assert_eq!(col.as_str_vec(), vec![Some("1".into()), Some("3".into())]);
    }

    #[test]
    fn test_predicate_first_via_resolve_and_put() {
        // Uses resolve_and_put (scanner path) instead of put_field (LineParser path)
        // to verify the predicate machinery works through the scanner's code path.
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Equal {
            field: "B".to_string(),
            value: "reject".to_string(),
        });
        let mut tb = TableBuilder::with_plan(16, Arc::new(plan));
        // Row 1: B=ok → should pass
        tb.begin_row();
        tb.resolve_and_put("A", Value::Str(Cow::Borrowed("1")));
        tb.resolve_and_put("B", Value::Str(Cow::Borrowed("ok")));
        tb.end_row();
        // Row 2: B=reject → should fail
        tb.begin_row();
        tb.resolve_and_put("A", Value::Str(Cow::Borrowed("2")));
        tb.resolve_and_put("B", Value::Str(Cow::Borrowed("reject")));
        tb.end_row();
        // Row 3: B=ok → should pass
        tb.begin_row();
        tb.resolve_and_put("A", Value::Str(Cow::Borrowed("3")));
        tb.resolve_and_put("B", Value::Str(Cow::Borrowed("ok")));
        tb.end_row();
        let batch = tb.finish().unwrap();
        assert_eq!(batch.num_rows(), 1, "only row 2 (B==reject) should pass");
    }

    #[test]
    fn test_owned_cow_values_survive_buffered_filter() {
        // Regression for the use-after-free behind this change: Value::Str
        // used to be `&'a str`, and the buffered filtered path transmutes
        // `Value<'a>` to `Value<'static>` to hold values until the predicate
        // is decided. Adapters that unescape entities produce owned Strings;
        // the owned buffer was dropped at the end of the scan function and
        // the transmuted reference dangled, so heap reuse corrupted accepted
        // rows after enough rejections. With `Str(Cow<'a, str>)` the owned
        // buffer moves into the row buffer.
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Equal {
            field: "B".to_string(),
            value: "ok".to_string(),
        });
        let mut tb = TableBuilder::with_plan(16, Arc::new(plan));
        for i in 0..50 {
            tb.begin_row();
            // Owned values, as produced by entity unescaping in an adapter.
            let a = Cow::Owned(format!("value-{i}-unescaped"));
            let b = Cow::Owned(if i % 2 == 0 {
                "ok".to_string()
            } else {
                "no".to_string()
            });
            tb.resolve_and_put("A", Value::Str(a));
            tb.resolve_and_put("B", Value::Str(b));
            tb.end_row();
        }
        assert_eq!(tb.num_rows(), 25, "even rows pass (B == ok)");
        let col = tb.get_column("A").unwrap();
        let vals = col.as_str_vec();
        assert_eq!(vals.len(), 25);
        assert_eq!(vals[0], Some("value-0-unescaped".to_string()));
        assert_eq!(vals[24], Some("value-48-unescaped".to_string()));
    }

    #[test]
    fn test_predicate_first_skip_via_resolve_and_put() {
        // Test the skip path: predicate on first field, all rows rejected.
        // This exercises the mark_predicate_slot + row_rejected + end_row path
        // that the scanner uses via resolve_and_put.
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Equal {
            field: "A".to_string(),
            value: "999".to_string(),
        });
        let mut tb = TableBuilder::with_plan(16, Arc::new(plan));
        for _i in 0..100 {
            tb.begin_row();
            tb.resolve_and_put("A", Value::Str(Cow::Borrowed("0")));
            tb.resolve_and_put("B", Value::Str(Cow::Borrowed("x")));
            tb.resolve_and_put("C", Value::Str(Cow::Borrowed("y")));
            tb.end_row();
        }
        let batch = tb.finish().unwrap();
        assert_eq!(
            batch.num_rows(),
            0,
            "all rows should be rejected (A=0 != 999)"
        );
    }

    #[test]
    fn test_sparse_column_predicate_skip() {
        // Regression test for ncols gate: sparse column appears only after
        // row 50, predicate on early field (A). The adaptive strategy must
        // not disable buffering because ncols is computed from the incomplete
        // column set before the sparse column appears.
        //
        // Data: 100 rows. Rows 1-50 have A, B, C. Rows 51-100 also have D.
        // Filter: A == "reject" → all rows rejected.
        // The skip must fire for all rows, not just the first few.
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Equal {
            field: "A".to_string(),
            value: "reject".to_string(),
        });
        let mut tb = TableBuilder::with_plan(128, Arc::new(plan));
        for i in 0..100 {
            tb.begin_row();
            tb.resolve_and_put("A", Value::Str(Cow::Borrowed("ok")));
            tb.resolve_and_put("B", Value::Str(Cow::Borrowed("x")));
            tb.resolve_and_put("C", Value::Str(Cow::Borrowed("y")));
            if i >= 50 {
                tb.resolve_and_put("D", Value::Str(Cow::Borrowed("z")));
            }
            tb.end_row();
        }
        let batch = tb.finish().unwrap();
        assert_eq!(batch.num_rows(), 0, "all rows rejected (A=ok != reject)");
    }

    #[test]
    fn test_sparse_column_predicate_pass() {
        // Like above, but predicate passes. The sparse column D should appear
        // only for rows 51-100; rows 1-50 should have D = null.
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Equal {
            field: "A".to_string(),
            value: "ok".to_string(),
        });
        let mut tb = TableBuilder::with_plan(128, Arc::new(plan));
        for _i in 0..100 {
            tb.begin_row();
            tb.resolve_and_put("A", Value::Str(Cow::Borrowed("ok")));
            tb.resolve_and_put("B", Value::Str(Cow::Borrowed("x")));
            tb.resolve_and_put("C", Value::Str(Cow::Borrowed("y")));
            if _i >= 50 {
                tb.resolve_and_put("D", Value::Str(Cow::Borrowed("z")));
            }
            tb.end_row();
        }
        let batch = tb.finish().unwrap();
        assert_eq!(batch.num_rows(), 100, "all rows pass (A=ok == ok)");
        // D column: null for first 50, "z" for last 50
        if let Some(col) = batch.column_by_name("D") {
            let arr = col.as_string::<i32>();
            for i in 0..50 {
                assert!(arr.is_null(i), "row {} should have D=null", i);
            }
            for i in 50..100 {
                assert!(
                    !arr.is_null(i),
                    "row {} should not be null (D len={}, total rows={})",
                    i,
                    arr.len(),
                    batch.num_rows()
                );
                assert_eq!(arr.value(i), "z", "rows 50+ should have D=z");
            }
        } else {
            panic!("D column should exist");
        }
    }

    #[test]
    fn test_sparse_late_predicate_ordinal() {
        // Regression: predicate on column E that only appears after row 30.
        // ncols gate must use schema/column count that includes E, not just
        // the columns seen so far.
        let mut plan = ExecutionPlan::new();
        plan.filter = Some(FilterPredicate::Equal {
            field: "E".to_string(),
            value: "999".to_string(),
        });
        let mut tb = TableBuilder::with_plan(128, Arc::new(plan));
        // First 30 rows: only A, B
        for _i in 0..30 {
            tb.begin_row();
            tb.resolve_and_put("A", Value::Str(Cow::Borrowed("x")));
            tb.resolve_and_put("B", Value::Str(Cow::Borrowed("y")));
            tb.end_row();
        }
        // Rows 31-100: A, B, C, D, E
        for _i in 30..100 {
            tb.begin_row();
            tb.resolve_and_put("A", Value::Str(Cow::Borrowed("x")));
            tb.resolve_and_put("B", Value::Str(Cow::Borrowed("y")));
            tb.resolve_and_put("C", Value::Str(Cow::Borrowed("c")));
            tb.resolve_and_put("D", Value::Str(Cow::Borrowed("d")));
            tb.resolve_and_put("E", Value::Str(Cow::Borrowed("e")));
            tb.end_row();
        }
        let batch = tb.finish().unwrap();
        // E="e" != "999" → all rows rejected
        assert_eq!(batch.num_rows(), 0, "all rows rejected (E=\"e\" != 999)");
    }

    #[test]
    fn raw_name_helpers_apply_rename_and_drop() {
        use crate::decoder::ColumnarSink;

        let plan = ExecutionPlan::new()
            .rename("raw", "renamed")
            .drop("ignored");
        let mut tb = TableBuilder::with_plan(2, Arc::new(plan));
        tb.begin_row();
        tb.resolve_and_put_raw(b"raw", Value::Str(Cow::Borrowed("value")));
        tb.resolve_and_put_raw(b"ignored", Value::Str(Cow::Borrowed("not stored")));
        tb.put_row(&[("other", Value::Str(Cow::Borrowed("also stored")))]);
        tb.end_row();

        assert_eq!(tb.column_names(), &["renamed", "other"]);
        assert_eq!(tb.resolve_raw(b"raw"), Some("renamed"));
    }

    // -----------------------------------------------------------------------
    // Schema projection semantics: schema=[...] declares exactly which
    // columns are extracted, in order.  Unlisted fields are skipped during
    // parsing (wants()/resolve() reject them); listed columns absent from
    // the data are null-filled.
    // -----------------------------------------------------------------------

    /// Parser that mimics adapter projection behavior (e.g. crxml's scanner):
    /// skips fields the sink rejects via `resolve()` and byte-jumps to the
    /// end of the row once `row_satisfied()` reports all wanted columns seen.
    struct SkippingParser;

    impl RecordParser for SkippingParser {
        fn validate(&self, bytes: &[u8]) -> Result<()> {
            simdutf8::basic::from_utf8(bytes)?;
            Ok(())
        }

        fn parse_chunk(&self, bytes: &[u8], sink: &mut dyn ColumnarSink) -> Result<()> {
            let text = std::str::from_utf8(bytes).map_err(|e| crate::Error::Plan(e.to_string()))?;
            for line in text.lines() {
                if line.is_empty() {
                    continue;
                }
                sink.begin_row();
                for token in line.split_whitespace() {
                    if sink.row_satisfied() {
                        break; // byte-jump to row close: remaining fields skipped
                    }
                    if let Some((k, v)) = token.split_once('=') {
                        if sink.resolve(k).is_some() {
                            sink.resolve_and_put(k, Value::Str(Cow::Borrowed(v)));
                        }
                    }
                }
                sink.end_row();
            }
            Ok(())
        }
    }

    fn parse_skipping(bytes: &[u8], plan: ExecutionPlan) -> TableBuilder {
        let mut sink = TableBuilder::with_plan((bytes.len() / 16).max(4), Arc::new(plan));
        SkippingParser.parse_chunk(bytes, &mut sink).unwrap();
        sink
    }

    fn batch_names(tb: &mut TableBuilder) -> Vec<String> {
        tb.finish()
            .unwrap()
            .schema()
            .fields()
            .iter()
            .map(|f| f.name().clone())
            .collect()
    }

    const REPORT: &[u8] = b"Name=n1 Department=d1 Amount=1 Status=s1 Date=2024\n\
                            Name=n2 Department=d2 Amount=2 Status=s2 Date=2024\n";

    #[test]
    fn schema_projection_subset() {
        // schema=["Name","Department"] must yield exactly those two columns,
        // in that order.  Regression: the old wanted_mask was derived from
        // field_index mid-row, so row_satisfied fired after "Name" on row 1
        // and "Department" was never materialized (output was ["Name"]).
        let mut tb = parse_skipping(
            REPORT,
            ExecutionPlan::new().schema_order(["Name", "Department"]),
        );
        assert_eq!(batch_names(&mut tb), vec!["Name", "Department"]);
    }

    #[test]
    fn schema_projection_single_non_first_column() {
        // Regression: the old code emitted ["Department", "Name"] here —
        // "Name" was materialized because resolve_field did no projection.
        let mut tb = parse_skipping(REPORT, ExecutionPlan::new().schema_order(["Department"]));
        assert_eq!(batch_names(&mut tb), vec!["Department"]);
    }

    #[test]
    fn schema_projection_full_natural_order() {
        let mut tb = parse_skipping(
            REPORT,
            ExecutionPlan::new().schema_order(["Name", "Department", "Amount", "Status", "Date"]),
        );
        assert_eq!(
            batch_names(&mut tb),
            vec!["Name", "Department", "Amount", "Status", "Date"]
        );
    }

    #[test]
    fn schema_projection_reversed_order() {
        let mut tb = parse_skipping(
            REPORT,
            ExecutionPlan::new().schema_order(["Date", "Status", "Amount", "Department", "Name"]),
        );
        assert_eq!(
            batch_names(&mut tb),
            vec!["Date", "Status", "Amount", "Department", "Name"]
        );
    }

    #[test]
    fn schema_projection_absent_column_null_filled() {
        // Schema is a superset of the data: the absent column is null-filled.
        let mut tb = parse_skipping(
            REPORT,
            ExecutionPlan::new().schema_order(["Name", "Missing"]),
        );
        let batch = tb.finish().unwrap();
        assert_eq!(batch.num_rows(), 2);
        let missing = batch.column_by_name("Missing").unwrap().as_string::<i32>();
        assert!(missing.is_null(0) && missing.is_null(1));
        let name = batch.column_by_name("Name").unwrap().as_string::<i32>();
        assert_eq!(name.value(0), "n1");
    }

    #[test]
    fn schema_projection_wants_rejects_unlisted_fields() {
        // The perf contract: unlisted fields are rejected by wants()/resolve()
        // so adapters skip extracting them entirely.
        let plan = ExecutionPlan::new().schema_order(["Name"]);
        let tb = TableBuilder::with_plan(4, Arc::new(plan));
        assert!(tb.wants("Name"));
        assert!(!tb.wants("Department"));
        assert_eq!(tb.resolve("Amount"), None);
    }

    #[test]
    fn schema_projection_rename_then_match() {
        // field_mapping applies before schema matching: the schema lists the
        // renamed (output) column name.
        let plan = ExecutionPlan::new()
            .rename("Name", "Employee")
            .schema_order(["Employee", "Amount"]);
        let mut tb = parse_skipping(REPORT, plan);
        assert_eq!(batch_names(&mut tb), vec!["Employee", "Amount"]);
    }

    #[test]
    fn schema_projection_field_types_apply() {
        let plan = ExecutionPlan::new()
            .type_as("Amount", FieldType::Int64)
            .schema_order(["Name", "Amount"]);
        let mut tb = parse_skipping(REPORT, plan);
        let batch = tb.finish().unwrap();
        let amount = batch.column_by_name("Amount").unwrap();
        assert!(matches!(
            amount.data_type(),
            arrow::datatypes::DataType::Int64
        ));
        assert_eq!(
            amount
                .as_primitive::<arrow::datatypes::Int64Type>()
                .value(1),
            2
        );
    }

    #[test]
    fn schema_projection_filter_on_unlisted_field() {
        // Filter fields are materialized for predicate evaluation even when
        // not in the schema, but are projected out of the final batch.
        let plan = ExecutionPlan::new()
            .schema_order(["Name"])
            .filter_eq("Status", "s2");
        let mut tb = parse_skipping(REPORT, plan);
        let batch = tb.finish().unwrap();
        assert_eq!(batch.num_rows(), 1);
        assert_eq!(batch.schema().fields().len(), 1);
        let name = batch.column_by_name("Name").unwrap().as_string::<i32>();
        assert_eq!(name.value(0), "n2");
    }

    #[test]
    fn schema_projection_drop_wins_over_schema() {
        // A column listed in both schema and drop_fields is dropped:
        // dropping is an explicit exclusion and would otherwise be
        // resurrected as a null-filled column.
        let plan = ExecutionPlan::new()
            .schema_order(["Name", "Department"])
            .drop("Department");
        let mut tb = parse_skipping(REPORT, plan);
        assert_eq!(batch_names(&mut tb), vec!["Name"]);
    }

    #[test]
    fn schema_projection_no_parser_cooperation() {
        // Even when the adapter pushes every field (no wants/resolve checks),
        // the projection still holds: unlisted fields are never materialized.
        let mut tb = parse_bytes(
            REPORT,
            ExecutionPlan::new().schema_order(["Department", "Name"]),
        );
        let batch = tb.finish().unwrap();
        let names: Vec<String> = batch
            .schema()
            .fields()
            .iter()
            .map(|f| f.name().clone())
            .collect();
        assert_eq!(names, vec!["Department", "Name"]);
        let dept = batch
            .column_by_name("Department")
            .unwrap()
            .as_string::<i32>();
        assert_eq!(dept.value(0), "d1");
    }
}