delta_kernel 0.25.0

Core crate providing a Delta/Deltalake implementation focused on interoperability with a wide range of query engines.
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
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
use std::path::PathBuf;
use std::sync::Arc;
use std::vec;

use delta_kernel::actions::deletion_vector::split_vector;
use delta_kernel::arrow::array::{ArrayRef, AsArray as _, RecordBatch, TimestampMicrosecondArray};
use delta_kernel::arrow::compute::{concat_batches, filter_record_batch};
use delta_kernel::arrow::datatypes::{
    DataType as ArrowDataType, Field as ArrowField, Int64Type, Schema as ArrowSchema, TimeUnit,
};
use delta_kernel::engine::arrow_conversion::TryFromKernel as _;
use delta_kernel::engine::arrow_data::EngineDataArrowExt as _;
use delta_kernel::expressions::{
    column_expr, column_pred, Expression as Expr, ExpressionRef, Predicate as Pred, PredicateRef,
    Scalar,
};
use delta_kernel::log_segment::LogSegment;
use delta_kernel::object_store::memory::InMemory;
use delta_kernel::object_store::path::Path;
use delta_kernel::object_store::ObjectStoreExt as _;
use delta_kernel::parquet::file::properties::{EnabledStatistics, WriterProperties};
use delta_kernel::path::ParsedLogPath;
use delta_kernel::scan::state::{transform_to_logical, ScanFile};
use delta_kernel::scan::{Scan, StatsOptions};
use delta_kernel::schema::{DataType, MetadataColumnSpec, Schema, StructField, StructType};
use delta_kernel::{Engine, FileMeta, Snapshot};
use itertools::Itertools;
use test_utils::delta_kernel_default_engine::DefaultEngineBuilder;
use test_utils::{
    actions_to_string, add_commit, generate_batch, generate_simple_batch, into_record_batch,
    load_test_data, read_scan, record_batch_to_bytes, record_batch_to_bytes_with_props, IntoArray,
    TestAction, METADATA,
};
use url::Url;

const PARQUET_FILE1: &str = "part-00000-a72b1fb3-f2df-41fe-a8f0-e65b746382dd-c000.snappy.parquet";
const PARQUET_FILE2: &str = "part-00001-c506e79a-0bf8-4e2b-a42b-9731b2e490ae-c000.snappy.parquet";
const PARQUET_FILE3: &str = "part-00002-c506e79a-0bf8-4e2b-a42b-9731b2e490ff-c000.snappy.parquet";

#[cfg(all(feature = "arrow-57", not(feature = "arrow-58")))]
/// Bridge the new `Path::join` method that deprecates `Path::child` in object_store 0.13.
trait PathExt {
    fn join(&self, other: &str) -> Self;
}

#[cfg(all(feature = "arrow-57", not(feature = "arrow-58")))]
impl PathExt for Path {
    fn join(&self, other: &str) -> Self {
        self.child(other)
    }
}

/// Convert all top-level fields in a RecordBatch to nullable, matching Delta table schema
/// conventions where the table metadata declares columns as nullable.
fn make_top_level_fields_nullable(batch: &RecordBatch) -> RecordBatch {
    let schema = Arc::new(ArrowSchema::new(
        batch
            .schema()
            .fields()
            .iter()
            .map(|f| ArrowField::new(f.name(), f.data_type().clone(), true))
            .collect::<Vec<_>>(),
    ));
    RecordBatch::try_new(schema, batch.columns().to_vec()).unwrap()
}

#[tokio::test]
async fn single_commit_two_add_files() -> Result<(), Box<dyn std::error::Error>> {
    let batch = generate_simple_batch()?;
    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";
    let parquet_bytes = record_batch_to_bytes(&batch);
    let file_size = parquet_bytes.len() as u64;
    add_commit(
        table_root,
        storage.as_ref(),
        0,
        actions_to_string(vec![
            TestAction::Metadata,
            TestAction::AddWithSize(PARQUET_FILE1.to_string(), file_size),
            TestAction::AddWithSize(PARQUET_FILE2.to_string(), file_size),
        ]),
    )
    .await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;
    storage
        .put(
            &Path::from(PARQUET_FILE2),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());

    let expected = make_top_level_fields_nullable(&batch);
    let expected_data = vec![expected.clone(), expected];

    let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;
    let scan = snapshot.scan_builder().build()?;

    let mut files = 0;
    let stream = scan.execute(engine)?.zip(expected_data);

    for (data, expected) in stream {
        files += 1;
        assert_eq!(into_record_batch(data?), expected);
    }
    assert_eq!(2, files, "Expected to have scanned two files");
    Ok(())
}

#[tokio::test]
async fn two_commits() -> Result<(), Box<dyn std::error::Error>> {
    let batch = generate_simple_batch()?;
    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";
    let parquet_bytes = record_batch_to_bytes(&batch);
    let file_size = parquet_bytes.len() as u64;
    add_commit(
        table_root,
        storage.as_ref(),
        0,
        actions_to_string(vec![
            TestAction::Metadata,
            TestAction::AddWithSize(PARQUET_FILE1.to_string(), file_size),
        ]),
    )
    .await?;
    add_commit(
        table_root,
        storage.as_ref(),
        1,
        actions_to_string(vec![TestAction::AddWithSize(
            PARQUET_FILE2.to_string(),
            file_size,
        )]),
    )
    .await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;
    storage
        .put(
            &Path::from(PARQUET_FILE2),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let engine = DefaultEngineBuilder::new(storage.clone()).build();

    let expected = make_top_level_fields_nullable(&batch);
    let expected_data = vec![expected.clone(), expected];

    let snapshot = Snapshot::builder_for(table_root).build(&engine)?;
    let scan = snapshot.scan_builder().build()?;

    let mut files = 0;
    let stream = scan.execute(Arc::new(engine))?.zip(expected_data);

    for (data, expected) in stream {
        files += 1;
        assert_eq!(into_record_batch(data?), expected);
    }
    assert_eq!(2, files, "Expected to have scanned two files");

    Ok(())
}

#[tokio::test]
async fn remove_action() -> Result<(), Box<dyn std::error::Error>> {
    let batch = generate_simple_batch()?;
    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";
    let parquet_bytes = record_batch_to_bytes(&batch);
    let file_size = parquet_bytes.len() as u64;
    add_commit(
        table_root,
        storage.as_ref(),
        0,
        actions_to_string(vec![
            TestAction::Metadata,
            TestAction::AddWithSize(PARQUET_FILE1.to_string(), file_size),
        ]),
    )
    .await?;
    add_commit(
        table_root,
        storage.as_ref(),
        1,
        actions_to_string(vec![TestAction::AddWithSize(
            PARQUET_FILE2.to_string(),
            file_size,
        )]),
    )
    .await?;
    add_commit(
        table_root,
        storage.as_ref(),
        2,
        actions_to_string(vec![TestAction::RemoveWithSize(
            PARQUET_FILE2.to_string(),
            file_size,
        )]),
    )
    .await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let engine = DefaultEngineBuilder::new(storage.clone()).build();

    let expected = make_top_level_fields_nullable(&batch);
    let expected_data = vec![expected];

    let snapshot = Snapshot::builder_for(table_root).build(&engine)?;
    let scan = snapshot.scan_builder().build()?;

    let stream = scan.execute(Arc::new(engine))?.zip(expected_data);

    let mut files = 0;
    for (data, expected) in stream {
        files += 1;
        assert_eq!(into_record_batch(data?), expected);
    }
    assert_eq!(1, files, "Expected to have scanned one file");
    Ok(())
}

#[tokio::test]
async fn stats() -> Result<(), Box<dyn std::error::Error>> {
    fn generate_commit2(actions: Vec<TestAction>) -> String {
        actions
            .into_iter()
            .map(|test_action| match test_action {
                TestAction::Add(path) => format!(r#"{{"{action}":{{"path":"{path}","partitionValues":{{}},"size":262,"modificationTime":1587968586000,"dataChange":true, "stats":"{{\"numRecords\":2,\"nullCount\":{{\"id\":0}},\"minValues\":{{\"id\": 5}},\"maxValues\":{{\"id\":7}}}}"}}}}"#, action = "add", path = path),
                TestAction::Remove(path) => format!(r#"{{"{action}":{{"path":"{path}","partitionValues":{{}},"size":262,"modificationTime":1587968586000,"dataChange":true}}}}"#, action = "remove", path = path),
                TestAction::Metadata => METADATA.into(),
                TestAction::AddWithSize(path, size) => format!(r#"{{"{action}":{{"path":"{path}","partitionValues":{{}},"size":{size},"modificationTime":1587968586000,"dataChange":true, "stats":"{{\"numRecords\":2,\"nullCount\":{{\"id\":0}},\"minValues\":{{\"id\": 5}},\"maxValues\":{{\"id\":7}}}}"}}}}"#, action = "add", path = path),
                TestAction::RemoveWithSize(path, size) => format!(r#"{{"{action}":{{"path":"{path}","partitionValues":{{}},"size":{size},"modificationTime":1587968586000,"dataChange":true}}}}"#, action = "remove", path = path),
            })
            .fold(String::new(), |a, b| a + &b + "\n")
    }

    let batch1 = make_top_level_fields_nullable(&generate_simple_batch()?);
    let batch2 = make_top_level_fields_nullable(&generate_batch(vec![
        ("id", vec![5, 7].into_array()),
        ("val", vec!["e", "g"].into_array()),
    ])?);
    let file_size1 = record_batch_to_bytes(&batch1).len() as u64;
    let file_size2 = record_batch_to_bytes(&batch2).len() as u64;
    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";
    // valid commit with min/max (0, 2)
    add_commit(
        table_root,
        storage.as_ref(),
        0,
        actions_to_string(vec![
            TestAction::Metadata,
            TestAction::AddWithSize(PARQUET_FILE1.to_string(), file_size1),
        ]),
    )
    .await?;
    // storage.add_commit(1, &format!("{}\n",
    // r#"{{"add":{{"path":"doesnotexist","partitionValues":{{}},"size":262,"modificationTime":
    // 1587968586000,"dataChange":true,
    // "stats":"{{\"numRecords\":2,\"nullCount\":{{\"id\":0}},\"minValues\":{{\"id\":
    // 0}},\"maxValues\":{{\"id\":2}}}}"}}}}"#));
    add_commit(
        table_root,
        storage.as_ref(),
        1,
        generate_commit2(vec![TestAction::AddWithSize(
            PARQUET_FILE2.to_string(),
            file_size2,
        )]),
    )
    .await?;

    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch1).into(),
        )
        .await?;

    storage
        .put(
            &Path::from(PARQUET_FILE2),
            record_batch_to_bytes(&batch2).into(),
        )
        .await?;

    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;

    // The first file has id between 1 and 3; the second has id between 5 and 7. For each operator,
    // we validate the boundary values where we expect the set of matched files to change.
    //
    // NOTE: For cases that match both batch1 and batch2, we list batch2 first because log replay
    // returns most recently added files first.
    #[allow(clippy::type_complexity)] // otherwise it's even more complex because no `_`
    let test_cases: Vec<(fn(Expr, Expr) -> _, _, _)> = vec![
        (Pred::eq, 0i32, vec![]),
        (Pred::eq, 1, vec![&batch1]),
        (Pred::eq, 3, vec![&batch1]),
        (Pred::eq, 4, vec![]),
        (Pred::eq, 5, vec![&batch2]),
        (Pred::eq, 7, vec![&batch2]),
        (Pred::eq, 8, vec![]),
        (Pred::lt, 1, vec![]),
        (Pred::lt, 2, vec![&batch1]),
        (Pred::lt, 5, vec![&batch1]),
        (Pred::lt, 6, vec![&batch2, &batch1]),
        (Pred::le, 0, vec![]),
        (Pred::le, 1, vec![&batch1]),
        (Pred::le, 4, vec![&batch1]),
        (Pred::le, 5, vec![&batch2, &batch1]),
        (Pred::gt, 2, vec![&batch2, &batch1]),
        (Pred::gt, 3, vec![&batch2]),
        (Pred::gt, 6, vec![&batch2]),
        (Pred::gt, 7, vec![]),
        (Pred::ge, 3, vec![&batch2, &batch1]),
        (Pred::ge, 4, vec![&batch2]),
        (Pred::ge, 7, vec![&batch2]),
        (Pred::ge, 8, vec![]),
        (Pred::ne, 0, vec![&batch2, &batch1]),
        (Pred::ne, 1, vec![&batch2, &batch1]),
        (Pred::ne, 3, vec![&batch2, &batch1]),
        (Pred::ne, 4, vec![&batch2, &batch1]),
        (Pred::ne, 5, vec![&batch2, &batch1]),
        (Pred::ne, 7, vec![&batch2, &batch1]),
        (Pred::ne, 8, vec![&batch2, &batch1]),
    ];
    for (pred_fn, value, expected_batches) in test_cases {
        let predicate = pred_fn(column_expr!("id"), Expr::literal(value));
        let scan = snapshot
            .clone()
            .scan_builder()
            .with_predicate(Arc::new(predicate.clone()))
            .build()?;

        let expected_files = expected_batches.len();
        let mut files_scanned = 0;
        let stream = scan.execute(engine.clone())?.zip(expected_batches);

        for (batch, expected) in stream {
            files_scanned += 1;
            assert_eq!(into_record_batch(batch?), expected.clone());
        }
        assert_eq!(expected_files, files_scanned, "{predicate:?}");
    }
    Ok(())
}

fn read_with_execute(
    engine: Arc<dyn Engine>,
    scan: &Scan,
    expected: &[String],
) -> Result<(), Box<dyn std::error::Error>> {
    let result_schema = Arc::new(ArrowSchema::try_from_kernel(
        scan.logical_schema().as_ref(),
    )?);
    let batches = read_scan(scan, engine)?;

    if expected.is_empty() {
        assert_eq!(batches.len(), 0);
    } else {
        let batch = concat_batches(&result_schema, &batches)?;
        assert_batches_sorted_eq!(expected, &[batch]);
    }
    Ok(())
}

fn scan_metadata_callback(batches: &mut Vec<ScanFile>, scan_file: ScanFile) {
    batches.push(scan_file);
}

fn read_with_scan_metadata(
    location: &Url,
    engine: &dyn Engine,
    scan: &Scan,
    expected: &[String],
) -> Result<(), Box<dyn std::error::Error>> {
    let result_schema = Arc::new(ArrowSchema::try_from_kernel(
        scan.logical_schema().as_ref(),
    )?);
    let scan_metadata = scan.scan_metadata(engine)?;
    let mut scan_files = vec![];
    for res in scan_metadata {
        let scan_metadata = res?;
        scan_files = scan_metadata.visit_scan_files(scan_files, scan_metadata_callback)?;
    }

    let mut batches = vec![];
    for scan_file in scan_files.into_iter() {
        let file_path = location.join(&scan_file.path)?;
        let mut selection_vector = scan_file
            .dv_info
            .get_selection_vector(engine, location)
            .unwrap();
        let meta = FileMeta {
            last_modified: 0,
            size: scan_file.size.try_into().unwrap(),
            location: file_path,
        };
        let read_results = engine
            .parquet_handler()
            .read_parquet_files(
                &[meta],
                scan.physical_schema().clone(),
                scan.physical_predicate().clone(),
            )
            .unwrap();

        for read_result in read_results {
            let read_result = read_result.unwrap();
            let len = read_result.len();
            // to transform the physical data into the correct logical form
            let logical = transform_to_logical(
                engine,
                read_result,
                scan.physical_schema(),
                scan.logical_schema(),
                scan_file.transform.clone(),
            )
            .unwrap();
            let record_batch = logical.try_into_record_batch()?;
            let rest = split_vector(selection_vector.as_mut(), len, Some(true));
            let batch = if let Some(mask) = selection_vector.clone() {
                // apply the selection vector
                filter_record_batch(&record_batch, &mask.into()).unwrap()
            } else {
                record_batch
            };
            selection_vector = rest;
            batches.push(batch);
        }
    }

    if expected.is_empty() {
        assert_eq!(batches.len(), 0);
    } else {
        let batch = concat_batches(&result_schema, &batches)?;
        assert_batches_sorted_eq!(expected, &[batch]);
    }
    Ok(())
}

fn read_table_data(
    path: &str,
    select_cols: Option<&[&str]>,
    predicate: Option<Pred>,
    mut expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = std::fs::canonicalize(PathBuf::from(path))?;
    let predicate = predicate.map(Arc::new);
    let url = url::Url::from_directory_path(path).unwrap();
    let engine = test_utils::create_default_engine(&url)?;

    let snapshot = Snapshot::builder_for(url.clone()).build(engine.as_ref())?;

    let read_schema = select_cols.map(|select_cols| {
        let table_schema = snapshot.schema();
        let selected_fields = select_cols
            .iter()
            .map(|col| table_schema.field(col).cloned().unwrap());
        Arc::new(Schema::new_unchecked(selected_fields))
    });
    println!("Read {url:?} with schema {read_schema:#?} and predicate {predicate:#?}");
    let scan = snapshot
        .scan_builder()
        .with_schema_opt(read_schema)
        .with_predicate(predicate.clone())
        .build()?;

    sort_lines!(expected);
    read_with_scan_metadata(&url, engine.as_ref(), &scan, &expected)?;
    read_with_execute(engine, &scan, &expected)?;
    Ok(())
}

// util to take a Vec<&str> and call read_table_data with Vec<String>
fn read_table_data_str(
    path: &str,
    select_cols: Option<&[&str]>,
    predicate: Option<Pred>,
    expected: Vec<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    read_table_data(
        path,
        select_cols,
        predicate,
        expected.into_iter().map(String::from).collect(),
    )
}

#[test]
fn data() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+--------+--------+---------+",
        "| letter | number | a_float |",
        "+--------+--------+---------+",
        "|        | 6      | 6.6     |",
        "| a      | 1      | 1.1     |",
        "| a      | 4      | 4.4     |",
        "| b      | 2      | 2.2     |",
        "| c      | 3      | 3.3     |",
        "| e      | 5      | 5.5     |",
        "+--------+--------+---------+",
    ];
    read_table_data_str("./tests/data/basic_partitioned", None, None, expected)?;

    Ok(())
}

#[test]
fn column_ordering() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+---------+--------+--------+",
        "| a_float | letter | number |",
        "+---------+--------+--------+",
        "| 6.6     |        | 6      |",
        "| 4.4     | a      | 4      |",
        "| 5.5     | e      | 5      |",
        "| 1.1     | a      | 1      |",
        "| 2.2     | b      | 2      |",
        "| 3.3     | c      | 3      |",
        "+---------+--------+--------+",
    ];
    read_table_data_str(
        "./tests/data/basic_partitioned",
        Some(&["a_float", "letter", "number"]),
        None,
        expected,
    )?;

    Ok(())
}

#[test]
fn column_ordering_and_projection() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+---------+--------+",
        "| a_float | number |",
        "+---------+--------+",
        "| 6.6     | 6      |",
        "| 4.4     | 4      |",
        "| 5.5     | 5      |",
        "| 1.1     | 1      |",
        "| 2.2     | 2      |",
        "| 3.3     | 3      |",
        "+---------+--------+",
    ];
    read_table_data_str(
        "./tests/data/basic_partitioned",
        Some(&["a_float", "number"]),
        None,
        expected,
    )?;

    Ok(())
}

// get the basic_partitioned table for a set of expected numbers
fn table_for_numbers(nums: Vec<u32>) -> Vec<String> {
    let mut res: Vec<String> = vec![
        "+---------+--------+",
        "| a_float | number |",
        "+---------+--------+",
    ]
    .into_iter()
    .map(String::from)
    .collect();
    for num in nums.iter() {
        res.push(format!("| {num}.{num}     | {num}      |"));
    }
    res.push("+---------+--------+".to_string());
    res
}

// get the basic_partitioned table for a set of expected letters
fn table_for_letters(letters: &[char]) -> Vec<String> {
    let mut res: Vec<String> = vec![
        "+--------+--------+",
        "| letter | number |",
        "+--------+--------+",
    ]
    .into_iter()
    .map(String::from)
    .collect();
    let rows = vec![(1, 'a'), (2, 'b'), (3, 'c'), (4, 'a'), (5, 'e')];
    for (num, letter) in rows {
        if letters.contains(&letter) {
            res.push(format!("| {letter}      | {num}      |"));
        }
    }
    res.push("+--------+--------+".to_string());
    res
}

#[rstest::rstest]
#[case::less_than(
    column_expr!("number").lt(Expr::literal(4i64)),
    table_for_numbers(vec![1, 2, 3])
)]
#[case::less_than_or_equal(
    column_expr!("number").le(Expr::literal(4i64)),
    table_for_numbers(vec![1, 2, 3, 4])
)]
#[case::greater_than(
    column_expr!("number").gt(Expr::literal(4i64)),
    table_for_numbers(vec![5, 6])
)]
#[case::greater_than_or_equal(
    column_expr!("number").ge(Expr::literal(4i64)),
    table_for_numbers(vec![4, 5, 6])
)]
#[case::equal(
    column_expr!("number").eq(Expr::literal(4i64)),
    table_for_numbers(vec![4])
)]
#[case::not_equal(
    column_expr!("number").ne(Expr::literal(4i64)),
    table_for_numbers(vec![1, 2, 3, 5, 6])
)]
fn predicate_on_number(
    #[case] pred: Pred,
    #[case] expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    read_table_data(
        "./tests/data/basic_partitioned",
        Some(&["a_float", "number"]),
        Some(pred),
        expected,
    )?;
    Ok(())
}

#[rstest::rstest]
#[case::is_null(
    column_expr!("letter").is_null(),
    vec![
        "+--------+--------+",
        "| letter | number |",
        "+--------+--------+",
        "|        | 6      |",
        "+--------+--------+",
    ]
    .into_iter()
    .map(String::from)
    .collect()
)]
#[case::is_not_null(
    column_expr!("letter").is_not_null(),
    table_for_letters(&['a', 'b', 'c', 'e'])
)]
#[case::less_than(
    column_expr!("letter").lt(Expr::literal("c")),
    table_for_letters(&['a', 'b'])
)]
#[case::less_than_or_equal(
    column_expr!("letter").le(Expr::literal("c")),
    table_for_letters(&['a', 'b', 'c'])
)]
#[case::greater_than(
    column_expr!("letter").gt(Expr::literal("c")),
    table_for_letters(&['e'])
)]
#[case::greater_than_or_equal(
    column_expr!("letter").ge(Expr::literal("c")),
    table_for_letters(&['c', 'e'])
)]
#[case::equal(
    column_expr!("letter").eq(Expr::literal("c")),
    table_for_letters(&['c'])
)]
#[case::not_equal(
    column_expr!("letter").ne(Expr::literal("c")),
    table_for_letters(&['a', 'b', 'e'])
)]
fn predicate_on_letter(
    #[case] pred: Pred,
    #[case] expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    // Test basic column pruning. Note that the actual predicate machinery is already well-tested,
    // so we're just testing wiring here.
    read_table_data(
        "./tests/data/basic_partitioned",
        Some(&["letter", "number"]),
        Some(pred),
        expected,
    )?;
    Ok(())
}

#[rstest::rstest]
#[case::or_with_pruning(
    Pred::or(
        column_expr!("letter").gt(Expr::literal("a")),
        column_expr!("number").gt(Expr::literal(3i64)),
    ),
    // Unified data skipping evaluates partition + data predicates in a single pass.
    // File a/1 (letter='a', max(number)=1): OR('a'>'a', 1>3) = FALSE -> pruned
    vec![
        "+--------+--------+",
        "| letter | number |",
        "+--------+--------+",
        "|        | 6      |",
        "| a      | 4      |",
        "| b      | 2      |",
        "| c      | 3      |",
        "| e      | 5      |",
        "+--------+--------+",
    ]
    .into_iter()
    .map(String::from)
    .collect()
)]
#[case::and_with_pruning(
    Pred::and(
        column_expr!("letter").gt(Expr::literal("a")), // numbers 2, 3, 5
        column_expr!("number").gt(Expr::literal(3i64)), // letters a, e
    ),
    table_for_letters(&['e'])
)]
#[case::and_with_nested_or(
    Pred::and(
        column_expr!("letter").gt(Expr::literal("a")), // numbers 2, 3, 5
        Pred::or(
            column_expr!("letter").eq(Expr::literal("c")),
            column_expr!("number").eq(Expr::literal(3i64)),
        ),
    ),
    // Unified data skipping evaluates the full expression:
    // b/2: AND(TRUE, OR(FALSE, FALSE)) = FALSE -> pruned
    // c/3: AND(TRUE, OR(TRUE, TRUE)) = TRUE -> kept
    // e/5: AND(TRUE, OR(FALSE, FALSE)) = FALSE -> pruned
    table_for_letters(&['c'])
)]
fn predicate_on_letter_and_number(
    #[case] pred: Pred,
    #[case] expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    // Unified data skipping evaluates partition + data predicates together in a single
    // columnar pass, enabling pruning for mixed predicates including OR expressions.
    read_table_data(
        "./tests/data/basic_partitioned",
        Some(&["letter", "number"]),
        Some(pred),
        expected,
    )?;
    Ok(())
}

// Regression test for issue #2468
#[rstest::rstest]
#[case::predicate_on_unprojected_data_column_in_table_schema_succeeds(
    // `number` is a data column not present in the projected schema (`a_float`).
    column_expr!("number").gt(Expr::literal(4i64)),
    vec![
        "+---------+",
        "| a_float |",
        "+---------+",
        "| 5.5     |",
        "| 6.6     |",
        "+---------+",
    ]
    .into_iter()
    .map(String::from)
    .collect()
)]
#[case::predicate_on_partition_column_in_table_schema_succeeds(
    column_expr!("letter").eq(Expr::literal("a")),
    vec![
        "+---------+",
        "| a_float |",
        "+---------+",
        "| 1.1     |",
        "| 4.4     |",
        "+---------+",
    ]
    .into_iter()
    .map(String::from)
    .collect()
)]
#[case::predicate_on_mixed_projected_and_unprojected_columns_succeeds(
    // a_float is projected, number is unprojected
    Pred::and(
        column_expr!("a_float").gt(Expr::literal(4.0)),
        column_expr!("number").lt(Expr::literal(6i64)),
    ),
    vec![
        "+---------+",
        "| a_float |",
        "+---------+",
        "| 4.4     |",
        "| 5.5     |",
        "+---------+",
    ]
    .into_iter()
    .map(String::from)
    .collect()
)]
fn predicate_on_unprojected_column(
    #[case] pred: Pred,
    #[case] expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    read_table_data(
        "./tests/data/basic_partitioned",
        Some(&["a_float"]),
        Some(pred),
        expected,
    )?;
    Ok(())
}

/// Test partition pruning on a table with a checkpoint containing `partitionValues_parsed`.
/// This exercises the checkpoint code path where typed partition values are read directly
/// from the parquet column rather than parsed from the string map via `MapToStruct`.
///
/// Table: app-txn-checkpoint (checkpoint at v1, partition column: `modified` (string))
///   - 2 files with modified=2021-02-01 (value 4-11, 8 rows each)
///   - 2 files with modified=2021-02-02 (value 1-3, 3 rows each)
#[rstest::rstest]
#[case::partition_only_prunes_one_partition(
    // Partition-only predicate: modified = '2021-02-02' should prune 2021-02-01 files
    column_expr!("modified").eq(Expr::literal("2021-02-02")),
    vec![
        "+----+------------+-------+",
        "| id | modified   | value |",
        "+----+------------+-------+",
        "| A  | 2021-02-02 | 1     |",
        "| A  | 2021-02-02 | 1     |",
        "| A  | 2021-02-02 | 3     |",
        "| A  | 2021-02-02 | 3     |",
        "| B  | 2021-02-02 | 2     |",
        "| B  | 2021-02-02 | 2     |",
        "+----+------------+-------+",
    ]
    .into_iter()
    .map(String::from)
    .collect()
)]
#[case::partition_prunes_other_partition(
    // modified = '2021-02-01' should prune 2021-02-02 files, keeping all 2021-02-01 rows
    column_expr!("modified").eq(Expr::literal("2021-02-01")),
    vec![
        "+----+------------+-------+",
        "| id | modified   | value |",
        "+----+------------+-------+",
        "| A  | 2021-02-01 | 10    |",
        "| A  | 2021-02-01 | 10    |",
        "| A  | 2021-02-01 | 11    |",
        "| A  | 2021-02-01 | 11    |",
        "| A  | 2021-02-01 | 5     |",
        "| A  | 2021-02-01 | 5     |",
        "| A  | 2021-02-01 | 6     |",
        "| A  | 2021-02-01 | 6     |",
        "| A  | 2021-02-01 | 7     |",
        "| A  | 2021-02-01 | 7     |",
        "| B  | 2021-02-01 | 4     |",
        "| B  | 2021-02-01 | 4     |",
        "| B  | 2021-02-01 | 8     |",
        "| B  | 2021-02-01 | 8     |",
        "| B  | 2021-02-01 | 9     |",
        "| B  | 2021-02-01 | 9     |",
        "+----+------------+-------+",
    ]
    .into_iter()
    .map(String::from)
    .collect()
)]
fn partition_pruning_with_checkpoint_parsed_values(
    #[case] pred: Pred,
    #[case] expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    read_table_data(
        "./tests/data/app-txn-checkpoint",
        Some(&["id", "modified", "value"]),
        Some(pred),
        expected,
    )?;
    Ok(())
}

/// Test mixed predicates (partition + data stats) on a checkpoint with both
/// `partitionValues_parsed` and `stats_parsed`. This exercises the unified columnar data skipping
/// pass that evaluates both partition values and data column statistics together.
///
/// Table: app-txn-checkpoint (checkpoint at v1, partition column: `modified` (string))
///   - 2 files: modified=2021-02-02 -- 3 rows each, value in [1, 3]
///   - 2 files: modified=2021-02-01 -- 8 rows each, value in [4, 11]
#[rstest::rstest]
#[case::and_keeps_partition_matched_files(
    // Data skipping keeps 2021-02-01 files (partition matches, max(value)=11 > 9) and
    // prunes 2021-02-02 files (partition mismatch). All rows from kept files are returned
    // since kernel does not apply row-level predicate filtering.
    Pred::and(
        column_expr!("modified").eq(Expr::literal("2021-02-01")),
        column_expr!("value").gt(Expr::literal(9i32)),
    ),
    vec![
        "+----+------------+-------+",
        "| id | modified   | value |",
        "+----+------------+-------+",
        "| A  | 2021-02-01 | 10    |",
        "| A  | 2021-02-01 | 10    |",
        "| A  | 2021-02-01 | 11    |",
        "| A  | 2021-02-01 | 11    |",
        "| A  | 2021-02-01 | 5     |",
        "| A  | 2021-02-01 | 5     |",
        "| A  | 2021-02-01 | 6     |",
        "| A  | 2021-02-01 | 6     |",
        "| A  | 2021-02-01 | 7     |",
        "| A  | 2021-02-01 | 7     |",
        "| B  | 2021-02-01 | 4     |",
        "| B  | 2021-02-01 | 4     |",
        "| B  | 2021-02-01 | 8     |",
        "| B  | 2021-02-01 | 8     |",
        "| B  | 2021-02-01 | 9     |",
        "| B  | 2021-02-01 | 9     |",
        "+----+------------+-------+",
    ]
    .into_iter()
    .map(String::from)
    .collect()
)]
#[case::and_prunes_all_files(
    // 2021-02-02: partition matches but data stats fail (max value=3, NOT > 3).
    // 2021-02-01: partition mismatch. All 4 files pruned.
    Pred::and(
        column_expr!("modified").eq(Expr::literal("2021-02-02")),
        column_expr!("value").gt(Expr::literal(3i32)),
    ),
    vec![]
)]
#[case::or_prunes_by_both_partition_and_stats(
    // 2021-02-01 pruned: partition mismatch AND max(value)=11 NOT > 11.
    // 2021-02-02 kept by partition match. Only 2021-02-02 rows returned.
    Pred::or(
        column_expr!("modified").eq(Expr::literal("2021-02-02")),
        column_expr!("value").gt(Expr::literal(11i32)),
    ),
    vec![
        "+----+------------+-------+",
        "| id | modified   | value |",
        "+----+------------+-------+",
        "| A  | 2021-02-02 | 1     |",
        "| A  | 2021-02-02 | 1     |",
        "| A  | 2021-02-02 | 3     |",
        "| A  | 2021-02-02 | 3     |",
        "| B  | 2021-02-02 | 2     |",
        "| B  | 2021-02-02 | 2     |",
        "+----+------------+-------+",
    ]
    .into_iter()
    .map(String::from)
    .collect()
)]
#[case::or_keeps_all_files(
    // 2021-02-02 kept by partition match, 2021-02-01 kept by data stats (max=11 > 9).
    // All rows from all 4 files are returned.
    Pred::or(
        column_expr!("modified").eq(Expr::literal("2021-02-02")),
        column_expr!("value").gt(Expr::literal(9i32)),
    ),
    vec![
        "+----+------------+-------+",
        "| id | modified   | value |",
        "+----+------------+-------+",
        "| A  | 2021-02-01 | 10    |",
        "| A  | 2021-02-01 | 10    |",
        "| A  | 2021-02-01 | 11    |",
        "| A  | 2021-02-01 | 11    |",
        "| A  | 2021-02-01 | 5     |",
        "| A  | 2021-02-01 | 5     |",
        "| A  | 2021-02-01 | 6     |",
        "| A  | 2021-02-01 | 6     |",
        "| A  | 2021-02-01 | 7     |",
        "| A  | 2021-02-01 | 7     |",
        "| A  | 2021-02-02 | 1     |",
        "| A  | 2021-02-02 | 1     |",
        "| A  | 2021-02-02 | 3     |",
        "| A  | 2021-02-02 | 3     |",
        "| B  | 2021-02-01 | 4     |",
        "| B  | 2021-02-01 | 4     |",
        "| B  | 2021-02-01 | 8     |",
        "| B  | 2021-02-01 | 8     |",
        "| B  | 2021-02-01 | 9     |",
        "| B  | 2021-02-01 | 9     |",
        "| B  | 2021-02-02 | 2     |",
        "| B  | 2021-02-02 | 2     |",
        "+----+------------+-------+",
    ]
    .into_iter()
    .map(String::from)
    .collect()
)]
fn mixed_predicate_with_checkpoint_parsed_columns(
    #[case] pred: Pred,
    #[case] expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    // Exercises the unified data skipping path that reads both `partitionValues_parsed` and
    // `stats_parsed` from the checkpoint parquet file in a single columnar pass.
    read_table_data(
        "./tests/data/app-txn-checkpoint",
        Some(&["id", "modified", "value"]),
        Some(pred),
        expected,
    )?;
    Ok(())
}

/// Test partition pruning on a table with column mapping (name mode). The logical partition
/// column "category" has physical name "phys_category". With column mapping, `partitionValues`
/// in the log uses physical column names, and the partition schema + predicate must also use
/// physical names for `MapToStruct` extraction and data skipping to work correctly.
#[rstest::rstest]
#[case::partition_only(
    // Partition-only predicate: category = 'A' prunes the category=B file
    Arc::new(Pred::eq(column_expr!("category"), Expr::literal("A"))),
    None,
    1
)]
#[case::mixed_partition_and_data(
    // Mixed predicate: category = 'A' OR val > 'z'. Category=A kept by partition match.
    // Category=B: partition mismatch, but max(val)='z' NOT > 'z', so data skipping prunes it.
    Arc::new(Pred::or(
        Pred::eq(column_expr!("category"), Expr::literal("A")),
        Pred::gt(column_expr!("val"), Expr::literal("z")),
    )),
    None,
    1
)]
#[case::predicate_on_unprojected_data_column(
    // Project only "category"; predicate references unprojected "val" (logical) whose
    // physical name is "phys_val". Kernel must resolve to phys_val via the full table
    // schema and prune both files: max(phys_val)='z' is NOT > 'z'.
    Arc::new(Pred::gt(column_expr!("val"), Expr::literal("z"))),
    Some(vec!["category"]),
    0
)]
#[case::predicate_on_unprojected_partition_column(
    // Project only "val"; predicate references unprojected partition column "category"
    // (logical, physical name "phys_category"). Partition pruning must still kick in
    // using the physical partition name, keeping only the category=A file.
    Arc::new(Pred::eq(column_expr!("category"), Expr::literal("A"))),
    Some(vec!["val"]),
    1
)]
#[tokio::test]
async fn test_partition_pruning_with_column_mapping(
    #[case] predicate: Arc<Pred>,
    #[case] select_cols: Option<Vec<&'static str>>,
    #[case] expected_files: usize,
) -> Result<(), Box<dyn std::error::Error>> {
    let batch = generate_batch(vec![("phys_val", vec!["x", "y", "z"].into_array())])?;

    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";

    // Column mapping name mode: logical "category" -> physical "phys_category",
    // logical "val" -> physical "phys_val"
    let schema_str = r#"{"type":"struct","fields":[{"name":"category","type":"string","nullable":true,"metadata":{"delta.columnMapping.id":1,"delta.columnMapping.physicalName":"phys_category"}},{"name":"val","type":"string","nullable":true,"metadata":{"delta.columnMapping.id":2,"delta.columnMapping.physicalName":"phys_val"}}]}"#;

    let actions = [
        r#"{"protocol":{"minReaderVersion":3,"minWriterVersion":7,"readerFeatures":["columnMapping"],"writerFeatures":["columnMapping"]}}"#.to_string(),
        r#"{"commitInfo":{"timestamp":1587968586154,"operation":"WRITE","isBlindAppend":true}}"#.to_string(),
        format!(
            r#"{{"metaData":{{"id":"test-cm","format":{{"provider":"parquet","options":{{}}}},"schemaString":"{schema}","partitionColumns":["category"],"configuration":{{"delta.columnMapping.mode":"name","delta.columnMapping.maxColumnId":"2"}},"createdTime":1587968585495}}}}"#,
            schema = schema_str.replace('"', r#"\""#),
        ),
        // partitionValues uses physical column name when column mapping is enabled
        format!(
            r#"{{"add":{{"path":"phys_category=A/{PARQUET_FILE1}","partitionValues":{{"phys_category":"A"}},"size":0,"modificationTime":1587968586000,"dataChange":true,"stats":"{{\"numRecords\":3,\"nullCount\":{{\"phys_val\":0}},\"minValues\":{{\"phys_val\":\"x\"}},\"maxValues\":{{\"phys_val\":\"z\"}}}}" }}}}"#
        ),
        format!(
            r#"{{"add":{{"path":"phys_category=B/{PARQUET_FILE2}","partitionValues":{{"phys_category":"B"}},"size":0,"modificationTime":1587968586000,"dataChange":true,"stats":"{{\"numRecords\":3,\"nullCount\":{{\"phys_val\":0}},\"minValues\":{{\"phys_val\":\"x\"}},\"maxValues\":{{\"phys_val\":\"z\"}}}}" }}}}"#
        ),
    ];

    add_commit(table_root, storage.as_ref(), 0, actions.iter().join("\n")).await?;
    storage
        .put(
            &Path::from("phys_category=A").join(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;
    storage
        .put(
            &Path::from("phys_category=B").join(PARQUET_FILE2),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;

    // Predicates use logical column names -- kernel must map to physical names. The
    // optional projection narrows the output schema; when set, the predicate may still
    // reference columns outside it
    let projection = select_cols
        .as_ref()
        .map(|cols| snapshot.schema().project(cols))
        .transpose()?;
    let scan = snapshot
        .scan_builder()
        .with_schema_opt(projection)
        .with_predicate(predicate)
        .build()?;

    let stream = scan.execute(engine)?;
    let mut files_scanned = 0;
    // "category" is in the output iff there's no projection (SELECT *) or the projection
    // explicitly includes it.
    let expect_category = select_cols
        .as_ref()
        .is_none_or(|cols| cols.contains(&"category"));
    for engine_data in stream {
        let result_batch = into_record_batch(engine_data?);
        // The "category" partition column should be present exactly when projected, and
        // should be 'A' for every surviving row.
        match result_batch.schema().index_of("category") {
            Ok(category_idx) => {
                assert!(
                    expect_category,
                    "category present but not expected in projection"
                );
                let category_col = result_batch.column(category_idx).as_string::<i32>();
                for i in 0..result_batch.num_rows() {
                    assert_eq!(category_col.value(i), "A");
                }
            }
            Err(_) => assert!(
                !expect_category,
                "category missing but expected in projection"
            ),
        }
        files_scanned += 1;
    }
    assert_eq!(
        expected_files, files_scanned,
        "Expected partition pruning to return {expected_files} file(s)"
    );

    Ok(())
}

#[rstest::rstest]
#[case::not_less_than(
    Pred::not(column_expr!("number").lt(Expr::literal(4i64))),
    table_for_numbers(vec![4, 5, 6])
)]
#[case::not_less_than_or_equal(
    Pred::not(column_expr!("number").le(Expr::literal(4i64))),
    table_for_numbers(vec![5, 6])
)]
#[case::not_greater_than(
    Pred::not(column_expr!("number").gt(Expr::literal(4i64))),
    table_for_numbers(vec![1, 2, 3, 4])
)]
#[case::not_greater_than_or_equal(
    Pred::not(column_expr!("number").ge(Expr::literal(4i64))),
    table_for_numbers(vec![1, 2, 3])
)]
#[case::not_equal(
    Pred::not(column_expr!("number").eq(Expr::literal(4i64))),
    table_for_numbers(vec![1, 2, 3, 5, 6])
)]
#[case::not_not_equal(
    Pred::not(column_expr!("number").ne(Expr::literal(4i64))),
    table_for_numbers(vec![4])
)]
fn predicate_on_number_not(
    #[case] pred: Pred,
    #[case] expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    read_table_data(
        "./tests/data/basic_partitioned",
        Some(&["a_float", "number"]),
        Some(pred),
        expected,
    )?;
    Ok(())
}

#[test]
fn predicate_on_number_with_not_null() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+---------+--------+",
        "| a_float | number |",
        "+---------+--------+",
        "| 1.1     | 1      |",
        "| 2.2     | 2      |",
        "+---------+--------+",
    ];
    read_table_data_str(
        "./tests/data/basic_partitioned",
        Some(&["a_float", "number"]),
        Some(Pred::and(
            column_expr!("number").is_not_null(),
            column_expr!("number").lt(Expr::literal(3i64)),
        )),
        expected,
    )?;
    Ok(())
}

#[test]
fn predicate_null() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![]; // number is never null
    read_table_data_str(
        "./tests/data/basic_partitioned",
        Some(&["a_float", "number"]),
        Some(column_expr!("number").is_null()),
        expected,
    )?;
    Ok(())
}

#[test]
fn mixed_null() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+------+--------------+",
        "| part | n            |",
        "+------+--------------+",
        "| 0    |              |",
        "| 0    |              |",
        "| 0    |              |",
        "| 0    |              |",
        "| 0    |              |",
        "| 2    |              |",
        "| 2    | non-null-mix |",
        "| 2    |              |",
        "| 2    | non-null-mix |",
        "| 2    |              |",
        "+------+--------------+",
    ];
    read_table_data_str(
        "./tests/data/mixed-nulls",
        Some(&["part", "n"]),
        Some(column_expr!("n").is_null()),
        expected,
    )?;
    Ok(())
}

#[test]
fn mixed_not_null() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+------+--------------+",
        "| part | n            |",
        "+------+--------------+",
        "| 1    | non-null     |",
        "| 1    | non-null     |",
        "| 1    | non-null     |",
        "| 1    | non-null     |",
        "| 1    | non-null     |",
        "| 2    |              |",
        "| 2    |              |",
        "| 2    |              |",
        "| 2    | non-null-mix |",
        "| 2    | non-null-mix |",
        "+------+--------------+",
    ];
    read_table_data_str(
        "./tests/data/mixed-nulls",
        Some(&["part", "n"]),
        Some(column_expr!("n").is_not_null()),
        expected,
    )?;
    Ok(())
}

#[rstest::rstest]
#[case::and_both_conditions(
    Pred::and(
        column_expr!("number").gt(Expr::literal(4i64)),
        column_expr!("a_float").gt(Expr::literal(5.5)),
    ),
    table_for_numbers(vec![6])
)]
#[case::and_with_negation(
    Pred::and(
        column_expr!("number").gt(Expr::literal(4i64)),
        Pred::not(column_expr!("a_float").gt(Expr::literal(5.5))),
    ),
    table_for_numbers(vec![5])
)]
#[case::or_either_condition(
    Pred::or(
        column_expr!("number").gt(Expr::literal(4i64)),
        column_expr!("a_float").gt(Expr::literal(5.5)),
    ),
    table_for_numbers(vec![5, 6])
)]
#[case::or_with_negation(
    Pred::or(
        column_expr!("number").gt(Expr::literal(4i64)),
        Pred::not(column_expr!("a_float").gt(Expr::literal(5.5))),
    ),
    table_for_numbers(vec![1, 2, 3, 4, 5, 6])
)]
fn and_or_predicates(
    #[case] pred: Pred,
    #[case] expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    read_table_data(
        "./tests/data/basic_partitioned",
        Some(&["a_float", "number"]),
        Some(pred),
        expected,
    )?;
    Ok(())
}

#[rstest::rstest]
#[case::not_and_both_conditions(
    Pred::not(Pred::and(
        column_expr!("number").gt(Expr::literal(4i64)),
        column_expr!("a_float").gt(Expr::literal(5.5)),
    )),
    table_for_numbers(vec![1, 2, 3, 4, 5])
)]
#[case::not_and_with_negation(
    Pred::not(Pred::and(
        column_expr!("number").gt(Expr::literal(4i64)),
        Pred::not(column_expr!("a_float").gt(Expr::literal(5.5))),
    )),
    table_for_numbers(vec![1, 2, 3, 4, 6])
)]
#[case::not_or_either_condition(
    Pred::not(Pred::or(
        column_expr!("number").gt(Expr::literal(4i64)),
        column_expr!("a_float").gt(Expr::literal(5.5)),
    )),
    table_for_numbers(vec![1, 2, 3, 4])
)]
#[case::not_or_with_negation(
    Pred::not(Pred::or(
        column_expr!("number").gt(Expr::literal(4i64)),
        Pred::not(column_expr!("a_float").gt(Expr::literal(5.5))),
    )),
    vec![]
)]
fn not_and_or_predicates(
    #[case] pred: Pred,
    #[case] expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    read_table_data(
        "./tests/data/basic_partitioned",
        Some(&["a_float", "number"]),
        Some(pred),
        expected,
    )?;
    Ok(())
}

#[rstest::rstest]
#[case::literal_false(Pred::literal(false), table_for_numbers(vec![]))]
#[case::and_with_literal_false(
    Pred::and(column_pred!("number"), Pred::literal(false)),
    table_for_numbers(vec![])
)]
#[case::literal_true(
    Pred::literal(true),
    table_for_numbers(vec![1, 2, 3, 4, 5, 6])
)]
#[case::from_literal_expr(
    Pred::from_expr(Expr::literal(3i64)),
    table_for_numbers(vec![1, 2, 3, 4, 5, 6])
)]
#[case::distinct_value(
    column_expr!("number").distinct(Expr::literal(3i64)),
    table_for_numbers(vec![1, 2, 4, 5, 6])
)]
#[case::distinct_null(
    column_expr!("number").distinct(Expr::null_literal(DataType::LONG)),
    table_for_numbers(vec![1, 2, 3, 4, 5, 6])
)]
#[case::not_distinct_value(
    Pred::not(column_expr!("number").distinct(Expr::literal(3i64))),
    table_for_numbers(vec![3])
)]
#[case::not_distinct_null(
    Pred::not(column_expr!("number").distinct(Expr::null_literal(DataType::LONG))),
    table_for_numbers(vec![])
)]
#[case::gt_empty_struct(
    column_expr!("number").gt(Expr::struct_from(Vec::<ExpressionRef>::new())),
    table_for_numbers(vec![1, 2, 3, 4, 5, 6])
)]
#[case::not_gt_empty_struct(
    Pred::not(column_expr!("number").gt(Expr::struct_from(Vec::<ExpressionRef>::new()))),
    table_for_numbers(vec![1, 2, 3, 4, 5, 6])
)]
fn invalid_skips_none_predicates(
    #[case] pred: Pred,
    #[case] expected: Vec<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    read_table_data(
        "./tests/data/basic_partitioned",
        Some(&["a_float", "number"]),
        Some(pred),
        expected,
    )?;
    Ok(())
}

#[test]
fn with_predicate_and_removes() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+-------+",
        "| value |",
        "+-------+",
        "| 1     |",
        "| 2     |",
        "| 3     |",
        "| 4     |",
        "| 5     |",
        "| 6     |",
        "| 7     |",
        "| 8     |",
        "+-------+",
    ];
    read_table_data_str(
        "./tests/data/table-with-dv-small/",
        None,
        Some(Pred::gt(column_expr!("value"), Expr::literal(3))),
        expected,
    )?;
    Ok(())
}

#[tokio::test]
async fn predicate_on_non_nullable_partition_column() -> Result<(), Box<dyn std::error::Error>> {
    // Test for https://github.com/delta-io/delta-kernel-rs/issues/698
    let batch = generate_batch(vec![("val", vec!["a", "b", "c"].into_array())])?;

    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";
    let actions = [
        r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#.to_string(),
        r#"{"commitInfo":{"timestamp":1587968586154,"operation":"WRITE","operationParameters":{"mode":"ErrorIfExists","partitionBy":"[\"id\"]"},"isBlindAppend":true}}"#.to_string(),
        r#"{"metaData":{"id":"5fba94ed-9794-4965-ba6e-6ee3c0d22af9","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"id\",\"type\":\"integer\",\"nullable\":false,\"metadata\":{}},{\"name\":\"val\",\"type\":\"string\",\"nullable\":false,\"metadata\":{}}]}","partitionColumns":["id"],"configuration":{},"createdTime":1587968585495}}"#.to_string(),
        format!(r#"{{"add":{{"path":"id=1/{PARQUET_FILE1}","partitionValues":{{"id":"1"}},"size":0,"modificationTime":1587968586000,"dataChange":true, "stats":"{{\"numRecords\":3,\"nullCount\":{{\"val\":0}},\"minValues\":{{\"val\":\"a\"}},\"maxValues\":{{\"val\":\"c\"}}}}"}}}}"#),
        format!(r#"{{"add":{{"path":"id=2/{PARQUET_FILE2}","partitionValues":{{"id":"2"}},"size":0,"modificationTime":1587968586000,"dataChange":true, "stats":"{{\"numRecords\":3,\"nullCount\":{{\"val\":0}},\"minValues\":{{\"val\":\"a\"}},\"maxValues\":{{\"val\":\"c\"}}}}"}}}}"#),
    ];

    add_commit(table_root, storage.as_ref(), 0, actions.iter().join("\n")).await?;
    storage
        .put(
            &Path::from("id=1").join(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;
    storage
        .put(
            &Path::from("id=2").join(PARQUET_FILE2),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;

    let predicate = Pred::eq(column_expr!("id"), Expr::literal(2));
    let scan = snapshot
        .scan_builder()
        .with_predicate(Arc::new(predicate))
        .build()?;

    let stream = scan.execute(engine)?;

    let mut files_scanned = 0;
    for engine_data in stream {
        let mut result_batch = into_record_batch(engine_data?);
        let _ = result_batch.remove_column(result_batch.schema().index_of("id")?);
        assert_eq!(&batch, &result_batch);
        files_scanned += 1;
    }
    assert_eq!(1, files_scanned);
    Ok(())
}

#[tokio::test]
async fn predicate_on_non_nullable_column_missing_stats() -> Result<(), Box<dyn std::error::Error>>
{
    let batch_1 = generate_batch(vec![("val", vec!["a", "b", "c"].into_array())])?;
    let batch_2 = generate_batch(vec![("val", vec!["d", "e", "f"].into_array())])?;

    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";
    let actions = [
        r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#.to_string(),
        r#"{"commitInfo":{"timestamp":1587968586154,"operation":"WRITE","operationParameters":{"mode":"ErrorIfExists","partitionBy":"[]"},"isBlindAppend":true}}"#.to_string(),
        r#"{"metaData":{"id":"5fba94ed-9794-4965-ba6e-6ee3c0d22af9","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"val\",\"type\":\"string\",\"nullable\":false,\"metadata\":{}}]}","partitionColumns":[],"configuration":{},"createdTime":1587968585495}}"#.to_string(),
        // Add one file with stats, one file without
        format!(r#"{{"add":{{"path":"{PARQUET_FILE1}","partitionValues":{{}},"size":0,"modificationTime":1587968586000,"dataChange":true, "stats":"{{\"numRecords\":3,\"nullCount\":{{\"val\":0}},\"minValues\":{{\"val\":\"a\"}},\"maxValues\":{{\"val\":\"c\"}}}}"}}}}"#),
        format!(r#"{{"add":{{"path":"{PARQUET_FILE2}","partitionValues":{{}},"size":0,"modificationTime":1587968586000,"dataChange":true, "stats":"{{\"numRecords\":3,\"nullCount\":{{}},\"minValues\":{{}},\"maxValues\":{{}}}}"}}}}"#),
    ];

    // Disable writing Parquet statistics so these cannot be used for pruning row groups
    let writer_props = WriterProperties::builder()
        .set_statistics_enabled(EnabledStatistics::None)
        .build();

    add_commit(table_root, storage.as_ref(), 0, actions.iter().join("\n")).await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes_with_props(&batch_1, writer_props.clone()).into(),
        )
        .await?;
    storage
        .put(
            &Path::from(PARQUET_FILE2),
            record_batch_to_bytes_with_props(&batch_2, writer_props).into(),
        )
        .await?;

    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;

    let predicate = Pred::eq(column_expr!("val"), Expr::literal("g"));
    let scan = snapshot
        .scan_builder()
        .with_predicate(Arc::new(predicate))
        .build()?;

    let stream = scan.execute(engine)?;

    let mut files_scanned = 0;
    for engine_data in stream {
        let result_batch = into_record_batch(engine_data?);
        assert_eq!(&batch_2, &result_batch);
        files_scanned += 1;
    }
    // One file is scanned as stats are missing so we don't know the predicate isn't satisfied
    assert_eq!(1, files_scanned);

    Ok(())
}

#[test]
fn short_dv() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+----+-------+--------------------------+---------------------+",
        "| id | value | timestamp                | rand                |",
        "+----+-------+--------------------------+---------------------+",
        "| 3  | 3     | 2023-05-31T18:58:33.633Z | 0.7918174793484931  |",
        "| 4  | 4     | 2023-05-31T18:58:33.633Z | 0.9281049271981882  |",
        "| 5  | 5     | 2023-05-31T18:58:33.633Z | 0.27796520310701633 |",
        "| 6  | 6     | 2023-05-31T18:58:33.633Z | 0.15263801464228832 |",
        "| 7  | 7     | 2023-05-31T18:58:33.633Z | 0.1981143710215575  |",
        "| 8  | 8     | 2023-05-31T18:58:33.633Z | 0.3069439236599195  |",
        "| 9  | 9     | 2023-05-31T18:58:33.633Z | 0.5175919190815845  |",
        "+----+-------+--------------------------+---------------------+",
    ];
    read_table_data_str("./tests/data/with-short-dv/", None, None, expected)?;
    Ok(())
}

#[test]
fn basic_decimal() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+----------------+---------+--------------+------------------------+",
        "| part           | col1    | col2         | col3                   |",
        "+----------------+---------+--------------+------------------------+",
        "| -2342342.23423 | -999.99 | -99999.99999 | -9999999999.9999999999 |",
        "| 0.00004        | 0.00    | 0.00000      | 0.0000000000           |",
        "| 234.00000      | 1.00    | 2.00000      | 3.0000000000           |",
        "| 2342222.23454  | 111.11  | 22222.22222  | 3333333333.3333333333  |",
        "+----------------+---------+--------------+------------------------+",
    ];
    read_table_data_str("./tests/data/basic-decimal-table/", None, None, expected)?;
    Ok(())
}

#[test]
fn timestamp_ntz() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+----+----------------------------+----------------------------+",
        "| id | tsNtz                      | tsNtzPartition             |",
        "+----+----------------------------+----------------------------+",
        "| 0  | 2021-11-18T02:30:00.123456 | 2021-11-18T02:30:00.123456 |",
        "| 1  | 2013-07-05T17:01:00.123456 | 2021-11-18T02:30:00.123456 |",
        "| 2  |                            | 2021-11-18T02:30:00.123456 |",
        "| 3  | 2021-11-18T02:30:00.123456 | 2013-07-05T17:01:00.123456 |",
        "| 4  | 2013-07-05T17:01:00.123456 | 2013-07-05T17:01:00.123456 |",
        "| 5  |                            | 2013-07-05T17:01:00.123456 |",
        "| 6  | 2021-11-18T02:30:00.123456 |                            |",
        "| 7  | 2013-07-05T17:01:00.123456 |                            |",
        "| 8  |                            |                            |",
        "+----+----------------------------+----------------------------+",
    ];
    read_table_data_str(
        "./tests/data/data-reader-timestamp_ntz/",
        None,
        None,
        expected,
    )?;
    Ok(())
}

#[test]
fn type_widening_basic() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+---------------------+---------------------+--------------------+----------------+----------------+----------------+----------------------------+",
        "| byte_long           | int_long            | float_double       | byte_double    | short_double   | int_double     | date_timestamp_ntz         |",
        "+---------------------+---------------------+--------------------+----------------+----------------+----------------+----------------------------+",
        "| 1                   | 2                   | 3.4000000953674316 | 5.0            | 6.0            | 7.0            | 2024-09-09T00:00:00        |",
        "| 9223372036854775807 | 9223372036854775807 | 1.234567890123     | 1.234567890123 | 1.234567890123 | 1.234567890123 | 2024-09-09T12:34:56.123456 |",
        "+---------------------+---------------------+--------------------+----------------+----------------+----------------+----------------------------+",
   ];
    let select_cols: Option<&[&str]> = Some(&[
        "byte_long",
        "int_long",
        "float_double",
        "byte_double",
        "short_double",
        "int_double",
        "date_timestamp_ntz",
    ]);

    read_table_data_str("./tests/data/type-widening/", select_cols, None, expected)
}

#[test]
fn type_widening_decimal() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+----------------------------+-------------------------------+--------------+---------------+--------------+----------------------+",
        "| decimal_decimal_same_scale | decimal_decimal_greater_scale | byte_decimal | short_decimal | int_decimal  | long_decimal         |",
        "+----------------------------+-------------------------------+--------------+---------------+--------------+----------------------+",
        "| 123.45                     | 67.89000                      | 1.0          | 2.0           | 3.0          | 4.0                  |",
        "| 12345678901234.56          | 12345678901.23456             | 123.4        | 12345.6       | 1234567890.1 | 123456789012345678.9 |",
        "+----------------------------+-------------------------------+--------------+---------------+--------------+----------------------+",
    ];
    let select_cols: Option<&[&str]> = Some(&[
        "decimal_decimal_same_scale",
        "decimal_decimal_greater_scale",
        "byte_decimal",
        "short_decimal",
        "int_decimal",
        "long_decimal",
    ]);
    read_table_data_str("./tests/data/type-widening/", select_cols, None, expected)
}

// Verify that predicates over invalid/missing columns do not cause skipping.
#[test]
fn predicate_references_invalid_missing_column() -> Result<(), Box<dyn std::error::Error>> {
    // Attempted skipping over a logically valid but physically missing column. We should be able to
    // skip the data file because the missing column is inferred to be all-null.
    //
    // WARNING: https://github.com/delta-io/delta-kernel-rs/issues/434 -- currently disabled.
    //
    //let expected = vec![
    //    "+--------+",
    //    "| chrono |",
    //    "+--------+",
    //    "+--------+",
    //];
    let columns = &["chrono", "missing"];
    let expected = vec![
        "+-------------------------------------------------------------------------------------------+---------+",
        "| chrono                                                                                    | missing |",
        "+-------------------------------------------------------------------------------------------+---------+",
        "| {date32: 1971-01-01, timestamp: 1970-02-01T08:00:00Z, timestamp_ntz: 1970-01-02T00:00:00} |         |",
        "| {date32: 1971-01-02, timestamp: 1970-02-01T09:00:00Z, timestamp_ntz: 1970-01-02T00:01:00} |         |",
        "| {date32: 1971-01-03, timestamp: 1970-02-01T10:00:00Z, timestamp_ntz: 1970-01-02T00:02:00} |         |",
        "| {date32: 1971-01-04, timestamp: 1970-02-01T11:00:00Z, timestamp_ntz: 1970-01-02T00:03:00} |         |",
        "| {date32: 1971-01-05, timestamp: 1970-02-01T12:00:00Z, timestamp_ntz: 1970-01-02T00:04:00} |         |",
        "+-------------------------------------------------------------------------------------------+---------+",
    ];
    let predicate = column_expr!("missing").lt(Expr::literal(10i64));
    read_table_data_str(
        "./tests/data/parquet_row_group_skipping/",
        Some(columns),
        Some(predicate),
        expected,
    )?;

    // Attempted skipping over an invalid (logically missing) column. Ideally this should throw a
    // query error, but at a minimum it should not cause incorrect data skipping.
    let expected = vec![
        "+-------------------------------------------------------------------------------------------+",
        "| chrono                                                                                    |",
        "+-------------------------------------------------------------------------------------------+",
        "| {date32: 1971-01-01, timestamp: 1970-02-01T08:00:00Z, timestamp_ntz: 1970-01-02T00:00:00} |",
        "| {date32: 1971-01-02, timestamp: 1970-02-01T09:00:00Z, timestamp_ntz: 1970-01-02T00:01:00} |",
        "| {date32: 1971-01-03, timestamp: 1970-02-01T10:00:00Z, timestamp_ntz: 1970-01-02T00:02:00} |",
        "| {date32: 1971-01-04, timestamp: 1970-02-01T11:00:00Z, timestamp_ntz: 1970-01-02T00:03:00} |",
        "| {date32: 1971-01-05, timestamp: 1970-02-01T12:00:00Z, timestamp_ntz: 1970-01-02T00:04:00} |",
        "+-------------------------------------------------------------------------------------------+",
    ];
    let predicate = column_expr!("invalid").lt(Expr::literal(10));
    read_table_data_str(
        "./tests/data/parquet_row_group_skipping/",
        Some(columns),
        Some(predicate),
        expected,
    )
    .expect_err("unknown column");
    Ok(())
}

// Note: This test is disabled for windows because it creates a directory with name
// `time=1971-07-22T03:06:40.000000Z`. This is disallowed in windows due to having a `:` in
// the name.
#[cfg(not(windows))]
#[test]
fn timestamp_partitioned_table() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+----+-----+---+----------------------+",
        "| id | x   | s | time                 |",
        "+----+-----+---+----------------------+",
        "| 1  | 0.5 |   | 1971-07-22T03:06:40Z |",
        "+----+-----+---+----------------------+",
    ];
    let test_name = "timestamp-partitioned-table";
    let test_dir = load_test_data("./tests/data", test_name).unwrap();
    let test_path = test_dir.path().join(test_name);
    read_table_data_str(test_path.to_str().unwrap(), None, None, expected)
}

#[test]
fn compacted_log_files_table() -> Result<(), Box<dyn std::error::Error>> {
    let expected = vec![
        "+----+--------------------+",
        "| id | comment            |",
        "+----+--------------------+",
        "| 0  | new                |",
        "| 1  | after-large-delete |",
        "| 2  |                    |",
        "| 10 | merge1-insert      |",
        "| 12 | merge2-insert      |",
        "+----+--------------------+",
    ];
    let test_name = "compacted-log-files-table";
    let test_dir = load_test_data("./tests/data", test_name).unwrap();
    let test_path = test_dir.path().join(test_name);
    read_table_data_str(test_path.to_str().unwrap(), None, None, expected)
}

#[test]
fn unshredded_variant_table() -> Result<(), Box<dyn std::error::Error>> {
    let expected = include!("../data/unshredded-variant.expected.in");
    let test_name = "unshredded-variant";
    let test_dir = load_test_data("./tests/data", test_name).unwrap();
    let test_path = test_dir.path().join(test_name);
    read_table_data_str(test_path.to_str().unwrap(), None, None, expected)
}

#[tokio::test]
async fn test_row_index_metadata_column() -> Result<(), Box<dyn std::error::Error>> {
    // Setup up an in-memory table with different numbers of rows in each file
    let batch1 = generate_batch(vec![
        ("id", vec![1i32, 2, 3, 4, 5].into_array()),
        ("value", vec!["a", "b", "c", "d", "e"].into_array()),
    ])?;
    let batch2 = generate_batch(vec![
        ("id", vec![10i32, 20, 30].into_array()),
        ("value", vec!["x", "y", "z"].into_array()),
    ])?;
    let batch3 = generate_batch(vec![
        ("id", vec![100i32, 200, 300, 400].into_array()),
        ("value", vec!["p", "q", "r", "s"].into_array()),
    ])?;

    let file_size1 = record_batch_to_bytes(&batch1).len() as u64;
    let file_size2 = record_batch_to_bytes(&batch2).len() as u64;
    let file_size3 = record_batch_to_bytes(&batch3).len() as u64;
    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";
    add_commit(
        table_root,
        storage.as_ref(),
        0,
        actions_to_string(vec![
            TestAction::Metadata,
            TestAction::AddWithSize(PARQUET_FILE1.to_string(), file_size1),
            TestAction::AddWithSize(PARQUET_FILE2.to_string(), file_size2),
            TestAction::AddWithSize(PARQUET_FILE3.to_string(), file_size3),
        ]),
    )
    .await?;

    for (parquet_file, batch) in [
        (PARQUET_FILE1, &batch1),
        (PARQUET_FILE2, &batch2),
        (PARQUET_FILE3, &batch3),
    ] {
        storage
            .put(
                &Path::from(parquet_file),
                record_batch_to_bytes(batch).into(),
            )
            .await?;
    }

    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());

    // Create a schema that includes a row index metadata column
    let schema = Arc::new(StructType::try_new([
        StructField::nullable("id", DataType::INTEGER),
        StructField::create_metadata_column("row_index", MetadataColumnSpec::RowIndex),
        StructField::nullable("value", DataType::STRING),
    ])?);

    let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;
    let scan = snapshot.scan_builder().with_schema(schema).build()?;

    let mut file_count = 0;
    let expected_row_counts = [5, 3, 4];
    let stream = scan.execute(engine.clone())?;

    for data in stream {
        let batch = into_record_batch(data?);
        file_count += 1;

        // Verify the schema structure
        assert_eq!(batch.num_columns(), 3, "Expected 3 columns in the batch");
        assert_eq!(
            batch.schema().field(0).name(),
            "id",
            "First column should be 'id'"
        );
        assert_eq!(
            batch.schema().field(1).name(),
            "row_index",
            "Second column should be 'row_index'"
        );
        assert_eq!(
            batch.schema().field(2).name(),
            "value",
            "Third column should be 'value'"
        );

        // Each file should have row indexes starting from 0 (file-local indexing)
        let row_index_array = batch.column(1).as_primitive::<Int64Type>();
        let expected_values: Vec<i64> = (0..batch.num_rows() as i64).collect();
        assert_eq!(
            row_index_array.values().to_vec(),
            expected_values,
            "Row index values incorrect for file {} (expected {} rows)",
            file_count,
            expected_row_counts[file_count - 1]
        );
    }

    assert_eq!(file_count, 3, "Expected to scan 3 files");
    Ok(())
}

#[tokio::test]
async fn test_file_path_metadata_column() -> Result<(), Box<dyn std::error::Error>> {
    use delta_kernel::arrow::array::{Array, StringArray};

    // Set up an in-memory table with multiple data files
    let batch1 = generate_batch(vec![
        ("id", vec![1i32, 2, 3].into_array()),
        ("value", vec!["a", "b", "c"].into_array()),
    ])?;
    let batch2 = generate_batch(vec![
        ("id", vec![10i32, 20].into_array()),
        ("value", vec!["x", "y"].into_array()),
    ])?;

    let file_size1 = record_batch_to_bytes(&batch1).len() as u64;
    let file_size2 = record_batch_to_bytes(&batch2).len() as u64;
    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";
    add_commit(
        table_root,
        storage.as_ref(),
        0,
        actions_to_string(vec![
            TestAction::Metadata,
            TestAction::AddWithSize(PARQUET_FILE1.to_string(), file_size1),
            TestAction::AddWithSize(PARQUET_FILE2.to_string(), file_size2),
        ]),
    )
    .await?;

    for (parquet_file, batch) in [(PARQUET_FILE1, &batch1), (PARQUET_FILE2, &batch2)] {
        storage
            .put(
                &Path::from(parquet_file),
                record_batch_to_bytes(batch).into(),
            )
            .await?;
    }

    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());

    // Create a schema that includes the file path metadata column
    let schema = Arc::new(StructType::try_new([
        StructField::nullable("id", DataType::INTEGER),
        StructField::create_metadata_column("_file", MetadataColumnSpec::FilePath),
        StructField::nullable("value", DataType::STRING),
    ])?);

    let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;
    let scan = snapshot.scan_builder().with_schema(schema).build()?;

    let mut file_count = 0;
    let expected_files = [PARQUET_FILE1, PARQUET_FILE2];
    let expected_row_counts = [3, 2];
    let stream = scan.execute(engine.clone())?;

    for data in stream {
        let batch = into_record_batch(data?);

        // Verify the schema structure
        assert_eq!(batch.num_columns(), 3, "Expected 3 columns in the batch");
        assert_eq!(
            batch.schema().field(0).name(),
            "id",
            "First column should be 'id'"
        );
        assert_eq!(
            batch.schema().field(1).name(),
            "_file",
            "Second column should be '_file'"
        );
        assert_eq!(
            batch.schema().field(2).name(),
            "value",
            "Third column should be 'value'"
        );

        // Verify the file path column contains the expected file name
        let file_path_array = batch.column(1);
        let expected_file_name = expected_files[file_count];
        let expected_path = format!("{table_root}{expected_file_name}");

        // The file path array should be a plain StringArray with the path repeated for each row.
        let string_array = file_path_array
            .as_any()
            .downcast_ref::<StringArray>()
            .expect("File path column should be a StringArray");

        assert_eq!(
            string_array.len(),
            expected_row_counts[file_count],
            "File {} should have {} rows",
            expected_file_name,
            expected_row_counts[file_count]
        );
        assert!(
            string_array
                .iter()
                .all(|v| v == Some(expected_path.as_str())),
            "All rows should contain file path '{expected_path}'"
        );

        file_count += 1;
    }

    assert_eq!(file_count, 2, "Expected to scan 2 files");
    Ok(())
}

#[tokio::test]
async fn test_unsupported_metadata_columns() -> Result<(), Box<dyn std::error::Error>> {
    // Prepare an in-memory table with some data
    let batch = generate_simple_batch()?;
    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";
    add_commit(
        table_root,
        storage.as_ref(),
        0,
        actions_to_string(vec![
            TestAction::Metadata,
            TestAction::Add(PARQUET_FILE1.to_string()),
        ]),
    )
    .await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());

    // Test that unsupported metadata columns fail with appropriate errors
    let test_cases = [
        (
            "row_id",
            MetadataColumnSpec::RowId,
            "Row ids are not enabled on this table",
        ),
        (
            "row_commit_version",
            MetadataColumnSpec::RowCommitVersion,
            "Row commit versions not supported",
        ),
    ];

    for (column_name, metadata_spec, error_text) in test_cases {
        let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;
        let schema = Arc::new(StructType::try_new([
            StructField::nullable("id", DataType::INTEGER),
            StructField::create_metadata_column(column_name, metadata_spec),
        ])?);

        let scan_err = snapshot
            .scan_builder()
            .with_schema(schema)
            .build()
            .unwrap_err();
        let error_msg = scan_err.to_string();
        assert!(
            error_msg.contains(error_text),
            "Expected {error_msg} to contain {error_text}"
        );
    }

    Ok(())
}

#[tokio::test]
async fn test_invalid_files_are_skipped() -> Result<(), Box<dyn std::error::Error>> {
    let batch = generate_simple_batch()?;
    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";
    add_commit(
        table_root,
        storage.as_ref(),
        0,
        actions_to_string(vec![
            TestAction::Metadata,
            TestAction::Add(PARQUET_FILE1.to_string()),
            TestAction::Add(PARQUET_FILE2.to_string()),
        ]),
    )
    .await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;
    storage
        .put(
            &Path::from(PARQUET_FILE2),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());

    let invalid_files = [
        "_delta_log/0.zip",
        "_delta_log/_copy_into_log/0.zip",
        "_delta_log/_ignore_me/00000000000000000000.json",
        "_delta_log/_and_me/00000000000000000000.checkpoint.parquet",
        "_delta_log/02184.json",
        "_delta_log/0x000000000000000000.checkpoint.parquet",
        "00000000000000000000.json",
        "_delta_log/_staged_commits/_staged_commits/00000000000000000000.3a0d65cd-4056-49b8-937b-95f9e3ee90e5.json",
        "_delta_log/my_random_dir/_staged_commits/00000000000000000000.3a0d65cd-4056-49b8-937b-95f9e3ee90e5.json",
        "_delta_log/my_random_dir/_delta_log/_staged_commits/00000000000000000000.3a0d65cd-4056-49b8-937b-95f9e3ee90e5.json",
        "_delta_log/_delta_log/00000000000000000000.json",
        "_delta_log/_delta_log/00000000000000000000.checkpoint.parquet",
        "_delta_log/something/_delta_log/00000000000000000000.crc",
        "_delta_log/something/_delta_log/00000000000000000000.json",
        "_delta_log/something/_delta_log/00000000000000000000.checkpoint.parquet",
    ];

    fn get_file_path_for_test(path: &ParsedLogPath) -> &str {
        &path.location.location.as_str()[10..]
    }

    fn ensure_segment_does_not_contain(invalid_files: &[&str], segment: &LogSegment) {
        assert!(
            !segment.listed.ascending_commit_files.iter().any(|p| {
                let test_path = get_file_path_for_test(p);
                invalid_files.contains(&test_path)
            }),
            "ascending_commit_files contained invalid file"
        );
        assert!(
            !segment.listed.ascending_compaction_files.iter().any(|p| {
                let test_path = get_file_path_for_test(p);
                invalid_files.contains(&test_path)
            }),
            "ascending_compaction_files contained invalid file"
        );
        assert!(
            !segment.listed.checkpoint_parts.iter().any(|p| {
                let test_path = get_file_path_for_test(p);
                invalid_files.contains(&test_path)
            }),
            "checkpoint_parts contained invalid file"
        );
        if let Some(ref crc) = segment.listed.latest_crc_file {
            assert!(
                !invalid_files.contains(&get_file_path_for_test(crc)),
                "Latest crc contained invalid file"
            );
        }
        if let Some(ref latest_commit) = segment.listed.latest_commit_file {
            assert!(
                !invalid_files.contains(&get_file_path_for_test(latest_commit)),
                "Latest commit contained invalid file"
            );
        }
    }

    for invalid_file in invalid_files.iter() {
        let invalid_path = Path::from(*invalid_file);
        storage.put(&invalid_path, vec![1u8].into()).await?;
        let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;
        ensure_segment_does_not_contain(&invalid_files, snapshot.log_segment());
        storage.delete(&invalid_path).await?;
    }

    // final test with _all_ the files we should ignore
    for invalid_file in invalid_files.iter() {
        let invalid_path = Path::from(*invalid_file);
        storage.put(&invalid_path, vec![1u8].into()).await?;
    }
    let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;
    ensure_segment_does_not_contain(&invalid_files, snapshot.log_segment());

    Ok(())
}

// Verifies data skipping works via stats_parsed across all checkpoint types.
// All tables have writeStatsAsStruct=true, writeStatsAsJson=false (struct stats only),
// schema (id: long, value: string), 5 rows (id 1-5), checkpoint at v5.
// Predicate id > 3 skips files where max(id) <= 3, returning only rows 4 and 5.
#[rstest::rstest]
#[test]
fn checkpoint_stats_skipping(
    #[values(
        "v1-single-part",
        "v1-multi-part",
        "v2-parquet-sidecars",
        "v2-json-sidecars",
        "v2-classic-parquet"
    )]
    checkpoint_type: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let table_path = format!("./tests/data/{checkpoint_type}-struct-stats-only/");
    let expected = vec![
        "+----+---------+",
        "| id | value   |",
        "+----+---------+",
        "| 4  | value_4 |",
        "| 5  | value_5 |",
        "+----+---------+",
    ];
    let predicate = column_expr!("id").gt(Expr::literal(3i64));
    read_table_data_str(&table_path, None, Some(predicate), expected)?;
    Ok(())
}

// Verifies ScanFile.stats handling for parsed-stats checkpoints. Tables have
// writeStatsAsStruct=true, writeStatsAsJson=false (no JSON stats in checkpoint),
// schema (id: long, value: string), 5 files with 1 row each, checkpoint at v5.
// Cross-product covers all five checkpoint variants against four stats option
// shapes: ScanFile.stats should be populated via the COALESCE/ToJson fallback
// when both `json=true` and `struct_stats=All` are set; otherwise null on these
// struct-stats-only checkpoints.
#[rstest::rstest]
#[case::default_json_only(StatsOptions::default(), false)]
#[case::all_both(StatsOptions::all(), true)]
#[case::all_struct_only(StatsOptions::all_struct(), false)]
#[case::none(StatsOptions::none(), false)]
fn struct_stats_surfaced_in_scan_file(
    #[values(
        "v1-single-part",
        "v1-multi-part",
        "v2-parquet-sidecars",
        "v2-json-sidecars",
        "v2-classic-parquet"
    )]
    checkpoint_type: &str,
    #[case] stats: StatsOptions,
    #[case] expect_json_stats: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let table_path = format!("./tests/data/{checkpoint_type}-struct-stats-only/");
    let path = std::fs::canonicalize(PathBuf::from(table_path))?;
    let url = url::Url::from_directory_path(path).unwrap();
    let engine = test_utils::create_default_engine(&url)?;

    let snapshot = Snapshot::builder_for(url).build(engine.as_ref())?;
    let scan = snapshot.scan_builder().with_stats(stats).build()?;

    let mut scan_files = vec![];
    for res in scan.scan_metadata(engine.as_ref())? {
        let scan_metadata = res?;
        scan_files = scan_metadata.visit_scan_files(scan_files, scan_metadata_callback)?;
    }

    assert_eq!(scan_files.len(), 5, "expected 5 files in checkpoint");
    for scan_file in &scan_files {
        if expect_json_stats {
            assert!(
                scan_file.stats.is_some(),
                "ScanFile.stats should be populated, path: {}",
                scan_file.path
            );
            assert_eq!(
                scan_file.stats.as_ref().unwrap().num_records,
                1,
                "each file has exactly 1 row, path: {}",
                scan_file.path
            );
        } else {
            assert!(
                scan_file.stats.is_none(),
                "ScanFile.stats should be None, path: {}",
                scan_file.path
            );
        }
    }
    Ok(())
}

// On a JSON-only table (no parsed-stats checkpoint), `has_stats_parsed` is
// false and the COALESCE branch is never selected, so `StatsOptions::all_struct`
// vs `StatsOptions::default` is a no-op for the `stats` JSON column: `add.stats`
// is read directly from the commit JSON either way.
#[rstest::rstest]
fn struct_stats_only_no_op_on_json_only_table(
    #[values(StatsOptions::default(), StatsOptions::all_struct())] stats: StatsOptions,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = std::fs::canonicalize(PathBuf::from("./tests/data/basic_partitioned/"))?;
    let url = url::Url::from_directory_path(path).unwrap();
    let engine = test_utils::create_default_engine(&url)?;

    let snapshot = Snapshot::builder_for(url).build(engine.as_ref())?;
    let scan = snapshot.scan_builder().with_stats(stats).build()?;

    let mut scan_files = vec![];
    for res in scan.scan_metadata(engine.as_ref())? {
        let scan_metadata = res?;
        scan_files = scan_metadata.visit_scan_files(scan_files, scan_metadata_callback)?;
    }

    assert!(!scan_files.is_empty());
    for scan_file in &scan_files {
        assert!(
            scan_file.stats.is_some(),
            "JSON commits populate stats from add.stats"
        );
    }
    Ok(())
}

// Confirms `stats_parsed` is still consumed by data skipping when only struct
// stats are requested (no JSON synthesis). Predicate `id > 3` should skip files
// where `max(id) <= 3`, returning rows 4 and 5 only. If `all_struct` accidentally
// disabled the stats_parsed read path, all 5 rows would come back.
#[rstest::rstest]
fn struct_stats_only_preserves_data_skipping(
    #[values(
        "v1-single-part",
        "v1-multi-part",
        "v2-parquet-sidecars",
        "v2-json-sidecars",
        "v2-classic-parquet"
    )]
    checkpoint_type: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let table_path = format!("./tests/data/{checkpoint_type}-struct-stats-only/");
    let path = std::fs::canonicalize(PathBuf::from(table_path))?;
    let url = url::Url::from_directory_path(path).unwrap();
    let engine = test_utils::create_default_engine(&url)?;
    let snapshot = Snapshot::builder_for(url).build(engine.as_ref())?;

    let predicate: PredicateRef = Arc::new(column_expr!("id").gt(Expr::literal(3i64)));
    let scan = snapshot
        .scan_builder()
        .with_stats(StatsOptions::all_struct())
        .with_predicate(predicate)
        .build()?;

    let mut scan_files = vec![];
    for res in scan.scan_metadata(engine.as_ref())? {
        let scan_metadata = res?;
        scan_files = scan_metadata.visit_scan_files(scan_files, scan_metadata_callback)?;
    }

    assert_eq!(
        scan_files.len(),
        2,
        "data skipping via stats_parsed should leave only 2 files (id=4, id=5)"
    );
    for scan_file in &scan_files {
        assert!(
            scan_file.stats.is_none(),
            "ScanFile.stats must remain null when synthesis is skipped, path: {}",
            scan_file.path
        );
    }
    Ok(())
}

// Multi-part V1 checkpoint with partitionValues_parsed on a partitioned table.
// Schema: (id: long, value: string, part: int) partitioned by part.
// Each commit inserts one row with part = i % 3 (parts 0, 1, 2).
#[test]
fn partition_values_parsed_skipping() -> Result<(), Box<dyn std::error::Error>> {
    // Predicate part = 0 should skip partitions 1 and 2, returning rows with part=0.
    // i % 3 == 0: i=3 -> (3, "value_3", 0)
    let expected = vec![
        "+----+---------+------+",
        "| id | value   | part |",
        "+----+---------+------+",
        "| 3  | value_3 | 0    |",
        "+----+---------+------+",
    ];
    let predicate = column_expr!("part").eq(Expr::literal(0i32));
    read_table_data_str(
        "./tests/data/v1-multi-part-partitioned-struct-stats-only/",
        None,
        Some(predicate),
        expected,
    )?;
    Ok(())
}

// In-memory test with crafted truncated JSON stats. Three files:
//   file 1: ts_col [1s, 2s]           -- max at ms boundary
//   file 2: ts_col [3s, 4.000500s]    -- JSON max truncated to 4.000s
//   file 3: ts_col [7s, 8s]           -- max at ms boundary
//
// Predicate `ts_col > 4_000_400us`:
//   file 1: max=2s << adjusted predicate (3_999_401) -> pruned (skipping works)
//   file 2: truncated max=4s > adjusted predicate (3_999_401) -> kept (truncation safe)
//   file 3: max=8s >> adjusted predicate -> kept
#[tokio::test]
async fn timestamp_max_stat_truncation_does_not_over_prune(
) -> Result<(), Box<dyn std::error::Error>> {
    let ts_metadata = "{\
        \"id\":\"test-ts-table\",\
        \"format\":{\"provider\":\"parquet\",\"options\":{}},\
        \"schemaString\":\"{\\\"type\\\":\\\"struct\\\",\\\"fields\\\":[\
            {\\\"name\\\":\\\"ts_col\\\",\\\"type\\\":\\\"timestamp\\\",\\\"nullable\\\":true,\\\"metadata\\\":{}}\
        ]}\",\
        \"partitionColumns\":[],\
        \"configuration\":{},\
        \"createdTime\":1700000000000\
    }";

    let ts_schema = Arc::new(ArrowSchema::new(vec![ArrowField::new(
        "ts_col",
        delta_kernel::arrow::datatypes::DataType::Timestamp(
            TimeUnit::Microsecond,
            Some("UTC".into()),
        ),
        true,
    )]));

    // file1: max at ms boundary, will be pruned
    let file1_stats = r#"{"numRecords":2,"nullCount":{"ts_col":0},"minValues":{"ts_col":"1970-01-01T00:00:01.000Z"},"maxValues":{"ts_col":"1970-01-01T00:00:02.000Z"}}"#;
    // file2: max truncated from 4.000500s to 4.000s -- truncation adjustment must keep this
    let file2_stats = r#"{"numRecords":2,"nullCount":{"ts_col":0},"minValues":{"ts_col":"1970-01-01T00:00:03.000Z"},"maxValues":{"ts_col":"1970-01-01T00:00:04.000Z"}}"#;
    // file3: max clearly above predicate
    let file3_stats = r#"{"numRecords":2,"nullCount":{"ts_col":0},"minValues":{"ts_col":"1970-01-01T00:00:07.000Z"},"maxValues":{"ts_col":"1970-01-01T00:00:08.000Z"}}"#;

    let batch1 = RecordBatch::try_new(
        ts_schema.clone(),
        vec![Arc::new(
            TimestampMicrosecondArray::from(vec![1_000_000i64, 2_000_000]).with_timezone("UTC"),
        )],
    )?;
    let batch2 = RecordBatch::try_new(
        ts_schema.clone(),
        vec![Arc::new(
            TimestampMicrosecondArray::from(vec![3_000_000i64, 4_000_500]).with_timezone("UTC"),
        )],
    )?;
    let batch3 = RecordBatch::try_new(
        ts_schema,
        vec![Arc::new(
            TimestampMicrosecondArray::from(vec![7_000_000i64, 8_000_000]).with_timezone("UTC"),
        )],
    )?;

    let file1_bytes = record_batch_to_bytes(&batch1);
    let file2_bytes = record_batch_to_bytes(&batch2);
    let file3_bytes = record_batch_to_bytes(&batch3);

    let storage = Arc::new(InMemory::new());
    let table_root = "memory:///";

    let make_add = |name: &str, size: usize, stats: &str| -> String {
        format!(
            "{{\"add\":{{\"path\":\"{name}\",\"partitionValues\":{{}},\"size\":{size},\
             \"modificationTime\":1700000000000,\"dataChange\":true,\
             \"stats\":\"{stats_escaped}\"}}}}",
            stats_escaped = stats.replace('"', "\\\""),
        )
    };

    let commit0 = format!(
        "{{\"protocol\":{{\"minReaderVersion\":1,\"minWriterVersion\":2}}}}\n\
         {{\"metaData\":{ts_metadata}}}\n\
         {}",
        make_add("file1.parquet", file1_bytes.len(), file1_stats)
    );
    add_commit(table_root, storage.as_ref(), 0, commit0).await?;
    add_commit(
        table_root,
        storage.as_ref(),
        1,
        make_add("file2.parquet", file2_bytes.len(), file2_stats),
    )
    .await?;
    add_commit(
        table_root,
        storage.as_ref(),
        2,
        make_add("file3.parquet", file3_bytes.len(), file3_stats),
    )
    .await?;

    storage
        .put(&Path::from("file1.parquet"), file1_bytes.into())
        .await?;
    storage
        .put(&Path::from("file2.parquet"), file2_bytes.into())
        .await?;
    storage
        .put(&Path::from("file3.parquet"), file3_bytes.into())
        .await?;

    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(table_root).build(engine.as_ref())?;

    let row_count = |predicate_us: i64| -> Result<usize, Box<dyn std::error::Error>> {
        let predicate = Arc::new(Pred::gt(
            column_expr!("ts_col"),
            Expr::literal(Scalar::Timestamp(predicate_us)),
        ));
        let scan = snapshot
            .clone()
            .scan_builder()
            .with_predicate(predicate)
            .build()?;
        let batches = read_scan(&scan, engine.clone())?;
        Ok(batches.iter().map(|b| b.num_rows()).sum())
    };

    // Mid-ms value (4.000400s): adjusted to 3_999_401
    //   file1 max=2s < 3_999_401 -> pruned; file2+3 kept (4 rows)
    assert_eq!(row_count(4_000_400)?, 4, "mid-ms: file2+file3 kept");

    // Exact ms boundary (4.000000s = truncated max of file2): adjusted to 3_999_001
    //   file1 max=2s < 3_999_001 -> pruned; file2 max=4s > 3_999_001 -> kept (4 rows)
    assert_eq!(
        row_count(4_000_000)?,
        4,
        "exact ms boundary: file2+file3 kept"
    );

    // 1us above ms boundary (4.000001s): adjusted to 3_999_002
    //   file1 pruned; file2 max=4s > 3_999_002 -> kept (4 rows)
    assert_eq!(row_count(4_000_001)?, 4, "1us above ms: file2+file3 kept");

    // 998us above ms boundary (4.000998s): adjusted to 3_999_999
    //   file2 max=4s > 3_999_999 -> kept (just not prunable)
    assert_eq!(
        row_count(4_000_998)?,
        4,
        "just not prunable: file2+file3 kept"
    );

    // 999us above ms boundary (4.000999s): adjusted to 4_000_000
    //   file2 max=4s == 4_000_000 -> NOT strictly greater -> pruned (just prunable)
    assert_eq!(row_count(4_000_999)?, 2, "just prunable: only file3 kept");

    // Next ms boundary (4.001000s): adjusted to 4_000_001
    //   file2 max=4s < 4_000_001 -> pruned (2 rows)
    assert_eq!(
        row_count(4_001_000)?,
        2,
        "next ms boundary: only file3 kept"
    );

    Ok(())
}

// Regression test for https://github.com/delta-io/delta-kernel-rs/issues/739
// Void columns should be present in scan results as all-null columns.
#[tokio::test]
async fn read_table_with_void_column() -> Result<(), Box<dyn std::error::Error>> {
    // Parquet batch has only the non-void column (parquet cannot represent void)
    let batch = generate_batch(vec![("id", vec![1, 2, 3].into_array())])?;

    let storage = Arc::new(InMemory::new());
    let actions = [
        r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#.to_string(),
        r#"{"commitInfo":{"timestamp":1587968586154,"operation":"WRITE","operationParameters":{"mode":"ErrorIfExists","partitionBy":"[]"},"isBlindAppend":true}}"#.to_string(),
        r#"{"metaData":{"id":"test-void","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"id\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"void_col\",\"type\":\"void\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"configuration":{},"createdTime":1587968585495}}"#.to_string(),
        format!(r#"{{"add":{{"path":"{PARQUET_FILE1}","partitionValues":{{}},"size":0,"modificationTime":1587968586000,"dataChange":true}}}}"#),
    ];

    add_commit("memory:///", storage.as_ref(), 0, actions.iter().join("\n")).await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let location = Url::parse("memory:///")?;
    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(location).build(engine.as_ref())?;

    // The table schema has both "id" and "void_col"
    assert!(snapshot.schema().field("void_col").is_some());
    assert!(snapshot.schema().field("id").is_some());

    let scan = snapshot.scan_builder().build()?;

    // The scan's logical schema should contain the void column (returned as null)
    let logical_schema = scan.logical_schema();
    assert!(logical_schema.field("void_col").is_some());
    assert!(logical_schema.field("id").is_some());
    assert_eq!(logical_schema.fields().count(), 2);

    // Execute the scan and verify void column appears as all-null
    let batches = read_scan(&scan, engine)?;
    assert_eq!(batches.len(), 1);
    assert_eq!(batches[0].num_columns(), 2);
    assert_eq!(batches[0].schema().field(0).name(), "id");
    assert_eq!(batches[0].schema().field(1).name(), "void_col");
    assert_eq!(batches[0].num_rows(), 3);
    // void column should be Arrow Null type
    assert_eq!(
        *batches[0].schema().field(1).data_type(),
        ArrowDataType::Null
    );

    Ok(())
}

// End-to-end tests using a Spark-written Delta table with real truncated JSON stats.
// Table has three files:
//   file 1: id=[1,2], ts_col=[1s, 2s]           -- max at ms boundary
//   file 2: id=[3,4], ts_col=[3s, 4.000500s]    -- max truncated to 4.000s in JSON stats
//   file 3: id=[5,6], ts_col=[7s, 8s]           -- max at ms boundary
//
// Predicate value 4.000400s sits between the truncated max (4.000s) and actual max
// (4.000500s) of file 2, exercising the truncation adjustment.

// GT: file1 pruned (max=2s < adjusted 3.999401s), file2+3 kept
#[test]
fn timestamp_truncation_real_table_gt() -> Result<(), Box<dyn std::error::Error>> {
    read_table_data_str(
        "./tests/data/timestamp-truncation-stats",
        None,
        Some(Pred::gt(
            column_expr!("ts_col"),
            Expr::literal(Scalar::Timestamp(4_000_400)),
        )),
        vec![
            "+----+-----------------------------+",
            "| id | ts_col                      |",
            "+----+-----------------------------+",
            "| 3  | 1970-01-01T00:00:03Z        |",
            "| 4  | 1970-01-01T00:00:04.000500Z |",
            "| 5  | 1970-01-01T00:00:07Z        |",
            "| 6  | 1970-01-01T00:00:08Z        |",
            "+----+-----------------------------+",
        ],
    )
}

// Verify that an explicit projection including a void column returns it as null.
#[tokio::test]
async fn explicit_projection_with_void_column_returns_nulls(
) -> Result<(), Box<dyn std::error::Error>> {
    let batch = generate_batch(vec![("id", vec![1, 2, 3].into_array())])?;

    let storage = Arc::new(InMemory::new());
    let actions = [
        r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#.to_string(),
        r#"{"commitInfo":{"timestamp":1587968586154,"operation":"WRITE","operationParameters":{"mode":"ErrorIfExists","partitionBy":"[]"},"isBlindAppend":true}}"#.to_string(),
        r#"{"metaData":{"id":"test-void","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"id\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"void_col\",\"type\":\"void\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"configuration":{},"createdTime":1587968585495}}"#.to_string(),
        format!(r#"{{"add":{{"path":"{PARQUET_FILE1}","partitionValues":{{}},"size":0,"modificationTime":1587968586000,"dataChange":true}}}}"#),
    ];

    add_commit("memory:///", storage.as_ref(), 0, actions.iter().join("\n")).await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let location = Url::parse("memory:///")?;
    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(location).build(engine.as_ref())?;

    // Explicitly request both columns, including the void one
    let schema = snapshot.schema();
    let scan = snapshot.scan_builder().with_schema(schema).build()?;

    // The void column should be present in the logical schema (returned as null)
    let logical_schema = scan.logical_schema();
    assert!(logical_schema.field("void_col").is_some());
    assert!(logical_schema.field("id").is_some());
    assert_eq!(logical_schema.fields().count(), 2);

    // Execute and verify void column appears as all-null
    let batches = read_scan(&scan, engine)?;
    assert_eq!(batches.len(), 1);
    assert_eq!(batches[0].num_columns(), 2);
    assert_eq!(batches[0].schema().field(0).name(), "id");
    assert_eq!(batches[0].schema().field(1).name(), "void_col");
    assert_eq!(
        *batches[0].schema().field(1).data_type(),
        ArrowDataType::Null
    );

    Ok(())
}

// Verify that void fields inside nested structs are preserved in the scan schema and data.
// Delta schema: {id: int, info: struct<name: string, v: void>}
// Parquet schema: {id: int, info: struct<name: string>} (void field missing from Parquet)
// Result: void field appears as all-null in the returned data.
#[tokio::test]
async fn read_table_with_void_in_nested_struct() -> Result<(), Box<dyn std::error::Error>> {
    // Parquet batch: {id: int, info: struct<name: string>} (without the void field)
    let name_array: ArrayRef = Arc::new(delta_kernel::arrow::array::StringArray::from(vec![
        "alice", "bob",
    ]));
    let inner_fields = vec![delta_kernel::arrow::datatypes::Field::new(
        "name",
        ArrowDataType::Utf8,
        true,
    )];
    let struct_array =
        delta_kernel::arrow::array::StructArray::new(inner_fields.into(), vec![name_array], None);
    let batch = RecordBatch::try_from_iter(vec![
        (
            "id",
            Arc::new(delta_kernel::arrow::array::Int32Array::from(vec![1, 2])) as ArrayRef,
        ),
        ("info", Arc::new(struct_array) as ArrayRef),
    ])?;

    let storage = Arc::new(InMemory::new());
    let actions = [
        r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#.to_string(),
        r#"{"commitInfo":{"timestamp":1587968586154,"operation":"WRITE","operationParameters":{"mode":"ErrorIfExists","partitionBy":"[]"},"isBlindAppend":true}}"#.to_string(),
        r#"{"metaData":{"id":"test-void-nested","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"id\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"info\",\"type\":{\"type\":\"struct\",\"fields\":[{\"name\":\"name\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"v\",\"type\":\"void\",\"nullable\":true,\"metadata\":{}}]},\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"configuration":{},"createdTime":1587968585495}}"#.to_string(),
        format!(r#"{{"add":{{"path":"{PARQUET_FILE1}","partitionValues":{{}},"size":0,"modificationTime":1587968586000,"dataChange":true}}}}"#),
    ];

    add_commit("memory:///", storage.as_ref(), 0, actions.iter().join("\n")).await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let location = Url::parse("memory:///")?;
    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(location).build(engine.as_ref())?;

    // Table schema has the void field inside nested struct
    let table_schema = snapshot.schema();
    let info_field = table_schema.field("info").expect("info should exist");
    if let DataType::Struct(inner) = info_field.data_type() {
        assert!(
            inner.field("v").is_some(),
            "table schema should have void field 'v'"
        );
    }

    let scan = snapshot.scan_builder().build()?;

    // Scan logical schema should preserve the void field in the nested struct
    let logical_schema = scan.logical_schema();
    let info_field = logical_schema
        .field("info")
        .expect("info should exist in scan");
    if let DataType::Struct(inner) = info_field.data_type() {
        assert!(
            inner.field("v").is_some(),
            "void field 'v' should be preserved"
        );
        assert!(
            inner.field("name").is_some(),
            "non-void field 'name' should remain"
        );
        assert_eq!(inner.fields().count(), 2);
    } else {
        panic!("info should be a struct type");
    }

    // Execute the scan and verify void field appears as null in the struct
    let batches = read_scan(&scan, engine)?;
    assert_eq!(batches.len(), 1);
    assert_eq!(batches[0].num_rows(), 2);

    // The info struct should have 2 fields: name (string) and v (null)
    let info_col = batches[0].column_by_name("info").expect("info column");
    let info_struct = info_col
        .as_any()
        .downcast_ref::<delta_kernel::arrow::array::StructArray>()
        .expect("info should be struct");
    assert_eq!(info_struct.num_columns(), 2);
    assert_eq!(info_struct.column_by_name("name").unwrap().len(), 2);
    let v_col = info_struct
        .column_by_name("v")
        .expect("v field should exist");
    assert_eq!(*v_col.data_type(), ArrowDataType::Null);
    assert_eq!(v_col.len(), 2);

    Ok(())
}

// Integration test using a real Delta table created by Spark with a void column.
// Verifies that the kernel returns void column as all-null on reads.
#[test]
fn read_spark_table_with_void_column() -> Result<(), Box<dyn std::error::Error>> {
    read_table_data_str(
        "./tests/data/void-column",
        None, // SELECT * -- void column should appear as null
        None,
        vec![
            "+----+----------+",
            "| id | void_col |",
            "+----+----------+",
            "| 1  |          |",
            "| 2  |          |",
            "| 3  |          |",
            "+----+----------+",
        ],
    )
}

// GE: file1 pruned (max=2s < adjusted 3.999401s), file2+3 kept
#[test]
fn timestamp_truncation_real_table_ge() -> Result<(), Box<dyn std::error::Error>> {
    read_table_data_str(
        "./tests/data/timestamp-truncation-stats",
        None,
        Some(Pred::ge(
            column_expr!("ts_col"),
            Expr::literal(Scalar::Timestamp(4_000_400)),
        )),
        vec![
            "+----+-----------------------------+",
            "| id | ts_col                      |",
            "+----+-----------------------------+",
            "| 3  | 1970-01-01T00:00:03Z        |",
            "| 4  | 1970-01-01T00:00:04.000500Z |",
            "| 5  | 1970-01-01T00:00:07Z        |",
            "| 6  | 1970-01-01T00:00:08Z        |",
            "+----+-----------------------------+",
        ],
    )
}

// LT: file3 pruned (min=7s > 4.000400s), file1+2 kept
#[test]
fn timestamp_truncation_real_table_lt() -> Result<(), Box<dyn std::error::Error>> {
    read_table_data_str(
        "./tests/data/timestamp-truncation-stats",
        None,
        Some(Pred::lt(
            column_expr!("ts_col"),
            Expr::literal(Scalar::Timestamp(4_000_400)),
        )),
        vec![
            "+----+-----------------------------+",
            "| id | ts_col                      |",
            "+----+-----------------------------+",
            "| 1  | 1970-01-01T00:00:01Z        |",
            "| 2  | 1970-01-01T00:00:02Z        |",
            "| 3  | 1970-01-01T00:00:03Z        |",
            "| 4  | 1970-01-01T00:00:04.000500Z |",
            "+----+-----------------------------+",
        ],
    )
}

// LE: file3 pruned (min=7s > 4.000400s), file1+2 kept
#[test]
fn timestamp_truncation_real_table_le() -> Result<(), Box<dyn std::error::Error>> {
    read_table_data_str(
        "./tests/data/timestamp-truncation-stats",
        None,
        Some(Pred::le(
            column_expr!("ts_col"),
            Expr::literal(Scalar::Timestamp(4_000_400)),
        )),
        vec![
            "+----+-----------------------------+",
            "| id | ts_col                      |",
            "+----+-----------------------------+",
            "| 1  | 1970-01-01T00:00:01Z        |",
            "| 2  | 1970-01-01T00:00:02Z        |",
            "| 3  | 1970-01-01T00:00:03Z        |",
            "| 4  | 1970-01-01T00:00:04.000500Z |",
            "+----+-----------------------------+",
        ],
    )
}

// EQ: file1 pruned (max=2s < adjusted 3.999401s), file3 pruned (min=7s > 4.000400s).
// Only file2 kept (ids 3,4).
#[test]
fn timestamp_truncation_real_table_eq() -> Result<(), Box<dyn std::error::Error>> {
    read_table_data_str(
        "./tests/data/timestamp-truncation-stats",
        None,
        Some(Pred::eq(
            column_expr!("ts_col"),
            Expr::literal(Scalar::Timestamp(4_000_400)),
        )),
        vec![
            "+----+-----------------------------+",
            "| id | ts_col                      |",
            "+----+-----------------------------+",
            "| 3  | 1970-01-01T00:00:03Z        |",
            "| 4  | 1970-01-01T00:00:04.000500Z |",
            "+----+-----------------------------+",
        ],
    )
}

async fn scan_with_void_schema(
    schema_string: &str,
    table_id: &str,
    num_rows: i32,
) -> Result<Vec<RecordBatch>, Box<dyn std::error::Error>> {
    let batch = generate_batch(vec![(
        "id",
        (1..=num_rows).collect::<Vec<_>>().into_array(),
    )])?;

    let storage = Arc::new(InMemory::new());
    let actions = [
        r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#.to_string(),
        format!(
            r#"{{"metaData":{{"id":"{table_id}","format":{{"provider":"parquet","options":{{}}}},"schemaString":"{schema_string}","partitionColumns":[],"configuration":{{}},"createdTime":1587968585495}}}}"#
        ),
        format!(
            r#"{{"add":{{"path":"{PARQUET_FILE1}","partitionValues":{{}},"size":0,"modificationTime":1587968586000,"dataChange":true}}}}"#
        ),
    ];

    add_commit("memory:///", storage.as_ref(), 0, actions.iter().join("\n")).await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let location = Url::parse("memory:///")?;
    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(location).build(engine.as_ref())?;
    let scan = snapshot.scan_builder().build()?;
    Ok(read_scan(&scan, engine)?)
}

// Verify that a table with void nested inside an Array can be read at runtime.
// Write-time validation rejects void-in-array, but reads and metadata ops always work.
// The arr column is absent from the Parquet schema; kernel synthesizes a null column at read
// time (the entire column is NULL, not an array of null elements).
#[tokio::test]
async fn read_void_in_array_type_ok() -> Result<(), Box<dyn std::error::Error>> {
    let schema_string = r#"{\"type\":\"struct\",\"fields\":[{\"name\":\"id\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"arr\",\"type\":{\"type\":\"array\",\"elementType\":\"void\",\"containsNull\":true},\"nullable\":true,\"metadata\":{}}]}"#;
    let batches = scan_with_void_schema(schema_string, "test-void-array", 2).await?;
    assert_eq!(batches.len(), 1);
    assert_eq!(batches[0].num_rows(), 2);

    let arr_col = batches[0]
        .column_by_name("arr")
        .expect("arr column must be in RecordBatch");
    assert_eq!(
        arr_col.null_count(),
        arr_col.len(),
        "entire column should be null"
    );
    match arr_col.data_type() {
        ArrowDataType::List(elem) => assert_eq!(*elem.data_type(), ArrowDataType::Null),
        other => panic!("expected List<Null>, got {other:?}"),
    }

    Ok(())
}

// Verify that a table with void nested inside a Map value can be read at runtime.
// Write-time validation rejects void-in-map, but reads and metadata ops always work.
// The m column is absent from the Parquet schema; kernel synthesizes a null column at read
// time (the entire column is NULL, not a map with null entries).
#[tokio::test]
async fn read_void_in_map_type_ok() -> Result<(), Box<dyn std::error::Error>> {
    let schema_string = r#"{\"type\":\"struct\",\"fields\":[{\"name\":\"id\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"m\",\"type\":{\"type\":\"map\",\"keyType\":\"string\",\"valueType\":\"void\",\"valueContainsNull\":true},\"nullable\":true,\"metadata\":{}}]}"#;
    let batches = scan_with_void_schema(schema_string, "test-void-map", 2).await?;
    assert_eq!(batches.len(), 1);
    assert_eq!(batches[0].num_rows(), 2);

    let m_col = batches[0]
        .column_by_name("m")
        .expect("m column must be in RecordBatch");
    assert_eq!(
        m_col.null_count(),
        m_col.len(),
        "entire column should be null"
    );
    match m_col.data_type() {
        ArrowDataType::Map(entries, _) => {
            let entries = entries.data_type();
            match entries {
                ArrowDataType::Struct(fields) => {
                    assert_eq!(*fields[0].data_type(), ArrowDataType::Utf8);
                    assert_eq!(*fields[1].data_type(), ArrowDataType::Null);
                }
                other => panic!("expected Struct inside Map, got {other:?}"),
            }
        }
        other => panic!("expected Map<String,Null>, got {other:?}"),
    }

    Ok(())
}

// Verify runtime read of a struct where all fields are void.
// Delta schema: {id: int, s: struct<x: void, y: void>}
// Parquet has only {id} — the entire struct is missing and must materialize as null.
#[tokio::test]
async fn read_all_void_struct() -> Result<(), Box<dyn std::error::Error>> {
    let schema_string = r#"{\"type\":\"struct\",\"fields\":[{\"name\":\"id\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"s\",\"type\":{\"type\":\"struct\",\"fields\":[{\"name\":\"x\",\"type\":\"void\",\"nullable\":true,\"metadata\":{}},{\"name\":\"y\",\"type\":\"void\",\"nullable\":true,\"metadata\":{}}]},\"nullable\":true,\"metadata\":{}}]}"#;
    let batches = scan_with_void_schema(schema_string, "test-all-void-struct", 3).await?;
    assert_eq!(batches.len(), 1);
    assert_eq!(batches[0].num_rows(), 3);

    let s_col = batches[0].column_by_name("s").expect("s column");
    let s_struct = s_col
        .as_any()
        .downcast_ref::<delta_kernel::arrow::array::StructArray>()
        .expect("s should be struct");
    assert_eq!(s_struct.num_columns(), 2);

    let x_col = s_struct.column_by_name("x").expect("x field");
    let y_col = s_struct.column_by_name("y").expect("y field");
    assert_eq!(*x_col.data_type(), ArrowDataType::Null);
    assert_eq!(*y_col.data_type(), ArrowDataType::Null);
    assert_eq!(x_col.len(), 3);
    assert_eq!(y_col.len(), 3);

    Ok(())
}

// Verify that a table where ALL field are void can still be read (returns all-null rows).
// Reads always succeed; only writes fail for all-void tables.
#[tokio::test]
async fn read_all_void_table() -> Result<(), Box<dyn std::error::Error>> {
    // Empty Parquet file (no columns) — the row count comes from the Parquet metadata
    let batch = RecordBatch::new_empty(Arc::new(ArrowSchema::empty()));

    let storage = Arc::new(InMemory::new());
    let actions = [
        r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#.to_string(),
        r#"{"commitInfo":{"timestamp":1587968586154,"operation":"WRITE","operationParameters":{"mode":"ErrorIfExists","partitionBy":"[]"},"isBlindAppend":true}}"#.to_string(),
        r#"{"metaData":{"id":"test-all-void","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"a\",\"type\":\"void\",\"nullable\":true,\"metadata\":{}},{\"name\":\"b\",\"type\":\"void\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"configuration":{},"createdTime":1587968585495}}"#.to_string(),
        format!(r#"{{"add":{{"path":"{PARQUET_FILE1}","partitionValues":{{}},"size":0,"modificationTime":1587968586000,"dataChange":true}}}}"#),
    ];

    add_commit("memory:///", storage.as_ref(), 0, actions.iter().join("\n")).await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let location = Url::parse("memory:///")?;
    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(location).build(engine.as_ref())?;

    // Schema should contain both void columns
    assert_eq!(snapshot.schema().fields().count(), 2);
    assert!(snapshot.schema().field("a").is_some());
    assert!(snapshot.schema().field("b").is_some());

    let scan = snapshot.scan_builder().build()?;
    let logical_schema = scan.logical_schema();
    assert_eq!(logical_schema.fields().count(), 2);

    // Execute read_scan — runtime must not crash even with all-void schema.
    // Parquet file has 0 columns/0 rows → empty row group → reader produces no batches.
    // The key verification is that read_scan() doesn't error.
    let batches = read_scan(&scan, engine)?;
    let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
    assert_eq!(total_rows, 0);

    Ok(())
}

// Verify that a void column used as a partition column works on reads.
// The partition value is missing (null), so parse_partition_value_raw returns Scalar::Null(VOID).
#[tokio::test]
async fn read_table_with_void_partition_column() -> Result<(), Box<dyn std::error::Error>> {
    // Parquet file has only the non-partition, non-void column
    let batch = generate_batch(vec![("id", vec![1, 2].into_array())])?;

    let storage = Arc::new(InMemory::new());
    let actions = [
        r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#.to_string(),
        r#"{"commitInfo":{"timestamp":1587968586154,"operation":"WRITE","operationParameters":{"mode":"ErrorIfExists","partitionBy":"[\"void_part\"]"},"isBlindAppend":true}}"#.to_string(),
        r#"{"metaData":{"id":"test-void-part","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"id\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"void_part\",\"type\":\"void\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":["void_part"],"configuration":{},"createdTime":1587968585495}}"#.to_string(),
        format!(r#"{{"add":{{"path":"{PARQUET_FILE1}","partitionValues":{{}},"size":0,"modificationTime":1587968586000,"dataChange":true}}}}"#),
    ];

    add_commit("memory:///", storage.as_ref(), 0, actions.iter().join("\n")).await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let location = Url::parse("memory:///")?;
    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(location).build(engine.as_ref())?;

    let scan = snapshot.scan_builder().build()?;
    let logical_schema = scan.logical_schema();
    assert!(logical_schema.field("void_part").is_some());
    assert!(logical_schema.field("id").is_some());

    // Execute and verify both columns appear
    let batches = read_scan(&scan, engine)?;
    assert_eq!(batches.len(), 1);
    assert_eq!(batches[0].num_rows(), 2);
    // void partition column should appear as Null type
    let void_col = batches[0]
        .column_by_name("void_part")
        .expect("void partition column");
    assert_eq!(*void_col.data_type(), ArrowDataType::Null);
    assert_eq!(void_col.len(), 2);

    Ok(())
}

// Verify that predicate pushdown on a void column works correctly.
// A predicate like `void_col IS NULL` is always true for void columns, so no rows are skipped.
#[tokio::test]
async fn read_with_predicate_on_void_column() -> Result<(), Box<dyn std::error::Error>> {
    let batch = generate_batch(vec![("id", vec![1, 2, 3].into_array())])?;

    let storage = Arc::new(InMemory::new());
    let actions = [
        r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#.to_string(),
        r#"{"commitInfo":{"timestamp":1587968586154,"operation":"WRITE","operationParameters":{"mode":"ErrorIfExists","partitionBy":"[]"},"isBlindAppend":true}}"#.to_string(),
        r#"{"metaData":{"id":"test-void-pred","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"id\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"void_col\",\"type\":\"void\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"configuration":{},"createdTime":1587968585495}}"#.to_string(),
        format!(r#"{{"add":{{"path":"{PARQUET_FILE1}","partitionValues":{{}},"size":0,"modificationTime":1587968586000,"dataChange":true}}}}"#),
    ];

    add_commit("memory:///", storage.as_ref(), 0, actions.iter().join("\n")).await?;
    storage
        .put(
            &Path::from(PARQUET_FILE1),
            record_batch_to_bytes(&batch).into(),
        )
        .await?;

    let location = Url::parse("memory:///")?;
    let engine = Arc::new(DefaultEngineBuilder::new(storage.clone()).build());
    let snapshot = Snapshot::builder_for(location).build(engine.as_ref())?;

    // Predicate: void_col IS NULL — always true for void, should return all rows
    let predicate = Arc::new(column_expr!("void_col").is_null());
    let scan = snapshot
        .clone()
        .scan_builder()
        .with_predicate(predicate)
        .build()?;

    let batches = read_scan(&scan, engine.clone())?;
    let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
    assert_eq!(total_rows, 3, "IS NULL on void should return all rows");

    // Predicate: void_col IS NOT NULL — always false for void. The Add action above has no
    // `stats` string, so kernel has nothing to skip on. All rows are returned.
    // Skipping driven by `nullCount` is exercised by `void_predicate_skips_via_null_count`.
    let predicate_not_null = Arc::new(column_expr!("void_col").is_not_null());
    let scan_not_null = snapshot
        .scan_builder()
        .with_predicate(predicate_not_null)
        .build()?;
    let batches_not_null = read_scan(&scan_not_null, engine)?;
    let total_rows_not_null: usize = batches_not_null.iter().map(|b| b.num_rows()).sum();
    assert_eq!(
        total_rows_not_null, 3,
        "IS NOT NULL on void: no row-level filtering, all rows returned"
    );

    Ok(())
}

// File-level skipping via the `nullCount` Delta stat for void columns. The Spark fixture's 3
// Add actions each carry stats with `nullCount.void_col == numRecords == 1`, so kernel can prune
// every file for `IS NOT NULL`. Contrast with `read_with_predicate_on_void_column`, whose Add
// action has no `stats` and consequently returns all 3 rows for the same predicate -- confirming
// that pruning (not row-level filtering) is what produces the empty result here.
#[rstest::rstest]
#[case::is_null(
    column_expr!("void_col").is_null(),
    vec![
        "+----+----------+",
        "| id | void_col |",
        "+----+----------+",
        "| 1  |          |",
        "| 2  |          |",
        "| 3  |          |",
        "+----+----------+",
    ]
)]
#[case::is_not_null(column_expr!("void_col").is_not_null(), vec![])]
fn void_predicate_skips_via_null_count(
    #[case] predicate: Pred,
    #[case] expected: Vec<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    read_table_data_str("./tests/data/void-column", None, Some(predicate), expected)
}

// Direct evidence that void-column predicates drive file-level pruning: count the surviving
// ScanFiles after `scan_metadata` rather than relying on the empty-batches contrast. With the
// Spark fixture's `nullCount.void_col == numRecords` stats, `IS NOT NULL` prunes all 3 files
// and `IS NULL` keeps all 3.
#[rstest::rstest]
#[case::is_null_keeps_all(column_expr!("void_col").is_null(), 3)]
#[case::is_not_null_prunes_all(column_expr!("void_col").is_not_null(), 0)]
fn void_predicate_pruning_scan_file_count(
    #[case] predicate: Pred,
    #[case] expected_files: usize,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = std::fs::canonicalize(PathBuf::from("./tests/data/void-column"))?;
    let url = Url::from_directory_path(path).unwrap();
    let engine = test_utils::create_default_engine(&url)?;
    let snapshot = Snapshot::builder_for(url).build(engine.as_ref())?;
    let scan = snapshot
        .scan_builder()
        .with_predicate(Arc::new(predicate))
        .build()?;

    let mut scan_files: Vec<ScanFile> = vec![];
    for res in scan.scan_metadata(engine.as_ref())? {
        scan_files = res?.visit_scan_files(scan_files, scan_metadata_callback)?;
    }
    assert_eq!(scan_files.len(), expected_files);
    Ok(())
}