tylertoo-core 0.7.0

Core library for converting GeoParquet to PMTiles vector tiles
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
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
//! Overview conversion pipeline (task P5; streaming since H3).
//!
//! [`convert_to_overviews`] wires the existing overview modules into a single
//! GeoParquet → GeoParquet overview build. By default
//! ([`ConvertOptions::streaming`]) it dispatches to the two-pass
//! bounded-memory pipeline in [`super::stream`]; the in-memory reference
//! implementation below (`streaming: false`) proceeds as:
//!
//! 1. **read** the whole input GeoParquet preserving the full property schema
//!    (the entire table is concatenated into one batch). The CRS is detected
//!    from the `geo` metadata and mapped to [`Crs`]; non-4326/3857 inputs and
//!    inputs that already carry a `level` column are rejected (spec Q3, §4.1).
//! 2. **assign** every feature a coarsest level via [`assign::assign_levels`]
//!    over per-feature bbox + [`FeatureKind`] + an optional sort key.
//! 3. **generalize + write**, coarse→fine, feeding [`OverviewWriter`]:
//!    - `duplicating` non-canonical levels: [`simplify::simplify_for_level`]
//!      per feature, dropping [`Simplified::Dropped`];
//!    - `duplicating` canonical (finest) level: original geometry **untouched**
//!      (spec §2.4, value-identity — no simplify round-trip);
//!    - `partitioning` (all levels): original geometry **verbatim** (§2.3).
//!
//! Input (Hilbert) order is preserved within each level (no re-sort).
//! 4. **report**: a [`ConvertReport`] (per-level feature/vertex/byte counts,
//!    totals, duration) is returned and is `serde` `Serialize` for the later
//!    benchmark tasks.
//!
//! The in-memory path is the correctness-first reference: memory is
//! `O(dataset)`. The default streaming path ([`super::stream`]) produces
//! equivalent output in `O(read batch + winner tables)` memory; equivalence
//! is asserted by the `streaming_matches_*` tests below.

use std::collections::HashMap;
use std::collections::HashSet;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

use arrow_array::{Array, RecordBatch, UInt32Array};
use arrow_schema::{DataType, Field, Schema, SchemaRef};
use arrow_select::concat::concat_batches;
use arrow_select::take::take;
use geo::{Area, BoundingRect, Geometry};
use geoarrow::array::{from_arrow_array, GeometryBuilder};
use geoarrow::datatypes::GeometryType;
use geoarrow_array::GeoArrowArray;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;

use crate::input::InputSource;
use crate::input_set::ConvertSource;
use serde::Serialize;

use crate::batch_processor::extract_geometries_opt_from_array;

use super::accumulate::{is_carrier, level_accumulates, tiny_polygon_carriers, AccumulateLevel};
use super::assign::{
    apply_density_budget, assign_levels_bounded, AssignConfig, AssignFeature, Assignment,
    DensityBudgetConfig, FeatureKind, SUPERCELL_GSD_FACTOR,
};
use super::cluster::{
    build_cluster_tables, verify_sum_invariant, AccumulateSpec, ClusterEntry, ClusterTables,
    POINT_COUNT_COLUMN,
};
use super::coalesce::{
    coalesce_level_lines, CoalesceInput, CoalesceParams, COALESCED_COUNT_COLUMN,
    DEFAULT_COALESCE_MAX_LEVEL_ROWS, DEFAULT_JUNCTION_ANGLE_DEG, DEFAULT_SNAP_GSD_FACTOR,
};
use super::ladder::{build_ladder, entry_levels, EntryZoomSpec};
use super::level::{
    gsd_with_base, AccumulatedColumn, ClusteringProvenance, CoalescingProvenance, Crs,
    DensityProvenance, Generalization, GeneralizationLevel, MemoryProfile, Mode, RankingProvenance,
    RepresentationBandProvenance, GSD_TILE_BASE, METERS_PER_DEGREE,
};
use super::properties::{PropertySelection, PropertySelectionError};
use super::simplify::{
    carrier_square, simplify_cascade, simplify_for_level, simplify_step, CascadeStep, CollapseMode,
    Representation, Simplified, SimplifyOptions,
};
use super::writer::{
    LevelSpec, LevelWriteOutcome, OverviewWriter, RowGroupSizePolicy, WriterError, LEVEL_COLUMN,
};

/// How the caller specifies the overview levels.
#[derive(Debug, Clone, PartialEq)]
pub enum LevelPlan {
    /// A Web Mercator zoom range, mapped through [`gsd_for_zoom`]. `min_zoom`
    /// is the coarsest (level 0), `max_zoom` the finest. Both inclusive.
    ZoomRange {
        /// Coarsest zoom (level 0).
        min_zoom: u8,
        /// Finest zoom (canonical level in duplicating mode).
        max_zoom: u8,
    },
    /// An explicit list of per-level GSDs in **meters**, coarse→fine (strictly
    /// decreasing). No `zoom` is recorded on the levels.
    Gsds(Vec<f64>),
}

/// Maximum number of levels a plan may resolve to. The per-feature winner
/// tables store level indices as `u8` (with `u8::MAX` reserved as the
/// streaming pipeline's "no feature on this row" sentinel), so plans beyond
/// 255 levels are rejected instead of silently wrapping.
pub(super) const MAX_LEVELS: usize = 255;

impl LevelPlan {
    /// Resolve to the coarse→fine list of `(gsd_meters, zoom?)` level specs.
    ///
    /// `gsd_base` is the GSD tile-band base (spec §5.2 / Q6); it scales the
    /// per-zoom GSDs of a [`ZoomRange`](LevelPlan::ZoomRange) plan and has no
    /// effect on an explicit [`Gsds`](LevelPlan::Gsds) plan (those GSDs are
    /// already in meters).
    pub(super) fn resolve(&self, gsd_base: f64) -> Result<Vec<(f64, Option<u8>)>, ConvertError> {
        let check_len = |n: usize| {
            if n > MAX_LEVELS {
                return Err(ConvertError::InvalidLevels(format!(
                    "{n} levels requested; at most {MAX_LEVELS} levels are supported"
                )));
            }
            Ok(())
        };
        match self {
            LevelPlan::ZoomRange { min_zoom, max_zoom } => {
                if min_zoom > max_zoom {
                    return Err(ConvertError::InvalidLevels(format!(
                        "min_zoom {min_zoom} must be <= max_zoom {max_zoom}"
                    )));
                }
                check_len(*max_zoom as usize - *min_zoom as usize + 1)?;
                Ok((*min_zoom..=*max_zoom)
                    .map(|z| (gsd_with_base(z, gsd_base), Some(z)))
                    .collect())
            }
            LevelPlan::Gsds(gsds) => {
                if gsds.is_empty() {
                    return Err(ConvertError::InvalidLevels(
                        "explicit gsd list must be non-empty".to_string(),
                    ));
                }
                check_len(gsds.len())?;
                let mut prev: Option<f64> = None;
                for (i, &g) in gsds.iter().enumerate() {
                    if g <= 0.0 || g.is_nan() {
                        return Err(ConvertError::InvalidLevels(format!(
                            "gsd[{i}] = {g} must be > 0"
                        )));
                    }
                    if let Some(p) = prev {
                        if g >= p {
                            return Err(ConvertError::InvalidLevels(format!(
                                "gsd list must be strictly decreasing coarse→fine (gsd[{i}] = {g} >= previous {p})"
                            )));
                        }
                    }
                    prev = Some(g);
                }
                Ok(gsds.iter().map(|&g| (g, None)).collect())
            }
        }
    }
}

/// A categorical (class-aware) cell-winner ranking (Q1, tier 1 / tier 3).
///
/// Maps the string values of a column to numeric priorities. Higher priority
/// **wins** a grid cell — matching [`assign`](super::assign)'s default
/// `SortDirection::Desc` (larger `sort_key` wins). A feature whose column value
/// is present but not in [`ranks`](ClassRanking::ranks) is assigned
/// [`unknown_rank`](ClassRanking::unknown_rank), which — as long as it is below
/// every named rank — **loses to all named classes but still beats a
/// null/missing value** (nulls encode as `None`, which loses to any `Some` in
/// the priority order).
#[derive(Debug, Clone, PartialEq)]
pub struct ClassRanking {
    /// Name of the (Utf8/LargeUtf8) column whose values are ranked.
    pub column: String,
    /// `(value, priority)` pairs; higher priority wins the cell. Order is
    /// irrelevant (looked up by value).
    pub ranks: Vec<(String, f64)>,
    /// Priority for a present-but-unranked value. Set below every named rank so
    /// unknown classes lose to known ones but beat nulls.
    pub unknown_rank: f64,
}

/// Upper bound on how many `(value, priority)` pairs are echoed into the
/// footer provenance block (§3.5). Larger maps record only the mode + column.
const MAX_PROVENANCE_RANKS: usize = 64;

/// Built-in Overture transportation `class` ranking (Q1, tier 3 auto-detect).
///
/// Spine (highest→lowest, always holds): motorway > trunk > primary >
/// secondary > tertiary > residential > unclassified > service. Below service
/// come the remaining pedestrian/minor classes, then everything unrecognized
/// (rail classes, the literal `unknown`, driveways, …) falls to
/// [`unknown_rank`](ClassRanking::unknown_rank).
pub fn overture_road_ranking(column: String) -> ClassRanking {
    // Descending priorities; spine first (see doc comment), then the tail.
    let ordered = [
        "motorway", // spine
        "trunk",
        "primary",
        "secondary",
        "tertiary",
        "residential",
        "unclassified",
        "service",
        "living_street", // tail (all below service)
        "pedestrian",
        "track",
        "cycleway",
        "bridleway",
        "footway",
        "steps",
        "path",
        "driveway",
        "parking_aisle",
    ];
    let n = ordered.len();
    let ranks = ordered
        .iter()
        .enumerate()
        // Highest priority for the first entry; all strictly positive so every
        // named class beats unknown_rank (0.0).
        .map(|(i, &c)| (c.to_string(), (n - i) as f64))
        .collect();
    ClassRanking {
        column,
        ranks,
        unknown_rank: 0.0,
    }
}

/// Known Overture transportation `class` / `road_class` vocabulary, used only to
/// decide whether an auto-detected `class`/`road_class` column is *actually* a
/// road-class column (overlap gate). Includes rail/pedestrian values that the
/// ranking itself leaves at `unknown_rank`.
pub(super) const KNOWN_ROAD_CLASSES: &[&str] = &[
    "motorway",
    "trunk",
    "primary",
    "secondary",
    "tertiary",
    "residential",
    "unclassified",
    "service",
    "living_street",
    "pedestrian",
    "track",
    "cycleway",
    "bridleway",
    "footway",
    "steps",
    "path",
    "driveway",
    "parking_aisle",
    "unknown",
    // rail subtype classes (present in Overture transportation extracts)
    "standard_gauge",
    "light_rail",
    "tram",
    "subway",
    "monorail",
    "funicular",
];

/// Minimum number of *distinct* known road classes a candidate column must
/// contain before auto-detection treats it as Overture roads.
pub(super) const ROAD_VOCAB_MIN_DISTINCT: usize = 3;

/// Options for [`convert_to_overviews`].
#[derive(Debug, Clone)]
pub struct ConvertOptions {
    /// Level materialization mode. Default [`Mode::Duplicating`].
    pub mode: Mode,
    /// How levels are specified (zoom range or explicit GSDs).
    pub levels: LevelPlan,
    /// Thinning / visibility / sort configuration for level assignment.
    pub assign: AssignConfig,
    /// Attribute-driven entry zoom (#364): a magnitude ladder that decides how
    /// early each feature may appear, overriding the visibility gate and
    /// cell-winner thinning rather than acting after them.
    ///
    /// For nested-band data the strongest signal is carried by the physically
    /// *smallest* feature, so geometry-ranked thinning gets coarse levels
    /// backwards. [`sort_key`](Self::sort_key) cannot fix that on its own — it
    /// chooses between features competing for a cell, and the gate has already
    /// dropped the small ones on size.
    pub entry_zoom: Option<EntryZoomSpec>,
    /// Optional column name whose (numeric) value is used as the cell-winner
    /// sort key. Mutually exclusive with [`class_ranking`](Self::class_ranking).
    pub sort_key: Option<String>,
    /// Optional explicit categorical class ranking (Q1 tier 1). Mutually
    /// exclusive with [`sort_key`](Self::sort_key).
    pub class_ranking: Option<ClassRanking>,
    /// Disable tier-3 auto-detection of well-known schemas (Overture roads /
    /// places confidence). No effect when `sort_key` or `class_ranking` is set.
    pub no_auto_rank: bool,
    /// Per-level simplification options (duplicating mode only).
    pub simplify: SimplifyOptions,
    /// Zoom-band representation selector (#317 / #279): per-zoom-band
    /// [`Representation`] overrides — e.g. `0-7:point, 8-14:geom` renders
    /// polygonal features as representative points (centroid) at z0–7 and
    /// full geometry at z8–14 in ONE archive, no two-archive merge;
    /// `0-7:square` emits tippecanoe-style area-dithered placeholder squares
    /// for below-tolerance polygons in the band. Zooms not covered by a band
    /// default to [`Representation::Geometry`]. Duplicating mode with a
    /// [`LevelPlan::ZoomRange`] plan only; bands must not overlap, a
    /// non-geometry band must end strictly before `max_zoom` (the canonical
    /// level stays verbatim, spec §2.4), and every zoom coarser than a
    /// `point` zoom must also be `point` (the cascade's point passes through
    /// coarser levels regardless). Within a `point` band, polygons bypass
    /// the visibility gate (a dot is always visible) and thin on the
    /// point-thinning grid; within a `square` band they bypass the gate but
    /// keep the polygon grid. Lines and genuine points are unaffected by
    /// every band kind. Default empty (all levels `geom`).
    pub representation: Vec<RepresentationBand>,
    /// Per-level density budget applied after cell-winner thinning (Q2). Default
    /// enabled; disable via `--no-density-drop` to reproduce pre-Q2 behavior.
    pub density: DensityBudgetConfig,
    /// GSD tile-band base for zoom→GSD derivation (spec §5.2 / Q6; the cogp-rs
    /// `base` knob). Default [`GSD_TILE_BASE`] (1024). Larger ⇒ smaller GSDs
    /// (finer detail / less thinning); smaller ⇒ larger GSDs (coarser / more
    /// thinning). No effect on an explicit [`LevelPlan::Gsds`] plan.
    pub gsd_base: f64,
    /// Emit the optional COGP compatibility footer key (§3.1). Default `false`.
    pub cogp_compat_key: bool,
    /// Maximum row-group size in rows for the output writer.
    pub max_row_group_size: usize,
    /// How the per-level row-group cap is derived from `max_row_group_size`
    /// (#202). Default [`RowGroupSizePolicy::Constant`]; `ZoomScaled` doubles
    /// the cap per zoom step below the finest level (fewer requests on coarse
    /// bands that wide viewports read mostly whole anyway).
    pub row_group_size_policy: RowGroupSizePolicy,
    /// Keep full Parquet statistics on every column (including high-cardinality
    /// string/binary property columns and the WKB geometry column). Default
    /// `false`: those stats are suppressed to keep the footer small (H1); the
    /// bbox covering and `level` column always keep their pruning stats. Set
    /// `true` for clients that push property predicates to the remote file.
    pub full_column_stats: bool,
    /// Use the two-pass bounded-memory streaming pipeline (H3). Default `true`.
    ///
    /// Pass 1 streams the input once to build the per-feature winner tables
    /// (level assignment + Q2 density budget); pass 2 streams the input again
    /// per level, simplifying and writing batch-by-batch. Peak memory is
    /// `O(read batch + winner tables)` instead of `O(dataset)`. Set `false`
    /// to use the original in-memory pipeline (kept for comparison; produces
    /// equivalent output).
    pub streaming: bool,
    /// Rows per Arrow read batch in the streaming pipeline (both passes).
    /// Default [`DEFAULT_READ_BATCH_SIZE`]. Larger batches amortize per-batch
    /// overhead at the cost of proportionally more peak memory; smaller
    /// batches bound memory tighter. No effect when `streaming` is `false`.
    pub read_batch_size: usize,
    /// Memory/throughput profile for the streaming pass-2 engine (#213/#212).
    /// Default [`MemoryProfile::Auto`], resolved per mode + estimated output
    /// size at convert entry. Changes speed and peak memory only — output is
    /// byte-identical across profiles. No effect when `streaming` is `false`.
    pub profile: MemoryProfile,
    /// Number of Arrow read batches allowed in flight through the streaming
    /// pass-2 pipeline at once (bounded-channel depth / read-compute overlap
    /// knob). Default [`IN_FLIGHT_BATCHES_AUTO`], which
    /// [`resolve_in_flight_batches`] expands to the machine's available
    /// parallelism (clamped to `[IN_FLIGHT_BATCHES_MIN, IN_FLIGHT_BATCHES_MAX]`)
    /// at pass-2 setup; any explicit positive value is honoured verbatim.
    /// Higher improves core utilization on long-pole geometries at
    /// proportionally more peak memory (`in_flight_batches × read_batch_size`
    /// rows resident). No effect when `streaming` is `false`.
    pub in_flight_batches: usize,
    /// Enable point clustering (plan Q4; opt-in per spec §11 Q4). Duplicating
    /// mode only. When enabled, each level's point cell-winners absorb the
    /// other point features in their cell: the output gains a `point_count`
    /// INT64 NOT NULL column (1 at the canonical level) and the winner keeps
    /// its own geometry and attributes (see [`super::cluster`]). Lines and
    /// polygons are unaffected. Default `false`.
    pub cluster: bool,
    /// Numeric per-cluster attribute aggregation (Q6): for each spec, the
    /// winner's value of the column becomes the aggregate over itself + the
    /// absorbed features at that level. Requires [`cluster`](Self::cluster).
    /// Empty by default.
    pub accumulate: Vec<AccumulateSpec>,
    /// Enable line network coalescing (plan Q3). **Default `true`** (like
    /// `line_thinning = 1.0` and the clustering point grid, chosen by
    /// maintainer render review: defaults should look right). At each
    /// non-canonical duplicating level, touching same-class line segments
    /// are chained into single "stroke" LineStrings BEFORE the visibility
    /// gate and thinning run (see [`super::coalesce`]), so fragmented
    /// networks read as connected arteries at coarse zooms. The output
    /// gains a `coalesced_count` INT32 NOT NULL column (source segments
    /// merged per row; 1 for unmerged rows and at the canonical level).
    /// Points and polygons are unaffected.
    ///
    /// **Partitioning mode**: coalescing cannot be represented there (a
    /// merged chain violates §2.3's feature-once/verbatim contract), so
    /// this option is treated as INERT for partitioning conversions — the
    /// output has no `coalesced_count` column and no coalescing provenance.
    /// (The CLI additionally rejects an *explicit* request.)
    pub coalesce_lines: bool,
    /// Endpoint snap tolerance for coalescing, in GSD multiples (default
    /// [`DEFAULT_SNAP_GSD_FACTOR`] = 1.0): after exact-endpoint chaining,
    /// chain ends within `factor × gsd` of each other are joined. `<= 0`
    /// disables the snap pass (exact coordinate matching only).
    pub coalesce_snap: f64,
    /// Per-level candidate ceiling for coalescing (default
    /// [`DEFAULT_COALESCE_MAX_LEVEL_ROWS`]): chaining holds the level's
    /// candidate line geometries in memory at once, so levels with more
    /// candidate lines than this skip coalescing (with a log) instead of
    /// breaking the streaming pipeline's memory bound.
    pub coalesce_max_level_rows: usize,
    /// Junction continuation threshold for coalescing, in degrees (default
    /// [`DEFAULT_JUNCTION_ANGLE_DEG`] = `0` = OFF, per maintainer render
    /// review — strict degree-2 chaining looks better on road networks).
    /// When `> 0`: at junction nodes (degree >= 3), compatible incident
    /// lines that continue each other within this deviation from straight
    /// merge best-pair-first, so arterials chain THROUGH same-class
    /// crossings (fewer, longer strokes at the cost of over-merging).
    pub coalesce_junction_angle: f64,
    /// Regional extract (#102): `[xmin, ymin, xmax, ymax]` in EPSG:4326
    /// lon/lat degrees. When set, the conversion behaves as if the input
    /// contained only the features whose bounding box intersects this region
    /// (closed-interval AABB test): input row groups whose GeoParquet 1.1
    /// bbox covering statistics don't intersect are skipped at the parquet
    /// footer level (their data pages are never read), and features of the
    /// surviving row groups are filtered exactly by their own bbox. Inputs
    /// without covering statistics degrade gracefully — every row group is
    /// read and only the exact per-feature filter applies, so the output is
    /// identical either way. Default `None` (full-extent conversion,
    /// byte-identical output to a build without this option).
    pub bbox: Option<[f64; 4]>,
    /// Attribute filter (#315): a SQL-WHERE-style predicate over the input's
    /// property columns (`--filter` / `--where`), e.g. `confidence > 0.8`,
    /// `crop_type IN ('soy', 'corn') AND note IS NOT NULL`. Evaluated during
    /// the pass-1 scan with SQL three-valued null semantics (a row is kept
    /// only when the predicate is TRUE), so it composes with
    /// [`bbox`](Self::bbox) and feeds the same downstream pipeline. Input row
    /// groups whose parquet column statistics prove the predicate cannot
    /// match are skipped at the footer level (no data pages read — on remote
    /// input those byte ranges are never fetched); row groups without usable
    /// statistics degrade gracefully to the exact per-row evaluation. See
    /// [`super::filter`] for the grammar. Default `None` (no filtering).
    pub filter: Option<String>,
    /// Which property columns the output carries (#386): tippecanoe's
    /// `-x` / `-y` / `-X`. Resolved once against the input schema and applied
    /// as a read projection before anything else looks at the schema, so the
    /// excluded columns are never decoded and the overview file only
    /// carries the kept columns. The geometry column is always kept. A
    /// column another knob reads (`sort_key`, `class_ranking`, `entry_zoom`,
    /// `accumulate`, `filter`) must stay included; excluding it is rejected.
    /// Default: keep everything.
    pub properties: PropertySelection,
    /// Directory for the remote-input disk spill (#219 / #272). A remote
    /// convert stages every fetched column chunk in an anonymous temp file
    /// (growing to ≈1× the touched input bytes) so later passes re-read
    /// from local disk instead of the network. `None` (default) places it
    /// under the process temp dir (`$TMPDIR`); set this to use a roomier
    /// or faster volume instead. The directory must exist (validated up
    /// front). Local inputs never spill, so this has no effect on them.
    pub spill_dir: Option<PathBuf>,
}

/// Default rows per read batch for the streaming pipeline (H3).
pub const DEFAULT_READ_BATCH_SIZE: usize = 8192;

/// Sentinel value for [`ConvertOptions::in_flight_batches`] requesting
/// automatic sizing from the machine's available parallelism (see
/// [`resolve_in_flight_batches`]). This is the library default so a convert
/// uses the cores it is given without the caller having to know the box.
pub const IN_FLIGHT_BATCHES_AUTO: usize = 0;

/// Lower clamp for auto-sized in-flight batches. Keeps a few cores fed even
/// on a small box, and matches the historical hard default (#213).
pub const IN_FLIGHT_BATCHES_MIN: usize = 4;

/// Upper clamp for auto-sized in-flight batches. The single-threaded parquet
/// writer (#264 follow-up) caps the achievable speedup, so pushing in-flight
/// past this only grows the resident batch set (`in_flight × read_batch_size`
/// rows) without a matching throughput gain. Power users can still pass a
/// larger explicit value.
pub const IN_FLIGHT_BATCHES_MAX: usize = 16;

/// Resolve a requested in-flight-batches value to a concrete depth.
///
/// [`IN_FLIGHT_BATCHES_AUTO`] (0) auto-sizes from
/// [`std::thread::available_parallelism`], clamped to
/// `[IN_FLIGHT_BATCHES_MIN, IN_FLIGHT_BATCHES_MAX]`; any explicit positive
/// value is honoured verbatim (uncapped — the caller opted in to the memory
/// cost). Output is byte-identical for every value: in-flight depth only sets
/// read/compute overlap, never level assignment or write order (see the
/// `pipelined_in_flight_matches_reference` equivalence test).
pub fn resolve_in_flight_batches(requested: usize) -> usize {
    if requested == IN_FLIGHT_BATCHES_AUTO {
        std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(IN_FLIGHT_BATCHES_MIN)
            .clamp(IN_FLIGHT_BATCHES_MIN, IN_FLIGHT_BATCHES_MAX)
    } else {
        requested
    }
}

impl ConvertOptions {
    /// Turn off the whole generalization ladder: tile this input **exactly as
    /// given** at every level (#345 / #360).
    ///
    /// The ladder derives coarse levels from the fine input by thinning and
    /// simplifying. That is right for a road network and wrong for a
    /// pre-aggregated grid: an H3 r6 cell is not a simplified r7 cell, it is
    /// their parent, and its count is their sum. Run an aggregate through the
    /// gates and a coarse level shows *some* children and silently omits the
    /// rest, rather than showing what they sum to — a choropleth in which
    /// every cell must be drawn loses most of itself.
    ///
    /// Before this existed the only way there was a four-flag incantation
    /// (`--no-density-drop --polygon-visibility 0 --polygon-thinning 1e-9
    /// --simplify-factor 0`), which covered only polygons and leaned on `1e-9`
    /// because `0` was rejected. This is the same intent, stated once, for
    /// every geometry kind:
    ///
    /// - no cell-winner thinning (points, lines, polygons)
    /// - no visibility gates
    /// - no simplification
    /// - no per-level density budget
    /// - no line coalescing (merging changes feature identity)
    ///
    /// It leaves everything else — mode, level plan, CRS, row-group layout,
    /// clustering if the caller asked for it — untouched, so it composes with
    /// the rest of the configuration. Apply it first and override afterwards
    /// if you want *nearly* verbatim.
    ///
    /// Note that this governs the **convert** side. A per-tile size limit on
    /// the export can still drop features; pass `--max-tile-size 0` (which
    /// `tylertoo tiles --verbatim` does for you) when every feature must
    /// survive.
    #[must_use]
    pub fn verbatim(mut self) -> Self {
        self.assign.point_thinning = 0.0;
        self.assign.line_thinning = 0.0;
        self.assign.polygon_thinning = 0.0;
        self.assign.line_visibility = 0.0;
        self.assign.polygon_visibility = 0.0;
        self.simplify.factor = 0.0;
        self.density.enabled = false;
        self.coalesce_lines = false;
        self
    }

    /// Whether this configuration generalizes nothing — the predicate form of
    /// [`Self::verbatim`], true for a config that reproduces its input at
    /// every level however it was reached (the flag, or the equivalent knobs
    /// set by hand).
    pub fn is_verbatim(&self) -> bool {
        // An entry-zoom ladder is not a generalization knob, but it does hold
        // features out of coarse levels — so a laddered run does NOT reproduce
        // its input at every level, whatever the knobs say. Reporting it as
        // verbatim would make the CLI's "every level reproduces the input"
        // line a lie on exactly the runs that combine the two (#364).
        self.generalization_is_off() && self.entry_zoom.is_none()
    }

    /// Whether every *generalization* knob is off, ignoring the entry-zoom
    /// ladder.
    ///
    /// This is the half that governs feature and vertex dropping, and it is
    /// what the mode guards test: a ladder gives laddered features a level to
    /// sit at, but unlabelled ones still collapse into the coarsest level
    /// under partitioning, so the guard has to fire either way.
    pub(crate) fn generalization_is_off(&self) -> bool {
        self.assign.point_thinning == 0.0
            && self.assign.line_thinning == 0.0
            && self.assign.polygon_thinning == 0.0
            && self.assign.line_visibility == 0.0
            && self.assign.polygon_visibility == 0.0
            && self.simplify.factor == 0.0
            && !self.density.enabled
            && !self.coalesce_lines
    }
}

impl Default for ConvertOptions {
    fn default() -> Self {
        Self {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 0,
                max_zoom: 6,
            },
            assign: AssignConfig::default(),
            entry_zoom: None,
            sort_key: None,
            class_ranking: None,
            no_auto_rank: false,
            simplify: SimplifyOptions::default(),
            representation: Vec::new(),
            density: DensityBudgetConfig::default(),
            gsd_base: GSD_TILE_BASE,
            cogp_compat_key: false,
            max_row_group_size: super::writer::DEFAULT_MAX_ROW_GROUP_SIZE,
            row_group_size_policy: RowGroupSizePolicy::default(),
            full_column_stats: false,
            streaming: true,
            read_batch_size: DEFAULT_READ_BATCH_SIZE,
            profile: MemoryProfile::Auto,
            in_flight_batches: IN_FLIGHT_BATCHES_AUTO,
            cluster: false,
            accumulate: Vec::new(),
            coalesce_lines: true,
            coalesce_snap: DEFAULT_SNAP_GSD_FACTOR,
            coalesce_max_level_rows: DEFAULT_COALESCE_MAX_LEVEL_ROWS,
            coalesce_junction_angle: DEFAULT_JUNCTION_ANGLE_DEG,
            bbox: None,
            filter: None,
            properties: PropertySelection::default(),
            spill_dir: None,
        }
    }
}

/// Per-level statistics in a [`ConvertReport`].
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct LevelReport {
    /// Level index in the output file (0 = coarsest).
    pub level: usize,
    /// Ground sample distance in meters for this level.
    pub gsd: f64,
    /// Web Mercator zoom, if the level plan supplied one.
    pub zoom: Option<u8>,
    /// Number of features (rows) written at this level.
    pub feature_count: usize,
    /// Total geometry vertex (coordinate) count across the level's features.
    pub vertex_count: usize,
    /// Uncompressed size of the level's row groups (bytes).
    pub uncompressed_bytes: i64,
    /// Compressed on-disk size of the level's row groups (bytes).
    pub compressed_bytes: i64,
}

/// A planned level omitted from the output because it contained no rows
/// (#211 auto-clamp; spec §7.3 requires empty levels to be omitted and the
/// remaining levels renumbered).
///
/// The most common shape is a coarse prefix: e.g. country-scale buildings
/// where every feature is culled by the visibility gates at world zooms, so
/// the written pyramid starts at the first zoom with visible features.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SkippedLevelReport {
    /// Index of the level in the *planned* (requested) level range
    /// (0 = requested coarsest). NOT an index into the written file.
    pub planned_level: usize,
    /// Planned ground sample distance in meters.
    pub gsd: f64,
    /// Planned Web Mercator zoom, if the level plan supplied one.
    pub zoom: Option<u8>,
}

/// One WARN for the planned levels omitted because no feature is visible at
/// their scale (#211 auto-clamp). No-op when nothing was skipped.
pub(super) fn warn_plan_skipped_levels(
    skipped: &[SkippedLevelReport],
    input_features: usize,
    first_written_gsd: f64,
    first_written_zoom: Option<u8>,
) {
    if skipped.is_empty() {
        return;
    }
    let ids: Vec<String> = skipped
        .iter()
        .map(|s| s.planned_level.to_string())
        .collect();
    let gsd_max = skipped.iter().map(|s| s.gsd).fold(f64::MIN, f64::max);
    let gsd_min = skipped.iter().map(|s| s.gsd).fold(f64::MAX, f64::min);
    let zoom_note = first_written_zoom.map_or_else(String::new, |z| format!(" (zoom {z})"));
    log::warn!(
        "omitting {} empty level(s) [{}] spanning GSD {:.2}–{:.2} m: none of the {} input \
         feature(s) are visible at those scales (visibility gates / density budget); the \
         output pyramid starts at GSD {:.2} m{}. To populate coarse levels, lower \
         --polygon-visibility/--line-visibility, or pass --collapse to keep sub-GSD \
         polygons as representative points (see docs/OVERVIEW_TUNING.md)",
        skipped.len(),
        ids.join(", "),
        gsd_max,
        gsd_min,
        input_features,
        first_written_gsd,
        zoom_note,
    );
}

/// Fold one [`OverviewWriter::write_level`] outcome into the driver
/// bookkeeping shared by both pipelines (#211): a written level appends a
/// [`LevelReport`] renumbered to the written count; an empty level (every
/// candidate collapsed during simplification) warns and records `planned` in
/// the skipped list instead.
pub(super) fn record_level_outcome(
    outcome: LevelWriteOutcome,
    planned: SkippedLevelReport,
    candidates: usize,
    rows: usize,
    vertices: usize,
    level_reports: &mut Vec<LevelReport>,
    skipped: &mut Vec<SkippedLevelReport>,
) {
    match outcome {
        LevelWriteOutcome::SkippedEmpty => {
            log::warn!(
                "level planned at GSD {:.2} m{} became empty after simplification \
                 (all {} candidate feature(s) collapsed); omitted from the output pyramid. \
                 Pass --collapse to keep sub-GSD polygons as representative points at \
                 coarse levels (see docs/OVERVIEW_TUNING.md)",
                planned.gsd,
                planned
                    .zoom
                    .map_or_else(String::new, |z| format!(" (zoom {z})")),
                candidates,
            );
            skipped.push(planned);
        }
        LevelWriteOutcome::Written => level_reports.push(LevelReport {
            level: level_reports.len(),
            gsd: planned.gsd,
            zoom: planned.zoom,
            feature_count: rows,
            vertex_count: vertices,
            uncompressed_bytes: 0,
            compressed_bytes: 0,
        }),
    }
}

/// Result of a conversion, `Serialize` for JSON output (benchmark tasks).
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ConvertReport {
    /// Level materialization mode used.
    pub mode: Mode,
    /// Per-level statistics, coarse→fine. `level` here is the index in the
    /// WRITTEN file, which is shifted down from the planned range when empty
    /// levels were skipped (see
    /// [`skipped_empty_levels`](Self::skipped_empty_levels)).
    pub levels: Vec<LevelReport>,
    /// Planned levels omitted because they contained no rows (#211
    /// auto-clamp), ordered by planned level. Empty when every planned level
    /// was written. The effective level range of the output is exactly
    /// [`levels`](Self::levels).
    pub skipped_empty_levels: Vec<SkippedLevelReport>,
    /// Number of source features read from the input.
    pub input_features: usize,
    /// Total rows written across all levels.
    pub total_rows: usize,
    /// Total vertices written across all levels.
    pub total_vertices: usize,
    /// Total compressed output size (bytes) across all levels.
    pub total_compressed_bytes: i64,
    /// Total row groups in the input file.
    pub row_groups_total: usize,
    /// Input row groups actually read. Less than
    /// [`row_groups_total`](Self::row_groups_total) only when
    /// [`ConvertOptions::bbox`] pruned row groups via the input's bbox
    /// covering statistics (#102).
    pub row_groups_read: usize,
    /// Features whose bbox spans more than 180° of longitude — almost
    /// certainly antimeridian-crossing geometry stored verbatim. Warned
    /// about (one aggregate `log::warn!`), never mutated; see
    /// `context/ANTIMERIDIAN.md` (issue #188).
    pub antimeridian_suspect_features: usize,
    /// Wall-clock conversion duration in seconds.
    pub duration_secs: f64,
    /// Remote-input fetch counters (#210): range requests issued and bytes
    /// downloaded, against the total object size. `None` for local inputs.
    /// With [`ConvertOptions::bbox`], `bytes_fetched / object_size` is the
    /// fraction of the remote file actually moved.
    pub remote_fetch: Option<crate::input::FetchStats>,
}

/// Errors from [`convert_to_overviews`].
#[derive(Debug, thiserror::Error)]
pub enum ConvertError {
    /// I/O error.
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    /// Opening the input failed (bad URL scheme, remote store error, ...).
    #[error("input error: {0}")]
    Input(#[from] crate::input::InputError),
    /// The property selection (#386) does not fit the input schema.
    #[error("property selection: {0}")]
    Properties(#[from] PropertySelectionError),
    /// Underlying parquet error (reading the input).
    #[error("parquet error: {0}")]
    Parquet(#[from] parquet::errors::ParquetError),
    /// Arrow error (concat / take / batch build).
    #[error("arrow error: {0}")]
    Arrow(#[from] arrow_schema::ArrowError),
    /// A core-library error (geometry decode, CRS extraction).
    #[error("{0}")]
    Core(#[from] crate::Error),
    /// The overview writer failed.
    #[error("writer error: {0}")]
    Writer(#[from] WriterError),
    /// The input CRS is neither EPSG:4326 nor EPSG:3857 (spec Q3).
    #[error("unsupported input CRS {crs:?}: overviews require EPSG:4326 or EPSG:3857")]
    UnsupportedCrs {
        /// The rejected CRS identifier.
        crs: String,
    },
    /// The input has no geometry column.
    #[error("input has no geometry column")]
    NoGeometryColumn,
    /// The `--sort-key` column is not present in the input schema.
    #[error("sort-key column {name:?} not found in input schema")]
    SortKeyColumnMissing {
        /// The requested column name.
        name: String,
    },
    /// Both a numeric sort key and a categorical class ranking were supplied.
    #[error("--sort-key and --class-rank are mutually exclusive; supply at most one")]
    RankingConflict,
    /// The `--class-rank` column is not present in the input schema.
    #[error("class-rank column {name:?} not found in input schema")]
    ClassRankColumnMissing {
        /// The requested column name.
        name: String,
    },
    /// The `--class-rank` column is not a string (Utf8/LargeUtf8) column.
    #[error("class-rank column {name:?} is {data_type} but must be a string column")]
    ClassRankColumnNotString {
        /// The requested column name.
        name: String,
        /// The actual Arrow data type found.
        data_type: String,
    },
    /// The level plan is invalid (empty / non-monotonic / bad zoom range).
    #[error("invalid level specification: {0}")]
    InvalidLevels(String),
    /// A conversion knob carries a nonsensical value (non-finite or
    /// non-positive where a positive finite value is required).
    #[error("invalid option: {0}")]
    InvalidConfig(String),
    /// The attribute filter (#315) failed to parse or bind against the input
    /// schema (unknown column, type mismatch, unsupported column type).
    #[error(transparent)]
    Filter(#[from] super::filter::FilterError),
    /// `--cluster` was requested in partitioning mode. A partitioning row is
    /// read at MANY display zooms (prefix reads, §2.3) but exists at exactly
    /// one level, so a single stored `point_count` cannot reflect "that
    /// level's grid" for every zoom it is displayed at — and absorbed
    /// features reappear as their own rows at finer levels while remaining
    /// counted in coarser winners, double-counting every prefix sum.
    #[error(
        "--cluster requires duplicating mode: a partitioning-mode feature has one \
         row read across many zoom prefixes, so a per-level point_count cannot be \
         represented without double counting"
    )]
    ClusterPartitioningUnsupported,
    /// Verbatim tiling was requested in partitioning mode, where it degenerates.
    ///
    /// Partitioning places each feature at exactly its `min_level` (§2.3), and
    /// `min_level` is the coarsest level whose thinning grid the feature wins.
    /// With thinning off every feature wins at level 0, so the entire dataset
    /// lands in the coarsest level and every finer level is emitted empty —
    /// the opposite of "every level reproduces the input". Duplicating mode is
    /// what makes verbatim meaningful, because it writes each feature at every
    /// level it is visible at.
    #[error(
        "--verbatim requires duplicating mode: partitioning places each feature at \
         exactly one level, so with thinning off every feature lands in the coarsest \
         level and every finer level is empty"
    )]
    VerbatimPartitioningUnsupported,
    /// `--accumulate-attribute` was supplied without `--cluster`.
    #[error("--accumulate-attribute requires --cluster")]
    AccumulateWithoutCluster,
    /// Multi-partition input (directory / glob) reached the in-memory
    /// reference pipeline, which reads through a single parquet builder.
    #[error(
        "multi-partition input requires the streaming pipeline; \
         remove --no-streaming"
    )]
    MultiPartitionRequiresStreaming,
    /// An `--accumulate-attribute` column is not present in the input schema.
    #[error("accumulate-attribute column {name:?} not found in input schema")]
    AccumulateColumnMissing {
        /// The requested column name.
        name: String,
    },
    /// An `--accumulate-attribute` column is not numeric.
    #[error(
        "accumulate-attribute column {name:?} is {data_type} but must be numeric \
         (int/uint/float)"
    )]
    AccumulateColumnNotNumeric {
        /// The requested column name.
        name: String,
        /// The actual Arrow data type found.
        data_type: String,
    },
    /// The input already contains a `point_count` column (clustering enabled).
    #[error(
        "input already contains a '{POINT_COUNT_COLUMN}' column; rename it before \
         converting with --cluster"
    )]
    PointCountColumnPresent,
    /// The input already contains a `coalesced_count` column (coalescing
    /// enabled).
    #[error(
        "input already contains a '{COALESCED_COUNT_COLUMN}' column; rename it \
         before converting with --coalesce-lines"
    )]
    CoalescedCountColumnPresent,
    /// The input has no features, or every feature was dropped from every level.
    #[error("no output rows produced (empty input or all features dropped)")]
    NoData,
    /// The strict cluster accounting / sum invariant (spec §12.1) was
    /// violated while building the per-level cluster tables: a level's
    /// `point_count` values would not partition the source point set (or a
    /// clustered level thinned its points to zero with source points left
    /// to absorb). This is a producer bug guard — a conforming conversion
    /// can never trip it.
    #[error("cluster invariant violated (spec §12.1): {0}")]
    ClusterInvariant(String),
}

/// Convert a GeoParquet file into a multi-resolution overview GeoParquet file.
///
/// See the module documentation for the pipeline. Returns a [`ConvertReport`]
/// describing the levels written.
/// Validate the numeric conversion knobs (H4 hostile-input hardening).
///
/// A NaN, infinite, or non-positive thinning factor (or GSD base) silently
/// degenerates the assignment grid — every cell-winner pass would skip every
/// feature — so nonsensical values are rejected up front with a clear error
/// instead of producing an "everything at the canonical level" file.
fn validate_options(options: &ConvertOptions) -> Result<(), ConvertError> {
    let positive = |name: &str, v: f64| {
        if !v.is_finite() || v <= 0.0 {
            return Err(ConvertError::InvalidConfig(format!(
                "{name} = {v} must be a finite value > 0"
            )));
        }
        Ok(())
    };
    let non_negative = |name: &str, v: f64| {
        if !v.is_finite() || v < 0.0 {
            return Err(ConvertError::InvalidConfig(format!(
                "{name} = {v} must be a finite value >= 0"
            )));
        }
        Ok(())
    };
    positive("gsd-base", options.gsd_base)?;
    // Thinning factors accept 0 as the documented OFF switch (#345/#360):
    // every feature is its own cell, so nothing is thinned. Negative and
    // non-finite values remain meaningless.
    non_negative("point-thinning", options.assign.point_thinning)?;
    non_negative("line-thinning", options.assign.line_thinning)?;
    non_negative("polygon-thinning", options.assign.polygon_thinning)?;
    non_negative("line-visibility", options.assign.line_visibility)?;
    non_negative("polygon-visibility", options.assign.polygon_visibility)?;
    // Negative snap / junction-angle values are documented OFF switches; only
    // NaN is meaningless.
    if options.coalesce_snap.is_nan() {
        return Err(ConvertError::InvalidConfig(
            "coalesce-snap must not be NaN (use <= 0 to disable snapping)".to_string(),
        ));
    }
    if options.coalesce_junction_angle.is_nan() {
        return Err(ConvertError::InvalidConfig(
            "coalesce-junction-angle must not be NaN (use 0 to disable)".to_string(),
        ));
    }
    if let Some(bb) = &options.bbox {
        if bb.iter().any(|v| !v.is_finite()) {
            return Err(ConvertError::InvalidConfig(format!(
                "bbox {bb:?} must contain only finite values"
            )));
        }
        if bb[0] > bb[2] || bb[1] > bb[3] {
            return Err(ConvertError::InvalidConfig(format!(
                "bbox {bb:?} must satisfy xmin <= xmax and ymin <= ymax"
            )));
        }
    }
    // Attribute filter (#315): fail fast on a syntactically invalid
    // expression, before any input is opened. Binding (unknown column /
    // type mismatch) happens later, once the schema is known.
    if let Some(f) = &options.filter {
        super::filter::parse_filter(f)?;
    }
    // Zoom-band representation selector (#317 / #279).
    if !options.representation.is_empty() {
        if matches!(options.mode, Mode::Partitioning)
            && options
                .representation
                .iter()
                .any(|b| b.repr != Representation::Geometry)
        {
            return Err(ConvertError::InvalidConfig(
                "representation bands require duplicating mode: partitioning places \
                 each feature exactly once with geometry verbatim (spec §2.3), which \
                 a point or square representation cannot satisfy"
                    .to_string(),
            ));
        }
        let (plan_min, plan_max) = match &options.levels {
            LevelPlan::ZoomRange { min_zoom, max_zoom } => (*min_zoom, *max_zoom),
            LevelPlan::Gsds(_) => {
                return Err(ConvertError::InvalidConfig(
                    "representation bands require a zoom-range level plan \
                     (--min-zoom/--max-zoom); an explicit --gsd plan carries no \
                     per-level zooms to band on"
                        .to_string(),
                ));
            }
        };
        for band in &options.representation {
            let (lo, hi, repr) = (band.min_zoom, band.max_zoom, band.repr);
            let kw = repr.as_str();
            if lo > hi {
                return Err(ConvertError::InvalidConfig(format!(
                    "representation band {lo}-{hi}:{kw} must satisfy LO <= HI"
                )));
            }
            if lo < plan_min || hi > plan_max {
                return Err(ConvertError::InvalidConfig(format!(
                    "representation band {lo}-{hi}:{kw} lies outside the level plan \
                     ({plan_min}-{plan_max})"
                )));
            }
            if repr != Representation::Geometry && hi >= plan_max {
                return Err(ConvertError::InvalidConfig(format!(
                    "representation band {lo}-{hi}:{kw} must end before the plan's \
                     max zoom ({plan_max}): the canonical (finest) level reproduces \
                     source geometry verbatim (spec §2.4)"
                )));
            }
        }
        // Overlap: each zoom may be claimed by at most one band.
        let mut claimed: Vec<Option<Representation>> =
            vec![None; plan_max as usize - plan_min as usize + 1];
        for band in &options.representation {
            for z in band.min_zoom..=band.max_zoom {
                let slot = &mut claimed[(z - plan_min) as usize];
                if slot.is_some() {
                    return Err(ConvertError::InvalidConfig(format!(
                        "representation bands overlap at zoom {z}"
                    )));
                }
                *slot = Some(band.repr);
            }
        }
        // Point-prefix rule: every zoom coarser than a point zoom is a point
        // zoom. The cascade fold's point passes through coarser levels
        // untouched whatever they declare, so anything else would silently
        // not do what the spec string says.
        let mut seen_non_point_coarser = false;
        for slot in &claimed {
            match slot {
                Some(Representation::Point) => {
                    if seen_non_point_coarser {
                        return Err(ConvertError::InvalidConfig(
                            "point bands must start at the plan's min zoom and be \
                             contiguous from the coarsest level: a coarser non-point \
                             level would still receive the cascaded point"
                                .to_string(),
                        ));
                    }
                }
                _ => seen_non_point_coarser = true,
            }
        }
    }
    // in_flight_batches == 0 is the IN_FLIGHT_BATCHES_AUTO sentinel (resolved
    // to available parallelism at pass-2 setup), not an error. Any explicit
    // positive value is honoured verbatim, so there is nothing to reject here.
    // #272: fail fast on a bad spill dir — the spill is best-effort, so a
    // mid-convert creation failure would only surface as a silent degrade
    // to network re-fetch.
    if let Some(dir) = &options.spill_dir {
        if !dir.is_dir() {
            return Err(ConvertError::InvalidConfig(format!(
                "spill-dir {} is not an existing directory",
                dir.display()
            )));
        }
    }
    Ok(())
}

/// One zoom band of the representation selector (#317 / #279): levels whose
/// zoom lies in `min_zoom..=max_zoom` (inclusive) take `repr`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RepresentationBand {
    /// Coarsest zoom of the band (inclusive).
    pub min_zoom: u8,
    /// Finest zoom of the band (inclusive).
    pub max_zoom: u8,
    /// Representation applied at the band's levels.
    pub repr: Representation,
}

/// The [`Representation`] for a zoom under a set of bands (unclaimed zooms
/// default to [`Representation::Geometry`]).
pub(super) fn representation_for_zoom(
    bands: &[RepresentationBand],
    zoom: Option<u8>,
) -> Representation {
    let Some(z) = zoom else {
        return Representation::Geometry;
    };
    bands
        .iter()
        .find(|b| b.min_zoom <= z && z <= b.max_zoom)
        .map(|b| b.repr)
        .unwrap_or_default()
}

/// Parse a representation spec string (#317 / #279): comma-separated
/// `LO-HI:KIND` (or `Z:KIND`) entries, e.g. `0-7:point,8-14:geom` or
/// `0-5:square`. KIND is one of `geom` (alias `geometry`), `point`,
/// `square`. Shared by the CLI and the Python bindings so the grammar has a
/// single definition; structural validity against the level plan is checked
/// later by convert-entry validation.
pub fn parse_representation_spec(spec: &str) -> Result<Vec<RepresentationBand>, String> {
    let mut bands = Vec::new();
    for part in spec.split(',') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        let (range, kind) = part.split_once(':').ok_or_else(|| {
            format!("representation entry {part:?} must be LO-HI:KIND (e.g. 0-7:point)")
        })?;
        let repr = match kind.trim() {
            "geom" | "geometry" => Representation::Geometry,
            "point" => Representation::Point,
            "square" => Representation::Square,
            other => {
                return Err(format!(
                    "unknown representation {other:?} (expected geom, point, or square)"
                ))
            }
        };
        let range = range.trim();
        let (lo, hi) = match range.split_once('-') {
            Some((lo, hi)) => (lo.trim(), hi.trim()),
            None => (range, range),
        };
        let parse_zoom = |s: &str| {
            s.parse::<u8>()
                .map_err(|_| format!("invalid zoom {s:?} in representation entry {part:?}"))
        };
        bands.push(RepresentationBand {
            min_zoom: parse_zoom(lo)?,
            max_zoom: parse_zoom(hi)?,
            repr,
        });
    }
    if bands.is_empty() {
        return Err("representation spec is empty".to_string());
    }
    Ok(bands)
}

/// Per-level [`Representation`] (#317 / #279), parallel to `level_specs`
/// (the resolved plan). Levels without a zoom (explicit-GSD plans) are never
/// banded; [`validate_options`] rejects that combination up front.
pub(super) fn level_representations(
    level_specs: &[(f64, Option<u8>)],
    bands: &[RepresentationBand],
) -> Vec<Representation> {
    level_specs
        .iter()
        .map(|&(_, zoom)| representation_for_zoom(bands, zoom))
        .collect()
}

pub fn convert_to_overviews(
    input_path: impl AsRef<Path>,
    output_path: impl AsRef<Path>,
    options: &ConvertOptions,
) -> Result<ConvertReport, ConvertError> {
    // Local path, remote URL (s3://, https://, gs:// — #210), or a
    // multi-partition directory / glob pattern (v0.7): directories and
    // globs resolve to an ordered, validated set of local partitions read
    // as one logical dataset; remote objects are read with byte-range
    // requests through the same sync parquet plumbing, composing with the
    // bbox row-group pruning below so pruned row groups are never
    // downloaded at all.
    let source = ConvertSource::resolve_path(input_path.as_ref())?;
    convert_to_overviews_source_strategy(
        &source,
        output_path.as_ref(),
        options,
        super::stream::Pass2Strategy::Pipelined,
    )
}

/// [`convert_to_overviews`] over an already-resolved [`ConvertSource`] —
/// the entry point for callers that build the (possibly multi-partition)
/// source themselves: a `--files-from` manifest
/// ([`ConvertSource::from_manifest`]), an explicit input list
/// ([`ConvertSource::from_input_list`]), or custom object stores.
///
/// A source is single-use once a property selection (`options.properties`,
/// #386) has been applied to it: the column projection lives on the
/// `ConvertSource`, so a second conversion through the same source is an
/// error — with any selection, the default included.
pub fn convert_to_overviews_sources(
    source: &ConvertSource,
    output_path: &Path,
    options: &ConvertOptions,
) -> Result<ConvertReport, ConvertError> {
    convert_to_overviews_source_strategy(
        source,
        output_path,
        options,
        super::stream::Pass2Strategy::Pipelined,
    )
}

/// [`convert_to_overviews`] over an already-resolved [`InputSource`] — the
/// entry point for callers that construct the source themselves (custom
/// object stores, tests over in-memory stores).
pub fn convert_to_overviews_source(
    source: &InputSource,
    output_path: &Path,
    options: &ConvertOptions,
) -> Result<ConvertReport, ConvertError> {
    // `InputSource` clones are cheap handles sharing caches and counters.
    convert_to_overviews_source_strategy(
        &ConvertSource::single(source.clone()),
        output_path,
        options,
        super::stream::Pass2Strategy::Pipelined,
    )
}

/// [`convert_to_overviews`] over a path with an explicit pass-2
/// [`Pass2Strategy`] — tests pin the serial reference strategy through the
/// exact production setup.
///
/// [`Pass2Strategy`]: super::stream::Pass2Strategy
#[cfg(test)]
pub(crate) fn convert_to_overviews_strategy(
    input_path: impl AsRef<Path>,
    output_path: impl AsRef<Path>,
    options: &ConvertOptions,
    strategy: super::stream::Pass2Strategy,
) -> Result<ConvertReport, ConvertError> {
    let source = ConvertSource::resolve_path(input_path.as_ref())?;
    convert_to_overviews_source_strategy(&source, output_path.as_ref(), options, strategy)
}

/// Decode every geometry in `full` (row-aligned to the batch) and drop the rows
/// that cannot participate in level assignment: a null/empty/non-finite
/// geometry, or — under a regional extract (#102) — one whose bbox misses
/// `bbox_units`. The batch and the geometry vec are filtered together so every
/// downstream index stays aligned. Returns the filtered batch and its surviving
/// geometries.
fn decode_and_filter_geometries(
    full: RecordBatch,
    geom_idx: usize,
    geom_field: &Field,
    bbox_units: Option<&[f64; 4]>,
    filter_mask: Option<&[Option<bool>]>,
) -> Result<(RecordBatch, Vec<Geometry<f64>>), ConvertError> {
    let geom_array: Arc<dyn GeoArrowArray> =
        from_arrow_array(full.column(geom_idx).as_ref(), geom_field)
            .map_err(|e| crate::Error::GeoParquetRead(format!("geometry decode: {e}")))?;
    let mut geom_opts: Vec<Option<Geometry<f64>>> = Vec::with_capacity(full.num_rows());
    extract_geometries_opt_from_array(geom_array.as_ref(), &mut geom_opts)?;
    let mut geom_skipped = 0usize;
    let keep: Vec<bool> = geom_opts
        .iter()
        .enumerate()
        .map(|(i, g)| {
            // Attribute filter (#315): a row is kept only when the predicate
            // evaluated TRUE (SQL-UNKNOWN drops, like FALSE).
            if let Some(mask) = filter_mask {
                if mask[i] != Some(true) {
                    return false;
                }
            }
            match g.as_ref().filter(|g| usable_geometry(g)) {
                // Regional extract (#102): drop features whose bbox misses the
                // requested region exactly, independent of row-group pruning.
                Some(g) => bbox_units.is_none_or(|bb| bboxes_intersect(&geometry_bbox(g), bb)),
                None => {
                    geom_skipped += 1;
                    false
                }
            }
        })
        .collect();
    let dropped = keep.iter().filter(|k| !**k).count();
    if dropped == 0 {
        return Ok((full, geom_opts.into_iter().flatten().collect()));
    }
    if geom_skipped > 0 {
        log::warn!(
            "skipping {geom_skipped} of {} input rows with a null, empty, or \
             non-finite geometry",
            full.num_rows()
        );
    }
    let mask = arrow_array::BooleanArray::from(keep.clone());
    let filtered = arrow_select::filter::filter_record_batch(&full, &mask)?;
    let geoms = geom_opts
        .into_iter()
        .zip(&keep)
        .filter(|(_, k)| **k)
        .map(|(g, _)| g.expect("kept rows are Some"))
        .collect();
    Ok((filtered, geoms))
}

/// Adjustments both pipelines make before converting, or `None` to use the
/// options as given.
///
/// These are silent-by-default traps, so each one logs. They are applied here
/// rather than in the CLI so that every caller gets them — the Python bindings
/// and direct library users included, where the untouched defaults delete the
/// features a ladder has just promoted.
pub(crate) fn adjusted_for_ladder_and_mode(options: &ConvertOptions) -> Option<ConvertOptions> {
    // Q3 / #364: coalescing replaces source lines with merged chains and
    // re-derives their features, so a chain has no entry zoom to inherit and
    // the coalescer's own gate would re-drop the lines a ladder promoted.
    // Partitioning cannot represent a merged chain at all (§2.3).
    let coalescing_off = options.coalesce_lines
        && match options.mode {
            Mode::Partitioning => Some(
                "line coalescing is inert in partitioning mode (feature-once / \
                 geometry-verbatim contract); converting without it",
            ),
            _ if options.entry_zoom.is_some() => Some(
                "line coalescing is inert with an entry-zoom ladder (a merged chain \
                 has no entry zoom to inherit, and coalescing would re-gate the \
                 lines the ladder promoted); converting without it",
            ),
            _ => None,
        }
        .inspect(|why| log::info!("{why}"))
        .is_some();

    // #364: a promoted feature is, by construction, below its new level's
    // simplification tolerance, so the drop default deletes it again at exactly
    // the levels it was promoted to — and a level left with nothing is omitted
    // from the file entirely.
    let collapse_to_point =
        options.entry_zoom.is_some() && matches!(options.simplify.collapse, CollapseMode::Drop);
    if collapse_to_point {
        log::info!(
            "an entry-zoom ladder implies collapse-to-point: a promoted feature is \
             usually below its level's simplification tolerance and would be deleted \
             there instead of drawn. Coarse levels therefore carry representative \
             POINTS for those features — style them with a circle layer, or ask for \
             --collapse-square to keep polygons."
        );
    }

    // #384: partitioning levels are verbatim, so neither the tiny-polygon
    // accumulator (a carrier is a second appearance of a feature) nor the
    // write-time dither ever runs there. Say so rather than silently
    // producing the same file the flag was meant to change.
    if matches!(options.mode, Mode::Partitioning)
        && matches!(options.simplify.collapse, CollapseMode::Square)
    {
        log::info!(
            "collapse-square has no effect in partitioning mode (levels are verbatim: \
             no polygon is dropped or collapsed, so there is nothing to stand in for)"
        );
    }

    if !coalescing_off && !collapse_to_point {
        return None;
    }
    Some(ConvertOptions {
        coalesce_lines: options.coalesce_lines && !coalescing_off,
        simplify: SimplifyOptions {
            collapse: if collapse_to_point {
                CollapseMode::Point
            } else {
                options.simplify.collapse
            },
            ..options.simplify
        },
        ..options.clone()
    })
}

#[cfg(test)]
mod ladder_adjustment_tests {
    use super::*;

    fn with_ladder() -> ConvertOptions {
        ConvertOptions {
            entry_zoom: Some(crate::overview::ladder::EntryZoomSpec {
                column: "level".to_string(),
                kind: crate::overview::ladder::EntryZoomKind::DenseRank { step: 1 },
            }),
            ..Default::default()
        }
    }

    /// #364: the implication lives in core, so the CLI is not the only caller
    /// that gets it. The Python bindings previously lost the whole coarsest
    /// level to the drop default, taking the features the ladder had just
    /// promoted with it.
    #[test]
    fn ladder_implies_collapse_to_point() {
        let adjusted = adjusted_for_ladder_and_mode(&with_ladder())
            .expect("a ladder must trigger an adjustment");
        assert_eq!(adjusted.simplify.collapse, CollapseMode::Point);
    }

    /// An explicit choice is never overridden.
    #[test]
    fn an_explicit_collapse_square_survives_the_implication() {
        let mut o = with_ladder();
        o.simplify.collapse = CollapseMode::Square;
        let adjusted = adjusted_for_ladder_and_mode(&o);
        assert!(adjusted.is_none_or(|a| a.simplify.collapse == CollapseMode::Square));
    }

    /// Coalescing replaces lines with merged chains that carry no entry zoom,
    /// which made the ladder a silent no-op for line features.
    #[test]
    fn ladder_turns_line_coalescing_off() {
        let mut o = with_ladder();
        o.coalesce_lines = true;
        let adjusted = adjusted_for_ladder_and_mode(&o).expect("adjusted");
        assert!(!adjusted.coalesce_lines);
    }

    /// Without a ladder nothing is adjusted, so default output is untouched.
    #[test]
    fn no_ladder_means_no_adjustment() {
        assert!(adjusted_for_ladder_and_mode(&ConvertOptions::default()).is_none());
    }
}

/// Option combinations that no pipeline can honour, checked once for both.
///
/// These are rejections rather than silent adjustments: each one would
/// otherwise produce a structurally valid file that is not what was asked for,
/// which is harder to notice than an error.
fn check_mode_combinations(options: &ConvertOptions) -> Result<(), ConvertError> {
    // Q4: a partitioning-mode feature has one row read across many zoom
    // prefixes, so a per-level point_count cannot be represented.
    if options.cluster && matches!(options.mode, Mode::Partitioning) {
        return Err(ConvertError::ClusterPartitioningUnsupported);
    }
    // Verbatim degenerates in partitioning mode rather than doing nothing:
    // every feature wins level 0, and partitioning writes it there and nowhere
    // else. Rejecting beats emitting a pyramid whose finer levels are all
    // empty and whose warning blames the visibility gates.
    if options.generalization_is_off() && matches!(options.mode, Mode::Partitioning) {
        return Err(ConvertError::VerbatimPartitioningUnsupported);
    }
    // Aggregation is meaningless without clustering.
    if !options.accumulate.is_empty() && !options.cluster {
        return Err(ConvertError::AccumulateWithoutCluster);
    }
    Ok(())
}

/// Columns the tuning knobs read, paired with the knob that reads them —
/// these must survive the property selection (#386).
fn knob_columns(options: &ConvertOptions) -> Vec<(String, String)> {
    let mut out = Vec::new();
    if let Some(c) = &options.sort_key {
        out.push((c.clone(), "--sort-key".to_string()));
    }
    if let Some(r) = &options.class_ranking {
        out.push((r.column.clone(), "--class-rank".to_string()));
    }
    if let Some(e) = &options.entry_zoom {
        out.push((
            e.column.clone(),
            "--magnitude-ladder / --entry-zoom".to_string(),
        ));
    }
    for a in &options.accumulate {
        out.push((a.column.clone(), "--accumulate-attribute".to_string()));
    }
    if let Some(f) = &options.filter {
        // Syntax was validated by `validate_options`; a parse failure here
        // would already have been reported, so an unparsable filter simply
        // contributes no required columns.
        if let Ok(expr) = super::filter::parse_filter(f) {
            for c in expr.column_names() {
                out.push((c, "--filter".to_string()));
            }
        }
    }
    out
}

/// Apply `options.properties` (#386) to `source`: resolve the selection
/// against the file schema and restrict every later read to the kept
/// columns. A no-op for the default (keep everything).
///
/// The projection lives on the source, so a source that already carries
/// one is refused whatever the new selection — the default included, which
/// would otherwise silently produce a file narrowed to the earlier call's
/// columns. One rule: a `ConvertSource` is single-use once a selection has
/// been applied.
fn apply_property_selection(
    source: &ConvertSource,
    options: &ConvertOptions,
) -> Result<(), ConvertError> {
    if source.column_projection().is_some() {
        return Err(
            crate::input::InputError::Arrow(arrow_schema::ArrowError::SchemaError(
                "column restriction already applied to this source; a ConvertSource is \
                 single-use once a property selection has been applied"
                    .to_string(),
            ))
            .into(),
        );
    }
    if options.properties.is_identity() {
        return Ok(());
    }
    let schema = source.file_schema()?;
    let geom_idx = find_geometry_column(&schema).ok_or(ConvertError::NoGeometryColumn)?;
    let mut warn = |msg: String| log::warn!("[convert] {msg}");
    let keep = options
        .properties
        .resolve(&schema, geom_idx, &knob_columns(options), &mut warn)?;
    let kept_names: Vec<&str> = keep
        .iter()
        .filter(|&&i| i != geom_idx)
        .map(|&i| schema.field(i).name().as_str())
        .collect();
    let dropped = schema.fields().len() - keep.len();
    log::info!(
        "[convert] property selection: keeping {} of {} property column(s) ({}), dropping {dropped}",
        kept_names.len(),
        schema.fields().len() - 1,
        if kept_names.is_empty() {
            "none — geometry only".to_string()
        } else {
            kept_names
                .iter()
                .map(|n| format!("{n:?}"))
                .collect::<Vec<_>>()
                .join(", ")
        }
    );
    source.restrict_columns(keep)?;
    Ok(())
}

/// Apply the property selection (#386) to the in-memory path's parquet
/// builder as a read projection — exactly what the streaming path gets
/// through `ConvertSource::schema` — and return the builder with the schema
/// its batches will carry.
fn project_builder_to_selection(
    source: &ConvertSource,
    builder: parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder<
        crate::input::InputReader,
    >,
) -> Result<
    (
        parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder<crate::input::InputReader>,
        SchemaRef,
    ),
    ConvertError,
> {
    match source.column_projection() {
        Some(keep) => {
            let mask = parquet::arrow::ProjectionMask::roots(
                builder.parquet_schema(),
                keep.iter().copied(),
            );
            let projected = Arc::new(builder.schema().project(keep)?);
            Ok((builder.with_projection(mask), projected))
        }
        None => {
            let schema = builder.schema().clone();
            Ok((builder, schema))
        }
    }
}

/// Intern the class-group column that line coalescing (Q3) groups chains by.
///
/// `None` unless the resolved ranking is class-based, which is what supplies
/// the grouping column.
fn intern_coalesce_groups(
    input_schema: &Schema,
    full: &RecordBatch,
    ranking_provenance: &RankingProvenance,
) -> Option<Vec<u32>> {
    let col = coalesce_group_column(ranking_provenance)?;
    let idx = input_schema.index_of(col).expect("ranking column exists");
    let mut interner = GroupInterner::default();
    let mut groups = Vec::with_capacity(full.num_rows());
    interner.extend(full.column(idx).as_ref(), &mut groups);
    Some(groups)
}

/// Build the cluster tables (Q4) and check the §12.1 sum invariant.
///
/// `acc_values` holds one vector per accumulate spec, indexed by position in
/// `features` (not by input row).
pub(super) fn build_verified_cluster_tables(
    features: &[AssignFeature],
    min_levels: &[u8],
    level_gsds: &[f64],
    acc_values: &[Vec<Option<f64>>],
    crs: Crs,
    options: &ConvertOptions,
) -> Result<ClusterTables, ConvertError> {
    let ops: Vec<_> = options.accumulate.iter().map(|s| s.op).collect();
    let tables = build_cluster_tables(
        features,
        min_levels,
        level_gsds,
        &options.assign,
        crs,
        acc_values,
        &ops,
    );
    // Strict §12.1 accounting: Σ point_count per level == source point count,
    // and no clustered level thins its points to zero.
    verify_sum_invariant(features, min_levels, &tables).map_err(ConvertError::ClusterInvariant)?;
    Ok(tables)
}

/// The in-memory input table, plus everything the footer settles about it.
///
/// The in-memory reference path reads the whole (row-group-pruned, attribute-
/// filtered) input into one `RecordBatch` and decodes its geometries once.
struct LoadedInput {
    /// `options` with reserved-column renames applied (#288); the caller
    /// borrows this for the rest of the conversion.
    options: ConvertOptions,
    input_schema: SchemaRef,
    crs: Crs,
    renames: Vec<(String, String)>,
    geom_idx: usize,
    geom_field: Field,
    /// Schema indices of the accumulate columns (Q4).
    acc_cols: Vec<usize>,
    /// The filtered table, relabelled to `input_schema`.
    full: RecordBatch,
    /// Decoded geometries, row-aligned with `full`.
    geometries: Vec<Geometry<f64>>,
    row_groups_total: usize,
    row_groups_read: usize,
}

fn load_input_table(
    source: &ConvertSource,
    source_single: &InputSource,
    options: &ConvertOptions,
) -> Result<LoadedInput, ConvertError> {
    // --- Read the input footer, preserving the full property schema. ---------
    // (For a remote source, the footer is range-fetched once and cached.)
    // `read_schema` matches the raw batches read below; `input_schema` is the
    // possibly-renamed schema used for every downstream (name-based) lookup.
    let (builder, read_schema) = project_builder_to_selection(source, source_single.open()?)?;

    // --- CRS detection + rejection (spec Q3) — footer metadata only. ---------
    let crs = detect_crs_from_kv(builder.metadata().file_metadata().key_value_metadata())?;

    // Reserved-column collisions (#288): rename any input column named `level`
    // / `point_count` / `coalesced_count` (case-insensitive) out of the way
    // rather than reject the file, keeping the reserved output columns
    // authoritative. `options` is cloned so by-name ranking/accumulate options
    // can be rewritten to the renamed columns. The rename preserves column
    // order, so `read_schema` and `input_schema` share indices.
    let mut resolved = options.clone();
    let (input_schema, renames) = resolve_reserved_column_collisions(&read_schema, &mut resolved);
    let options = &resolved;

    // Attribute filter (#315): parse + bind against the (possibly renamed)
    // input schema. Syntax was already validated in `validate_options`.
    let bound_filter = bind_attribute_filter(options, &input_schema, &renames)?;

    let geom_idx = find_geometry_column(&input_schema).ok_or(ConvertError::NoGeometryColumn)?;
    let geom_field = input_schema.field(geom_idx).clone();

    // Clustering schema checks + accumulate column resolution (Q4).
    let acc_cols = validate_cluster_schema(&input_schema, options)?;
    // Coalescing schema check (Q3).
    validate_coalesce_schema(&input_schema, options)?;

    // Regional extract (#102) + attribute filter (#315): prune input row
    // groups by footer statistics (bbox covering stats / per-column
    // min-max-null stats), before any data pages are read. The two prunings
    // compose by intersection. Groups without stats are kept; the exact
    // per-feature filters below guarantee identical output either way.
    let row_groups_total = builder.metadata().num_row_groups();
    let bbox_units = options.bbox.map(|b| bbox_to_crs_units(&b, crs));
    let combined_sel = select_input_row_groups_combined(
        builder.metadata(),
        bbox_units.as_ref(),
        bound_filter.as_ref(),
    );
    let (builder, row_groups_read) = match combined_sel {
        Some(sel) => {
            let n = sel.len();
            let what = pruning_label(bbox_units.is_some(), bound_filter.is_some());
            log::info!("{what} filter: reading {n}/{row_groups_total} input row groups");
            (builder.with_row_groups(sel), n)
        }
        None => (builder, row_groups_total),
    };

    let reader = builder.build()?;
    let mut batches: Vec<RecordBatch> = Vec::new();
    for batch in reader {
        batches.push(batch?);
    }
    // Concat with `read_schema` (the raw batches carry the original names).
    let full = concat_batches(&read_schema, &batches)?;

    // Decode geometries once (in-memory v1), row-aligned. Rows with a null,
    // empty, or non-finite geometry cannot participate in level assignment:
    // they are dropped, from the batch and the geometry vec together, so every
    // downstream index stays aligned (H4: an interleaved null geometry must
    // never shift attributes onto a neighboring row's geometry).
    // Attribute filter (#315): evaluate the predicate over the full table
    // once (identity projection — the raw batch carries the full schema, and
    // the #288 rename is order-preserving so indices line up).
    let filter_mask: Option<Vec<Option<bool>>> =
        bound_filter.as_ref().map(|f| f.eval_mask(&full, &|i| i));
    let (full, geometries) = decode_and_filter_geometries(
        full,
        geom_idx,
        &geom_field,
        bbox_units.as_ref(),
        filter_mask.as_deref(),
    )?;

    // Apply the reserved-column renames (#288) to the in-memory table. Columns
    // are positional, so re-associating them with the renamed schema is a
    // metadata-only relabel (a no-op when nothing collided).
    let full = if Arc::ptr_eq(&input_schema, &read_schema) {
        full
    } else {
        RecordBatch::try_new(input_schema.clone(), full.columns().to_vec())?
    };

    Ok(LoadedInput {
        options: resolved.clone(),
        input_schema,
        crs,
        renames,
        geom_idx,
        geom_field,
        acc_cols,
        full,
        geometries,
        row_groups_total,
        row_groups_read,
    })
}

struct EmittedLevel {
    /// Index in the resolved level plan (cluster-table key; may differ
    /// from the emitted index when empty levels are omitted, §7.3).
    orig: usize,
    gsd: f64,
    zoom: Option<u8>,
    indices: Vec<usize>,
    geoms: Vec<Geometry<f64>>,
    vertex_count: usize,
    /// Coalescing (Q3): this level's chain table (rep row → merged
    /// geometry + member count). `None` at non-coalesced levels.
    coalesce: Option<CoalesceTable>,
}

/// Build every level's generalized selection, coarse to fine.
///
/// Returns the emitted levels and the planned levels that were omitted because
/// every candidate collapsed (§7.3, #211 auto-clamp).
#[allow(clippy::too_many_arguments)]
fn build_emitted_levels(
    assignment: &Assignment,
    features: &[AssignFeature],
    geometries: &[Geometry<f64>],
    level_specs: &[(f64, Option<u8>)],
    level_reprs: &[Representation],
    line_groups: Option<&Vec<u32>>,
    coalesce_on: bool,
    finest: usize,
    crs: Crs,
    // Coarsest level per input row (#384), and per planned level the
    // tiny-polygon accumulator's carrier rows.
    row_min_levels: &[u8],
    carriers: &[Vec<usize>],
    options: &ConvertOptions,
) -> (Vec<EmittedLevel>, Vec<SkippedLevelReport>) {
    // --- Build per-level generalized selections (coarse→fine). ---------------
    // Each emitted entry: (spec, feature indices, geometries, vertex_count).
    let mut emitted: Vec<EmittedLevel> = Vec::new();
    let mut skipped: Vec<SkippedLevelReport> = Vec::new();

    for (level, &(gsd_m, zoom)) in level_specs.iter().enumerate() {
        let member_indices: Vec<usize> = match options.mode {
            Mode::Duplicating => {
                let mut v = assignment.duplicating_at_level(level as u8);
                // #384: carriers join the level (sorted merge; disjoint from
                // members by construction).
                if !carriers[level].is_empty() {
                    v.extend_from_slice(&carriers[level]);
                    v.sort_unstable();
                }
                v
            }
            Mode::Partitioning => assignment.partitioning_at_level(level as u8),
        };

        // Verbatim path: partitioning at every level (§2.3), and duplicating at
        // the canonical (finest) level (§2.4). Otherwise simplify per feature.
        let verbatim = matches!(options.mode, Mode::Partitioning) || level == finest;

        // Coalescing (Q3): at non-canonical duplicating levels, ALL line rows
        // enter the per-level chain stage (pre-gate, pre-thinning — chains of
        // sub-visibility fragments must be reclaimable) and the winner-table
        // path handles only the non-line rows. The chain table's rep rows are
        // added back below with their merged, pre-simplified geometry.
        let coalesce: Option<CoalesceTable> = if coalesce_on && !verbatim {
            let inputs: Vec<CoalesceInput<'_>> = features
                .iter()
                .filter(|f| f.kind == FeatureKind::Line)
                .map(|f| CoalesceInput {
                    index: f.index,
                    geom: &geometries[f.index],
                    sort_key: f.sort_key,
                    group: line_groups.as_ref().map_or(0, |g| g[f.index]),
                })
                .collect();
            Some(build_level_coalesce_table(
                &inputs, level, finest, gsd_m, crs, options,
            ))
        } else {
            None
        };
        let member_indices: Vec<usize> = if let Some(table) = &coalesce {
            let mut v: Vec<usize> = member_indices
                .into_iter()
                .filter(|&i| features[i].kind != FeatureKind::Line)
                .collect();
            v.extend(table.keys().copied());
            v.sort_unstable();
            v
        } else {
            member_indices
        };

        let mut indices = Vec::with_capacity(member_indices.len());
        let mut geoms = Vec::with_capacity(member_indices.len());
        let mut vertex_count = 0usize;

        // Cascading (#218, duplicating default): fold canonical geometry
        // through the fine→coarse GSD chain ending at this level, so this
        // level consumes the next-finer level's output. Same chain the
        // streaming ctxs build — the paths stay in lockstep.
        // Zoom-band point representation (#317): this level's representation,
        // and the chain steps carry each contributing level's representation
        // so the fold pointifies at the band boundary (see `simplify_cascade`).
        let repr = level_reprs[level];
        let cascade_chain: Vec<CascadeStep> = if options.simplify.cascade && !verbatim {
            (level..finest)
                .rev()
                .map(|li| CascadeStep {
                    gsd_meters: level_specs[li].0,
                    repr: level_reprs[li],
                })
                .collect()
        } else {
            Vec::new()
        };

        if verbatim {
            for i in member_indices {
                let g = &geometries[i];
                vertex_count += count_vertices(g);
                indices.push(i);
                geoms.push(g.clone());
            }
        } else {
            for i in member_indices {
                // Chain reps carry their merged, already-simplified geometry.
                if let Some((g, _)) = coalesce.as_ref().and_then(|t| t.get(&i)) {
                    vertex_count += count_vertices(g);
                    indices.push(i);
                    geoms.push(g.clone());
                    continue;
                }
                // #384: a carrier is not a member — it stands in for its
                // cell's dropped area as one placeholder square.
                if usize::from(row_min_levels[i]) > level && is_carrier(&carriers[level], i) {
                    if let Some(sq) = carrier_square(&geometries[i], gsd_m, crs, &options.simplify)
                    {
                        vertex_count += count_vertices(&sq);
                        indices.push(i);
                        geoms.push(sq);
                    }
                    continue;
                }
                let simplified = if cascade_chain.is_empty() {
                    simplify_step(&geometries[i], gsd_m, crs, &options.simplify, repr)
                } else {
                    simplify_cascade(&geometries[i], &cascade_chain, crs, &options.simplify)
                };
                match simplified {
                    Simplified::Keep(g) => {
                        vertex_count += count_vertices(&g);
                        indices.push(i);
                        geoms.push(g);
                    }
                    Simplified::Dropped => {}
                }
            }
        }

        // Empty levels are not allowed (§7.3): omit and renumber (#211
        // auto-clamp), recording the omission for the report + warning.
        if indices.is_empty() {
            skipped.push(SkippedLevelReport {
                planned_level: level,
                gsd: gsd_m,
                zoom,
            });
            continue;
        }
        emitted.push(EmittedLevel {
            orig: level,
            gsd: gsd_m,
            zoom,
            indices,
            geoms,
            vertex_count,
            coalesce,
        });
    }

    (emitted, skipped)
}

/// [`convert_to_overviews_source`] with an explicit pass-2 [`Pass2Strategy`].
/// Runs the full option normalization (validation, cluster/accumulate checks,
/// the partitioning-coalesce-inert rewrite) before dispatching.
pub(crate) fn convert_to_overviews_source_strategy(
    source: &ConvertSource,
    output_path: &Path,
    options: &ConvertOptions,
    strategy: super::stream::Pass2Strategy,
) -> Result<ConvertReport, ConvertError> {
    // Knob sanity (H4), shared by both pipelines.
    validate_options(options)?;
    // #386: narrow the source to the requested property columns before any
    // schema index is derived, so both pipelines see the projected layout.
    apply_property_selection(source, options)?;
    // #272: place the remote-input disk spill (#219) where the caller asked
    // (no-op for local inputs, which never spill).
    source.set_spill_dir(options.spill_dir.as_deref());
    check_mode_combinations(options)?;
    // Coalescing is INERT in partitioning mode (Q3, spec §13.5): a merged
    // chain is a new geometry replacing several source rows, which the
    // feature-once/verbatim contract of §2.3 cannot represent, and removing
    // merged members from finer bands would break prefix reads. Coalescing
    // is on by default, so partitioning conversions silently proceed
    // without it (no column, no provenance); the CLI rejects an EXPLICIT
    // request instead.
    let inert_options: ConvertOptions;
    let options: &ConvertOptions = match adjusted_for_ladder_and_mode(options) {
        Some(adjusted) => {
            inert_options = adjusted;
            &inert_options
        }
        None => options,
    };

    // Two-pass bounded-memory pipeline (H3, default). The in-memory path below
    // is kept as the reference implementation (`streaming: false`).
    if options.streaming {
        return super::stream::convert_streaming_strategy(source, output_path, options, strategy);
    }

    // The in-memory reference path below predates multi-partition input
    // (v0.7) and reads through one parquet builder; multi sources are
    // streaming-only.
    let source_single: &InputSource = match source {
        ConvertSource::Single(s) => s.input(),
        ConvertSource::Multi(_) => return Err(ConvertError::MultiPartitionRequiresStreaming),
    };

    let start = Instant::now();

    // A numeric sort key and a categorical class ranking are mutually
    // exclusive (Q1): they would both drive `AssignFeature::sort_key`.
    if options.sort_key.is_some() && options.class_ranking.is_some() {
        return Err(ConvertError::RankingConflict);
    }

    let LoadedInput {
        options: resolved_options,
        input_schema,
        crs,
        renames,
        geom_idx,
        geom_field,
        acc_cols,
        full,
        geometries,
        row_groups_total,
        row_groups_read,
    } = load_input_table(source, source_single, options)?;
    let options = &resolved_options;
    let num_features = full.num_rows();

    // Resolve the cell-winner ranking (Q1): explicit sort key / explicit class
    // ranking / auto-detected well-known schema / size fallback. Returns the
    // per-feature sort keys and the provenance recorded in the footer (§3.5).
    let (sort_keys, ranking_provenance) =
        resolve_ranking(&input_schema, &full, &geometries, options)?;

    // --- Coalescing groups (Q3): interned class values, when class-ranked. ---
    let num_lines = geometries
        .iter()
        .filter(|g| feature_kind(g) == FeatureKind::Line)
        .count();
    let coalesce_on = coalesce_effective(options, num_lines);
    let line_groups: Option<Vec<u32>> = coalesce_on
        .then(|| intern_coalesce_groups(&input_schema, &full, &ranking_provenance))
        .flatten();

    // --- Level assignment. ---------------------------------------------------
    let level_specs = options.levels.resolve(options.gsd_base)?;
    let level_gsds: Vec<f64> = level_specs.iter().map(|(g, _)| *g).collect();

    // Entry-zoom ladder (#364), resolved before assignment so the gate and
    // thinning never see the features it governs.
    let ladder_values = entry_zoom_column_values(options, &input_schema, &full)?;
    let entry = resolve_entry_levels(options, &ladder_values, &level_specs)?;

    let features: Vec<AssignFeature> = geometries
        .iter()
        .enumerate()
        .map(|(i, g)| AssignFeature {
            index: i,
            bbox: geometry_bbox(g),
            kind: feature_kind(g),
            sort_key: sort_keys[i],
            entry_level: entry.as_ref().and_then(|e| e[i]),
        })
        .collect();

    // #188 follow-up: count antimeridian-suspect bboxes and warn once.
    let antimeridian_suspect_features = features
        .iter()
        .filter(|f| bbox_antimeridian_suspect(&f.bbox, crs))
        .count();
    warn_antimeridian_suspects(antimeridian_suspect_features);

    // #306: cap the transient winner-grid memory at the profile-derived RAM
    // budget (`speed` stays unbounded). Pure scheduling — output-identical.
    // Zoom-band representation selector (#317 / #279): per-level
    // representations, parallel to the plan.
    let level_reprs = level_representations(&level_specs, &options.representation);
    let assignment = assign_levels_bounded(
        &features,
        &level_gsds,
        &options.assign,
        crs,
        super::pipeline::pass1_grid_budget_bytes(options.profile),
        &level_reprs,
    );
    // Q2: layer the per-level density budget on top of cell-winner thinning.
    // When disabled this is an identity, so `--no-density-drop` reproduces the
    // pre-Q2 assignment (and, since no density_drop provenance is emitted, a
    // byte-identical footer).
    let assignment = if options.density.enabled {
        apply_density_budget(
            &assignment,
            &features,
            &level_gsds,
            &options.assign,
            &options.density,
            crs,
        )
    } else {
        assignment
    };
    let num_levels = level_gsds.len();
    let finest = num_levels.saturating_sub(1);

    // #384: tiny-polygon accumulator carriers per level (row-indexed here,
    // since `features[i].index == i`), and the winner table by row for the
    // carrier test in the level loop.
    let row_min_levels: Vec<u8> = assignment.assignments.iter().map(|a| a.min_level).collect();
    let carriers = in_memory_carriers(
        options,
        &features,
        &row_min_levels,
        &geometries,
        &level_gsds,
        &level_reprs,
        crs,
    );

    // --- Cluster tables (Q4): per level, winner → point_count + aggregates. --
    let cluster_tables = if options.cluster {
        let min_levels: Vec<u8> = assignment.assignments.iter().map(|a| a.min_level).collect();
        let acc_values = extract_accumulate_values(&full, &acc_cols);
        Some(build_verified_cluster_tables(
            &features,
            &min_levels,
            &level_gsds,
            &acc_values,
            crs,
            options,
        )?)
    } else {
        None
    };

    let (emitted, mut skipped) = build_emitted_levels(
        &assignment,
        &features,
        &geometries,
        &level_specs,
        &level_reprs,
        line_groups.as_ref(),
        coalesce_on,
        finest,
        crs,
        &row_min_levels,
        &carriers,
        options,
    );

    if emitted.is_empty() {
        return Err(ConvertError::NoData);
    }
    warn_plan_skipped_levels(&skipped, num_features, emitted[0].gsd, emitted[0].zoom);

    // --- Build the output writer schema (source schema + geoarrow geometry). -
    // Base + point_count when clustering (Q4) + coalesced_count when
    // coalescing (Q3) — the same three schemas the streaming path builds.
    let geom_name = geom_field.name().clone();
    let (source_schema, cluster_schema, out_schema) =
        super::stream::build_level_schemas(&input_schema, geom_idx, &geom_name, options);

    let writer_levels: Vec<LevelSpec> = emitted
        .iter()
        .map(|e| LevelSpec::new(e.gsd, e.zoom))
        .collect();
    let emitted_gsds: Vec<f64> = emitted.iter().map(|e| e.gsd).collect();
    let writer_opts = super::stream::build_writer_options(
        writer_levels,
        &emitted_gsds,
        crs,
        ranking_provenance,
        &renames,
        options,
    );

    let mut writer = OverviewWriter::create(output_path, &out_schema, writer_opts)?;

    // Column indices of the non-geometry source columns (preserve original order).
    let non_geom_cols: Vec<usize> = (0..input_schema.fields().len())
        .filter(|&c| c != geom_idx)
        .collect();

    let mut level_reports = write_emitted_levels(
        &mut writer,
        &emitted,
        &LevelWriteInputs {
            full: &full,
            source_schema: &source_schema,
            cluster_schema: &cluster_schema,
            out_schema: &out_schema,
            non_geom_cols: &non_geom_cols,
            geom_idx,
            cluster_tables: cluster_tables.as_ref(),
            acc_cols: &acc_cols,
            finest,
        },
        options,
        &mut skipped,
    )?;
    skipped.sort_by_key(|s| s.planned_level);

    let meta = writer.finish()?;

    // --- Fill in real per-level byte sizes from the output footer. -----------
    fill_level_bytes(output_path, &meta, &mut level_reports)?;

    let total_rows: usize = level_reports.iter().map(|l| l.feature_count).sum();
    let total_vertices: usize = level_reports.iter().map(|l| l.vertex_count).sum();
    let total_compressed_bytes: i64 = level_reports.iter().map(|l| l.compressed_bytes).sum();

    Ok(ConvertReport {
        mode: options.mode,
        levels: level_reports,
        skipped_empty_levels: skipped,
        input_features: num_features,
        total_rows,
        total_vertices,
        total_compressed_bytes,
        row_groups_total,
        row_groups_read,
        antimeridian_suspect_features,
        duration_secs: start.elapsed().as_secs_f64(),
        remote_fetch: log_remote_fetch(source),
    })
}

/// Everything the in-memory level-write loop reads besides the levels.
///
/// `write_emitted_levels` borrows a dozen pieces of the conversion state;
/// threading them as separate parameters made the signature longer than the
/// body, so they travel together.
struct LevelWriteInputs<'a> {
    /// The whole input table; each level takes its rows by index.
    full: &'a RecordBatch,
    source_schema: &'a Schema,
    cluster_schema: &'a Schema,
    out_schema: &'a Schema,
    non_geom_cols: &'a [usize],
    geom_idx: usize,
    /// Cluster tables (Q4), or `None` when clustering is off.
    cluster_tables: Option<&'a ClusterTables>,
    /// Schema indices of the accumulate columns (Q4).
    acc_cols: &'a [usize],
    /// Index of the canonical (finest) planned level.
    finest: usize,
}

/// Write every emitted level to the output file, coarse to fine.
///
/// Per level: take the member rows into a batch, layer the cluster (Q4) and
/// coalesced-count (Q3) columns on top, and record what the writer did with
/// it. Levels the writer skipped are appended to `skipped`, matching the
/// streaming path's bookkeeping.
fn write_emitted_levels(
    writer: &mut OverviewWriter<File>,
    emitted: &[EmittedLevel],
    inputs: &LevelWriteInputs<'_>,
    options: &ConvertOptions,
    skipped: &mut Vec<SkippedLevelReport>,
) -> Result<Vec<LevelReport>, ConvertError> {
    let mut level_reports = Vec::with_capacity(emitted.len());
    for (level_idx, e) in emitted.iter().enumerate() {
        let mut batch = build_level_batch(
            inputs.source_schema,
            inputs.full,
            inputs.non_geom_cols,
            inputs.geom_idx,
            &e.indices,
            &e.geoms,
        )?;
        if let Some(tables) = inputs.cluster_tables {
            // Canonical level: singleton clusters, columns verbatim (§2.4).
            let table = (e.orig != inputs.finest).then(|| &tables[e.orig]);
            batch = apply_cluster_columns(
                batch,
                inputs.cluster_schema,
                &e.indices,
                table,
                inputs.acc_cols,
            )?;
        }
        if options.coalesce_lines {
            // Canonical level (and guard-skipped runs): table is None ⇒ all 1.
            batch =
                apply_coalesced_count(batch, inputs.out_schema, &e.indices, e.coalesce.as_ref())?;
        }
        // SkippedEmpty is unreachable here (every emitted level has >= 1
        // feature), but the bookkeeping stays aligned with the streaming path.
        let outcome =
            writer.write_level(level_idx, Some(e.indices.len()), std::iter::once(batch))?;
        record_level_outcome(
            outcome,
            SkippedLevelReport {
                planned_level: e.orig,
                gsd: e.gsd,
                zoom: e.zoom,
            },
            e.indices.len(),
            e.indices.len(),
            e.vertex_count,
            &mut level_reports,
            skipped,
        );
    }
    Ok(level_reports)
}

/// The tiny-polygon accumulator's carriers for the in-memory reference path
/// (#384): the same function the streaming path runs, over the same feature
/// table, so the two paths agree on every carrier.
fn in_memory_carriers(
    options: &ConvertOptions,
    features: &[AssignFeature],
    row_min_levels: &[u8],
    geometries: &[Geometry<f64>],
    level_gsds: &[f64],
    level_reprs: &[Representation],
    crs: Crs,
) -> Vec<Vec<usize>> {
    let num_levels = level_gsds.len();
    let finest = num_levels.saturating_sub(1);
    let enabled = matches!(options.mode, Mode::Duplicating)
        && (options.simplify.collapse == CollapseMode::Square
            || level_reprs.contains(&Representation::Square));
    let acc_levels: Vec<AccumulateLevel> = level_gsds
        .iter()
        .enumerate()
        .map(|(l, &gsd)| AccumulateLevel {
            gsd_meters: gsd,
            enabled: enabled
                && l != finest
                && level_accumulates(options.simplify.collapse, level_reprs[l]),
        })
        .collect();
    if !acc_levels.iter().any(|l| l.enabled) {
        return vec![Vec::new(); num_levels];
    }
    let areas: Vec<f32> = geometries
        .iter()
        .map(|g| match g {
            Geometry::Polygon(p) => p.unsigned_area() as f32,
            Geometry::MultiPolygon(mp) => mp.unsigned_area() as f32,
            _ => 0.0,
        })
        .collect();
    tiny_polygon_carriers(
        features,
        row_min_levels,
        &areas,
        &acc_levels,
        crs,
        options.simplify.factor,
    )
}

/// Snapshot (and `log::info!`) the remote fetch counters at the end of a
/// conversion; `None` (and silent) when no part of the input is remote.
/// Multi-part sources report counters summed over their remote parts.
pub(super) fn log_remote_fetch(source: &ConvertSource) -> Option<crate::input::FetchStats> {
    let stats = source.fetch_stats()?;
    let pct = if stats.object_size > 0 {
        100.0 * stats.bytes_fetched as f64 / stats.object_size as f64
    } else {
        0.0
    };
    log::info!(
        "remote input: {} range requests, {:.2} MiB fetched of a {:.2} MiB object ({:.1}%)",
        stats.requests,
        stats.bytes_fetched as f64 / (1024.0 * 1024.0),
        stats.object_size as f64 / (1024.0 * 1024.0),
        pct
    );
    Some(stats)
}

// ============================================================================
// Helpers
// ============================================================================

/// Detect the input CRS from parsed parquet key-value metadata and map it to
/// [`Crs`], rejecting anything that is not EPSG:4326 or EPSG:3857 (spec Q3).
/// Metadata-only so remote inputs (#210) pay no extra footer fetch.
pub(crate) fn detect_crs_from_kv(
    kv: Option<&Vec<parquet::file::metadata::KeyValue>>,
) -> Result<Crs, ConvertError> {
    let info = crate::quality::crs_info_from_kv_metadata(kv)?;
    if info.is_wgs84 {
        return Ok(Crs::Epsg4326);
    }
    if let Some(id) = &info.identifier {
        let up = id.to_uppercase();
        if up.contains("3857") || up.contains("900913") {
            return Ok(Crs::Epsg3857);
        }
    }
    Err(ConvertError::UnsupportedCrs {
        crs: info
            .identifier
            .clone()
            .or_else(|| info.name.clone())
            .unwrap_or_else(|| "unknown".to_string()),
    })
}

/// Half the Web Mercator world extent in meters (`±` = the x/y range of
/// EPSG:3857). Matches the constant used by the export reprojection.
const WEBMERC_HALF_M: f64 = 20_037_508.342_789_244;

/// Web Mercator latitude clamp (the projection diverges at the poles).
const WEBMERC_MAX_LAT: f64 = 85.051_128_779_806_59;

/// Reproject one EPSG:4326 point (lon/lat degrees) to EPSG:3857 (meters) —
/// the exact inverse of the export path's `webmerc_to_lnglat`. Latitude is
/// clamped to the projection's valid range.
#[inline]
fn lnglat_to_webmerc(lng: f64, lat: f64) -> (f64, f64) {
    use std::f64::consts::{FRAC_PI_4, PI};
    let x = lng / 180.0 * WEBMERC_HALF_M;
    let lat = lat.clamp(-WEBMERC_MAX_LAT, WEBMERC_MAX_LAT);
    let y = (FRAC_PI_4 + lat.to_radians() / 2.0).tan().ln() / PI * WEBMERC_HALF_M;
    (x, y)
}

/// Express a `[xmin, ymin, xmax, ymax]` EPSG:4326 bbox in the input file's
/// coordinate units ([`ConvertOptions::bbox`] is always lon/lat degrees; a
/// 3857 input stores meters).
pub(super) fn bbox_to_crs_units(bbox: &[f64; 4], crs: Crs) -> [f64; 4] {
    match crs {
        Crs::Epsg4326 => *bbox,
        Crs::Epsg3857 => {
            let (xmin, ymin) = lnglat_to_webmerc(bbox[0], bbox[1]);
            let (xmax, ymax) = lnglat_to_webmerc(bbox[2], bbox[3]);
            [xmin, ymin, xmax, ymax]
        }
    }
}

/// Closed-interval AABB intersection of two `[xmin, ymin, xmax, ymax]` boxes
/// (touching edges count as intersecting, matching
/// [`crate::covering::RowGroupBounds::intersects`]).
pub(super) fn bboxes_intersect(a: &[f64; 4], b: &[f64; 4]) -> bool {
    a[0] <= b[2] && a[2] >= b[0] && a[1] <= b[3] && a[3] >= b[1]
}

/// Row-group encode concurrency for the overview writer (#296), derived from
/// the memory profile. The writer holds `O(concurrency × row_group)` extra
/// memory, so `bounded` caps it while still overlapping several row groups;
/// `speed`/`auto` use the full Rayon pool (row groups within a level bound the
/// effective parallelism anyway). Never zero.
pub(super) fn encode_concurrency_for(profile: MemoryProfile) -> usize {
    /// Cap on in-flight row-group encodes under the `bounded` profile, keeping
    /// the writer's extra memory to a few row groups while still breaking the
    /// single-threaded ceiling.
    const BOUNDED_ENCODE_CONCURRENCY_CAP: usize = 4;

    let threads = rayon::current_num_threads().max(1);
    match profile {
        MemoryProfile::Bounded => threads.min(BOUNDED_ENCODE_CONCURRENCY_CAP),
        MemoryProfile::Speed | MemoryProfile::Auto => threads,
    }
}

/// Row groups of the input whose bbox covering statistics intersect
/// `bbox_units` (`[xmin, ymin, xmax, ymax]` in the file's CRS units).
///
/// Statistics-only: operates purely on the parsed parquet footer
/// ([`crate::covering::extract_row_group_bounds_from_metadata`]); no data
/// pages are touched. Row groups with missing/unparseable covering
/// statistics are conservatively KEPT (graceful degradation — the exact
/// per-feature bbox filter downstream guarantees correctness either way).
pub(crate) fn select_input_row_groups(
    metadata: &parquet::file::metadata::ParquetMetaData,
    bbox_units: &[f64; 4],
) -> Vec<usize> {
    let bounds = crate::covering::extract_row_group_bounds_from_metadata(metadata)
        .unwrap_or_else(|_| vec![None; metadata.num_row_groups()]);
    let filter = crate::tile::TileBounds {
        lng_min: bbox_units[0],
        lat_min: bbox_units[1],
        lng_max: bbox_units[2],
        lat_max: bbox_units[3],
    };
    (0..metadata.num_row_groups())
        .filter(|&i| match bounds.get(i).and_then(|b| b.as_ref()) {
            Some(b) => b.intersects(&filter),
            None => true, // no stats — must read to stay correct
        })
        .collect()
}

/// Parse + bind [`ConvertOptions::filter`] (#315) against the (possibly
/// reserved-renamed, #288) input schema. `Ok(None)` when no filter is set.
pub(super) fn bind_attribute_filter(
    options: &ConvertOptions,
    input_schema: &Schema,
    renames: &[(String, String)],
) -> Result<Option<super::filter::BoundFilter>, ConvertError> {
    let Some(src) = options.filter.as_deref() else {
        return Ok(None);
    };
    let expr = super::filter::parse_filter(src)?;
    Ok(Some(super::filter::BoundFilter::bind(
        &expr,
        input_schema,
        renames,
    )?))
}

/// Log label for the active footer-statistics prunings.
pub(super) fn pruning_label(bbox: bool, filter: bool) -> &'static str {
    match (bbox, filter) {
        (true, true) => "bbox+attribute",
        (true, false) => "bbox",
        _ => "attribute",
    }
}

/// Combined single-file footer-statistics row-group selection: bbox covering
/// pruning (#102) intersected with attribute-filter statistics pushdown
/// (#315). `None` when neither pruning is active (read everything).
fn select_input_row_groups_combined(
    metadata: &parquet::file::metadata::ParquetMetaData,
    bbox_units: Option<&[f64; 4]>,
    filter: Option<&super::filter::BoundFilter>,
) -> Option<Vec<usize>> {
    let bbox_sel: Option<Vec<usize>> = bbox_units.map(|bb| select_input_row_groups(metadata, bb));
    let filter_sel: Option<Vec<usize>> = filter.map(|f| f.select_row_groups(metadata));
    match (bbox_sel, filter_sel) {
        (Some(a), Some(b)) => Some(a.into_iter().filter(|i| b.contains(i)).collect()),
        (Some(a), None) => Some(a),
        (None, Some(b)) => Some(b),
        (None, None) => None,
    }
}

/// Find the primary geometry column index (name `geometry`, else first `geom*`).
pub(super) fn find_geometry_column(schema: &Schema) -> Option<usize> {
    schema
        .fields()
        .iter()
        .position(|f| f.name() == "geometry")
        .or_else(|| {
            schema
                .fields()
                .iter()
                .position(|f| f.name().contains("geom"))
        })
}

/// `[xmin, ymin, xmax, ymax]` of a geometry (`[0;4]` when the bbox is undefined).
pub(super) fn geometry_bbox(g: &Geometry<f64>) -> [f64; 4] {
    match g.bounding_rect() {
        Some(r) => [r.min().x, r.min().y, r.max().x, r.max().y],
        None => [0.0, 0.0, 0.0, 0.0],
    }
}

/// Whether a feature bbox is antimeridian-suspect: wider than 180° of
/// longitude. A real feature that wide is essentially impossible; the near
/// certain cause is an antimeridian-crossing geometry stored verbatim, whose
/// min/max bbox inflates to ~360° (see `context/ANTIMERIDIAN.md`, #188).
/// Detection only — geometry is never mutated.
pub(super) fn bbox_antimeridian_suspect(bbox: &[f64; 4], crs: Crs) -> bool {
    bbox[2] - bbox[0] > crs.meters_to_units(180.0 * METERS_PER_DEGREE)
}

/// Emit the single aggregate antimeridian warning (#188 follow-up). Called
/// once per convert, from both the streaming and in-memory paths.
pub(super) fn warn_antimeridian_suspects(count: usize) {
    if count > 0 {
        log::warn!(
            "{count} feature(s) have bounding boxes wider than 180° of longitude — \
             likely antimeridian-crossing geometry. These will be assigned to \
             overly coarse levels and defeat bbox pruning; pre-split them at \
             ±180° before converting (see docs/advanced-usage.md, \
             \"Antimeridian-Crossing Geometry\")."
        );
    }
}

/// Object-size threshold above which a *full-file* remote convert emits the
/// #267 download-first nudge. Below ~1 GiB the local spill footprint and the
/// second-pass disk read are cheap enough not to warrant a warning.
pub(super) const FULL_FILE_REMOTE_WARN_BYTES: u64 = 1 << 30;

/// #267 decision + message (pure, so it is unit-testable without capturing
/// logs). Returns the one-line nudge to emit, or `None` to stay quiet.
///
/// Fires only for a *whole-file* remote convert of a large object: the disk
/// spill (#219) already bounds network traffic to ≈1× the object, but a
/// full-file remote convert still stages ≈the object's bytes under `$TMPDIR`
/// and re-reads them from disk on the second pass. For a region of interest,
/// `--bbox` fetches only the covering row groups and skips the spill entirely,
/// so we point the user there (or to a download-first workflow). Stays quiet
/// for local inputs (OS page cache), for effective bbox extracts (fewer row
/// groups read than the file holds), and for objects below the threshold.
pub(super) fn full_file_remote_warning(
    remote_parts: usize,
    row_groups_read: usize,
    row_groups_total: usize,
    object_size: u64,
) -> Option<String> {
    if remote_parts == 0
        || row_groups_read < row_groups_total
        || object_size < FULL_FILE_REMOTE_WARN_BYTES
    {
        return None;
    }
    let gib = object_size as f64 / (1024.0 * 1024.0 * 1024.0);
    // Multi-partition sources (v0.7) sum object_size over their remote
    // parts, so name the part count: 20 × 600 MB partitions trip the same
    // ≥1 GiB total-transfer threshold as one 12 GiB object.
    let what = if remote_parts > 1 {
        format!("{remote_parts} remote partitions totalling {gib:.1} GiB")
    } else {
        format!("a {gib:.1} GiB object")
    };
    Some(format!(
        "full-file remote convert of {what}: the input is fetched once over \
         the network (≈1× — the local spill keeps later passes off the network, \
         #219) and staged under $TMPDIR. For a region of interest pass --bbox to \
         fetch only the covering row groups (and skip the spill); otherwise \
         downloading first (e.g. `aws s3 cp`) and converting locally avoids the \
         second-pass disk read. Point --spill-dir (or $TMPDIR) at fast local disk \
         with room for it, not a small tmpfs.",
    ))
}

/// Emit the #267 nudge for a full-file remote convert, if warranted. Thin
/// logging wrapper over [`full_file_remote_warning`] (for a multi source,
/// `object_size` is summed over the remote parts and the part count is
/// named in the message).
pub(super) fn warn_full_file_remote(
    source: &ConvertSource,
    row_groups_read: usize,
    row_groups_total: usize,
) {
    let object_size = source.fetch_stats().map_or(0, |s| s.object_size);
    let remote_parts = source.parts().iter().filter(|p| p.is_remote()).count();
    if let Some(msg) =
        full_file_remote_warning(remote_parts, row_groups_read, row_groups_total, object_size)
    {
        log::warn!("{msg}");
    }
}

/// #272 spill-preflight safety margin: warn when the spill volume's free
/// space is below the projected spill size plus 1/20th (5%) of it — spill
/// bookkeeping is exact but the volume is shared with everything else the
/// process (and host) writes during the convert.
const SPILL_MARGIN_DENOM: u64 = 20;

/// #272 decision + message (pure, so it is unit-testable without touching
/// a filesystem). Returns the warning to emit when the projected input
/// spill (≈ the selected input bytes, see
/// [`crate::input::selected_compressed_bytes`]) plus a 5% safety margin
/// exceeds `available_bytes` on the spill volume, or `None` when it fits.
pub(super) fn spill_space_warning(
    estimated_spill_bytes: u64,
    available_bytes: u64,
    spill_dir: &Path,
) -> Option<String> {
    let need = estimated_spill_bytes + estimated_spill_bytes / SPILL_MARGIN_DENOM;
    if available_bytes >= need {
        return None;
    }
    let gib = |b: u64| b as f64 / (1024.0 * 1024.0 * 1024.0);
    Some(format!(
        "projected input spill (≈{:.1} GiB — the selected input bytes are \
         staged on local disk so later passes stay off the network, #219) may \
         not fit: {} has {:.1} GiB free ({:.1} GiB short, including a 5% \
         margin). If the volume fills mid-convert the spill degrades to \
         network re-fetch; pass --spill-dir (spill_dir) to place it on a \
         roomier volume, or free up space first.",
        gib(estimated_spill_bytes),
        spill_dir.display(),
        gib(available_bytes),
        gib(need - available_bytes),
    ))
}

/// #272 preflight gate over [`spill_space_warning`], with the free-space
/// probe injected so the gating is unit-testable with a fake probe. Only a
/// remote input spills, so for local inputs (and an empty selection) the
/// probe is never even called; a failed probe (`None` — unsupported
/// filesystem, permission error) stays quiet rather than crying wolf.
pub(super) fn spill_space_check(
    is_remote: bool,
    estimated_spill_bytes: u64,
    spill_dir: &Path,
    probe: impl FnOnce(&Path) -> Option<u64>,
) -> Option<String> {
    if !is_remote || estimated_spill_bytes == 0 {
        return None;
    }
    let available = probe(spill_dir)?;
    spill_space_warning(estimated_spill_bytes, available, spill_dir)
}

/// Free bytes available to the current user on the volume holding `dir`
/// (statvfs / GetDiskFreeSpaceEx via `fs4`), or `None` if the probe fails.
/// Compiled to a stub without the `remote` feature — nothing spills there,
/// and [`spill_space_check`] never probes for a local input.
fn probe_available_space(dir: &Path) -> Option<u64> {
    #[cfg(feature = "remote")]
    {
        fs4::available_space(dir).ok()
    }
    #[cfg(not(feature = "remote"))]
    {
        let _ = dir;
        None
    }
}

/// Emit the #272 spill free-space preflight warning, if warranted. Thin
/// logging wrapper over [`spill_space_check`] with the real filesystem
/// probe; `spill_dir = None` means the process temp dir, exactly where the
/// spill file would go.
pub(super) fn warn_spill_space(
    source: &ConvertSource,
    estimated_spill_bytes: u64,
    spill_dir: Option<&Path>,
) {
    let dir = spill_dir.map_or_else(std::env::temp_dir, Path::to_path_buf);
    if let Some(msg) = spill_space_check(
        source.is_remote(),
        estimated_spill_bytes,
        &dir,
        probe_available_space,
    ) {
        log::warn!("{msg}");
    }
}

/// Whether a decoded geometry can participate in level assignment: it must
/// carry at least one coordinate and every coordinate must be finite.
///
/// Rows failing this check (alongside null-geometry rows) are **skipped with
/// a warning** rather than converted: an empty geometry has no location to
/// thin against, and a NaN/infinite coordinate would silently collapse into
/// grid cell `(0, 0)` (H4 hostile-input hardening).
pub(super) fn usable_geometry(g: &Geometry<f64>) -> bool {
    use geo::coords_iter::CoordsIter;
    let mut any = false;
    for c in g.coords_iter() {
        if !c.x.is_finite() || !c.y.is_finite() {
            return false;
        }
        any = true;
    }
    any
}

/// Map a geometry to the [`FeatureKind`] used for thinning / visibility.
pub(super) fn feature_kind(g: &Geometry<f64>) -> FeatureKind {
    match g {
        Geometry::Point(_) | Geometry::MultiPoint(_) => FeatureKind::Point,
        Geometry::LineString(_) | Geometry::MultiLineString(_) | Geometry::Line(_) => {
            FeatureKind::Line
        }
        _ => FeatureKind::Polygon,
    }
}

/// Accumulator for [`scan_feature`]: min/max over the bounding-rect coord set
/// plus a finiteness/non-empty tally over *all* coords.
#[derive(Debug)]
struct FeatureScan {
    min_x: f64,
    min_y: f64,
    max_x: f64,
    max_y: f64,
    /// A bounding-rect coord was seen (exterior of polygons; every coord of
    /// other kinds). When false the bbox is undefined ([`geometry_bbox`] → 0s).
    bbox_seen: bool,
    /// Any coord at all was seen (matches `usable_geometry`'s non-empty test).
    any_coord: bool,
    /// Every coord seen so far is finite (matches `usable_geometry`).
    finite: bool,
}

impl FeatureScan {
    fn new() -> Self {
        FeatureScan {
            min_x: f64::INFINITY,
            min_y: f64::INFINITY,
            max_x: f64::NEG_INFINITY,
            max_y: f64::NEG_INFINITY,
            bbox_seen: false,
            any_coord: false,
            finite: true,
        }
    }

    /// A coord that counts for BOTH the bounding box and the finiteness tally
    /// (i.e. a coord `bounding_rect` would include: points, line vertices,
    /// polygon *exterior* rings).
    #[inline]
    fn note_bbox(&mut self, c: geo::Coord<f64>) {
        self.any_coord = true;
        if !c.x.is_finite() || !c.y.is_finite() {
            self.finite = false;
            return;
        }
        self.bbox_seen = true;
        if c.x < self.min_x {
            self.min_x = c.x;
        }
        if c.y < self.min_y {
            self.min_y = c.y;
        }
        if c.x > self.max_x {
            self.max_x = c.x;
        }
        if c.y > self.max_y {
            self.max_y = c.y;
        }
    }

    /// A coord that counts for finiteness/non-empty only, NOT the bbox —
    /// polygon *interior* rings, which `bounding_rect` ignores but
    /// `usable_geometry` (via `coords_iter`) includes.
    #[inline]
    fn note_finite_only(&mut self, c: geo::Coord<f64>) {
        self.any_coord = true;
        if !c.x.is_finite() || !c.y.is_finite() {
            self.finite = false;
        }
    }

    fn bbox(&self) -> [f64; 4] {
        if self.bbox_seen {
            [self.min_x, self.min_y, self.max_x, self.max_y]
        } else {
            // Matches `geometry_bbox` when `bounding_rect` is `None`.
            [0.0, 0.0, 0.0, 0.0]
        }
    }
}

/// Walk `g` into `scan`, distinguishing bbox-contributing coords (exterior
/// rings) from finiteness-only coords (polygon interiors), recursing through
/// geometry collections. Mirrors `bounding_rect`'s coord set and
/// `coords_iter`'s coord set exactly.
fn scan_geometry_into(g: &Geometry<f64>, scan: &mut FeatureScan) {
    use geo::coords_iter::CoordsIter;
    let scan_polygon = |poly: &geo::Polygon<f64>, scan: &mut FeatureScan| {
        for c in poly.exterior().coords_iter() {
            scan.note_bbox(c);
        }
        for ring in poly.interiors() {
            for c in ring.coords_iter() {
                scan.note_finite_only(c);
            }
        }
    };
    match g {
        Geometry::Polygon(poly) => scan_polygon(poly, scan),
        Geometry::MultiPolygon(mp) => {
            for poly in &mp.0 {
                scan_polygon(poly, scan);
            }
        }
        Geometry::GeometryCollection(gc) => {
            for child in &gc.0 {
                scan_geometry_into(child, scan);
            }
        }
        // Every other kind's `bounding_rect` set == its `coords_iter` set.
        other => {
            for c in other.coords_iter() {
                scan.note_bbox(c);
            }
        }
    }
}

/// Fused single-traversal replacement for `usable_geometry` + `geometry_bbox`
/// + `feature_kind` used by the streaming pass-1 scan (#274).
///
/// Returns `None` for a geometry `usable_geometry` would reject (empty or any
/// non-finite coord), otherwise `(feature_kind(g), geometry_bbox(g))`. It is
/// byte-equivalent to calling those three functions in sequence — the bbox is
/// exterior-only for polygons, finiteness spans all coords — but walks the
/// decoded geometry once instead of twice (`usable_geometry` iterated every
/// coord, then `bounding_rect` iterated the exterior again). The
/// `scan_feature_matches_components` proptest pins the equivalence.
pub(super) fn scan_feature(g: &Geometry<f64>) -> Option<(FeatureKind, [f64; 4])> {
    let mut scan = FeatureScan::new();
    scan_geometry_into(g, &mut scan);
    if !scan.finite || !scan.any_coord {
        return None;
    }
    Some((feature_kind(g), scan.bbox()))
}

/// Count coordinates (vertices) in a geometry.
pub(super) fn count_vertices(g: &Geometry<f64>) -> usize {
    use geo::coords_iter::CoordsIter;
    g.coords_count()
}

/// Extract an optional f64 sort key per row from a numeric Arrow column.
/// Non-numeric columns and null values yield `None`.
pub(super) fn extract_sort_keys(col: &dyn Array) -> Vec<Option<f64>> {
    use arrow_array::cast::AsArray;
    use arrow_array::types::{
        Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, Int8Type, UInt16Type,
        UInt32Type, UInt64Type, UInt8Type,
    };
    use arrow_schema::DataType;

    let n = col.len();
    macro_rules! collect_prim {
        ($ty:ty) => {{
            let a = col.as_primitive::<$ty>();
            (0..n)
                .map(|i| {
                    if a.is_null(i) {
                        None
                    } else {
                        Some(a.value(i) as f64)
                    }
                })
                .collect()
        }};
    }
    match col.data_type() {
        DataType::Int8 => collect_prim!(Int8Type),
        DataType::Int16 => collect_prim!(Int16Type),
        DataType::Int32 => collect_prim!(Int32Type),
        DataType::Int64 => collect_prim!(Int64Type),
        DataType::UInt8 => collect_prim!(UInt8Type),
        DataType::UInt16 => collect_prim!(UInt16Type),
        DataType::UInt32 => collect_prim!(UInt32Type),
        DataType::UInt64 => collect_prim!(UInt64Type),
        DataType::Float32 => collect_prim!(Float32Type),
        DataType::Float64 => collect_prim!(Float64Type),
        _ => vec![None; n],
    }
}

/// A mixed-`Geometry` GeoArrow field carrying the geoarrow extension metadata.
pub(super) fn mixed_geometry_field(name: &str) -> Arc<Field> {
    use geoarrow_array::GeoArrowArray;
    let typ = GeometryType::new(Default::default());
    let empty = GeometryBuilder::new(typ).with_prefer_multi(false).finish();
    Arc::new(empty.data_type().to_field(name, true))
}

/// Build the writer source schema: original fields, geometry field replaced by
/// the geoarrow-typed field, no file-level metadata (the encoder regenerates it).
pub(super) fn build_source_schema(
    input_schema: &Schema,
    geom_idx: usize,
    geom_out_field: Arc<Field>,
) -> Schema {
    let fields: Vec<Arc<Field>> = input_schema
        .fields()
        .iter()
        .enumerate()
        .map(|(i, f)| {
            if i == geom_idx {
                geom_out_field.clone()
            } else {
                f.clone()
            }
        })
        .collect();
    Schema::new(fields)
}

/// Assemble one level's record batch: non-geometry columns via `take` on the
/// selected indices (preserving input order), geometry rebuilt from `geoms`.
pub(super) fn build_level_batch(
    source_schema: &Schema,
    full: &RecordBatch,
    non_geom_cols: &[usize],
    geom_idx: usize,
    indices: &[usize],
    geoms: &[Geometry<f64>],
) -> Result<RecordBatch, ConvertError> {
    let take_idx = UInt32Array::from(indices.iter().map(|&i| i as u32).collect::<Vec<_>>());

    // Build columns in the source schema order (geometry field kept in place).
    let mut columns: Vec<Arc<dyn Array>> = Vec::with_capacity(source_schema.fields().len());
    let mut non_geom_iter = non_geom_cols.iter();
    for i in 0..source_schema.fields().len() {
        if i == geom_idx {
            let typ = GeometryType::new(Default::default());
            let mut b = GeometryBuilder::new(typ).with_prefer_multi(false);
            b.extend_from_iter(geoms.iter().map(Some));
            columns.push(b.finish().to_array_ref());
        } else {
            let src_col = *non_geom_iter.next().expect("non-geom column index");
            let taken = take(full.column(src_col).as_ref(), &take_idx, None)?;
            columns.push(taken);
        }
    }
    Ok(RecordBatch::try_new(
        Arc::new(source_schema.clone()),
        columns,
    )?)
}

// ============================================================================
// Clustering helpers (Q4) — shared by the in-memory and streaming pipelines
// ============================================================================

/// Validate the clustering-related schema constraints and resolve the
/// accumulate columns to schema indices (parallel to `options.accumulate`).
///
/// Checks (clustering enabled only):
/// - the input does not already carry a `point_count` column
///   (case-insensitive, mirroring the `level` column rule §4.1);
/// - every accumulate column exists and is numeric.
pub(super) fn validate_cluster_schema(
    schema: &Schema,
    options: &ConvertOptions,
) -> Result<Vec<usize>, ConvertError> {
    if !options.cluster {
        return Ok(Vec::new());
    }
    // Backstop: both pipelines run `resolve_reserved_column_collisions` first,
    // which renames any colliding `point_count` away (#288), so this normally
    // never fires — it guards a direct caller that skipped the resolver.
    if schema
        .fields()
        .iter()
        .any(|f| f.name().eq_ignore_ascii_case(POINT_COUNT_COLUMN))
    {
        return Err(ConvertError::PointCountColumnPresent);
    }
    let mut indices = Vec::with_capacity(options.accumulate.len());
    for spec in &options.accumulate {
        let idx =
            schema
                .index_of(&spec.column)
                .map_err(|_| ConvertError::AccumulateColumnMissing {
                    name: spec.column.clone(),
                })?;
        let dt = schema.field(idx).data_type();
        if !is_numeric_type(dt) {
            return Err(ConvertError::AccumulateColumnNotNumeric {
                name: spec.column.clone(),
                data_type: format!("{dt:?}"),
            });
        }
        indices.push(idx);
    }
    Ok(indices)
}

/// Whether an Arrow type is accepted by `--accumulate-attribute`.
fn is_numeric_type(dt: &DataType) -> bool {
    matches!(
        dt,
        DataType::Int8
            | DataType::Int16
            | DataType::Int32
            | DataType::Int64
            | DataType::UInt8
            | DataType::UInt16
            | DataType::UInt32
            | DataType::UInt64
            | DataType::Float32
            | DataType::Float64
    )
}

/// The writer source schema with the trailing `point_count` INT64 NOT NULL
/// column appended (clustering enabled).
pub(super) fn append_point_count_field(schema: &Schema) -> Schema {
    let mut fields: Vec<Arc<Field>> = schema.fields().iter().cloned().collect();
    fields.push(Arc::new(Field::new(
        POINT_COUNT_COLUMN,
        DataType::Int64,
        false,
    )));
    Schema::new(fields)
}

/// Per-feature accumulate values (one vector per spec, parallel to the rows),
/// extracted from the resolved column indices of a batch-shaped table.
pub(super) fn extract_accumulate_values(
    batch: &RecordBatch,
    acc_col_indices: &[usize],
) -> Vec<Vec<Option<f64>>> {
    acc_col_indices
        .iter()
        .map(|&idx| extract_sort_keys(batch.column(idx).as_ref()))
        .collect()
}

/// Append the `point_count` column to a level batch and overwrite the
/// accumulate columns for clustered rows (Q4).
///
/// - `batch`: the level batch built by [`build_level_batch`] (base schema).
/// - `out_schema`: base schema + trailing `point_count` field.
/// - `global_indices`: per batch row, the source-row index used as the
///   cluster-table key.
/// - `table`: the level's cluster table; `None` at the canonical level (all
///   singletons — every column passes through verbatim, count = 1).
/// - `acc_cols`: schema indices of the accumulate columns (parallel to the
///   aggregates in each [`ClusterEntry`]).
///
/// Singleton rows (absent from the table) keep every source value; only
/// non-singleton winners have `point_count > 1` and rewritten aggregates.
/// Aggregates are computed in `f64`; written back in the column's original
/// type (integer columns round to nearest — relevant for `mean`).
pub(super) fn apply_cluster_columns(
    batch: RecordBatch,
    out_schema: &Schema,
    global_indices: &[usize],
    table: Option<&HashMap<usize, ClusterEntry>>,
    acc_cols: &[usize],
) -> Result<RecordBatch, ConvertError> {
    use arrow_array::Int64Array;

    debug_assert_eq!(batch.num_rows(), global_indices.len());
    let mut columns: Vec<Arc<dyn Array>> = batch.columns().to_vec();

    // Overwrite accumulate columns for clustered rows.
    if let Some(table) = table {
        for (s, &col_idx) in acc_cols.iter().enumerate() {
            let overrides: Vec<Option<f64>> = global_indices
                .iter()
                .map(|g| table.get(g).and_then(|e| e.aggregates[s]))
                .collect();
            if overrides.iter().any(|o| o.is_some()) {
                columns[col_idx] = overwrite_numeric_column(&columns[col_idx], &overrides)?;
            }
        }
    }

    // Append point_count (1 for singletons / non-points / canonical rows).
    let counts: Vec<i64> = global_indices
        .iter()
        .map(|g| table.and_then(|t| t.get(g)).map_or(1, |e| e.point_count))
        .collect();
    columns.push(Arc::new(Int64Array::from(counts)));

    Ok(RecordBatch::try_new(Arc::new(out_schema.clone()), columns)?)
}

/// Rebuild a numeric column with per-row override values (`None` keeps the
/// original value, including its nullness). Aggregates arrive as `f64`;
/// integer columns round to nearest.
fn overwrite_numeric_column(
    col: &Arc<dyn Array>,
    overrides: &[Option<f64>],
) -> Result<Arc<dyn Array>, ConvertError> {
    use arrow_array::cast::AsArray;
    use arrow_array::types::{
        Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, Int8Type, UInt16Type,
        UInt32Type, UInt64Type, UInt8Type,
    };
    use arrow_array::PrimitiveArray;

    macro_rules! rebuild {
        ($ty:ty, $cast:expr) => {{
            let a = col.as_primitive::<$ty>();
            let rebuilt: PrimitiveArray<$ty> = (0..a.len())
                .map(|i| match overrides[i] {
                    Some(v) => Some($cast(v)),
                    None => {
                        if a.is_null(i) {
                            None
                        } else {
                            Some(a.value(i))
                        }
                    }
                })
                .collect();
            Ok(Arc::new(rebuilt))
        }};
    }
    match col.data_type() {
        DataType::Int8 => rebuild!(Int8Type, |v: f64| v.round() as i8),
        DataType::Int16 => rebuild!(Int16Type, |v: f64| v.round() as i16),
        DataType::Int32 => rebuild!(Int32Type, |v: f64| v.round() as i32),
        DataType::Int64 => rebuild!(Int64Type, |v: f64| v.round() as i64),
        DataType::UInt8 => rebuild!(UInt8Type, |v: f64| v.round() as u8),
        DataType::UInt16 => rebuild!(UInt16Type, |v: f64| v.round() as u16),
        DataType::UInt32 => rebuild!(UInt32Type, |v: f64| v.round() as u32),
        DataType::UInt64 => rebuild!(UInt64Type, |v: f64| v.round() as u64),
        DataType::Float32 => rebuild!(Float32Type, |v: f64| v as f32),
        DataType::Float64 => rebuild!(Float64Type, |v: f64| v),
        other => Err(ConvertError::AccumulateColumnNotNumeric {
            name: "<accumulate column>".to_string(),
            data_type: format!("{other:?}"),
        }),
    }
}

// ============================================================================
// Coalescing helpers (Q3) — shared by the in-memory and streaming pipelines
// ============================================================================

/// One level's coalescing result: rep source row → (simplified merged
/// geometry, number of source segments merged).
pub(super) type CoalesceTable = HashMap<usize, (Geometry<f64>, i32)>;

/// Validate the coalescing-related schema constraint: the input must not
/// already carry a `coalesced_count` column (case-insensitive, mirroring the
/// `level` / `point_count` rules).
pub(super) fn validate_coalesce_schema(
    schema: &Schema,
    options: &ConvertOptions,
) -> Result<(), ConvertError> {
    if !options.coalesce_lines {
        return Ok(());
    }
    // Backstop: both pipelines run `resolve_reserved_column_collisions` first,
    // which renames any colliding `coalesced_count` away (#288), so this
    // normally never fires — it guards a direct caller that skipped the
    // resolver.
    if schema
        .fields()
        .iter()
        .any(|f| f.name().eq_ignore_ascii_case(COALESCED_COUNT_COLUMN))
    {
        return Err(ConvertError::CoalescedCountColumnPresent);
    }
    Ok(())
}

// ============================================================================
// Reserved-column collision handling (#288) — shared by both pipelines
// ============================================================================

/// The output columns the overview writer reserves for a given conversion.
/// `level` is always appended (§4.1); `point_count` and `coalesced_count` are
/// appended only when clustering / coalescing are enabled, so they are reserved
/// only in those modes — mirroring [`validate_cluster_schema`] /
/// [`validate_coalesce_schema`].
fn reserved_output_columns(options: &ConvertOptions) -> Vec<&'static str> {
    let mut names = vec![LEVEL_COLUMN];
    if options.cluster {
        names.push(POINT_COUNT_COLUMN);
    }
    if options.coalesce_lines {
        names.push(COALESCED_COUNT_COLUMN);
    }
    names
}

/// Rename any input column that collides (case-insensitively) with a reserved
/// overview output column, so real-world data whose properties happen to be
/// named `level` (Overture buildings' floor number), `LEVEL` (admin data),
/// `point_count`, etc. converts instead of being rejected (#288). Each
/// colliding column is renamed by appending `_`, looping until the name is
/// unique against both the existing columns and the reserved names. The
/// reserved output column stays authoritative.
///
/// The rename is metadata-only and **order-preserving** — type, nullability,
/// and field metadata are kept, and columns are not reordered — so every
/// downstream index- and projection-based path (which addresses columns
/// positionally) stays valid against the raw input. Any by-name option that
/// referenced a renamed column (`sort_key`, `class_ranking.column`,
/// `accumulate[].column`) is rewritten in `options` to the new name so it still
/// resolves. A `log::warn!` is emitted per rename.
///
/// Returns the rewritten schema — the same `Arc` when nothing collided, so
/// callers can cheaply detect the no-op via [`Arc::ptr_eq`] — and the applied
/// `(old, new)` renames.
pub(super) fn resolve_reserved_column_collisions(
    input_schema: &SchemaRef,
    options: &mut ConvertOptions,
) -> (SchemaRef, Vec<(String, String)>) {
    let reserved = reserved_output_columns(options);
    let match_reserved = |name: &str| -> Option<&'static str> {
        reserved
            .iter()
            .copied()
            .find(|r| name.eq_ignore_ascii_case(r))
    };

    let mut taken: HashSet<String> = input_schema
        .fields()
        .iter()
        .map(|f| f.name().to_ascii_lowercase())
        .collect();
    let mut renames: Vec<(String, String)> = Vec::new();
    let mut new_fields: Vec<Arc<Field>> = Vec::with_capacity(input_schema.fields().len());

    for field in input_schema.fields() {
        let name = field.name();
        let Some(reserved_name) = match_reserved(name) else {
            new_fields.push(field.clone());
            continue;
        };
        // Append `_` until the candidate collides with no existing column and
        // no reserved name. `_` can never introduce a `geom`/`geometry`
        // substring, so geometry detection stays unaffected.
        let mut candidate = format!("{name}_");
        while taken.contains(&candidate.to_ascii_lowercase())
            || match_reserved(&candidate).is_some()
        {
            candidate.push('_');
        }
        taken.insert(candidate.to_ascii_lowercase());
        log::warn!(
            "input column {name:?} collides with the reserved overview column \
             {reserved_name:?}; renaming the input column to {candidate:?} in \
             the output (the reserved {reserved_name:?} column is authoritative)"
        );
        renames.push((name.to_string(), candidate.clone()));
        new_fields.push(Arc::new(
            Field::new(candidate, field.data_type().clone(), field.is_nullable())
                .with_metadata(field.metadata().clone()),
        ));
    }

    if renames.is_empty() {
        return (input_schema.clone(), renames);
    }

    // A by-name option that pointed at a renamed column must follow the rename,
    // or a supported invocation (`--sort-key level`) would fail with
    // `*ColumnMissing` (or, for coalesce grouping, panic) downstream.
    let remap = |col: &str| -> Option<String> {
        renames
            .iter()
            .find(|(old, _)| col.eq_ignore_ascii_case(old))
            .map(|(_, new)| new.clone())
    };
    if let Some(new) = options.sort_key.as_deref().and_then(remap) {
        options.sort_key = Some(new);
    }
    if let Some(cr) = options.class_ranking.as_mut() {
        if let Some(new) = remap(&cr.column) {
            cr.column = new;
        }
    }
    for spec in &mut options.accumulate {
        if let Some(new) = remap(&spec.column) {
            spec.column = new;
        }
    }
    // #364: the motivating ladder column is literally named `level` (#359's
    // reporter and #364's are the same dataset), so a ladder is the
    // single most likely option to name a reserved column.
    if let Some(spec) = options.entry_zoom.as_mut() {
        if let Some(new) = remap(&spec.column) {
            spec.column = new;
        }
    }

    let schema = Arc::new(Schema::new_with_metadata(
        new_fields,
        input_schema.metadata().clone(),
    ));
    (schema, renames)
}

/// The writer schema with the trailing `coalesced_count` INT32 NOT NULL
/// column appended (coalescing enabled).
pub(super) fn append_coalesced_count_field(schema: &Schema) -> Schema {
    let mut fields: Vec<Arc<Field>> = schema.fields().iter().cloned().collect();
    fields.push(Arc::new(Field::new(
        COALESCED_COUNT_COLUMN,
        DataType::Int32,
        false,
    )));
    Schema::new(fields)
}

/// Append the `coalesced_count` column to a level batch: chain reps take
/// their member count from `table`; every other row (non-lines, unmerged
/// lines, canonical rows — `table` is `None` there) carries `1`.
pub(super) fn apply_coalesced_count(
    batch: RecordBatch,
    out_schema: &Schema,
    global_indices: &[usize],
    table: Option<&CoalesceTable>,
) -> Result<RecordBatch, ConvertError> {
    use arrow_array::Int32Array;

    debug_assert_eq!(batch.num_rows(), global_indices.len());
    let mut columns: Vec<Arc<dyn Array>> = batch.columns().to_vec();
    let counts: Vec<i32> = global_indices
        .iter()
        .map(|g| table.and_then(|t| t.get(g)).map_or(1, |(_, c)| *c))
        .collect();
    columns.push(Arc::new(Int32Array::from(counts)));
    Ok(RecordBatch::try_new(Arc::new(out_schema.clone()), columns)?)
}

/// The class column driving coalescing compatibility groups, when the Q1
/// ranking is class-based (explicit `--class-rank` or auto-detected Overture
/// roads). Numeric rankings (`--sort-key`, auto-confidence) and the size
/// fallback have no class semantics: all lines are compatible.
pub(super) fn coalesce_group_column(ranking: &RankingProvenance) -> Option<&str> {
    match ranking.mode.as_str() {
        "class-ranking" | "auto-overture-roads" => ranking.column.as_deref(),
        _ => None,
    }
}

/// Incremental string→id interner for coalescing compatibility groups.
/// Null values map to [`GroupInterner::NULL_GROUP`] (all nulls compatible
/// with each other, never with a named class).
#[derive(Debug, Default)]
pub(super) struct GroupInterner {
    map: HashMap<String, u32>,
}

impl GroupInterner {
    /// Group id assigned to null/missing class values.
    pub(super) const NULL_GROUP: u32 = u32::MAX;

    /// Intern one column's values, appending a group id per row to `out`.
    /// Non-string columns intern every row as [`Self::NULL_GROUP`] (callers
    /// only pass validated class-ranking columns, which are strings).
    pub(super) fn extend(&mut self, col: &dyn Array, out: &mut Vec<u32>) {
        use arrow_array::cast::AsArray;

        macro_rules! intern {
            ($arr:expr) => {{
                let a = $arr;
                for i in 0..a.len() {
                    if a.is_null(i) {
                        out.push(Self::NULL_GROUP);
                    } else {
                        let next = self.map.len() as u32;
                        let id = *self.map.entry(a.value(i).to_string()).or_insert(next);
                        out.push(id);
                    }
                }
            }};
        }
        match col.data_type() {
            DataType::Utf8 => intern!(col.as_string::<i32>()),
            DataType::LargeUtf8 => intern!(col.as_string::<i64>()),
            _ => out.extend(std::iter::repeat_n(Self::NULL_GROUP, col.len())),
        }
    }
}

/// Run the chain stage for one level: chain + gate + thin + per-level
/// density budget. The budget mirrors the Q2 geometric ladder over the LINE
/// candidate count — `budget(L) = num_lines / drop_rate^(finest − L)`, with
/// the same [`MIN_DENSITY_LEVEL_FEATURES`](super::assign) floor and
/// spatial-fairness gamma — so coalescing does not bypass the mid-zoom cap
/// the budget was calibrated for. Deterministic; shared verbatim by both
/// pipelines (and the streaming counting pass) so their outputs and hints
/// stay identical.
pub(super) fn coalesce_level_chains(
    inputs: &[CoalesceInput<'_>],
    level: usize,
    finest: usize,
    gsd_m: f64,
    crs: Crs,
    options: &ConvertOptions,
) -> Vec<super::coalesce::CoalescedLine> {
    let budget = if options.density.enabled
        && options.density.drop_rate > 1.0
        && !options.density.drop_rate.is_nan()
        && level < finest
    {
        let keep = 1.0 / options.density.drop_rate;
        let raw = inputs.len() as f64 * keep.powi((finest - level) as i32);
        let max_chains = (raw.round() as usize).max(super::assign::MIN_DENSITY_LEVEL_FEATURES);
        Some((max_chains, options.density.gamma))
    } else {
        None
    };
    coalesce_level_lines(
        inputs,
        gsd_m,
        crs,
        &options.assign,
        &CoalesceParams {
            snap_gsd_factor: options.coalesce_snap,
            junction_angle_deg: options.coalesce_junction_angle,
            budget,
        },
    )
}

/// Build one level's [`CoalesceTable`]: run the chain stage
/// ([`coalesce_level_chains`]), then simplify each surviving chain for the
/// level. Chains that degenerate during simplification are dropped (default
/// knobs never hit this: the 2×GSD gate is stricter than the 1×GSD simplify
/// drop gate).
pub(super) fn build_level_coalesce_table(
    inputs: &[CoalesceInput<'_>],
    level: usize,
    finest: usize,
    gsd_m: f64,
    crs: Crs,
    options: &ConvertOptions,
) -> CoalesceTable {
    let chains = coalesce_level_chains(inputs, level, finest, gsd_m, crs, options);
    let mut table = CoalesceTable::with_capacity(chains.len());
    for chain in chains {
        match simplify_for_level(&chain.geom, gsd_m, crs, &options.simplify) {
            Simplified::Keep(g) => {
                table.insert(chain.rep, (g, chain.count));
            }
            Simplified::Dropped => {}
        }
    }
    table
}

/// Whether coalescing is effectively active for this conversion: enabled,
/// and the candidate line count fits the per-level memory guard. Logs when
/// the guard trips (the file still carries the `coalesced_count` column,
/// all 1, and the coalescing provenance).
pub(super) fn coalesce_effective(options: &ConvertOptions, num_lines: usize) -> bool {
    if !options.coalesce_lines {
        return false;
    }
    if num_lines > options.coalesce_max_level_rows {
        log::warn!(
            "coalescing skipped: {num_lines} candidate lines exceed \
             --coalesce-max-level-rows {} (chaining holds a level's line \
             geometries in memory; near-canonical levels this large need \
             coalescing least). Output keeps the coalesced_count column \
             (all 1).",
            options.coalesce_max_level_rows
        );
        return false;
    }
    true
}

/// Resolve the per-feature entry levels for a conversion (#364), or `None`
/// when no ladder was requested.
///
/// Shared by both pipelines so the ladder is derived once, the same way: the
/// column is looked up by name (following any #288 rename, since `options` is
/// already rewritten by then), its values extracted with the same numeric
/// coercion `--sort-key` uses, and the rungs mapped onto the level plan.
pub(super) fn resolve_entry_levels(
    options: &ConvertOptions,
    column_values: &[Option<f64>],
    level_specs: &[(f64, Option<u8>)],
) -> Result<Option<Vec<Option<u8>>>, ConvertError> {
    let Some(spec) = &options.entry_zoom else {
        return Ok(None);
    };
    let level_zooms: Vec<Option<u8>> = level_specs.iter().map(|(_, z)| *z).collect();
    let ladder = build_ladder(spec, column_values, &level_zooms)
        .map_err(|e| ConvertError::InvalidConfig(format!("entry-zoom: {e}")))?;
    let levels = entry_levels(&ladder, column_values, &level_zooms);
    let placed = levels.iter().filter(|l| l.is_some()).count();
    log::info!(
        "[assign] entry-zoom ladder on {:?}: {} rung(s) {:?}; {placed} of {} feature(s) placed",
        spec.column,
        ladder.len(),
        ladder.to_map(),
        column_values.len(),
    );
    // The ladder admits a feature to a level; write-time simplification then
    // decides what its geometry becomes there. With the drop default, a
    // feature whose geometry falls below the level tolerance is deleted — and
    // for a ladder those are exactly the features the caller asked for, since
    // the whole premise is that the strongest signal is the smallest geometry.
    // Orthogonal mechanisms, so this warns rather than overriding; the CLI
    // composes them by defaulting `--collapse` on alongside a ladder.
    if matches!(options.simplify.collapse, CollapseMode::Drop) && options.simplify.factor > 0.0 {
        log::warn!(
            "[assign] entry-zoom ladder with --collapse off: a laddered feature \
             admitted to a coarse level is still DROPPED there if its geometry \
             simplifies below that level's tolerance, which is the usual case for \
             the small-but-strong features a ladder exists to promote. Pass \
             --collapse (representative point) or --collapse-square to keep them, \
             or --simplify-factor 0 to disable simplification."
        );
    }
    // Likewise the per-level density budget, which runs after assignment and
    // sheds the lowest-priority survivors. Its priority is geometry-ranked
    // unless a sort key says otherwise — the same inversion the ladder exists
    // to correct — so it can undo the promotion feature by feature.
    if options.density.enabled && options.sort_key.is_none() {
        log::warn!(
            "[assign] entry-zoom ladder with the density budget on and no \
             --sort-key: the budget caps each level and sheds its lowest-priority \
             survivors by SIZE, which can drop the small-but-strong features the \
             ladder just promoted. Pass --no-density-drop, or --sort-key on the \
             same column so the budget ranks the way the ladder does."
        );
    }
    Ok(Some(levels))
}

/// Extract the ladder column's values, by name, from an in-memory table.
pub(super) fn entry_zoom_column_values(
    options: &ConvertOptions,
    schema: &Schema,
    table: &RecordBatch,
) -> Result<Vec<Option<f64>>, ConvertError> {
    let Some(spec) = &options.entry_zoom else {
        return Ok(Vec::new());
    };
    let idx = schema.index_of(&spec.column).map_err(|_| {
        ConvertError::InvalidConfig(format!(
            "entry-zoom column {:?} not found in the input schema",
            spec.column
        ))
    })?;
    Ok(extract_sort_keys(table.column(idx).as_ref()))
}

/// Build informative generalization provenance (§3.5) from the emitted gsds.
pub(super) fn build_generalization(
    gsds: &[f64],
    _crs: Crs,
    options: &ConvertOptions,
    ranking: RankingProvenance,
    renames: &[(String, String)],
) -> Generalization {
    let levels = gsds
        .iter()
        .map(|&gsd_m| GeneralizationLevel {
            simplify_tolerance_m: match options.mode {
                Mode::Duplicating => options.simplify.factor * gsd_m,
                Mode::Partitioning => 0.0,
            },
            thinning_factor: options.assign.polygon_thinning,
            visibility_gate_m: options.assign.polygon_visibility * gsd_m,
            geometry_types: Vec::new(),
        })
        .collect();
    Generalization {
        engine: format!("tylertoo {}", env!("CARGO_PKG_VERSION")),
        // Only record the base when it deviates from the default: a default run
        // then produces a byte-identical footer to before this knob existed
        // (the levels[].gsd already imply the default base, §5.2 / Q6).
        gsd_base: if options.gsd_base == GSD_TILE_BASE {
            None
        } else {
            Some(options.gsd_base)
        },
        levels,
        // Recorded only when cascading applied (#218, duplicating default):
        // a --no-cascade run omits the member so its footer stays
        // byte-identical to pre-cascade output. Partitioning never
        // simplifies, so it never cascades.
        cascade: if matches!(options.mode, Mode::Duplicating) && options.simplify.cascade {
            Some(true)
        } else {
            None
        },
        // Recorded only when a below-tolerance collapse disposition other
        // than the drop default was requested (`--collapse` /
        // `--collapse-square`, #279); a default run emits a byte-identical
        // footer to before this field existed.
        collapse: match options.simplify.collapse {
            CollapseMode::Drop => None,
            mode => Some(
                match mode {
                    CollapseMode::Point => "point",
                    CollapseMode::Square => "square",
                    CollapseMode::Drop => unreachable!(),
                }
                .to_string(),
            ),
        },
        // Recorded only when zoom-band representation overrides were
        // requested (#317 / #279); a band-free run emits a byte-identical
        // footer to before this feature existed.
        representation: if options.representation.is_empty() {
            None
        } else {
            Some(
                options
                    .representation
                    .iter()
                    .map(|b| RepresentationBandProvenance {
                        zooms: [b.min_zoom, b.max_zoom],
                        repr: b.repr.as_str().to_string(),
                    })
                    .collect(),
            )
        },
        ranking: Some(ranking),
        // Record the density budget only when it was applied; a disabled run
        // omits the block so its footer matches pre-Q2 output.
        density_drop: if options.density.enabled {
            Some(DensityProvenance {
                drop_rate: options.density.drop_rate,
                gamma: options.density.gamma,
                supercell_gsd_factor: SUPERCELL_GSD_FACTOR,
            })
        } else {
            None
        },
        // Recorded only when coalescing was requested; a non-coalesced run
        // emits a byte-identical footer to before this feature existed.
        coalescing: if options.coalesce_lines {
            Some(CoalescingProvenance {
                enabled: true,
                snap_tolerance_gsd_factor: options.coalesce_snap,
                // §13.4 (v0.2.0): the junction-continuation threshold and the
                // per-level candidate ceiling are REQUIRED provenance so the
                // generalization is reproducible from the file alone.
                junction_angle: Some(options.coalesce_junction_angle),
                max_level_rows: Some(options.coalesce_max_level_rows as u64),
                coalesced_count_column: COALESCED_COUNT_COLUMN.to_string(),
            })
        } else {
            None
        },
        // Recorded only when clustering was applied; a non-clustered run emits
        // a byte-identical footer to before this feature existed.
        clustering: if options.cluster {
            Some(ClusteringProvenance {
                enabled: true,
                point_count_column: POINT_COUNT_COLUMN.to_string(),
                accumulated: options
                    .accumulate
                    .iter()
                    .map(|s| AccumulatedColumn {
                        column: s.column.clone(),
                        op: s.op.as_str().to_string(),
                    })
                    .collect(),
            })
        } else {
            None
        },
        // #359: record which source columns were moved aside for a reserved
        // overview column, so the export can publish them under the name the
        // caller's data actually had. Absent when nothing collided, keeping
        // those footers byte-identical to before this field existed.
        renamed_columns: if renames.is_empty() {
            None
        } else {
            Some(
                renames
                    .iter()
                    .map(|(old, new)| (new.clone(), old.clone()))
                    .collect(),
            )
        },
    }
}

/// Resolve the cell-winner ranking for a conversion (Q1). Returns per-feature
/// sort keys (parallel to `full`'s rows / `geometries`) plus the provenance
/// block (§3.5). Tiers, in priority order:
///
/// 1. explicit numeric `--sort-key`;
/// 2. explicit categorical `class_ranking`;
/// 3. auto-detected Overture roads (`road_class`/`class`) or places
///    (`confidence`, points only) — unless `no_auto_rank`;
/// 4. `size-fallback` (no keys; assignment ranks by bbox diagonal + hash).
///
/// The chosen tier is logged (`log::info!`) so corpus runs show what happened.
fn resolve_ranking(
    input_schema: &Schema,
    full: &RecordBatch,
    geometries: &[Geometry<f64>],
    options: &ConvertOptions,
) -> Result<(Vec<Option<f64>>, RankingProvenance), ConvertError> {
    let n = full.num_rows();

    // Tier 1a: explicit numeric --sort-key.
    if let Some(name) = &options.sort_key {
        let idx = input_schema
            .index_of(name)
            .map_err(|_| ConvertError::SortKeyColumnMissing { name: name.clone() })?;
        let keys = extract_sort_keys(full.column(idx));
        log::info!("overview ranking: explicit numeric sort-key column {name:?}");
        return Ok((
            keys,
            RankingProvenance {
                mode: "explicit-sort-key".to_string(),
                column: Some(name.clone()),
                ranks: None,
                unknown_rank: None,
            },
        ));
    }

    // Tier 1b: explicit categorical class ranking.
    if let Some(cr) = &options.class_ranking {
        let idx = input_schema.index_of(&cr.column).map_err(|_| {
            ConvertError::ClassRankColumnMissing {
                name: cr.column.clone(),
            }
        })?;
        let keys = extract_class_ranks(full.column(idx), cr)?;
        log::info!(
            "overview ranking: explicit class-ranking on column {:?} ({} named classes, unknown_rank={})",
            cr.column,
            cr.ranks.len(),
            cr.unknown_rank
        );
        return Ok((keys, class_ranking_provenance("class-ranking", cr)));
    }

    // Tier 3: auto-detection of well-known schemas.
    if !options.no_auto_rank {
        // Overture transportation road classes.
        if let Some((idx, col_name)) = find_road_class_column(input_schema, full) {
            let cr = overture_road_ranking(col_name.clone());
            let keys = extract_class_ranks(full.column(idx), &cr)?;
            log::info!(
                "overview ranking: auto-detected Overture road classes in column {col_name:?}; \
                 applying built-in ranking (motorway > … > service > tail)"
            );
            return Ok((keys, class_ranking_provenance("auto-overture-roads", &cr)));
        }
        // Overture places confidence (numeric, point datasets only).
        if let Some((idx, col_name)) = find_confidence_column(input_schema, geometries) {
            let keys = extract_sort_keys(full.column(idx));
            log::info!(
                "overview ranking: auto-detected Overture places confidence column {col_name:?} \
                 (numeric point ranking)"
            );
            return Ok((
                keys,
                RankingProvenance {
                    mode: "auto-confidence".to_string(),
                    column: Some(col_name),
                    ranks: None,
                    unknown_rank: None,
                },
            ));
        }
    }

    // Fallback: size (bbox diagonal) + deterministic hash (existing behavior).
    log::info!(
        "overview ranking: no sort key specified or auto-detected; using size + \
         deterministic-hash fallback"
    );
    Ok((
        vec![None; n],
        RankingProvenance {
            mode: "size-fallback".to_string(),
            column: None,
            ranks: None,
            unknown_rank: None,
        },
    ))
}

/// Provenance for a categorical class ranking, echoing the map when small.
/// The footer shape is a JSON object map (spec §3.5 v0.2.0), so the ordered
/// pair list collapses into a `BTreeMap` here.
pub(super) fn class_ranking_provenance(mode: &str, cr: &ClassRanking) -> RankingProvenance {
    let ranks = if cr.ranks.len() <= MAX_PROVENANCE_RANKS {
        Some(cr.ranks.iter().cloned().collect())
    } else {
        None
    };
    RankingProvenance {
        mode: mode.to_string(),
        column: Some(cr.column.clone()),
        ranks,
        unknown_rank: Some(cr.unknown_rank),
    }
}

/// Map each row's string value to its class priority. Null values → `None`
/// (they lose to every ranked feature). A present-but-unranked value maps to
/// [`ClassRanking::unknown_rank`].
pub(super) fn extract_class_ranks(
    col: &dyn Array,
    ranking: &ClassRanking,
) -> Result<Vec<Option<f64>>, ConvertError> {
    use arrow_array::cast::AsArray;

    let map: HashMap<&str, f64> = ranking
        .ranks
        .iter()
        .map(|(k, v)| (k.as_str(), *v))
        .collect();
    let n = col.len();

    macro_rules! collect_str {
        ($arr:expr) => {{
            let a = $arr;
            (0..n)
                .map(|i| {
                    if a.is_null(i) {
                        None
                    } else {
                        Some(*map.get(a.value(i)).unwrap_or(&ranking.unknown_rank))
                    }
                })
                .collect()
        }};
    }

    match col.data_type() {
        DataType::Utf8 => Ok(collect_str!(col.as_string::<i32>())),
        DataType::LargeUtf8 => Ok(collect_str!(col.as_string::<i64>())),
        other => Err(ConvertError::ClassRankColumnNotString {
            name: ranking.column.clone(),
            data_type: format!("{other:?}"),
        }),
    }
}

/// Auto-detect an Overture road-class column: a Utf8/LargeUtf8 column named
/// `road_class` or `class` (case-insensitive) whose values overlap the known
/// transportation vocabulary by at least [`ROAD_VOCAB_MIN_DISTINCT`] distinct
/// classes. Returns `(column index, column name)`.
fn find_road_class_column(schema: &Schema, full: &RecordBatch) -> Option<(usize, String)> {
    for (idx, f) in schema.fields().iter().enumerate() {
        let lname = f.name().to_ascii_lowercase();
        if lname != "road_class" && lname != "class" {
            continue;
        }
        if !matches!(f.data_type(), DataType::Utf8 | DataType::LargeUtf8) {
            continue;
        }
        if column_overlaps_road_vocab(full.column(idx)) {
            return Some((idx, f.name().clone()));
        }
    }
    None
}

/// True if the string column contains at least [`ROAD_VOCAB_MIN_DISTINCT`]
/// distinct values from [`KNOWN_ROAD_CLASSES`].
fn column_overlaps_road_vocab(col: &dyn Array) -> bool {
    use arrow_array::cast::AsArray;

    let vocab: HashSet<&str> = KNOWN_ROAD_CLASSES.iter().copied().collect();
    let mut found: HashSet<&str> = HashSet::new();

    macro_rules! scan {
        ($arr:expr) => {{
            let a = $arr;
            for i in 0..a.len() {
                if a.is_null(i) {
                    continue;
                }
                if let Some(&hit) = vocab.get(a.value(i)) {
                    found.insert(hit);
                    if found.len() >= ROAD_VOCAB_MIN_DISTINCT {
                        return true;
                    }
                }
            }
        }};
    }

    match col.data_type() {
        DataType::Utf8 => scan!(col.as_string::<i32>()),
        DataType::LargeUtf8 => scan!(col.as_string::<i64>()),
        _ => return false,
    }
    found.len() >= ROAD_VOCAB_MIN_DISTINCT
}

/// Auto-detect an Overture places `confidence` column: a Float32/Float64 column
/// named `confidence` (case-insensitive), applied only when the dataset is
/// predominantly points. Returns `(column index, column name)`.
fn find_confidence_column(
    schema: &Schema,
    geometries: &[Geometry<f64>],
) -> Option<(usize, String)> {
    if geometries.is_empty() {
        return None;
    }
    let points = geometries
        .iter()
        .filter(|g| matches!(feature_kind(g), FeatureKind::Point))
        .count();
    // Require a point majority; confidence ranking is a points convention.
    if points * 2 < geometries.len() {
        return None;
    }
    for (idx, f) in schema.fields().iter().enumerate() {
        if f.name().eq_ignore_ascii_case("confidence")
            && matches!(f.data_type(), DataType::Float32 | DataType::Float64)
        {
            return Some((idx, f.name().clone()));
        }
    }
    None
}

/// Fill each level report's byte sizes by summing its row-group band from the
/// output file's Parquet footer.
pub(super) fn fill_level_bytes(
    output_path: &Path,
    meta: &super::level::OverviewsMeta,
    reports: &mut [LevelReport],
) -> Result<(), ConvertError> {
    let file = std::fs::File::open(output_path)?;
    let pq = ParquetRecordBatchReaderBuilder::try_new(file)?;
    let pmeta = pq.metadata();

    let mut start = 0usize;
    for (level, report) in meta.levels.iter().zip(reports.iter_mut()) {
        let end = level.row_group_end as usize;
        let mut uncompressed = 0i64;
        let mut compressed = 0i64;
        for rg in start..=end {
            let rgm = pmeta.row_group(rg);
            uncompressed += rgm.total_byte_size();
            compressed += rgm.compressed_size();
        }
        report.uncompressed_bytes = uncompressed;
        report.compressed_bytes = compressed;
        start = end + 1;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// #274: proptest pinning `scan_feature` byte-equivalent to the three
    /// functions it fuses (`usable_geometry` + `geometry_bbox` + `feature_kind`).
    /// Generates points/lines/polygons/multis with holes and occasional
    /// non-finite/empty coords, exercising every parity edge (exterior-only
    /// polygon bbox, all-coords finiteness, empty-exterior → 0-bbox).
    mod scan_feature_props {
        use super::super::{feature_kind, geometry_bbox, scan_feature, usable_geometry};
        use geo::{Geometry, LineString, MultiLineString, MultiPolygon, Point, Polygon};
        use proptest::prelude::*;

        fn any_f64() -> impl Strategy<Value = f64> {
            prop_oneof![
                8 => -1.0e6f64..1.0e6f64,
                1 => Just(f64::NAN),
                1 => prop_oneof![Just(f64::INFINITY), Just(f64::NEG_INFINITY)],
            ]
        }
        fn any_coord() -> impl Strategy<Value = geo::Coord<f64>> {
            (any_f64(), any_f64()).prop_map(|(x, y)| geo::Coord { x, y })
        }
        fn any_ring() -> impl Strategy<Value = LineString<f64>> {
            proptest::collection::vec(any_coord(), 0..6).prop_map(LineString::new)
        }
        fn any_polygon() -> impl Strategy<Value = Polygon<f64>> {
            (any_ring(), proptest::collection::vec(any_ring(), 0..3))
                .prop_map(|(ext, ints)| Polygon::new(ext, ints))
        }
        fn any_geometry() -> impl Strategy<Value = Geometry<f64>> {
            prop_oneof![
                any_coord().prop_map(|c| Geometry::Point(Point::from(c))),
                proptest::collection::vec(any_coord(), 0..5)
                    .prop_map(|cs| Geometry::MultiPoint(cs.into_iter().map(Point::from).collect())),
                any_ring().prop_map(Geometry::LineString),
                proptest::collection::vec(any_ring(), 0..3)
                    .prop_map(|ls| Geometry::MultiLineString(MultiLineString::new(ls))),
                any_polygon().prop_map(Geometry::Polygon),
                proptest::collection::vec(any_polygon(), 0..3)
                    .prop_map(|ps| Geometry::MultiPolygon(MultiPolygon::new(ps))),
            ]
        }

        proptest! {
            #[test]
            fn scan_feature_matches_components(g in any_geometry()) {
                let expected = if usable_geometry(&g) {
                    Some((feature_kind(&g), geometry_bbox(&g)))
                } else {
                    None
                };
                prop_assert_eq!(scan_feature(&g), expected);
            }
        }
    }

    use crate::overview::check::validate_file;
    use crate::overview::level::gsd;
    use crate::overview::reader::OverviewReader;
    use arrow_array::{Float64Array, Int64Array, RecordBatch, StringArray};
    use arrow_schema::{DataType, Field, Schema};
    use geo::{Geometry, LineString, Point, Polygon};
    use geoarrow::array::GeometryBuilder;
    use geoarrow::datatypes::GeometryType;
    use geoarrow_array::GeoArrowArray;
    use geoparquet::writer::{
        GeoParquetRecordBatchEncoder, GeoParquetWriterEncoding, GeoParquetWriterOptionsBuilder,
    };
    use parquet::arrow::ArrowWriter;

    use crate::batch_processor::extract_geometries_from_array;

    /// #267: the download-first nudge fires only for a large *whole-file*
    /// remote convert, and stays quiet for local inputs, effective bbox
    /// extracts, and small objects.
    #[test]
    fn full_file_remote_warning_gated_on_large_unpruned_remote() {
        const BIG: u64 = 4 << 30; // 4 GiB, above the 1 GiB threshold
                                  // Local input (0 remote parts): re-reads hit
                                  // the OS page cache — never warn.
        assert!(full_file_remote_warning(0, 8, 8, BIG).is_none());
        // Effective bbox extract (fewer row groups read): never warn.
        assert!(full_file_remote_warning(1, 2, 8, BIG).is_none());
        // Small remote object: below threshold — never warn.
        assert!(full_file_remote_warning(1, 8, 8, 100 << 20).is_none());
        // Just below the threshold: still quiet.
        assert!(full_file_remote_warning(1, 8, 8, FULL_FILE_REMOTE_WARN_BYTES - 1).is_none());
        // At the threshold: warns (guard is a strict `<`).
        assert!(full_file_remote_warning(1, 8, 8, FULL_FILE_REMOTE_WARN_BYTES).is_some());
        // Large full-file remote: warns, and the nudge names the cheaper paths.
        let msg = full_file_remote_warning(1, 8, 8, BIG)
            .expect("large full-file remote convert should warn");
        assert!(msg.contains("--bbox"), "nudge should mention --bbox: {msg}");
        assert!(
            msg.contains("4.0 GiB"),
            "nudge should state the object size: {msg}"
        );
        assert!(
            !msg.contains("partitions"),
            "single object: no part count in the message: {msg}"
        );
    }

    /// v0.7 multi-partition: the summed object size trips the same
    /// threshold (20 × 600 MB with no bbox IS a ≥1 GiB full-file remote
    /// convert), and the message names the part count so the total is not
    /// mistaken for one object.
    #[test]
    fn full_file_remote_warning_names_partition_count() {
        const PART: u64 = 600 << 20; // 600 MB per partition
        let msg = full_file_remote_warning(20, 40, 40, 20 * PART)
            .expect("20 x 600 MB unpruned remote parts should warn");
        assert!(
            msg.contains("20 remote partitions"),
            "message names the part count: {msg}"
        );
        assert!(
            msg.contains("11.7 GiB"),
            "message states the summed size: {msg}"
        );
        // Summed size below the threshold stays quiet regardless of count.
        assert!(full_file_remote_warning(20, 40, 40, 500 << 20).is_none());
    }

    /// #272: the spill free-space preflight warns when the projected spill
    /// (≈ the selected input bytes, plus a 5% safety margin) exceeds the
    /// free space on the spill volume — naming the directory, the shortfall,
    /// and the `--spill-dir` escape hatch.
    #[test]
    fn spill_space_warning_names_dir_and_shortfall() {
        let dir = Path::new("/mnt/scratch");
        let msg = spill_space_warning(10 << 30, 1 << 30, dir).expect("shortfall should warn");
        assert!(
            msg.contains("/mnt/scratch"),
            "warning names the spill dir: {msg}"
        );
        assert!(
            msg.contains("--spill-dir"),
            "warning suggests --spill-dir: {msg}"
        );
        // need = 10 GiB + 5% = 10.5 GiB; available 1 GiB → 9.5 GiB short.
        assert!(
            msg.contains("9.5 GiB"),
            "warning states the shortfall: {msg}"
        );
    }

    /// #272: ample space stays quiet, and the margin boundary is exact —
    /// available == estimated + 5% is enough, one byte less is not.
    #[test]
    fn spill_space_warning_quiet_with_ample_space() {
        let dir = Path::new("/tmp");
        assert!(spill_space_warning(1 << 30, 20 << 30, dir).is_none());
        let est: u64 = 20 << 20;
        let need = est + est / 20;
        assert!(spill_space_warning(est, need, dir).is_none());
        assert!(spill_space_warning(est, need - 1, dir).is_some());
    }

    /// #272: local inputs never spill, so the free-space probe must not
    /// even run for them; a failed probe (None) stays quiet rather than
    /// crying wolf; a zero estimate (empty selection) stays quiet too.
    #[test]
    fn spill_space_check_gating() {
        let dir = Path::new("/tmp");
        assert!(spill_space_check(false, 10 << 30, dir, |_| panic!(
            "free-space probe must not run for local inputs"
        ))
        .is_none());
        assert!(spill_space_check(true, 10 << 30, dir, |_| None).is_none());
        assert!(spill_space_check(true, 0, dir, |_| Some(0)).is_none());
        assert!(spill_space_check(true, 10 << 30, dir, |_| Some(1)).is_some());
    }

    /// #272: a configured spill dir must exist — fail fast at option
    /// validation instead of silently degrading to network re-fetch when
    /// the spill file cannot be created mid-convert.
    #[test]
    fn validate_options_rejects_missing_spill_dir() {
        let opts = ConvertOptions {
            spill_dir: Some(std::path::PathBuf::from(
                "/nonexistent/tylertoo-spill-dir-272",
            )),
            ..Default::default()
        };
        let err = validate_options(&opts).expect_err("missing spill dir must be rejected");
        let msg = err.to_string();
        assert!(msg.contains("spill-dir"), "error names the option: {msg}");
        assert!(
            msg.contains("/nonexistent/tylertoo-spill-dir-272"),
            "error names the path: {msg}"
        );
    }

    // --- synthetic GeoParquet input builders --------------------------------

    /// A mix of points, lines, and polygons spread far apart so coarse-level
    /// thinning keeps distinct cell winners.
    fn synthetic_geometries() -> Vec<Geometry<f64>> {
        let mut geoms = Vec::new();
        // Points on a coarse grid (meters, EPSG:3857-ish scale via 4326? we use
        // 4326 degrees here, but coordinates are just far apart).
        for i in 0..6 {
            let x = i as f64 * 5.0;
            let y = i as f64 * 3.0;
            geoms.push(Geometry::Point(Point::new(x, y)));
        }
        // A few multi-vertex lines.
        for i in 0..4 {
            let base = 40.0 + i as f64 * 10.0;
            let ls = LineString::from(
                (0..12)
                    .map(|k| {
                        (
                            base + k as f64 * 0.5,
                            (k as f64 * 0.6).sin() + i as f64 * 8.0,
                        )
                    })
                    .collect::<Vec<_>>(),
            );
            geoms.push(Geometry::LineString(ls));
        }
        // Polygons of varying size.
        for i in 0..4 {
            let cx = -60.0 + i as f64 * 12.0;
            let cy = -40.0 - i as f64 * 5.0;
            let half = 2.0 + i as f64 * 1.5;
            let ext = LineString::from(vec![
                (cx - half, cy - half),
                (cx + half, cy - half),
                (cx + half, cy + half),
                (cx - half, cy + half),
                (cx - half, cy - half),
            ]);
            geoms.push(Geometry::Polygon(Polygon::new(ext, vec![])));
        }
        geoms
    }

    fn build_geometry_array(geoms: &[Geometry<f64>]) -> geoarrow::array::GeometryArray {
        let typ = GeometryType::new(Default::default());
        let mut b = GeometryBuilder::new(typ).with_prefer_multi(false);
        b.extend_from_iter(geoms.iter().map(Some));
        b.finish()
    }

    /// Field names of an overview output file, in schema order.
    fn output_column_names(path: &Path) -> Vec<String> {
        let file = std::fs::File::open(path).unwrap();
        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
        builder
            .schema()
            .fields()
            .iter()
            .map(|f| f.name().clone())
            .collect()
    }

    /// Write a valid GeoParquet file (WKB, covering) with id/name/rank props and
    /// the given geometries. `extra_level_col` injects a `level` Int32 column to
    /// exercise the reserved-column auto-rename path (#288). `crs_projjson`
    /// overrides the geometry CRS.
    fn write_input(
        path: &Path,
        geoms: &[Geometry<f64>],
        extra_level_col: bool,
        crs_metadata: Option<geoarrow::datatypes::Metadata>,
    ) {
        let n = geoms.len();
        let id = Int64Array::from((0..n as i64).collect::<Vec<_>>());
        let name = StringArray::from((0..n).map(|i| format!("f{i}")).collect::<Vec<_>>());
        let rank = Float64Array::from((0..n).map(|i| (n - i) as f64).collect::<Vec<_>>());

        let geom_arr = if let Some(md) = crs_metadata {
            let typ = GeometryType::new(Arc::new(md));
            let mut b = GeometryBuilder::new(typ).with_prefer_multi(false);
            b.extend_from_iter(geoms.iter().map(Some));
            b.finish()
        } else {
            build_geometry_array(geoms)
        };
        let geom_field = geom_arr.data_type().to_field("geometry", true);

        let mut fields = vec![
            Arc::new(Field::new("id", DataType::Int64, false)),
            Arc::new(Field::new("name", DataType::Utf8, false)),
            Arc::new(Field::new("rank", DataType::Float64, false)),
        ];
        let mut columns: Vec<Arc<dyn Array>> = vec![Arc::new(id), Arc::new(name), Arc::new(rank)];
        if extra_level_col {
            fields.push(Arc::new(Field::new("level", DataType::Int32, false)));
            columns.push(Arc::new(arrow_array::Int32Array::from(vec![0i32; n])));
        }
        fields.push(Arc::new(geom_field));
        columns.push(geom_arr.to_array_ref());

        let schema = Arc::new(Schema::new(fields));
        let batch = RecordBatch::try_new(schema.clone(), columns).unwrap();

        let gpq_options = GeoParquetWriterOptionsBuilder::default()
            .set_encoding(GeoParquetWriterEncoding::WKB)
            .set_generate_covering(true)
            .build();
        let encoder = GeoParquetRecordBatchEncoder::try_new(&schema, &gpq_options).unwrap();
        let target_schema = encoder.target_schema();

        let file = std::fs::File::create(path).unwrap();
        let mut writer = ArrowWriter::try_new(file, target_schema, None).unwrap();
        // encode_record_batch requires &mut encoder.
        let mut encoder = encoder;
        let encoded = encoder.encode_record_batch(&batch).unwrap();
        writer.write(&encoded).unwrap();
        writer.append_key_value_metadata(encoder.into_keyvalue().unwrap());
        writer.close().unwrap();
    }

    /// Read (id, name, rank, geometry) for a single level from an overview file.
    fn read_level_rows(
        reader: &OverviewReader,
        level: usize,
    ) -> Vec<(i64, String, f64, Geometry<f64>)> {
        use arrow_array::cast::AsArray;
        use arrow_array::types::Float64Type;
        let rdr = reader.read_level(level, None).unwrap();
        let mut out = Vec::new();
        for batch in rdr {
            let batch = batch.unwrap();
            let ids = batch
                .column(batch.schema().index_of("id").unwrap())
                .as_primitive::<arrow_array::types::Int64Type>()
                .clone();
            let names = batch
                .column(batch.schema().index_of("name").unwrap())
                .as_string::<i32>()
                .clone();
            let ranks = batch
                .column(batch.schema().index_of("rank").unwrap())
                .as_primitive::<Float64Type>()
                .clone();
            let gcol = batch.column(batch.schema().index_of("geometry").unwrap());
            let garr: Arc<dyn GeoArrowArray> = from_arrow_array(
                gcol.as_ref(),
                batch
                    .schema()
                    .field(batch.schema().index_of("geometry").unwrap()),
            )
            .unwrap();
            let mut gvec = Vec::new();
            extract_geometries_from_array(garr.as_ref(), &mut gvec).unwrap();
            for (i, g) in gvec.iter().enumerate() {
                out.push((
                    ids.value(i),
                    names.value(i).to_string(),
                    ranks.value(i),
                    g.clone(),
                ));
            }
        }
        out
    }

    // --- multi-partition input (v0.7) ----------------------------------------

    /// Write a valid GeoParquet partition holding `geoms[range]` with the
    /// SAME global id/name/rank values [`write_input`] assigns, so the
    /// concatenation of partitions equals the single file row-for-row.
    /// `row_group_rows` caps rows per row group (None = single row group).
    fn write_input_partition(
        path: &Path,
        geoms: &[Geometry<f64>],
        range: std::ops::Range<usize>,
        row_group_rows: Option<usize>,
    ) {
        use parquet::file::properties::WriterProperties;
        let total = geoms.len();
        let idx: Vec<usize> = range.collect();
        let id = Int64Array::from(idx.iter().map(|&i| i as i64).collect::<Vec<_>>());
        let name = StringArray::from(idx.iter().map(|&i| format!("f{i}")).collect::<Vec<_>>());
        let rank = Float64Array::from(idx.iter().map(|&i| (total - i) as f64).collect::<Vec<_>>());
        let part_geoms: Vec<Geometry<f64>> = idx.iter().map(|&i| geoms[i].clone()).collect();
        let geom_arr = build_geometry_array(&part_geoms);
        let geom_field = geom_arr.data_type().to_field("geometry", true);

        let fields = vec![
            Arc::new(Field::new("id", DataType::Int64, false)),
            Arc::new(Field::new("name", DataType::Utf8, false)),
            Arc::new(Field::new("rank", DataType::Float64, false)),
            Arc::new(geom_field),
        ];
        let columns: Vec<Arc<dyn Array>> = vec![
            Arc::new(id),
            Arc::new(name),
            Arc::new(rank),
            geom_arr.to_array_ref(),
        ];
        let schema = Arc::new(Schema::new(fields));
        let batch = RecordBatch::try_new(schema.clone(), columns).unwrap();

        let gpq_options = GeoParquetWriterOptionsBuilder::default()
            .set_encoding(GeoParquetWriterEncoding::WKB)
            .set_generate_covering(true)
            .build();
        let mut encoder = GeoParquetRecordBatchEncoder::try_new(&schema, &gpq_options).unwrap();
        let target_schema = encoder.target_schema();
        let props = row_group_rows.map(|n| {
            WriterProperties::builder()
                .set_max_row_group_row_count(Some(n))
                .build()
        });
        let file = std::fs::File::create(path).unwrap();
        let mut writer = ArrowWriter::try_new(file, target_schema, props).unwrap();
        let encoded = encoder.encode_record_batch(&batch).unwrap();
        writer.write(&encoded).unwrap();
        writer.append_key_value_metadata(encoder.into_keyvalue().unwrap());
        writer.close().unwrap();
    }

    /// Convert `input` and export to PMTiles; returns the archive bytes.
    /// PMTiles export is byte-deterministic (unlike the overview parquet
    /// footer), so multi/single equivalence is asserted on these bytes.
    fn convert_and_export(input: &Path, workdir: &Path, opts: &ConvertOptions) -> Vec<u8> {
        use crate::overview::export::{export_pmtiles, ExportOptions};
        let stem = input
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .replace('.', "_");
        let overview = workdir.join(format!("{stem}-overview.parquet"));
        let pmtiles = workdir.join(format!("{stem}.pmtiles"));
        convert_to_overviews(input, &overview, opts).unwrap();
        export_pmtiles(&overview, &pmtiles, &ExportOptions::default()).unwrap();
        std::fs::read(&pmtiles).unwrap()
    }

    fn multi_test_options() -> ConvertOptions {
        ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            ..Default::default()
        }
    }

    /// THE anchor: identical rows as (a) one parquet file and (b) three
    /// partition files must produce byte-identical PMTiles. All passes see
    /// the same rows in the same order (winner tables are keyed by global
    /// row offset), so the outputs match exactly.
    #[test]
    fn multi_partition_output_matches_single_file() {
        let geoms = synthetic_geometries();
        let n = geoms.len();
        let dir = tempfile::tempdir().unwrap();
        let single = dir.path().join("single.parquet");
        write_input_partition(&single, &geoms, 0..n, None);
        let parts = dir.path().join("parts");
        std::fs::create_dir(&parts).unwrap();
        write_input_partition(&parts.join("part-000.parquet"), &geoms, 0..5, None);
        write_input_partition(&parts.join("part-001.parquet"), &geoms, 5..9, None);
        write_input_partition(&parts.join("part-002.parquet"), &geoms, 9..n, None);

        let opts = multi_test_options();
        let report =
            convert_to_overviews(&parts, dir.path().join("probe-overview.parquet"), &opts).unwrap();
        assert_eq!(report.input_features, n);
        assert_eq!(report.row_groups_total, 3, "one row group per partition");

        let pm_single = convert_and_export(&single, dir.path(), &opts);
        let pm_multi = convert_and_export(&parts, dir.path(), &opts);
        assert!(
            pm_single == pm_multi,
            "multi-partition output must be byte-identical to single-file \
             ({} vs {} bytes)",
            pm_single.len(),
            pm_multi.len()
        );
    }

    /// A 0-row partition mid-set is skipped cleanly: global row offsets are
    /// unaffected and the output still matches the single-file equivalent.
    #[test]
    fn multi_partition_zero_row_part_matches_single_file() {
        let geoms = synthetic_geometries();
        let n = geoms.len();
        let dir = tempfile::tempdir().unwrap();
        let single = dir.path().join("single.parquet");
        write_input_partition(&single, &geoms, 0..n, None);
        let parts = dir.path().join("parts");
        std::fs::create_dir(&parts).unwrap();
        write_input_partition(&parts.join("part-000.parquet"), &geoms, 0..5, None);
        write_input_partition(&parts.join("part-001.parquet"), &geoms, 5..5, None); // 0 rows
        write_input_partition(&parts.join("part-002.parquet"), &geoms, 5..n, None);

        let opts = multi_test_options();
        let pm_single = convert_and_export(&single, dir.path(), &opts);
        let pm_multi = convert_and_export(&parts, dir.path(), &opts);
        assert!(
            pm_single == pm_multi,
            "0-row partition must not shift rows or offsets"
        );
    }

    /// bbox row-group pruning (#102) composes with multi-partition input:
    /// the selection is per part, offsets stay aligned across the pruned
    /// read, and the output matches the single-file bbox extract.
    #[test]
    fn multi_partition_bbox_selection_matches_single_file() {
        let geoms = synthetic_geometries();
        let n = geoms.len();
        let dir = tempfile::tempdir().unwrap();
        let single = dir.path().join("single.parquet");
        write_input_partition(&single, &geoms, 0..n, Some(2));
        let parts = dir.path().join("parts");
        std::fs::create_dir(&parts).unwrap();
        write_input_partition(&parts.join("part-000.parquet"), &geoms, 0..6, Some(2));
        write_input_partition(&parts.join("part-001.parquet"), &geoms, 6..10, Some(2));
        write_input_partition(&parts.join("part-002.parquet"), &geoms, 10..n, Some(2));

        // Points (x 0..25) and polygons (x -78..-15) only; the lines
        // (x 40..96) fall outside, so their row groups prune away.
        let bbox = Some([-100.0, -70.0, 30.0, 20.0]);
        let opts = ConvertOptions {
            bbox,
            ..multi_test_options()
        };
        let report =
            convert_to_overviews(&parts, dir.path().join("probe-overview.parquet"), &opts).unwrap();
        assert!(
            report.row_groups_read < report.row_groups_total,
            "bbox must prune row groups across parts: {}/{}",
            report.row_groups_read,
            report.row_groups_total
        );

        let pm_single = convert_and_export(&single, dir.path(), &opts);
        let pm_multi = convert_and_export(&parts, dir.path(), &opts);
        assert!(
            pm_single == pm_multi,
            "per-part bbox selection must keep offsets aligned"
        );
    }

    /// The in-memory reference path (`--no-streaming`) does not support
    /// multi-partition input; it must fail with a clear error.
    #[test]
    fn multi_partition_requires_streaming_pipeline() {
        let geoms = synthetic_geometries();
        let dir = tempfile::tempdir().unwrap();
        let parts = dir.path().join("parts");
        std::fs::create_dir(&parts).unwrap();
        write_input_partition(&parts.join("part-000.parquet"), &geoms, 0..5, None);
        write_input_partition(
            &parts.join("part-001.parquet"),
            &geoms,
            5..geoms.len(),
            None,
        );

        let opts = ConvertOptions {
            streaming: false,
            ..multi_test_options()
        };
        let err = convert_to_overviews(&parts, dir.path().join("out.parquet"), &opts).unwrap_err();
        assert!(
            matches!(err, ConvertError::MultiPartitionRequiresStreaming),
            "expected MultiPartitionRequiresStreaming, got {err:?}"
        );
    }

    /// Partitions disagreeing on CRS are rejected at resolve time with an
    /// error naming the offending file.
    #[test]
    fn multi_partition_crs_mismatch_rejected() {
        let geoms = synthetic_geometries();
        let dir = tempfile::tempdir().unwrap();
        let parts = dir.path().join("parts");
        std::fs::create_dir(&parts).unwrap();
        write_input(&parts.join("a.parquet"), &geoms, false, None);
        // EPSG:32633 in the second partition (also differs in geometry
        // extension metadata — either check may fire; both name the file).
        let projjson = serde_json::json!({
            "type": "ProjectedCRS",
            "name": "UTM zone 33N",
            "id": { "authority": "EPSG", "code": 32633 }
        });
        let md = geoarrow::datatypes::Metadata::new(
            geoarrow::datatypes::Crs::from_projjson(projjson),
            None,
        );
        write_input(&parts.join("b.parquet"), &geoms, false, Some(md));

        let err = convert_to_overviews(
            &parts,
            dir.path().join("out.parquet"),
            &multi_test_options(),
        )
        .unwrap_err();
        match err {
            ConvertError::Input(crate::input::InputError::IncompatiblePartition {
                offender,
                ..
            }) => {
                assert!(offender.ends_with("b.parquet"), "offender: {offender}");
            }
            other => panic!("expected IncompatiblePartition, got {other:?}"),
        }
    }

    // --- tests --------------------------------------------------------------

    #[test]
    fn duplicating_canonical_matches_input() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();

        // Output validates clean.
        let vr = validate_file(tout.path()).unwrap();
        assert!(
            vr.is_valid(),
            "failures: {:?}",
            vr.failures().collect::<Vec<_>>()
        );

        let reader = OverviewReader::open(tout.path()).unwrap();
        assert_eq!(reader.mode(), Mode::Duplicating);
        let canonical = reader.num_levels() - 1;

        // Canonical row count == input row count, values identical & in order.
        let rows = read_level_rows(&reader, canonical);
        assert_eq!(rows.len(), geoms.len());
        for (i, (id, name, rank, geom)) in rows.iter().enumerate() {
            assert_eq!(*id, i as i64);
            assert_eq!(name, &format!("f{i}"));
            assert_eq!(*rank, (geoms.len() - i) as f64);
            assert_eq!(geom, &geoms[i], "canonical geometry must be verbatim");
        }

        // Report canonical level feature count matches input.
        assert_eq!(report.input_features, geoms.len());
        assert_eq!(report.levels[canonical].feature_count, geoms.len());
    }

    #[test]
    fn duplicating_coarse_levels_monotone() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 1,
                max_zoom: 10,
            },
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();

        // Feature and vertex counts are monotonically non-decreasing coarse→fine.
        for w in report.levels.windows(2) {
            assert!(
                w[0].feature_count <= w[1].feature_count,
                "feature counts not monotone: {:?}",
                report.levels
            );
            assert!(
                w[0].vertex_count <= w[1].vertex_count,
                "vertex counts not monotone: {:?}",
                report.levels
            );
        }
        // Canonical has all features.
        assert_eq!(report.levels.last().unwrap().feature_count, geoms.len());

        // level column consistent with footer bands (validator covers this).
        assert!(validate_file(tout.path()).unwrap().is_valid());
    }

    // ---- zoom-band representation selector (#317 / #279) --------------------

    /// Polygon fixtures spanning sizes from "visible at every zoom" down to
    /// tiny, scattered so they don't all share thinning cells.
    fn polygon_fixture() -> Vec<Geometry<f64>> {
        let mut geoms = Vec::new();
        for i in 0..12 {
            let cx = -150.0 + i as f64 * 25.0;
            let cy = -60.0 + (i % 5) as f64 * 27.0;
            // Halves from 20 degrees down to 0.002 degrees.
            let half = 20.0 / (3f64).powi(i % 9);
            let ext = LineString::from(vec![
                (cx - half, cy - half),
                (cx + half, cy - half),
                (cx + half, cy + half),
                (cx - half, cy + half),
                (cx - half, cy - half),
            ]);
            geoms.push(Geometry::Polygon(Polygon::new(ext, vec![])));
        }
        geoms
    }

    fn band(min_zoom: u8, max_zoom: u8, repr: Representation) -> RepresentationBand {
        RepresentationBand {
            min_zoom,
            max_zoom,
            repr,
        }
    }

    /// THE #317 acceptance anchor: one convert yields an archive whose point-
    /// band levels contain ONLY points while the finer levels keep polygons —
    /// no two-archive merge.
    #[test]
    fn representation_point_band_points_coarse_polygons_fine() {
        let geoms = polygon_fixture();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            representation: vec![band(2, 5, Representation::Point)],
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        assert!(validate_file(tout.path()).unwrap().is_valid());

        let reader = OverviewReader::open(tout.path()).unwrap();
        for (idx, lvl) in report.levels.iter().enumerate() {
            let rows = read_level_rows(&reader, idx);
            assert!(!rows.is_empty());
            let zoom = lvl.zoom.expect("zoom-range plan records zooms");
            if zoom <= 5 {
                for (id, _, _, g) in &rows {
                    assert!(
                        matches!(g, Geometry::Point(_)),
                        "level z{zoom} feature {id} must be a Point, got {g:?}"
                    );
                }
            } else {
                assert!(
                    rows.iter().any(|(_, _, _, g)| matches!(
                        g,
                        Geometry::Polygon(_) | Geometry::MultiPolygon(_)
                    )),
                    "level z{zoom} must keep polygons"
                );
            }
        }
        // Canonical is verbatim.
        let canonical = read_level_rows(&reader, report.levels.len() - 1);
        assert_eq!(canonical.len(), geoms.len());
        for (i, (_, _, _, g)) in canonical.iter().enumerate() {
            assert_eq!(g, &geoms[i]);
        }

        // Point-band levels have full coverage: the visibility gate is
        // bypassed, so the coarsest level carries a dot per surviving
        // thinning cell — more features than the gate-limited polygon run.
        let plain = ConvertOptions {
            representation: Vec::new(),
            ..opts.clone()
        };
        let tout2 = tempfile::NamedTempFile::new().unwrap();
        let plain_report = convert_to_overviews(tin.path(), tout2.path(), &plain).unwrap();
        assert!(
            report.levels[0].feature_count >= plain_report.levels[0].feature_count,
            "point band must not lose coarse coverage vs the gated polygon run"
        );

        // Provenance recorded (§3.5).
        let gen = reader
            .meta()
            .generalization
            .as_ref()
            .expect("generalization block present");
        let bands = gen.representation.as_ref().expect("bands recorded");
        assert_eq!(bands.len(), 1);
        assert_eq!(bands[0].zooms, [2, 5]);
        assert_eq!(bands[0].repr, "point");
        assert!(gen.collapse.is_none(), "no global collapse requested");
    }

    /// Streaming and in-memory pipelines produce identical per-level rows
    /// for a point-band conversion (the #218-style engine equivalence).
    #[test]
    fn representation_point_band_streaming_matches_in_memory() {
        let geoms = polygon_fixture();
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let base = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            representation: vec![band(2, 4, Representation::Point)],
            ..Default::default()
        };
        let t_stream = tempfile::NamedTempFile::new().unwrap();
        let t_mem = tempfile::NamedTempFile::new().unwrap();
        let r1 = convert_to_overviews(tin.path(), t_stream.path(), &base).unwrap();
        let mem = ConvertOptions {
            streaming: false,
            ..base
        };
        let r2 = convert_to_overviews(tin.path(), t_mem.path(), &mem).unwrap();
        assert_eq!(r1.levels.len(), r2.levels.len());

        let rd1 = OverviewReader::open(t_stream.path()).unwrap();
        let rd2 = OverviewReader::open(t_mem.path()).unwrap();
        for lvl in 0..r1.levels.len() {
            assert_eq!(
                read_level_rows(&rd1, lvl),
                read_level_rows(&rd2, lvl),
                "level {lvl} rows must match across engines"
            );
        }
    }

    /// #279: a square band keeps the level type-uniform (`Polygon` only) —
    /// visible polygons simplified, below-tolerance ones dithered into
    /// placeholder squares instead of vanishing.
    #[test]
    fn representation_square_band_type_preserving() {
        // Many tiny polygons clustered plus a few large ones.
        let mut geoms = polygon_fixture();
        for i in 0..30 {
            let cx = 10.0 + (i % 6) as f64 * 0.02;
            let cy = 20.0 + (i / 6) as f64 * 0.02;
            let half = 0.004;
            let ext = LineString::from(vec![
                (cx - half, cy - half),
                (cx + half, cy - half),
                (cx + half, cy + half),
                (cx - half, cy + half),
                (cx - half, cy - half),
            ]);
            geoms.push(Geometry::Polygon(Polygon::new(ext, vec![])));
        }
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 4,
                max_zoom: 10,
            },
            representation: vec![band(4, 7, Representation::Square)],
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        assert!(validate_file(tout.path()).unwrap().is_valid());

        let reader = OverviewReader::open(tout.path()).unwrap();
        for (idx, lvl) in report.levels.iter().enumerate() {
            let zoom = lvl.zoom.unwrap();
            let rows = read_level_rows(&reader, idx);
            for (id, _, _, g) in &rows {
                assert!(
                    matches!(g, Geometry::Polygon(_) | Geometry::MultiPolygon(_)),
                    "square band is type-preserving; level z{zoom} feature {id} \
                     is {g:?}"
                );
            }
        }

        // At the band's levels, at least one emitted geometry is an exact
        // GSD-sized placeholder square (5-coordinate ring, side = level
        // tolerance in degrees).
        let z4_rows = read_level_rows(&reader, 0);
        let tol_deg = report.levels[0].gsd / METERS_PER_DEGREE;
        let squares = z4_rows
            .iter()
            .filter(|(_, _, _, g)| match g {
                Geometry::Polygon(p) => {
                    let r = geo::BoundingRect::bounding_rect(p).unwrap();
                    p.exterior().0.len() == 5
                        && (r.width() - tol_deg).abs() < 1e-9
                        && (r.height() - tol_deg).abs() < 1e-9
                }
                _ => false,
            })
            .count();
        assert!(
            squares > 0,
            "band level must contain dithered placeholder squares"
        );

        let gen = reader.meta().generalization.as_ref().unwrap();
        let bands = gen.representation.as_ref().unwrap();
        assert_eq!(bands[0].repr, "square");
    }

    /// #279 global disposition: `--collapse-square` emits placeholder
    /// squares wherever the drop default would have dropped, at every level,
    /// and records `"square"` provenance.
    #[test]
    fn collapse_square_global_disposition() {
        let geoms = polygon_fixture();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            simplify: SimplifyOptions {
                collapse: CollapseMode::Square,
                ..Default::default()
            },
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        assert!(validate_file(tout.path()).unwrap().is_valid());

        let reader = OverviewReader::open(tout.path()).unwrap();
        // Type-preserving everywhere.
        for idx in 0..report.levels.len() {
            for (_, _, _, g) in read_level_rows(&reader, idx) {
                assert!(matches!(
                    g,
                    Geometry::Polygon(_) | Geometry::MultiPolygon(_)
                ));
            }
        }
        let gen = reader.meta().generalization.as_ref().unwrap();
        assert_eq!(gen.collapse.as_deref(), Some("square"));
        assert!(gen.representation.is_none());
    }

    #[test]
    fn representation_validation_rejects_bad_bands() {
        let mk = |mode: Mode, levels: LevelPlan, bands: Vec<RepresentationBand>| ConvertOptions {
            mode,
            levels,
            representation: bands,
            ..Default::default()
        };
        let zr = |lo: u8, hi: u8| LevelPlan::ZoomRange {
            min_zoom: lo,
            max_zoom: hi,
        };

        // Partitioning rejected.
        let err = validate_options(&mk(
            Mode::Partitioning,
            zr(0, 6),
            vec![band(0, 3, Representation::Point)],
        ))
        .unwrap_err();
        assert!(matches!(err, ConvertError::InvalidConfig(_)), "{err}");

        // Explicit-GSD plan rejected.
        let err = validate_options(&mk(
            Mode::Duplicating,
            LevelPlan::Gsds(vec![1000.0, 100.0]),
            vec![band(0, 3, Representation::Point)],
        ))
        .unwrap_err();
        assert!(matches!(err, ConvertError::InvalidConfig(_)), "{err}");

        // Band covering the canonical zoom rejected.
        let err = validate_options(&mk(
            Mode::Duplicating,
            zr(0, 6),
            vec![band(0, 6, Representation::Point)],
        ))
        .unwrap_err();
        assert!(matches!(err, ConvertError::InvalidConfig(_)), "{err}");

        // Overlapping bands rejected.
        let err = validate_options(&mk(
            Mode::Duplicating,
            zr(0, 8),
            vec![
                band(0, 3, Representation::Point),
                band(3, 5, Representation::Square),
            ],
        ))
        .unwrap_err();
        assert!(matches!(err, ConvertError::InvalidConfig(_)), "{err}");

        // Non-prefix point band rejected (coarser geom levels would still
        // receive the cascaded point).
        let err = validate_options(&mk(
            Mode::Duplicating,
            zr(0, 8),
            vec![band(3, 5, Representation::Point)],
        ))
        .unwrap_err();
        assert!(matches!(err, ConvertError::InvalidConfig(_)), "{err}");

        // Mid-plan square band is fine (disposition only, type-preserving).
        validate_options(&mk(
            Mode::Duplicating,
            zr(0, 8),
            vec![band(3, 5, Representation::Square)],
        ))
        .expect("mid-plan square band is valid");

        // Point prefix + square continuation is fine.
        validate_options(&mk(
            Mode::Duplicating,
            zr(0, 8),
            vec![
                band(0, 3, Representation::Point),
                band(4, 6, Representation::Square),
            ],
        ))
        .expect("point prefix + square band is valid");
    }

    #[test]
    fn parse_representation_spec_grammar() {
        let bands = parse_representation_spec("0-7:point,8-14:geom").unwrap();
        assert_eq!(bands.len(), 2);
        assert_eq!(bands[0], band(0, 7, Representation::Point));
        assert_eq!(bands[1], band(8, 14, Representation::Geometry));

        let bands = parse_representation_spec(" 0-5 : square ").unwrap();
        assert_eq!(bands, vec![band(0, 5, Representation::Square)]);

        // Single-zoom entry and the "geometry" alias.
        let bands = parse_representation_spec("3:geometry").unwrap();
        assert_eq!(bands, vec![band(3, 3, Representation::Geometry)]);

        assert!(parse_representation_spec("").is_err());
        assert!(parse_representation_spec("0-7").is_err());
        assert!(parse_representation_spec("0-7:blob").is_err());
        assert!(parse_representation_spec("x-7:point").is_err());
    }

    #[test]
    fn partitioning_total_equals_input() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            mode: Mode::Partitioning,
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();

        let vr = validate_file(tout.path()).unwrap();
        assert!(
            vr.is_valid(),
            "failures: {:?}",
            vr.failures().collect::<Vec<_>>()
        );

        let reader = OverviewReader::open(tout.path()).unwrap();
        assert_eq!(reader.mode(), Mode::Partitioning);

        // Total rows across all levels == input (each feature exactly once).
        assert_eq!(report.total_rows, geoms.len());

        // Union of all levels reproduces the input id set.
        let mut all_ids = Vec::new();
        for level in 0..reader.num_levels() {
            for (id, _, _, _) in read_level_rows(&reader, level) {
                all_ids.push(id);
            }
        }
        all_ids.sort();
        assert_eq!(all_ids, (0..geoms.len() as i64).collect::<Vec<_>>());

        // Partitioning: geometry verbatim at every level.
        for level in 0..reader.num_levels() {
            for (id, _, _, geom) in read_level_rows(&reader, level) {
                assert_eq!(geom, geoms[id as usize], "partitioning geometry verbatim");
            }
        }
    }

    #[test]
    fn explicit_gsd_list_works() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::Gsds(vec![gsd(3), gsd(6), gsd(9)]),
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        assert!(validate_file(tout.path()).unwrap().is_valid());
        // gsds recorded strictly decreasing.
        for w in report.levels.windows(2) {
            assert!(w[0].gsd > w[1].gsd);
        }
        assert_eq!(report.levels.last().unwrap().feature_count, geoms.len());
    }

    #[test]
    fn default_gsd_base_footer_gsds_match_const() {
        // Regression: a default-flag (gsd_base == GSD_TILE_BASE) conversion must
        // produce footer GSDs byte-identical to the constant-base `gsd(z)` —
        // i.e. this knob is inert at its default, so default output is unchanged.
        use crate::overview::level::gsd;
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            ..Default::default()
        };
        assert_eq!(
            opts.gsd_base, GSD_TILE_BASE,
            "default must be the const base"
        );
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();

        let reader = OverviewReader::open(tout.path()).unwrap();
        // Footer GSDs equal the const-base gsd(z) for each level's zoom, exactly.
        for level in &reader.meta().levels {
            let z = level.zoom.expect("zoom-range plan records zooms");
            assert_eq!(level.gsd, gsd(z), "footer gsd must match const gsd(z={z})");
        }
        // Default base is NOT echoed into provenance (implied by the GSDs).
        assert_eq!(
            reader.meta().generalization.as_ref().unwrap().gsd_base,
            None,
            "default gsd_base must be absent from provenance"
        );
    }

    #[test]
    fn nondefault_gsd_base_scales_footer_gsds() {
        // Footer GSDs scale with `--gsd-base`: doubling the base halves every
        // level GSD, and the non-default base is recorded in provenance.
        use crate::overview::level::{gsd_with_base, GSD_TILE_BASE};
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let base = GSD_TILE_BASE * 2.0;
        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            gsd_base: base,
            ..Default::default()
        };
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();

        let reader = OverviewReader::open(tout.path()).unwrap();
        assert!(validate_file(tout.path()).unwrap().is_valid());
        for level in &reader.meta().levels {
            let z = level.zoom.unwrap();
            assert_eq!(
                level.gsd,
                gsd_with_base(z, base),
                "scaled footer gsd (z={z})"
            );
        }
        // Non-default base recorded in provenance.
        assert_eq!(
            reader.meta().generalization.as_ref().unwrap().gsd_base,
            Some(base),
            "non-default gsd_base must be recorded"
        );
    }

    #[test]
    fn rejects_unsupported_crs() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();

        // EPSG:32633 (UTM 33N) PROJJSON: neither 4326 nor 3857.
        // Note: no "WGS 84" in the name — `is_wgs84_projjson` name-matches that.
        let projjson = serde_json::json!({
            "type": "ProjectedCRS",
            "name": "UTM zone 33N",
            "id": { "authority": "EPSG", "code": 32633 }
        });
        let md = geoarrow::datatypes::Metadata::new(
            geoarrow::datatypes::Crs::from_projjson(projjson),
            None,
        );
        write_input(tin.path(), &geoms, false, Some(md));

        let opts = ConvertOptions::default();
        let err = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap_err();
        assert!(
            matches!(err, ConvertError::UnsupportedCrs { .. }),
            "expected UnsupportedCrs, got {err:?}"
        );
    }

    #[test]
    fn renames_existing_level_column() {
        // #288: an input `level` property must be auto-renamed (not rejected)
        // so flagship data (Overture buildings' floor-number `level`) converts.
        // The reserved `level` output column stays authoritative; the source
        // column becomes `level_`.
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, true, None);

        let opts = ConvertOptions::default();
        convert_to_overviews(tin.path(), tout.path(), &opts)
            .expect("colliding `level` column must be auto-renamed, not rejected");

        // Output validates and carries exactly one authoritative `level` column
        // plus the renamed source column `level_`.
        let report = crate::overview::check::validate_file(tout.path()).unwrap();
        assert!(
            report.is_valid(),
            "failures: {:?}",
            report.failures().collect::<Vec<_>>()
        );
        let names = output_column_names(tout.path());
        assert_eq!(
            names
                .iter()
                .filter(|n| n.eq_ignore_ascii_case("level"))
                .count(),
            1,
            "exactly one authoritative `level` column, names={names:?}"
        );
        assert!(
            names.iter().any(|n| n == "level_"),
            "renamed source column `level_` present, names={names:?}"
        );
    }

    #[test]
    fn resolver_renames_and_loops_suffix() {
        // `level` collides; `level_` already exists → the suffix loop keeps
        // appending until free (`level__`). Order and other columns are kept.
        let schema = Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int64, false),
            Field::new("level", DataType::Int32, false),
            Field::new("level_", DataType::Int32, false),
            Field::new("geometry", DataType::Binary, false),
        ]));
        let mut opts = ConvertOptions::default();
        let (out, renames) = resolve_reserved_column_collisions(&schema, &mut opts);
        assert_eq!(renames, vec![("level".to_string(), "level__".to_string())]);
        let names: Vec<_> = out.fields().iter().map(|f| f.name().clone()).collect();
        assert_eq!(names, vec!["id", "level__", "level_", "geometry"]);
    }

    #[test]
    fn resolver_rewrites_option_column_references() {
        // A `--sort-key` that named the (case-insensitive) reserved column must
        // follow the rename, or ranking would fail with SortKeyColumnMissing.
        let schema = Arc::new(Schema::new(vec![
            Field::new("level", DataType::Int32, false),
            Field::new("geometry", DataType::Binary, false),
        ]));
        let mut opts = ConvertOptions {
            sort_key: Some("LEVEL".to_string()),
            ..Default::default()
        };
        let (_out, renames) = resolve_reserved_column_collisions(&schema, &mut opts);
        assert_eq!(renames.len(), 1);
        assert_eq!(opts.sort_key.as_deref(), Some("level_"));
    }

    /// #364 + #288: the motivating ladder column is named `level`, which is
    /// also the reserved overview column — so a `--magnitude-ladder level`
    /// must follow the rename, or the conversion fails with "column not found"
    /// on the very case the feature exists for.
    #[test]
    fn resolver_rewrites_the_entry_zoom_column() {
        use super::super::ladder::{EntryZoomKind, EntryZoomSpec};

        let schema = Arc::new(Schema::new(vec![
            Field::new("level", DataType::Float64, false),
            Field::new("geometry", DataType::Binary, false),
        ]));
        let mut opts = ConvertOptions {
            entry_zoom: Some(EntryZoomSpec {
                column: "level".to_string(),
                kind: EntryZoomKind::DenseRank { step: 1 },
            }),
            ..Default::default()
        };
        let (_out, renames) = resolve_reserved_column_collisions(&schema, &mut opts);
        assert_eq!(renames.len(), 1);
        assert_eq!(
            opts.entry_zoom.as_ref().unwrap().column,
            "level_",
            "the ladder column must follow the reserved-column rename"
        );
    }

    #[test]
    fn resolver_noop_when_no_collision() {
        // No reserved-name collision → same `Arc` returned (cheap no-op) and no
        // renames.
        let schema = Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int64, false),
            Field::new("geometry", DataType::Binary, false),
        ]));
        let mut opts = ConvertOptions::default();
        let (out, renames) = resolve_reserved_column_collisions(&schema, &mut opts);
        assert!(renames.is_empty());
        assert!(Arc::ptr_eq(&out, &schema));
    }

    #[test]
    fn resolver_reserves_count_columns_only_when_enabled() {
        // `point_count` is a normal passthrough property unless clustering is
        // on; likewise `coalesced_count` needs coalescing.
        let schema = Arc::new(Schema::new(vec![
            Field::new("point_count", DataType::Int64, false),
            Field::new("geometry", DataType::Binary, false),
        ]));
        // Clustering off, coalescing off → no collision.
        let mut off = ConvertOptions {
            cluster: false,
            coalesce_lines: false,
            ..Default::default()
        };
        let (_out, renames) = resolve_reserved_column_collisions(&schema, &mut off);
        assert!(
            renames.is_empty(),
            "point_count is a passthrough without --cluster"
        );
        // Clustering on → reserved, so renamed.
        let mut on = ConvertOptions {
            cluster: true,
            ..Default::default()
        };
        let (_out, renames) = resolve_reserved_column_collisions(&schema, &mut on);
        assert_eq!(
            renames,
            vec![("point_count".to_string(), "point_count_".to_string())]
        );
    }

    /// Write a GeoParquet file with `id` (Int64) + `road_class` (Utf8) +
    /// geometry, for the class-ranking tests. Uses the default (WGS84) CRS.
    fn write_class_input(path: &Path, geoms: &[Geometry<f64>], classes: &[Option<&str>]) {
        let n = geoms.len();
        assert_eq!(n, classes.len());
        let id = Int64Array::from((0..n as i64).collect::<Vec<_>>());
        let class = StringArray::from(classes.to_vec());
        let geom_arr = build_geometry_array(geoms);
        let geom_field = geom_arr.data_type().to_field("geometry", true);

        let fields = vec![
            Arc::new(Field::new("id", DataType::Int64, false)),
            Arc::new(Field::new("road_class", DataType::Utf8, true)),
            Arc::new(geom_field),
        ];
        let columns: Vec<Arc<dyn Array>> =
            vec![Arc::new(id), Arc::new(class), geom_arr.to_array_ref()];
        let schema = Arc::new(Schema::new(fields));
        let batch = RecordBatch::try_new(schema.clone(), columns).unwrap();

        let gpq_options = GeoParquetWriterOptionsBuilder::default()
            .set_encoding(GeoParquetWriterEncoding::WKB)
            .set_generate_covering(true)
            .build();
        let encoder = GeoParquetRecordBatchEncoder::try_new(&schema, &gpq_options).unwrap();
        let target_schema = encoder.target_schema();
        let file = std::fs::File::create(path).unwrap();
        let mut writer = ArrowWriter::try_new(file, target_schema, None).unwrap();
        let mut encoder = encoder;
        let encoded = encoder.encode_record_batch(&batch).unwrap();
        writer.write(&encoded).unwrap();
        writer.append_key_value_metadata(encoder.into_keyvalue().unwrap());
        writer.close().unwrap();
    }

    /// Coarsest (min) level each `id` appears at, scanned across all levels.
    fn min_level_by_id(reader: &OverviewReader) -> std::collections::HashMap<i64, usize> {
        use arrow_array::cast::AsArray;
        use arrow_array::types::Int64Type;
        let mut out: std::collections::HashMap<i64, usize> = std::collections::HashMap::new();
        for level in 0..reader.num_levels() {
            let rdr = reader.read_level(level, None).unwrap();
            for batch in rdr {
                let batch = batch.unwrap();
                let ids = batch
                    .column(batch.schema().index_of("id").unwrap())
                    .as_primitive::<Int64Type>()
                    .clone();
                for i in 0..batch.num_rows() {
                    let id = ids.value(i);
                    out.entry(id)
                        .and_modify(|l| *l = (*l).min(level))
                        .or_insert(level);
                }
            }
        }
        out
    }

    // --- Q1 class-ranking unit tests ----------------------------------------

    #[test]
    fn class_rank_maps_named_unknown_null() {
        // named → its rank; present-but-unlisted → unknown_rank; null → None.
        let col = StringArray::from(vec![
            Some("motorway"),
            Some("driveway"), // unlisted → unknown_rank
            None,             // null → None
        ]);
        let ranking = ClassRanking {
            column: "road_class".to_string(),
            ranks: vec![("motorway".to_string(), 5.0)],
            unknown_rank: 0.0,
        };
        let keys = extract_class_ranks(&col, &ranking).unwrap();
        assert_eq!(keys, vec![Some(5.0), Some(0.0), None]);
    }

    #[test]
    fn class_rank_rejects_non_string_column() {
        let col = Float64Array::from(vec![1.0, 2.0]);
        let ranking = ClassRanking {
            column: "road_class".to_string(),
            ranks: vec![("x".to_string(), 1.0)],
            unknown_rank: 0.0,
        };
        let err = extract_class_ranks(&col, &ranking).unwrap_err();
        assert!(matches!(err, ConvertError::ClassRankColumnNotString { .. }));
    }

    #[test]
    fn overture_road_ranking_spine_is_ordered() {
        let cr = overture_road_ranking("road_class".to_string());
        let rank = |v: &str| -> f64 {
            cr.ranks
                .iter()
                .find(|(k, _)| k == v)
                .map(|(_, r)| *r)
                .unwrap()
        };
        // Spine strictly descending.
        let spine = [
            "motorway",
            "trunk",
            "primary",
            "secondary",
            "tertiary",
            "residential",
            "unclassified",
            "service",
        ];
        for w in spine.windows(2) {
            assert!(rank(w[0]) > rank(w[1]), "{} !> {}", w[0], w[1]);
        }
        // Tail classes all rank below service, above unknown_rank.
        for tail in ["living_street", "footway", "path", "cycleway", "track"] {
            assert!(rank(tail) < rank("service"), "{tail} !< service");
            assert!(rank(tail) > cr.unknown_rank, "{tail} !> unknown");
        }
        // Rail / literal-unknown are not named → fall to unknown_rank.
        assert!(cr.ranks.iter().all(|(k, _)| k != "standard_gauge"));
    }

    // --- Q1 mutual-exclusion + auto-detection tests -------------------------

    #[test]
    fn sort_key_and_class_ranking_conflict() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            sort_key: Some("rank".to_string()),
            class_ranking: Some(ClassRanking {
                column: "road_class".to_string(),
                ranks: vec![("motorway".to_string(), 1.0)],
                unknown_rank: 0.0,
            }),
            ..Default::default()
        };
        let err = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap_err();
        assert!(matches!(err, ConvertError::RankingConflict));
    }

    /// Lines with 5+ distinct Overture road classes, spread apart so each wins
    /// its own coarse cell — used to exercise auto-detection provenance.
    fn overture_line_geoms() -> (Vec<Geometry<f64>>, Vec<Option<&'static str>>) {
        let classes = [
            "motorway",
            "trunk",
            "primary",
            "residential",
            "footway",
            "service",
        ];
        let mut geoms = Vec::new();
        let mut cls = Vec::new();
        for (i, c) in classes.iter().enumerate() {
            let base = i as f64 * 2.0; // far apart → distinct cells
            let ls = LineString::from(vec![(base, 0.0), (base + 0.5, 0.3)]);
            geoms.push(Geometry::LineString(ls));
            cls.push(Some(*c));
        }
        (geoms, cls)
    }

    fn ranking_mode_of(path: &Path) -> String {
        let reader = OverviewReader::open(path).unwrap();
        reader
            .meta()
            .generalization
            .as_ref()
            .unwrap()
            .ranking
            .as_ref()
            .unwrap()
            .mode
            .clone()
    }

    #[test]
    fn auto_detect_overture_roads_triggers() {
        let (geoms, classes) = overture_line_geoms();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_class_input(tin.path(), &geoms, &classes);

        let opts = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 4,
                max_zoom: 10,
            },
            ..Default::default()
        };
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        assert_eq!(ranking_mode_of(tout.path()), "auto-overture-roads");
    }

    #[test]
    fn auto_detect_disabled_falls_back_to_size() {
        let (geoms, classes) = overture_line_geoms();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_class_input(tin.path(), &geoms, &classes);

        let opts = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 4,
                max_zoom: 10,
            },
            no_auto_rank: true,
            ..Default::default()
        };
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        assert_eq!(ranking_mode_of(tout.path()), "size-fallback");
    }

    #[test]
    fn auto_detect_non_trigger_without_class_column() {
        // synthetic_geometries has no road_class column → size fallback.
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions::default();
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        assert_eq!(ranking_mode_of(tout.path()), "size-fallback");
    }

    #[test]
    fn class_rank_provenance_recorded() {
        let (geoms, classes) = overture_line_geoms();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_class_input(tin.path(), &geoms, &classes);

        let opts = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 4,
                max_zoom: 10,
            },
            class_ranking: Some(ClassRanking {
                column: "road_class".to_string(),
                ranks: vec![("motorway".to_string(), 5.0), ("footway".to_string(), 1.0)],
                unknown_rank: 0.0,
            }),
            ..Default::default()
        };
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        let reader = OverviewReader::open(tout.path()).unwrap();
        let r = reader
            .meta()
            .generalization
            .as_ref()
            .unwrap()
            .ranking
            .clone()
            .unwrap();
        assert_eq!(r.mode, "class-ranking");
        assert_eq!(r.column.as_deref(), Some("road_class"));
        let ranks = r.ranks.unwrap();
        assert_eq!(ranks.len(), 2);
        assert_eq!(ranks.get("motorway"), Some(&5.0));
        assert_eq!(ranks.get("footway"), Some(&1.0));
        assert_eq!(r.unknown_rank, Some(0.0));

        // §3.5 (v0.2.0): the footer JSON carries ranks as an object map, not
        // an array of pairs.
        let json = overviews_footer_json(tout.path());
        assert!(
            json.contains(r#""ranks":{"footway":1.0,"motorway":5.0}"#),
            "footer must serialize ranks as an object map, got {json}"
        );
    }

    // --- Q1 regression: high class beats larger low class in a shared cell ---

    #[test]
    fn high_class_small_feature_wins_coarse_cell() {
        // Two lines sharing one coarse cell. The high-class line is SMALLER
        // (shorter bbox diagonal) than the low-class line. Under size-only
        // ranking the big low-class line would win the coarse level; with class
        // ranking the small high-class line must win it (coarser min_level).
        // Both clear the level-0 line visibility gate.
        //
        // 4326 units. gsd(4) ≈ 2445.98 m ⇒ 0.02197°; line gate = 2·gsd ⇒
        // 0.04394°; cell size = 2·gsd ⇒ 0.04394°. Both bboxes centered at
        // (0.02, 0.01) ⇒ same cell (0,0).
        let big_low = Geometry::LineString(LineString::from(vec![
            (-0.03, -0.04),
            (0.07, 0.06), // diag ≈ 0.1414° (well over gate), larger
        ]));
        let small_high = Geometry::LineString(LineString::from(vec![
            (0.0, 0.0),
            (0.04, 0.02), // diag ≈ 0.0447° (just over gate), smaller
        ]));
        let geoms = vec![big_low, small_high];
        let classes = vec![Some("footway"), Some("motorway")];

        let tin = tempfile::NamedTempFile::new().unwrap();

        // Baseline: size-fallback → the BIG low-class line (id 0) wins coarse.
        {
            let tout = tempfile::NamedTempFile::new().unwrap();
            write_class_input(tin.path(), &geoms, &classes);
            let opts = ConvertOptions {
                levels: LevelPlan::ZoomRange {
                    min_zoom: 4,
                    max_zoom: 10,
                },
                no_auto_rank: true, // force size fallback
                ..Default::default()
            };
            convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
            let reader = OverviewReader::open(tout.path()).unwrap();
            let ml = min_level_by_id(&reader);
            assert!(
                ml[&0] < ml[&1],
                "size fallback: big low-class (id0) should win coarse, got {ml:?}"
            );
        }

        // Class ranking: the SMALL high-class line (id 1) wins the coarse cell.
        {
            let tout = tempfile::NamedTempFile::new().unwrap();
            write_class_input(tin.path(), &geoms, &classes);
            let opts = ConvertOptions {
                levels: LevelPlan::ZoomRange {
                    min_zoom: 4,
                    max_zoom: 10,
                },
                class_ranking: Some(ClassRanking {
                    column: "road_class".to_string(),
                    ranks: vec![("motorway".to_string(), 5.0), ("footway".to_string(), 1.0)],
                    unknown_rank: 0.0,
                }),
                ..Default::default()
            };
            convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
            let reader = OverviewReader::open(tout.path()).unwrap();
            let ml = min_level_by_id(&reader);
            assert!(
                ml[&1] < ml[&0],
                "class ranking: small high-class (id1) must win coarse, got {ml:?}"
            );
            assert_eq!(ml[&1], 0, "high-class line should reach the coarsest level");
        }
    }

    // --- Q2 density budget --------------------------------------------------

    fn density_provenance_of(path: &Path) -> Option<crate::overview::level::DensityProvenance> {
        let reader = OverviewReader::open(path).unwrap();
        reader
            .meta()
            .generalization
            .as_ref()
            .unwrap()
            .density_drop
            .clone()
    }

    /// Many points on a grid, spread so cell-winner keeps them all at fine
    /// levels — enough features that the density budget binds at a mid level.
    fn grid_points(n: usize) -> Vec<Geometry<f64>> {
        (0..n)
            .map(|i| {
                let x = (i % 40) as f64 * 0.3 - 6.0;
                let y = (i / 40) as f64 * 0.3 - 6.0;
                Geometry::Point(Point::new(x, y))
            })
            .collect()
    }

    #[test]
    fn density_provenance_recorded_by_default() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            ..Default::default()
        };
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        let d = density_provenance_of(tout.path()).expect("default run records density_drop");
        assert_eq!(d.drop_rate, DensityBudgetConfig::default().drop_rate);
        assert_eq!(d.gamma, DensityBudgetConfig::default().gamma);
        assert_eq!(d.supercell_gsd_factor, SUPERCELL_GSD_FACTOR);
    }

    #[test]
    fn density_disabled_omits_provenance_and_keeps_canonical() {
        let geoms = grid_points(600);
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 0,
                max_zoom: 8,
            },
            density: DensityBudgetConfig {
                enabled: false,
                ..DensityBudgetConfig::default()
            },
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        // Off switch: no density_drop provenance (footer matches pre-Q2).
        assert!(
            density_provenance_of(tout.path()).is_none(),
            "disabled budget must not emit provenance"
        );
        assert!(validate_file(tout.path()).unwrap().is_valid());
        assert_eq!(report.levels.last().unwrap().feature_count, geoms.len());
    }

    #[test]
    fn density_thins_midlevels_keeps_canonical() {
        let geoms = grid_points(600);
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout_on = tempfile::NamedTempFile::new().unwrap();
        let tout_off = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let base = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 0,
                max_zoom: 8,
            },
            ..Default::default()
        };
        let on = convert_to_overviews(tin.path(), tout_on.path(), &base).unwrap();
        let off = convert_to_overviews(
            tin.path(),
            tout_off.path(),
            &ConvertOptions {
                density: DensityBudgetConfig {
                    enabled: false,
                    ..DensityBudgetConfig::default()
                },
                ..base.clone()
            },
        )
        .unwrap();

        // Canonical fidelity: both keep every feature at the finest level.
        assert_eq!(on.levels.last().unwrap().feature_count, geoms.len());
        assert_eq!(off.levels.last().unwrap().feature_count, geoms.len());
        assert!(validate_file(tout_on.path()).unwrap().is_valid());

        // The budget removes mid-level features that cell-winner alone retained:
        // the on-budget run writes strictly fewer total rows than the off run.
        assert!(
            on.total_rows < off.total_rows,
            "density budget should thin mid levels: on={} off={}",
            on.total_rows,
            off.total_rows
        );
        // Counts remain monotone non-decreasing coarse→fine under the budget.
        for w in on.levels.windows(2) {
            assert!(w[0].feature_count <= w[1].feature_count);
        }
    }

    // --- H3 streaming / in-memory equivalence -------------------------------

    /// Raw `geo:overviews` footer JSON of an overview file.
    fn overviews_footer_json(path: &Path) -> String {
        let file = std::fs::File::open(path).unwrap();
        let b = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
        b.metadata()
            .file_metadata()
            .key_value_metadata()
            .unwrap()
            .iter()
            .find(|kv| kv.key == crate::overview::level::OVERVIEWS_KEY)
            .expect("geo:overviews key")
            .value
            .clone()
            .unwrap()
    }

    /// Convert the same input through the in-memory and streaming paths and
    /// assert equivalent outputs: per-level feature/vertex counts, footer
    /// metadata (byte-identical JSON), and row values in order at every level.
    /// Assumes a `write_input`-shaped file (id/name/rank/geometry columns).
    fn assert_streaming_equivalent(input: &Path, base: &ConvertOptions) {
        let mem_out = tempfile::NamedTempFile::new().unwrap();
        let stream_out = tempfile::NamedTempFile::new().unwrap();

        let mem_opts = ConvertOptions {
            streaming: false,
            ..base.clone()
        };
        let stream_opts = ConvertOptions {
            streaming: true,
            ..base.clone()
        };
        let mem = convert_to_overviews(input, mem_out.path(), &mem_opts).unwrap();
        let strm = convert_to_overviews(input, stream_out.path(), &stream_opts).unwrap();

        // Reports agree on everything but duration.
        assert_eq!(mem.mode, strm.mode);
        assert_eq!(mem.input_features, strm.input_features);
        assert_eq!(mem.total_rows, strm.total_rows);
        assert_eq!(mem.total_vertices, strm.total_vertices);
        assert_eq!(mem.levels.len(), strm.levels.len());
        for (a, b) in mem.levels.iter().zip(&strm.levels) {
            assert_eq!(a.level, b.level);
            assert_eq!(a.gsd, b.gsd, "level {} gsd", a.level);
            assert_eq!(a.zoom, b.zoom, "level {} zoom", a.level);
            assert_eq!(
                a.feature_count, b.feature_count,
                "level {} feature count",
                a.level
            );
            assert_eq!(
                a.vertex_count, b.vertex_count,
                "level {} vertex count",
                a.level
            );
        }

        // Footer metadata byte-identical; both files validate.
        assert_eq!(
            overviews_footer_json(mem_out.path()),
            overviews_footer_json(stream_out.path()),
            "geo:overviews footers differ"
        );
        assert!(validate_file(mem_out.path()).unwrap().is_valid());
        assert!(validate_file(stream_out.path()).unwrap().is_valid());

        // Row-level equality per level (ids, attributes, geometry, order).
        let mr = OverviewReader::open(mem_out.path()).unwrap();
        let sr = OverviewReader::open(stream_out.path()).unwrap();
        assert_eq!(mr.num_levels(), sr.num_levels());
        for level in 0..mr.num_levels() {
            assert_eq!(
                read_level_rows(&mr, level),
                read_level_rows(&sr, level),
                "level {level} rows differ"
            );
        }
    }

    /// Assert two overview output files are structurally + logically identical:
    /// same row-group layout (the deterministic on-disk structure), same footer
    /// `geo:overviews` metadata, and same per-level row content (ids, attrs,
    /// geometry, order). This is the meaningful "byte-identical" invariant — the
    /// Parquet writer's footer metadata region is not byte-deterministic
    /// run-to-run (serial-vs-serial also differs by a few bytes there), so a raw
    /// `Vec<u8>` compare is not a valid equivalence check.
    fn assert_outputs_equivalent(a: &Path, b: &Path, ctx: &str) {
        use parquet::file::reader::{FileReader, SerializedFileReader};

        // Row-group layout (num groups, rows per group, column count).
        let layout = |p: &Path| -> Vec<(i64, usize)> {
            let r = SerializedFileReader::new(std::fs::File::open(p).unwrap()).unwrap();
            let md = r.metadata();
            (0..md.num_row_groups())
                .map(|i| (md.row_group(i).num_rows(), md.row_group(i).columns().len()))
                .collect()
        };
        assert_eq!(layout(a), layout(b), "{ctx}: row-group layout differs");

        // Footer geo:overviews metadata (semantic).
        assert_eq!(
            overviews_footer_json(a),
            overviews_footer_json(b),
            "{ctx}: geo:overviews footer differs"
        );

        // Per-level row content + order.
        let ra = OverviewReader::open(a).unwrap();
        let rb = OverviewReader::open(b).unwrap();
        assert_eq!(
            ra.num_levels(),
            rb.num_levels(),
            "{ctx}: level count differs"
        );
        for level in 0..ra.num_levels() {
            assert_eq!(
                read_level_rows(&ra, level),
                read_level_rows(&rb, level),
                "{ctx}: level {level} rows differ"
            );
        }
    }

    /// The single-read pipelined engine (#213/#212) must produce output
    /// identical to the serial per-level-re-read reference — across both modes,
    /// both sink backings (speed = RAM, bounded = Arrow IPC spill), and the
    /// clustering feature. The bounded case also proves the spill round-trip is
    /// lossless.
    #[test]
    fn pipelined_matches_serial() {
        use super::super::level::MemoryProfile;
        use super::super::stream::Pass2Strategy;

        // A polygon set (duplicating/clustering simplify paths) and a dense
        // point grid (partitioning fans many features across several levels, so
        // the engine buffers/spills multiple non-finest levels).
        let poly_in = tempfile::NamedTempFile::new().unwrap();
        write_input(poly_in.path(), &synthetic_geometries(), false, None);
        let grid_in = tempfile::NamedTempFile::new().unwrap();
        write_input(grid_in.path(), &grid_points(600), false, None);

        let cases: Vec<(&str, &Path, ConvertOptions)> = vec![
            (
                "duplicating",
                poly_in.path(),
                ConvertOptions {
                    mode: Mode::Duplicating,
                    levels: LevelPlan::ZoomRange {
                        min_zoom: 1,
                        max_zoom: 10,
                    },
                    ..Default::default()
                },
            ),
            (
                "partitioning",
                grid_in.path(),
                ConvertOptions {
                    mode: Mode::Partitioning,
                    levels: LevelPlan::ZoomRange {
                        min_zoom: 1,
                        max_zoom: 9,
                    },
                    ..Default::default()
                },
            ),
            (
                "clustering",
                grid_in.path(),
                ConvertOptions {
                    mode: Mode::Duplicating,
                    cluster: true,
                    levels: LevelPlan::ZoomRange {
                        min_zoom: 1,
                        max_zoom: 9,
                    },
                    ..Default::default()
                },
            ),
        ];

        for (name, input, base) in &cases {
            let serial_out = tempfile::NamedTempFile::new().unwrap();
            convert_to_overviews_strategy(input, serial_out.path(), base, Pass2Strategy::Serial)
                .unwrap();

            // Auto included (#294): its workload-based backing choice must not
            // change output — on this tiny input it resolves to RAM, matching
            // Speed; the pipeline unit tests cover the large-input Spill flip,
            // and the Bounded case proves the Spill round-trip is lossless.
            for profile in [
                MemoryProfile::Speed,
                MemoryProfile::Bounded,
                MemoryProfile::Auto,
            ] {
                let opts = ConvertOptions {
                    profile,
                    ..base.clone()
                };
                let piped_out = tempfile::NamedTempFile::new().unwrap();
                convert_to_overviews_strategy(
                    input,
                    piped_out.path(),
                    &opts,
                    Pass2Strategy::Pipelined,
                )
                .unwrap();
                assert_outputs_equivalent(
                    serial_out.path(),
                    piped_out.path(),
                    &format!("{name}/{profile:?}"),
                );
            }
        }
    }

    /// Pipelined output must be invariant to batching/overlap knobs
    /// (`read_batch_size`, `in_flight_batches`) — proving the ordered-sink /
    /// no-reorder-buffer invariant holds regardless of how the single read is
    /// chunked or how many batches overlap in flight.
    #[test]
    fn pipelined_invariant_to_batching_knobs() {
        use super::super::stream::Pass2Strategy;

        let geoms = grid_points(600);
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let base = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 1,
                max_zoom: 9,
            },
            ..Default::default()
        };

        let convert = |read_batch_size: usize, in_flight_batches: usize| {
            let opts = ConvertOptions {
                read_batch_size,
                in_flight_batches,
                ..base.clone()
            };
            let out = tempfile::NamedTempFile::new().unwrap();
            convert_to_overviews_strategy(tin.path(), out.path(), &opts, Pass2Strategy::Pipelined)
                .unwrap();
            out
        };

        let reference = convert(7, 1);
        // ifb = 0 is the IN_FLIGHT_BATCHES_AUTO sentinel: it must produce the
        // same output as any explicit depth (auto only changes overlap, not
        // level assignment or write order).
        for (rbs, ifb) in [(64usize, 4usize), (4096, 8), (8192, 0)] {
            let candidate = convert(rbs, ifb);
            assert_outputs_equivalent(
                reference.path(),
                candidate.path(),
                &format!("read_batch_size={rbs} in_flight_batches={ifb}"),
            );
        }
    }

    #[test]
    fn resolve_in_flight_batches_auto_and_explicit() {
        // Auto (0) sizes from available parallelism, clamped to [MIN, MAX].
        let auto = resolve_in_flight_batches(IN_FLIGHT_BATCHES_AUTO);
        assert!(
            (IN_FLIGHT_BATCHES_MIN..=IN_FLIGHT_BATCHES_MAX).contains(&auto),
            "auto in-flight {auto} outside [{IN_FLIGHT_BATCHES_MIN}, {IN_FLIGHT_BATCHES_MAX}]"
        );
        let cores = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(IN_FLIGHT_BATCHES_MIN);
        assert_eq!(
            auto,
            cores.clamp(IN_FLIGHT_BATCHES_MIN, IN_FLIGHT_BATCHES_MAX),
            "auto must equal core count clamped to the configured range"
        );
        // Explicit values pass through verbatim, including above the auto cap.
        assert_eq!(resolve_in_flight_batches(1), 1);
        assert_eq!(resolve_in_flight_batches(7), 7);
        assert_eq!(
            resolve_in_flight_batches(IN_FLIGHT_BATCHES_MAX + 100),
            IN_FLIGHT_BATCHES_MAX + 100
        );
    }

    #[test]
    fn streaming_matches_in_memory_duplicating() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let base = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 1,
                max_zoom: 10,
            },
            ..Default::default()
        };
        assert_streaming_equivalent(tin.path(), &base);
    }

    #[test]
    fn streaming_matches_in_memory_partitioning() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let base = ConvertOptions {
            mode: Mode::Partitioning,
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            ..Default::default()
        };
        assert_streaming_equivalent(tin.path(), &base);
    }

    #[test]
    fn streaming_matches_with_small_read_batches_and_density_budget() {
        // Many features + a tiny read batch: exercises batch-boundary handling
        // in both passes AND the Q2 density-budget cuts in the winner tables.
        let geoms = grid_points(600);
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let base = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 0,
                max_zoom: 8,
            },
            read_batch_size: 7,
            ..Default::default()
        };
        assert_streaming_equivalent(tin.path(), &base);
    }

    #[test]
    fn streaming_matches_with_explicit_sort_key() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let base = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 2,
                max_zoom: 8,
            },
            sort_key: Some("rank".to_string()),
            ..Default::default()
        };
        assert_streaming_equivalent(tin.path(), &base);
    }

    #[test]
    fn streaming_auto_rank_matches_in_memory() {
        // Auto-detected Overture road-class ranking must resolve identically in
        // the streaming pass-1 (incremental vocab scan) and in-memory paths.
        let (geoms, classes) = overture_line_geoms();
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_class_input(tin.path(), &geoms, &classes);

        let base = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 4,
                max_zoom: 10,
            },
            read_batch_size: 2,
            ..Default::default()
        };
        let mem_out = tempfile::NamedTempFile::new().unwrap();
        let stream_out = tempfile::NamedTempFile::new().unwrap();
        convert_to_overviews(
            tin.path(),
            mem_out.path(),
            &ConvertOptions {
                streaming: false,
                ..base.clone()
            },
        )
        .unwrap();
        convert_to_overviews(tin.path(), stream_out.path(), &base).unwrap();

        assert_eq!(ranking_mode_of(mem_out.path()), "auto-overture-roads");
        assert_eq!(ranking_mode_of(stream_out.path()), "auto-overture-roads");
        assert_eq!(
            overviews_footer_json(mem_out.path()),
            overviews_footer_json(stream_out.path())
        );
        let mr = OverviewReader::open(mem_out.path()).unwrap();
        let sr = OverviewReader::open(stream_out.path()).unwrap();
        assert_eq!(min_level_by_id(&mr), min_level_by_id(&sr));
    }

    // --- Q4 point clustering -------------------------------------------------

    /// Read the `point_count` column for one level, in row order.
    fn read_point_counts(reader: &OverviewReader, level: usize) -> Vec<i64> {
        use arrow_array::cast::AsArray;
        use arrow_array::types::Int64Type;
        let rdr = reader.read_level(level, None).unwrap();
        let mut out = Vec::new();
        for batch in rdr {
            let batch = batch.unwrap();
            let idx = batch.schema().index_of("point_count").unwrap();
            let col = batch.column(idx).as_primitive::<Int64Type>().clone();
            assert_eq!(col.null_count(), 0, "point_count must be NOT NULL");
            out.extend(col.values().iter().copied());
        }
        out
    }

    /// Read a Float64 column for one level, in row order (None = null).
    fn read_f64_column(reader: &OverviewReader, level: usize, name: &str) -> Vec<Option<f64>> {
        use arrow_array::cast::AsArray;
        use arrow_array::types::Float64Type;
        let rdr = reader.read_level(level, None).unwrap();
        let mut out = Vec::new();
        for batch in rdr {
            let batch = batch.unwrap();
            let idx = batch.schema().index_of(name).unwrap();
            let col = batch.column(idx).as_primitive::<Float64Type>().clone();
            for i in 0..col.len() {
                out.push(if col.is_null(i) {
                    None
                } else {
                    Some(col.value(i))
                });
            }
        }
        out
    }

    #[test]
    fn cluster_duplicating_end_to_end_counts_partition_every_level() {
        // 600 grid points, clustering on: every level's point_count sums to
        // the source count, canonical counts are all 1, file validates.
        let geoms = grid_points(600);
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 0,
                max_zoom: 8,
            },
            cluster: true,
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        let vr = validate_file(tout.path()).unwrap();
        assert!(
            vr.is_valid(),
            "failures: {:?}",
            vr.failures().collect::<Vec<_>>()
        );

        let reader = OverviewReader::open(tout.path()).unwrap();
        let canonical = reader.num_levels() - 1;
        for level in 0..reader.num_levels() {
            let counts = read_point_counts(&reader, level);
            assert!(counts.iter().all(|&c| c >= 1), "level {level} counts >= 1");
            assert_eq!(
                counts.iter().sum::<i64>(),
                geoms.len() as i64,
                "level {level}: sum(point_count) must equal source count"
            );
        }
        // Canonical: every cluster is a singleton.
        assert!(read_point_counts(&reader, canonical)
            .iter()
            .all(|&c| c == 1));
        // Density budget bites mid-levels: some coarse level must actually
        // cluster (a count > 1), or this test tests nothing.
        let coarse = read_point_counts(&reader, 0);
        assert!(coarse.iter().any(|&c| c > 1), "no clustering happened");
        assert!(coarse.len() < geoms.len());
        assert_eq!(report.levels.last().unwrap().feature_count, geoms.len());
    }

    /// §12.1 sum-invariant property across knob combinations: clustering
    /// crossed with the density budget (on/off), point-thinning grid sizes,
    /// and both pipelines (streaming / in-memory) — every produced file must
    /// partition the source point set at every level, pass the
    /// `cluster_sum_invariant` validator rule, and keep a singleton-only
    /// canonical band. Coalescing stays at its default (on): it only touches
    /// lines and must not interact with point accounting.
    #[test]
    fn cluster_sum_invariant_across_knob_combinations() {
        let geoms = grid_points(300);
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        for streaming in [true, false] {
            for density in [true, false] {
                for thinning in [2.0, 8.0] {
                    let tout = tempfile::NamedTempFile::new().unwrap();
                    let mut opts = ConvertOptions {
                        levels: LevelPlan::ZoomRange {
                            min_zoom: 0,
                            max_zoom: 6,
                        },
                        cluster: true,
                        streaming,
                        ..Default::default()
                    };
                    opts.density.enabled = density;
                    opts.assign.point_thinning = thinning;
                    let label =
                        format!("streaming={streaming} density={density} thinning={thinning}");
                    convert_to_overviews(tin.path(), tout.path(), &opts)
                        .unwrap_or_else(|e| panic!("{label}: {e}"));

                    let vr = validate_file(tout.path()).unwrap();
                    assert!(
                        vr.is_valid(),
                        "{label}: failures: {:?}",
                        vr.failures().collect::<Vec<_>>()
                    );
                    assert_eq!(
                        vr.check_passed("cluster_sum_invariant"),
                        Some(true),
                        "{label}"
                    );

                    let reader = OverviewReader::open(tout.path()).unwrap();
                    let canonical = reader.num_levels() - 1;
                    for level in 0..reader.num_levels() {
                        let counts = read_point_counts(&reader, level);
                        assert!(
                            !counts.is_empty(),
                            "{label}: level {level} thinned points to zero"
                        );
                        assert_eq!(
                            counts.iter().sum::<i64>(),
                            geoms.len() as i64,
                            "{label}: level {level} must partition the source set"
                        );
                    }
                    assert!(
                        read_point_counts(&reader, canonical)
                            .iter()
                            .all(|&c| c == 1),
                        "{label}: canonical band must be singleton-only"
                    );
                }
            }
        }
    }

    #[test]
    fn cluster_accumulate_sum_and_mean_consistent() {
        // The `rank` column (Float64, values n..1) accumulated as sum: every
        // level's Σ rank over rows must equal the source Σ (clusters
        // partition the source set and sum is additive). Canonical stays
        // verbatim.
        let geoms = grid_points(400);
        let n = geoms.len();
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);
        let source_sum: f64 = (1..=n).map(|v| v as f64).sum();

        // sum
        let tout = tempfile::NamedTempFile::new().unwrap();
        let opts = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 0,
                max_zoom: 8,
            },
            cluster: true,
            accumulate: vec![AccumulateSpec {
                column: "rank".to_string(),
                op: super::super::cluster::AccumulateOp::Sum,
            }],
            ..Default::default()
        };
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        let reader = OverviewReader::open(tout.path()).unwrap();
        for level in 0..reader.num_levels() {
            let ranks = read_f64_column(&reader, level, "rank");
            let total: f64 = ranks.iter().flatten().sum();
            assert!(
                (total - source_sum).abs() < 1e-6,
                "level {level}: rank sum {total} != source {source_sum}"
            );
        }
        // Canonical: verbatim source values (id i has rank n - i).
        let canonical = reader.num_levels() - 1;
        let rows = read_level_rows(&reader, canonical);
        for (id, _, rank, _) in rows {
            assert_eq!(rank, (n as i64 - id) as f64, "canonical rank verbatim");
        }

        // mean: Σ (mean_i × point_count_i) must reproduce the source sum at
        // every level (mean computed from source values, not mean-of-means).
        let tout2 = tempfile::NamedTempFile::new().unwrap();
        let opts_mean = ConvertOptions {
            accumulate: vec![AccumulateSpec {
                column: "rank".to_string(),
                op: super::super::cluster::AccumulateOp::Mean,
            }],
            ..opts.clone()
        };
        convert_to_overviews(tin.path(), tout2.path(), &opts_mean).unwrap();
        let reader2 = OverviewReader::open(tout2.path()).unwrap();
        for level in 0..reader2.num_levels() {
            let means = read_f64_column(&reader2, level, "rank");
            let counts = read_point_counts(&reader2, level);
            let total: f64 = means
                .iter()
                .zip(&counts)
                .map(|(m, &c)| m.unwrap() * c as f64)
                .sum();
            assert!(
                (total - source_sum).abs() < 1e-6,
                "level {level}: Σ mean×count {total} != source {source_sum}"
            );
        }
    }

    #[test]
    fn cluster_footer_provenance_recorded() {
        let geoms = grid_points(100);
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            cluster: true,
            accumulate: vec![AccumulateSpec {
                column: "rank".to_string(),
                op: super::super::cluster::AccumulateOp::Mean,
            }],
            ..Default::default()
        };
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        let reader = OverviewReader::open(tout.path()).unwrap();
        let c = reader
            .meta()
            .generalization
            .as_ref()
            .unwrap()
            .clustering
            .clone()
            .expect("clustering provenance recorded");
        assert!(c.enabled);
        assert_eq!(c.point_count_column, "point_count");
        assert_eq!(c.accumulated.len(), 1);
        assert_eq!(c.accumulated[0].column, "rank");
        assert_eq!(c.accumulated[0].op, "mean");

        // Off by default: no clustering block, no point_count column.
        let tout_off = tempfile::NamedTempFile::new().unwrap();
        convert_to_overviews(tin.path(), tout_off.path(), &ConvertOptions::default()).unwrap();
        let r_off = OverviewReader::open(tout_off.path()).unwrap();
        assert!(r_off
            .meta()
            .generalization
            .as_ref()
            .unwrap()
            .clustering
            .is_none());
    }

    #[test]
    fn cluster_option_errors() {
        let geoms = grid_points(20);
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        // Partitioning + cluster is rejected.
        let err = convert_to_overviews(
            tin.path(),
            tout.path(),
            &ConvertOptions {
                mode: Mode::Partitioning,
                cluster: true,
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(matches!(err, ConvertError::ClusterPartitioningUnsupported));

        // Accumulate without cluster is rejected.
        let err = convert_to_overviews(
            tin.path(),
            tout.path(),
            &ConvertOptions {
                accumulate: vec![AccumulateSpec {
                    column: "rank".to_string(),
                    op: super::super::cluster::AccumulateOp::Sum,
                }],
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(matches!(err, ConvertError::AccumulateWithoutCluster));

        // Missing accumulate column is rejected (both pipelines).
        for streaming in [true, false] {
            let err = convert_to_overviews(
                tin.path(),
                tout.path(),
                &ConvertOptions {
                    cluster: true,
                    streaming,
                    accumulate: vec![AccumulateSpec {
                        column: "nonexistent".to_string(),
                        op: super::super::cluster::AccumulateOp::Sum,
                    }],
                    ..Default::default()
                },
            )
            .unwrap_err();
            assert!(
                matches!(err, ConvertError::AccumulateColumnMissing { .. }),
                "streaming={streaming}: got {err:?}"
            );
        }

        // Non-numeric accumulate column is rejected.
        let err = convert_to_overviews(
            tin.path(),
            tout.path(),
            &ConvertOptions {
                cluster: true,
                accumulate: vec![AccumulateSpec {
                    column: "name".to_string(),
                    op: super::super::cluster::AccumulateOp::Max,
                }],
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(matches!(
            err,
            ConvertError::AccumulateColumnNotNumeric { .. }
        ));
    }

    #[test]
    fn cluster_renames_existing_point_count_column() {
        // #288: an input already carrying a `point_count` column (case-
        // insensitively) is auto-renamed when clustering, and is an ordinary
        // passthrough property when clustering is off.
        let geoms = grid_points(10);
        let n = geoms.len();
        let tin = tempfile::NamedTempFile::new().unwrap();
        {
            let id = Int64Array::from((0..n as i64).collect::<Vec<_>>());
            let pc = Int64Array::from(vec![7i64; n]);
            let geom_arr = build_geometry_array(&geoms);
            let geom_field = geom_arr.data_type().to_field("geometry", true);
            let fields = vec![
                Arc::new(Field::new("id", DataType::Int64, false)),
                Arc::new(Field::new("Point_Count", DataType::Int64, false)),
                Arc::new(geom_field),
            ];
            let columns: Vec<Arc<dyn Array>> =
                vec![Arc::new(id), Arc::new(pc), geom_arr.to_array_ref()];
            let schema = Arc::new(Schema::new(fields));
            let batch = RecordBatch::try_new(schema.clone(), columns).unwrap();
            let gpq_options = GeoParquetWriterOptionsBuilder::default()
                .set_encoding(GeoParquetWriterEncoding::WKB)
                .set_generate_covering(true)
                .build();
            let mut encoder = GeoParquetRecordBatchEncoder::try_new(&schema, &gpq_options).unwrap();
            let target_schema = encoder.target_schema();
            let file = std::fs::File::create(tin.path()).unwrap();
            let mut writer = ArrowWriter::try_new(file, target_schema, None).unwrap();
            writer
                .write(&encoder.encode_record_batch(&batch).unwrap())
                .unwrap();
            writer.append_key_value_metadata(encoder.into_keyvalue().unwrap());
            writer.close().unwrap();
        }

        let tout = tempfile::NamedTempFile::new().unwrap();
        convert_to_overviews(
            tin.path(),
            tout.path(),
            &ConvertOptions {
                cluster: true,
                ..Default::default()
            },
        )
        .expect("colliding `Point_Count` column must be auto-renamed, not rejected");
        let names = output_column_names(tout.path());
        assert!(
            names.iter().any(|n| n == "Point_Count_"),
            "renamed source column present, names={names:?}"
        );
        assert_eq!(
            names
                .iter()
                .filter(|n| n.eq_ignore_ascii_case("point_count"))
                .count(),
            1,
            "one authoritative `point_count`, names={names:?}"
        );

        // Without clustering the column is an ordinary passthrough property
        // (kept verbatim, no reserved column added).
        convert_to_overviews(tin.path(), tout.path(), &ConvertOptions::default()).unwrap();
        let names = output_column_names(tout.path());
        assert!(
            names.iter().any(|n| n == "Point_Count"),
            "passthrough column kept verbatim, names={names:?}"
        );
    }

    #[test]
    fn streaming_matches_in_memory_clustering() {
        // Clustering + accumulation must be byte-equivalent between the
        // streaming and in-memory pipelines, including with tiny read batches
        // and the density budget's orphan-cell handling.
        let geoms = grid_points(600);
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let base = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 0,
                max_zoom: 8,
            },
            read_batch_size: 7,
            cluster: true,
            accumulate: vec![
                AccumulateSpec {
                    column: "rank".to_string(),
                    op: super::super::cluster::AccumulateOp::Sum,
                },
                AccumulateSpec {
                    column: "rank".to_string(),
                    op: super::super::cluster::AccumulateOp::Mean,
                },
            ],
            ..Default::default()
        };
        // NOTE: two specs on one column — the LAST rewrite wins per column;
        // exercised here purely for pipeline equivalence.
        assert_streaming_equivalent(tin.path(), &base);

        // Explicitly compare point_count per level too (read_level_rows in
        // the shared helper does not include it).
        let mem_out = tempfile::NamedTempFile::new().unwrap();
        let stream_out = tempfile::NamedTempFile::new().unwrap();
        convert_to_overviews(
            tin.path(),
            mem_out.path(),
            &ConvertOptions {
                streaming: false,
                ..base.clone()
            },
        )
        .unwrap();
        convert_to_overviews(tin.path(), stream_out.path(), &base).unwrap();
        let mr = OverviewReader::open(mem_out.path()).unwrap();
        let sr = OverviewReader::open(stream_out.path()).unwrap();
        for level in 0..mr.num_levels() {
            assert_eq!(
                read_point_counts(&mr, level),
                read_point_counts(&sr, level),
                "level {level} point_count differs"
            );
        }
    }

    // --- Q3 line coalescing ---------------------------------------------------

    /// Read the `coalesced_count` column for one level, in row order.
    fn read_coalesced_counts(reader: &OverviewReader, level: usize) -> Vec<i32> {
        use arrow_array::cast::AsArray;
        use arrow_array::types::Int32Type;
        let rdr = reader.read_level(level, None).unwrap();
        let mut out = Vec::new();
        for batch in rdr {
            let batch = batch.unwrap();
            let idx = batch.schema().index_of("coalesced_count").unwrap();
            let col = batch.column(idx).as_primitive::<Int32Type>().clone();
            assert_eq!(col.null_count(), 0, "coalesced_count must be NOT NULL");
            out.extend(col.values().iter().copied());
        }
        out
    }

    /// A chain of `n` touching collinear segments (each 0.01° long) starting
    /// at (0,0), plus one far-away point. Each segment alone is below the
    /// coarse-level line visibility gate; the chain is well above it.
    fn fragment_chain_geoms(n: usize) -> Vec<Geometry<f64>> {
        let mut geoms: Vec<Geometry<f64>> = (0..n)
            .map(|i| {
                let x0 = i as f64 * 0.01;
                Geometry::LineString(LineString::from(vec![(x0, 0.0), (x0 + 0.01, 0.0)]))
            })
            .collect();
        geoms.push(Geometry::Point(Point::new(5.0, 5.0)));
        geoms
    }

    #[test]
    fn coalesce_reclaims_sub_visibility_fragments_and_keeps_canonical() {
        // z4 gsd ≈ 2446 m ⇒ gate 2·gsd ≈ 0.0439°. Segments are 0.01° (fail
        // alone); the 6-segment chain is 0.06° (passes). Without coalescing
        // the coarse level holds only the point; with it, point + one artery.
        let geoms = fragment_chain_geoms(6);
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 4,
                max_zoom: 10,
            },
            no_auto_rank: true,
            ..Default::default() // coalescing is ON by default
        };

        // Baseline (opt-out): fragments vanish from the coarse level.
        let tout_off = tempfile::NamedTempFile::new().unwrap();
        let off = convert_to_overviews(
            tin.path(),
            tout_off.path(),
            &ConvertOptions {
                coalesce_lines: false,
                ..opts.clone()
            },
        )
        .unwrap();
        assert_eq!(
            off.levels[0].feature_count, 1,
            "without coalescing only the point survives level 0: {:?}",
            off.levels
        );

        // Coalescing (default): the chain survives as ONE feature, count 6.
        let tout = tempfile::NamedTempFile::new().unwrap();
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        assert_eq!(
            report.levels[0].feature_count, 2,
            "chain + point at level 0: {:?}",
            report.levels
        );

        let vr = validate_file(tout.path()).unwrap();
        assert!(
            vr.is_valid(),
            "failures: {:?}",
            vr.failures().collect::<Vec<_>>()
        );

        let reader = OverviewReader::open(tout.path()).unwrap();
        let counts0 = read_coalesced_counts(&reader, 0);
        let mut sorted = counts0.clone();
        sorted.sort_unstable();
        assert_eq!(sorted, vec![1, 6], "point=1, merged chain=6: {counts0:?}");

        // Canonical level: every source row verbatim, all counts 1.
        let canonical = reader.num_levels() - 1;
        let rows = read_level_rows(&reader, canonical);
        assert_eq!(rows.len(), geoms.len());
        for (id, _, _, geom) in &rows {
            assert_eq!(
                geom, &geoms[*id as usize],
                "canonical geometry verbatim (never coalesced)"
            );
        }
        assert!(read_coalesced_counts(&reader, canonical)
            .iter()
            .all(|&c| c == 1));
    }

    #[test]
    fn coalesce_groups_by_auto_detected_class() {
        // Two touching motorway segments merge; the footway touching the
        // same chain end does not (class mismatch). Extra far-away classed
        // lines trigger the Overture auto-detection vocab gate.
        let mut geoms = vec![
            Geometry::LineString(LineString::from(vec![(0.0, 0.0), (0.1, 0.0)])),
            Geometry::LineString(LineString::from(vec![(0.1, 0.0), (0.2, 0.0)])),
            Geometry::LineString(LineString::from(vec![(0.2, 0.0), (0.2, 0.1)])),
        ];
        let mut classes = vec![Some("motorway"), Some("motorway"), Some("footway")];
        for (i, c) in ["primary", "service", "residential"].iter().enumerate() {
            geoms.push(Geometry::LineString(LineString::from(vec![
                (3.0 + i as f64, 3.0),
                (3.1 + i as f64, 3.05),
            ])));
            classes.push(Some(*c));
        }
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_class_input(tin.path(), &geoms, &classes);

        let opts = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 4,
                max_zoom: 10,
            },
            coalesce_lines: true,
            ..Default::default()
        };
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        assert_eq!(ranking_mode_of(tout.path()), "auto-overture-roads");

        let reader = OverviewReader::open(tout.path()).unwrap();
        let counts0 = read_coalesced_counts(&reader, 0);
        assert_eq!(
            counts0.iter().filter(|&&c| c == 2).count(),
            1,
            "exactly one 2-segment motorway chain: {counts0:?}"
        );
        assert!(
            counts0.iter().all(|&c| c <= 2),
            "footway never merges into the motorway chain: {counts0:?}"
        );
    }

    #[test]
    fn coalesce_inert_in_partitioning() {
        // Partitioning cannot represent merged chains (§13.5); with
        // coalescing on by default, partitioning conversions proceed
        // WITHOUT it: no coalesced_count column, no coalescing provenance.
        let geoms = fragment_chain_geoms(3);
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        for streaming in [true, false] {
            let tout = tempfile::NamedTempFile::new().unwrap();
            let report = convert_to_overviews(
                tin.path(),
                tout.path(),
                &ConvertOptions {
                    mode: Mode::Partitioning,
                    coalesce_lines: true, // the default; explicit for clarity
                    streaming,
                    ..Default::default()
                },
            )
            .unwrap();
            // Feature-once: total rows == input rows, no merging happened.
            assert_eq!(report.total_rows, geoms.len(), "streaming={streaming}");
            let reader = OverviewReader::open(tout.path()).unwrap();
            assert!(
                reader
                    .meta()
                    .generalization
                    .as_ref()
                    .unwrap()
                    .coalescing
                    .is_none(),
                "no coalescing provenance in partitioning mode"
            );
            let batch_schema = reader.read_level(0, None).unwrap().next().unwrap().unwrap();
            assert!(
                batch_schema.schema().index_of("coalesced_count").is_err(),
                "no coalesced_count column in partitioning mode"
            );
            assert!(validate_file(tout.path()).unwrap().is_valid());
        }
    }

    #[test]
    fn coalesce_renames_existing_coalesced_count_column() {
        // #288: an input already carrying a `coalesced_count` column (case-
        // insensitively) is auto-renamed when coalescing, and is an ordinary
        // passthrough property when coalescing is off.
        let geoms = fragment_chain_geoms(2);
        let n = geoms.len();
        let tin = tempfile::NamedTempFile::new().unwrap();
        {
            let id = Int64Array::from((0..n as i64).collect::<Vec<_>>());
            let cc = arrow_array::Int32Array::from(vec![7i32; n]);
            let geom_arr = build_geometry_array(&geoms);
            let geom_field = geom_arr.data_type().to_field("geometry", true);
            let fields = vec![
                Arc::new(Field::new("id", DataType::Int64, false)),
                Arc::new(Field::new("Coalesced_Count", DataType::Int32, false)),
                Arc::new(geom_field),
            ];
            let columns: Vec<Arc<dyn Array>> =
                vec![Arc::new(id), Arc::new(cc), geom_arr.to_array_ref()];
            let schema = Arc::new(Schema::new(fields));
            let batch = RecordBatch::try_new(schema.clone(), columns).unwrap();
            let gpq_options = GeoParquetWriterOptionsBuilder::default()
                .set_encoding(GeoParquetWriterEncoding::WKB)
                .set_generate_covering(true)
                .build();
            let mut encoder = GeoParquetRecordBatchEncoder::try_new(&schema, &gpq_options).unwrap();
            let target_schema = encoder.target_schema();
            let file = std::fs::File::create(tin.path()).unwrap();
            let mut writer = ArrowWriter::try_new(file, target_schema, None).unwrap();
            writer
                .write(&encoder.encode_record_batch(&batch).unwrap())
                .unwrap();
            writer.append_key_value_metadata(encoder.into_keyvalue().unwrap());
            writer.close().unwrap();
        }

        let tout = tempfile::NamedTempFile::new().unwrap();
        for streaming in [true, false] {
            convert_to_overviews(
                tin.path(),
                tout.path(),
                &ConvertOptions {
                    coalesce_lines: true,
                    streaming,
                    ..Default::default()
                },
            )
            .unwrap_or_else(|e| {
                panic!("streaming={streaming}: `Coalesced_Count` must be auto-renamed, got {e}")
            });
            let names = output_column_names(tout.path());
            assert!(
                names.iter().any(|n| n == "Coalesced_Count_"),
                "streaming={streaming}: renamed source column present, names={names:?}"
            );
        }
        // With coalescing disabled the column is an ordinary passthrough
        // property (kept verbatim).
        convert_to_overviews(
            tin.path(),
            tout.path(),
            &ConvertOptions {
                coalesce_lines: false,
                ..Default::default()
            },
        )
        .unwrap();
        let names = output_column_names(tout.path());
        assert!(
            names.iter().any(|n| n == "Coalesced_Count"),
            "passthrough column kept verbatim, names={names:?}"
        );
    }

    #[test]
    fn coalesce_footer_provenance_recorded() {
        let geoms = fragment_chain_geoms(3);
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            coalesce_lines: true,
            coalesce_snap: 1.5,
            coalesce_junction_angle: 30.0,
            coalesce_max_level_rows: 123_456,
            ..Default::default()
        };
        convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        let reader = OverviewReader::open(tout.path()).unwrap();
        let c = reader
            .meta()
            .generalization
            .as_ref()
            .unwrap()
            .coalescing
            .clone()
            .expect("coalescing provenance recorded");
        assert!(c.enabled);
        assert_eq!(c.snap_tolerance_gsd_factor, 1.5);
        // §13.4 (v0.2.0): junction angle + memory-guard ceiling recorded so
        // the generalization is reproducible from the file alone.
        assert_eq!(c.junction_angle, Some(30.0));
        assert_eq!(c.max_level_rows, Some(123_456));
        assert_eq!(c.coalesced_count_column, "coalesced_count");

        // Opt-out (`--no-coalesce-lines`): no coalescing block recorded.
        let tout_off = tempfile::NamedTempFile::new().unwrap();
        convert_to_overviews(
            tin.path(),
            tout_off.path(),
            &ConvertOptions {
                coalesce_lines: false,
                ..Default::default()
            },
        )
        .unwrap();
        let r_off = OverviewReader::open(tout_off.path()).unwrap();
        assert!(r_off
            .meta()
            .generalization
            .as_ref()
            .unwrap()
            .coalescing
            .is_none());
    }

    #[test]
    fn coalesce_guard_skips_chaining_but_keeps_column() {
        // A max-level-rows guard smaller than the line count: no chaining
        // happens (fragments still vanish at coarse levels) but the schema
        // and provenance stay stable (coalesced_count all 1).
        let geoms = fragment_chain_geoms(6);
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 4,
                max_zoom: 10,
            },
            no_auto_rank: true,
            coalesce_lines: true,
            coalesce_max_level_rows: 2, // < 6 lines → guard trips
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        assert_eq!(
            report.levels[0].feature_count, 1,
            "guard-skipped run behaves like non-coalesced: {:?}",
            report.levels
        );
        let reader = OverviewReader::open(tout.path()).unwrap();
        for level in 0..reader.num_levels() {
            assert!(read_coalesced_counts(&reader, level)
                .iter()
                .all(|&c| c == 1));
        }
        assert!(validate_file(tout.path()).unwrap().is_valid());
    }

    #[test]
    fn streaming_matches_in_memory_coalescing() {
        // Coalescing must be byte-equivalent between the streaming and
        // in-memory pipelines, including with tiny read batches (chain reps
        // scattered across batch boundaries).
        let geoms = fragment_chain_geoms(6);
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let base = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 4,
                max_zoom: 10,
            },
            no_auto_rank: true,
            coalesce_lines: true,
            read_batch_size: 2,
            ..Default::default()
        };
        assert_streaming_equivalent(tin.path(), &base);

        // Explicitly compare coalesced_count per level too.
        let mem_out = tempfile::NamedTempFile::new().unwrap();
        let stream_out = tempfile::NamedTempFile::new().unwrap();
        convert_to_overviews(
            tin.path(),
            mem_out.path(),
            &ConvertOptions {
                streaming: false,
                ..base.clone()
            },
        )
        .unwrap();
        convert_to_overviews(tin.path(), stream_out.path(), &base).unwrap();
        let mr = OverviewReader::open(mem_out.path()).unwrap();
        let sr = OverviewReader::open(stream_out.path()).unwrap();
        for level in 0..mr.num_levels() {
            assert_eq!(
                read_coalesced_counts(&mr, level),
                read_coalesced_counts(&sr, level),
                "level {level} coalesced_count differs"
            );
        }
    }

    #[test]
    fn streaming_matches_in_memory_coalescing_with_class_groups() {
        // Same equivalence with the auto-detected class ranking driving the
        // compatibility groups (interner parity across batch boundaries).
        let mut geoms = vec![
            Geometry::LineString(LineString::from(vec![(0.0, 0.0), (0.1, 0.0)])),
            Geometry::LineString(LineString::from(vec![(0.1, 0.0), (0.2, 0.0)])),
            Geometry::LineString(LineString::from(vec![(0.2, 0.0), (0.2, 0.1)])),
        ];
        let mut classes = vec![Some("motorway"), Some("motorway"), Some("footway")];
        for (i, c) in ["primary", "service", "residential", "trunk"]
            .iter()
            .enumerate()
        {
            geoms.push(Geometry::LineString(LineString::from(vec![
                (3.0 + i as f64, 3.0),
                (3.1 + i as f64, 3.05),
            ])));
            classes.push(Some(*c));
        }
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_class_input(tin.path(), &geoms, &classes);

        let base = ConvertOptions {
            levels: LevelPlan::ZoomRange {
                min_zoom: 4,
                max_zoom: 10,
            },
            coalesce_lines: true,
            read_batch_size: 2,
            ..Default::default()
        };
        let mem_out = tempfile::NamedTempFile::new().unwrap();
        let stream_out = tempfile::NamedTempFile::new().unwrap();
        convert_to_overviews(
            tin.path(),
            mem_out.path(),
            &ConvertOptions {
                streaming: false,
                ..base.clone()
            },
        )
        .unwrap();
        convert_to_overviews(tin.path(), stream_out.path(), &base).unwrap();
        assert_eq!(
            overviews_footer_json(mem_out.path()),
            overviews_footer_json(stream_out.path())
        );
        let mr = OverviewReader::open(mem_out.path()).unwrap();
        let sr = OverviewReader::open(stream_out.path()).unwrap();
        assert_eq!(mr.num_levels(), sr.num_levels());
        for level in 0..mr.num_levels() {
            assert_eq!(
                read_coalesced_counts(&mr, level),
                read_coalesced_counts(&sr, level),
                "level {level} coalesced_count differs"
            );
        }
    }

    #[test]
    fn sort_key_column_missing_errors() {
        let geoms = synthetic_geometries();
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            sort_key: Some("nonexistent".to_string()),
            ..Default::default()
        };
        let err = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap_err();
        assert!(matches!(err, ConvertError::SortKeyColumnMissing { .. }));
    }

    // ========================================================================
    // Bbox row-group filtering tests (#102)
    // ========================================================================

    /// Write a multi-row-group GeoParquet file with covering column stats so
    /// row-group pruning can actually bite. Each row group contains one point
    /// at `(x, y)` with id = row-group index.
    fn write_multi_rg_input(path: &Path, coords: &[(f64, f64)], with_covering: bool) {
        use parquet::file::properties::WriterProperties;

        let geoms: Vec<Geometry<f64>> = coords
            .iter()
            .map(|&(x, y)| Geometry::Point(Point::new(x, y)))
            .collect();
        let n = geoms.len();
        let id = Int64Array::from((0..n as i64).collect::<Vec<_>>());
        let geom_arr = build_geometry_array(&geoms);
        let geom_field = geom_arr.data_type().to_field("geometry", true);
        let fields = vec![
            Arc::new(Field::new("id", DataType::Int64, false)),
            Arc::new(geom_field),
        ];
        let columns: Vec<Arc<dyn Array>> = vec![Arc::new(id), geom_arr.to_array_ref()];
        let schema = Arc::new(Schema::new(fields));
        let batch = RecordBatch::try_new(schema.clone(), columns).unwrap();

        let gpq_options = GeoParquetWriterOptionsBuilder::default()
            .set_encoding(GeoParquetWriterEncoding::WKB)
            .set_generate_covering(with_covering)
            .build();
        let encoder = GeoParquetRecordBatchEncoder::try_new(&schema, &gpq_options).unwrap();
        let target_schema = encoder.target_schema();
        // Row-group size = 1 to force n row groups.
        let props = WriterProperties::builder()
            .set_max_row_group_row_count(Some(1))
            .build();
        let file = std::fs::File::create(path).unwrap();
        let mut writer = ArrowWriter::try_new(file, target_schema, Some(props)).unwrap();
        let mut encoder = encoder;
        let encoded = encoder.encode_record_batch(&batch).unwrap();
        writer.write(&encoded).unwrap();
        writer.append_key_value_metadata(encoder.into_keyvalue().unwrap());
        writer.close().unwrap();
    }

    /// Read all ids from all levels of an overview file.
    fn read_all_ids(reader: &OverviewReader) -> Vec<i64> {
        use arrow_array::cast::AsArray;
        let mut ids = Vec::new();
        for level in 0..reader.num_levels() {
            let rdr = reader.read_level(level, None).unwrap();
            for batch in rdr {
                let batch = batch.unwrap();
                let col = batch
                    .column(batch.schema().index_of("id").unwrap())
                    .as_primitive::<arrow_array::types::Int64Type>();
                ids.extend(col.iter().flatten());
            }
        }
        ids.sort_unstable();
        ids.dedup();
        ids
    }

    #[test]
    fn bbox_filter_matches_posthoc_filter() {
        // 4 row groups with points at (0,0), (10,10), (20,20), (30,30).
        // A bbox around (10,10) should keep only id=1.
        let coords = vec![(0.0, 0.0), (10.0, 10.0), (20.0, 20.0), (30.0, 30.0)];
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_multi_rg_input(tin.path(), &coords, true);

        // Full unfiltered conversion.
        let tout_full = tempfile::NamedTempFile::new().unwrap();
        let opts_full = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 6,
                max_zoom: 6,
            },
            ..Default::default()
        };
        let report_full = convert_to_overviews(tin.path(), tout_full.path(), &opts_full).unwrap();
        assert_eq!(report_full.row_groups_total, 4);
        assert_eq!(report_full.row_groups_read, 4);
        let reader_full = OverviewReader::open(tout_full.path()).unwrap();
        let ids_full = read_all_ids(&reader_full);

        // Bbox-filtered conversion: keep only (10,10).
        let tout_bbox = tempfile::NamedTempFile::new().unwrap();
        let opts_bbox = ConvertOptions {
            bbox: Some([9.0, 9.0, 11.0, 11.0]),
            ..opts_full.clone()
        };
        let report_bbox = convert_to_overviews(tin.path(), tout_bbox.path(), &opts_bbox).unwrap();
        // The bbox intersects only one row group, so pruning should fire.
        assert_eq!(report_bbox.row_groups_total, 4);
        assert_eq!(
            report_bbox.row_groups_read, 1,
            "bbox pruning did not fire: read {} row groups",
            report_bbox.row_groups_read
        );
        let reader_bbox = OverviewReader::open(tout_bbox.path()).unwrap();
        let ids_bbox = read_all_ids(&reader_bbox);
        assert_eq!(ids_bbox, vec![1], "bbox filter kept wrong ids");

        // Correctness: filtered == unfiltered then post-hoc filtered.
        let ids_posthoc: Vec<i64> = ids_full
            .into_iter()
            .filter(|&id| {
                let (x, y) = coords[id as usize];
                (9.0..=11.0).contains(&x) && (9.0..=11.0).contains(&y)
            })
            .collect();
        assert_eq!(ids_bbox, ids_posthoc);
    }

    #[test]
    fn bbox_filter_stats_free_degradation() {
        // Same layout but WITHOUT covering column (stats-free input).
        let coords = vec![(0.0, 0.0), (10.0, 10.0), (20.0, 20.0), (30.0, 30.0)];
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_multi_rg_input(tin.path(), &coords, false);

        let tout = tempfile::NamedTempFile::new().unwrap();
        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 6,
                max_zoom: 6,
            },
            bbox: Some([9.0, 9.0, 11.0, 11.0]),
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
        // Without stats, all row groups are read (graceful degradation).
        assert_eq!(report.row_groups_total, 4);
        assert_eq!(
            report.row_groups_read, 4,
            "stats-free should read all row groups"
        );
        // Exact per-feature filter still applies: only id=1 survives.
        let reader = OverviewReader::open(tout.path()).unwrap();
        let ids = read_all_ids(&reader);
        assert_eq!(ids, vec![1], "exact filter did not apply");
    }

    #[test]
    fn bbox_filter_nothing_intersects() {
        let coords = vec![(0.0, 0.0), (10.0, 10.0)];
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_multi_rg_input(tin.path(), &coords, true);

        let tout = tempfile::NamedTempFile::new().unwrap();
        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 6,
                max_zoom: 6,
            },
            bbox: Some([100.0, 100.0, 110.0, 110.0]), // far away
            ..Default::default()
        };
        let err = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap_err();
        // No features survive → NoData error.
        assert!(
            matches!(err, ConvertError::NoData),
            "expected NoData, got {err:?}"
        );
    }

    #[test]
    fn bbox_filter_everything_intersects() {
        let coords = vec![(0.0, 0.0), (10.0, 10.0)];
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_multi_rg_input(tin.path(), &coords, true);

        // Full conversion (no bbox).
        let tout_full = tempfile::NamedTempFile::new().unwrap();
        let opts_full = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 6,
                max_zoom: 6,
            },
            ..Default::default()
        };
        let _report_full = convert_to_overviews(tin.path(), tout_full.path(), &opts_full).unwrap();
        let reader_full = OverviewReader::open(tout_full.path()).unwrap();
        let ids_full = read_all_ids(&reader_full);

        // Bbox containing everything.
        let tout_bbox = tempfile::NamedTempFile::new().unwrap();
        let opts_bbox = ConvertOptions {
            bbox: Some([-1.0, -1.0, 11.0, 11.0]),
            ..opts_full.clone()
        };
        let report_bbox = convert_to_overviews(tin.path(), tout_bbox.path(), &opts_bbox).unwrap();
        // All row groups intersect, so row_groups_read == row_groups_total.
        assert_eq!(report_bbox.row_groups_read, report_bbox.row_groups_total);
        let reader_bbox = OverviewReader::open(tout_bbox.path()).unwrap();
        let ids_bbox = read_all_ids(&reader_bbox);
        assert_eq!(ids_bbox, ids_full);
    }

    // ========================================================================
    // Attribute filter tests (#315)
    // ========================================================================

    /// One fixture row: `((x, y), confidence, crop)`.
    type AttrRow = ((f64, f64), Option<f64>, Option<&'static str>);

    /// Multi-row-group input with attribute columns: one row per row group at
    /// `(x, y)` with `id` = row-group index, plus a nullable `confidence`
    /// Float64 and a nullable `crop` Utf8 column. One row per row group makes
    /// per-row-group column statistics exact, so pushdown pruning can bite.
    fn write_multi_rg_attr_input(path: &Path, rows: &[AttrRow]) {
        use parquet::file::properties::WriterProperties;

        let geoms: Vec<Geometry<f64>> = rows
            .iter()
            .map(|&((x, y), _, _)| Geometry::Point(Point::new(x, y)))
            .collect();
        let n = geoms.len();
        let id = Int64Array::from((0..n as i64).collect::<Vec<_>>());
        let confidence =
            arrow_array::Float64Array::from(rows.iter().map(|(_, c, _)| *c).collect::<Vec<_>>());
        let crop =
            arrow_array::StringArray::from(rows.iter().map(|(_, _, s)| *s).collect::<Vec<_>>());
        let geom_arr = build_geometry_array(&geoms);
        let geom_field = geom_arr.data_type().to_field("geometry", true);
        let fields = vec![
            Arc::new(Field::new("id", DataType::Int64, false)),
            Arc::new(Field::new("confidence", DataType::Float64, true)),
            Arc::new(Field::new("crop", DataType::Utf8, true)),
            Arc::new(geom_field),
        ];
        let columns: Vec<Arc<dyn Array>> = vec![
            Arc::new(id),
            Arc::new(confidence),
            Arc::new(crop),
            geom_arr.to_array_ref(),
        ];
        let schema = Arc::new(Schema::new(fields));
        let batch = RecordBatch::try_new(schema.clone(), columns).unwrap();

        let gpq_options = GeoParquetWriterOptionsBuilder::default()
            .set_encoding(GeoParquetWriterEncoding::WKB)
            .set_generate_covering(true)
            .build();
        let encoder = GeoParquetRecordBatchEncoder::try_new(&schema, &gpq_options).unwrap();
        let target_schema = encoder.target_schema();
        let props = WriterProperties::builder()
            .set_max_row_group_row_count(Some(1))
            .build();
        let file = std::fs::File::create(path).unwrap();
        let mut writer = ArrowWriter::try_new(file, target_schema, Some(props)).unwrap();
        let mut encoder = encoder;
        let encoded = encoder.encode_record_batch(&batch).unwrap();
        writer.write(&encoded).unwrap();
        writer.append_key_value_metadata(encoder.into_keyvalue().unwrap());
        writer.close().unwrap();
    }

    /// Rows: (0,0)/0.1/soy, (10,10)/0.9/corn, (20,20)/0.85/soy, (30,30)/null/rice.
    fn attr_rows() -> Vec<AttrRow> {
        vec![
            ((0.0, 0.0), Some(0.1), Some("soy")),
            ((10.0, 10.0), Some(0.9), Some("corn")),
            ((20.0, 20.0), Some(0.85), Some("soy")),
            ((30.0, 30.0), None, Some("rice")),
        ]
    }

    fn attr_opts() -> ConvertOptions {
        ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 6,
                max_zoom: 6,
            },
            ..Default::default()
        }
    }

    /// `--filter "confidence > 0.8"` keeps only the matching features
    /// (null confidence drops per SQL three-valued logic) AND prunes the
    /// non-matching row groups via column statistics — in both the streaming
    /// and in-memory engines.
    #[test]
    fn attribute_filter_matches_posthoc_and_prunes_row_groups() {
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_multi_rg_attr_input(tin.path(), &attr_rows());

        for streaming in [true, false] {
            let tout = tempfile::NamedTempFile::new().unwrap();
            let opts = ConvertOptions {
                filter: Some("confidence > 0.8".to_string()),
                streaming,
                ..attr_opts()
            };
            let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
            assert_eq!(report.row_groups_total, 4, "streaming={streaming}");
            // RG0 (0.1) and RG3 (all-null) are provably non-matching by stats.
            assert_eq!(
                report.row_groups_read, 2,
                "stats pushdown did not fire (streaming={streaming})"
            );
            let ids = read_all_ids(&OverviewReader::open(tout.path()).unwrap());
            assert_eq!(ids, vec![1, 2], "streaming={streaming}");
        }
    }

    /// `--filter` composes with `--bbox`: row-group selections intersect and
    /// the per-feature filters both apply.
    #[test]
    fn attribute_filter_composes_with_bbox() {
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_multi_rg_attr_input(tin.path(), &attr_rows());

        for streaming in [true, false] {
            let tout = tempfile::NamedTempFile::new().unwrap();
            let opts = ConvertOptions {
                // bbox keeps (10,10) and (20,20); filter keeps 0.9 and 0.85;
                // combined with bbox tightened to exclude (20,20): only id=1.
                bbox: Some([9.0, 9.0, 11.0, 11.0]),
                filter: Some("confidence > 0.8".to_string()),
                streaming,
                ..attr_opts()
            };
            let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
            assert_eq!(
                report.row_groups_read, 1,
                "bbox+filter selection must intersect (streaming={streaming})"
            );
            let ids = read_all_ids(&OverviewReader::open(tout.path()).unwrap());
            assert_eq!(ids, vec![1], "streaming={streaming}");
        }
    }

    /// String equality / IN, IS NULL, and OR-composition semantics.
    #[test]
    fn attribute_filter_string_in_and_null_semantics() {
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_multi_rg_attr_input(tin.path(), &attr_rows());

        for streaming in [true, false] {
            // IN over strings.
            let tout = tempfile::NamedTempFile::new().unwrap();
            let opts = ConvertOptions {
                filter: Some("crop IN ('corn', 'rice')".to_string()),
                streaming,
                ..attr_opts()
            };
            convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
            let ids = read_all_ids(&OverviewReader::open(tout.path()).unwrap());
            assert_eq!(ids, vec![1, 3], "IN (streaming={streaming})");

            // IS NULL keeps exactly the null-confidence row.
            let tout = tempfile::NamedTempFile::new().unwrap();
            let opts = ConvertOptions {
                filter: Some("confidence IS NULL".to_string()),
                streaming,
                ..attr_opts()
            };
            convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
            let ids = read_all_ids(&OverviewReader::open(tout.path()).unwrap());
            assert_eq!(ids, vec![3], "IS NULL (streaming={streaming})");

            // Three-valued OR: null confidence is rescued by the crop arm.
            let tout = tempfile::NamedTempFile::new().unwrap();
            let opts = ConvertOptions {
                filter: Some("confidence > 0.8 OR crop = 'rice'".to_string()),
                streaming,
                ..attr_opts()
            };
            convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();
            let ids = read_all_ids(&OverviewReader::open(tout.path()).unwrap());
            assert_eq!(ids, vec![1, 2, 3], "OR (streaming={streaming})");
        }
    }

    /// Filter errors: bad syntax fails in validation, an unknown column and
    /// a type mismatch fail at bind — all before any output is written.
    #[test]
    fn attribute_filter_error_paths() {
        let tin = tempfile::NamedTempFile::new().unwrap();
        write_multi_rg_attr_input(tin.path(), &attr_rows());

        let tout = tempfile::NamedTempFile::new().unwrap();
        let bad_syntax = ConvertOptions {
            filter: Some("confidence >".to_string()),
            ..attr_opts()
        };
        let err = convert_to_overviews(tin.path(), tout.path(), &bad_syntax).unwrap_err();
        assert!(matches!(err, ConvertError::Filter(_)), "got {err:?}");

        let unknown = ConvertOptions {
            filter: Some("nope = 1".to_string()),
            ..attr_opts()
        };
        let err = convert_to_overviews(tin.path(), tout.path(), &unknown).unwrap_err();
        assert!(
            matches!(err, ConvertError::Filter(_)) && err.to_string().contains("unknown column"),
            "got {err:?}"
        );

        let mismatch = ConvertOptions {
            filter: Some("crop > 3".to_string()),
            ..attr_opts()
        };
        let err = convert_to_overviews(tin.path(), tout.path(), &mismatch).unwrap_err();
        assert!(matches!(err, ConvertError::Filter(_)), "got {err:?}");

        // A filter matching nothing surfaces as NoData, like an empty bbox.
        let none = ConvertOptions {
            filter: Some("confidence > 99".to_string()),
            ..attr_opts()
        };
        let err = convert_to_overviews(tin.path(), tout.path(), &none).unwrap_err();
        assert!(matches!(err, ConvertError::NoData), "got {err:?}");
    }

    // ========================================================================
    // Remote input tests (#210)
    // ========================================================================

    #[cfg(feature = "remote")]
    mod remote_input {
        use super::*;
        use crate::input::{test_memory_source, InputSource};

        /// Byte span `[start, end)` of each row group's data pages.
        fn row_group_spans(bytes: &[u8]) -> Vec<std::ops::Range<u64>> {
            let builder =
                ParquetRecordBatchReaderBuilder::try_new(bytes::Bytes::from(bytes.to_vec()))
                    .unwrap();
            builder
                .metadata()
                .row_groups()
                .iter()
                .map(|rg| {
                    let mut start = u64::MAX;
                    let mut end = 0u64;
                    for col in rg.columns() {
                        let (s, len) = col.byte_range();
                        start = start.min(s);
                        end = end.max(s + len);
                    }
                    start..end
                })
                .collect()
        }

        /// THE #210 headline property: a `--bbox` extract from a remote file
        /// must fetch byte ranges ONLY from the bbox-selected row groups (plus
        /// the footer) — pruned row groups are never downloaded at all.
        fn assert_bbox_extract_fetches_only_selected(streaming: bool) {
            // 4 single-point row groups at (0,0), (10,10), (20,20), (30,30)
            // with covering stats; a bbox around (10,10) selects only rg 1.
            let coords = vec![(0.0, 0.0), (10.0, 10.0), (20.0, 20.0), (30.0, 30.0)];
            let tin = tempfile::NamedTempFile::new().unwrap();
            write_multi_rg_input(tin.path(), &coords, true);
            let bytes = std::fs::read(tin.path()).unwrap();
            let spans = row_group_spans(&bytes);
            assert_eq!(spans.len(), 4);

            let source = test_memory_source(bytes, "multi.parquet");
            let tout = tempfile::NamedTempFile::new().unwrap();
            let opts = ConvertOptions {
                mode: Mode::Duplicating,
                levels: LevelPlan::ZoomRange {
                    min_zoom: 6,
                    max_zoom: 6,
                },
                bbox: Some([9.0, 9.0, 11.0, 11.0]),
                streaming,
                ..Default::default()
            };
            let report = convert_to_overviews_source(&source, tout.path(), &opts).unwrap();

            assert_eq!(report.row_groups_total, 4);
            assert_eq!(report.row_groups_read, 1, "bbox pruning must fire");
            let ids = read_all_ids(&OverviewReader::open(tout.path()).unwrap());
            assert_eq!(ids, vec![1], "only the (10,10) feature survives");

            // No fetched range may touch a pruned row group's data pages.
            let fetched = source.fetched_ranges().unwrap();
            assert!(!fetched.is_empty());
            for (i, span) in spans.iter().enumerate() {
                if i == 1 {
                    continue;
                }
                for r in &fetched {
                    assert!(
                        r.end <= span.start || r.start >= span.end,
                        "fetched range {r:?} overlaps PRUNED row group {i} ({span:?})"
                    );
                }
            }
            // ... while the selected row group's data pages WERE fetched.
            assert!(
                fetched
                    .iter()
                    .any(|r| r.start >= spans[1].start && r.end <= spans[1].end),
                "selected row group 1 ({:?}) never fetched: {fetched:?}",
                spans[1]
            );

            // And the report carries the savings.
            let stats = report.remote_fetch.expect("remote stats in report");
            assert!(stats.requests as usize >= fetched.len());
            assert!(
                stats.bytes_fetched < stats.object_size,
                "bbox extract must move fewer bytes than the object: {stats:?}"
            );
        }

        #[test]
        fn bbox_extract_streaming_fetches_only_selected_row_groups() {
            assert_bbox_extract_fetches_only_selected(true);
        }

        #[test]
        fn bbox_extract_in_memory_fetches_only_selected_row_groups() {
            assert_bbox_extract_fetches_only_selected(false);
        }

        /// The #315 headline property: a `--filter` convert over a remote
        /// file must fetch data pages ONLY from the row groups whose column
        /// statistics permit a match — pruned groups' byte ranges are never
        /// downloaded at all (fetched-bytes reduction).
        #[test]
        fn attribute_filter_remote_fetches_only_matching_row_groups() {
            // 4 single-row row groups; `confidence > 0.8` stats-selects only
            // rg 1 (0.9) and rg 2 (0.85); rg 0 (0.1) and rg 3 (null) prune.
            let tin = tempfile::NamedTempFile::new().unwrap();
            write_multi_rg_attr_input(tin.path(), &attr_rows());
            let bytes = std::fs::read(tin.path()).unwrap();
            let spans = row_group_spans(&bytes);
            assert_eq!(spans.len(), 4);

            let source = test_memory_source(bytes, "attrs.parquet");
            let tout = tempfile::NamedTempFile::new().unwrap();
            let opts = ConvertOptions {
                filter: Some("confidence > 0.8".to_string()),
                ..attr_opts()
            };
            let report = convert_to_overviews_source(&source, tout.path(), &opts).unwrap();

            assert_eq!(report.row_groups_total, 4);
            assert_eq!(report.row_groups_read, 2, "filter pushdown must fire");
            let ids = read_all_ids(&OverviewReader::open(tout.path()).unwrap());
            assert_eq!(ids, vec![1, 2]);

            // No fetched range may touch a pruned row group's data pages.
            let fetched = source.fetched_ranges().unwrap();
            assert!(!fetched.is_empty());
            for (i, span) in spans.iter().enumerate() {
                if i == 1 || i == 2 {
                    continue;
                }
                for r in &fetched {
                    assert!(
                        r.end <= span.start || r.start >= span.end,
                        "fetched range {r:?} overlaps PRUNED row group {i} ({span:?})"
                    );
                }
            }
            let stats = report.remote_fetch.expect("remote stats in report");
            assert!(
                stats.bytes_fetched < stats.object_size,
                "filter extract must move fewer bytes than the object: {stats:?}"
            );
        }

        /// A full (no-bbox) remote conversion must produce the same result as
        /// the same conversion over the local file.
        #[test]
        fn remote_convert_matches_local_convert() {
            let geoms = synthetic_geometries();
            let tin = tempfile::NamedTempFile::new().unwrap();
            write_input(tin.path(), &geoms, false, None);
            let opts = ConvertOptions::default();

            let tout_local = tempfile::NamedTempFile::new().unwrap();
            let report_local = convert_to_overviews(tin.path(), tout_local.path(), &opts).unwrap();
            assert!(report_local.remote_fetch.is_none(), "local input: no stats");

            let source = test_memory_source(std::fs::read(tin.path()).unwrap(), "in.parquet");
            let tout_remote = tempfile::NamedTempFile::new().unwrap();
            let report_remote =
                convert_to_overviews_source(&source, tout_remote.path(), &opts).unwrap();

            assert_eq!(report_remote.input_features, report_local.input_features);
            assert_eq!(report_remote.total_rows, report_local.total_rows);
            assert_eq!(
                read_all_ids(&OverviewReader::open(tout_remote.path()).unwrap()),
                read_all_ids(&OverviewReader::open(tout_local.path()).unwrap()),
            );
            assert!(report_remote.remote_fetch.is_some());
        }

        /// #286 + #287: a full remote convert must COALESCE its data-page
        /// fetches to ~one range request per selected row group. A row
        /// group's column chunks are a contiguous byte span, so staging that
        /// span up front (in parallel) turns the whole conversion's reads
        /// into one request per row group — instead of a separate serial
        /// request per column chunk per pass (#287), and in particular
        /// instead of pass 2 re-fetching, cold, the property columns that
        /// pass 1's geometry-only projection skipped (#286).
        #[test]
        fn remote_convert_coalesces_fetches_to_one_request_per_row_group() {
            let geoms = synthetic_geometries();
            let n = geoms.len();
            // Several row groups, each carrying property columns (id, name,
            // rank) that pass 1's geometry+ranking projection does not fully
            // read — the #286 pass-2 re-fetch shape.
            let tin = tempfile::NamedTempFile::new().unwrap();
            write_input_partition(tin.path(), &geoms, 0..n, Some(2));
            let bytes = std::fs::read(tin.path()).unwrap();
            let rg = row_group_spans(&bytes).len();
            assert!(rg >= 3, "test needs several row groups, got {rg}");

            let opts = ConvertOptions::default();

            // Reference: the local convert of the identical bytes.
            let tout_local = tempfile::NamedTempFile::new().unwrap();
            convert_to_overviews(tin.path(), tout_local.path(), &opts).unwrap();
            let local_ids = read_all_ids(&OverviewReader::open(tout_local.path()).unwrap());

            let source = test_memory_source(bytes, "staged.parquet");
            let tout = tempfile::NamedTempFile::new().unwrap();
            let report = convert_to_overviews_source(&source, tout.path(), &opts).unwrap();

            // Staging must not change the output.
            assert_eq!(
                read_all_ids(&OverviewReader::open(tout.path()).unwrap()),
                local_ids,
                "staged remote convert must match the local convert row-for-row"
            );

            let stats = report.remote_fetch.expect("remote stats in report");
            // THE property: one coalesced request per selected row group, plus
            // a small fixed footer/metadata overhead — NOT ~one request per
            // column chunk per pass.
            const FOOTER_SLACK: u64 = 4;
            assert!(
                stats.requests <= rg as u64 + FOOTER_SLACK,
                "expected ~1 request per row group (<= {} for {rg} row groups); \
                 got {} — fetches not coalesced (#287) or properties re-fetched (#286)",
                rg as u64 + FOOTER_SLACK,
                stats.requests,
            );
            // Coalescing must not over-fetch: still ≈1× the object (#219).
            assert!(
                stats.bytes_fetched <= stats.object_size + stats.object_size / 2,
                "staging must stay ≈1× the object: {} of {} bytes",
                stats.bytes_fetched,
                stats.object_size,
            );
        }

        // --- multi-partition remote input (v0.7 PR-B) ------------------------

        /// Partition bytes for `geoms[range]`, via the shared local writer.
        fn partition_bytes(
            geoms: &[Geometry<f64>],
            range: std::ops::Range<usize>,
            row_group_rows: Option<usize>,
        ) -> Vec<u8> {
            let tmp = tempfile::NamedTempFile::new().unwrap();
            write_input_partition(tmp.path(), geoms, range, row_group_rows);
            std::fs::read(tmp.path()).unwrap()
        }

        /// Convert a remote ConvertSource and export to PMTiles; returns
        /// the archive bytes (PMTiles export is byte-deterministic).
        fn convert_sources_and_export(
            source: &crate::input_set::ConvertSource,
            workdir: &Path,
            tag: &str,
            opts: &ConvertOptions,
        ) -> Vec<u8> {
            use crate::overview::export::{export_pmtiles, ExportOptions};
            let overview = workdir.join(format!("{tag}-overview.parquet"));
            let pmtiles = workdir.join(format!("{tag}.pmtiles"));
            convert_to_overviews_sources(source, &overview, opts).unwrap();
            export_pmtiles(&overview, &pmtiles, &ExportOptions::default()).unwrap();
            std::fs::read(&pmtiles).unwrap()
        }

        /// #219's ≈1× guarantee must hold PER PART across the streaming
        /// pipeline's three passes (assign, coarse levels, finest last):
        /// each part's fetched ranges sum to at most ~1.5× its object size
        /// (footer overhead), and no byte range crosses the network twice.
        #[test]
        fn multi_part_three_pass_moves_each_part_once() {
            let geoms = synthetic_geometries();
            let n = geoms.len();
            let (source, parts) = crate::input::test_memory_multi_source(vec![
                ("p0.parquet", partition_bytes(&geoms, 0..5, None)),
                ("p1.parquet", partition_bytes(&geoms, 5..9, None)),
                ("p2.parquet", partition_bytes(&geoms, 9..n, None)),
            ]);
            assert_eq!(parts.len(), 3);

            let tout = tempfile::NamedTempFile::new().unwrap();
            let report =
                convert_to_overviews_sources(&source, tout.path(), &multi_test_options()).unwrap();
            assert_eq!(report.input_features, n);

            let summed = report.remote_fetch.expect("multi remote reports stats");
            let mut object_total = 0;
            for part in &parts {
                let stats = part.fetch_stats().expect("remote part has stats");
                object_total += stats.object_size;
                assert!(
                    stats.bytes_fetched <= stats.object_size + stats.object_size / 2,
                    "part {} moved {} bytes for a {}-byte object (>1.5x, #219 \
                     must hold per part)",
                    part.display_name(),
                    stats.bytes_fetched,
                    stats.object_size,
                );
                // No byte range crosses the network twice for any part.
                let mut seen = std::collections::HashSet::new();
                for r in part.fetched_ranges().expect("remote part logs ranges") {
                    assert!(
                        seen.insert((r.start, r.end)),
                        "part {}: range {r:?} fetched more than once (#219)",
                        part.display_name(),
                    );
                }
            }
            assert_eq!(
                summed.object_size, object_total,
                "ConvertReport.remote_fetch.object_size sums the parts"
            );
        }

        /// #286 + #287 across the multi-partition path (the demo scenario):
        /// each remote part must coalesce ITS OWN selected row groups to ~one
        /// range request per row group, so a prefix of N partitions pays one
        /// TTFB per row group — not ~one per column chunk per pass.
        #[test]
        fn multi_part_remote_coalesces_per_part_row_groups() {
            let geoms = synthetic_geometries();
            let n = geoms.len();
            // Each partition carries several row groups (2 rows each) with
            // property columns (id, name, rank) that pass 1 skips — the #286
            // shape, per part.
            let p0 = partition_bytes(&geoms, 0..5, Some(2));
            let p1 = partition_bytes(&geoms, 5..9, Some(2));
            let p2 = partition_bytes(&geoms, 9..n, Some(2));
            let rg = [&p0, &p1, &p2].map(|b| row_group_spans(b).len());
            assert!(
                rg.iter().all(|&r| r >= 2),
                "each part needs several row groups: {rg:?}"
            );

            let (source, parts) = crate::input::test_memory_multi_source(vec![
                ("p0.parquet", p0),
                ("p1.parquet", p1),
                ("p2.parquet", p2),
            ]);
            let tout = tempfile::NamedTempFile::new().unwrap();
            convert_to_overviews_sources(&source, tout.path(), &multi_test_options()).unwrap();

            const FOOTER_SLACK: u64 = 4;
            for (i, part) in parts.iter().enumerate() {
                let stats = part.fetch_stats().expect("remote part has stats");
                assert!(
                    stats.requests <= rg[i] as u64 + FOOTER_SLACK,
                    "part {i}: expected ~1 request per row group (<= {} for {} \
                     row groups); got {} — not coalesced (#287) or properties \
                     re-fetched (#286)",
                    rg[i] as u64 + FOOTER_SLACK,
                    rg[i],
                    stats.requests,
                );
            }
        }

        /// bbox pruning an ENTIRE part: its row groups are pruned at the
        /// footer level, so the network never touches that part's data
        /// pages — only its footer (fetched once at set construction).
        #[test]
        fn multi_part_bbox_prunes_part_to_footer_only() {
            let geoms = synthetic_geometries();
            let n = geoms.len();
            // p1 holds ONLY the lines (x 40..96); the bbox below excludes them.
            let p1_bytes = partition_bytes(&geoms, 6..10, None);
            let p1_spans = row_group_spans(&p1_bytes);
            let (source, parts) = crate::input::test_memory_multi_source(vec![
                ("p0.parquet", partition_bytes(&geoms, 0..6, None)),
                ("p1.parquet", p1_bytes),
                ("p2.parquet", partition_bytes(&geoms, 10..n, None)),
            ]);

            let opts = ConvertOptions {
                bbox: Some([-100.0, -70.0, 30.0, 20.0]),
                ..multi_test_options()
            };
            let tout = tempfile::NamedTempFile::new().unwrap();
            let report = convert_to_overviews_sources(&source, tout.path(), &opts).unwrap();
            assert!(
                report.row_groups_read < report.row_groups_total,
                "bbox must prune the lines part: {}/{}",
                report.row_groups_read,
                report.row_groups_total
            );

            let pruned = &parts[1];
            let fetched = pruned.fetched_ranges().expect("remote part logs ranges");
            assert!(
                !fetched.is_empty(),
                "the footer itself is fetched at set construction"
            );
            for r in &fetched {
                for span in &p1_spans {
                    assert!(
                        r.end <= span.start || r.start >= span.end,
                        "pruned part fetched data-page range {r:?} \
                         (row-group span {span:?}) — must be footer-only"
                    );
                }
            }
        }

        /// The PR-A anchor, over the wire: the same rows as one remote
        /// object and as three remote partitions under one prefix must
        /// produce byte-identical PMTiles.
        #[test]
        fn multi_part_remote_output_matches_single_remote() {
            let geoms = synthetic_geometries();
            let n = geoms.len();
            let dir = tempfile::tempdir().unwrap();
            let opts = multi_test_options();

            let (single, _) = crate::input::test_memory_multi_source(vec![(
                "single.parquet",
                partition_bytes(&geoms, 0..n, None),
            )]);
            let (multi, parts) = crate::input::test_memory_multi_source(vec![
                ("part-000.parquet", partition_bytes(&geoms, 0..5, None)),
                ("part-001.parquet", partition_bytes(&geoms, 5..9, None)),
                ("part-002.parquet", partition_bytes(&geoms, 9..n, None)),
            ]);
            assert_eq!(parts.len(), 3);

            let pm_single = convert_sources_and_export(&single, dir.path(), "single", &opts);
            let pm_multi = convert_sources_and_export(&multi, dir.path(), "multi", &opts);
            assert!(
                pm_single == pm_multi,
                "remote multi-partition output must be byte-identical to the \
                 single remote object ({} vs {} bytes)",
                pm_single.len(),
                pm_multi.len()
            );
        }

        /// A throwaway localhost HTTP/1.1 server that serves one byte blob with
        /// Range support — the hermetic, no-network stand-in for object storage.
        /// Answers `HEAD` (size) and ranged/full `GET` exactly as object_store's
        /// HTTP store expects. Returns the base URL (`http://127.0.0.1:PORT`);
        /// the accept loop runs on a detached thread until the test process
        /// exits. Binding happens before return, so the listen backlog absorbs
        /// any connect that races the accept loop.
        fn serve_bytes_over_http(body: Vec<u8>) -> String {
            use std::io::{BufRead, BufReader, Write};
            use std::net::TcpListener;
            use std::sync::Arc;

            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
            let addr = listener.local_addr().unwrap();
            let body = Arc::new(body);
            std::thread::spawn(move || {
                for stream in listener.incoming() {
                    let Ok(mut stream) = stream else { continue };
                    let body = Arc::clone(&body);
                    std::thread::spawn(move || {
                        let peer = stream.try_clone().unwrap();
                        let mut reader = BufReader::new(peer);
                        let size = body.len() as u64;
                        // One connection may carry several keep-alive requests.
                        loop {
                            let mut request_line = String::new();
                            match reader.read_line(&mut request_line) {
                                Ok(0) | Err(_) => break, // client closed
                                Ok(_) => {}
                            }
                            let mut parts = request_line.split_whitespace();
                            let method = parts.next().unwrap_or("").to_string();
                            if method.is_empty() {
                                break;
                            }
                            // Consume headers; only Range matters.
                            let mut range: Option<(u64, u64)> = None;
                            loop {
                                let mut header = String::new();
                                if reader.read_line(&mut header).unwrap_or(0) == 0 {
                                    break;
                                }
                                if header == "\r\n" || header == "\n" {
                                    break;
                                }
                                let lower = header.to_ascii_lowercase();
                                let Some(spec) = lower
                                    .strip_prefix("range:")
                                    .and_then(|v| v.trim().strip_prefix("bytes="))
                                else {
                                    continue;
                                };
                                let spec = spec.split(',').next().unwrap_or("").trim();
                                let (a, b) = spec.split_once('-').unwrap_or((spec, ""));
                                let (start, end) = if a.is_empty() {
                                    // Suffix range: the last N bytes.
                                    let n: u64 = b.trim().parse().unwrap_or(0);
                                    (size.saturating_sub(n), size.saturating_sub(1))
                                } else {
                                    let start = a.trim().parse().unwrap_or(0);
                                    let end = if b.trim().is_empty() {
                                        size.saturating_sub(1)
                                    } else {
                                        b.trim().parse().unwrap_or(size - 1)
                                    };
                                    (start, end.min(size.saturating_sub(1)))
                                };
                                range = Some((start, end));
                            }
                            let response: Vec<u8> = match (method.as_str(), range) {
                                ("HEAD", _) => format!(
                                    "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n\
                                     Accept-Ranges: bytes\r\nContent-Length: {size}\r\n\r\n"
                                )
                                .into_bytes(),
                                ("GET", Some((start, end))) => {
                                    let slice = &body[start as usize..=end as usize];
                                    let mut resp = format!(
                                        "HTTP/1.1 206 Partial Content\r\n\
                                         Content-Type: application/octet-stream\r\n\
                                         Accept-Ranges: bytes\r\n\
                                         Content-Range: bytes {start}-{end}/{size}\r\n\
                                         Content-Length: {}\r\n\r\n",
                                        slice.len()
                                    )
                                    .into_bytes();
                                    resp.extend_from_slice(slice);
                                    resp
                                }
                                ("GET", None) => {
                                    let mut resp = format!(
                                        "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n\
                                         Accept-Ranges: bytes\r\nContent-Length: {size}\r\n\r\n"
                                    )
                                    .into_bytes();
                                    resp.extend_from_slice(&body);
                                    resp
                                }
                                _ => {
                                    b"HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n"
                                        .to_vec()
                                }
                            };
                            if stream.write_all(&response).is_err() {
                                break;
                            }
                            let _ = stream.flush();
                        }
                    });
                }
            });
            format!("http://{addr}")
        }

        /// #262 end-to-end guard: a full conversion from an `http://` input must
        /// succeed and match the local conversion. Without `allow_http` on the
        /// store the `http://` input builder-errors immediately, so this test
        /// fails the moment that regresses — no network, no credentials.
        #[test]
        fn remote_http_convert_matches_local() {
            let geoms = synthetic_geometries();
            let tin = tempfile::NamedTempFile::new().unwrap();
            write_input(tin.path(), &geoms, false, None);
            let opts = ConvertOptions::default();

            let tout_local = tempfile::NamedTempFile::new().unwrap();
            let report_local = convert_to_overviews(tin.path(), tout_local.path(), &opts).unwrap();

            let base = serve_bytes_over_http(std::fs::read(tin.path()).unwrap());
            let url = format!("{base}/in.parquet");
            let source = InputSource::from_str_input(&url).unwrap();
            assert!(source.is_remote(), "http:// input must be remote");

            let tout_remote = tempfile::NamedTempFile::new().unwrap();
            let report_remote =
                convert_to_overviews_source(&source, tout_remote.path(), &opts).unwrap();

            assert_eq!(report_remote.input_features, report_local.input_features);
            assert_eq!(
                read_all_ids(&OverviewReader::open(tout_remote.path()).unwrap()),
                read_all_ids(&OverviewReader::open(tout_local.path()).unwrap()),
            );
            let stats = report_remote
                .remote_fetch
                .expect("http input reports fetch stats");
            assert!(
                stats.bytes_fetched > 0 && stats.requests > 0,
                "http conversion moved bytes: {stats:?}"
            );
        }

        /// A URL with an unsupported scheme surfaces a helpful error through
        /// the public `convert_to_overviews` path.
        #[test]
        fn unsupported_scheme_errors_through_convert() {
            let tout = tempfile::NamedTempFile::new().unwrap();
            let err = convert_to_overviews(
                Path::new("ftp://example.com/x.parquet"),
                tout.path(),
                &ConvertOptions::default(),
            )
            .unwrap_err();
            assert!(matches!(err, ConvertError::Input(_)), "got: {err}");
            assert!(err.to_string().contains("s3://"), "helpful message: {err}");
        }

        /// Network integration test against the bench bucket (issue #210):
        /// a full remote city extract must move only a fraction of the
        /// object's bytes. Skips (passing trivially, loudly) when
        /// credentials or network are unavailable — CI has neither.
        ///
        /// Locally: `AWS_PROFILE=<profile> AWS_REGION=us-east-2 cargo test
        /// --features remote remote_s3_city_extract -- --nocapture`
        #[test]
        fn remote_s3_city_extract_integration() {
            // gpio-optimized (Hilbert-sorted, bbox covering, 20k-row row
            // groups) copy of the NYC corpus input; row-group granularity
            // bounds the minimum fetch, so finer groups mean bigger savings.
            const URL: &str = "s3://tylertoo-bench/corpus/points-nyc-medium.rg20k.parquet";
            let source = match InputSource::from_str_input(URL) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!(
                        "SKIP remote_s3_city_extract_integration (no credentials/network): {e}"
                    );
                    return;
                }
            };
            let tout = tempfile::NamedTempFile::new().unwrap();
            // A ~1 km neighborhood window inside the NYC dataset (the input
            // is Hilbert-sorted, so a small window prunes most row groups).
            // Default (streaming) pipeline: its per-pass/per-level re-reads
            // must be absorbed by the column-chunk cache, so the byte
            // assertion below also guards the multi-pass refetch behavior.
            let opts = ConvertOptions {
                bbox: Some([-73.99, 40.72, -73.98, 40.73]),
                ..Default::default()
            };
            let report = match convert_to_overviews_source(&source, tout.path(), &opts) {
                Ok(r) => r,
                Err(e) => {
                    eprintln!("SKIP remote_s3_city_extract_integration (network flake?): {e}");
                    return;
                }
            };
            assert!(report.input_features > 0, "bbox should select features");
            assert!(
                report.row_groups_read < report.row_groups_total,
                "row-group pruning should fire on the Hilbert-sorted input \
                 ({}/{} read)",
                report.row_groups_read,
                report.row_groups_total
            );
            let stats = report.remote_fetch.expect("remote stats");
            assert!(
                stats.bytes_fetched * 4 < stats.object_size,
                "city extract should move <25% of the remote object even \
                 across streaming passes: {stats:?}"
            );
            eprintln!(
                "remote_s3_city_extract_integration: {} requests, {} of {} bytes ({:.2}%)",
                stats.requests,
                stats.bytes_fetched,
                stats.object_size,
                100.0 * stats.bytes_fetched as f64 / stats.object_size as f64
            );
        }
    }

    // --- empty coarse levels: auto-clamp (#211) ------------------------------

    /// Tiny (~10 m) squares spread far apart: they fail the polygon
    /// visibility gate (2 × GSD) at every coarse zoom, so only the canonical
    /// level keeps them.
    fn tiny_polygons(n: usize) -> Vec<Geometry<f64>> {
        (0..n)
            .map(|i| {
                let cx = -150.0 + (i % 10) as f64 * 3.0;
                let cy = -60.0 + (i / 10) as f64 * 1.5;
                let h = 5e-5;
                let ext = LineString::from(vec![
                    (cx - h, cy - h),
                    (cx + h, cy - h),
                    (cx + h, cy + h),
                    (cx - h, cy + h),
                    (cx - h, cy - h),
                ]);
                Geometry::Polygon(Polygon::new(ext, vec![]))
            })
            .collect()
    }

    /// Convert `tiny_polygons` over z0..z4 and assert the pyramid is clamped
    /// to the canonical level, with the skipped planned levels recorded.
    fn assert_clamped_pyramid(mode: Mode, streaming: bool) {
        let geoms = tiny_polygons(20);
        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            mode,
            levels: LevelPlan::ZoomRange {
                min_zoom: 0,
                max_zoom: 4,
            },
            streaming,
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();

        // Only the canonical level survives; the pyramid clamps to it.
        assert_eq!(report.levels.len(), 1, "expected a single written level");
        assert_eq!(report.levels[0].level, 0);
        assert_eq!(report.levels[0].zoom, Some(4));
        assert_eq!(report.levels[0].feature_count, geoms.len());
        assert_eq!(report.total_rows, geoms.len());

        // The skipped planned levels are recorded coarse→fine with their
        // planned zoom and a positive GSD.
        let skipped: Vec<(usize, Option<u8>)> = report
            .skipped_empty_levels
            .iter()
            .map(|s| (s.planned_level, s.zoom))
            .collect();
        assert_eq!(
            skipped,
            vec![(0, Some(0)), (1, Some(1)), (2, Some(2)), (3, Some(3))]
        );
        assert!(report.skipped_empty_levels.iter().all(|s| s.gsd > 0.0));

        // The clamped file is valid, readable, and exportable: the PMTiles
        // header starts at the clamped (canonical) zoom.
        let vr = validate_file(tout.path()).unwrap();
        assert!(
            vr.is_valid(),
            "failures: {:?}",
            vr.failures().collect::<Vec<_>>()
        );
        let reader = OverviewReader::open(tout.path()).unwrap();
        assert_eq!(reader.num_levels(), 1);
        let tpm = tempfile::NamedTempFile::new().unwrap();
        let export = crate::overview::export::export_pmtiles(
            tout.path(),
            tpm.path(),
            &crate::overview::export::ExportOptions::default(),
        )
        .unwrap();
        assert_eq!(export.min_zoom, 4);
        assert_eq!(export.max_zoom, 4);
    }

    #[test]
    fn empty_coarse_levels_clamped_duplicating_memory() {
        assert_clamped_pyramid(Mode::Duplicating, false);
    }

    #[test]
    fn empty_coarse_levels_clamped_duplicating_streaming() {
        assert_clamped_pyramid(Mode::Duplicating, true);
    }

    #[test]
    fn empty_coarse_levels_clamped_partitioning_memory() {
        assert_clamped_pyramid(Mode::Partitioning, false);
    }

    #[test]
    fn empty_coarse_levels_clamped_partitioning_streaming() {
        assert_clamped_pyramid(Mode::Partitioning, true);
    }

    /// The degenerate extreme — NO level has any rows (empty input) — must
    /// remain a hard, actionable error in both pipelines.
    #[test]
    fn all_levels_empty_is_hard_error() {
        for streaming in [false, true] {
            let tin = tempfile::NamedTempFile::new().unwrap();
            let tout = tempfile::NamedTempFile::new().unwrap();
            write_input(tin.path(), &[], false, None);
            let opts = ConvertOptions {
                mode: Mode::Duplicating,
                levels: LevelPlan::ZoomRange {
                    min_zoom: 0,
                    max_zoom: 3,
                },
                streaming,
                ..Default::default()
            };
            let err = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap_err();
            assert!(
                matches!(err, ConvertError::NoData),
                "streaming={streaming}: expected NoData, got {err:?}"
            );
        }
    }

    /// #211 regression: a feature can pass the assign visibility gate (huge
    /// bbox) yet be dropped by simplification at write time (degenerate
    /// sliver). The streaming pass 2 must skip the now-empty level instead of
    /// failing the whole conversion with `EmptyLevel`.
    #[test]
    fn write_time_empty_level_skipped_streaming() {
        let mut geoms = tiny_polygons(8);
        // Pathological feature: a MultiPolygon of two ~10 m squares 160°
        // apart. Its whole-feature bbox diagonal passes the assign visibility
        // gate at every zoom, but each PART is far below the per-level
        // simplify tolerance, so `simplify_for_level` drops the feature at
        // every non-canonical level.
        let square = |cx: f64, cy: f64| {
            let h = 5e-5;
            Polygon::new(
                LineString::from(vec![
                    (cx - h, cy - h),
                    (cx + h, cy - h),
                    (cx + h, cy + h),
                    (cx - h, cy + h),
                    (cx - h, cy - h),
                ]),
                vec![],
            )
        };
        geoms.push(Geometry::MultiPolygon(geo::MultiPolygon::new(vec![
            square(-80.0, 10.0),
            square(80.0, 30.0),
        ])));

        let tin = tempfile::NamedTempFile::new().unwrap();
        let tout = tempfile::NamedTempFile::new().unwrap();
        write_input(tin.path(), &geoms, false, None);

        let opts = ConvertOptions {
            mode: Mode::Duplicating,
            levels: LevelPlan::ZoomRange {
                min_zoom: 0,
                max_zoom: 3,
            },
            streaming: true,
            ..Default::default()
        };
        let report = convert_to_overviews(tin.path(), tout.path(), &opts).unwrap();

        // Levels z0..z2 each contained only the sliver, which simplification
        // dropped: they are skipped at write time and the pyramid clamps to
        // the canonical level.
        assert_eq!(report.levels.len(), 1);
        assert_eq!(report.levels[0].level, 0);
        assert_eq!(report.levels[0].zoom, Some(3));
        assert_eq!(report.levels[0].feature_count, geoms.len());
        assert_eq!(
            report
                .skipped_empty_levels
                .iter()
                .map(|s| s.planned_level)
                .collect::<Vec<_>>(),
            vec![0, 1, 2]
        );

        let vr = validate_file(tout.path()).unwrap();
        assert!(
            vr.is_valid(),
            "failures: {:?}",
            vr.failures().collect::<Vec<_>>()
        );
        let reader = OverviewReader::open(tout.path()).unwrap();
        assert_eq!(reader.num_levels(), 1);
    }
}