fsqlite-vdbe 0.3.9

Virtual database engine bytecode interpreter
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
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
36486
36487
36488
36489
36490
36491
36492
36493
36494
36495
36496
36497
36498
36499
36500
36501
36502
36503
36504
36505
36506
36507
36508
36509
36510
36511
36512
36513
36514
36515
36516
36517
36518
36519
36520
36521
36522
36523
36524
36525
36526
36527
36528
36529
36530
36531
36532
36533
36534
36535
36536
36537
36538
36539
36540
36541
36542
36543
36544
36545
36546
36547
36548
36549
36550
36551
36552
36553
36554
36555
36556
36557
36558
36559
36560
36561
36562
36563
36564
36565
36566
36567
36568
36569
36570
36571
36572
36573
36574
36575
36576
36577
36578
36579
36580
36581
36582
36583
36584
36585
36586
36587
36588
36589
36590
36591
36592
36593
36594
36595
36596
36597
36598
36599
36600
36601
36602
36603
36604
36605
36606
36607
36608
36609
36610
36611
36612
36613
36614
36615
36616
36617
36618
36619
36620
36621
36622
36623
36624
36625
36626
36627
36628
36629
36630
36631
36632
36633
36634
36635
36636
36637
36638
36639
36640
36641
36642
36643
36644
36645
36646
36647
36648
36649
36650
36651
36652
36653
36654
36655
36656
36657
36658
36659
36660
36661
36662
36663
36664
36665
36666
36667
36668
36669
36670
36671
36672
36673
36674
36675
36676
36677
36678
36679
36680
36681
36682
36683
36684
36685
36686
36687
36688
36689
36690
36691
36692
36693
36694
36695
36696
36697
36698
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708
36709
36710
36711
36712
36713
36714
36715
36716
36717
36718
36719
36720
36721
36722
36723
36724
36725
36726
36727
36728
36729
36730
36731
36732
36733
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
36749
36750
36751
36752
36753
36754
36755
36756
36757
36758
36759
36760
36761
36762
36763
36764
36765
36766
36767
36768
36769
36770
36771
36772
36773
36774
36775
36776
36777
36778
36779
36780
36781
36782
36783
36784
36785
36786
36787
36788
36789
36790
36791
36792
36793
36794
36795
36796
36797
36798
36799
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812
36813
36814
36815
36816
36817
36818
36819
36820
36821
36822
36823
36824
36825
36826
36827
36828
36829
36830
36831
36832
36833
36834
36835
36836
36837
36838
36839
36840
36841
36842
36843
36844
36845
36846
36847
36848
36849
36850
36851
36852
36853
36854
36855
36856
36857
36858
36859
36860
36861
36862
36863
36864
36865
36866
36867
36868
36869
36870
36871
36872
36873
36874
36875
36876
36877
36878
36879
36880
36881
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903
36904
36905
36906
36907
36908
36909
36910
36911
36912
36913
36914
36915
36916
36917
36918
36919
36920
36921
36922
36923
36924
36925
36926
36927
36928
36929
36930
36931
36932
36933
36934
36935
36936
36937
36938
36939
36940
36941
36942
36943
36944
36945
36946
36947
36948
36949
36950
36951
36952
36953
36954
36955
36956
36957
36958
36959
36960
36961
36962
36963
36964
36965
36966
36967
36968
36969
36970
36971
36972
36973
36974
36975
36976
36977
36978
36979
36980
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
36996
36997
36998
36999
37000
37001
37002
37003
37004
37005
37006
37007
37008
37009
37010
37011
37012
37013
37014
37015
37016
37017
37018
37019
37020
37021
37022
37023
37024
37025
37026
37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
37042
37043
37044
37045
37046
37047
37048
37049
37050
37051
37052
37053
37054
37055
37056
37057
37058
37059
37060
37061
37062
37063
37064
37065
37066
37067
37068
37069
37070
37071
37072
37073
37074
37075
37076
37077
37078
37079
37080
37081
37082
37083
37084
37085
37086
37087
37088
37089
37090
37091
37092
37093
37094
37095
37096
37097
37098
37099
37100
37101
37102
37103
37104
37105
37106
37107
37108
37109
37110
37111
37112
37113
37114
37115
37116
37117
37118
37119
37120
37121
37122
37123
37124
37125
37126
37127
37128
37129
37130
37131
37132
37133
37134
37135
37136
37137
37138
37139
37140
37141
37142
37143
37144
37145
37146
37147
37148
37149
37150
37151
37152
37153
37154
37155
37156
37157
37158
37159
37160
37161
37162
37163
37164
37165
37166
37167
37168
37169
37170
37171
37172
37173
37174
37175
37176
37177
37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
37195
37196
37197
37198
37199
37200
37201
37202
37203
37204
37205
37206
37207
37208
37209
37210
37211
37212
37213
37214
37215
37216
37217
37218
37219
37220
37221
37222
37223
37224
37225
37226
37227
37228
37229
37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
37253
37254
37255
37256
37257
37258
37259
37260
37261
37262
37263
37264
37265
37266
37267
37268
37269
37270
37271
37272
37273
37274
37275
37276
37277
37278
37279
37280
37281
37282
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
37387
37388
37389
37390
37391
37392
37393
37394
37395
37396
37397
37398
37399
37400
37401
37402
37403
37404
37405
37406
37407
37408
37409
37410
37411
37412
37413
37414
37415
37416
37417
37418
37419
37420
37421
37422
37423
37424
37425
37426
37427
37428
37429
37430
37431
37432
37433
37434
37435
37436
37437
37438
37439
37440
37441
37442
37443
37444
37445
37446
37447
37448
37449
37450
37451
37452
37453
37454
37455
37456
37457
37458
37459
37460
37461
37462
37463
37464
37465
37466
37467
37468
37469
37470
37471
37472
37473
37474
37475
37476
37477
37478
37479
37480
37481
37482
37483
37484
37485
37486
37487
37488
37489
37490
37491
37492
37493
37494
37495
37496
37497
37498
37499
37500
37501
37502
37503
37504
37505
37506
37507
37508
37509
37510
37511
37512
37513
37514
37515
37516
37517
37518
37519
37520
37521
37522
37523
37524
37525
37526
37527
37528
37529
37530
37531
37532
37533
37534
37535
37536
37537
37538
37539
37540
37541
37542
37543
37544
37545
37546
37547
37548
37549
37550
37551
37552
37553
37554
37555
37556
37557
37558
37559
37560
37561
37562
37563
37564
37565
37566
37567
37568
37569
37570
37571
37572
37573
37574
37575
37576
37577
37578
37579
37580
37581
37582
37583
37584
37585
37586
37587
37588
37589
37590
37591
37592
37593
37594
37595
37596
37597
37598
37599
37600
37601
37602
37603
37604
37605
37606
37607
37608
37609
37610
37611
37612
37613
37614
37615
37616
37617
37618
37619
37620
37621
37622
37623
37624
37625
37626
37627
37628
37629
37630
37631
37632
37633
37634
37635
37636
37637
37638
37639
37640
37641
37642
37643
37644
37645
37646
37647
37648
37649
37650
37651
37652
37653
37654
37655
37656
37657
37658
37659
37660
37661
37662
37663
37664
37665
37666
37667
37668
37669
37670
37671
37672
37673
37674
37675
37676
37677
37678
37679
37680
37681
37682
37683
37684
37685
37686
37687
37688
37689
37690
37691
37692
37693
37694
37695
37696
37697
37698
37699
37700
37701
37702
37703
37704
37705
37706
37707
37708
37709
37710
37711
37712
37713
37714
37715
37716
37717
37718
37719
37720
37721
37722
37723
37724
37725
37726
37727
37728
37729
37730
37731
37732
37733
37734
37735
37736
37737
37738
37739
37740
37741
37742
37743
37744
37745
37746
37747
37748
37749
37750
37751
37752
37753
37754
37755
37756
37757
37758
37759
37760
37761
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806
37807
37808
37809
37810
37811
37812
37813
37814
37815
37816
37817
37818
37819
37820
37821
37822
37823
37824
37825
37826
37827
37828
37829
37830
37831
37832
37833
37834
37835
37836
37837
37838
37839
37840
37841
37842
37843
37844
37845
37846
37847
37848
37849
37850
37851
37852
37853
37854
37855
37856
37857
37858
37859
37860
37861
37862
37863
37864
37865
37866
37867
37868
37869
37870
37871
37872
37873
37874
37875
37876
37877
37878
37879
37880
37881
37882
37883
37884
37885
37886
37887
37888
37889
37890
37891
37892
37893
37894
37895
37896
37897
37898
37899
37900
37901
37902
37903
37904
37905
37906
37907
37908
37909
37910
37911
37912
37913
37914
37915
37916
37917
37918
37919
37920
37921
37922
37923
37924
37925
37926
37927
37928
37929
37930
37931
37932
37933
37934
37935
37936
37937
37938
37939
37940
37941
37942
37943
37944
37945
37946
37947
37948
37949
37950
37951
37952
37953
37954
37955
37956
37957
37958
37959
37960
37961
37962
37963
37964
37965
37966
37967
37968
37969
37970
37971
37972
37973
37974
37975
37976
37977
37978
37979
37980
37981
37982
37983
37984
37985
37986
37987
37988
37989
37990
37991
37992
37993
37994
37995
37996
37997
37998
37999
38000
38001
38002
38003
38004
38005
38006
38007
38008
38009
38010
38011
38012
38013
38014
38015
38016
38017
38018
38019
38020
38021
38022
38023
38024
38025
38026
38027
38028
38029
38030
38031
38032
38033
38034
38035
38036
38037
38038
38039
38040
38041
38042
38043
38044
38045
38046
38047
38048
38049
38050
38051
38052
38053
38054
38055
38056
38057
38058
38059
38060
38061
38062
38063
38064
38065
38066
38067
38068
38069
38070
38071
38072
38073
38074
38075
38076
38077
38078
38079
38080
38081
38082
38083
38084
38085
38086
38087
38088
38089
38090
38091
38092
38093
38094
38095
38096
38097
38098
38099
38100
38101
38102
38103
38104
38105
38106
38107
38108
38109
38110
38111
38112
38113
38114
38115
38116
38117
38118
38119
38120
38121
38122
38123
38124
38125
38126
38127
38128
38129
38130
38131
38132
38133
38134
38135
38136
38137
38138
38139
38140
38141
38142
38143
38144
38145
38146
38147
38148
38149
38150
38151
38152
38153
38154
38155
38156
38157
38158
38159
38160
38161
38162
38163
38164
38165
38166
38167
38168
38169
38170
38171
38172
38173
38174
38175
38176
38177
38178
38179
38180
38181
38182
38183
38184
38185
38186
38187
38188
38189
38190
38191
38192
38193
38194
38195
38196
38197
38198
38199
38200
38201
38202
38203
38204
38205
38206
38207
38208
38209
38210
38211
38212
38213
38214
38215
38216
38217
38218
38219
38220
38221
38222
38223
38224
38225
38226
38227
38228
38229
38230
38231
38232
38233
38234
38235
38236
38237
38238
38239
38240
38241
38242
38243
38244
38245
38246
38247
38248
38249
38250
38251
38252
38253
38254
38255
38256
38257
38258
38259
38260
38261
38262
38263
38264
38265
38266
38267
38268
38269
38270
38271
38272
38273
38274
38275
38276
38277
38278
38279
38280
38281
38282
38283
38284
38285
38286
38287
38288
38289
38290
38291
38292
38293
38294
38295
38296
38297
38298
38299
38300
38301
38302
38303
38304
38305
38306
38307
38308
38309
38310
38311
38312
38313
38314
38315
38316
38317
38318
38319
38320
38321
38322
38323
38324
38325
38326
38327
38328
38329
38330
38331
38332
38333
38334
38335
38336
38337
38338
38339
38340
38341
38342
38343
38344
38345
38346
38347
38348
38349
38350
38351
38352
38353
38354
38355
38356
38357
38358
38359
38360
38361
38362
38363
38364
38365
38366
38367
38368
38369
38370
38371
38372
38373
38374
38375
38376
38377
38378
38379
38380
38381
38382
38383
38384
38385
38386
38387
38388
38389
38390
38391
38392
38393
38394
38395
38396
38397
38398
38399
38400
38401
38402
38403
38404
38405
38406
38407
38408
38409
38410
38411
38412
38413
38414
38415
38416
38417
38418
38419
38420
38421
38422
38423
38424
38425
38426
38427
38428
38429
38430
38431
38432
38433
38434
38435
38436
38437
38438
38439
38440
38441
38442
38443
38444
38445
38446
38447
38448
38449
38450
38451
38452
38453
38454
38455
38456
38457
38458
38459
38460
38461
38462
38463
38464
38465
38466
38467
38468
38469
38470
38471
38472
38473
38474
38475
38476
38477
38478
38479
38480
38481
38482
38483
38484
38485
38486
38487
38488
38489
38490
38491
38492
38493
38494
38495
38496
38497
38498
38499
38500
38501
38502
38503
38504
38505
38506
38507
38508
38509
38510
38511
38512
38513
38514
38515
38516
38517
38518
38519
38520
38521
38522
38523
38524
38525
38526
38527
38528
38529
38530
38531
38532
38533
38534
38535
38536
38537
38538
38539
38540
38541
38542
38543
38544
38545
38546
38547
38548
38549
38550
38551
38552
38553
38554
38555
38556
38557
38558
38559
38560
38561
38562
38563
38564
38565
38566
38567
38568
38569
38570
38571
38572
38573
38574
38575
38576
38577
38578
38579
38580
38581
38582
38583
38584
38585
38586
38587
38588
38589
38590
38591
38592
38593
38594
38595
38596
38597
38598
38599
38600
38601
38602
38603
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
38619
38620
38621
38622
38623
38624
38625
38626
38627
38628
38629
38630
38631
38632
38633
38634
38635
38636
38637
38638
38639
38640
38641
38642
38643
38644
38645
38646
38647
38648
38649
38650
38651
38652
38653
38654
38655
38656
38657
38658
38659
38660
38661
38662
38663
38664
38665
38666
38667
38668
38669
38670
38671
38672
38673
38674
38675
38676
38677
38678
38679
38680
38681
38682
38683
38684
38685
38686
38687
38688
38689
38690
38691
38692
38693
38694
38695
38696
38697
38698
38699
38700
38701
38702
38703
38704
38705
38706
38707
38708
38709
38710
38711
38712
38713
38714
38715
38716
38717
38718
38719
38720
38721
38722
38723
38724
38725
38726
38727
38728
38729
38730
38731
38732
38733
38734
38735
38736
38737
38738
38739
38740
38741
38742
38743
38744
38745
38746
38747
38748
38749
38750
38751
38752
38753
38754
38755
38756
38757
38758
38759
38760
38761
38762
38763
38764
38765
38766
38767
38768
38769
38770
38771
38772
38773
38774
38775
38776
38777
38778
38779
38780
38781
38782
38783
38784
38785
38786
38787
38788
38789
38790
38791
38792
38793
38794
38795
38796
38797
38798
38799
38800
38801
38802
38803
38804
38805
38806
38807
38808
38809
38810
38811
38812
38813
38814
38815
38816
38817
38818
38819
38820
38821
38822
38823
38824
38825
38826
38827
38828
38829
38830
38831
38832
38833
38834
38835
38836
38837
38838
38839
38840
38841
38842
38843
38844
38845
38846
38847
38848
38849
38850
38851
38852
38853
38854
38855
38856
38857
38858
38859
38860
38861
38862
38863
38864
38865
38866
38867
38868
38869
38870
38871
38872
38873
38874
38875
38876
38877
38878
38879
38880
38881
38882
38883
38884
38885
38886
38887
38888
38889
38890
38891
38892
38893
38894
38895
38896
38897
38898
38899
38900
38901
38902
38903
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937
38938
38939
38940
38941
38942
38943
38944
38945
38946
38947
38948
38949
38950
38951
38952
38953
38954
38955
38956
38957
38958
38959
38960
38961
38962
38963
38964
38965
38966
38967
38968
38969
38970
38971
38972
38973
38974
38975
38976
38977
38978
38979
38980
38981
38982
38983
38984
38985
38986
38987
38988
38989
38990
38991
38992
38993
38994
38995
38996
38997
38998
38999
39000
39001
39002
39003
39004
39005
39006
39007
39008
39009
39010
39011
39012
39013
39014
39015
39016
39017
39018
39019
39020
39021
39022
39023
39024
39025
39026
39027
39028
39029
39030
39031
39032
39033
39034
39035
39036
39037
39038
39039
39040
39041
39042
39043
39044
39045
39046
39047
39048
39049
39050
39051
39052
39053
39054
39055
39056
39057
39058
39059
39060
39061
39062
39063
39064
39065
39066
39067
39068
39069
39070
39071
39072
39073
39074
39075
39076
39077
39078
39079
39080
39081
39082
39083
39084
39085
39086
39087
39088
39089
39090
39091
39092
39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105
39106
39107
39108
39109
39110
39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123
39124
39125
39126
39127
39128
39129
39130
39131
39132
39133
39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
39144
39145
39146
39147
39148
39149
39150
39151
39152
39153
39154
39155
39156
39157
39158
39159
39160
39161
39162
39163
39164
39165
39166
39167
39168
39169
39170
39171
39172
39173
39174
39175
39176
39177
39178
39179
39180
39181
39182
39183
39184
39185
39186
39187
39188
39189
39190
39191
39192
39193
39194
39195
39196
39197
39198
39199
39200
39201
39202
39203
39204
39205
39206
39207
39208
39209
39210
39211
39212
39213
39214
39215
39216
39217
39218
39219
39220
39221
39222
39223
39224
39225
39226
39227
39228
39229
39230
39231
39232
39233
39234
39235
39236
39237
39238
39239
39240
39241
39242
39243
39244
39245
39246
39247
39248
39249
39250
39251
39252
39253
39254
39255
39256
39257
39258
39259
39260
39261
39262
39263
39264
39265
39266
39267
39268
39269
39270
39271
39272
39273
39274
39275
39276
39277
39278
39279
39280
39281
39282
39283
39284
39285
39286
39287
39288
39289
39290
39291
39292
39293
39294
39295
39296
39297
39298
39299
39300
39301
39302
39303
39304
39305
39306
39307
39308
39309
39310
39311
39312
39313
39314
39315
39316
39317
39318
39319
39320
39321
39322
39323
39324
39325
39326
39327
39328
39329
39330
39331
39332
39333
39334
39335
39336
39337
39338
39339
39340
39341
39342
39343
39344
39345
39346
39347
39348
39349
39350
39351
39352
39353
39354
39355
39356
39357
39358
39359
39360
39361
39362
39363
39364
39365
39366
39367
39368
39369
39370
39371
39372
39373
39374
39375
39376
39377
39378
39379
39380
39381
39382
39383
39384
39385
39386
39387
39388
39389
39390
39391
39392
39393
39394
39395
39396
39397
39398
39399
39400
39401
39402
39403
39404
39405
39406
39407
39408
39409
39410
39411
39412
39413
39414
39415
39416
39417
39418
39419
39420
39421
39422
39423
39424
39425
39426
39427
39428
39429
39430
39431
39432
39433
39434
39435
39436
39437
39438
39439
39440
39441
39442
39443
39444
39445
39446
39447
39448
39449
39450
39451
39452
39453
39454
39455
39456
39457
39458
39459
39460
39461
39462
39463
39464
39465
39466
39467
39468
39469
39470
39471
39472
39473
39474
39475
39476
39477
39478
39479
39480
39481
39482
39483
39484
39485
39486
39487
39488
39489
39490
39491
39492
39493
39494
39495
39496
39497
39498
39499
39500
39501
39502
39503
39504
39505
39506
39507
39508
39509
39510
39511
39512
39513
39514
39515
39516
39517
39518
39519
39520
39521
39522
39523
39524
39525
39526
39527
39528
39529
39530
39531
39532
39533
39534
39535
39536
39537
39538
39539
39540
39541
39542
39543
39544
39545
39546
39547
39548
39549
39550
39551
39552
39553
39554
39555
39556
39557
39558
39559
39560
39561
39562
39563
39564
39565
39566
39567
39568
39569
39570
39571
39572
39573
39574
39575
39576
39577
39578
39579
39580
39581
39582
39583
39584
39585
39586
39587
39588
39589
39590
39591
39592
39593
39594
39595
39596
39597
39598
39599
39600
39601
39602
39603
39604
39605
39606
39607
39608
39609
39610
39611
39612
39613
39614
39615
39616
39617
39618
39619
39620
39621
39622
39623
39624
39625
39626
39627
39628
39629
39630
39631
39632
39633
39634
39635
39636
39637
39638
39639
39640
39641
39642
39643
39644
39645
39646
39647
39648
39649
39650
39651
39652
39653
39654
39655
39656
39657
39658
39659
39660
39661
39662
39663
39664
39665
39666
39667
39668
39669
39670
39671
39672
39673
39674
39675
39676
39677
39678
39679
39680
39681
39682
39683
39684
39685
39686
39687
39688
39689
39690
39691
39692
39693
39694
39695
39696
39697
39698
39699
39700
39701
39702
39703
39704
39705
39706
39707
39708
39709
39710
39711
39712
39713
39714
39715
39716
39717
39718
39719
39720
39721
39722
39723
39724
39725
39726
39727
39728
39729
39730
39731
39732
39733
39734
39735
39736
39737
39738
39739
39740
39741
39742
39743
39744
39745
39746
39747
39748
39749
39750
39751
39752
39753
39754
39755
39756
39757
39758
39759
39760
39761
39762
39763
39764
39765
39766
39767
39768
39769
39770
39771
39772
39773
39774
39775
39776
39777
39778
39779
39780
39781
39782
39783
39784
39785
39786
39787
39788
39789
39790
39791
39792
39793
39794
39795
39796
39797
39798
39799
39800
39801
39802
39803
39804
39805
39806
39807
39808
39809
39810
39811
39812
39813
39814
39815
39816
39817
39818
39819
39820
39821
39822
39823
39824
39825
39826
39827
39828
39829
39830
39831
39832
39833
39834
39835
39836
39837
39838
39839
39840
39841
39842
39843
39844
39845
39846
39847
39848
39849
39850
39851
39852
39853
39854
39855
39856
39857
39858
39859
39860
39861
39862
39863
39864
39865
39866
39867
39868
39869
39870
39871
39872
39873
39874
39875
39876
39877
39878
39879
39880
39881
39882
39883
39884
39885
39886
39887
39888
39889
39890
39891
39892
39893
39894
39895
39896
39897
39898
39899
39900
39901
39902
39903
39904
39905
39906
39907
39908
39909
39910
39911
39912
39913
39914
39915
39916
39917
39918
39919
39920
39921
39922
39923
39924
39925
39926
39927
39928
39929
39930
39931
39932
39933
39934
39935
39936
39937
39938
39939
39940
39941
39942
39943
39944
39945
39946
39947
39948
39949
39950
39951
39952
39953
39954
39955
39956
39957
39958
39959
39960
39961
39962
39963
39964
39965
39966
39967
39968
39969
39970
39971
39972
39973
39974
39975
39976
39977
39978
39979
39980
39981
39982
39983
39984
39985
39986
39987
39988
39989
39990
39991
39992
39993
39994
39995
39996
39997
39998
39999
40000
40001
40002
40003
40004
40005
40006
40007
40008
40009
40010
40011
40012
40013
40014
40015
40016
40017
40018
40019
40020
40021
40022
40023
40024
40025
40026
40027
40028
40029
40030
40031
40032
40033
40034
40035
40036
40037
40038
40039
40040
40041
40042
40043
40044
40045
40046
40047
40048
40049
40050
40051
40052
40053
40054
40055
40056
40057
40058
40059
40060
40061
40062
40063
40064
40065
40066
40067
40068
40069
40070
40071
40072
40073
40074
40075
40076
40077
40078
40079
40080
40081
40082
40083
40084
40085
40086
40087
40088
40089
40090
40091
40092
40093
40094
40095
40096
40097
40098
40099
40100
40101
40102
40103
40104
40105
40106
40107
40108
40109
40110
40111
40112
40113
40114
40115
40116
40117
40118
40119
40120
40121
40122
40123
40124
40125
40126
40127
40128
40129
40130
40131
40132
40133
40134
40135
40136
40137
40138
40139
40140
40141
40142
40143
40144
40145
40146
40147
40148
40149
40150
40151
40152
40153
40154
40155
40156
40157
40158
40159
40160
40161
40162
40163
40164
40165
40166
40167
40168
40169
40170
40171
40172
40173
40174
40175
40176
40177
40178
40179
40180
40181
40182
40183
40184
40185
40186
40187
40188
40189
40190
40191
40192
40193
40194
40195
40196
40197
40198
40199
40200
40201
40202
40203
40204
40205
40206
40207
40208
40209
40210
40211
40212
40213
40214
40215
40216
40217
40218
40219
40220
40221
40222
40223
40224
40225
40226
40227
40228
40229
40230
40231
40232
40233
40234
40235
40236
40237
40238
40239
40240
40241
40242
40243
40244
40245
40246
40247
40248
40249
40250
40251
40252
40253
40254
40255
40256
40257
40258
40259
40260
40261
40262
40263
40264
40265
40266
40267
40268
40269
40270
40271
40272
40273
40274
40275
40276
40277
40278
40279
40280
40281
40282
40283
40284
40285
40286
40287
40288
40289
40290
40291
40292
40293
40294
40295
40296
40297
40298
40299
40300
40301
40302
40303
40304
40305
40306
40307
40308
40309
40310
40311
40312
40313
40314
40315
40316
40317
40318
40319
40320
40321
40322
40323
40324
40325
40326
40327
40328
40329
40330
40331
40332
40333
40334
40335
40336
40337
40338
40339
40340
40341
40342
40343
40344
40345
40346
40347
40348
40349
40350
40351
40352
40353
40354
40355
40356
40357
40358
40359
40360
40361
40362
40363
40364
40365
40366
40367
40368
40369
40370
40371
40372
40373
40374
40375
40376
40377
40378
40379
40380
40381
40382
40383
40384
40385
40386
40387
40388
40389
40390
40391
40392
40393
40394
40395
40396
40397
40398
40399
40400
40401
40402
40403
40404
40405
40406
40407
40408
40409
40410
40411
40412
40413
40414
40415
40416
40417
40418
40419
40420
40421
40422
40423
40424
40425
40426
40427
40428
40429
40430
40431
40432
40433
40434
40435
40436
40437
40438
40439
40440
40441
40442
40443
40444
40445
40446
40447
40448
40449
40450
40451
40452
40453
40454
40455
40456
40457
40458
40459
40460
40461
40462
40463
40464
40465
40466
40467
40468
40469
40470
40471
40472
40473
40474
40475
40476
40477
40478
40479
40480
40481
40482
40483
40484
40485
40486
40487
40488
40489
40490
40491
40492
40493
40494
40495
40496
40497
40498
40499
40500
40501
40502
40503
40504
40505
40506
40507
40508
40509
40510
40511
40512
40513
40514
40515
40516
40517
40518
40519
40520
40521
40522
40523
40524
40525
40526
40527
40528
40529
40530
40531
40532
40533
40534
40535
40536
40537
40538
40539
40540
40541
40542
40543
40544
40545
40546
40547
40548
40549
40550
40551
40552
40553
40554
40555
40556
40557
40558
40559
40560
40561
40562
40563
40564
40565
40566
40567
40568
40569
40570
40571
40572
40573
40574
40575
40576
40577
40578
40579
40580
40581
40582
40583
40584
40585
40586
40587
40588
40589
40590
40591
40592
40593
40594
40595
40596
40597
40598
40599
40600
40601
40602
40603
40604
40605
40606
40607
40608
40609
40610
40611
40612
40613
40614
40615
40616
40617
40618
40619
40620
40621
40622
40623
40624
40625
40626
40627
40628
40629
40630
40631
40632
40633
40634
40635
40636
40637
40638
40639
40640
40641
40642
40643
40644
40645
40646
40647
40648
40649
40650
40651
40652
40653
40654
40655
40656
40657
40658
40659
40660
40661
40662
40663
40664
40665
40666
40667
40668
40669
40670
40671
40672
40673
40674
40675
40676
40677
40678
40679
40680
40681
40682
40683
40684
40685
40686
40687
40688
40689
40690
40691
40692
40693
40694
40695
40696
40697
40698
40699
40700
40701
40702
40703
40704
40705
40706
40707
40708
40709
40710
40711
40712
40713
40714
40715
40716
40717
40718
40719
40720
40721
40722
40723
40724
40725
40726
40727
40728
40729
40730
40731
40732
40733
40734
40735
40736
40737
40738
40739
40740
40741
40742
40743
40744
40745
40746
40747
40748
40749
40750
40751
40752
40753
40754
40755
40756
40757
40758
40759
40760
40761
40762
40763
40764
40765
40766
40767
40768
40769
40770
40771
40772
40773
40774
40775
40776
40777
40778
40779
40780
40781
40782
40783
40784
40785
40786
40787
40788
40789
40790
40791
40792
40793
40794
40795
40796
40797
40798
40799
40800
40801
40802
40803
40804
40805
40806
40807
40808
40809
40810
40811
40812
40813
40814
40815
40816
40817
40818
40819
40820
40821
40822
40823
40824
40825
40826
40827
40828
40829
40830
40831
40832
40833
40834
40835
40836
40837
40838
40839
40840
40841
40842
40843
40844
40845
40846
40847
40848
40849
40850
40851
40852
40853
40854
40855
40856
40857
40858
40859
40860
40861
40862
40863
40864
40865
40866
40867
40868
40869
40870
40871
40872
40873
40874
40875
40876
40877
40878
40879
40880
40881
40882
40883
40884
40885
40886
40887
40888
40889
40890
40891
40892
40893
40894
40895
40896
40897
40898
40899
40900
40901
40902
40903
40904
40905
40906
40907
40908
40909
40910
40911
40912
40913
40914
40915
40916
40917
40918
40919
40920
40921
40922
40923
40924
40925
40926
40927
40928
40929
40930
40931
40932
40933
40934
40935
40936
40937
40938
40939
40940
40941
40942
40943
40944
40945
40946
40947
40948
40949
40950
40951
40952
40953
40954
40955
40956
40957
40958
40959
40960
40961
40962
40963
40964
40965
40966
40967
40968
40969
40970
40971
40972
40973
40974
40975
40976
40977
40978
40979
40980
40981
40982
40983
40984
40985
40986
40987
40988
40989
40990
40991
40992
40993
40994
40995
40996
40997
40998
40999
41000
41001
41002
41003
41004
41005
41006
41007
41008
41009
41010
41011
41012
41013
41014
41015
41016
41017
41018
41019
41020
41021
41022
41023
41024
41025
41026
41027
41028
41029
41030
41031
41032
41033
41034
41035
41036
41037
41038
41039
41040
41041
41042
41043
41044
41045
41046
41047
41048
41049
41050
41051
41052
41053
41054
41055
41056
41057
41058
41059
41060
41061
41062
41063
41064
41065
41066
41067
41068
41069
41070
41071
41072
41073
41074
41075
41076
41077
41078
41079
41080
41081
41082
41083
41084
41085
41086
41087
41088
41089
41090
41091
41092
41093
41094
41095
41096
41097
41098
41099
41100
41101
41102
41103
41104
41105
41106
41107
41108
41109
41110
41111
41112
41113
41114
41115
41116
41117
41118
41119
41120
41121
41122
41123
41124
41125
41126
41127
41128
41129
41130
41131
41132
41133
41134
41135
41136
41137
41138
41139
41140
41141
41142
41143
41144
41145
41146
41147
41148
41149
41150
41151
41152
41153
41154
41155
41156
41157
41158
41159
41160
41161
41162
41163
41164
41165
41166
41167
41168
41169
41170
41171
41172
41173
41174
41175
41176
41177
41178
41179
41180
41181
41182
41183
41184
41185
41186
41187
41188
41189
41190
41191
41192
41193
41194
41195
41196
41197
41198
41199
41200
41201
41202
41203
41204
41205
41206
41207
41208
41209
41210
41211
41212
41213
41214
41215
41216
41217
41218
41219
41220
41221
41222
41223
41224
41225
41226
41227
41228
41229
41230
41231
41232
41233
41234
41235
41236
41237
41238
41239
41240
41241
41242
41243
41244
41245
41246
41247
41248
41249
41250
41251
41252
41253
41254
41255
41256
41257
41258
41259
41260
41261
41262
41263
41264
41265
41266
41267
41268
41269
41270
41271
41272
41273
41274
41275
41276
41277
41278
41279
41280
41281
41282
41283
41284
41285
41286
41287
41288
41289
41290
41291
41292
41293
41294
41295
41296
41297
41298
41299
41300
41301
41302
41303
41304
41305
41306
41307
41308
41309
41310
41311
41312
41313
41314
41315
41316
41317
41318
41319
41320
41321
41322
41323
41324
41325
41326
41327
41328
41329
41330
41331
41332
41333
41334
41335
41336
41337
41338
41339
41340
41341
41342
41343
41344
41345
41346
41347
41348
41349
41350
41351
41352
41353
41354
41355
41356
41357
41358
41359
41360
41361
41362
41363
41364
41365
41366
41367
41368
41369
41370
41371
41372
41373
41374
41375
41376
41377
41378
41379
41380
41381
41382
41383
41384
41385
41386
41387
41388
41389
41390
41391
41392
41393
41394
41395
41396
41397
41398
41399
41400
41401
41402
41403
41404
41405
41406
41407
41408
41409
41410
41411
41412
41413
41414
41415
41416
41417
41418
41419
41420
41421
41422
41423
41424
41425
41426
41427
41428
41429
41430
41431
41432
41433
41434
41435
41436
41437
41438
41439
41440
41441
41442
41443
41444
41445
41446
41447
41448
41449
41450
41451
41452
41453
41454
41455
41456
41457
41458
41459
41460
41461
41462
41463
41464
41465
41466
41467
41468
41469
41470
41471
41472
41473
41474
41475
41476
41477
41478
41479
41480
41481
41482
41483
41484
41485
41486
41487
41488
41489
41490
41491
41492
41493
41494
41495
41496
41497
41498
41499
41500
41501
41502
41503
41504
41505
41506
41507
41508
41509
41510
41511
41512
41513
41514
41515
41516
41517
41518
41519
41520
41521
41522
41523
41524
41525
41526
41527
41528
41529
41530
41531
41532
41533
41534
41535
41536
41537
41538
41539
41540
41541
41542
41543
41544
41545
41546
41547
41548
41549
41550
41551
41552
41553
41554
41555
41556
41557
41558
41559
41560
41561
41562
41563
41564
41565
41566
41567
41568
41569
41570
41571
41572
41573
41574
41575
41576
41577
41578
41579
41580
41581
41582
41583
41584
41585
41586
41587
41588
41589
41590
41591
41592
41593
41594
41595
41596
41597
41598
41599
41600
41601
41602
41603
41604
41605
41606
41607
41608
41609
41610
41611
41612
41613
41614
41615
41616
41617
41618
41619
41620
41621
41622
41623
41624
41625
41626
41627
41628
41629
41630
41631
41632
41633
41634
41635
41636
41637
41638
41639
41640
41641
41642
41643
41644
41645
41646
41647
41648
41649
41650
41651
41652
41653
41654
41655
41656
41657
41658
41659
41660
41661
41662
41663
41664
41665
41666
41667
41668
41669
41670
41671
41672
41673
41674
41675
41676
41677
41678
41679
41680
41681
41682
41683
41684
41685
41686
41687
41688
41689
41690
41691
41692
41693
41694
41695
41696
41697
41698
41699
41700
41701
41702
41703
41704
41705
41706
41707
41708
41709
41710
41711
41712
41713
41714
41715
41716
41717
41718
41719
41720
41721
41722
41723
41724
41725
41726
41727
41728
41729
41730
41731
41732
41733
41734
41735
41736
41737
41738
41739
41740
41741
41742
41743
41744
41745
41746
41747
41748
41749
41750
41751
41752
41753
41754
41755
41756
41757
41758
41759
41760
41761
41762
41763
41764
41765
41766
41767
41768
41769
41770
41771
41772
41773
41774
41775
41776
41777
41778
41779
41780
41781
41782
41783
41784
41785
41786
41787
41788
41789
41790
41791
41792
41793
41794
41795
41796
41797
41798
41799
41800
41801
41802
41803
41804
41805
41806
41807
41808
41809
41810
41811
41812
41813
41814
41815
41816
41817
41818
41819
41820
41821
41822
41823
41824
41825
41826
41827
41828
41829
41830
41831
41832
41833
41834
41835
41836
41837
41838
41839
41840
41841
41842
41843
41844
41845
41846
41847
41848
41849
41850
41851
41852
41853
41854
41855
41856
41857
41858
41859
41860
41861
41862
41863
41864
41865
41866
41867
41868
41869
41870
41871
41872
41873
41874
41875
41876
41877
41878
41879
41880
41881
41882
41883
41884
41885
41886
41887
41888
41889
41890
41891
41892
41893
41894
41895
41896
41897
41898
41899
41900
41901
41902
41903
41904
41905
41906
41907
41908
41909
41910
41911
41912
41913
41914
41915
41916
41917
41918
41919
41920
41921
41922
41923
41924
41925
41926
41927
41928
41929
41930
41931
41932
41933
41934
41935
41936
41937
41938
41939
41940
41941
41942
41943
41944
41945
41946
41947
41948
41949
41950
41951
41952
41953
41954
41955
41956
41957
41958
41959
41960
41961
41962
41963
41964
41965
41966
41967
41968
41969
41970
41971
41972
41973
41974
41975
41976
41977
41978
41979
41980
41981
41982
41983
41984
41985
41986
41987
41988
41989
41990
41991
41992
41993
41994
41995
41996
41997
41998
41999
42000
42001
42002
42003
42004
42005
42006
42007
42008
42009
42010
42011
42012
42013
42014
42015
42016
42017
42018
42019
42020
42021
42022
42023
42024
42025
42026
42027
42028
42029
42030
42031
42032
42033
42034
42035
42036
42037
42038
42039
42040
42041
42042
42043
42044
42045
42046
42047
42048
42049
42050
42051
42052
42053
42054
42055
42056
42057
42058
42059
42060
42061
42062
42063
42064
42065
42066
42067
42068
42069
42070
42071
42072
42073
42074
42075
42076
42077
42078
42079
42080
42081
42082
42083
42084
42085
42086
42087
42088
42089
42090
42091
42092
42093
42094
42095
42096
42097
42098
42099
42100
42101
42102
42103
42104
42105
42106
42107
42108
42109
42110
42111
42112
42113
42114
42115
42116
42117
42118
42119
42120
42121
42122
42123
42124
42125
42126
42127
42128
42129
42130
42131
42132
42133
42134
42135
42136
42137
42138
42139
42140
42141
42142
42143
42144
42145
42146
42147
42148
42149
42150
42151
42152
42153
42154
42155
42156
42157
42158
42159
42160
42161
42162
42163
42164
42165
42166
42167
42168
42169
42170
42171
42172
42173
42174
42175
42176
42177
42178
42179
42180
42181
42182
42183
42184
42185
42186
42187
42188
42189
42190
42191
42192
42193
42194
42195
42196
42197
42198
42199
42200
42201
42202
42203
42204
42205
42206
42207
42208
42209
42210
42211
42212
42213
42214
42215
42216
42217
42218
42219
42220
42221
42222
42223
42224
42225
42226
42227
42228
42229
42230
42231
42232
42233
42234
42235
42236
42237
42238
42239
42240
42241
42242
42243
42244
42245
42246
42247
42248
42249
42250
42251
42252
42253
42254
42255
42256
42257
42258
42259
42260
42261
42262
42263
42264
42265
42266
42267
42268
42269
42270
42271
42272
42273
42274
42275
42276
42277
42278
42279
42280
42281
42282
42283
42284
42285
42286
42287
42288
42289
42290
42291
42292
42293
42294
42295
42296
42297
42298
42299
42300
42301
42302
42303
42304
42305
42306
42307
42308
42309
42310
42311
42312
42313
42314
42315
42316
42317
42318
42319
42320
42321
42322
42323
42324
42325
42326
42327
42328
42329
42330
42331
42332
42333
42334
42335
42336
42337
42338
42339
42340
42341
42342
42343
42344
42345
42346
42347
42348
42349
42350
42351
42352
42353
42354
42355
42356
42357
42358
42359
42360
42361
42362
42363
42364
42365
42366
42367
42368
42369
42370
42371
42372
42373
42374
42375
42376
42377
42378
42379
42380
42381
42382
42383
42384
42385
42386
42387
42388
42389
42390
42391
42392
42393
42394
42395
42396
42397
42398
42399
42400
42401
42402
42403
42404
42405
42406
42407
42408
42409
42410
42411
42412
42413
42414
42415
42416
42417
42418
42419
42420
42421
42422
42423
42424
42425
42426
42427
42428
42429
42430
42431
42432
42433
42434
42435
42436
42437
42438
42439
42440
42441
42442
42443
42444
42445
42446
42447
42448
42449
42450
42451
42452
42453
42454
42455
42456
42457
42458
42459
42460
42461
42462
42463
42464
42465
42466
42467
42468
42469
42470
42471
42472
42473
42474
42475
42476
42477
42478
42479
42480
42481
42482
42483
42484
42485
42486
42487
42488
42489
42490
42491
42492
42493
42494
42495
42496
42497
42498
42499
42500
42501
42502
42503
42504
42505
42506
42507
42508
42509
42510
42511
42512
42513
42514
42515
42516
42517
42518
42519
42520
42521
42522
42523
42524
42525
42526
42527
42528
42529
42530
42531
42532
42533
42534
42535
42536
42537
42538
42539
42540
42541
42542
42543
42544
42545
42546
42547
42548
42549
42550
42551
42552
42553
42554
42555
42556
42557
42558
42559
42560
42561
42562
42563
42564
42565
42566
42567
42568
42569
42570
42571
42572
42573
42574
42575
42576
42577
42578
42579
42580
42581
42582
42583
42584
42585
42586
42587
42588
42589
42590
42591
42592
42593
42594
42595
42596
42597
42598
42599
42600
42601
42602
42603
42604
42605
42606
42607
42608
42609
42610
42611
42612
42613
42614
42615
42616
42617
42618
42619
42620
42621
42622
42623
42624
42625
42626
42627
42628
42629
42630
42631
42632
42633
42634
42635
42636
42637
42638
42639
42640
42641
42642
42643
42644
42645
42646
42647
42648
42649
42650
42651
42652
42653
42654
42655
42656
42657
42658
42659
42660
42661
42662
42663
42664
42665
42666
42667
42668
42669
42670
42671
42672
42673
42674
42675
42676
42677
42678
42679
42680
42681
42682
42683
42684
42685
42686
42687
42688
42689
42690
42691
42692
42693
42694
42695
42696
42697
42698
42699
42700
42701
42702
42703
42704
42705
42706
42707
42708
42709
42710
42711
42712
42713
42714
42715
42716
42717
42718
42719
42720
42721
42722
42723
42724
42725
42726
42727
42728
42729
42730
42731
42732
42733
42734
42735
42736
42737
42738
42739
42740
42741
42742
42743
42744
42745
42746
42747
42748
42749
42750
42751
42752
42753
42754
42755
42756
42757
42758
42759
42760
42761
42762
42763
42764
42765
42766
42767
42768
42769
42770
42771
42772
42773
42774
42775
42776
42777
42778
42779
42780
42781
42782
42783
42784
42785
42786
42787
42788
42789
42790
42791
42792
42793
42794
42795
42796
42797
42798
42799
42800
42801
42802
42803
42804
42805
42806
42807
42808
42809
42810
42811
42812
42813
42814
42815
42816
42817
42818
42819
42820
42821
42822
42823
42824
42825
42826
42827
42828
42829
42830
42831
42832
42833
42834
42835
42836
42837
42838
42839
42840
42841
42842
42843
42844
42845
42846
42847
42848
42849
42850
42851
42852
42853
42854
42855
42856
42857
42858
42859
42860
42861
42862
42863
42864
42865
42866
42867
42868
42869
42870
42871
42872
42873
42874
42875
42876
42877
42878
42879
42880
42881
42882
42883
42884
42885
42886
42887
42888
42889
42890
42891
42892
42893
42894
42895
42896
42897
42898
42899
42900
42901
42902
42903
42904
42905
42906
42907
42908
42909
42910
42911
42912
42913
42914
42915
42916
42917
42918
42919
42920
42921
42922
42923
42924
42925
42926
42927
42928
42929
42930
42931
42932
42933
42934
42935
42936
42937
42938
42939
42940
42941
42942
42943
42944
42945
42946
42947
42948
42949
42950
42951
42952
42953
42954
42955
42956
42957
42958
42959
42960
42961
42962
42963
42964
42965
42966
42967
42968
42969
42970
42971
42972
42973
42974
42975
42976
42977
42978
42979
42980
42981
42982
42983
42984
42985
42986
42987
42988
42989
42990
42991
42992
42993
42994
42995
42996
42997
42998
42999
43000
43001
43002
43003
43004
43005
43006
43007
43008
43009
43010
43011
43012
43013
43014
43015
43016
43017
43018
43019
43020
43021
43022
43023
43024
43025
43026
43027
43028
43029
43030
43031
43032
43033
43034
43035
43036
43037
43038
43039
43040
43041
43042
43043
43044
43045
43046
43047
43048
43049
43050
43051
43052
43053
43054
43055
43056
43057
43058
43059
43060
43061
43062
43063
43064
43065
43066
43067
43068
43069
43070
43071
43072
43073
43074
43075
43076
43077
43078
43079
43080
43081
43082
43083
43084
43085
43086
43087
43088
43089
43090
43091
43092
43093
43094
43095
43096
43097
43098
43099
43100
43101
43102
43103
43104
43105
43106
43107
43108
43109
43110
43111
43112
43113
43114
43115
43116
43117
43118
43119
43120
43121
43122
43123
43124
43125
43126
43127
43128
43129
43130
43131
43132
43133
43134
43135
43136
43137
43138
43139
43140
43141
43142
43143
43144
43145
43146
43147
43148
43149
43150
43151
43152
43153
43154
43155
43156
43157
43158
43159
43160
43161
43162
43163
43164
43165
43166
43167
43168
43169
43170
43171
43172
43173
43174
43175
43176
43177
43178
43179
43180
43181
43182
43183
43184
43185
43186
43187
43188
43189
43190
43191
43192
43193
43194
43195
43196
43197
43198
43199
43200
43201
43202
43203
43204
43205
43206
43207
43208
43209
43210
43211
43212
43213
43214
43215
43216
43217
43218
43219
43220
43221
43222
43223
43224
43225
43226
43227
43228
43229
43230
43231
43232
43233
43234
43235
43236
43237
43238
43239
43240
43241
43242
43243
43244
43245
43246
43247
43248
43249
43250
43251
43252
43253
43254
43255
43256
43257
43258
43259
43260
43261
43262
43263
43264
43265
43266
43267
43268
43269
43270
43271
43272
43273
43274
43275
43276
43277
43278
43279
43280
43281
43282
43283
43284
43285
43286
43287
43288
43289
43290
43291
43292
43293
43294
43295
43296
43297
43298
43299
43300
43301
43302
43303
43304
43305
43306
43307
43308
43309
43310
43311
43312
43313
43314
43315
43316
43317
43318
43319
43320
43321
43322
43323
43324
43325
43326
43327
43328
43329
43330
43331
43332
43333
43334
43335
43336
43337
43338
43339
43340
43341
43342
43343
43344
43345
43346
43347
43348
43349
43350
43351
43352
43353
43354
43355
43356
43357
43358
43359
43360
43361
43362
43363
43364
43365
43366
43367
43368
43369
43370
43371
43372
43373
43374
43375
43376
43377
43378
43379
43380
43381
43382
43383
43384
43385
43386
43387
43388
43389
43390
43391
43392
43393
43394
43395
43396
43397
43398
43399
43400
43401
43402
43403
43404
43405
43406
43407
43408
43409
43410
43411
43412
43413
43414
43415
43416
43417
43418
43419
43420
43421
43422
43423
43424
43425
43426
43427
43428
43429
43430
43431
43432
43433
43434
43435
43436
43437
43438
43439
43440
43441
43442
43443
43444
43445
43446
43447
43448
43449
43450
43451
43452
43453
43454
43455
43456
43457
43458
43459
43460
43461
43462
43463
43464
43465
43466
43467
43468
43469
43470
43471
43472
43473
43474
43475
43476
43477
43478
43479
43480
43481
43482
43483
43484
43485
43486
43487
43488
43489
43490
43491
43492
43493
43494
43495
43496
43497
43498
43499
43500
43501
43502
43503
43504
43505
43506
43507
43508
43509
43510
43511
43512
43513
43514
43515
43516
43517
43518
43519
43520
43521
43522
43523
43524
43525
43526
43527
43528
43529
43530
43531
43532
43533
43534
43535
43536
43537
43538
43539
43540
43541
43542
43543
43544
43545
43546
43547
43548
43549
43550
43551
43552
43553
43554
43555
43556
43557
43558
43559
43560
43561
43562
43563
43564
43565
43566
43567
43568
43569
43570
43571
43572
43573
43574
43575
43576
43577
43578
43579
43580
43581
43582
43583
43584
43585
43586
43587
43588
43589
43590
43591
43592
43593
43594
43595
43596
43597
43598
43599
43600
43601
43602
43603
43604
43605
43606
43607
43608
43609
43610
43611
43612
43613
43614
43615
43616
43617
43618
43619
43620
43621
43622
43623
43624
43625
43626
43627
43628
43629
43630
43631
43632
43633
43634
43635
43636
43637
43638
43639
43640
43641
43642
43643
43644
43645
43646
43647
43648
43649
43650
43651
43652
43653
43654
43655
43656
43657
43658
43659
43660
43661
43662
43663
43664
43665
43666
43667
43668
43669
43670
43671
43672
43673
43674
43675
43676
43677
43678
43679
43680
43681
43682
43683
43684
43685
43686
43687
43688
43689
43690
43691
43692
43693
43694
43695
43696
43697
43698
43699
43700
43701
43702
43703
43704
43705
43706
43707
43708
43709
43710
43711
43712
43713
43714
43715
43716
43717
43718
43719
43720
43721
43722
43723
43724
43725
43726
43727
43728
43729
43730
43731
43732
43733
43734
43735
43736
43737
43738
43739
43740
43741
43742
43743
43744
43745
43746
43747
43748
43749
43750
43751
43752
43753
43754
43755
43756
43757
43758
43759
43760
43761
43762
43763
43764
43765
43766
43767
43768
43769
43770
43771
43772
43773
43774
43775
43776
43777
43778
43779
43780
43781
43782
43783
43784
43785
43786
43787
43788
43789
43790
43791
43792
43793
43794
43795
43796
43797
43798
43799
43800
43801
43802
43803
43804
43805
43806
43807
43808
43809
43810
43811
43812
43813
43814
43815
43816
43817
43818
43819
43820
43821
43822
43823
43824
43825
43826
43827
43828
43829
43830
43831
43832
43833
43834
43835
43836
43837
43838
43839
43840
43841
43842
43843
43844
43845
43846
43847
43848
43849
43850
43851
43852
43853
43854
43855
43856
43857
43858
43859
43860
43861
43862
43863
43864
43865
43866
43867
43868
43869
43870
43871
43872
43873
43874
43875
43876
43877
43878
43879
43880
43881
43882
43883
43884
43885
43886
43887
43888
43889
43890
43891
43892
43893
43894
43895
43896
43897
43898
43899
43900
43901
43902
43903
43904
43905
43906
43907
43908
43909
43910
43911
43912
43913
43914
43915
43916
43917
43918
43919
43920
43921
43922
43923
43924
43925
43926
43927
43928
43929
43930
43931
43932
43933
43934
43935
43936
43937
43938
43939
43940
43941
43942
43943
43944
43945
43946
43947
43948
43949
43950
43951
43952
43953
43954
43955
43956
43957
43958
43959
43960
43961
43962
43963
43964
43965
43966
43967
43968
43969
43970
43971
43972
43973
43974
43975
43976
43977
43978
43979
43980
43981
43982
43983
43984
43985
43986
43987
43988
43989
43990
43991
43992
43993
43994
43995
43996
43997
43998
43999
44000
44001
44002
44003
44004
44005
44006
44007
44008
44009
44010
44011
44012
44013
44014
44015
44016
44017
44018
44019
44020
44021
44022
44023
44024
44025
44026
44027
44028
44029
44030
44031
44032
44033
44034
44035
44036
44037
44038
44039
44040
44041
44042
44043
44044
44045
44046
44047
44048
44049
44050
44051
44052
44053
44054
44055
44056
44057
44058
44059
44060
44061
44062
44063
44064
44065
44066
44067
44068
44069
44070
44071
44072
44073
44074
44075
44076
44077
44078
44079
44080
44081
44082
44083
44084
44085
44086
44087
44088
44089
44090
44091
44092
44093
44094
44095
44096
44097
44098
44099
44100
44101
44102
44103
44104
44105
44106
44107
44108
44109
44110
44111
44112
44113
44114
44115
44116
44117
44118
44119
44120
44121
44122
44123
44124
44125
44126
44127
44128
44129
44130
44131
44132
44133
44134
44135
44136
44137
44138
44139
44140
44141
44142
44143
44144
44145
44146
44147
44148
44149
44150
44151
44152
44153
44154
44155
44156
44157
44158
44159
44160
44161
44162
44163
44164
44165
44166
44167
44168
44169
44170
44171
44172
44173
44174
44175
44176
44177
44178
44179
44180
44181
44182
44183
44184
44185
44186
44187
44188
44189
44190
44191
44192
44193
44194
44195
44196
44197
44198
44199
44200
44201
44202
44203
44204
44205
44206
44207
44208
44209
44210
44211
44212
44213
44214
44215
44216
44217
44218
44219
44220
44221
44222
44223
44224
44225
44226
44227
44228
44229
44230
44231
44232
44233
44234
44235
44236
44237
44238
44239
44240
44241
44242
44243
44244
44245
44246
44247
44248
44249
44250
44251
44252
44253
44254
44255
44256
44257
44258
44259
44260
44261
44262
44263
44264
44265
44266
44267
44268
44269
44270
44271
44272
44273
44274
44275
44276
44277
44278
44279
44280
44281
44282
44283
44284
44285
44286
44287
44288
44289
44290
44291
44292
44293
44294
44295
44296
44297
44298
44299
44300
44301
44302
44303
44304
44305
44306
44307
44308
44309
44310
44311
44312
44313
44314
44315
44316
44317
44318
44319
44320
44321
44322
44323
44324
44325
44326
44327
44328
44329
44330
44331
44332
44333
44334
44335
44336
44337
44338
44339
44340
44341
44342
44343
44344
44345
44346
44347
44348
44349
44350
44351
44352
44353
44354
44355
44356
44357
44358
44359
44360
44361
44362
44363
44364
44365
44366
44367
44368
44369
44370
44371
44372
44373
44374
44375
44376
44377
44378
44379
44380
44381
44382
44383
44384
44385
44386
44387
44388
44389
44390
44391
44392
44393
44394
44395
44396
44397
44398
44399
44400
44401
44402
44403
44404
44405
44406
44407
44408
44409
44410
44411
44412
44413
44414
44415
44416
44417
44418
44419
44420
44421
44422
44423
44424
44425
44426
44427
44428
44429
44430
44431
44432
44433
44434
44435
44436
44437
44438
44439
44440
44441
44442
44443
44444
44445
44446
44447
44448
44449
44450
44451
44452
44453
44454
44455
44456
44457
44458
44459
44460
44461
44462
44463
44464
44465
44466
44467
44468
44469
44470
44471
44472
44473
44474
44475
44476
44477
44478
44479
44480
44481
44482
44483
44484
44485
44486
44487
44488
44489
44490
44491
44492
44493
44494
44495
44496
44497
44498
44499
44500
44501
44502
44503
44504
44505
44506
44507
44508
44509
44510
44511
44512
44513
44514
44515
44516
44517
44518
44519
44520
44521
44522
44523
44524
44525
44526
44527
44528
44529
44530
44531
44532
44533
44534
44535
44536
44537
44538
44539
44540
44541
44542
44543
44544
44545
44546
44547
44548
44549
44550
44551
44552
44553
44554
44555
44556
44557
44558
44559
44560
44561
44562
44563
44564
44565
44566
44567
44568
44569
44570
44571
44572
44573
44574
44575
44576
44577
44578
44579
44580
44581
44582
44583
44584
44585
44586
44587
44588
44589
44590
44591
44592
44593
44594
44595
44596
44597
44598
44599
44600
44601
44602
44603
44604
44605
44606
44607
44608
44609
44610
44611
44612
44613
44614
44615
44616
44617
44618
44619
44620
44621
44622
44623
44624
44625
44626
44627
44628
44629
44630
44631
44632
44633
44634
44635
44636
44637
44638
44639
44640
44641
44642
44643
44644
44645
44646
44647
44648
44649
44650
44651
44652
44653
44654
44655
44656
44657
44658
44659
44660
44661
44662
44663
44664
44665
44666
44667
44668
44669
44670
44671
44672
44673
44674
44675
44676
44677
44678
44679
44680
44681
44682
44683
44684
44685
44686
44687
44688
44689
44690
44691
44692
44693
44694
44695
44696
44697
44698
44699
44700
44701
44702
44703
44704
44705
44706
44707
44708
44709
44710
44711
44712
44713
44714
44715
44716
44717
44718
44719
44720
44721
44722
44723
44724
44725
44726
44727
44728
44729
44730
44731
44732
44733
44734
44735
44736
44737
44738
44739
44740
44741
44742
44743
44744
44745
44746
44747
44748
44749
44750
44751
44752
44753
44754
44755
44756
44757
44758
44759
44760
44761
44762
44763
44764
44765
44766
44767
44768
44769
44770
44771
44772
44773
44774
44775
44776
44777
44778
44779
44780
44781
44782
44783
44784
44785
44786
44787
44788
44789
44790
44791
44792
44793
44794
44795
44796
44797
44798
44799
44800
44801
44802
44803
44804
44805
44806
44807
44808
44809
44810
44811
44812
44813
44814
44815
44816
44817
44818
44819
44820
44821
44822
44823
44824
44825
44826
44827
44828
44829
44830
44831
44832
44833
44834
44835
44836
44837
44838
44839
44840
44841
44842
44843
44844
44845
44846
44847
44848
44849
44850
44851
44852
44853
44854
44855
44856
44857
44858
44859
44860
44861
44862
44863
44864
44865
44866
44867
44868
44869
44870
44871
44872
44873
44874
44875
44876
44877
44878
44879
44880
44881
44882
44883
44884
44885
44886
44887
44888
44889
44890
44891
44892
44893
44894
44895
44896
44897
44898
44899
44900
44901
44902
44903
44904
44905
44906
44907
44908
44909
44910
44911
44912
44913
44914
44915
44916
44917
44918
44919
44920
44921
44922
44923
44924
44925
44926
44927
44928
44929
44930
44931
44932
44933
44934
44935
44936
44937
44938
44939
44940
44941
44942
44943
44944
44945
44946
44947
44948
44949
44950
44951
44952
44953
44954
44955
44956
44957
44958
44959
44960
44961
44962
44963
44964
44965
44966
44967
44968
44969
44970
44971
44972
44973
44974
44975
44976
44977
44978
44979
44980
44981
44982
44983
44984
44985
44986
44987
44988
44989
44990
44991
44992
44993
44994
44995
44996
44997
44998
44999
45000
45001
45002
45003
45004
45005
45006
45007
45008
45009
45010
45011
45012
45013
45014
45015
45016
45017
45018
45019
45020
45021
45022
45023
45024
45025
45026
45027
45028
45029
45030
45031
45032
45033
45034
45035
45036
45037
45038
45039
45040
45041
45042
45043
45044
45045
45046
45047
45048
45049
45050
45051
45052
45053
45054
45055
45056
45057
45058
45059
45060
45061
45062
45063
45064
45065
45066
45067
45068
45069
45070
45071
45072
45073
45074
45075
45076
45077
45078
45079
45080
45081
45082
45083
45084
45085
45086
45087
45088
45089
45090
45091
45092
45093
45094
45095
45096
45097
45098
45099
45100
45101
45102
45103
45104
45105
45106
45107
45108
45109
45110
45111
45112
45113
45114
45115
45116
45117
45118
45119
45120
45121
45122
45123
45124
45125
45126
45127
45128
45129
45130
45131
45132
45133
45134
45135
45136
45137
45138
45139
45140
45141
45142
45143
45144
45145
45146
45147
45148
45149
45150
45151
45152
45153
45154
45155
45156
45157
45158
45159
45160
45161
45162
45163
45164
45165
45166
45167
45168
45169
45170
45171
45172
45173
45174
45175
45176
45177
45178
45179
45180
45181
45182
45183
45184
45185
45186
45187
45188
45189
45190
45191
45192
45193
45194
45195
45196
45197
45198
45199
45200
45201
45202
45203
45204
45205
45206
45207
45208
45209
45210
45211
45212
45213
45214
45215
45216
45217
45218
45219
45220
45221
45222
45223
45224
45225
45226
45227
45228
45229
45230
45231
45232
45233
45234
45235
45236
45237
45238
45239
45240
45241
45242
45243
45244
45245
45246
45247
45248
45249
45250
45251
45252
45253
45254
45255
45256
45257
45258
45259
45260
45261
45262
45263
45264
45265
45266
45267
45268
45269
45270
45271
45272
45273
45274
45275
45276
45277
45278
45279
45280
45281
45282
45283
45284
45285
45286
45287
45288
45289
45290
45291
45292
45293
45294
45295
45296
45297
45298
45299
45300
45301
45302
45303
45304
45305
45306
45307
45308
45309
45310
45311
45312
45313
45314
45315
45316
45317
45318
45319
45320
45321
45322
45323
45324
45325
45326
45327
45328
45329
45330
45331
45332
45333
45334
45335
45336
45337
45338
45339
45340
45341
45342
45343
45344
45345
45346
45347
45348
45349
45350
45351
45352
45353
45354
45355
45356
45357
45358
45359
45360
45361
45362
45363
45364
45365
45366
45367
45368
45369
45370
45371
45372
45373
45374
45375
45376
45377
45378
45379
45380
45381
45382
45383
45384
45385
45386
45387
45388
45389
45390
45391
45392
45393
45394
45395
45396
45397
45398
45399
45400
45401
45402
45403
45404
45405
45406
45407
45408
45409
45410
45411
45412
45413
45414
45415
45416
45417
45418
45419
45420
45421
45422
45423
45424
45425
45426
45427
45428
45429
45430
45431
45432
45433
45434
45435
45436
45437
45438
45439
45440
45441
45442
45443
45444
45445
45446
45447
45448
45449
45450
45451
45452
45453
45454
45455
45456
45457
45458
45459
45460
45461
45462
45463
45464
45465
45466
45467
45468
45469
45470
45471
45472
45473
45474
45475
45476
45477
45478
45479
45480
45481
45482
45483
45484
45485
45486
45487
45488
45489
45490
45491
45492
45493
45494
45495
45496
45497
45498
45499
45500
45501
45502
45503
45504
45505
45506
45507
45508
45509
45510
45511
45512
45513
45514
45515
45516
45517
45518
45519
45520
45521
45522
45523
45524
45525
45526
45527
45528
45529
45530
45531
45532
45533
45534
45535
45536
45537
45538
45539
45540
45541
45542
45543
45544
45545
45546
45547
45548
45549
45550
45551
45552
45553
45554
45555
45556
45557
45558
45559
45560
45561
45562
45563
45564
45565
45566
45567
45568
45569
45570
45571
45572
45573
45574
45575
45576
45577
45578
45579
45580
45581
45582
45583
45584
45585
45586
45587
45588
45589
45590
45591
45592
45593
45594
45595
45596
45597
45598
45599
45600
45601
45602
45603
45604
45605
45606
45607
45608
45609
45610
45611
45612
45613
45614
45615
45616
45617
45618
45619
45620
45621
45622
45623
45624
45625
45626
45627
45628
45629
45630
45631
45632
45633
45634
45635
45636
45637
45638
45639
45640
45641
45642
45643
45644
45645
45646
45647
45648
45649
45650
45651
45652
45653
45654
45655
45656
45657
45658
45659
45660
45661
45662
45663
45664
45665
45666
45667
45668
45669
45670
45671
45672
45673
45674
45675
45676
45677
45678
45679
45680
45681
45682
45683
45684
45685
45686
45687
45688
45689
45690
45691
45692
45693
45694
45695
45696
45697
45698
45699
45700
45701
45702
45703
45704
45705
45706
45707
45708
45709
45710
45711
45712
45713
45714
45715
45716
45717
45718
45719
45720
45721
45722
45723
45724
45725
45726
45727
45728
45729
45730
45731
45732
45733
45734
45735
45736
45737
45738
45739
45740
45741
45742
45743
45744
45745
45746
45747
45748
45749
45750
45751
45752
45753
45754
45755
45756
45757
45758
45759
45760
45761
45762
45763
45764
45765
45766
45767
45768
45769
45770
45771
45772
45773
45774
45775
45776
45777
45778
45779
45780
45781
45782
45783
45784
45785
45786
45787
45788
45789
45790
45791
45792
45793
45794
45795
45796
45797
45798
45799
45800
45801
45802
45803
45804
45805
45806
45807
45808
45809
45810
45811
45812
45813
45814
45815
45816
45817
45818
45819
45820
45821
45822
45823
45824
45825
45826
45827
45828
45829
45830
45831
45832
45833
45834
45835
45836
45837
45838
45839
45840
45841
45842
45843
45844
45845
45846
45847
45848
45849
45850
45851
45852
45853
45854
45855
45856
45857
45858
45859
45860
45861
45862
45863
45864
45865
45866
45867
45868
45869
45870
45871
45872
45873
45874
45875
45876
45877
45878
45879
45880
45881
45882
45883
45884
45885
45886
45887
45888
45889
45890
45891
45892
45893
45894
45895
45896
45897
45898
45899
45900
45901
45902
45903
45904
45905
45906
45907
45908
45909
45910
45911
45912
45913
45914
45915
45916
45917
45918
45919
45920
45921
45922
45923
45924
45925
45926
45927
45928
45929
45930
45931
45932
45933
45934
45935
45936
45937
45938
45939
45940
45941
45942
45943
45944
45945
45946
45947
45948
45949
45950
45951
45952
45953
45954
45955
45956
45957
45958
45959
45960
45961
45962
45963
45964
45965
45966
45967
45968
45969
45970
45971
45972
45973
45974
45975
45976
45977
45978
45979
45980
45981
45982
45983
45984
45985
45986
45987
45988
45989
45990
45991
45992
45993
45994
45995
45996
45997
45998
45999
46000
46001
46002
46003
46004
46005
46006
46007
46008
46009
46010
46011
46012
46013
46014
46015
46016
46017
46018
46019
46020
46021
46022
46023
46024
46025
46026
46027
46028
46029
46030
46031
46032
46033
46034
46035
46036
46037
46038
46039
46040
46041
46042
46043
46044
46045
46046
46047
46048
46049
46050
46051
46052
46053
46054
46055
46056
46057
46058
46059
46060
46061
46062
46063
46064
46065
46066
46067
46068
46069
46070
46071
46072
46073
46074
46075
46076
46077
46078
46079
46080
46081
46082
46083
46084
46085
46086
46087
46088
46089
46090
46091
46092
46093
46094
46095
46096
46097
46098
46099
46100
46101
46102
46103
46104
46105
46106
46107
46108
46109
46110
46111
46112
46113
46114
46115
46116
46117
46118
46119
46120
46121
46122
46123
46124
46125
46126
46127
46128
46129
46130
46131
46132
46133
46134
46135
46136
46137
46138
46139
46140
46141
46142
46143
46144
46145
46146
46147
46148
46149
46150
46151
46152
46153
46154
46155
46156
46157
46158
46159
46160
46161
46162
46163
46164
46165
46166
46167
46168
46169
46170
46171
46172
46173
46174
46175
46176
46177
46178
46179
46180
46181
46182
46183
46184
46185
46186
46187
46188
46189
46190
46191
46192
46193
46194
46195
46196
46197
46198
46199
46200
46201
46202
46203
46204
46205
46206
46207
46208
46209
46210
46211
46212
46213
46214
46215
46216
46217
46218
46219
46220
46221
46222
46223
46224
46225
46226
46227
46228
46229
46230
46231
46232
46233
46234
46235
46236
46237
46238
46239
46240
46241
46242
46243
46244
46245
46246
46247
46248
46249
46250
46251
46252
46253
46254
46255
46256
46257
46258
46259
46260
46261
46262
46263
46264
46265
46266
46267
46268
46269
46270
46271
46272
46273
46274
46275
46276
46277
46278
46279
46280
46281
46282
46283
46284
46285
46286
46287
46288
46289
46290
46291
46292
46293
46294
46295
46296
46297
46298
46299
46300
46301
46302
46303
46304
46305
46306
46307
46308
46309
46310
46311
46312
46313
46314
46315
46316
46317
46318
46319
46320
46321
46322
46323
46324
46325
46326
46327
46328
46329
46330
46331
46332
46333
46334
46335
46336
46337
46338
46339
46340
46341
46342
46343
46344
46345
46346
46347
46348
46349
46350
46351
46352
46353
46354
46355
46356
46357
46358
46359
46360
46361
46362
46363
46364
46365
46366
46367
46368
46369
46370
46371
46372
46373
46374
46375
46376
46377
46378
46379
46380
46381
46382
46383
46384
46385
46386
46387
46388
46389
46390
46391
46392
46393
46394
46395
46396
46397
46398
46399
46400
46401
46402
46403
46404
46405
46406
46407
46408
46409
46410
46411
46412
46413
46414
46415
46416
46417
46418
46419
46420
46421
46422
46423
46424
46425
46426
46427
46428
46429
46430
46431
46432
46433
46434
46435
46436
46437
46438
46439
46440
46441
46442
46443
46444
46445
46446
46447
46448
46449
46450
46451
46452
46453
46454
46455
46456
46457
46458
46459
46460
46461
46462
46463
46464
46465
46466
46467
46468
46469
46470
46471
46472
46473
46474
46475
46476
46477
46478
46479
46480
46481
46482
46483
46484
46485
46486
46487
46488
46489
46490
46491
46492
46493
46494
46495
46496
46497
46498
46499
46500
46501
46502
46503
46504
46505
46506
46507
46508
46509
46510
46511
46512
46513
46514
46515
46516
46517
46518
46519
46520
46521
46522
46523
46524
46525
46526
46527
46528
46529
46530
46531
46532
46533
46534
46535
46536
46537
46538
46539
46540
46541
46542
46543
46544
46545
46546
46547
46548
46549
46550
46551
46552
46553
46554
46555
46556
46557
46558
46559
46560
46561
46562
46563
46564
46565
46566
46567
46568
46569
46570
46571
46572
46573
46574
46575
46576
46577
46578
46579
46580
46581
46582
46583
46584
46585
46586
46587
46588
46589
46590
46591
46592
46593
46594
46595
46596
46597
46598
46599
46600
46601
46602
46603
46604
46605
46606
46607
46608
46609
46610
46611
46612
46613
46614
46615
46616
46617
46618
46619
46620
46621
46622
46623
46624
46625
46626
46627
46628
46629
46630
46631
46632
46633
46634
46635
46636
46637
46638
46639
46640
46641
46642
46643
46644
46645
46646
46647
46648
46649
46650
46651
46652
46653
46654
46655
46656
46657
46658
46659
46660
46661
46662
46663
46664
46665
46666
46667
46668
46669
46670
46671
46672
46673
46674
46675
46676
46677
46678
46679
46680
46681
46682
46683
46684
46685
46686
46687
46688
46689
46690
46691
46692
46693
46694
46695
46696
46697
46698
46699
46700
46701
46702
46703
46704
46705
46706
46707
46708
46709
46710
46711
46712
46713
46714
46715
46716
46717
46718
46719
46720
46721
46722
46723
46724
46725
46726
46727
46728
46729
46730
46731
46732
46733
46734
46735
46736
46737
46738
46739
46740
46741
46742
46743
46744
46745
46746
46747
46748
46749
46750
46751
46752
46753
46754
46755
46756
46757
46758
46759
46760
46761
46762
46763
46764
46765
46766
46767
46768
46769
46770
46771
46772
46773
46774
46775
46776
46777
46778
46779
46780
46781
46782
46783
46784
46785
46786
46787
46788
46789
46790
46791
46792
46793
46794
46795
46796
46797
46798
46799
46800
46801
46802
46803
46804
46805
46806
46807
46808
46809
46810
46811
46812
46813
46814
46815
46816
46817
46818
46819
46820
46821
46822
46823
46824
46825
46826
46827
46828
46829
46830
46831
46832
46833
46834
46835
46836
46837
46838
46839
46840
46841
46842
46843
46844
46845
46846
46847
46848
46849
46850
46851
46852
46853
46854
46855
46856
46857
46858
46859
46860
46861
46862
46863
46864
46865
46866
46867
46868
46869
46870
46871
46872
46873
46874
46875
46876
46877
46878
46879
46880
46881
46882
46883
46884
46885
46886
46887
46888
46889
46890
46891
46892
46893
46894
46895
46896
46897
46898
46899
46900
46901
46902
46903
46904
46905
46906
46907
46908
46909
46910
46911
46912
46913
46914
46915
46916
46917
46918
46919
46920
46921
46922
46923
46924
46925
46926
46927
46928
46929
46930
46931
46932
46933
46934
46935
46936
46937
46938
46939
46940
46941
46942
46943
46944
46945
46946
46947
46948
46949
46950
46951
46952
46953
46954
46955
46956
46957
46958
46959
46960
46961
46962
46963
46964
46965
46966
46967
46968
46969
46970
46971
46972
46973
46974
46975
46976
46977
46978
46979
46980
46981
46982
46983
46984
46985
46986
46987
46988
46989
46990
46991
46992
46993
46994
46995
46996
46997
46998
46999
47000
47001
47002
47003
47004
47005
47006
47007
47008
47009
47010
47011
47012
47013
47014
47015
47016
47017
47018
47019
47020
47021
47022
47023
47024
47025
47026
47027
47028
47029
47030
47031
47032
47033
47034
47035
47036
47037
47038
47039
47040
47041
47042
47043
47044
47045
47046
47047
47048
47049
47050
47051
47052
47053
47054
47055
47056
47057
47058
47059
47060
47061
47062
47063
47064
47065
47066
47067
47068
47069
47070
47071
47072
47073
47074
47075
47076
47077
47078
47079
47080
47081
47082
47083
47084
47085
47086
47087
47088
47089
47090
47091
47092
47093
47094
47095
47096
47097
47098
47099
47100
47101
47102
47103
47104
47105
47106
47107
47108
47109
47110
47111
47112
47113
47114
47115
47116
47117
47118
47119
47120
47121
47122
47123
47124
47125
47126
47127
47128
47129
47130
47131
47132
47133
47134
47135
47136
47137
47138
47139
47140
47141
47142
47143
47144
47145
47146
47147
47148
47149
47150
47151
47152
47153
47154
47155
47156
47157
47158
47159
47160
47161
47162
47163
47164
47165
47166
47167
47168
47169
47170
47171
47172
47173
47174
47175
47176
47177
47178
47179
47180
47181
47182
47183
47184
47185
47186
47187
47188
47189
47190
47191
47192
47193
47194
47195
47196
47197
47198
47199
47200
47201
47202
47203
47204
47205
47206
47207
47208
47209
47210
47211
47212
47213
47214
47215
47216
47217
47218
47219
47220
47221
47222
47223
47224
47225
47226
47227
47228
47229
47230
47231
47232
47233
47234
47235
47236
47237
47238
47239
47240
47241
47242
47243
47244
47245
47246
47247
47248
47249
47250
47251
47252
47253
47254
47255
47256
47257
47258
47259
47260
47261
47262
47263
47264
47265
47266
47267
47268
47269
47270
47271
47272
47273
47274
47275
47276
47277
47278
47279
47280
47281
47282
47283
47284
47285
47286
47287
47288
47289
47290
47291
47292
47293
47294
47295
47296
47297
47298
47299
47300
47301
47302
47303
47304
47305
47306
47307
47308
47309
47310
47311
47312
47313
47314
47315
47316
47317
47318
47319
47320
47321
47322
47323
47324
47325
47326
47327
47328
47329
47330
47331
47332
47333
47334
47335
47336
47337
47338
47339
47340
47341
47342
47343
47344
47345
47346
47347
47348
47349
47350
47351
47352
47353
47354
47355
47356
47357
47358
47359
47360
47361
47362
47363
47364
47365
47366
47367
47368
47369
47370
47371
47372
47373
47374
47375
47376
47377
47378
47379
47380
47381
47382
47383
47384
47385
47386
47387
47388
47389
47390
47391
47392
47393
47394
47395
47396
47397
47398
47399
47400
47401
47402
47403
47404
47405
47406
47407
47408
47409
47410
47411
47412
47413
47414
47415
47416
47417
47418
47419
47420
47421
47422
47423
47424
47425
47426
47427
47428
47429
47430
47431
47432
47433
47434
47435
47436
47437
47438
47439
47440
47441
47442
47443
47444
47445
47446
47447
47448
47449
47450
47451
47452
47453
47454
47455
47456
47457
47458
47459
47460
47461
47462
47463
47464
47465
47466
47467
47468
47469
47470
47471
47472
47473
47474
47475
47476
47477
47478
47479
47480
47481
47482
47483
47484
47485
47486
47487
47488
47489
47490
47491
47492
47493
47494
47495
47496
47497
47498
47499
47500
47501
47502
47503
47504
47505
47506
47507
47508
47509
47510
47511
47512
47513
47514
47515
47516
47517
47518
47519
47520
47521
47522
47523
47524
47525
47526
47527
47528
47529
47530
47531
47532
47533
47534
47535
47536
47537
47538
47539
47540
47541
47542
47543
47544
47545
47546
47547
47548
47549
47550
47551
47552
47553
47554
47555
47556
47557
47558
47559
47560
47561
47562
47563
47564
47565
47566
47567
47568
47569
47570
47571
47572
47573
47574
47575
47576
47577
47578
47579
47580
47581
47582
47583
47584
47585
47586
47587
47588
47589
47590
47591
47592
47593
47594
47595
47596
47597
47598
47599
47600
47601
47602
47603
47604
47605
47606
47607
47608
47609
47610
47611
47612
47613
47614
47615
47616
47617
47618
47619
47620
47621
47622
47623
47624
47625
47626
47627
47628
47629
47630
47631
47632
47633
47634
47635
47636
47637
47638
47639
47640
47641
47642
47643
47644
47645
47646
47647
47648
47649
47650
47651
47652
47653
47654
47655
47656
47657
47658
47659
47660
47661
47662
47663
47664
47665
47666
47667
47668
47669
47670
47671
47672
47673
47674
47675
47676
47677
47678
47679
47680
47681
47682
47683
47684
47685
47686
47687
47688
47689
47690
47691
47692
47693
47694
47695
47696
47697
47698
47699
47700
47701
47702
47703
47704
47705
47706
47707
47708
47709
47710
47711
47712
47713
47714
47715
47716
47717
47718
47719
47720
47721
47722
47723
47724
47725
47726
47727
47728
47729
47730
47731
47732
47733
47734
47735
47736
47737
47738
47739
47740
47741
47742
47743
47744
47745
47746
47747
47748
47749
47750
47751
47752
47753
47754
47755
47756
47757
47758
47759
47760
47761
47762
47763
47764
47765
47766
47767
47768
47769
47770
47771
47772
47773
47774
47775
47776
47777
47778
47779
47780
47781
47782
47783
47784
47785
47786
47787
47788
47789
47790
47791
47792
47793
47794
47795
47796
47797
47798
47799
47800
47801
47802
47803
47804
47805
47806
47807
47808
47809
47810
47811
47812
47813
47814
47815
47816
47817
47818
47819
47820
47821
47822
47823
47824
47825
47826
47827
47828
47829
47830
47831
47832
47833
47834
47835
47836
47837
47838
47839
47840
47841
47842
47843
47844
47845
47846
47847
47848
47849
47850
47851
47852
47853
47854
47855
47856
47857
47858
47859
47860
47861
47862
47863
47864
47865
47866
47867
47868
47869
47870
47871
47872
47873
47874
47875
47876
47877
47878
47879
47880
47881
47882
47883
47884
47885
47886
47887
47888
47889
47890
47891
47892
47893
47894
47895
47896
47897
47898
47899
47900
47901
47902
47903
47904
47905
47906
47907
47908
47909
47910
47911
47912
47913
47914
47915
47916
47917
47918
47919
47920
47921
47922
47923
47924
47925
47926
47927
47928
47929
47930
47931
47932
47933
47934
47935
47936
47937
47938
47939
47940
47941
47942
47943
47944
47945
47946
47947
47948
47949
47950
47951
47952
47953
47954
47955
47956
47957
47958
47959
47960
47961
47962
47963
47964
47965
47966
47967
47968
47969
47970
47971
47972
47973
47974
47975
47976
47977
47978
47979
47980
47981
47982
47983
47984
47985
47986
47987
47988
47989
47990
47991
47992
47993
47994
47995
47996
47997
47998
47999
48000
48001
48002
48003
48004
48005
48006
48007
48008
48009
48010
48011
48012
48013
48014
48015
48016
48017
48018
48019
48020
48021
48022
48023
48024
48025
48026
48027
48028
48029
48030
48031
48032
48033
48034
48035
48036
48037
48038
48039
48040
48041
48042
48043
48044
48045
48046
48047
48048
48049
48050
48051
48052
48053
48054
48055
48056
48057
48058
48059
48060
48061
48062
48063
48064
48065
48066
48067
48068
48069
48070
48071
48072
48073
48074
48075
48076
48077
48078
48079
48080
48081
48082
48083
48084
48085
48086
48087
48088
48089
48090
48091
48092
48093
48094
48095
48096
48097
48098
48099
48100
48101
48102
48103
48104
48105
48106
48107
48108
48109
48110
48111
48112
48113
48114
48115
48116
48117
48118
48119
48120
48121
48122
48123
48124
48125
48126
48127
48128
48129
48130
48131
48132
48133
48134
48135
48136
48137
48138
48139
48140
48141
48142
48143
48144
48145
48146
48147
48148
48149
48150
48151
48152
48153
48154
48155
48156
48157
48158
48159
48160
48161
48162
48163
48164
48165
48166
48167
48168
48169
48170
48171
48172
48173
48174
48175
48176
48177
48178
48179
48180
48181
48182
48183
48184
48185
48186
48187
48188
48189
48190
48191
48192
48193
48194
48195
48196
48197
48198
48199
48200
48201
48202
48203
48204
48205
48206
48207
48208
48209
48210
48211
48212
48213
48214
48215
48216
48217
48218
48219
48220
48221
48222
48223
48224
48225
48226
48227
48228
48229
48230
48231
48232
48233
48234
48235
48236
48237
48238
48239
48240
48241
48242
48243
48244
48245
48246
48247
48248
48249
48250
48251
48252
48253
48254
48255
48256
48257
48258
48259
48260
48261
48262
48263
48264
48265
48266
48267
48268
48269
48270
48271
48272
48273
48274
48275
48276
48277
48278
48279
48280
48281
48282
48283
48284
48285
48286
48287
48288
48289
48290
48291
48292
48293
48294
48295
48296
48297
48298
48299
48300
48301
48302
48303
48304
48305
48306
48307
48308
48309
48310
48311
48312
48313
48314
48315
48316
48317
48318
48319
48320
48321
48322
48323
48324
48325
48326
48327
48328
48329
48330
48331
48332
48333
48334
48335
48336
48337
48338
48339
48340
48341
48342
48343
48344
48345
48346
48347
48348
48349
48350
48351
48352
48353
48354
48355
48356
48357
48358
48359
48360
48361
48362
48363
48364
48365
48366
48367
48368
48369
48370
48371
48372
48373
48374
48375
48376
48377
48378
48379
48380
48381
48382
48383
48384
48385
48386
48387
48388
48389
48390
48391
48392
48393
48394
48395
48396
48397
48398
48399
48400
48401
48402
48403
48404
48405
48406
48407
48408
48409
48410
48411
48412
48413
48414
48415
48416
48417
48418
48419
48420
48421
48422
48423
48424
48425
48426
48427
48428
48429
48430
48431
48432
48433
48434
48435
48436
48437
48438
48439
48440
48441
48442
48443
48444
48445
48446
48447
48448
48449
48450
48451
48452
48453
48454
48455
48456
48457
48458
48459
48460
48461
48462
48463
48464
48465
48466
48467
48468
48469
48470
48471
48472
48473
48474
48475
48476
48477
48478
48479
48480
48481
48482
48483
48484
48485
48486
48487
48488
48489
48490
48491
48492
48493
48494
48495
48496
48497
48498
48499
48500
48501
48502
48503
48504
48505
48506
48507
48508
48509
48510
48511
48512
48513
48514
48515
48516
48517
48518
48519
48520
48521
48522
48523
48524
48525
48526
48527
48528
48529
48530
48531
48532
48533
48534
48535
48536
48537
48538
48539
48540
48541
48542
48543
48544
48545
48546
48547
48548
48549
48550
48551
48552
48553
48554
48555
48556
48557
48558
48559
48560
48561
48562
48563
48564
48565
48566
48567
48568
48569
48570
48571
48572
48573
48574
48575
48576
48577
48578
48579
48580
48581
48582
48583
48584
48585
48586
48587
48588
48589
48590
48591
48592
48593
48594
48595
48596
48597
48598
48599
48600
48601
48602
48603
48604
48605
48606
48607
48608
48609
48610
48611
48612
48613
48614
48615
48616
48617
48618
48619
48620
48621
48622
48623
48624
48625
48626
48627
48628
48629
48630
48631
48632
48633
48634
48635
48636
48637
48638
48639
48640
48641
48642
48643
48644
48645
48646
48647
48648
48649
48650
48651
48652
48653
48654
48655
48656
48657
48658
48659
48660
48661
48662
48663
48664
48665
48666
48667
48668
48669
48670
48671
48672
48673
48674
48675
48676
48677
48678
48679
48680
48681
48682
48683
48684
48685
48686
48687
48688
48689
48690
48691
48692
48693
48694
48695
48696
48697
48698
48699
48700
48701
48702
48703
48704
48705
48706
48707
48708
48709
48710
48711
48712
48713
48714
48715
48716
48717
48718
48719
48720
48721
48722
48723
48724
48725
48726
48727
48728
48729
48730
48731
48732
48733
48734
48735
48736
48737
48738
48739
48740
48741
48742
48743
48744
48745
48746
48747
48748
48749
48750
48751
48752
48753
48754
48755
48756
48757
48758
48759
48760
48761
48762
48763
48764
48765
48766
48767
48768
48769
48770
48771
48772
48773
48774
48775
48776
48777
48778
48779
48780
48781
48782
48783
48784
48785
48786
48787
48788
48789
48790
48791
48792
48793
48794
48795
48796
48797
48798
48799
48800
48801
48802
48803
48804
48805
48806
48807
48808
48809
48810
48811
48812
48813
48814
48815
48816
48817
48818
48819
48820
48821
48822
48823
48824
48825
48826
48827
48828
48829
48830
48831
48832
48833
48834
48835
48836
48837
48838
48839
48840
48841
48842
48843
48844
48845
48846
48847
48848
48849
48850
48851
48852
48853
48854
48855
48856
48857
48858
48859
48860
48861
48862
48863
48864
48865
48866
48867
48868
48869
48870
48871
48872
48873
48874
48875
48876
48877
48878
48879
48880
48881
48882
48883
48884
48885
48886
48887
48888
48889
48890
48891
48892
48893
48894
48895
48896
48897
48898
48899
48900
48901
48902
48903
48904
48905
48906
48907
48908
48909
48910
48911
48912
48913
48914
48915
48916
48917
48918
48919
48920
48921
48922
48923
48924
48925
48926
48927
48928
48929
48930
48931
48932
48933
48934
48935
48936
48937
48938
48939
48940
48941
48942
48943
48944
48945
48946
48947
48948
48949
48950
48951
48952
48953
48954
48955
48956
48957
48958
48959
48960
48961
48962
48963
48964
48965
48966
48967
48968
48969
48970
48971
48972
48973
48974
48975
48976
48977
48978
48979
48980
48981
48982
48983
48984
48985
48986
48987
48988
48989
48990
48991
48992
48993
48994
48995
48996
48997
48998
48999
49000
49001
49002
49003
49004
49005
49006
49007
49008
49009
49010
49011
49012
49013
49014
49015
49016
49017
49018
49019
49020
49021
49022
49023
49024
49025
49026
49027
49028
49029
49030
49031
49032
49033
49034
49035
49036
49037
49038
49039
49040
49041
49042
49043
49044
49045
49046
49047
49048
49049
49050
49051
49052
49053
49054
49055
49056
49057
49058
49059
49060
49061
49062
49063
49064
49065
49066
49067
49068
49069
49070
49071
49072
49073
49074
49075
49076
49077
49078
49079
49080
49081
49082
49083
49084
49085
49086
49087
49088
49089
49090
49091
49092
49093
49094
49095
49096
49097
49098
49099
49100
49101
49102
49103
49104
49105
49106
49107
49108
49109
49110
49111
49112
49113
49114
49115
49116
49117
49118
49119
49120
49121
49122
49123
49124
49125
49126
49127
49128
49129
49130
49131
49132
49133
49134
49135
49136
49137
49138
49139
49140
49141
49142
49143
49144
49145
49146
49147
49148
49149
49150
49151
49152
49153
49154
49155
49156
49157
49158
49159
49160
49161
49162
49163
49164
49165
49166
49167
49168
49169
49170
49171
49172
49173
49174
49175
49176
49177
49178
49179
49180
49181
49182
49183
49184
49185
49186
49187
49188
49189
49190
49191
49192
49193
49194
49195
49196
49197
49198
49199
49200
49201
49202
49203
49204
49205
49206
49207
49208
49209
49210
49211
49212
49213
49214
49215
49216
49217
49218
49219
49220
49221
49222
49223
49224
49225
49226
49227
49228
49229
49230
49231
49232
49233
49234
49235
49236
49237
49238
49239
49240
49241
49242
49243
49244
49245
49246
49247
49248
49249
49250
49251
49252
49253
49254
49255
49256
49257
49258
49259
49260
49261
49262
49263
49264
49265
49266
49267
49268
49269
49270
49271
49272
49273
49274
49275
49276
49277
49278
49279
49280
49281
49282
49283
49284
49285
49286
49287
49288
49289
49290
49291
49292
49293
49294
49295
49296
49297
49298
49299
49300
49301
49302
49303
49304
49305
49306
49307
49308
49309
49310
49311
49312
49313
49314
49315
49316
49317
49318
49319
49320
49321
49322
49323
49324
49325
49326
49327
49328
49329
49330
49331
49332
49333
49334
49335
49336
49337
49338
49339
49340
49341
49342
49343
49344
49345
49346
49347
49348
49349
49350
49351
49352
49353
49354
49355
49356
49357
49358
49359
49360
49361
49362
49363
49364
49365
49366
49367
49368
49369
49370
49371
49372
49373
49374
49375
49376
49377
49378
49379
49380
49381
49382
49383
49384
49385
49386
49387
49388
49389
49390
49391
49392
49393
49394
49395
49396
49397
49398
49399
49400
49401
49402
49403
49404
49405
49406
49407
49408
49409
49410
49411
49412
49413
49414
49415
49416
49417
49418
49419
49420
49421
49422
49423
49424
49425
49426
49427
49428
49429
49430
49431
49432
49433
49434
49435
49436
49437
49438
49439
49440
49441
49442
49443
49444
49445
49446
49447
49448
49449
49450
49451
49452
49453
49454
49455
49456
49457
49458
49459
49460
49461
49462
49463
49464
49465
49466
49467
49468
49469
49470
49471
49472
49473
49474
49475
49476
49477
49478
49479
49480
49481
49482
49483
49484
49485
49486
49487
49488
49489
49490
49491
49492
49493
49494
49495
49496
49497
49498
49499
49500
49501
49502
49503
49504
49505
49506
49507
49508
49509
49510
49511
49512
49513
49514
49515
49516
49517
49518
49519
49520
49521
49522
49523
49524
49525
49526
49527
49528
49529
49530
49531
49532
49533
49534
49535
49536
49537
49538
49539
49540
49541
49542
49543
49544
49545
49546
49547
49548
49549
49550
49551
49552
49553
49554
49555
49556
49557
49558
49559
49560
49561
49562
49563
49564
49565
49566
49567
49568
49569
49570
49571
49572
49573
49574
49575
49576
49577
49578
49579
49580
49581
49582
49583
49584
49585
49586
49587
49588
49589
49590
49591
49592
49593
49594
49595
49596
49597
49598
49599
49600
49601
49602
49603
49604
49605
49606
49607
49608
49609
49610
49611
49612
49613
49614
49615
49616
49617
49618
49619
49620
49621
49622
49623
49624
49625
49626
49627
49628
49629
49630
49631
49632
49633
49634
49635
49636
49637
49638
49639
49640
49641
49642
49643
49644
49645
49646
49647
49648
49649
49650
49651
49652
49653
49654
49655
49656
49657
49658
49659
49660
49661
49662
49663
49664
49665
49666
49667
49668
49669
49670
49671
49672
49673
49674
49675
49676
49677
49678
49679
49680
49681
49682
49683
49684
49685
49686
49687
49688
49689
49690
49691
49692
49693
49694
49695
49696
49697
49698
49699
49700
49701
49702
49703
49704
49705
49706
49707
49708
49709
49710
49711
49712
49713
49714
49715
49716
49717
49718
49719
49720
49721
49722
49723
49724
49725
49726
49727
49728
49729
49730
49731
49732
49733
49734
49735
49736
49737
49738
49739
49740
49741
49742
49743
49744
49745
49746
49747
49748
49749
49750
49751
49752
49753
49754
49755
49756
49757
49758
49759
49760
49761
49762
49763
49764
49765
49766
49767
49768
49769
49770
49771
49772
49773
49774
49775
49776
49777
49778
49779
49780
49781
49782
49783
49784
49785
49786
49787
49788
49789
49790
49791
49792
49793
49794
49795
49796
49797
49798
49799
49800
49801
49802
49803
49804
49805
49806
49807
49808
49809
49810
49811
49812
49813
49814
49815
49816
49817
49818
49819
49820
49821
49822
49823
49824
49825
49826
49827
49828
49829
49830
49831
49832
49833
49834
49835
49836
49837
49838
49839
49840
49841
49842
49843
49844
49845
49846
49847
49848
49849
49850
49851
49852
49853
49854
49855
49856
49857
49858
49859
49860
49861
49862
49863
49864
49865
49866
49867
49868
49869
49870
49871
49872
49873
49874
49875
49876
49877
49878
49879
49880
49881
49882
49883
49884
49885
49886
49887
49888
49889
49890
49891
49892
49893
49894
49895
49896
49897
49898
49899
49900
49901
49902
49903
49904
49905
49906
49907
49908
49909
49910
49911
49912
49913
49914
49915
49916
49917
49918
49919
49920
49921
49922
49923
49924
49925
49926
49927
49928
49929
49930
49931
49932
49933
49934
49935
49936
49937
49938
49939
49940
49941
49942
49943
49944
49945
49946
49947
49948
49949
49950
49951
49952
49953
49954
49955
49956
49957
49958
49959
49960
49961
49962
49963
49964
49965
49966
49967
49968
49969
49970
49971
49972
49973
49974
49975
49976
49977
49978
49979
49980
49981
49982
49983
49984
49985
49986
49987
49988
49989
49990
49991
49992
49993
49994
49995
49996
49997
49998
49999
50000
50001
50002
50003
50004
50005
50006
50007
50008
50009
50010
50011
50012
50013
50014
50015
50016
50017
50018
50019
50020
50021
50022
50023
50024
50025
50026
50027
50028
50029
50030
50031
50032
50033
50034
50035
50036
50037
50038
50039
50040
50041
50042
50043
50044
50045
50046
50047
50048
50049
50050
50051
50052
50053
50054
50055
50056
50057
50058
50059
50060
50061
50062
50063
50064
50065
50066
50067
50068
50069
50070
50071
50072
50073
50074
50075
50076
50077
50078
50079
50080
50081
50082
50083
50084
50085
50086
50087
50088
50089
50090
50091
50092
50093
50094
50095
50096
50097
50098
50099
50100
50101
50102
50103
50104
50105
50106
50107
50108
50109
50110
50111
50112
50113
50114
50115
50116
50117
50118
50119
50120
50121
50122
50123
50124
50125
50126
50127
50128
50129
50130
50131
50132
50133
50134
50135
50136
50137
50138
50139
50140
50141
50142
50143
50144
50145
50146
50147
50148
50149
50150
50151
50152
50153
50154
50155
50156
50157
50158
50159
50160
50161
50162
50163
50164
50165
50166
50167
50168
50169
50170
50171
50172
50173
50174
50175
50176
50177
50178
50179
50180
50181
50182
50183
50184
50185
50186
50187
50188
50189
50190
50191
50192
50193
50194
50195
50196
50197
50198
50199
50200
50201
50202
50203
50204
50205
50206
50207
50208
50209
50210
50211
50212
50213
50214
50215
50216
50217
50218
50219
50220
50221
50222
50223
50224
50225
50226
50227
50228
50229
50230
50231
50232
50233
50234
50235
50236
50237
50238
50239
50240
50241
50242
50243
50244
50245
50246
50247
50248
50249
50250
50251
50252
50253
50254
50255
50256
50257
50258
50259
50260
50261
50262
50263
50264
50265
50266
50267
50268
50269
50270
50271
50272
50273
50274
50275
50276
50277
50278
50279
50280
50281
50282
50283
50284
50285
50286
50287
50288
50289
50290
50291
50292
50293
50294
50295
50296
50297
50298
50299
50300
50301
50302
50303
50304
50305
50306
50307
50308
50309
50310
50311
50312
50313
50314
50315
50316
50317
50318
50319
50320
50321
50322
50323
50324
50325
50326
50327
50328
50329
50330
50331
50332
50333
50334
50335
50336
50337
50338
50339
50340
50341
50342
50343
50344
50345
50346
50347
50348
50349
50350
50351
50352
50353
50354
50355
50356
50357
50358
50359
50360
50361
50362
50363
50364
50365
50366
50367
50368
50369
50370
50371
50372
50373
50374
50375
50376
50377
50378
50379
50380
50381
50382
50383
50384
50385
50386
50387
50388
50389
50390
50391
50392
50393
50394
50395
50396
50397
50398
50399
50400
50401
50402
50403
50404
50405
50406
50407
50408
50409
50410
50411
50412
50413
50414
50415
50416
50417
50418
50419
50420
50421
50422
50423
50424
50425
50426
50427
50428
50429
50430
50431
50432
50433
50434
50435
50436
50437
50438
50439
50440
50441
50442
50443
50444
50445
50446
50447
50448
50449
50450
50451
50452
50453
50454
50455
50456
50457
50458
50459
50460
50461
50462
50463
50464
50465
50466
50467
50468
50469
50470
50471
50472
50473
50474
50475
50476
50477
50478
50479
50480
50481
50482
50483
50484
50485
50486
50487
50488
50489
50490
50491
50492
50493
50494
50495
50496
50497
50498
50499
50500
50501
50502
50503
50504
50505
50506
50507
50508
50509
50510
50511
50512
50513
50514
50515
50516
50517
50518
50519
50520
50521
50522
50523
50524
50525
50526
50527
50528
50529
50530
50531
50532
50533
50534
50535
50536
50537
50538
50539
50540
50541
50542
50543
50544
50545
50546
50547
50548
50549
50550
50551
50552
50553
50554
50555
50556
50557
50558
50559
50560
50561
50562
50563
50564
50565
50566
50567
50568
50569
50570
50571
50572
50573
50574
50575
50576
50577
50578
50579
50580
50581
50582
50583
50584
50585
50586
50587
50588
50589
50590
50591
50592
50593
50594
50595
50596
50597
50598
50599
50600
50601
50602
50603
50604
50605
50606
50607
50608
50609
50610
50611
50612
50613
50614
50615
50616
50617
50618
50619
50620
50621
50622
50623
50624
50625
50626
50627
50628
50629
50630
50631
50632
50633
50634
50635
50636
50637
50638
50639
50640
50641
50642
50643
50644
50645
50646
50647
50648
50649
50650
50651
50652
50653
50654
50655
50656
50657
50658
50659
50660
50661
50662
50663
50664
50665
50666
50667
50668
50669
50670
50671
50672
50673
50674
50675
50676
50677
50678
50679
50680
50681
50682
50683
50684
50685
50686
50687
50688
50689
50690
50691
50692
50693
50694
50695
50696
50697
50698
50699
50700
50701
50702
50703
50704
50705
50706
50707
50708
50709
50710
50711
50712
50713
50714
50715
50716
50717
50718
50719
50720
50721
50722
50723
50724
50725
50726
50727
50728
50729
50730
50731
50732
50733
50734
50735
50736
50737
50738
50739
50740
50741
50742
50743
50744
50745
50746
50747
50748
50749
50750
50751
50752
50753
50754
50755
50756
50757
50758
50759
50760
50761
50762
50763
50764
50765
50766
50767
50768
50769
50770
50771
50772
50773
50774
50775
50776
50777
50778
50779
50780
50781
50782
50783
50784
50785
50786
50787
50788
50789
50790
50791
50792
50793
50794
50795
50796
50797
50798
50799
50800
50801
50802
50803
50804
50805
50806
50807
50808
50809
50810
50811
50812
50813
50814
50815
50816
50817
50818
50819
50820
50821
50822
50823
50824
50825
50826
50827
50828
50829
50830
50831
50832
50833
50834
50835
50836
50837
50838
50839
50840
50841
50842
50843
50844
50845
50846
50847
50848
50849
50850
50851
50852
50853
50854
50855
50856
50857
50858
50859
50860
50861
50862
50863
50864
50865
50866
50867
50868
50869
50870
50871
50872
50873
50874
50875
50876
50877
50878
50879
50880
50881
50882
50883
50884
50885
50886
50887
50888
50889
50890
50891
50892
50893
50894
50895
50896
50897
50898
50899
50900
50901
50902
50903
50904
50905
50906
50907
50908
50909
50910
50911
50912
50913
50914
50915
50916
50917
50918
50919
50920
50921
50922
50923
50924
50925
50926
50927
50928
50929
50930
50931
50932
50933
50934
50935
50936
50937
50938
50939
50940
50941
50942
50943
50944
50945
50946
50947
50948
50949
50950
50951
50952
50953
50954
50955
50956
50957
50958
50959
50960
50961
50962
50963
50964
50965
50966
50967
50968
50969
50970
50971
50972
50973
50974
50975
50976
50977
50978
50979
50980
50981
50982
50983
50984
50985
50986
50987
50988
50989
50990
50991
50992
50993
50994
50995
50996
50997
50998
50999
51000
51001
51002
51003
51004
51005
51006
51007
51008
51009
51010
51011
51012
51013
51014
51015
51016
51017
51018
51019
51020
51021
51022
51023
51024
51025
51026
51027
51028
51029
51030
51031
51032
51033
51034
51035
51036
51037
51038
51039
51040
51041
51042
51043
51044
51045
51046
51047
51048
51049
51050
51051
51052
51053
51054
51055
51056
51057
51058
51059
51060
51061
51062
51063
51064
51065
51066
51067
51068
51069
51070
51071
51072
51073
51074
51075
51076
51077
51078
51079
51080
51081
51082
51083
51084
51085
51086
51087
51088
51089
51090
51091
51092
51093
51094
51095
51096
51097
51098
51099
51100
51101
51102
51103
51104
51105
51106
51107
51108
51109
51110
51111
51112
51113
51114
51115
51116
51117
51118
51119
51120
51121
51122
51123
51124
51125
51126
51127
51128
51129
51130
51131
51132
51133
51134
51135
51136
51137
51138
51139
51140
51141
51142
51143
51144
51145
51146
51147
51148
51149
51150
51151
51152
51153
51154
51155
51156
51157
51158
51159
51160
51161
51162
51163
51164
51165
51166
51167
51168
51169
51170
51171
51172
51173
51174
51175
51176
51177
51178
51179
51180
51181
51182
51183
51184
51185
51186
51187
51188
51189
51190
51191
51192
51193
51194
51195
51196
51197
51198
51199
51200
51201
51202
51203
51204
51205
51206
51207
51208
51209
51210
51211
51212
51213
51214
51215
51216
51217
51218
51219
51220
51221
51222
51223
51224
51225
51226
51227
51228
51229
51230
51231
51232
51233
51234
51235
51236
51237
51238
51239
51240
51241
51242
51243
51244
51245
51246
51247
51248
51249
51250
51251
51252
51253
51254
51255
51256
51257
51258
51259
51260
51261
51262
51263
51264
51265
51266
51267
51268
51269
51270
51271
51272
51273
51274
51275
51276
51277
51278
51279
51280
51281
51282
51283
51284
51285
51286
51287
51288
51289
51290
51291
51292
51293
51294
51295
51296
51297
51298
51299
51300
51301
51302
51303
51304
51305
51306
51307
51308
51309
51310
51311
51312
51313
51314
51315
51316
51317
51318
51319
51320
51321
51322
51323
51324
51325
51326
51327
51328
51329
51330
51331
51332
51333
51334
51335
51336
51337
51338
51339
51340
51341
51342
51343
51344
51345
51346
51347
51348
51349
51350
51351
51352
51353
51354
51355
51356
51357
51358
51359
51360
51361
51362
51363
51364
51365
51366
51367
51368
51369
51370
51371
51372
51373
51374
51375
51376
51377
51378
51379
51380
51381
51382
51383
51384
51385
51386
51387
51388
51389
51390
51391
51392
51393
51394
51395
51396
51397
51398
51399
51400
51401
51402
51403
51404
51405
51406
51407
51408
51409
51410
51411
51412
51413
51414
51415
51416
51417
51418
51419
51420
51421
51422
51423
51424
51425
51426
51427
51428
51429
51430
51431
51432
51433
51434
51435
51436
51437
51438
51439
51440
51441
51442
51443
51444
51445
51446
51447
51448
51449
51450
51451
51452
51453
51454
51455
51456
51457
51458
51459
51460
51461
51462
51463
51464
51465
51466
51467
51468
51469
51470
51471
51472
51473
51474
51475
51476
51477
51478
51479
51480
51481
51482
51483
51484
51485
51486
51487
51488
51489
51490
51491
51492
51493
51494
51495
51496
51497
51498
51499
51500
51501
51502
51503
51504
51505
51506
51507
51508
51509
51510
51511
51512
51513
51514
51515
51516
51517
51518
51519
51520
51521
51522
51523
51524
51525
51526
51527
51528
51529
51530
51531
51532
51533
51534
51535
51536
51537
51538
51539
51540
51541
51542
51543
51544
51545
51546
51547
51548
51549
51550
51551
51552
51553
51554
51555
51556
51557
51558
51559
51560
51561
51562
51563
51564
51565
51566
51567
51568
51569
51570
51571
51572
51573
51574
51575
51576
51577
51578
51579
51580
51581
51582
51583
51584
51585
51586
51587
51588
51589
51590
51591
51592
51593
51594
51595
51596
51597
51598
51599
51600
51601
51602
51603
51604
51605
51606
51607
51608
51609
51610
51611
51612
51613
51614
51615
51616
51617
51618
51619
51620
51621
51622
51623
51624
51625
51626
51627
51628
51629
51630
51631
51632
51633
51634
51635
51636
51637
51638
51639
51640
51641
51642
51643
51644
51645
51646
51647
51648
51649
51650
51651
51652
51653
51654
51655
51656
51657
51658
51659
51660
51661
51662
51663
51664
51665
51666
51667
51668
51669
51670
51671
51672
51673
51674
51675
51676
51677
51678
51679
51680
51681
51682
51683
51684
51685
51686
51687
51688
51689
51690
51691
51692
51693
51694
51695
51696
51697
51698
51699
51700
51701
51702
51703
51704
51705
51706
51707
51708
51709
51710
51711
51712
51713
51714
51715
51716
51717
51718
51719
51720
51721
51722
51723
51724
51725
51726
51727
51728
51729
51730
51731
51732
51733
51734
51735
51736
51737
51738
51739
51740
51741
51742
51743
51744
51745
51746
51747
51748
51749
51750
51751
51752
51753
51754
51755
51756
51757
51758
51759
51760
51761
51762
51763
51764
51765
51766
51767
51768
51769
51770
51771
51772
51773
51774
51775
51776
51777
51778
51779
51780
51781
51782
51783
51784
51785
51786
51787
51788
51789
51790
51791
51792
51793
51794
51795
51796
51797
51798
51799
51800
51801
51802
51803
51804
51805
51806
51807
51808
51809
51810
51811
51812
51813
51814
51815
51816
51817
51818
51819
51820
51821
51822
51823
51824
51825
51826
51827
51828
51829
51830
51831
51832
51833
51834
51835
51836
51837
51838
51839
51840
51841
51842
51843
51844
51845
51846
51847
51848
51849
51850
51851
51852
51853
51854
51855
51856
51857
51858
51859
51860
51861
51862
51863
51864
51865
51866
51867
51868
51869
51870
51871
51872
51873
51874
51875
51876
51877
51878
51879
51880
51881
51882
51883
51884
51885
51886
51887
51888
51889
51890
51891
51892
51893
51894
51895
51896
51897
51898
51899
51900
51901
51902
51903
51904
51905
51906
51907
51908
51909
51910
51911
51912
51913
51914
51915
51916
51917
51918
51919
51920
51921
51922
51923
51924
51925
51926
51927
51928
51929
51930
51931
51932
51933
51934
51935
51936
51937
51938
51939
51940
51941
51942
51943
51944
51945
51946
51947
51948
51949
51950
51951
51952
51953
51954
51955
51956
51957
51958
51959
51960
51961
51962
51963
51964
51965
51966
51967
51968
51969
51970
51971
51972
51973
51974
51975
51976
51977
51978
51979
51980
51981
51982
51983
51984
51985
51986
51987
51988
51989
51990
51991
51992
51993
51994
51995
51996
51997
51998
51999
52000
52001
52002
52003
52004
52005
52006
52007
52008
52009
52010
52011
52012
52013
52014
52015
52016
52017
52018
52019
52020
52021
52022
52023
52024
52025
52026
52027
52028
52029
52030
52031
52032
52033
52034
52035
52036
52037
52038
52039
52040
52041
52042
52043
52044
52045
52046
52047
52048
52049
52050
52051
52052
52053
52054
52055
52056
52057
52058
52059
52060
52061
52062
52063
52064
52065
52066
52067
52068
52069
52070
52071
52072
52073
52074
52075
52076
52077
52078
52079
52080
52081
52082
52083
52084
52085
52086
52087
52088
52089
52090
52091
52092
52093
52094
52095
52096
52097
52098
52099
52100
52101
52102
52103
52104
52105
52106
52107
52108
52109
52110
52111
52112
52113
52114
52115
52116
52117
52118
52119
52120
52121
52122
52123
52124
52125
52126
52127
52128
52129
52130
52131
52132
52133
52134
52135
52136
52137
52138
52139
52140
52141
52142
52143
52144
52145
52146
52147
52148
52149
52150
52151
52152
52153
52154
52155
52156
52157
52158
52159
52160
52161
52162
52163
52164
52165
52166
52167
52168
52169
52170
52171
52172
52173
52174
52175
52176
52177
52178
52179
52180
52181
52182
52183
52184
52185
52186
52187
52188
52189
52190
52191
52192
52193
52194
52195
52196
52197
52198
52199
52200
52201
52202
52203
52204
52205
52206
52207
52208
52209
52210
52211
52212
52213
52214
52215
52216
52217
52218
52219
52220
52221
52222
52223
52224
52225
52226
52227
52228
52229
52230
52231
52232
52233
52234
52235
52236
52237
52238
52239
52240
52241
52242
52243
52244
52245
52246
52247
52248
52249
52250
52251
52252
52253
52254
52255
52256
52257
52258
52259
52260
52261
52262
52263
52264
52265
52266
52267
52268
52269
52270
52271
52272
52273
52274
52275
52276
52277
52278
52279
52280
52281
52282
52283
52284
52285
52286
52287
52288
52289
52290
52291
52292
52293
52294
52295
52296
52297
52298
52299
52300
52301
52302
52303
52304
52305
52306
52307
52308
52309
52310
52311
52312
52313
52314
52315
52316
52317
52318
52319
52320
52321
52322
52323
52324
52325
52326
52327
52328
52329
52330
52331
52332
52333
52334
52335
52336
52337
52338
52339
52340
52341
52342
52343
52344
52345
52346
52347
52348
52349
52350
52351
52352
52353
52354
52355
52356
52357
52358
52359
52360
52361
52362
52363
52364
52365
52366
52367
52368
52369
52370
52371
52372
52373
52374
52375
52376
52377
52378
52379
52380
52381
52382
52383
52384
52385
52386
52387
52388
52389
52390
52391
52392
52393
52394
52395
52396
52397
52398
52399
52400
52401
52402
52403
52404
52405
52406
52407
52408
52409
52410
52411
52412
52413
52414
52415
52416
52417
52418
52419
52420
52421
52422
52423
52424
52425
52426
52427
52428
52429
52430
52431
52432
52433
52434
52435
52436
52437
52438
52439
52440
52441
52442
52443
52444
52445
52446
52447
52448
52449
52450
52451
52452
52453
52454
52455
52456
52457
52458
52459
52460
52461
52462
52463
52464
52465
52466
52467
52468
52469
52470
52471
52472
52473
52474
52475
52476
52477
52478
52479
52480
52481
52482
52483
52484
52485
52486
52487
52488
52489
52490
52491
52492
52493
52494
52495
52496
52497
52498
52499
52500
52501
52502
52503
52504
52505
52506
52507
52508
52509
52510
52511
52512
52513
52514
52515
52516
52517
52518
52519
52520
52521
52522
52523
52524
52525
52526
52527
52528
52529
52530
52531
52532
52533
52534
52535
52536
52537
52538
52539
52540
52541
52542
52543
52544
52545
52546
52547
52548
52549
52550
52551
52552
52553
52554
52555
52556
52557
52558
52559
52560
52561
52562
52563
52564
52565
52566
52567
52568
52569
52570
52571
52572
52573
52574
52575
52576
52577
52578
52579
52580
52581
52582
52583
52584
52585
52586
52587
52588
52589
52590
52591
52592
52593
52594
52595
52596
52597
52598
52599
52600
52601
52602
52603
52604
52605
52606
52607
52608
52609
52610
52611
52612
52613
52614
52615
52616
52617
52618
52619
52620
52621
52622
52623
52624
52625
52626
52627
52628
52629
52630
52631
52632
52633
52634
52635
52636
52637
52638
52639
52640
52641
52642
52643
52644
52645
52646
52647
52648
52649
52650
52651
52652
52653
52654
52655
52656
52657
52658
52659
52660
52661
52662
52663
52664
52665
52666
52667
52668
52669
52670
52671
52672
52673
52674
52675
52676
52677
52678
52679
52680
52681
52682
52683
52684
52685
52686
52687
52688
52689
52690
52691
52692
52693
52694
52695
52696
52697
52698
52699
52700
52701
52702
52703
52704
52705
52706
52707
52708
52709
52710
52711
52712
52713
52714
52715
52716
52717
52718
52719
52720
52721
52722
52723
52724
52725
52726
52727
52728
52729
52730
52731
52732
52733
52734
52735
52736
52737
52738
52739
52740
52741
52742
52743
52744
52745
52746
52747
52748
52749
52750
52751
52752
52753
52754
52755
52756
52757
52758
52759
52760
52761
52762
52763
52764
52765
52766
52767
52768
52769
52770
52771
52772
52773
52774
52775
52776
52777
52778
52779
52780
52781
52782
52783
52784
52785
52786
52787
52788
52789
52790
52791
52792
52793
52794
52795
52796
52797
52798
52799
52800
52801
52802
52803
52804
52805
52806
52807
52808
52809
52810
52811
52812
52813
52814
52815
52816
52817
52818
52819
52820
52821
52822
52823
52824
52825
52826
52827
52828
52829
52830
52831
52832
52833
52834
52835
52836
52837
52838
52839
52840
52841
52842
52843
52844
52845
52846
52847
52848
52849
52850
52851
52852
52853
52854
52855
52856
52857
52858
52859
52860
52861
52862
52863
52864
52865
52866
52867
52868
52869
52870
52871
52872
52873
52874
52875
52876
52877
52878
52879
52880
52881
52882
52883
52884
52885
52886
52887
52888
52889
52890
52891
52892
52893
52894
52895
52896
52897
52898
52899
52900
52901
52902
52903
52904
52905
52906
52907
52908
52909
52910
52911
52912
52913
52914
52915
52916
52917
52918
52919
52920
52921
52922
52923
52924
52925
52926
52927
52928
52929
52930
52931
52932
52933
52934
52935
52936
52937
52938
52939
52940
52941
52942
52943
52944
52945
52946
52947
52948
52949
52950
52951
52952
52953
52954
52955
52956
52957
52958
52959
52960
52961
52962
52963
52964
52965
52966
52967
52968
52969
52970
52971
52972
52973
52974
52975
52976
52977
52978
52979
52980
52981
52982
52983
52984
52985
52986
52987
52988
52989
52990
52991
52992
52993
52994
52995
52996
52997
52998
52999
53000
53001
53002
53003
53004
53005
53006
53007
53008
53009
53010
53011
53012
53013
53014
53015
53016
53017
53018
53019
53020
53021
53022
53023
53024
53025
53026
53027
53028
53029
53030
53031
53032
53033
53034
53035
53036
53037
53038
53039
53040
53041
53042
53043
53044
53045
53046
53047
53048
53049
53050
53051
53052
53053
53054
53055
53056
53057
53058
53059
53060
53061
53062
53063
53064
53065
53066
53067
53068
53069
53070
53071
53072
53073
53074
53075
53076
53077
53078
53079
53080
53081
53082
53083
53084
53085
53086
53087
53088
53089
53090
53091
53092
53093
53094
53095
53096
53097
53098
53099
53100
53101
53102
53103
53104
53105
53106
53107
53108
53109
53110
53111
53112
53113
53114
53115
53116
53117
53118
53119
53120
53121
53122
53123
53124
53125
53126
53127
53128
53129
53130
53131
53132
53133
53134
53135
53136
53137
53138
53139
53140
53141
53142
53143
53144
53145
53146
53147
53148
53149
53150
53151
53152
53153
53154
53155
53156
53157
53158
53159
53160
53161
53162
53163
53164
53165
53166
53167
53168
53169
53170
53171
53172
53173
53174
53175
53176
53177
53178
53179
53180
53181
53182
53183
53184
53185
53186
53187
53188
53189
53190
53191
53192
53193
53194
53195
53196
53197
53198
53199
53200
53201
53202
53203
53204
53205
53206
53207
53208
53209
53210
53211
53212
53213
53214
53215
53216
53217
53218
53219
53220
53221
53222
53223
53224
53225
53226
53227
53228
53229
53230
53231
53232
53233
53234
53235
53236
53237
53238
53239
53240
53241
53242
53243
53244
53245
53246
53247
53248
53249
53250
53251
53252
53253
53254
53255
53256
53257
53258
53259
53260
53261
53262
53263
53264
53265
53266
53267
53268
53269
53270
53271
53272
53273
53274
53275
53276
53277
53278
53279
53280
53281
53282
53283
53284
53285
53286
53287
53288
53289
53290
53291
53292
53293
53294
53295
53296
53297
53298
53299
53300
53301
53302
53303
53304
53305
53306
53307
53308
53309
53310
53311
53312
53313
53314
53315
53316
53317
53318
53319
53320
53321
53322
53323
53324
53325
53326
53327
53328
53329
53330
53331
53332
53333
53334
53335
53336
53337
53338
53339
53340
53341
53342
53343
53344
53345
53346
53347
53348
53349
53350
53351
53352
53353
53354
53355
53356
53357
53358
53359
53360
53361
53362
53363
53364
53365
53366
53367
53368
53369
53370
53371
53372
53373
53374
53375
53376
53377
53378
53379
53380
53381
53382
53383
53384
53385
53386
53387
53388
53389
53390
53391
53392
53393
53394
53395
53396
53397
53398
53399
53400
53401
53402
53403
53404
53405
53406
53407
53408
53409
53410
53411
53412
53413
53414
53415
53416
53417
53418
53419
53420
53421
53422
53423
53424
53425
53426
53427
53428
53429
53430
53431
53432
53433
53434
53435
53436
53437
53438
53439
53440
53441
53442
53443
53444
53445
53446
53447
53448
53449
53450
53451
53452
53453
53454
53455
53456
53457
53458
53459
53460
53461
53462
53463
53464
53465
53466
53467
53468
53469
53470
53471
53472
53473
53474
53475
53476
53477
53478
53479
53480
53481
53482
53483
53484
53485
53486
53487
53488
53489
53490
53491
53492
53493
53494
53495
53496
53497
53498
53499
53500
53501
53502
53503
53504
53505
53506
53507
53508
53509
53510
53511
53512
53513
53514
53515
53516
53517
53518
53519
53520
53521
53522
53523
53524
53525
53526
53527
53528
53529
53530
53531
53532
53533
53534
53535
53536
53537
53538
53539
53540
53541
53542
53543
53544
53545
53546
53547
53548
53549
53550
53551
53552
53553
53554
53555
53556
53557
53558
53559
53560
53561
53562
53563
53564
53565
53566
53567
53568
53569
53570
53571
53572
53573
53574
53575
53576
53577
53578
53579
53580
53581
53582
53583
53584
53585
53586
53587
53588
53589
53590
53591
53592
53593
53594
53595
53596
53597
53598
53599
53600
53601
53602
53603
53604
53605
53606
53607
53608
53609
53610
53611
53612
53613
53614
53615
53616
53617
53618
53619
53620
53621
53622
53623
53624
53625
53626
53627
53628
53629
53630
53631
53632
53633
53634
53635
53636
53637
53638
53639
53640
53641
53642
53643
53644
53645
53646
53647
53648
53649
53650
53651
53652
53653
53654
53655
53656
53657
53658
53659
53660
53661
53662
53663
53664
53665
53666
53667
53668
53669
53670
53671
53672
53673
53674
53675
53676
53677
53678
53679
53680
53681
53682
53683
53684
53685
53686
53687
53688
53689
53690
53691
53692
53693
53694
53695
53696
53697
53698
53699
53700
53701
53702
53703
53704
53705
53706
53707
53708
53709
53710
53711
53712
53713
53714
53715
53716
53717
53718
53719
53720
53721
53722
53723
53724
53725
53726
53727
53728
53729
53730
53731
53732
53733
53734
53735
53736
53737
53738
53739
53740
53741
53742
53743
53744
53745
53746
53747
53748
53749
53750
53751
53752
53753
53754
53755
53756
53757
53758
53759
53760
53761
53762
53763
53764
53765
53766
53767
53768
53769
53770
53771
53772
53773
53774
53775
53776
53777
53778
53779
53780
53781
53782
53783
53784
53785
53786
53787
53788
53789
53790
53791
53792
53793
53794
53795
53796
53797
53798
53799
53800
53801
53802
53803
53804
53805
53806
53807
53808
53809
53810
53811
53812
53813
53814
53815
53816
53817
53818
53819
53820
53821
53822
53823
53824
53825
53826
53827
53828
53829
53830
53831
53832
53833
53834
53835
53836
53837
53838
53839
53840
53841
53842
53843
53844
53845
53846
53847
53848
53849
53850
53851
53852
53853
53854
53855
53856
53857
53858
53859
53860
53861
53862
53863
53864
53865
53866
53867
53868
53869
53870
53871
53872
53873
53874
53875
53876
53877
53878
53879
53880
53881
53882
53883
53884
53885
53886
53887
53888
53889
53890
53891
53892
53893
53894
53895
53896
53897
53898
53899
53900
53901
53902
53903
53904
53905
53906
53907
53908
53909
53910
53911
53912
53913
53914
53915
53916
53917
53918
53919
53920
53921
53922
53923
53924
53925
53926
53927
53928
53929
53930
53931
53932
53933
53934
53935
53936
53937
53938
53939
53940
53941
53942
53943
53944
53945
53946
53947
53948
53949
53950
53951
53952
53953
53954
53955
53956
53957
53958
53959
53960
53961
53962
53963
53964
53965
53966
53967
53968
53969
53970
53971
53972
53973
53974
53975
53976
53977
53978
53979
53980
53981
53982
53983
53984
53985
53986
53987
53988
53989
53990
53991
53992
53993
53994
53995
53996
53997
53998
53999
54000
54001
54002
54003
54004
54005
54006
54007
54008
54009
54010
54011
54012
54013
54014
54015
54016
54017
54018
54019
54020
54021
54022
54023
54024
54025
54026
54027
54028
54029
54030
54031
54032
54033
54034
54035
54036
54037
54038
54039
54040
54041
54042
54043
54044
54045
54046
54047
54048
54049
54050
54051
54052
54053
54054
54055
54056
54057
54058
54059
54060
54061
54062
54063
54064
54065
54066
54067
54068
54069
54070
54071
54072
54073
54074
54075
54076
54077
54078
54079
54080
54081
54082
54083
54084
54085
54086
54087
54088
54089
54090
54091
54092
54093
54094
54095
54096
54097
54098
54099
54100
54101
54102
54103
54104
54105
54106
54107
54108
54109
54110
54111
54112
54113
54114
54115
54116
54117
54118
54119
54120
54121
54122
54123
54124
54125
54126
54127
54128
54129
54130
54131
54132
54133
54134
54135
54136
54137
54138
54139
54140
54141
54142
54143
54144
54145
54146
54147
54148
54149
54150
54151
54152
54153
54154
54155
54156
54157
54158
54159
54160
54161
54162
54163
54164
54165
54166
54167
54168
54169
54170
54171
54172
54173
54174
54175
54176
54177
54178
54179
54180
54181
54182
54183
54184
54185
54186
54187
54188
54189
54190
54191
54192
54193
54194
54195
54196
54197
54198
54199
54200
54201
54202
54203
54204
54205
54206
54207
54208
54209
54210
54211
54212
54213
54214
54215
54216
54217
54218
54219
54220
54221
54222
54223
54224
54225
54226
54227
54228
54229
54230
54231
54232
54233
54234
54235
54236
54237
54238
54239
54240
54241
54242
54243
54244
54245
54246
54247
54248
54249
54250
54251
54252
54253
54254
54255
54256
54257
54258
54259
54260
54261
54262
54263
54264
54265
54266
54267
54268
54269
54270
54271
54272
54273
54274
54275
54276
54277
54278
54279
54280
54281
54282
54283
54284
54285
54286
54287
54288
54289
54290
54291
54292
54293
54294
54295
54296
54297
54298
54299
54300
54301
54302
54303
54304
54305
54306
54307
54308
54309
54310
54311
54312
54313
54314
54315
54316
54317
54318
54319
54320
54321
54322
54323
54324
54325
54326
54327
54328
54329
54330
54331
54332
54333
54334
54335
54336
54337
54338
54339
54340
54341
54342
54343
54344
54345
54346
54347
54348
54349
54350
54351
54352
54353
54354
54355
54356
54357
54358
54359
54360
54361
54362
54363
54364
54365
54366
54367
54368
54369
54370
54371
54372
54373
54374
54375
54376
54377
54378
54379
54380
54381
54382
54383
54384
54385
54386
54387
54388
54389
54390
54391
54392
54393
54394
54395
54396
54397
54398
54399
54400
54401
54402
54403
54404
54405
54406
54407
54408
54409
54410
54411
54412
54413
54414
54415
54416
54417
54418
54419
54420
54421
54422
54423
54424
54425
54426
54427
54428
54429
54430
54431
54432
54433
54434
54435
54436
54437
54438
54439
54440
54441
54442
54443
54444
54445
54446
54447
54448
54449
54450
54451
54452
54453
54454
54455
54456
54457
54458
54459
54460
54461
54462
54463
54464
54465
54466
54467
54468
54469
54470
54471
54472
54473
54474
54475
54476
54477
54478
54479
54480
54481
54482
54483
54484
54485
54486
54487
54488
54489
54490
54491
54492
54493
54494
54495
54496
54497
54498
54499
54500
54501
54502
54503
54504
54505
54506
54507
54508
54509
54510
54511
54512
54513
54514
54515
54516
54517
54518
54519
54520
54521
54522
54523
54524
54525
54526
54527
54528
54529
54530
54531
54532
54533
54534
54535
54536
54537
54538
54539
54540
54541
54542
54543
54544
54545
54546
54547
54548
54549
54550
54551
54552
54553
54554
54555
54556
54557
54558
54559
54560
54561
54562
54563
54564
54565
54566
54567
54568
54569
54570
54571
54572
54573
54574
54575
54576
54577
54578
54579
54580
54581
54582
54583
54584
54585
54586
54587
54588
54589
54590
54591
54592
54593
54594
54595
54596
54597
54598
54599
54600
54601
54602
54603
54604
54605
54606
54607
54608
54609
54610
54611
54612
54613
54614
54615
54616
54617
54618
54619
54620
54621
54622
54623
54624
54625
54626
54627
54628
54629
54630
54631
54632
54633
54634
54635
54636
54637
54638
54639
54640
54641
54642
54643
54644
54645
54646
54647
54648
54649
54650
54651
54652
54653
54654
54655
54656
54657
54658
54659
54660
54661
54662
54663
54664
54665
54666
54667
54668
54669
54670
54671
54672
54673
54674
54675
54676
54677
54678
54679
54680
54681
54682
54683
54684
54685
54686
54687
54688
54689
54690
54691
54692
54693
54694
54695
54696
54697
54698
54699
54700
54701
54702
54703
54704
54705
54706
54707
54708
54709
54710
54711
54712
54713
54714
54715
54716
54717
54718
54719
54720
54721
54722
54723
54724
54725
54726
54727
54728
54729
54730
54731
54732
54733
54734
54735
54736
54737
54738
54739
54740
54741
54742
54743
54744
54745
54746
54747
54748
54749
54750
54751
54752
54753
54754
54755
54756
54757
54758
54759
54760
54761
54762
54763
54764
54765
54766
54767
54768
54769
54770
54771
54772
54773
54774
54775
54776
54777
54778
54779
54780
54781
54782
54783
54784
54785
54786
54787
54788
54789
54790
54791
54792
54793
54794
54795
54796
54797
54798
54799
54800
54801
54802
54803
54804
54805
54806
54807
54808
54809
54810
54811
54812
54813
54814
54815
54816
54817
54818
54819
54820
54821
54822
54823
54824
54825
54826
54827
54828
54829
54830
54831
54832
54833
54834
54835
54836
54837
54838
54839
54840
54841
54842
54843
54844
54845
54846
54847
54848
54849
54850
54851
54852
54853
54854
54855
54856
54857
54858
54859
54860
54861
54862
54863
54864
54865
54866
54867
54868
54869
54870
54871
54872
54873
54874
54875
54876
54877
54878
54879
54880
54881
54882
54883
54884
54885
54886
54887
54888
54889
54890
54891
54892
54893
54894
54895
54896
54897
54898
54899
54900
54901
54902
54903
54904
54905
54906
54907
54908
54909
54910
54911
54912
54913
54914
54915
54916
54917
54918
54919
54920
54921
54922
54923
54924
54925
54926
54927
54928
54929
54930
54931
54932
54933
54934
54935
54936
54937
54938
54939
54940
54941
54942
54943
54944
54945
54946
54947
54948
54949
54950
54951
54952
54953
54954
54955
54956
54957
54958
54959
54960
54961
54962
54963
54964
54965
54966
54967
54968
54969
54970
54971
54972
54973
54974
54975
54976
54977
54978
54979
54980
54981
54982
54983
54984
54985
54986
54987
54988
54989
54990
54991
54992
54993
54994
54995
54996
54997
54998
54999
55000
55001
55002
55003
55004
55005
55006
55007
55008
55009
55010
55011
55012
55013
55014
55015
55016
55017
55018
55019
55020
55021
55022
55023
55024
55025
55026
55027
55028
55029
55030
55031
55032
55033
55034
55035
55036
55037
55038
55039
55040
55041
55042
55043
55044
55045
55046
55047
55048
55049
55050
55051
55052
55053
55054
55055
55056
55057
55058
55059
55060
55061
55062
55063
55064
55065
55066
55067
55068
55069
55070
55071
55072
55073
55074
55075
55076
55077
55078
55079
55080
55081
55082
55083
55084
55085
55086
55087
55088
55089
55090
55091
55092
55093
55094
55095
55096
55097
55098
55099
55100
55101
55102
55103
55104
55105
55106
55107
55108
55109
55110
55111
55112
55113
55114
55115
55116
55117
55118
55119
55120
55121
55122
55123
55124
55125
55126
55127
55128
55129
55130
55131
55132
55133
55134
55135
55136
55137
55138
55139
55140
55141
55142
55143
55144
55145
55146
55147
55148
55149
55150
55151
55152
55153
55154
55155
55156
55157
55158
55159
55160
55161
55162
55163
55164
55165
55166
55167
55168
55169
55170
55171
55172
55173
55174
55175
55176
55177
55178
55179
55180
55181
55182
55183
55184
55185
55186
55187
55188
55189
55190
55191
55192
55193
55194
55195
55196
55197
55198
55199
55200
55201
55202
55203
55204
55205
55206
55207
55208
55209
55210
55211
55212
55213
55214
55215
55216
55217
55218
55219
55220
55221
55222
55223
55224
55225
55226
55227
55228
55229
55230
55231
55232
55233
55234
55235
55236
55237
55238
55239
55240
55241
55242
55243
55244
55245
55246
55247
55248
55249
55250
55251
55252
55253
55254
55255
55256
55257
55258
55259
55260
55261
55262
55263
55264
55265
55266
55267
55268
55269
55270
55271
55272
55273
55274
55275
55276
55277
55278
55279
55280
55281
55282
55283
55284
55285
55286
55287
55288
55289
55290
55291
55292
55293
55294
55295
55296
55297
55298
55299
55300
55301
55302
55303
55304
55305
55306
55307
55308
55309
55310
55311
55312
55313
55314
55315
55316
55317
55318
55319
55320
55321
55322
55323
55324
55325
55326
55327
55328
55329
55330
55331
55332
55333
55334
55335
55336
55337
55338
55339
55340
55341
55342
55343
55344
55345
55346
55347
55348
55349
55350
55351
55352
55353
55354
55355
55356
55357
55358
55359
55360
55361
55362
55363
55364
55365
55366
55367
55368
55369
55370
55371
55372
55373
55374
55375
55376
55377
55378
55379
55380
55381
55382
55383
55384
55385
55386
55387
55388
55389
55390
55391
55392
55393
55394
55395
55396
55397
55398
55399
55400
55401
55402
55403
55404
55405
55406
55407
55408
55409
55410
55411
55412
55413
55414
55415
55416
55417
55418
55419
55420
55421
55422
55423
55424
55425
55426
55427
55428
55429
55430
55431
55432
55433
55434
55435
55436
55437
55438
55439
55440
55441
55442
55443
55444
55445
55446
55447
55448
55449
55450
55451
55452
55453
55454
55455
55456
55457
55458
55459
55460
55461
55462
55463
55464
55465
55466
55467
55468
55469
55470
55471
55472
55473
55474
55475
55476
55477
55478
55479
55480
55481
55482
55483
55484
55485
55486
55487
55488
55489
55490
55491
55492
55493
55494
55495
55496
55497
55498
55499
55500
55501
55502
55503
55504
55505
55506
55507
55508
55509
55510
55511
55512
55513
55514
55515
55516
55517
55518
55519
55520
55521
55522
55523
55524
55525
55526
55527
55528
55529
55530
55531
55532
55533
55534
55535
55536
55537
55538
55539
55540
55541
55542
55543
55544
55545
55546
55547
55548
55549
55550
55551
55552
55553
55554
55555
55556
55557
55558
55559
55560
55561
55562
55563
55564
55565
55566
55567
55568
55569
55570
55571
55572
55573
55574
55575
55576
55577
55578
55579
55580
55581
55582
55583
55584
55585
55586
55587
55588
55589
55590
55591
55592
55593
55594
55595
55596
55597
55598
55599
55600
55601
55602
55603
55604
55605
55606
55607
55608
55609
55610
55611
55612
55613
55614
55615
55616
55617
55618
55619
55620
55621
55622
55623
55624
55625
55626
55627
55628
55629
55630
55631
55632
55633
55634
55635
55636
55637
55638
55639
55640
55641
55642
55643
55644
55645
55646
55647
55648
55649
55650
55651
55652
55653
55654
55655
55656
55657
55658
55659
55660
55661
55662
55663
55664
55665
55666
55667
55668
55669
55670
55671
55672
55673
55674
55675
55676
55677
55678
//! AST-to-VDBE bytecode compilation (§10.6).
//!
//! Translates parsed SQL statements into VDBE register-based instructions
//! using `ProgramBuilder`. Handles SELECT, INSERT,
//! UPDATE, and DELETE with correct opcode patterns matching C SQLite behavior.

use std::cell::{Cell, RefCell};
use std::env;
use std::sync::Arc;

use crate::{Label, ProgramBuilder, SchemaEvaluationContext};
use fsqlite_ast::{
    AssignmentTarget, BinaryOp, ColumnRef, ConflictAction, CreateIndexStatement, DeleteStatement,
    Distinctness, Expr, FromClause, FunctionArgs, InSet, IndexedColumn, InsertSource,
    InsertStatement, JsonArrow, LimitClause, Literal, NullsOrder, OrderingTerm, QualifiedName,
    QualifiedTableRef, ResultColumn, SelectCore, SelectStatement, SortDirection, Span,
    TableOrSubquery, TimeTravelClause, TimeTravelTarget, UpdateStatement, UpsertAction,
    UpsertClause, UpsertTarget,
};
use fsqlite_error::ErrorCode;
use fsqlite_func::{FunctionArity, FunctionRegistry};
use fsqlite_parser::expr::parse_expr as parse_sql_expr;
use fsqlite_types::opcode::{
    IndexCursorMeta, Opcode, P4, SORTER_COMPARE_TOP_N_PREFLIGHT, SORTER_OPEN_TOP_N_REGISTER,
};
use fsqlite_types::record::{PrecomputedRecordHeader, PrecomputedSerialTypeKind};
use fsqlite_types::value::classify_sql_like_fast_path;
use fsqlite_types::{
    SmallText, SqliteValue, StrictColumnType, TextEncoding, TypeAffinity,
    without_rowid_pk_is_leading, without_rowid_storage_order,
};

// ---------------------------------------------------------------------------
// Thread-local custom aggregate keys for UDF support (bd-2wt.3)
// ---------------------------------------------------------------------------
// Custom aggregate UDFs registered via Connection::register_aggregate_function
// need to be recognized by the codegen so they emit AggStep/AggFinal opcodes
// instead of PureFunc. Arity is part of the key: a custom max/1 must not turn
// scalar max(x,y) into an aggregate, while a custom max/2 must replace that
// scalar-shaped built-in call. A thread-local avoids threading the keys through
// dozens of internal codegen helpers. Connection is !Send/!Sync so all codegen
// runs on a single thread.

thread_local! {
    static CUSTOM_AGG_KEYS: RefCell<Vec<(String, FunctionArity)>> = const { RefCell::new(Vec::new()) };
    static FUNCTION_REGISTRY: RefCell<Option<Arc<FunctionRegistry>>> = const { RefCell::new(None) };
    static USE_BUILTIN_LIKE_GLOB_SEMANTICS: Cell<bool> = const { Cell::new(true) };
    static USE_BUILTIN_SCALAR_FUNCTION_SEMANTICS: Cell<bool> = const { Cell::new(true) };
}

struct ConnectionFunctionContextGuard {
    custom_aggregate_keys: Vec<(String, FunctionArity)>,
    function_registry: Option<Arc<FunctionRegistry>>,
    builtin_like_glob_semantics: bool,
    builtin_scalar_function_semantics: bool,
}

impl Drop for ConnectionFunctionContextGuard {
    fn drop(&mut self) {
        let previous_custom_aggregate_keys = std::mem::take(&mut self.custom_aggregate_keys);
        CUSTOM_AGG_KEYS.with(|keys| {
            *keys.borrow_mut() = previous_custom_aggregate_keys;
        });
        let previous_function_registry = self.function_registry.take();
        FUNCTION_REGISTRY.with(|registry| {
            *registry.borrow_mut() = previous_function_registry;
        });
        USE_BUILTIN_LIKE_GLOB_SEMANTICS.with(|enabled| {
            enabled.set(self.builtin_like_glob_semantics);
        });
        USE_BUILTIN_SCALAR_FUNCTION_SEMANTICS.with(|enabled| {
            enabled.set(self.builtin_scalar_function_semantics);
        });
    }
}

/// Run one codegen invocation with the connection's function-overriding state.
///
/// Custom aggregate names must be lowercase. Each frozen arity contract controls
/// both exact/variadic precedence and the accepted variadic range.
/// `use_builtin_like_glob_semantics` must be false when the connection has
/// replaced an operator-compatible `like()` or `glob()` function: direct LIKE
/// opcodes and LIKE/GLOB prefix-to-range rewrites would otherwise bypass the
/// replacement. `use_builtin_scalar_function_semantics` must be false after
/// any scalar registration because function-bearing partial-index predicates
/// can no longer be assumed to match the semantics under which the index was
/// populated. The previous thread-local state is restored even if `codegen`
/// unwinds.
pub fn with_connection_function_context<R>(
    custom_aggregate_keys: Vec<(String, FunctionArity)>,
    use_builtin_like_glob_semantics: bool,
    use_builtin_scalar_function_semantics: bool,
    codegen: impl FnOnce() -> R,
) -> R {
    with_connection_function_registry_context(
        None,
        custom_aggregate_keys,
        use_builtin_like_glob_semantics,
        use_builtin_scalar_function_semantics,
        codegen,
    )
}

/// Registry-aware form of [`with_connection_function_context`] used by the
/// connection compiler.
///
/// Keeping the exact immutable registry snapshot in the
/// guard lets constant-expression decisions use frozen scalar safety metadata
/// without invoking user callbacks or racing a later registration.
pub fn with_connection_function_registry_context<R>(
    function_registry: Option<Arc<FunctionRegistry>>,
    custom_aggregate_keys: Vec<(String, FunctionArity)>,
    use_builtin_like_glob_semantics: bool,
    use_builtin_scalar_function_semantics: bool,
    codegen: impl FnOnce() -> R,
) -> R {
    let previous_custom_aggregate_keys = CUSTOM_AGG_KEYS
        .with(|keys| std::mem::replace(&mut *keys.borrow_mut(), custom_aggregate_keys));
    let previous_function_registry = FUNCTION_REGISTRY
        .with(|registry| std::mem::replace(&mut *registry.borrow_mut(), function_registry));
    let previous_builtin_like_glob_semantics = USE_BUILTIN_LIKE_GLOB_SEMANTICS
        .with(|enabled| enabled.replace(use_builtin_like_glob_semantics));
    let previous_builtin_scalar_function_semantics = USE_BUILTIN_SCALAR_FUNCTION_SEMANTICS
        .with(|enabled| enabled.replace(use_builtin_scalar_function_semantics));
    let _guard = ConnectionFunctionContextGuard {
        custom_aggregate_keys: previous_custom_aggregate_keys,
        function_registry: previous_function_registry,
        builtin_like_glob_semantics: previous_builtin_like_glob_semantics,
        builtin_scalar_function_semantics: previous_builtin_scalar_function_semantics,
    };
    codegen()
}

fn scalar_is_query_constant_for_codegen(name: &str, num_args: i32) -> bool {
    FUNCTION_REGISTRY.with(|registry| {
        registry
            .borrow()
            .as_ref()
            .and_then(|registry| registry.resolve_scalar(name, num_args))
            .is_some_and(|resolved| resolved.query_constancy().is_query_constant())
    })
}

/// Builtin scalar functions that consume (and therefore require) their
/// arguments' collation even when no custom registry entry covers them:
/// `NULLIF/2` and the `MIN`/`MAX` scalar forms (2+ arguments).
fn builtin_scalar_consumes_argument_collation(name: &str, num_args: i32) -> bool {
    matches!(
        (name.to_ascii_uppercase().as_str(), num_args),
        ("NULLIF", 2) | ("MIN" | "MAX", 2..)
    )
}

fn scalar_consumes_argument_collation_for_codegen(name: &str, num_args: i32) -> bool {
    FUNCTION_REGISTRY.with(|registry| {
        registry.borrow().as_ref().map_or_else(
            || builtin_scalar_consumes_argument_collation(name, num_args),
            |registry| {
                // bd-rwaxp: when the registry does not cover this (name, arity)
                // -- e.g. a partial custom registration shadowing `min/2` but
                // not `min/3` -- the BUILTIN is still used at that arity, so the
                // builtin NEEDCOLL requirement must survive. `unwrap_or(false)`
                // silently dropped it; fall back to the builtin table instead
                // (matching the no-registry branch above).
                registry
                    .scalar_consumes_argument_collation(name, num_args)
                    .unwrap_or_else(|| builtin_scalar_consumes_argument_collation(name, num_args))
            },
        )
    })
}

fn use_builtin_like_glob_semantics() -> bool {
    USE_BUILTIN_LIKE_GLOB_SEMANTICS.with(Cell::get)
}

fn use_builtin_scalar_function_semantics() -> bool {
    USE_BUILTIN_SCALAR_FUNCTION_SEMANTICS.with(Cell::get)
}

fn use_builtin_scalar_implementation_for_codegen(name: &str, num_args: i32) -> bool {
    FUNCTION_REGISTRY.with(|registry| {
        registry
            .borrow()
            .as_ref()
            .map_or_else(use_builtin_scalar_function_semantics, |registry| {
                registry
                    .resolve_application_function(name, num_args)
                    .is_none()
            })
    })
}

// ---------------------------------------------------------------------------
// Conflict resolution flags for Insert opcode p5 field
// ---------------------------------------------------------------------------
// These match SQLite's OE_* constants for on-error conflict handling.
// The low 4 bits of p5 encode the conflict action.

/// No conflict clause (default behavior: abort on constraint violation).
const OE_ABORT: u16 = 2;
/// ROLLBACK on conflict.
const OE_ROLLBACK: u16 = 1;
/// FAIL on conflict (abort statement but don't rollback transaction).
const OE_FAIL: u16 = 3;
/// IGNORE conflicting row (skip insert without error).
const OE_IGNORE: u16 = 4;
/// REPLACE conflicting row (delete old, insert new).
const OE_REPLACE: u16 = 5;
/// FrankenSQLite-specific p5 flag for `Insert`/`Delete` opcodes that are part
/// of an UPDATE rewrite.
///
/// This intentionally lives above the low 4 OE_* bits because this engine
/// encodes conflict handling directly in `p5`, unlike SQLite's native layout.
const OPFLAG_ISUPDATE: u16 = 0x10;
/// Marks a WITHOUT ROWID table-row `IdxDelete` as an implicit REPLACE
/// deletion whose exact OLD row must be reported for inbound FK actions.
const OPFLAG_REPLACE_VICTIM: u16 = 0x20;
/// Counts a successful clustered-table `IdxInsert` as one logical row change.
/// Secondary-index maintenance must never carry this flag.
const OPFLAG_IDX_NCHANGE: u16 = 0x40;
/// Marks a non-mutating UNIQUE constraint halt. P4 carries the column label.
const OPFLAG_HALT_UNIQUE: u16 = 0x01;

/// Convert AST `ConflictAction` to p5 OE_* flag value.
fn conflict_action_to_oe(action: Option<&ConflictAction>) -> u16 {
    match action {
        Some(ConflictAction::Rollback) => OE_ROLLBACK,
        None | Some(ConflictAction::Abort) => OE_ABORT,
        Some(ConflictAction::Fail) => OE_FAIL,
        Some(ConflictAction::Ignore) => OE_IGNORE,
        Some(ConflictAction::Replace) => OE_REPLACE,
    }
}

/// Resolve the effective conflict algorithm for a single constraint.
///
/// A statement-level `INSERT OR <algo>` (`stmt_level`) overrides a constraint's
/// declared `ON CONFLICT <algo>` (`constraint_level`); absent both, the default
/// is ABORT.
fn effective_oe(
    stmt_level: Option<ConflictAction>,
    constraint_level: Option<ConflictAction>,
) -> u16 {
    conflict_action_to_oe(stmt_level.or(constraint_level).as_ref())
}

fn json_access_func_name(arrow: JsonArrow) -> &'static str {
    match arrow {
        JsonArrow::Arrow => "->",
        JsonArrow::DoubleArrow => "->>",
    }
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_sqlite_value(b: &mut ProgramBuilder, value: &SqliteValue, reg: i32) {
    match value {
        SqliteValue::Null => {
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
        }
        SqliteValue::Integer(value) => {
            if let Ok(value) = i32::try_from(*value) {
                b.emit_op(Opcode::Integer, value, reg, 0, P4::None, 0);
            } else {
                b.emit_op(Opcode::Int64, 0, reg, 0, P4::Int64(*value), 0);
            }
        }
        SqliteValue::Float(value) => {
            b.emit_op(Opcode::Real, 0, reg, 0, P4::Real(*value), 0);
        }
        SqliteValue::Text(value) => {
            b.emit_op(
                Opcode::String8,
                0,
                reg,
                0,
                P4::Str(value.as_str().to_owned()),
                0,
            );
        }
        SqliteValue::Blob(value) => {
            b.emit_op(
                Opcode::Blob,
                value.len() as i32,
                reg,
                0,
                P4::Blob(value.as_ref().to_vec()),
                0,
            );
        }
    }
}

fn bound_outer_affinity_code(affinity: Option<TypeAffinity>) -> u8 {
    affinity.map_or(b'A', |affinity| affinity as u8)
}

fn scalar_function_p4(canonical_name: String, args: &[Expr], ctx: Option<&ScanCtx<'_>>) -> P4 {
    if scalar_consumes_argument_collation_for_codegen(
        &canonical_name,
        i32::try_from(args.len()).unwrap_or(i32::MAX),
    ) && let Some(collation) = scalar_function_argument_collation_ctx(args, ctx)
    {
        return P4::FuncNameCollated(canonical_name, collation);
    }
    P4::FuncName(canonical_name)
}

// ---------------------------------------------------------------------------
// Schema metadata (minimal info needed for codegen)
// ---------------------------------------------------------------------------

/// Column metadata needed by the code generator.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnInfo {
    /// Column name.
    pub name: String,
    /// Type affinity character: 'D'/'d' (integer), 'E'/'e' (real), 'B' (text),
    /// 'C' (numeric), 'A' or other (blob/none).
    pub affinity: char,
    /// True if this column is the INTEGER PRIMARY KEY (rowid alias).
    /// Column reads for IPK columns must emit `Rowid` instead of `Column`
    /// because the value is stored as the B-tree key, not in the data record.
    pub is_ipk: bool,
    /// Type name as written in the CREATE TABLE statement (e.g. "TEXT", "INTEGER").
    pub type_name: Option<String>,
    /// True if the column has a NOT NULL constraint.
    pub notnull: bool,
    /// True if the column has a UNIQUE constraint.
    pub unique: bool,
    /// Default value expression as SQL text (e.g. "'open'", "0", "CURRENT_TIMESTAMP").
    pub default_value: Option<String>,
    /// Strict type for STRICT tables; `None` for non-STRICT tables.
    pub strict_type: Option<StrictColumnType>,
    /// Generated column expression as SQL text, if this is a generated column.
    pub generated_expr: Option<String>,
    /// Whether the generated column is STORED (`true`) or VIRTUAL (`false`).
    /// `None` for non-generated columns.
    pub generated_stored: Option<bool>,
    /// Column collation sequence name (e.g. "NOCASE", "BINARY", "RTRIM").
    /// `None` means the default (BINARY).
    pub collation: Option<String>,
    /// Conflict-resolution algorithm declared on this column's NOT NULL or
    /// (INTEGER PRIMARY KEY) constraint via `ON CONFLICT <algo>`. `None` means
    /// the default (ABORT). UNIQUE-constraint conflict actions live on the
    /// corresponding `IndexSchema::conflict_action` instead.
    pub conflict_action: Option<ConflictAction>,
}

impl ColumnInfo {
    /// Create a basic `ColumnInfo` without type/notnull/default metadata.
    #[must_use]
    pub fn basic(name: impl Into<String>, affinity: char, is_ipk: bool) -> Self {
        Self {
            name: name.into(),
            affinity,
            is_ipk,
            type_name: None,
            notnull: false,
            unique: false,
            default_value: None,
            strict_type: None,
            generated_expr: None,
            generated_stored: None,
            collation: None,
            conflict_action: None,
        }
    }
}

/// Index metadata needed for codegen (index-scan SELECT).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexSchema {
    /// Index name.
    pub name: String,
    /// Root page number.
    pub root_page: i32,
    /// Indexed column names (leftmost first).
    ///
    /// This is populated only when every key term is a plain column
    /// reference. Expression indexes keep their executable term SQL in
    /// `key_expressions` and leave `columns` empty so planner fast paths do
    /// not accidentally treat them as simple column-lookup indexes.
    pub columns: Vec<String>,
    /// Executable SQL for each key term in storage order.
    pub key_expressions: Vec<String>,
    /// Sort direction for each logical key term.
    ///
    /// Empty means "all ASC" for legacy callers/tests that do not yet
    /// populate per-term ordering metadata.
    pub key_sort_directions: Vec<SortDirection>,
    /// Optional partial-index predicate as SQL text.
    pub where_clause: Option<String>,
    /// Whether this index enforces a UNIQUE constraint.
    pub is_unique: bool,
    /// Per-key-term collation sequences (e.g. `NOCASE`, `RTRIM`).
    ///
    /// `None` means "use the default (BINARY) collation" for that position.
    /// Empty vec means "all BINARY" for legacy callers/tests.
    pub key_collations: Vec<Option<String>>,
    /// Conflict-resolution algorithm declared on the UNIQUE / PRIMARY KEY
    /// constraint backing this index via `ON CONFLICT <algo>`. `None` means the
    /// default (ABORT) unless overridden by a statement-level `INSERT OR <algo>`.
    pub conflict_action: Option<ConflictAction>,
}

impl IndexSchema {
    /// Number of logical key terms before the trailing rowid suffix.
    #[must_use]
    pub fn key_term_count(&self) -> usize {
        if self.key_expressions.is_empty() {
            self.columns.len()
        } else {
            self.key_expressions.len()
        }
    }

    /// Return the SQL fragment for the `key_pos`th key term.
    #[must_use]
    pub fn key_term_sql(&self, key_pos: usize) -> Option<&str> {
        if self.key_expressions.is_empty() {
            self.columns.get(key_pos).map(String::as_str)
        } else {
            self.key_expressions.get(key_pos).map(String::as_str)
        }
    }

    /// Whether the `key_pos`th logical key term sorts descending.
    #[must_use]
    pub fn key_term_descending(&self, key_pos: usize) -> bool {
        matches!(
            self.key_sort_directions.get(key_pos),
            Some(SortDirection::Desc)
        )
    }

    /// Return the collation sequence for the `key_pos`th key term, if any.
    #[must_use]
    pub fn key_term_collation(&self, key_pos: usize) -> Option<&str> {
        self.key_collations.get(key_pos).and_then(|c| c.as_deref())
    }

    /// Whether planner / lookup fast paths may safely treat this as a simple
    /// non-partial column index.
    #[must_use]
    pub fn supports_direct_column_lookup(&self) -> bool {
        self.where_clause.is_none()
            && !self.columns.is_empty()
            && self.columns.len() == self.key_term_count()
    }

    /// Whether REPLACE cleanup metadata can reconstruct the key from raw row
    /// payload columns alone.
    #[must_use]
    pub fn supports_replace_cleanup_meta(&self) -> bool {
        self.supports_direct_column_lookup()
    }

    /// Human-readable key label for diagnostics / constraint errors.
    #[must_use]
    pub fn key_label(&self) -> String {
        if self.key_expressions.is_empty() {
            self.columns.join(", ")
        } else {
            self.key_expressions.join(", ")
        }
    }

    /// bd-a506j F1b: table-qualified key label for constraint-error messages —
    /// each key column carries the `table.` prefix, matching stock SQLite's
    /// "UNIQUE constraint failed: t.a, t.b" (not "t.a, b"). Single-column keys
    /// render "t.a" exactly as before.
    #[must_use]
    pub fn key_label_qualified(&self, table: &str) -> String {
        let cols = if self.key_expressions.is_empty() {
            &self.columns
        } else {
            &self.key_expressions
        };
        cols.iter()
            .map(|c| format!("{table}.{c}"))
            .collect::<Vec<_>>()
            .join(", ")
    }
}

/// A validated explicit-index definition before a physical root page exists.
///
/// This is the common binding result for live `CREATE INDEX` and persisted
/// `sqlite_master` reloads.  Root allocation deliberately remains a caller
/// responsibility so malformed catalog SQL and invalid live DDL fail before
/// they can mutate storage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoundExplicitIndex {
    /// Index name exactly as declared by the bound statement.
    pub name: String,
    /// Plain indexed column names, or empty for an expression index.
    pub columns: Vec<String>,
    /// Executable SQL for every key term when any term is an expression.
    pub key_expressions: Vec<String>,
    /// Effective sort direction for every key term.
    pub key_sort_directions: Vec<SortDirection>,
    /// Optional validated partial-index predicate SQL.
    pub where_clause: Option<String>,
    /// Whether the index enforces uniqueness.
    pub is_unique: bool,
    /// Effective collation for every key term.
    pub key_collations: Vec<Option<String>>,
}

impl BoundExplicitIndex {
    /// Attach an already-allocated root page to this validated definition.
    #[must_use]
    pub fn into_index_schema(self, root_page: i32) -> IndexSchema {
        IndexSchema {
            name: self.name,
            root_page,
            columns: self.columns,
            key_expressions: self.key_expressions,
            key_sort_directions: self.key_sort_directions,
            where_clause: self.where_clause,
            is_unique: self.is_unique,
            key_collations: self.key_collations,
            conflict_action: None,
        }
    }
}

/// Planner-selected single-table access-path family that lowering may honor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlannerSelectAccessKind {
    /// Lower as a plain table scan.
    FullTableScan,
    /// Lower as a direct rowid lookup.
    RowidLookup,
    /// Lower as an equality probe on a named index.
    IndexEquality,
    /// Lower as a bounded range scan on a named index.
    IndexRange,
}

impl PlannerSelectAccessKind {
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::FullTableScan => "full_table_scan",
            Self::RowidLookup => "rowid_lookup",
            Self::IndexEquality => "index_equality",
            Self::IndexRange => "index_range",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct PlannerIndexRangeBound {
    /// Bound expression evaluated once before the scan begins.
    pub expr: Expr,
    /// Whether the bound is inclusive.
    pub inclusive: bool,
}

#[derive(Debug, Clone, Default, PartialEq)]
pub struct PlannerIndexRangeTarget {
    /// Optional lower bound (`>=` / `>` / `BETWEEN` low).
    pub lower: Option<PlannerIndexRangeBound>,
    /// Optional upper bound (`<=` / `<` / `BETWEEN` high).
    pub upper: Option<PlannerIndexRangeBound>,
}

/// Planner-produced directive for a single-table SELECT lowering path.
#[derive(Debug, Clone, PartialEq)]
pub struct SelectPlannerDirective {
    /// Deterministic planner artifact identity.
    pub plan_id: String,
    /// Planner artifact generation/version.
    pub plan_generation: u64,
    /// Human-readable planner surface name.
    pub planner_surface: String,
    /// Table the directive applies to.
    pub table_name: String,
    /// Index to use when the access path is index-backed.
    pub index_name: Option<String>,
    /// Human-readable leading key term that drives the probe. For plain
    /// indexes this is the leading column name; for expression indexes it is
    /// the indexed expression text.
    pub index_key_label: Option<String>,
    /// Whether the leading key term is an expression rather than a plain
    /// column reference.
    pub index_key_is_expression: bool,
    /// Optional equality probe payload that lowering can emit directly.
    pub index_equality_target: Option<Expr>,
    /// Optional range probe payload that lowering can emit directly.
    pub index_range_target: Option<PlannerIndexRangeTarget>,
    /// Whether the planner expects a covering-index lowering.
    pub covering: bool,
    /// Access-path family lowering should consume.
    pub access_kind: PlannerSelectAccessKind,
}

/// A foreign key constraint definition stored on the child table.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FkDef {
    /// Column indices in the child table that form the FK.
    pub child_columns: Vec<usize>,
    /// Owning column for a column-level `REFERENCES` clause; `None` for a
    /// table-level `FOREIGN KEY` constraint.
    pub owner_column: Option<String>,
    /// Referenced (parent) table name.
    pub parent_table: String,
    /// Referenced column names in the parent table.
    /// Empty means the parent's implicit rowid.
    pub parent_columns: Vec<String>,
    /// Action on parent row deletion.
    pub on_delete: FkActionType,
    /// Action on parent row update.
    pub on_update: FkActionType,
    /// `true` for `DEFERRABLE INITIALLY DEFERRED` constraints, whose
    /// parent-existence check is deferred to COMMIT rather than checked at the
    /// statement (bd-do0d6).
    pub deferred: bool,
}

/// A CHECK constraint together with its schema-level ownership.
///
/// SQLite drops a column-level CHECK with its owning column, while a
/// table-level CHECK or a CHECK owned by another column remains a dependency
/// that can prevent `ALTER TABLE ... DROP COLUMN`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckConstraint {
    /// Constraint expression as SQL text.
    pub expr: String,
    /// Owning column for a column-level CHECK; `None` for table-level CHECKs.
    pub owner_column: Option<String>,
    /// The CHECK constraint's name (`CONSTRAINT <name> CHECK(...)`), if any.
    /// SQLite reports a NAMED check violation as `CHECK constraint failed:
    /// <name>` and an unnamed one as `CHECK constraint failed: <expr>`.
    pub name: Option<String>,
}

/// Foreign key action type (mirrors `fsqlite_ast::ForeignKeyActionType`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum FkActionType {
    /// No action (default) — raise error if children exist.
    #[default]
    NoAction,
    /// Propagate delete/update to children.
    Cascade,
    /// Set child FK columns to NULL.
    SetNull,
    /// Set child FK columns to their default value.
    SetDefault,
    /// Like `NoAction` but checked immediately (not deferred).
    Restrict,
}

/// Minimal table schema needed by the code generator.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableSchema {
    /// Table name.
    pub name: String,
    /// Root page of the table's B-tree.
    pub root_page: i32,
    /// Column definitions in storage order.
    pub columns: Vec<ColumnInfo>,
    /// Available indexes.
    pub indexes: Vec<IndexSchema>,
    /// Whether this table uses SQLite STRICT typing rules.
    pub strict: bool,
    /// Whether this table is declared WITHOUT ROWID.
    pub without_rowid: bool,
    /// PRIMARY KEY constraints expressed as ordered column-name groups.
    ///
    /// INTEGER PRIMARY KEY rowid aliases continue to use `ColumnInfo::is_ipk`;
    /// this field preserves non-rowid and composite PRIMARY KEY shape for SQL
    /// re-rendering during ALTER TABLE / persistence round-trips.
    pub primary_key_constraints: Vec<Vec<String>>,
    /// Foreign key constraints declared on this table (child side).
    pub foreign_keys: Vec<FkDef>,
    /// CHECK constraints with durable column-vs-table ownership.
    pub check_constraints: Vec<CheckConstraint>,
}

impl TableSchema {
    /// Build an affinity string for `MakeRecord` (one char per column).
    /// IPK columns are marked with 'X' so `MakeRecord` writes a NULL placeholder
    /// while the real key continues to come from the rowid.
    #[must_use]
    pub fn affinity_string(&self) -> String {
        self.columns
            .iter()
            .map(|c| if c.is_ipk { 'X' } else { c.affinity })
            .collect()
    }

    /// Find a column's 0-based index by name (case-insensitive).
    #[must_use]
    pub fn column_index(&self, name: &str) -> Option<usize> {
        self.columns
            .iter()
            .position(|c| c.name.eq_ignore_ascii_case(name))
    }

    /// Find an index by a column name (returns first index whose leftmost
    /// column matches).
    #[must_use]
    pub fn index_for_column(&self, col_name: &str) -> Option<&IndexSchema> {
        // WITHOUT ROWID secondary indexes are keyed by (cols..., primary key),
        // not (cols..., rowid), so the rowid-based IdxRowid/SeekRowid access
        // path cannot use them. Force a full table scan instead.
        if self.without_rowid {
            return None;
        }
        self.indexes.iter().find(|idx| {
            idx.supports_direct_column_lookup()
                && idx
                    .columns
                    .first()
                    .is_some_and(|c| c.eq_ignore_ascii_case(col_name))
        })
    }

    /// Find a single-column direct-lookup index for `col_name` whose
    /// comparison collation matches the join predicate.
    #[must_use]
    pub fn single_column_index_for_column_with_collation(
        &self,
        col_name: &str,
        comparison_collation: Option<&str>,
    ) -> Option<&IndexSchema> {
        if self.without_rowid {
            return None;
        }
        self.indexes.iter().find(|idx| {
            idx.supports_direct_column_lookup()
                && idx.columns.len() == 1
                && !idx.key_term_descending(0)
                && idx
                    .columns
                    .first()
                    .is_some_and(|c| c.eq_ignore_ascii_case(col_name))
                && direct_lookup_index_collation_matches_join(idx, comparison_collation)
        })
    }

    /// Find a direct-lookup UNIQUE index that guarantees at most one row for
    /// an equality probe on `col_name` and whose comparison collation matches
    /// the join predicate.
    #[must_use]
    pub fn unique_single_column_index_for_column(
        &self,
        col_name: &str,
        comparison_collation: Option<&str>,
    ) -> Option<&IndexSchema> {
        if self.without_rowid {
            return None;
        }
        self.indexes.iter().find(|idx| {
            idx.is_unique
                && idx.columns.len() == 1
                && idx.supports_direct_column_lookup()
                && !idx.key_term_descending(0)
                && idx
                    .columns
                    .first()
                    .is_some_and(|c| c.eq_ignore_ascii_case(col_name))
                && direct_lookup_index_collation_matches_join(idx, comparison_collation)
        })
    }

    /// STRICT type-check pattern for `Opcode::TypeCheck` (`I`,`R`,`T`,`L`,`A`).
    #[must_use]
    pub fn strict_type_pattern(&self) -> Option<String> {
        if !self.strict {
            return None;
        }
        Some(
            self.columns
                .iter()
                .map(|col| strict_type_code(col.strict_type))
                .collect(),
        )
    }

    fn resolves_to_hidden_rowid(&self, name: &str) -> bool {
        !self.without_rowid && self.column_index(name).is_none() && is_hidden_rowid_alias_name(name)
    }
}

/// Validate and bind an explicit `CREATE INDEX` without allocating storage.
///
/// `expected_index_name` and `expected_table_name` let catalog reload callers
/// bind the SQL text to the surrounding `sqlite_master` row.  Live DDL callers
/// pass the names from `stmt` itself.  Identifier comparisons are
/// case-insensitive, while the returned metadata preserves the spelling from
/// the declaration.
///
/// This pass validates expression shape, every table column reference, and
/// collation placement.  It intentionally does not decide whether a collation
/// name is registered: that is connection-local state and must be checked by
/// the caller before allocating the root page.
pub fn bind_explicit_index(
    stmt: &CreateIndexStatement,
    expected_index_name: &str,
    expected_table_name: &str,
    table: &TableSchema,
) -> Result<BoundExplicitIndex, CodegenError> {
    if stmt.name.name.is_empty() || expected_index_name.is_empty() {
        return Err(CodegenError::Unsupported(
            "malformed CREATE INDEX identity: empty index name".to_owned(),
        ));
    }
    if !stmt.name.name.eq_ignore_ascii_case(expected_index_name) {
        return Err(CodegenError::Unsupported(format!(
            "CREATE INDEX identity mismatch: statement names `{}`, expected `{expected_index_name}`",
            stmt.name.name
        )));
    }
    if stmt.table.is_empty() || expected_table_name.is_empty() {
        return Err(CodegenError::Unsupported(
            "malformed CREATE INDEX identity: empty table name".to_owned(),
        ));
    }
    if !stmt.table.eq_ignore_ascii_case(expected_table_name) {
        return Err(CodegenError::Unsupported(format!(
            "CREATE INDEX table identity mismatch: statement targets `{}`, expected `{expected_table_name}`",
            stmt.table
        )));
    }
    if !table.name.eq_ignore_ascii_case(expected_table_name) {
        return Err(CodegenError::TableNotFound(expected_table_name.to_owned()));
    }
    if stmt.columns.is_empty() {
        return Err(CodegenError::Unsupported(format!(
            "malformed CREATE INDEX `{}`: at least one key term is required",
            stmt.name.name
        )));
    }

    let mut simple_columns = Vec::with_capacity(stmt.columns.len());
    let mut key_sort_directions = Vec::with_capacity(stmt.columns.len());
    let mut key_collations = Vec::with_capacity(stmt.columns.len());

    for (term_index, indexed) in stmt.columns.iter().enumerate() {
        let context = format!("key term {}", term_index + 1);
        validate_explicit_index_term(indexed, table, &context)?;

        let simple_column = explicit_index_simple_column_name(&indexed.expr);
        if let Some(column_name) = simple_column {
            if table.column_index(column_name).is_none() {
                return Err(CodegenError::ColumnNotFound {
                    table: table.name.clone(),
                    column: column_name.to_owned(),
                });
            }
            simple_columns.push(column_name.to_owned());
        }

        let declared_collation = simple_column
            .and_then(|column_name| table.column_index(column_name))
            .and_then(|column_index| table.columns[column_index].collation.as_deref());
        // The collation of an expression-index key is not the collation of
        // every comparison performed inside that expression. SQLite assigns a
        // non-BINARY key collation only to a bare column (which inherits its
        // declaration) or to a COLLATE operator at the root of the indexed
        // expression. Nested COLLATE operators, CAST, and unary plus can still
        // be runtime dependencies without changing the stored key ordering.
        let root_collation = match &indexed.expr {
            Expr::Collate { collation, .. } => Some(collation.as_str()),
            _ => None,
        };
        let effective_collation = indexed
            .collation
            .as_deref()
            .or(root_collation)
            .or(declared_collation);
        validate_explicit_index_collation(effective_collation, &context)?;
        key_collations.push(effective_collation.map(str::to_owned));
        key_sort_directions.push(indexed.direction.unwrap_or(SortDirection::Asc));
    }

    if let Some(predicate) = stmt.where_clause.as_ref() {
        validate_explicit_index_expr_shape(predicate, "partial-index predicate")?;
        validate_single_table_expr_columns(predicate, table, None)?;
    }

    let all_terms_are_simple = simple_columns.len() == stmt.columns.len();
    let (columns, key_expressions) = if all_terms_are_simple {
        (simple_columns, Vec::new())
    } else {
        (
            Vec::new(),
            stmt.columns
                .iter()
                .map(|indexed| indexed.expr.to_string())
                .collect(),
        )
    };

    Ok(BoundExplicitIndex {
        name: stmt.name.name.clone(),
        columns,
        key_expressions,
        key_sort_directions,
        where_clause: stmt.where_clause.as_ref().map(ToString::to_string),
        is_unique: stmt.unique,
        key_collations,
    })
}

fn explicit_index_simple_column_name(expr: &Expr) -> Option<&str> {
    match expr {
        Expr::Column(col_ref, _) if col_ref.table.is_none() => Some(col_ref.column.as_ref()),
        // SQLite's indexed-column grammar resolves this legacy spelling as a
        // column identifier rather than a constant string expression.
        Expr::Literal(Literal::String(name), _) => Some(name),
        Expr::Collate { expr, .. } => explicit_index_simple_column_name(expr),
        _ => None,
    }
}

fn validate_explicit_index_term(
    indexed: &IndexedColumn,
    table: &TableSchema,
    context: &str,
) -> Result<(), CodegenError> {
    validate_explicit_index_collation(indexed.collation.as_deref(), context)?;
    validate_explicit_index_expr_shape(&indexed.expr, context)?;
    validate_explicit_index_key_columns(&indexed.expr, table, context)
}

fn validate_explicit_index_key_columns(
    expr: &Expr,
    table: &TableSchema,
    context: &str,
) -> Result<(), CodegenError> {
    validate_expr_columns_with(expr, &|column| {
        if column.table.is_some() {
            return Err(malformed_explicit_index_expr(
                context,
                "the `.` operator is prohibited in index key expressions",
            ));
        }
        if table.column_index(&column.column).is_some() {
            return Ok(());
        }
        Err(CodegenError::ColumnNotFound {
            table: table.name.clone(),
            column: column.column.to_string(),
        })
    })
}

fn validate_explicit_index_collation(
    collation: Option<&str>,
    context: &str,
) -> Result<(), CodegenError> {
    if collation.is_some_and(str::is_empty) {
        return Err(CodegenError::Unsupported(format!(
            "malformed CREATE INDEX {context}: empty collation name"
        )));
    }
    Ok(())
}

fn malformed_explicit_index_expr(context: &str, detail: &str) -> CodegenError {
    CodegenError::Unsupported(format!("malformed CREATE INDEX {context}: {detail}"))
}

fn validate_explicit_index_expr_shape(expr: &Expr, context: &str) -> Result<(), CodegenError> {
    match expr {
        Expr::Literal(..) | Expr::Column(..) => Ok(()),
        Expr::BoundOuterValue { .. } => Err(malformed_explicit_index_expr(
            context,
            "bound outer-query values are internal and are not allowed",
        )),
        Expr::BinaryOp { left, right, .. }
        | Expr::JsonAccess {
            expr: left,
            path: right,
            ..
        } => {
            validate_explicit_index_expr_shape(left, context)?;
            validate_explicit_index_expr_shape(right, context)
        }
        Expr::UnaryOp { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
            validate_explicit_index_expr_shape(expr, context)
        }
        Expr::Collate {
            expr, collation, ..
        } => {
            validate_explicit_index_collation(Some(collation), context)?;
            validate_explicit_index_expr_shape(expr, context)
        }
        Expr::Between {
            expr, low, high, ..
        } => {
            validate_explicit_index_expr_shape(expr, context)?;
            validate_explicit_index_expr_shape(low, context)?;
            validate_explicit_index_expr_shape(high, context)
        }
        Expr::In { expr, set, .. } => {
            validate_explicit_index_expr_shape(expr, context)?;
            let InSet::List(values) = set else {
                return Err(malformed_explicit_index_expr(
                    context,
                    "subqueries and table-valued IN operands are not allowed",
                ));
            };
            for value in values {
                validate_explicit_index_expr_shape(value, context)?;
            }
            Ok(())
        }
        Expr::Like {
            expr,
            pattern,
            escape,
            ..
        } => {
            validate_explicit_index_expr_shape(expr, context)?;
            validate_explicit_index_expr_shape(pattern, context)?;
            if let Some(escape) = escape {
                validate_explicit_index_expr_shape(escape, context)?;
            }
            Ok(())
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            if whens.is_empty() {
                return Err(malformed_explicit_index_expr(
                    context,
                    "CASE expression has no WHEN terms",
                ));
            }
            if let Some(operand) = operand {
                validate_explicit_index_expr_shape(operand, context)?;
            }
            for (when_expr, then_expr) in whens {
                validate_explicit_index_expr_shape(when_expr, context)?;
                validate_explicit_index_expr_shape(then_expr, context)?;
            }
            if let Some(else_expr) = else_expr {
                validate_explicit_index_expr_shape(else_expr, context)?;
            }
            Ok(())
        }
        Expr::FunctionCall {
            name,
            args,
            distinct,
            order_by,
            filter,
            over,
            ..
        } => {
            if name.is_empty()
                || *distinct
                || !order_by.is_empty()
                || filter.is_some()
                || over.is_some()
                || matches!(args, FunctionArgs::Star)
            {
                return Err(malformed_explicit_index_expr(
                    context,
                    "aggregate or window function term is not allowed",
                ));
            }
            let FunctionArgs::List(values) = args else {
                unreachable!("star arguments were rejected above");
            };
            for value in values {
                validate_explicit_index_expr_shape(value, context)?;
            }
            Ok(())
        }
        Expr::Exists { .. } | Expr::Subquery(..) => Err(malformed_explicit_index_expr(
            context,
            "subqueries are not allowed",
        )),
        Expr::Raise { .. } => Err(malformed_explicit_index_expr(
            context,
            "RAISE expressions are not allowed",
        )),
        Expr::RowValue(..) => Err(malformed_explicit_index_expr(
            context,
            "row-value key terms are not allowed",
        )),
        Expr::Placeholder(..) => Err(malformed_explicit_index_expr(
            context,
            "bind parameters are not allowed",
        )),
    }
}

fn strict_type_code(strict_type: Option<StrictColumnType>) -> char {
    match strict_type.unwrap_or(StrictColumnType::Any) {
        StrictColumnType::Integer => 'I',
        StrictColumnType::Real => 'R',
        StrictColumnType::Text => 'T',
        StrictColumnType::Blob => 'L',
        StrictColumnType::Any => 'A',
    }
}

fn emit_strict_type_check(b: &mut ProgramBuilder, table: &TableSchema, first_reg: i32) {
    if let Some(pattern) = table.strict_type_pattern() {
        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        let n_cols = table.columns.len() as i32;
        // Encode "pattern\ttable_name\tcol1\tcol2\t..." for error messages.
        let mut encoded = pattern;
        encoded.push('\t');
        encoded.push_str(&table.name);
        for col in &table.columns {
            encoded.push('\t');
            encoded.push_str(&col.name);
        }
        b.emit_op(Opcode::TypeCheck, first_reg, n_cols, 0, P4::Str(encoded), 0);
    }
}

/// Find the UNIQUE index matching the UPSERT target columns, if any.
///
/// Returns `(index_offset, &IndexSchema)` when the target columns match a
/// UNIQUE index on the table.  Returns `None` when the target is absent,
/// refers to the PRIMARY KEY, or does not match any UNIQUE index.
pub fn find_upsert_target_index<'a>(
    table: &'a TableSchema,
    target: Option<&UpsertTarget>,
) -> Option<(usize, &'a IndexSchema)> {
    let target = target?;
    // Only plain columns can match this direct UNIQUE-index probe. Expression
    // targets fail closed until the probe can evaluate expression-index keys.
    let target_cols: Vec<(&str, Option<&str>)> = target
        .columns
        .iter()
        .map(|indexed_column| match &indexed_column.expr {
            Expr::Column(column, _) => {
                Some((column.column.as_ref(), indexed_column.collation.as_deref()))
            }
            _ => None,
        })
        .collect::<Option<Vec<_>>>()?;
    if target_cols.is_empty() {
        return None;
    }
    // Check if the target matches a UNIQUE index (not the PK).
    for (idx_offset, index) in table.indexes.iter().enumerate() {
        if !index.is_unique
            || index.columns.is_empty()
            || index.columns.len() != index.key_term_count()
            || index.columns.len() != target_cols.len()
        {
            continue;
        }
        let mut matched_index_columns = vec![false; index.columns.len()];
        let columns_match = target_cols.iter().all(|(target_column, target_collation)| {
            let Some(index_position) =
                index
                    .columns
                    .iter()
                    .enumerate()
                    .position(|(index_position, index_column)| {
                        matched_index_columns
                            .get(index_position)
                            .is_some_and(|matched| !matched)
                            && index_column.eq_ignore_ascii_case(target_column)
                            && target_collation.is_none_or(|target_collation| {
                                index
                                    .key_term_collation(index_position)
                                    .unwrap_or("BINARY")
                                    .eq_ignore_ascii_case(target_collation)
                            })
                    })
            else {
                return false;
            };
            let Some(matched) = matched_index_columns.get_mut(index_position) else {
                return false;
            };
            *matched = true;
            true
        });
        if columns_match && upsert_target_matches_index_predicate(table, target, index) {
            return Some((idx_offset, index));
        }
    }
    None
}

/// SQLite permits an arbitrary conflict-target WHERE clause to accompany a
/// non-partial UNIQUE index. A partial index, however, is an arbiter only when
/// the target predicate structurally matches its stored predicate.
fn upsert_target_matches_index_predicate(
    table: &TableSchema,
    target: &UpsertTarget,
    index: &IndexSchema,
) -> bool {
    let Some(index_predicate_sql) = index.where_clause.as_deref() else {
        return true;
    };
    let Some(target_predicate) = target.where_clause.as_ref() else {
        return false;
    };
    let Ok(index_predicate) = parse_sql_expr(index_predicate_sql) else {
        return false;
    };
    expressions_match_table_locally(target_predicate, &index_predicate, table, None)
}

pub fn upsert_target_matches_rowid_primary_key(table: &TableSchema, target: &UpsertTarget) -> bool {
    let [indexed_column] = target.columns.as_slice() else {
        return false;
    };
    if indexed_column.collation.is_some() {
        return false;
    }
    let Expr::Column(column, _) = &indexed_column.expr else {
        return false;
    };
    table
        .column_index(&column.column)
        .and_then(|index| table.columns.get(index))
        .is_some_and(|column| column.is_ipk)
        || table.resolves_to_hidden_rowid(&column.column)
}

/// Match a WITHOUT ROWID table's PRIMARY KEY as an `ON CONFLICT` arbiter.
///
/// The PK is a valid arbiter but is stored as the clustering key in
/// `primary_key_constraints` — not as an entry in `table.indexes` (so
/// `find_upsert_target_index` misses it) and not as an `is_ipk` rowid alias (so
/// `upsert_target_matches_rowid_primary_key` misses it). Match a plain,
/// non-collated, non-partial target whose column set equals the PRIMARY KEY
/// column set (order-independent, like a UNIQUE-index arbiter).
#[must_use]
pub fn upsert_target_matches_without_rowid_primary_key(
    table: &TableSchema,
    target: &UpsertTarget,
) -> bool {
    if !table.without_rowid || target.where_clause.is_some() {
        return false;
    }
    let mut target_cols: Vec<&str> = Vec::with_capacity(target.columns.len());
    for indexed in &target.columns {
        // Only plain, non-collated column targets can name the PRIMARY KEY here.
        if indexed.collation.is_some() {
            return false;
        }
        let Expr::Column(column, _) = &indexed.expr else {
            return false;
        };
        target_cols.push(column.column.as_ref());
    }
    let Some(pk_group) = table.primary_key_constraints.first() else {
        return false;
    };
    if target_cols.is_empty() || pk_group.len() != target_cols.len() {
        return false;
    }
    // Order-independent set match against the PRIMARY KEY columns.
    let mut matched = vec![false; pk_group.len()];
    target_cols.iter().all(|target_column| {
        let Some(position) = pk_group.iter().enumerate().position(|(index, pk_column)| {
            matched.get(index).is_some_and(|m| !m) && pk_column.eq_ignore_ascii_case(target_column)
        }) else {
            return false;
        };
        matched[position] = true;
        true
    })
}

/// Emit UPSERT DO UPDATE assignments into `target_regs`.
///
/// For each assignment, evaluates the RHS expression using two contexts:
/// - `existing_ctx`: resolves unqualified column refs to existing row values
/// - `excluded_ctx`: resolves `excluded.col` refs to the attempted insert values
///
/// The result is written into the appropriate slot of `target_regs`.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::too_many_arguments
)]
fn emit_upsert_assignments(
    b: &mut ProgramBuilder,
    assignments: &[fsqlite_ast::Assignment],
    table: &TableSchema,
    target_regs: i32,
    existing_ctx: &ScanCtx<'_>,
    excluded_ctx: &ScanCtx<'_>,
    existing_hidden_rowid_reg: Option<i32>,
    excluded_hidden_rowid_reg: i32,
) -> Result<(), CodegenError> {
    for assign in assignments {
        match &assign.target {
            AssignmentTarget::Column(name) => {
                let col_idx =
                    table
                        .column_index(name)
                        .ok_or_else(|| CodegenError::ColumnNotFound {
                            table: table.name.clone(),
                            column: name.to_owned(),
                        })?;
                let dest_reg = target_regs + col_idx as i32;
                emit_upsert_expr(
                    b,
                    &assign.value,
                    dest_reg,
                    existing_ctx,
                    excluded_ctx,
                    table,
                    existing_hidden_rowid_reg,
                    excluded_hidden_rowid_reg,
                );
            }
            AssignmentTarget::ColumnList(columns) => {
                let Expr::RowValue(values, _) = &assign.value else {
                    return Err(CodegenError::Unsupported(
                        "multi-column SET requires a row-value expression".to_owned(),
                    ));
                };
                if columns.len() != values.len() {
                    return Err(CodegenError::Unsupported(format!(
                        "multi-column SET arity mismatch: {} targets, {} values",
                        columns.len(),
                        values.len()
                    )));
                }
                for (col_name, value_expr) in columns.iter().zip(values) {
                    let col_idx = table.column_index(col_name).ok_or_else(|| {
                        CodegenError::ColumnNotFound {
                            table: table.name.clone(),
                            column: col_name.to_owned(),
                        }
                    })?;
                    let dest_reg = target_regs + col_idx as i32;
                    emit_upsert_expr(
                        b,
                        value_expr,
                        dest_reg,
                        existing_ctx,
                        excluded_ctx,
                        table,
                        existing_hidden_rowid_reg,
                        excluded_hidden_rowid_reg,
                    );
                }
            }
        }
    }
    Ok(())
}

fn upsert_declared_collation(
    expr: &Expr,
    existing_ctx: &ScanCtx<'_>,
    _excluded_ctx: &ScanCtx<'_>,
    table: &TableSchema,
) -> Option<String> {
    let source = declared_collation_source_expr(expr);
    if let Expr::BoundOuterValue { collation, .. } = source {
        return collation.as_name().map(str::to_owned);
    }
    let Expr::Column(col_ref, _) = source else {
        return None;
    };

    // SQLite lowers excluded.* references to TK_REGISTER values. The register
    // keeps its runtime value but does not inherit the target column's declared
    // collation. An explicit COLLATE wrapper is handled by the caller before
    // this declared-collation fallback.
    if is_upsert_excluded_pseudo_table(col_ref, table, existing_ctx.table_alias) {
        return None;
    }

    let source_table = existing_ctx.table;
    let source_alias = existing_ctx.table_alias;
    if col_ref.table.as_deref().is_some_and(|qualifier| {
        !qualifier.eq_ignore_ascii_case("excluded")
            && !matches_table_or_alias(qualifier, source_table, source_alias)
    }) {
        return None;
    }
    if let Some(index) = source_table.column_index(&col_ref.column) {
        return Some(
            source_table.columns[index]
                .collation
                .as_deref()
                .unwrap_or("BINARY")
                .to_owned(),
        );
    }
    source_table
        .resolves_to_hidden_rowid(&col_ref.column)
        .then(|| "BINARY".to_owned())
}

fn upsert_effective_collation(
    expr: &Expr,
    existing_ctx: &ScanCtx<'_>,
    excluded_ctx: &ScanCtx<'_>,
    table: &TableSchema,
) -> Option<String> {
    extract_collation(expr)
        .map(str::to_owned)
        .or_else(|| upsert_declared_collation(expr, existing_ctx, excluded_ctx, table))
}

fn upsert_comparison_collation(
    left: &Expr,
    right: &Expr,
    existing_ctx: &ScanCtx<'_>,
    excluded_ctx: &ScanCtx<'_>,
    table: &TableSchema,
) -> Option<String> {
    extract_collation(left)
        .or_else(|| extract_collation(right))
        .map(str::to_owned)
        .or_else(|| upsert_declared_collation(left, existing_ctx, excluded_ctx, table))
        .or_else(|| upsert_declared_collation(right, existing_ctx, excluded_ctx, table))
}

fn upsert_expr_affinity(
    expr: &Expr,
    existing_ctx: &ScanCtx<'_>,
    _excluded_ctx: &ScanCtx<'_>,
    table: &TableSchema,
) -> u8 {
    let inner = strip_collate_wrappers(expr);
    if let Expr::Column(col_ref, _) = inner
        && is_upsert_excluded_pseudo_table(col_ref, table, existing_ctx.table_alias)
    {
        // Like its collation, an excluded.* TK_REGISTER has no declared
        // affinity. CAST remains intrinsic because it does not reach this
        // direct-column branch.
        b'A'
    } else {
        expr_affinity(expr, Some(existing_ctx))
    }
}

fn upsert_comparison_affinity(
    left: &Expr,
    right: &Expr,
    existing_ctx: &ScanCtx<'_>,
    excluded_ctx: &ScanCtx<'_>,
    table: &TableSchema,
) -> u16 {
    combine_comparison_affinity(
        upsert_expr_affinity(left, existing_ctx, excluded_ctx, table),
        upsert_expr_affinity(right, existing_ctx, excluded_ctx, table),
    )
}

fn upsert_scalar_function_collation<'expr>(
    args: impl IntoIterator<Item = &'expr Expr>,
    existing_ctx: &ScanCtx<'_>,
    excluded_ctx: &ScanCtx<'_>,
    table: &TableSchema,
) -> Option<String> {
    args.into_iter().find_map(|argument| {
        upsert_effective_collation(argument, existing_ctx, excluded_ctx, table)
    })
}

/// Emit an expression that may reference both `excluded.*` and existing row columns.
///
/// Recursively walks the expression tree, dispatching `excluded.col` references
/// to `excluded_ctx` and all other column references to `existing_ctx`.  This
/// ensures that expressions like `CASE WHEN excluded.val > val THEN excluded.val
/// ELSE val END` or `coalesce(excluded.val, val)` resolve correctly in UPSERT
/// DO UPDATE SET clauses.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn emit_upsert_expr(
    b: &mut ProgramBuilder,
    expr: &Expr,
    reg: i32,
    existing_ctx: &ScanCtx<'_>,
    excluded_ctx: &ScanCtx<'_>,
    _table: &TableSchema,
    existing_hidden_rowid_reg: Option<i32>,
    excluded_hidden_rowid_reg: i32,
) {
    match expr {
        // ── Leaf: column reference — dispatch to correct context ────────
        Expr::Column(col_ref, _) => {
            let is_excluded_pseudo_ref =
                is_upsert_excluded_pseudo_table(col_ref, _table, existing_ctx.table_alias);
            if _table.resolves_to_hidden_rowid(&col_ref.column) && is_excluded_pseudo_ref {
                b.emit_op(Opcode::Copy, excluded_hidden_rowid_reg, reg, 0, P4::None, 0);
            } else if _table.resolves_to_hidden_rowid(&col_ref.column) {
                if let Some(existing_hidden_rowid_reg) = existing_hidden_rowid_reg {
                    b.emit_op(Opcode::Copy, existing_hidden_rowid_reg, reg, 0, P4::None, 0);
                } else {
                    b.emit_op(Opcode::Rowid, existing_ctx.cursor, reg, 0, P4::None, 0);
                }
            } else if is_excluded_pseudo_ref {
                emit_expr(b, expr, reg, Some(excluded_ctx));
            } else {
                emit_expr(b, expr, reg, Some(existing_ctx));
            }
        }

        // ── Leaf: literals & placeholders — no column refs ─────────────
        // (Handled by the wildcard arm)

        // ── Binary operations ──────────────────────────────────────────
        Expr::BinaryOp {
            left, op, right, ..
        } => {
            use fsqlite_ast::BinaryOp;

            // Pre-emit both operands with dual-context resolution.
            let left_reg = b.alloc_reg();
            let right_reg = b.alloc_reg();
            emit_upsert_expr(
                b,
                left,
                left_reg,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            emit_upsert_expr(
                b,
                right,
                right_reg,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );

            match op {
                // Value-producing ops: arithmetic, concat, bitwise, AND, OR.
                BinaryOp::Add
                | BinaryOp::Subtract
                | BinaryOp::Multiply
                | BinaryOp::Divide
                | BinaryOp::Modulo
                | BinaryOp::Concat
                | BinaryOp::BitAnd
                | BinaryOp::BitOr
                | BinaryOp::ShiftLeft
                | BinaryOp::ShiftRight
                | BinaryOp::And
                | BinaryOp::Or => {
                    let opcode = binary_op_to_opcode(*op);
                    // VDBE: P3 = P2 op P1 → dest=reg, lhs=left, rhs=right.
                    b.emit_op(opcode, right_reg, left_reg, reg, P4::None, 0);
                }

                // Comparison ops: jump-based boolean (1/0/NULL).
                BinaryOp::Eq
                | BinaryOp::Ne
                | BinaryOp::Lt
                | BinaryOp::Le
                | BinaryOp::Gt
                | BinaryOp::Ge => {
                    let cmp_opcode = match op {
                        BinaryOp::Eq => Opcode::Eq,
                        BinaryOp::Ne => Opcode::Ne,
                        BinaryOp::Lt => Opcode::Lt,
                        BinaryOp::Le => Opcode::Le,
                        BinaryOp::Gt => Opcode::Gt,
                        BinaryOp::Ge => Opcode::Ge,
                        _ => unreachable!(),
                    };
                    let p4 = upsert_comparison_collation(
                        left,
                        right,
                        existing_ctx,
                        excluded_ctx,
                        _table,
                    )
                    .map_or(P4::None, P4::Collation);
                    let comparison_affinity =
                        upsert_comparison_affinity(left, right, existing_ctx, excluded_ctx, _table);

                    let null_label = b.emit_label();
                    let true_label = b.emit_label();
                    let done_label = b.emit_label();
                    b.emit_jump_to_label(Opcode::IsNull, left_reg, 0, null_label, P4::None, 0);
                    b.emit_jump_to_label(Opcode::IsNull, right_reg, 0, null_label, P4::None, 0);
                    b.emit_jump_to_label(
                        cmp_opcode,
                        right_reg,
                        left_reg,
                        true_label,
                        p4,
                        comparison_affinity,
                    );
                    b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    b.resolve_label(true_label);
                    b.emit_op(Opcode::Integer, 1, reg, 0, P4::None, 0);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    b.resolve_label(null_label);
                    b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                    b.resolve_label(done_label);
                }

                // IS / IS NOT: check for IS TRUE/FALSE/NOT TRUE/NOT FALSE.
                BinaryOp::Is | BinaryOp::IsNot => {
                    if let Some((p3, p4)) = is_true_false_params(*op, right) {
                        // Emit IsTrue opcode for IS TRUE/FALSE/NOT TRUE/NOT FALSE.
                        b.emit_op(Opcode::IsTrue, left_reg, reg, p3, p4, 0);
                    } else {
                        // General IS / IS NOT: NULLEQ semantics.
                        let true_label = b.emit_label();
                        let done_label = b.emit_label();
                        let cmp = if matches!(op, BinaryOp::Is) {
                            Opcode::Eq
                        } else {
                            Opcode::Ne
                        };
                        let p4 = upsert_comparison_collation(
                            left,
                            right,
                            existing_ctx,
                            excluded_ctx,
                            _table,
                        )
                        .map_or(P4::None, P4::Collation);
                        let comparison_affinity = upsert_comparison_affinity(
                            left,
                            right,
                            existing_ctx,
                            excluded_ctx,
                            _table,
                        );
                        b.emit_jump_to_label(
                            cmp,
                            right_reg,
                            left_reg,
                            true_label,
                            p4,
                            0x80 | comparison_affinity,
                        );
                        b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
                        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                        b.resolve_label(true_label);
                        b.emit_op(Opcode::Integer, 1, reg, 0, P4::None, 0);
                        b.resolve_label(done_label);
                    }
                }
            }
        }

        // ── Unary operations ───────────────────────────────────────────
        Expr::UnaryOp {
            op, expr: inner, ..
        } => {
            emit_upsert_expr(
                b,
                inner,
                reg,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            match op {
                fsqlite_ast::UnaryOp::Negate => {
                    let tmp = b.alloc_temp();
                    b.emit_op(Opcode::Integer, -1, tmp, 0, P4::None, 0);
                    b.emit_op(Opcode::Multiply, tmp, reg, reg, P4::None, 0);
                    b.free_temp(tmp);
                }
                fsqlite_ast::UnaryOp::Plus => {}
                fsqlite_ast::UnaryOp::BitNot => {
                    b.emit_op(Opcode::BitNot, reg, reg, 0, P4::None, 0);
                }
                fsqlite_ast::UnaryOp::Not => {
                    b.emit_op(Opcode::Not, reg, reg, 0, P4::None, 0);
                }
            }
        }

        // ── CAST ───────────────────────────────────────────────────────
        Expr::Cast {
            expr: inner,
            type_name,
            ..
        } => {
            emit_upsert_expr(
                b,
                inner,
                reg,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            let affinity = type_name_to_affinity(type_name);
            b.emit_op(Opcode::Cast, reg, i32::from(affinity), 0, P4::None, 0);
        }

        // ── IS [NOT] NULL ──────────────────────────────────────────────
        Expr::IsNull {
            expr: inner, not, ..
        } => {
            emit_upsert_expr(
                b,
                inner,
                reg,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            let lbl_null = b.emit_label();
            let lbl_done = b.emit_label();
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, lbl_null, P4::None, 0);
            b.emit_op(Opcode::Integer, i32::from(*not), reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, lbl_done, P4::None, 0);
            b.resolve_label(lbl_null);
            b.emit_op(Opcode::Integer, i32::from(!*not), reg, 0, P4::None, 0);
            b.resolve_label(lbl_done);
        }

        // ── COLLATE ────────────────────────────────────────────────────
        Expr::Collate { expr: inner, .. } => {
            emit_upsert_expr(
                b,
                inner,
                reg,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
        }

        // ── Scalar function calls ──────────────────────────────────────
        // (includes multi-arg max/min which are scalar, not aggregate)
        Expr::FunctionCall { name, args, .. } if !is_aggregate_function_call(name, args) => {
            let canon = name.to_ascii_uppercase();
            match args {
                fsqlite_ast::FunctionArgs::Star => {
                    b.emit_op(Opcode::PureFunc, 0, 0, reg, P4::FuncName(canon), 0);
                }
                fsqlite_ast::FunctionArgs::List(arg_list) => {
                    let Ok(nargs) = u16::try_from(arg_list.len()) else {
                        b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                        return;
                    };
                    let arg_base = b.alloc_regs(i32::from(nargs));
                    for (i, arg_expr) in arg_list.iter().enumerate() {
                        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                        emit_upsert_expr(
                            b,
                            arg_expr,
                            arg_base + i as i32,
                            existing_ctx,
                            excluded_ctx,
                            _table,
                            existing_hidden_rowid_reg,
                            excluded_hidden_rowid_reg,
                        );
                    }
                    let function_p4 =
                        if scalar_consumes_argument_collation_for_codegen(&canon, i32::from(nargs))
                        {
                            upsert_scalar_function_collation(
                                arg_list,
                                existing_ctx,
                                excluded_ctx,
                                _table,
                            )
                            .map_or_else(
                                || P4::FuncName(canon.clone()),
                                |collation| P4::FuncNameCollated(canon.clone(), collation),
                            )
                        } else {
                            P4::FuncName(canon.clone())
                        };
                    b.emit_op(Opcode::PureFunc, 0, arg_base, reg, function_p4, nargs);
                }
            }
        }

        // ── CASE expression ────────────────────────────────────────────
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            let done_label = b.emit_label();
            let r_operand = operand.as_deref().map(|op_expr| {
                let r = b.alloc_temp();
                emit_upsert_expr(
                    b,
                    op_expr,
                    r,
                    existing_ctx,
                    excluded_ctx,
                    _table,
                    existing_hidden_rowid_reg,
                    excluded_hidden_rowid_reg,
                );
                r
            });

            for (when_expr, then_expr) in whens {
                let next_when = b.emit_label();
                if let Some(r_op) = r_operand {
                    let r_when = b.alloc_temp();
                    emit_upsert_expr(
                        b,
                        when_expr,
                        r_when,
                        existing_ctx,
                        excluded_ctx,
                        _table,
                        existing_hidden_rowid_reg,
                        excluded_hidden_rowid_reg,
                    );
                    b.emit_jump_to_label(Opcode::IsNull, r_op, 0, next_when, P4::None, 0);
                    b.emit_jump_to_label(Opcode::IsNull, r_when, 0, next_when, P4::None, 0);
                    let comparison_p4 = operand
                        .as_deref()
                        .and_then(|operand| {
                            upsert_comparison_collation(
                                operand,
                                when_expr,
                                existing_ctx,
                                excluded_ctx,
                                _table,
                            )
                        })
                        .map_or(P4::None, P4::Collation);
                    let comparison_affinity = operand.as_deref().map_or(0, |operand| {
                        upsert_comparison_affinity(
                            operand,
                            when_expr,
                            existing_ctx,
                            excluded_ctx,
                            _table,
                        )
                    });
                    b.emit_jump_to_label(
                        Opcode::Ne,
                        r_when,
                        r_op,
                        next_when,
                        comparison_p4,
                        comparison_affinity,
                    );
                    b.free_temp(r_when);
                } else {
                    // Searched CASE WHEN is a TRUTH context: short-circuit AND/OR
                    // left-to-right so a would-be-skipped erroring operand is never
                    // evaluated (bd-and-or-short-circuit GAP-2, ON CONFLICT DO
                    // UPDATE path). Non-AND/OR conditions emit byte-identically.
                    //
                    // bd-xjfrt: the condition MUST evaluate into its own scratch
                    // register, never `reg`. `reg` is the assignment destination,
                    // which for an unqualified target column aliases the existing
                    // row's value register (`existing_regs + col_idx`). Using `reg`
                    // as the comparison scratch clobbered that existing value, so a
                    // later bare-column reference in the THEN/ELSE (e.g.
                    // `CASE WHEN 1>2 THEN excluded.v ELSE v END`) read the clobbered
                    // 0 instead of the real column value.
                    let cond_scratch = b.alloc_temp();
                    emit_upsert_case_when_condition(
                        b,
                        when_expr,
                        cond_scratch,
                        next_when,
                        existing_ctx,
                        excluded_ctx,
                        _table,
                        existing_hidden_rowid_reg,
                        excluded_hidden_rowid_reg,
                    );
                    b.free_temp(cond_scratch);
                }
                emit_upsert_expr(
                    b,
                    then_expr,
                    reg,
                    existing_ctx,
                    excluded_ctx,
                    _table,
                    existing_hidden_rowid_reg,
                    excluded_hidden_rowid_reg,
                );
                b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                b.resolve_label(next_when);
            }

            if let Some(el) = else_expr.as_deref() {
                emit_upsert_expr(
                    b,
                    el,
                    reg,
                    existing_ctx,
                    excluded_ctx,
                    _table,
                    existing_hidden_rowid_reg,
                    excluded_hidden_rowid_reg,
                );
            } else {
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            }
            b.resolve_label(done_label);
            if let Some(r_op) = r_operand {
                b.free_temp(r_op);
            }
        }

        // ── LIKE / GLOB / MATCH / REGEXP ───────────────────────────────
        Expr::Like {
            expr: operand,
            pattern,
            escape,
            op: like_op,
            not,
            ..
        } => {
            if use_builtin_like_glob_semantics()
                && matches!(like_op, fsqlite_ast::LikeOp::Like)
                && escape.is_none()
                && let Expr::Literal(Literal::String(pattern_text), _) = pattern.as_ref()
                && let Some((kind, literal)) = classify_sql_like_fast_path(pattern_text, None)
            {
                emit_upsert_expr(
                    b,
                    operand,
                    reg,
                    existing_ctx,
                    excluded_ctx,
                    _table,
                    existing_hidden_rowid_reg,
                    excluded_hidden_rowid_reg,
                );
                b.emit_op(
                    Opcode::LikeConstFast,
                    reg,
                    reg,
                    kind.opcode_tag(),
                    P4::Str(literal.to_owned()),
                    u16::from(*not),
                );
                return;
            }

            let func_name = match like_op {
                fsqlite_ast::LikeOp::Like => "LIKE",
                fsqlite_ast::LikeOp::Glob => "GLOB",
                fsqlite_ast::LikeOp::Match => "MATCH",
                fsqlite_ast::LikeOp::Regexp => "REGEXP",
            };
            let nargs: u16 = if escape.is_some() { 3 } else { 2 };
            let arg_base = b.alloc_regs(i32::from(nargs));
            emit_upsert_expr(
                b,
                pattern,
                arg_base,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            emit_upsert_expr(
                b,
                operand,
                arg_base + 1,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            if let Some(esc) = escape {
                emit_upsert_expr(
                    b,
                    esc,
                    arg_base + 2,
                    existing_ctx,
                    excluded_ctx,
                    _table,
                    existing_hidden_rowid_reg,
                    excluded_hidden_rowid_reg,
                );
            }
            let function_p4 =
                if scalar_consumes_argument_collation_for_codegen(func_name, i32::from(nargs)) {
                    upsert_scalar_function_collation(
                        [pattern.as_ref(), operand.as_ref()]
                            .into_iter()
                            .chain(escape.as_deref()),
                        existing_ctx,
                        excluded_ctx,
                        _table,
                    )
                    .map_or_else(
                        || P4::FuncName(func_name.to_owned()),
                        |collation| P4::FuncNameCollated(func_name.to_owned(), collation),
                    )
                } else {
                    P4::FuncName(func_name.to_owned())
                };
            b.emit_op(Opcode::PureFunc, 0, arg_base, reg, function_p4, nargs);
            if *not {
                b.emit_op(Opcode::Not, reg, reg, 0, P4::None, 0);
            }
        }

        // ── BETWEEN ────────────────────────────────────────────────────
        Expr::Between {
            expr: operand,
            low,
            high,
            not,
            ..
        } => {
            let r_operand = b.alloc_temp();
            let r_low = b.alloc_temp();
            let r_high = b.alloc_temp();
            emit_upsert_expr(
                b,
                operand,
                r_operand,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            emit_upsert_expr(
                b,
                low,
                r_low,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            emit_upsert_expr(
                b,
                high,
                r_high,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            let false_label = b.emit_label();
            let null_label = b.emit_label();
            let done_label = b.emit_label();
            let low_collation_p4 =
                upsert_comparison_collation(operand, low, existing_ctx, excluded_ctx, _table)
                    .map_or(P4::None, P4::Collation);
            let high_collation_p4 =
                upsert_comparison_collation(operand, high, existing_ctx, excluded_ctx, _table)
                    .map_or(P4::None, P4::Collation);
            let low_affinity =
                upsert_comparison_affinity(operand, low, existing_ctx, excluded_ctx, _table);
            let high_affinity =
                upsert_comparison_affinity(operand, high, existing_ctx, excluded_ctx, _table);
            b.emit_jump_to_label(Opcode::IsNull, r_operand, 0, null_label, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::Lt,
                r_low,
                r_operand,
                false_label,
                low_collation_p4,
                low_affinity,
            );
            b.emit_jump_to_label(
                Opcode::Gt,
                r_high,
                r_operand,
                false_label,
                high_collation_p4,
                high_affinity,
            );
            b.emit_jump_to_label(Opcode::IsNull, r_low, 0, null_label, P4::None, 0);
            b.emit_jump_to_label(Opcode::IsNull, r_high, 0, null_label, P4::None, 0);
            b.emit_op(Opcode::Integer, i32::from(!*not), reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
            b.resolve_label(false_label);
            b.emit_op(Opcode::Integer, i32::from(*not), reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
            b.resolve_label(null_label);
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            b.resolve_label(done_label);
            b.free_temp(r_high);
            b.free_temp(r_low);
            b.free_temp(r_operand);
        }

        // ── IN (list) ──────────────────────────────────────────────────
        Expr::In {
            expr: operand,
            set,
            not,
            ..
        } => {
            if let fsqlite_ast::InSet::List(values) = set {
                if values.is_empty() {
                    b.emit_op(Opcode::Integer, i32::from(*not), reg, 0, P4::None, 0);
                    return;
                }
                let r_operand = b.alloc_temp();
                emit_upsert_expr(
                    b,
                    operand,
                    r_operand,
                    existing_ctx,
                    excluded_ctx,
                    _table,
                    existing_hidden_rowid_reg,
                    excluded_hidden_rowid_reg,
                );
                let null_label = b.emit_label();
                let true_label = b.emit_label();
                let done_label = b.emit_label();
                b.emit_jump_to_label(Opcode::IsNull, r_operand, 0, null_label, P4::None, 0);
                let r_saw_null = b.alloc_temp();
                b.emit_op(Opcode::Integer, 0, r_saw_null, 0, P4::None, 0);
                let r_val = b.alloc_temp();
                let in_collation = if values.len() == 1 && singleton_in_rhs_is_constant(&values[0])
                {
                    upsert_comparison_collation(
                        operand,
                        &values[0],
                        existing_ctx,
                        excluded_ctx,
                        _table,
                    )
                } else {
                    upsert_effective_collation(operand, existing_ctx, excluded_ctx, _table)
                };
                let comparison_p4 = in_collation.map_or(P4::None, P4::Collation);
                let comparison_affinity = combine_comparison_affinity(
                    upsert_expr_affinity(operand, existing_ctx, excluded_ctx, _table),
                    b'A',
                );
                for val_expr in values {
                    emit_upsert_expr(
                        b,
                        val_expr,
                        r_val,
                        existing_ctx,
                        excluded_ctx,
                        _table,
                        existing_hidden_rowid_reg,
                        excluded_hidden_rowid_reg,
                    );
                    b.emit_jump_to_label(
                        Opcode::Eq,
                        r_val,
                        r_operand,
                        true_label,
                        comparison_p4.clone(),
                        comparison_affinity,
                    );
                    let next_val = b.emit_label();
                    let set_flag = b.emit_label();
                    b.emit_jump_to_label(Opcode::IsNull, r_val, 0, set_flag, P4::None, 0);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, next_val, P4::None, 0);
                    b.resolve_label(set_flag);
                    b.emit_op(Opcode::Integer, 1, r_saw_null, 0, P4::None, 0);
                    b.resolve_label(next_val);
                }
                b.free_temp(r_val);
                b.emit_jump_to_label(Opcode::If, r_saw_null, 0, null_label, P4::None, 0);
                b.free_temp(r_saw_null);
                b.emit_op(Opcode::Integer, i32::from(*not), reg, 0, P4::None, 0);
                b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                b.resolve_label(null_label);
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                b.resolve_label(true_label);
                b.emit_op(Opcode::Integer, i32::from(!*not), reg, 0, P4::None, 0);
                b.resolve_label(done_label);
                b.free_temp(r_operand);
            } else {
                // Subquery IN — unlikely in UPSERT SET, fall back to existing_ctx.
                emit_expr(b, expr, reg, Some(existing_ctx));
            }
        }

        // ── JSON access ────────────────────────────────────────────────
        Expr::JsonAccess {
            expr: inner,
            path,
            arrow,
            ..
        } => {
            let arg_base = b.alloc_regs(2);
            emit_upsert_expr(
                b,
                inner,
                arg_base,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            emit_upsert_expr(
                b,
                path,
                arg_base + 1,
                existing_ctx,
                excluded_ctx,
                _table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            let function_name = json_access_func_name(*arrow);
            let function_p4 = if scalar_consumes_argument_collation_for_codegen(function_name, 2) {
                upsert_scalar_function_collation(
                    [inner.as_ref(), path.as_ref()],
                    existing_ctx,
                    excluded_ctx,
                    _table,
                )
                .map_or_else(
                    || P4::FuncName(function_name.to_owned()),
                    |collation| P4::FuncNameCollated(function_name.to_owned(), collation),
                )
            } else {
                P4::FuncName(function_name.to_owned())
            };
            b.emit_op(Opcode::PureFunc, 0, arg_base, reg, function_p4, 2);
        }

        // ── Fallback: subqueries, EXISTS, aggregates, etc. ─────────────
        _ => {
            emit_expr(b, expr, reg, Some(existing_ctx));
        }
    }
}

/// Configuration for the code generator.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct CodegenContext {
    /// The database text encoding. When not UTF-8, codegen disables the
    /// compile-time preformatted-record bake (which assumes UTF-8 TEXT bytes) so
    /// the encoding-aware runtime `MakeRecord` path serializes TEXT in the DB
    /// encoding (bd-bld9w.7 family a). Defaults to UTF-8, so existing
    /// construction sites via `..CodegenContext::default()` are unchanged.
    pub text_encoding: TextEncoding,
    /// Whether we're in `BEGIN CONCURRENT` mode.
    /// When true, `OP_NewRowid` uses the snapshot-independent allocator.
    pub concurrent_mode: bool,
    /// Optional column index for an `INTEGER PRIMARY KEY` rowid alias on the
    /// target table. Used by INSERT DEFAULT VALUES to keep the aliased column
    /// in sync with the generated rowid.
    pub rowid_alias_col_idx: Option<usize>,
    /// Whether index-ordered scans produce correctly sorted output.
    /// When false, the codegen falls back to the sorter for ORDER BY
    /// instead of attempting index-assisted optimization.
    /// Set to false for MemDatabase backends where indexes don't maintain
    /// key-sorted iteration order.
    pub index_ordered_scan_reliable: bool,
    /// Optional planner-produced lowering directive for simple single-table
    /// SELECT access paths. When present, lowering either honors it or emits
    /// an explicit bypass reason before falling back to heuristic selection.
    pub planner_select_directive: Option<SelectPlannerDirective>,
    /// `PRAGMA reverse_unordered_selects`: when true, a SELECT whose row order
    /// is not fixed by an ORDER BY walks its full-table scan in reverse
    /// (`Last`/`Prev` instead of `Rewind`/`Next`). Only unordered scans are
    /// affected; a query with an ORDER BY keeps its required order (GH #236).
    pub reverse_unordered_selects: bool,
}

/// Errors during code generation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CodegenError {
    /// Table not found in schema.
    TableNotFound(String),
    /// Column not found in table.
    ColumnNotFound { table: String, column: String },
    /// Ambiguous unqualified column reference.
    AmbiguousColumn(String),
    /// Unsupported AST construct for this codegen pass.
    Unsupported(String),
    /// A genuine SQL statement error (e.g. an INSERT column/value count
    /// mismatch) that stock SQLite reports VERBATIM under SQLITE_ERROR — not an
    /// unsupported feature. Both codegen-error mappers surface it via
    /// `FunctionError` (no "not implemented: " prefix).
    SqlError(String),
}

impl std::fmt::Display for CodegenError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TableNotFound(name) => write!(f, "table not found: {name}"),
            Self::ColumnNotFound { table, column } => {
                write!(f, "column {column} not found in table {table}")
            }
            Self::AmbiguousColumn(name) => write!(f, "ambiguous column name: {name}"),
            Self::Unsupported(msg) => write!(f, "unsupported: {msg}"),
            Self::SqlError(msg) => write!(f, "{msg}"),
        }
    }
}

impl std::error::Error for CodegenError {}

// ---------------------------------------------------------------------------
// Schema lookup helper
// ---------------------------------------------------------------------------

fn find_table<'a>(schema: &'a [TableSchema], name: &str) -> Result<&'a TableSchema, CodegenError> {
    schema
        .iter()
        .find(|t| t.name.eq_ignore_ascii_case(name))
        .ok_or_else(|| CodegenError::TableNotFound(name.to_owned()))
}

fn find_index_named<'a>(table: &'a TableSchema, index_name: &str) -> Option<&'a IndexSchema> {
    table
        .indexes
        .iter()
        .find(|index| index.name.eq_ignore_ascii_case(index_name))
}

fn directive_index_contract_bypass_reason(
    directive: &SelectPlannerDirective,
    idx_schema: &IndexSchema,
    table: &TableSchema,
    table_alias: Option<&str>,
    columns: &[ResultColumn],
) -> Option<&'static str> {
    let Some(expected_index_key_label) = directive.index_key_label.as_deref() else {
        return Some("missing_index_key_label");
    };
    let Some(actual_index_key_label) = idx_schema.key_term_sql(0) else {
        return Some("index_has_no_key_term");
    };
    if !actual_index_key_label.eq_ignore_ascii_case(expected_index_key_label) {
        return Some("index_key_label_mismatch");
    }
    if directive.covering
        && resolve_covering_output_sources(columns, table, table_alias, idx_schema).is_none()
    {
        return Some("covering_contract_mismatch");
    }
    None
}

fn log_planner_select_directive_outcome(
    directive: &SelectPlannerDirective,
    honor_mode: &str,
    bypass_reason: &str,
    lowered_ops: &str,
) {
    if !tracing::enabled!(target: "fsqlite.planner_runtime", tracing::Level::INFO) {
        return;
    }

    let run_id = env::var("RUN_ID").unwrap_or_else(|_| "(none)".to_owned());
    let trace_id = env::var("TRACE_ID").unwrap_or_else(|_| "(none)".to_owned());
    let scenario_id = env::var("SCENARIO_ID").unwrap_or_else(|_| "(none)".to_owned());
    let index_name = directive.index_name.as_deref().unwrap_or("(none)");
    let index_key_label = directive.index_key_label.as_deref().unwrap_or("(none)");

    tracing::info!(
        target: "fsqlite.planner_runtime",
        run_id = %run_id,
        trace_id,
        scenario_id = %scenario_id,
        plan_id = %directive.plan_id,
        plan_generation = directive.plan_generation,
        planner_surface = %directive.planner_surface,
        table = %directive.table_name,
        index = %index_name,
        index_key = %index_key_label,
        access_kind = %directive.access_kind.label(),
        covering = directive.covering,
        honor_mode = %honor_mode,
        bypass_reason = %bypass_reason,
        lowered_ops = %lowered_ops,
        "vdbe.planner_select_directive"
    );
}

fn table_name_from_qualified(qtr: &QualifiedTableRef) -> &str {
    &qtr.name.name
}

/// Emit a `SetSnapshot` opcode for cursor `cursor` if a time-travel clause
/// is present. Must be called immediately after the corresponding `OpenRead`.
fn emit_set_snapshot(b: &mut ProgramBuilder, cursor: i32, tt: Option<&TimeTravelClause>) {
    if let Some(clause) = tt {
        let p4 = match &clause.target {
            TimeTravelTarget::CommitSequence(seq) => P4::TimeTravelCommitSeq(*seq),
            TimeTravelTarget::Timestamp(ts) => P4::TimeTravelTimestamp(ts.clone()),
        };
        b.emit_op(Opcode::SetSnapshot, cursor, 0, 0, p4, 0);
    }
}

/// Count anonymous placeholders in an expression tree.
///
/// Used by `codegen_update` to correctly number placeholders when bytecode
/// emission order differs from SQL textual order (WHERE is emitted before SET,
/// but SET placeholders appear first in the SQL text).
fn count_anon_placeholders(expr: &Expr) -> u32 {
    match expr {
        Expr::Placeholder(fsqlite_ast::PlaceholderType::Anonymous, _) => 1,
        Expr::Placeholder(_, _)
        | Expr::Literal(_, _)
        | Expr::BoundOuterValue { .. }
        | Expr::Column(_, _)
        | Expr::Raise { .. } => 0,
        Expr::Subquery(subquery, _) | Expr::Exists { subquery, .. } => {
            count_anon_placeholders_in_select(subquery)
        }
        Expr::BinaryOp { left, right, .. } => {
            count_anon_placeholders(left) + count_anon_placeholders(right)
        }
        Expr::UnaryOp { expr: inner, .. }
        | Expr::IsNull { expr: inner, .. }
        | Expr::Cast { expr: inner, .. }
        | Expr::Collate { expr: inner, .. } => count_anon_placeholders(inner),
        Expr::Between {
            expr: inner,
            low,
            high,
            ..
        } => {
            count_anon_placeholders(inner)
                + count_anon_placeholders(low)
                + count_anon_placeholders(high)
        }
        Expr::In {
            expr: inner, set, ..
        } => {
            count_anon_placeholders(inner)
                + match set {
                    fsqlite_ast::InSet::List(items) => {
                        items.iter().map(count_anon_placeholders).sum()
                    }
                    fsqlite_ast::InSet::Subquery(subquery) => {
                        count_anon_placeholders_in_select(subquery)
                    }
                    fsqlite_ast::InSet::Table(_) => 0,
                }
        }
        Expr::Like {
            expr: inner,
            pattern,
            escape,
            ..
        } => {
            count_anon_placeholders(inner)
                + count_anon_placeholders(pattern)
                + escape.as_deref().map_or(0, count_anon_placeholders)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand.as_deref().map_or(0, count_anon_placeholders)
                + whens
                    .iter()
                    .map(|(cond, then_expr)| {
                        count_anon_placeholders(cond) + count_anon_placeholders(then_expr)
                    })
                    .sum::<u32>()
                + else_expr.as_deref().map_or(0, count_anon_placeholders)
        }
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            over,
            ..
        } => {
            let args_count = match args {
                FunctionArgs::List(exprs) => exprs.iter().map(count_anon_placeholders).sum(),
                FunctionArgs::Star => 0,
            };
            args_count
                + order_by
                    .iter()
                    .map(|term| count_anon_placeholders(&term.expr))
                    .sum::<u32>()
                + filter.as_deref().map_or(0, count_anon_placeholders)
                + over
                    .as_ref()
                    .map_or(0, count_anon_placeholders_in_window_spec)
        }
        Expr::JsonAccess { expr, path, .. } => {
            count_anon_placeholders(expr) + count_anon_placeholders(path)
        }
        Expr::RowValue(items, _) => items.iter().map(count_anon_placeholders).sum(),
    }
}

fn count_anon_placeholders_in_select(select: &SelectStatement) -> u32 {
    let mut count = 0;
    if let Some(with_clause) = &select.with {
        for cte in &with_clause.ctes {
            count += count_anon_placeholders_in_select(&cte.query);
        }
    }
    count += count_anon_placeholders_in_select_core(&select.body.select);
    for (_, core) in &select.body.compounds {
        count += count_anon_placeholders_in_select_core(core);
    }
    for order_term in &select.order_by {
        count += count_anon_placeholders(&order_term.expr);
    }
    if let Some(limit_clause) = &select.limit {
        count += count_anon_placeholders(&limit_clause.limit);
        if let Some(offset) = &limit_clause.offset {
            count += count_anon_placeholders(offset);
        }
    }
    count
}

fn count_anon_placeholders_in_select_core(core: &SelectCore) -> u32 {
    match core {
        SelectCore::Select {
            columns,
            from,
            where_clause,
            group_by,
            having,
            windows,
            ..
        } => {
            let mut count = columns
                .iter()
                .filter_map(|col| match col {
                    ResultColumn::Expr { expr, .. } => Some(count_anon_placeholders(expr)),
                    ResultColumn::Star | ResultColumn::TableStar(_) => None,
                })
                .sum::<u32>();

            if let Some(from_clause) = from {
                count += count_anon_placeholders_in_from_clause(from_clause);
            }
            if let Some(predicate) = where_clause {
                count += count_anon_placeholders(predicate);
            }
            for expr in group_by {
                count += count_anon_placeholders(expr);
            }
            if let Some(predicate) = having {
                count += count_anon_placeholders(predicate);
            }
            for window in windows {
                count += count_anon_placeholders_in_window_spec(&window.spec);
            }
            count
        }
        SelectCore::Values(rows) => rows
            .iter()
            .map(|row| row.iter().map(count_anon_placeholders).sum::<u32>())
            .sum(),
    }
}

fn count_anon_placeholders_in_from_clause(from: &fsqlite_ast::FromClause) -> u32 {
    let mut count = count_anon_placeholders_in_table_or_subquery(&from.source);
    for join in &from.joins {
        count += count_anon_placeholders_in_table_or_subquery(&join.table);
        if let Some(fsqlite_ast::JoinConstraint::On(expr)) = &join.constraint {
            count += count_anon_placeholders(expr);
        }
    }
    count
}

fn count_anon_placeholders_in_table_or_subquery(source: &TableOrSubquery) -> u32 {
    match source {
        TableOrSubquery::Table { .. } => 0,
        TableOrSubquery::Subquery { query, .. } => count_anon_placeholders_in_select(query),
        TableOrSubquery::TableFunction { args, .. } => {
            args.iter().map(count_anon_placeholders).sum()
        }
        TableOrSubquery::ParenJoin(from_clause) => {
            count_anon_placeholders_in_from_clause(from_clause)
        }
    }
}

fn count_anon_placeholders_in_window_spec(spec: &fsqlite_ast::WindowSpec) -> u32 {
    let mut count: u32 = spec.partition_by.iter().map(count_anon_placeholders).sum();
    count += spec
        .order_by
        .iter()
        .map(|term| count_anon_placeholders(&term.expr))
        .sum::<u32>();
    if let Some(frame) = &spec.frame {
        count += count_anon_placeholders_in_frame_bound(&frame.start);
        if let Some(end) = &frame.end {
            count += count_anon_placeholders_in_frame_bound(end);
        }
    }
    count
}

fn count_anon_placeholders_in_frame_bound(bound: &fsqlite_ast::FrameBound) -> u32 {
    match bound {
        fsqlite_ast::FrameBound::Preceding(expr) | fsqlite_ast::FrameBound::Following(expr) => {
            count_anon_placeholders(expr)
        }
        fsqlite_ast::FrameBound::UnboundedPreceding
        | fsqlite_ast::FrameBound::CurrentRow
        | fsqlite_ast::FrameBound::UnboundedFollowing => 0,
    }
}

/// Whether an expression contains a placeholder that has not been canonicalized
/// to an explicit `?NNN` slot.
///
/// Connection-level compilation canonicalizes anonymous and named parameters
/// before calling VDBE codegen. Direct codegen callers can still supply raw ASTs,
/// though, and the builder's emission-order counter cannot preserve SQL textual
/// ordering (or named-parameter reuse) when one optimization emits LIMIT before
/// WHERE. Such callers must stay on an emission path that does not duplicate or
/// reorder the expression.
fn expr_contains_non_numbered_placeholder(expr: &Expr) -> bool {
    match expr {
        Expr::Placeholder(fsqlite_ast::PlaceholderType::Numbered(_), _)
        | Expr::Literal(_, _)
        | Expr::BoundOuterValue { .. }
        | Expr::Column(_, _)
        | Expr::Raise { .. } => false,
        Expr::Placeholder(_, _) => true,
        Expr::Subquery(select, _)
        | Expr::Exists {
            subquery: select, ..
        } => select_contains_non_numbered_placeholder(select),
        Expr::BinaryOp { left, right, .. } => {
            expr_contains_non_numbered_placeholder(left)
                || expr_contains_non_numbered_placeholder(right)
        }
        Expr::UnaryOp { expr, .. }
        | Expr::IsNull { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. } => expr_contains_non_numbered_placeholder(expr),
        Expr::Between {
            expr, low, high, ..
        } => {
            expr_contains_non_numbered_placeholder(expr)
                || expr_contains_non_numbered_placeholder(low)
                || expr_contains_non_numbered_placeholder(high)
        }
        Expr::In { expr, set, .. } => {
            expr_contains_non_numbered_placeholder(expr)
                || match set {
                    InSet::List(items) => items.iter().any(expr_contains_non_numbered_placeholder),
                    InSet::Subquery(select) => select_contains_non_numbered_placeholder(select),
                    InSet::Table(_) => false,
                }
        }
        Expr::Like {
            expr,
            pattern,
            escape,
            ..
        } => {
            expr_contains_non_numbered_placeholder(expr)
                || expr_contains_non_numbered_placeholder(pattern)
                || escape
                    .as_deref()
                    .is_some_and(expr_contains_non_numbered_placeholder)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand
                .as_deref()
                .is_some_and(expr_contains_non_numbered_placeholder)
                || whens.iter().any(|(when_expr, then_expr)| {
                    expr_contains_non_numbered_placeholder(when_expr)
                        || expr_contains_non_numbered_placeholder(then_expr)
                })
                || else_expr
                    .as_deref()
                    .is_some_and(expr_contains_non_numbered_placeholder)
        }
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            over,
            ..
        } => {
            matches!(
                args,
                FunctionArgs::List(items)
                    if items.iter().any(expr_contains_non_numbered_placeholder)
            ) || order_by
                .iter()
                .any(|term| expr_contains_non_numbered_placeholder(&term.expr))
                || filter
                    .as_deref()
                    .is_some_and(expr_contains_non_numbered_placeholder)
                || over
                    .as_ref()
                    .is_some_and(window_spec_contains_non_numbered_placeholder)
        }
        Expr::JsonAccess { expr, path, .. } => {
            expr_contains_non_numbered_placeholder(expr)
                || expr_contains_non_numbered_placeholder(path)
        }
        Expr::RowValue(items, _) => items.iter().any(expr_contains_non_numbered_placeholder),
    }
}

fn select_contains_non_numbered_placeholder(select: &SelectStatement) -> bool {
    select.with.as_ref().is_some_and(|with_clause| {
        with_clause
            .ctes
            .iter()
            .any(|cte| select_contains_non_numbered_placeholder(&cte.query))
    }) || select_core_contains_non_numbered_placeholder(&select.body.select)
        || select
            .body
            .compounds
            .iter()
            .any(|(_, core)| select_core_contains_non_numbered_placeholder(core))
        || select
            .order_by
            .iter()
            .any(|term| expr_contains_non_numbered_placeholder(&term.expr))
        || select.limit.as_ref().is_some_and(|clause| {
            expr_contains_non_numbered_placeholder(&clause.limit)
                || clause
                    .offset
                    .as_ref()
                    .is_some_and(expr_contains_non_numbered_placeholder)
        })
}

fn select_core_contains_non_numbered_placeholder(core: &SelectCore) -> bool {
    match core {
        SelectCore::Select {
            columns,
            from,
            where_clause,
            group_by,
            having,
            windows,
            ..
        } => {
            columns.iter().any(|column| {
                matches!(
                    column,
                    ResultColumn::Expr { expr, .. }
                        if expr_contains_non_numbered_placeholder(expr)
                )
            }) || from
                .as_ref()
                .is_some_and(from_clause_contains_non_numbered_placeholder)
                || where_clause
                    .as_deref()
                    .is_some_and(expr_contains_non_numbered_placeholder)
                || group_by.iter().any(expr_contains_non_numbered_placeholder)
                || having
                    .as_deref()
                    .is_some_and(expr_contains_non_numbered_placeholder)
                || windows
                    .iter()
                    .any(|window| window_spec_contains_non_numbered_placeholder(&window.spec))
        }
        SelectCore::Values(rows) => rows
            .iter()
            .flatten()
            .any(expr_contains_non_numbered_placeholder),
    }
}

fn from_clause_contains_non_numbered_placeholder(from: &FromClause) -> bool {
    table_or_subquery_contains_non_numbered_placeholder(&from.source)
        || from.joins.iter().any(|join| {
            table_or_subquery_contains_non_numbered_placeholder(&join.table)
                || matches!(
                    &join.constraint,
                    Some(fsqlite_ast::JoinConstraint::On(expr))
                        if expr_contains_non_numbered_placeholder(expr)
                )
        })
}

fn table_or_subquery_contains_non_numbered_placeholder(source: &TableOrSubquery) -> bool {
    match source {
        TableOrSubquery::Table { .. } => false,
        TableOrSubquery::Subquery { query, .. } => select_contains_non_numbered_placeholder(query),
        TableOrSubquery::TableFunction { args, .. } => {
            args.iter().any(expr_contains_non_numbered_placeholder)
        }
        TableOrSubquery::ParenJoin(from) => from_clause_contains_non_numbered_placeholder(from),
    }
}

fn window_spec_contains_non_numbered_placeholder(spec: &fsqlite_ast::WindowSpec) -> bool {
    spec.partition_by
        .iter()
        .any(expr_contains_non_numbered_placeholder)
        || spec
            .order_by
            .iter()
            .any(|term| expr_contains_non_numbered_placeholder(&term.expr))
        || spec.frame.as_ref().is_some_and(|frame| {
            frame_bound_contains_non_numbered_placeholder(&frame.start)
                || frame
                    .end
                    .as_ref()
                    .is_some_and(frame_bound_contains_non_numbered_placeholder)
        })
}

fn frame_bound_contains_non_numbered_placeholder(bound: &fsqlite_ast::FrameBound) -> bool {
    match bound {
        fsqlite_ast::FrameBound::Preceding(expr) | fsqlite_ast::FrameBound::Following(expr) => {
            expr_contains_non_numbered_placeholder(expr)
        }
        fsqlite_ast::FrameBound::UnboundedPreceding
        | fsqlite_ast::FrameBound::CurrentRow
        | fsqlite_ast::FrameBound::UnboundedFollowing => false,
    }
}

// ---------------------------------------------------------------------------
// SELECT codegen
// ---------------------------------------------------------------------------

/// Generate VDBE bytecode for a SELECT statement.
///
/// Handles two patterns:
/// 1. **Rowid lookup**: `SELECT cols FROM t WHERE rowid = ?`
/// 2. **Full table scan**: `SELECT cols FROM t`
///
/// Returns the cursor number used (for composability).
#[allow(clippy::too_many_lines)]
pub fn codegen_select(
    b: &mut ProgramBuilder,
    stmt: &SelectStatement,
    schema: &[TableSchema],
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    if stmt.with.is_some() {
        return Err(CodegenError::Unsupported(
            "WITH clauses require connection-level CTE lowering or an explicit fallback boundary"
                .to_owned(),
        ));
    }

    let (columns, from, where_clause, group_by, having, distinct) = match &stmt.body.select {
        SelectCore::Select {
            columns,
            from,
            where_clause,
            group_by,
            having,
            distinct,
            ..
        } => (columns, from, where_clause, group_by, having, *distinct),
        SelectCore::Values(rows) => {
            codegen_values_select(b, rows);
            return Ok(());
        }
    };

    // Handle SELECT without FROM (e.g. SELECT 1, SELECT 1+1, SELECT abs(-5)).
    if from.is_none() {
        codegen_select_without_from(b, columns, where_clause.as_deref());
        return Ok(());
    }

    // Determine the table from the FROM clause.
    // SAFETY: `from.is_none()` is handled above; `.expect` cannot panic.
    let from_clause = from.as_ref().expect("from already checked above");

    if !from_clause.joins.is_empty()
        && let Some(plan) = grouped_inner_join_count_sum_plan(stmt, from_clause, schema)?
    {
        return codegen_grouped_inner_join_count_sum_select(b, &plan, ctx);
    }

    let (table_name, table_alias, from_schema, time_travel, from_index_hint) =
        match &from_clause.source {
            fsqlite_ast::TableOrSubquery::Table {
                name,
                alias,
                time_travel,
                index_hint,
            } => (
                &name.name,
                alias.as_deref(),
                name.schema.as_deref(),
                time_travel.as_ref(),
                index_hint.as_ref(),
            ),
            _ => {
                return Err(CodegenError::Unsupported(
                    "non-table FROM source".to_owned(),
                ));
            }
        };
    let join_has_time_travel = from_clause.joins.iter().any(|join| {
        matches!(
            &join.table,
            fsqlite_ast::TableOrSubquery::Table {
                time_travel: Some(_),
                ..
            }
        )
    });
    if !from_clause.joins.is_empty() {
        let simple_join_eligible = !has_aggregate_columns(columns)
            && group_by.is_empty()
            && having.is_none()
            && !has_window_columns(columns)
            && distinct == Distinctness::All
            && time_travel.is_none()
            && !join_has_time_travel;
        if !simple_join_eligible {
            return Err(CodegenError::Unsupported(
                "JOIN shape not yet supported in VDBE codegen".to_owned(),
            ));
        }
    }

    // Route simple 2-table INNER JOINs through dedicated codegen when there
    // are no aggregates, GROUP BY, window functions, or DISTINCT — this is
    // the common "SELECT ... FROM a JOIN b ON ..." shape that the benchmark
    // exercises and that currently falls back to the connection interpreter.
    if !from_clause.joins.is_empty()
        && !has_aggregate_columns(columns)
        && group_by.is_empty()
        && having.is_none()
        && !has_window_columns(columns)
        && distinct == Distinctness::All
        && time_travel.is_none()
    {
        return self::codegen_join_select(
            b,
            stmt,
            from_clause,
            columns,
            where_clause.as_deref(),
            schema,
            ctx,
        );
    }

    let table = find_table(schema, table_name)?;
    let rewritten_order_by = stmt
        .order_by
        .iter()
        .map(|term| {
            let mut rewritten = term.clone();
            if resolve_order_by_output_expr(&term.expr, columns).is_none() {
                rewritten.expr = rewrite_having_select_aliases(&term.expr, columns, table);
            }
            rewritten
        })
        .collect::<Vec<_>>();
    if rewritten_order_by != stmt.order_by {
        let mut rewritten_stmt = stmt.clone();
        rewritten_stmt.order_by = rewritten_order_by;
        return codegen_select(b, &rewritten_stmt, schema, ctx);
    }
    // bd-ujuzr: SQLite resolves a result-column alias referenced in the WHERE
    // clause when no real table column matches.  Substitute aliases up front (a
    // real column always wins), reusing the HAVING alias-rewrite, so both
    // validation and the scan filter see the underlying expression.
    let where_clause_rewritten: Option<Box<Expr>> = where_clause
        .as_deref()
        .map(|w| Box::new(rewrite_having_select_aliases(w, columns, table)));
    // Re-bind with the original `&Option<Box<Expr>>` shape so the downstream
    // `.as_deref()` call sites keep their meaning (and avoid no-op derefs).
    let where_clause = &where_clause_rewritten;
    validate_single_table_result_columns(columns, table, table_alias, from_schema)?;
    if let Some(where_expr) = where_clause.as_deref() {
        validate_single_table_expr_columns(where_expr, table, table_alias)?;
    }
    validate_single_table_order_by_terms(&stmt.order_by, columns, table, table_alias)?;
    let cursor = 0_i32;

    // Labels for control flow.
    let end_label = b.emit_label();
    let done_label = b.emit_label();

    // Init: jump to end (standard SQLite pattern).
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);

    // Transaction (read-only, p2=0).
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);

    // Determine output columns and allocate registers.
    let out_col_count = result_column_count(columns, table);
    let out_regs = b.alloc_regs(out_col_count);

    let simple_count_star = is_simple_count_star(columns)
        && stmt.limit.is_none()
        && stmt.order_by.is_empty()
        && distinct == Distinctness::All
        && group_by.is_empty()
        && having.is_none()
        && !has_window_columns(columns)
        && from_clause.joins.is_empty()
        && time_travel.is_none()
        // bd-2dgf5: `COUNT(*) FROM t WHERE col = <const>` (equality) or `col IN (<int list>)` on an
        // indexed column is served far better by the aggregate index seek than by
        // `codegen_select_count_star`, whose only indexed path
        // (`extract_count_indexed_exists_target`) does not match a plain equality or an IN-list and so
        // degrades to Rewind/Next over the whole table. Yield to `codegen_select_aggregate`, which drives
        // AggStep from an index seek (`index_eq_seek` / `index_in_seek`). Every other COUNT(*) shape keeps
        // its specialized fast path.
        && !(aggregate_index_eq_seek_allowed(from_index_hint)
            && (aggregate_index_eq_seek_target(where_clause.as_deref(), table, table_alias).is_some()
                || index_integer_in_list_residual_target(where_clause.as_deref(), table, table_alias)
                    .is_some()
                || aggregate_index_range_seek_target(
                    where_clause.as_deref(),
                    table,
                    table_alias,
                    schema,
                )
                .is_some()
                || composite_index_prefix_range_target(
                    where_clause.as_deref(),
                    table,
                    table_alias,
                    schema,
                    None,
                )
                .is_some()
                || aggregate_index_prefix_literal_residual_target(
                    where_clause.as_deref(),
                    table,
                    table_alias,
                    None,
                )
                .is_some()
                || extract_rowid_range_residual_target(where_clause.as_deref(), table, table_alias)
                    .is_some_and(|(_, has_residual)| has_residual)));

    // Check for aggregate columns FIRST, before rowid/index seek optimizations.
    // Most aggregates still require a full scan + AggStep/AggFinal path. Plain
    // COUNT(*) is handled separately below so it can keep a specialized fast path.
    let is_aggregate = has_aggregate_columns(columns);
    let forced_index_hint = matches!(from_index_hint, Some(fsqlite_ast::IndexHint::IndexedBy(_)));
    // Check for rowid-equality WHERE clause (only for non-aggregate queries).
    let rowid_target = if is_aggregate || forced_index_hint {
        None
    } else {
        extract_rowid_target_expr(where_clause.as_deref(), Some(table), table_alias)
    };
    let rowid_order = (!stmt.order_by.is_empty())
        .then(|| resolve_order_by_rowid_direction(table, table_alias, columns, &stmt.order_by))
        .flatten();
    let rowid_range_allowed = !(forced_index_hint
        || (is_aggregate && !simple_count_star)
        || distinct != Distinctness::All
        || !group_by.is_empty()
        || having.is_some()
        || (!stmt.order_by.is_empty() && rowid_order.is_none()));
    let rowid_range = if rowid_range_allowed {
        extract_rowid_range_target(where_clause.as_deref(), Some(table), table_alias)
            .and_then(|range| rowid_range_fast_path_is_safe(range).then_some(range))
    } else {
        None
    };
    // bd-nonagg-rowid-range-residual: `rowid <range> AND <residual>` — walk only the [lower, upper] slice
    // (rowid order = full-scan order) and re-apply the whole WHERE per row, instead of full-scanning. The
    // bare range (no residual) is owned by `rowid_range` above; this handles ONLY the conjunction case
    // (`has_residual`). Gated to no-LIMIT so nothing before the residual filter emits a placeholder (the
    // detector already requires integer-literal bounds), keeping the residual `?` numbering trivial.
    let rowid_range_residual =
        if rowid_range_allowed && rowid_range.is_none() && stmt.limit.is_none() {
            extract_rowid_range_residual_target(where_clause.as_deref(), table, table_alias)
                .filter(|(_, has_residual)| *has_residual)
                .map(|(range, _)| range)
        } else {
            None
        };
    let index_range = if is_aggregate
        || from_index_hint.is_some()
        || time_travel.is_some()
        || distinct != Distinctness::All
        || !group_by.is_empty()
        || having.is_some()
    {
        None
    } else {
        extract_column_range_target(where_clause.as_deref(), table, table_alias).and_then(
            |(col_name, range)| {
                // All-index search: a composite `(col, …)` index declared before `idx_col` shadows it
                // in `index_for_column`, and filtering that result with `?` would decline even though a
                // usable single-column index exists — full-scanning `WHERE col <range>` (non-aggregate
                // mirror of bd-agg-range-shadowed-index). Search every index instead.
                let idx = table.indexes.iter().find(|idx| {
                    idx.supports_direct_column_lookup()
                        && idx.key_term_count() == 1
                        && !idx.key_term_descending(0)
                        && idx
                            .columns
                            .first()
                            .is_some_and(|c| c.eq_ignore_ascii_case(&col_name))
                })?;
                // bd-wimmv/bd-ss48y follow-up: the single-column range seek streams in `(col, rowid)`
                // order (single-key index), so it satisfies a deterministic `ORDER BY col, <rowid>`
                // (or bare `ORDER BY col` when the index is UNIQUE — no ties) without a sorter —
                // otherwise it falls to a sorter. Any other ORDER BY declines.
                if !stmt.order_by.is_empty()
                    && !range_order_by_is_deterministic(
                        &col_name,
                        &stmt.order_by,
                        table,
                        table_alias,
                        idx.is_unique,
                        false,
                    )
                {
                    return None;
                }
                if !index_range_fast_path_is_safe(table, table_alias, schema, &col_name, &range) {
                    return None;
                }
                Some((col_name, idx, range))
            },
        )
    };
    // Check for a simple indexed equality probe (only for non-aggregate queries).
    // We probe with [bound_value, i64::MIN] so SeekGE anchors on the first
    // duplicate entry in non-unique indexes and the loop can walk the full
    // duplicate run via Next + IdxRowid.
    let index_eq_target = if is_aggregate {
        None
    } else {
        extract_column_eq_target(where_clause.as_deref(), table, table_alias)
    };
    // Heuristic equality lowering must never compete with an explicit table hint. Resolve the exact
    // usable index once, including collation and physical-shape checks, and carry that same object into
    // emission. This prevents validating one index and then opening a different first-match index.
    // The current equality extractor accepts only a bare column paired with a simple constant, so the
    // comparison collation is exactly the column's declared collation; explicit COLLATE shapes decline.
    let heuristic_index_eq: Option<(&IndexSchema, &Expr)> = if from_index_hint.is_some() {
        None
    } else {
        index_eq_target
            .as_ref()
            .and_then(|(column_name, target_expr)| {
                let comparison_collation = table
                    .column_index(column_name)
                    .and_then(|column_idx| table.columns.get(column_idx))
                    .and_then(|column| column.collation.as_deref());
                table
                    .single_column_index_for_column_with_collation(
                        column_name,
                        comparison_collation,
                    )
                    .map(|index| (index, *target_expr))
            })
    };

    // bd-nonagg-eq-residual: `SELECT <cols> FROM t WHERE <int/text-indexed col> = <lit>
    // AND <residual on a non-indexed col>` (e.g. `SELECT * ... WHERE a = 5 AND c = 7`). The planner
    // emits an IndexEquality directive for the `col=lit` conjunct which bypasses on the residual it
    // cannot enforce (or emits none), reaching the heuristic chain below — where `index_eq_target`'s bare-`Eq`
    // detection misses the conjunction and the query full-scans. Detect the exact eq-literal prefix (via
    // the residual-safe `aggregate_index_prefix_literal_residual_target`, which requires ≥1 residual
    // conjunct so pure `col=lit` still routes through the directive) and seek the `col=lit` block,
    // filtering the FULL WHERE per row (`codegen_select_index_equality_scan` with `residual_filter =
    // true`, so its fast path narrows to the exact matches). Dispatched as a heuristic fallback (AFTER
    // rowid/range/index_eq, before the full scan) so strictly-better rowid/range paths still win. Single
    // eq column only. The residual-aware emitter always opens the table even when the projection itself
    // is index-covering, because the residual may read any table column. The `col=lit` rows come back in
    // rowid order — the full scan's order within that block — so byte-identical.
    let eq_residual: Option<(&IndexSchema, &Expr)> = if is_aggregate
        || from_index_hint.is_some()
        || time_travel.is_some()
        || !stmt.order_by.is_empty()
        || distinct != Distinctness::All
        || !group_by.is_empty()
        || having.is_some()
        || has_window_columns(columns)
        || table.without_rowid
        // The connection canonicalizes every bind parameter to `?NNN`, which
        // keeps the residual and LIMIT/OFFSET slots stable even though this
        // emitter generates LIMIT first and WHERE later. A direct/raw AST can
        // still contain anonymous or named parameters; decline only this
        // reorder-and-reapply optimization rather than assigning colliding
        // slots or breaking named-parameter reuse.
        || where_clause
            .as_deref()
            .is_some_and(expr_contains_non_numbered_placeholder)
        || stmt.limit.as_ref().is_some_and(|clause| {
            expr_contains_non_numbered_placeholder(&clause.limit)
                || clause
                    .offset
                    .as_ref()
                    .is_some_and(expr_contains_non_numbered_placeholder)
        }) {
        None
    } else {
        aggregate_index_prefix_literal_residual_target(
            where_clause.as_deref(),
            table,
            table_alias,
            Some(1),
        )
        .filter(|(_idx, prefix)| prefix.len() == 1)
        .map(|(idx, prefix)| (idx, prefix[0]))
    };

    // bd-2dgf5: non-aggregate `SELECT ... FROM t WHERE <int col> IN (<int literals>)` seeks
    // the index once per distinct value instead of full-scanning. Same INTEGER-affinity +
    // integer-literal safe subset as the aggregate IN path; declined for ORDER BY (the seek
    // yields value-then-rowid order, which only happens to equal the sort order sometimes),
    // LIMIT, and DISTINCT to keep this first cut small.
    let in_list_seek_allowed = !is_aggregate
        && from_index_hint.is_none()
        && stmt.order_by.is_empty()
        && stmt.limit.is_none()
        && distinct == Distinctness::All
        && group_by.is_empty()
        && having.is_none()
        && !table.without_rowid;
    // bd-nonagg-rowid-in-order: the rowid IN seek emits in ascending-rowid order (the values are sorted
    // and deduped), so it can serve `ORDER BY <rowid> ASC` for free — and `DESC` by reversing the emit
    // order — instead of declining to a full-scan-plus-sort. `rowid_order` (computed above) is `Some`
    // ONLY for a single ORDER BY term that resolves to the rowid; the IPK is unique so no tiebreaker is
    // needed. Unlike the index IN seek (value-then-rowid order), the rowid seek's order is exactly rowid
    // order, so this relaxation is rowid-IN-specific — `in_list_seek_allowed` stays strict for index_in.
    let rowid_in_seek_allowed = !is_aggregate
        && from_index_hint.is_none()
        && (stmt.order_by.is_empty() || rowid_order.is_some())
        && stmt.limit.is_none()
        && distinct == Distinctness::All
        && group_by.is_empty()
        && having.is_none()
        && !table.without_rowid;
    // bd-2dgf5: `WHERE <rowid> IN (<int literals>)` — one SeekRowid per distinct value.
    // bd-nonagg-rowid-in-residual: also admit `rowid IN (ints) AND <residual>` — the residual variant
    // returns `has_residual = true`; the SeekRowid probes visit only the listed rows and the emitter
    // re-applies the whole WHERE per row. The table is always open, so the residual reads any column.
    let rowid_in = if rowid_in_seek_allowed {
        extract_rowid_in_list_residual_target(where_clause.as_deref(), table, table_alias)
    } else {
        None
    };
    // bd-nonagg-in-list-residual: also admit `col IN (ints) AND <residual>` — the residual variant
    // returns `has_residual = true`, and the IN scan re-applies the whole WHERE per row (the seek
    // visits the IN runs, a superset; the residual narrows to exact). The IN emitter always opens the
    // table, so the residual reads any column and no covering gate is needed; IN is not a single-eq
    // prefix, so it does not collide with the composite-prefix-range path.
    let index_in = if in_list_seek_allowed && rowid_in.is_none() {
        index_integer_in_list_residual_target(where_clause.as_deref(), table, table_alias)
    } else {
        None
    };
    // bd-nonagg-rowid-eq-residual: `rowid = <const> AND <residual>` — one SeekRowid on the target row,
    // then the whole WHERE re-applied to it. The planner emits a RowidLookup directive (it sees the eq)
    // but codegen's bare `rowid_target` extraction declines the conjunction, so the directive bypasses
    // (`rowid_lookup_target_missing`) and the shape falls through to a full scan. Route it here, before
    // the directive. The bare `rowid = <const>` (single conjunct) is declined by the detector and keeps
    // its existing directive path. Same narrow gate as the IN seeks. `codegen_select_rowid_lookup`
    // always opens the table, so the residual reads any column and all outputs work.
    let rowid_eq_residual = if in_list_seek_allowed && rowid_in.is_none() {
        extract_rowid_eq_residual_target(where_clause.as_deref(), table, table_alias)
    } else {
        None
    };

    // bd-2dgf5: route a seekable integer IN-list BEFORE the planner directive. The connection
    // emits a `FullTableScan` directive for `rowid IN (...)` (it does not model IN as a
    // seekable access path), which would otherwise bypass these seeks. The gate is narrow
    // (INTEGER-affinity + integer literals + IN, no unsupported ORDER BY / LIMIT / DISTINCT):
    // a single rowid ASC/DESC ordering is served directly by the sorted seek sequence. The
    // seek is differential-proven bit-identical to SQLite, so preferring it over a full scan
    // is always correct and strictly faster.
    if let Some((values, has_residual)) = rowid_in {
        return codegen_select_rowid_in_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            out_regs,
            out_col_count,
            done_label,
            end_label,
            &values,
            where_clause.as_deref(),
            has_residual,
            matches!(rowid_order, Some(SortDirection::Desc)),
        );
    }

    // bd-nonagg-rowid-eq-residual: single SeekRowid + full-WHERE residual, ahead of the directive.
    if let Some(target_expr) = rowid_eq_residual {
        return codegen_select_rowid_lookup(
            b,
            cursor,
            table,
            table_alias,
            time_travel,
            schema,
            columns,
            out_regs,
            out_col_count,
            done_label,
            end_label,
            stmt.limit.as_ref(),
            target_expr,
            where_clause.as_deref(),
            true,
        );
    }

    if let Some((idx_schema, values, has_residual)) = index_in {
        return codegen_select_index_in_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            out_regs,
            out_col_count,
            done_label,
            end_label,
            idx_schema,
            &values,
            where_clause.as_deref(),
            has_residual,
        );
    }

    // A rowid-backed IN subquery over an indexed outer column can be lowered to
    // a streaming semijoin that counts each equal first-key run in the outer
    // index.  Route that proven shape before the planner directive: the planner
    // currently models IN as a scan and an explicit INDEXED BY hint therefore
    // otherwise commits us to the generic per-row membership program.  The
    // extractor honors INDEXED BY/NOT INDEXED and admits a composite index only
    // when the unique, ordered RHS rowid stream makes the merge path mandatory;
    // list/materialized probes retain their single-key seek contract.
    if simple_count_star {
        let scan_ctx = ScanCtx {
            cursor,
            table,
            table_alias,
            schema: Some(schema),
            register_base: None,
            secondaries: &[],
        };
        if let Some((idx_schema, in_target)) = extract_count_indexed_in_target(
            where_clause.as_deref(),
            table,
            table_alias,
            schema,
            &scan_ctx,
            from_index_hint,
        ) {
            return codegen_select_count_star_indexed_in_scan(
                b,
                cursor,
                table,
                table_alias,
                schema,
                out_regs,
                done_label,
                end_label,
                idx_schema,
                in_target,
            );
        }
    }

    // bd-g5ys1: route `SELECT <cols> FROM t WHERE <indexed col> IN (SELECT ...)`
    // (uncorrelated, single-key ascending index, matching collation) through a
    // materialize-then-seek program instead of the full scan probing an
    // ephemeral membership index. Same pre-directive routing rationale as the
    // IN-list and COUNT(*) hooks above: the planner models IN as a scan (its
    // IndexEquality directive carries no payload for an IN), so the directive
    // arm declines and the shape previously fell to `codegen_select_full_scan`.
    // The gate reuses `in_list_seek_allowed` (non-aggregate, no ORDER BY /
    // LIMIT / DISTINCT / GROUP BY / HAVING, rowid table); the extractor
    // enforces plain `IN` (not `NOT IN`), an uncorrelated subquery, index-hint
    // honor, and operand/index collation equivalence. Control reaching here
    // means the rowid/IN-list routes above did not fire. The `(key, i64::MIN)`
    // seek-probe contract requires a single-key index, so composite matches
    // (admitted by the extractor only for the COUNT merge path) are declined.
    if in_list_seek_allowed {
        let scan_ctx = ScanCtx {
            cursor,
            table,
            table_alias,
            schema: Some(schema),
            register_base: None,
            secondaries: &[],
        };
        if let Some((idx_schema, in_target)) = extract_count_indexed_in_target(
            where_clause.as_deref(),
            table,
            table_alias,
            schema,
            &scan_ctx,
            from_index_hint,
        ) && idx_schema.key_term_count() == 1
            && let CountIndexedInTarget::ProbeSource(probe_source)
            | CountIndexedInTarget::MaterializedProbeSource(probe_source) = in_target
        {
            return codegen_select_index_in_subquery_scan(
                b,
                cursor,
                table,
                table_alias,
                schema,
                columns,
                out_regs,
                out_col_count,
                done_label,
                end_label,
                idx_schema,
                &probe_source,
            );
        }
    }

    // bd-zqkrp: route a composite equality-prefix + trailing-range seek (`WHERE a = v AND b <range>`
    // on `index(a, b)`) BEFORE the planner directive. The planner reports this as an IndexRange
    // directive, but the single-column `index_range` local below is None for this shape, so the
    // directive bypasses to a full scan. The seek is affinity-coerced and differential-proven
    // bit-identical, so preferring it is always correct and strictly faster. First cut declines
    // ORDER BY / LIMIT / DISTINCT / aggregate / GROUP BY / WITHOUT ROWID.
    //
    // GH #291: an `INDEXED BY` hint naming a composite index MUST take this
    // seek — previously any hint declined it, and because the IndexRange
    // directive arm also rejects composite shapes, the hinted query fell all
    // the way back to a full table scan (observed as multi-GB RSS for a
    // 593-row range lookup on a 9 GB database). The hint now restricts the
    // candidate set to the named index; `NOT INDEXED` still declines by
    // definition.
    let composite_required_index = match from_index_hint {
        None => Some(None),
        Some(fsqlite_ast::IndexHint::IndexedBy(name)) => Some(Some(name.as_str())),
        Some(fsqlite_ast::IndexHint::NotIndexed) => None,
    };
    let composite_prefix_range = if !is_aggregate
        && time_travel.is_none()
        && let Some(required_index) = composite_required_index
        && distinct == Distinctness::All
        && group_by.is_empty()
        && having.is_none()
        && !table.without_rowid
    {
        composite_index_prefix_range_target(
            where_clause.as_deref(),
            table,
            table_alias,
            schema,
            required_index,
        )
    } else {
        None
    };
    // bd-zqkrp follow-up: the seek emits rows in `(range_col, rowid)` order, so it satisfies an
    // `ORDER BY <trailing range col> ASC` (when that column is the last key term) without a sorter —
    // and LIMIT/OFFSET streams straight off the seek. An empty ORDER BY always qualifies.
    if let Some(composite) = composite_prefix_range {
        if stmt.order_by.is_empty()
            || composite_order_by_satisfied(&composite, &stmt.order_by, table, table_alias)
        {
            return codegen_select_composite_index_prefix_range_scan(
                b,
                cursor,
                table,
                table_alias,
                schema,
                columns,
                stmt.limit.as_ref(),
                out_regs,
                out_col_count,
                done_label,
                end_label,
                composite.index,
                &composite.prefix_exprs,
                &composite.range,
            );
        }
        // bd-6x9z0 follow-up: composite DESC. `WHERE a = v AND b <range> ORDER BY b DESC, id DESC`
        // (composite keyset "most recent first" pagination) streams off a reverse index walk with NO
        // sorter — the composite mirror of the single-column DESC range seek. Only the deterministic
        // `range_col DESC[, id DESC]` order (or a bare `range_col DESC` on a UNIQUE index) qualifies;
        // any other order falls through to the sorter.
        if composite_order_by_satisfied_desc(&composite, &stmt.order_by, table, table_alias) {
            return codegen_select_composite_index_prefix_range_scan_desc(
                b,
                cursor,
                table,
                table_alias,
                schema,
                columns,
                stmt.limit.as_ref(),
                out_regs,
                out_col_count,
                done_label,
                end_label,
                composite.index,
                &composite.prefix_exprs,
                &composite.range,
            );
        }
    }

    // bd-ln7dp: reverse (DESC) single-column range seek. `WHERE col <range> ORDER BY col DESC, id
    // DESC` (keyset "most recent first" pagination) streams in `(col DESC, rowid DESC)` order off a
    // reverse index walk (SeekLE/Last + Prev) — no sorter, and LIMIT/OFFSET stream off it. Routed
    // before the directive (which would otherwise pick the ascending seek). Declines aggregate /
    // GROUP BY / DISTINCT / hints / WITHOUT ROWID and any order other than `col DESC[, id DESC]`.
    let index_range_desc = if !is_aggregate
        && time_travel.is_none()
        && from_index_hint.is_none()
        && distinct == Distinctness::All
        && group_by.is_empty()
        && having.is_none()
        && !table.without_rowid
        && !stmt.order_by.is_empty()
    {
        extract_column_range_target(where_clause.as_deref(), table, table_alias).and_then(
            |(col_name, range)| {
                // All-index search (see the ascending `index_range` above): don't let a composite
                // `(col, …)` index shadow a usable single-column one and force a full scan.
                let idx = table.indexes.iter().find(|idx| {
                    idx.supports_direct_column_lookup()
                        && idx.key_term_count() == 1
                        && !idx.key_term_descending(0)
                        && idx
                            .columns
                            .first()
                            .is_some_and(|c| c.eq_ignore_ascii_case(&col_name))
                })?;
                if !range_order_by_is_deterministic(
                    &col_name,
                    &stmt.order_by,
                    table,
                    table_alias,
                    idx.is_unique,
                    true,
                ) {
                    return None;
                }
                if !index_range_fast_path_is_safe(table, table_alias, schema, &col_name, &range) {
                    return None;
                }
                Some((idx, range))
            },
        )
    } else {
        None
    };
    if let Some((idx_schema, range)) = index_range_desc {
        return codegen_select_index_range_scan_desc(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            idx_schema,
            &range,
        );
    }

    // bd-nax2y skip scan: `SELECT <cols> FROM t WHERE <second_col> = <const>` where the constrained
    // column is the SECOND term of a two-column index whose LEADING term is unconstrained (a
    // MySQL-style skip scan). No constraint on the leading term, so the equality/range/composite seeks
    // above all decline and the query would otherwise full-scan. The emitter is adaptive so a
    // near-unique leading column degrades to a full index walk (== the covering scan it replaces).
    // First cut: no ORDER BY / LIMIT / GROUP BY / HAVING / DISTINCT / aggregate / index hint.
    if !is_aggregate
        && time_travel.is_none()
        && from_index_hint.is_none()
        && distinct == Distinctness::All
        && group_by.is_empty()
        && having.is_none()
        && let Some(skip) = skip_scan_eq_target(where_clause.as_deref(), table, table_alias)
        // ORDER BY `x, id` (the 2nd column is a constant here) is served in the emission order with no
        // sorter, and a satisfied ORDER BY makes a LIMIT's top-N deterministic so it may stream too. A
        // bare LIMIT with no ORDER BY (non-deterministic which-rows) declines.
        && ((stmt.order_by.is_empty() && stmt.limit.is_none())
            || skip_scan_order_by_satisfied(skip.index, false, &stmt.order_by, table, table_alias))
    {
        return codegen_select_skip_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            out_regs,
            out_col_count,
            done_label,
            end_label,
            skip.index,
            skip.const_expr,
            stmt.limit.as_ref(),
        );
    }
    // Range skip scan (bd-nax2y): the same shape but the constrained second key term carries an
    // inclusive-lower range instead of an equality.
    if !is_aggregate
        && time_travel.is_none()
        && from_index_hint.is_none()
        && distinct == Distinctness::All
        && group_by.is_empty()
        && having.is_none()
        && let Some(skip) = skip_scan_range_target(where_clause.as_deref(), table, table_alias)
        // ORDER BY `x, second, id` streams with no sorter, and a satisfied ORDER BY makes a LIMIT's
        // top-N deterministic so it may stream too. A bare LIMIT with no ORDER BY declines.
        && ((stmt.order_by.is_empty() && stmt.limit.is_none())
            || skip_scan_order_by_satisfied(skip.index, true, &stmt.order_by, table, table_alias))
    {
        return codegen_select_skip_scan_range(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            out_regs,
            out_col_count,
            done_label,
            end_label,
            skip.index,
            &skip.range,
            stmt.limit.as_ref(),
        );
    }
    // IS-NULL skip scan (bd-nax2y): `WHERE <second_col> IS NULL`; the 2nd key is constant (NULL) within
    // the run, so ORDER BY treats it like the equality case (`second_varies = false`).
    if !is_aggregate
        && time_travel.is_none()
        && from_index_hint.is_none()
        && distinct == Distinctness::All
        && group_by.is_empty()
        && having.is_none()
        && let Some(skip) = skip_scan_is_null_target(where_clause.as_deref(), table, table_alias)
        && ((stmt.order_by.is_empty() && stmt.limit.is_none())
            || skip_scan_order_by_satisfied(skip.index, false, &stmt.order_by, table, table_alias))
    {
        return codegen_select_skip_scan_is_null(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            out_regs,
            out_col_count,
            done_label,
            end_label,
            skip.index,
            stmt.limit.as_ref(),
        );
    }

    // bd-rowid-range-before-directive: `SELECT ... FROM t WHERE <rowid> <range>` receives a
    // `FullTableScan` planner directive — `PlannerSelectAccessKind` has no rowid-range variant, so the
    // planner cannot model it as a seekable path — which short-circuits to `codegen_select_full_scan`
    // below and reads every row, bypassing the `rowid_range` heuristic (only reached with no
    // directive). The rowid-range scan positions on the table b-tree at the bound and walks only the
    // `[lower, upper]` rowid slice in rowid order — the SAME order the full scan emits — so it is
    // byte-identical to the full scan (same rows, same order, just fewer) and always ≤ it: no covering
    // gate is needed because it reads the table directly, exactly like the scan, only bounded. Route it
    // before the directive, mirroring the bd-2dgf5 / bd-zqkrp seeks. `rowid_range` is `Copy`, so the
    // heuristic dispatch below is left intact for the no-directive path. bd-rowid-range-before-directive.
    if let Some(rr) = rowid_range
        && ctx.planner_select_directive.as_ref().is_some_and(|d| {
            d.table_name.eq_ignore_ascii_case(&table.name)
                && matches!(d.access_kind, PlannerSelectAccessKind::FullTableScan)
        })
    {
        return codegen_select_rowid_range_scan(
            b,
            cursor,
            table,
            table_alias,
            time_travel,
            schema,
            columns,
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            rr,
            matches!(rowid_order, Some(SortDirection::Desc)),
            None,
            false,
        );
    }

    // bd-nonagg-rowid-range-residual: same pre-directive hoist as the bare range above, but for
    // `rowid <range> AND <residual on a column the planner cannot seek>`. The planner still emits a
    // `FullTableScan` directive (it models neither the rowid range nor the non-indexed residual as
    // seekable), which would full-scan every row. The residual walk visits only the [lower, upper] slice
    // in rowid order and filters per row — byte-identical to the full scan, always ≤ it, so no covering
    // gate. (When the residual IS on an indexed column the planner emits an IndexEquality directive
    // instead and that path — with its own residual filter — owns the query; this hoist declines.)
    if let Some(rr) = rowid_range_residual
        && ctx.planner_select_directive.as_ref().is_some_and(|d| {
            d.table_name.eq_ignore_ascii_case(&table.name)
                && matches!(d.access_kind, PlannerSelectAccessKind::FullTableScan)
        })
    {
        return codegen_select_rowid_range_scan(
            b,
            cursor,
            table,
            table_alias,
            time_travel,
            schema,
            columns,
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            rr,
            matches!(rowid_order, Some(SortDirection::Desc)),
            where_clause.as_deref(),
            true,
        );
    }

    // bd-covering-range-before-directive: `SELECT <covering cols> FROM t WHERE col <range>` (no
    // ORDER BY) receives a `FullTableScan` planner directive — the planner does not model a
    // single-column range as a seekable access path — which short-circuits to
    // `codegen_select_full_scan` below and reads every row, bypassing the `index_range` heuristic (only
    // reached when no directive is emitted). When the seek is COVERING (every output is the rowid or an
    // index column, so `resolve_covering_output_sources` succeeds and no table row is ever read) the
    // index-range walk visits only the matching key slice and is strictly cheaper than the full scan —
    // it cannot pessimize even a non-selective range the way a non-covering per-row `SeekRowid` could.
    // Route it before the directive, exactly like the bd-2dgf5 IN-list and bd-zqkrp composite-prefix
    // seeks; the emitted rows are index-ordered (spec-legal without ORDER BY) and byte-identical as a
    // set to the full scan (same oracle-tested emitter used at the heuristic below). Rowid tables only;
    // non-covering ranges are left to the planner's full scan to avoid random-lookup regressions.
    if let Some((_range_col, idx_schema, range)) = index_range.as_ref()
        && !table.without_rowid
        && ctx.planner_select_directive.as_ref().is_some_and(|d| {
            d.table_name.eq_ignore_ascii_case(&table.name)
                && matches!(d.access_kind, PlannerSelectAccessKind::FullTableScan)
        })
        && resolve_covering_output_sources(columns, table, table_alias, idx_schema).is_some()
    {
        return codegen_select_index_range_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            idx_schema,
            planner_index_range_target_from_column_range(range),
        );
    }

    if let Some(directive) = ctx.planner_select_directive.as_ref() {
        let bypass_reason = if !directive.table_name.eq_ignore_ascii_case(&table.name) {
            Some("table_mismatch")
        } else {
            match directive.access_kind {
                PlannerSelectAccessKind::FullTableScan => {
                    // bd-gh-indexed-by-desc-scan-order (#224): `INDEXED BY <idx>`
                    // is a HARD contract. The planner directive falls back to a
                    // FullTableScan when no WHERE made the forced index seekable,
                    // but the forced index must still be honored as a full ordered
                    // index scan in its STORED order (forward Rewind/Next: ascending
                    // for an ASC index, descending for a DESC index), matching C
                    // SQLite, rather than silently table-scanning in rowid order.
                    if let Some(fsqlite_ast::IndexHint::IndexedBy(hinted)) = from_index_hint
                        && stmt.order_by.is_empty()
                        && let Some(forced_idx) = table
                            .indexes
                            .iter()
                            .find(|idx| idx.name.eq_ignore_ascii_case(hinted))
                        && forced_idx.supports_direct_column_lookup()
                    {
                        log_planner_select_directive_outcome(
                            directive,
                            "honored",
                            "none",
                            "forced_index_full_scan",
                        );
                        let plan = OrderByIndexPlan {
                            index: forced_idx.clone(),
                            descending: false,
                            equality_prefix_len: 0,
                            covering_output: resolve_covering_output_sources(
                                columns,
                                table,
                                table_alias,
                                forced_idx,
                            ),
                        };
                        return codegen_select_index_ordered_scan(
                            b,
                            cursor,
                            table,
                            table_alias,
                            schema,
                            columns,
                            where_clause.as_deref(),
                            stmt.limit.as_ref(),
                            out_regs,
                            out_col_count,
                            done_label,
                            end_label,
                            &plan,
                        );
                    }
                    log_planner_select_directive_outcome(
                        directive,
                        "honored",
                        "none",
                        "full_table_scan",
                    );
                    return codegen_select_full_scan(
                        b,
                        cursor,
                        table,
                        table_alias,
                        time_travel,
                        schema,
                        columns,
                        where_clause.as_deref(),
                        stmt.limit.as_ref(),
                        out_regs,
                        out_col_count,
                        done_label,
                        end_label,
                        // reverse_unordered_selects: reverse this scan only when
                        // the row order is not fixed by an ORDER BY (GH #236).
                        ctx.reverse_unordered_selects && stmt.order_by.is_empty(),
                    );
                }
                PlannerSelectAccessKind::RowidLookup => match rowid_target {
                    Some(target_expr) => {
                        log_planner_select_directive_outcome(
                            directive,
                            "honored",
                            "none",
                            "seek_rowid",
                        );
                        return codegen_select_rowid_lookup(
                            b,
                            cursor,
                            table,
                            table_alias,
                            time_travel,
                            schema,
                            columns,
                            out_regs,
                            out_col_count,
                            done_label,
                            end_label,
                            stmt.limit.as_ref(),
                            target_expr,
                            None,
                            false,
                        );
                    }
                    None => Some("rowid_lookup_target_missing"),
                },
                PlannerSelectAccessKind::IndexEquality => {
                    if let Some(index_name) = directive.index_name.as_deref() {
                        if let Some(idx_schema) = find_index_named(table, index_name) {
                            if let Some(reason) = directive_index_contract_bypass_reason(
                                directive,
                                idx_schema,
                                table,
                                table_alias,
                                columns,
                            ) {
                                Some(reason)
                            } else if directive.index_key_is_expression {
                                if let Some(directive_target_expr) =
                                    directive.index_equality_target.as_ref()
                                {
                                    match extract_expression_index_equality_expr(
                                        where_clause.as_deref(),
                                        idx_schema,
                                        table,
                                        table_alias,
                                    ) {
                                        Some(actual_target_expr)
                                            if actual_target_expr == directive_target_expr =>
                                        {
                                            log_planner_select_directive_outcome(
                                                directive,
                                                "honored",
                                                "none",
                                                "index_equality_probe",
                                            );
                                            return codegen_select_index_equality_scan(
                                                b,
                                                cursor,
                                                table,
                                                table_alias,
                                                schema,
                                                columns,
                                                where_clause.as_deref(),
                                                stmt.limit.as_ref(),
                                                out_regs,
                                                out_col_count,
                                                done_label,
                                                end_label,
                                                idx_schema,
                                                directive_target_expr,
                                                false,
                                                false,
                                            );
                                        }
                                        Some(_) => Some("index_equality_target_mismatch"),
                                        None => Some("index_equality_target_missing"),
                                    }
                                } else {
                                    Some("index_equality_target_missing")
                                }
                            } else if let Some((index_column_name, target_expr)) =
                                index_eq_target.as_ref()
                            {
                                if directive.index_key_label.as_deref().is_none_or(|label| {
                                    !label.eq_ignore_ascii_case(index_column_name)
                                }) {
                                    Some("index_key_label_mismatch")
                                } else {
                                    log_planner_select_directive_outcome(
                                        directive,
                                        "honored",
                                        "none",
                                        "index_equality_probe",
                                    );
                                    return codegen_select_index_equality_scan(
                                        b,
                                        cursor,
                                        table,
                                        table_alias,
                                        schema,
                                        columns,
                                        where_clause.as_deref(),
                                        stmt.limit.as_ref(),
                                        out_regs,
                                        out_col_count,
                                        done_label,
                                        end_label,
                                        idx_schema,
                                        target_expr,
                                        false,
                                        false,
                                    );
                                }
                            } else if !directive.index_key_is_expression
                                && let Some(label) = directive.index_key_label.as_deref()
                                && let Some(conjunct_target_expr) =
                                    extract_labeled_eq_conjunct_target(
                                        where_clause.as_deref(),
                                        table,
                                        table_alias,
                                        label,
                                    )
                            {
                                // bd-kwaam (#377): the directive's key column matched one
                                // conjunct of a larger AND-tree. Lower through the same seek
                                // emitter with the FULL WHERE re-applied per row
                                // (`residual_filter = true`), so the remaining conjuncts
                                // stay enforced.
                                log_planner_select_directive_outcome(
                                    directive,
                                    "honored",
                                    "none",
                                    "index_equality_probe_residual",
                                );
                                return codegen_select_index_equality_scan(
                                    b,
                                    cursor,
                                    table,
                                    table_alias,
                                    schema,
                                    columns,
                                    where_clause.as_deref(),
                                    stmt.limit.as_ref(),
                                    out_regs,
                                    out_col_count,
                                    done_label,
                                    end_label,
                                    idx_schema,
                                    conjunct_target_expr,
                                    true,
                                    false,
                                );
                            } else {
                                Some("index_equality_target_missing")
                            }
                        } else {
                            Some("index_not_found")
                        }
                    } else {
                        Some("missing_index_name")
                    }
                }
                PlannerSelectAccessKind::IndexRange => {
                    if let Some(index_name) = directive.index_name.as_deref() {
                        if let Some(idx_schema) = find_index_named(table, index_name) {
                            if idx_schema.key_term_count() != 1 || idx_schema.key_term_descending(0)
                            {
                                Some("index_shape_unsupported")
                            } else if let Some(reason) = directive_index_contract_bypass_reason(
                                directive,
                                idx_schema,
                                table,
                                table_alias,
                                columns,
                            ) {
                                Some(reason)
                            } else if directive.index_key_is_expression {
                                if let Some(directive_range_target) =
                                    directive.index_range_target.as_ref()
                                {
                                    match extract_expression_index_range_target(
                                        where_clause.as_deref(),
                                        idx_schema,
                                        table,
                                        table_alias,
                                    ) {
                                        Some(actual_range_target)
                                            if &actual_range_target == directive_range_target =>
                                        {
                                            log_planner_select_directive_outcome(
                                                directive,
                                                "honored",
                                                "none",
                                                "index_range_scan",
                                            );
                                            return codegen_select_index_range_scan(
                                                b,
                                                cursor,
                                                table,
                                                table_alias,
                                                schema,
                                                columns,
                                                stmt.limit.as_ref(),
                                                out_regs,
                                                out_col_count,
                                                done_label,
                                                end_label,
                                                idx_schema,
                                                directive_range_target.clone(),
                                            );
                                        }
                                        Some(_) => Some("index_range_target_mismatch"),
                                        None => Some("index_range_target_missing"),
                                    }
                                } else {
                                    Some("index_range_target_missing")
                                }
                            } else if let Some((index_column_name, _candidate_idx, range_target)) =
                                index_range.as_ref()
                            {
                                if directive.index_key_label.as_deref().is_none_or(|label| {
                                    !label.eq_ignore_ascii_case(index_column_name)
                                }) {
                                    Some("index_key_label_mismatch")
                                } else {
                                    log_planner_select_directive_outcome(
                                        directive,
                                        "honored",
                                        "none",
                                        "index_range_scan",
                                    );
                                    return codegen_select_index_range_scan(
                                        b,
                                        cursor,
                                        table,
                                        table_alias,
                                        schema,
                                        columns,
                                        stmt.limit.as_ref(),
                                        out_regs,
                                        out_col_count,
                                        done_label,
                                        end_label,
                                        idx_schema,
                                        planner_index_range_target_from_column_range(range_target),
                                    );
                                }
                            } else {
                                Some("index_range_target_missing")
                            }
                        } else {
                            Some("index_not_found")
                        }
                    } else {
                        Some("missing_index_name")
                    }
                }
            }
        };

        if let Some(reason) = bypass_reason {
            log_planner_select_directive_outcome(
                directive,
                "bypassed",
                reason,
                "heuristic_fallback",
            );
        }
    }

    if simple_count_star {
        codegen_select_count_star(
            b,
            cursor,
            table,
            table_alias,
            schema,
            where_clause.as_deref(),
            out_regs,
            done_label,
            end_label,
            rowid_range,
            from_index_hint,
        )
    } else if let Some(target_expr) = rowid_target {
        codegen_select_rowid_lookup(
            b,
            cursor,
            table,
            table_alias,
            time_travel,
            schema,
            columns,
            out_regs,
            out_col_count,
            done_label,
            end_label,
            stmt.limit.as_ref(),
            target_expr,
            None,
            false,
        )
    } else if let Some(rowid_range) = rowid_range {
        codegen_select_rowid_range_scan(
            b,
            cursor,
            table,
            table_alias,
            time_travel,
            schema,
            columns,
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            rowid_range,
            matches!(rowid_order, Some(SortDirection::Desc)),
            None,
            false,
        )
    } else if let Some(rr) = rowid_range_residual {
        // bd-nonagg-rowid-range-residual: the planner SUPPRESSES the directive for an IPK range (returns
        // None) so the VDBE picks its bounded seek here in the heuristic fallback — same path the bare
        // range uses. Walk the [lower, upper] slice and re-apply the whole WHERE per row.
        codegen_select_rowid_range_scan(
            b,
            cursor,
            table,
            table_alias,
            time_travel,
            schema,
            columns,
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            rr,
            matches!(rowid_order, Some(SortDirection::Desc)),
            where_clause.as_deref(),
            true,
        )
    } else if let Some((_index_column_name, idx_schema, index_range)) = index_range {
        codegen_select_index_range_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            idx_schema,
            planner_index_range_target_from_column_range(&index_range),
        )
    } else if let Some((idx_schema, target_expr)) = heuristic_index_eq.filter(|_| {
        // bd-nonagg-index-eq-order-rowid: the index-equality seek returns rows in index-key order — for a
        // SINGLE-column ASCENDING index that is exactly rowid order WITHIN the one eq value (ascending
        // seeks `(val, i64::MIN)` + walk forward; descending seeks `(val, i64::MAX)` + `Prev`), so it
        // also satisfies `ORDER BY <rowid>` ASC or DESC for free, seeking only the matching rows instead
        // of full-scanning + sorting. A composite index would order by its trailing key column, so it
        // declines and keeps the sorter / plain scan. No ORDER BY is always fine.
        stmt.order_by.is_empty() || rowid_order.is_some()
    }) {
        // --- Index-seek SELECT: no ORDER BY, or `ORDER BY <rowid>` served by the seek's key order.
        let idx_desc = matches!(rowid_order, Some(SortDirection::Desc));
        codegen_select_index_equality_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            where_clause.as_deref(),
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            idx_schema,
            target_expr,
            false,
            idx_desc,
        )
    } else if let Some((idx_schema, target_expr)) = eq_residual {
        // --- Eq-prefix + residual seek (bd-nonagg-eq-residual) ---
        // Reached when the IndexEquality directive bypassed on the residual (or none was emitted) and
        // `index_eq_target`'s bare-`Eq` detection missed the conjunction. Seek the `col = lit` block and filter
        // the FULL WHERE per row (`residual_filter = true`) instead of scanning every row.
        codegen_select_index_equality_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            where_clause.as_deref(),
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            idx_schema,
            target_expr,
            true,
            false,
        )
    } else if has_aggregate_columns(columns) && !group_by.is_empty() {
        // --- Aggregate query WITH GROUP BY ---
        codegen_select_group_by_aggregate(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            where_clause.as_deref(),
            group_by,
            having.as_deref(),
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
        )
    } else if has_aggregate_columns(columns) {
        // --- Aggregate query (single-group, no GROUP BY) ---
        let limit_anon_placeholder_base = stmt.limit.as_ref().map(|limit_clause| {
            let limit_placeholder_count = count_anon_placeholders(&limit_clause.limit)
                + limit_clause
                    .offset
                    .as_ref()
                    .map_or(0, count_anon_placeholders);
            b.current_anon_placeholder()
                + count_anon_placeholders_in_select(stmt).saturating_sub(limit_placeholder_count)
        });
        codegen_select_aggregate(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            where_clause.as_deref(),
            having.as_deref(),
            stmt.limit.as_ref(),
            limit_anon_placeholder_base,
            out_regs,
            out_col_count,
            done_label,
            end_label,
            aggregate_index_eq_seek_allowed(from_index_hint),
            from_index_hint,
        )
    } else if !stmt.order_by.is_empty() {
        if let Some(index_plan) = ctx
            .index_ordered_scan_reliable
            .then(|| {
                resolve_order_by_index_plan(
                    table,
                    table_alias,
                    columns,
                    where_clause.as_deref(),
                    &stmt.order_by,
                    distinct,
                )
            })
            .flatten()
        {
            tracing::info!(
                table = %table.name,
                index = %index_plan.index.name,
                covering = index_plan.covering_output.is_some(),
                descending = index_plan.descending,
                "vdbe.order_by.index_bypass"
            );
            return codegen_select_index_ordered_scan(
                b,
                cursor,
                table,
                table_alias,
                schema,
                columns,
                where_clause.as_deref(),
                stmt.limit.as_ref(),
                out_regs,
                out_col_count,
                done_label,
                end_label,
                &index_plan,
            );
        }

        // bd-nonagg-rowid-order-scan (+ -desc): `ORDER BY <rowid>` needs NO sorter — a forward table
        // walk (Rewind+Next) is ascending rowid order and a reverse walk (Last+Prev) is descending, and
        // the rowid is unique so there are no ties to resolve. `resolve_order_by_index_plan` returns None
        // for the rowid (no secondary index covers it), so we would otherwise sort every row. Route to
        // the plain scan, which applies LIMIT/OFFSET and stops early under a LIMIT. `rowid_range_allowed`
        // is exactly the safe gate (non-aggregate, no GROUP BY/HAVING/DISTINCT, and — since rowid_order
        // is Some — the ORDER BY is a single rowid term). A WHERE is allowed only when
        // `where_is_plain_scan_safe` proves it carries no MATCH and no subquery — `codegen_select_full_scan`
        // applies it via the SAME per-row filter the sorter path uses, so scan and sort are byte-identical
        // (the sort is just elided). MATCH / subquery cases keep the sorter (they churned golden snapshots
        // and are not oracle-proven equivalent here).
        // Both directions use the SAME scan emitter: `codegen_select_full_scan` walks ascending
        // (`Rewind`+`Next`) or descending (`Last`+`Prev`) and applies the WHERE + LIMIT/OFFSET the same
        // way the sorter path would, so it is byte-identical output with the sort elided.
        if let Some(dir) = rowid_order.filter(|_| {
            rowid_range_allowed && where_clause.as_deref().is_none_or(where_is_plain_scan_safe)
        }) {
            return codegen_select_full_scan(
                b,
                cursor,
                table,
                table_alias,
                time_travel,
                schema,
                columns,
                where_clause.as_deref(),
                stmt.limit.as_ref(),
                out_regs,
                out_col_count,
                done_label,
                end_label,
                dir == SortDirection::Desc,
            );
        }

        // --- Full table scan with ORDER BY (sorter path) ---
        codegen_select_ordered_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            where_clause.as_deref(),
            &stmt.order_by,
            stmt.limit.as_ref(),
            distinct,
            out_regs,
            out_col_count,
            done_label,
            end_label,
        )
    } else if distinct == Distinctness::Distinct {
        // bd-distinct-loose-scan: `SELECT DISTINCT <indexed col>` (no WHERE/GROUP BY/HAVING/LIMIT) is a
        // loose/skip index scan — emit each distinct value once and `SeekGT` past its whole run — instead
        // of scanning every row into a dedup sorter. Work scales with #distinct values, not rows.
        if where_clause.is_none()
            && stmt.limit.is_none()
            && group_by.is_empty()
            && having.is_none()
            && let Some(scan) = distinct_loose_scan_plan(columns, table, table_alias)
        {
            return codegen_select_distinct_loose_scan(
                b,
                cursor,
                &scan,
                out_regs,
                out_col_count,
                done_label,
                end_label,
            );
        }
        // --- Full table scan with DISTINCT ---
        codegen_select_distinct_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            where_clause.as_deref(),
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
        )
    } else if let Some(fsqlite_ast::IndexHint::IndexedBy(hinted)) = from_index_hint
        && stmt.order_by.is_empty()
        && let Some(forced_idx) = table
            .indexes
            .iter()
            .find(|idx| idx.name.eq_ignore_ascii_case(hinted))
        && forced_idx.supports_direct_column_lookup()
    {
        // bd-gh-indexed-by-desc-scan-order (#224): `INDEXED BY <idx>` is a HARD
        // contract. When no WHERE constraint made the index seekable we reached
        // the table-scan fallback and silently ignored the forced index. Instead
        // scan the forced index as a FULL ordered index scan in its STORED order
        // — a forward Rewind/Next walk, which yields ascending values for an ASC
        // index and descending for a DESC index, matching C SQLite. Covering when
        // every output column is in the index; otherwise the shared emitter reads
        // the rowid and looks the row up in the table. `descending: false` keeps
        // the forward (stored-order) traversal for both ASC and DESC indexes.
        let plan = OrderByIndexPlan {
            index: forced_idx.clone(),
            descending: false,
            equality_prefix_len: 0,
            covering_output: resolve_covering_output_sources(
                columns,
                table,
                table_alias,
                forced_idx,
            ),
        };
        codegen_select_index_ordered_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            columns,
            where_clause.as_deref(),
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            &plan,
        )
    } else {
        // --- Full table scan ---
        codegen_select_full_scan(
            b,
            cursor,
            table,
            table_alias,
            time_travel,
            schema,
            columns,
            where_clause.as_deref(),
            stmt.limit.as_ref(),
            out_regs,
            out_col_count,
            done_label,
            end_label,
            // reverse_unordered_selects: reverse only when the row order is not
            // fixed by an ORDER BY (GH #236).
            ctx.reverse_unordered_selects && stmt.order_by.is_empty(),
        )
    }
}

#[allow(clippy::too_many_arguments)]
fn codegen_select_rowid_lookup(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    time_travel: Option<&TimeTravelClause>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    limit_clause: Option<&LimitClause>,
    target_expr: &Expr,
    where_clause: Option<&Expr>,
    // When true, the full `where_clause` is applied as a residual filter after `SeekRowid` — for
    // `rowid = <const> AND <residual>`. The single lookup visits only the target row; the residual
    // decides whether to emit it. The table is always open here, so the residual reads any column.
    // `false` for the exact-`rowid = const` callers → byte-identical. bd-nonagg-rowid-eq-residual.
    residual_filter: bool,
) -> Result<(), CodegenError> {
    // Captured before `emit_expr(target_expr)`, which may consume an anon placeholder (`rowid = ?`).
    // The residual re-applies the whole WHERE, so it must re-number from this base (else the `id = ?`
    // conjunct would double-consume). Unused when `residual_filter` is false.
    let where_placeholder_base = b.current_anon_placeholder();
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    let rowid_reg = b.alloc_reg();
    emit_expr(b, target_expr, rowid_reg, None);
    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    emit_set_snapshot(b, cursor, time_travel);
    // Coerce a non-integer-literal rowid key (placeholder / real / text) to INTEGER affinity before the
    // seek: a non-exact key (2.5 / 'abc' / NULL) rejects to `done_label` (empty result) instead of raw
    // `SeekRowid` TRUNCATING it to a wrong rowid (e.g. `WHERE id = 2.5` must not match rowid 2). Emitted
    // after `OpenRead` so `done_label`'s Close sees an open cursor, mirroring `SeekRowid`'s own miss jump.
    // An integer literal is already exact -> no MustBeInt (byte-identical to the pre-existing callers).
    // Same coercion the count_star / aggregate rowid-eq paths use (bd-count/agg-rowid-eq-coerced).
    if !matches!(target_expr, Expr::Literal(Literal::Integer(_), _)) {
        b.emit_jump_to_label(Opcode::MustBeInt, rowid_reg, 0, done_label, P4::None, 0);
    }
    b.emit_jump_to_label(
        Opcode::SeekRowid,
        cursor,
        rowid_reg,
        done_label,
        P4::None,
        0,
    );
    // bd-nonagg-rowid-eq-residual: narrow the single seeked row with the full WHERE. A residual miss
    // jumps to `done_label` (Close + Halt) — there is only ever one row on this path.
    if residual_filter && let Some(where_expr) = where_clause {
        b.set_next_anon_placeholder(where_placeholder_base);
        emit_where_filter(
            b,
            where_expr,
            cursor,
            table,
            table_alias,
            schema,
            done_label,
        );
    }
    let skip_label = b.emit_label();
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_label, P4::None, 0);
    }
    emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }
    b.resolve_label(skip_label);
    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn codegen_select_index_equality_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    limit_clause: Option<&LimitClause>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    target_expr: &Expr,
    // When true, the FAST duplicate-run path also applies the full `where_clause` as a per-row residual
    // filter (the fast path otherwise emits every eq-block row unfiltered, correct only when the WHERE is
    // exactly the eq prefix). Callers whose WHERE is just `col = lit` pass `false` — their codegen is then
    // byte-identical. Only the bd-nonagg-eq-residual caller, whose WHERE is `col = lit AND <residual>`,
    // passes `true`. bd-nonagg-eq-residual.
    residual_filter: bool,
    // When true, walk the eq value's rows in DESCENDING rowid order — seek to `(val, i64::MAX)` with
    // `SeekLE` and step with `Prev` (and the affinity full-scan fallback uses `Last`+`Prev`) — to serve
    // `ORDER BY <rowid> DESC`. The single-column ASC path's key-equality (`Ne`) check is
    // direction-agnostic, so the value block is detected the same way. `false` is byte-identical to the
    // ascending emission. Gated by the caller to a single-column ASC index. bd-nonagg-index-eq-order-rowid.
    descending: bool,
) -> Result<(), CodegenError> {
    let idx_cursor = 1_i32;
    let full_scan_fallback = b.emit_label();
    let duplicate_run_done = b.emit_label();
    let where_placeholder_base = b.current_anon_placeholder();
    // WITHOUT ROWID index entries carry a PK suffix instead of a trailing
    // rowid (bd-rjaff): covering resolution is rowid-table shaped, so route
    // WITHOUT ROWID through the table-lookup path below.
    let wr_pk_indices = if table.without_rowid {
        Some(without_rowid_pk_indices(table)?)
    } else {
        None
    };
    let covering_output = if wr_pk_indices.is_some() || residual_filter {
        None
    } else {
        resolve_covering_output_sources(columns, table, table_alias, idx_schema)
    };
    let needs_table_lookup = covering_output.is_none();
    let fast_path_done_label = if needs_table_lookup {
        done_label
    } else {
        b.emit_label()
    };

    // Exact seek (single-column ASC INTEGER-affinity index probed by an integer literal): the index's
    // storage-class order matches the WHERE comparison's, so a 0-match seek is authoritative and the
    // full-scan fallback (an affinity safety net) is unnecessary — an absent key then produces the empty
    // result directly, making `WHERE col=<absent> LIMIT 1` / EXISTS O(log n) not O(n). Non-exact indexes
    // keep the fallback. bd-eq-seek-fallback-zero-match.
    let exact_seek = idx_schema.key_term_count() == 1
        && !idx_schema.key_term_descending(0)
        && matches!(target_expr, Expr::Literal(Literal::Integer(_), _))
        && idx_schema
            .columns
            .first()
            .and_then(|name| table.column_index(name))
            .and_then(|i| table.columns.get(i))
            .is_some_and(|c| c.affinity == 'D');
    let seek_miss_label = if exact_seek {
        fast_path_done_label
    } else {
        full_scan_fallback
    };

    let (limit_reg, offset_reg) =
        emit_limit_offset_registers(b, limit_clause, fast_path_done_label);

    // A composite index must be positioned with a true one-field prefix
    // record. Padding unconstrained trailing terms with NULL is not a block
    // floor when any such term is DESC: SeekGE would start in the trailing-NULL
    // region and silently skip preceding non-NULL entries. Single-key indexes
    // retain the exact `(key, rowid-floor)` record needed for rowid-order walks.
    let composite_prefix_probe = idx_schema.key_term_count() > 1;
    let probe_field_count = if composite_prefix_probe { 1 } else { 2 };
    let probe_key_regs = b.alloc_regs(probe_field_count);
    emit_expr(b, target_expr, probe_key_regs, None);
    b.emit_jump_to_label(
        Opcode::IsNull,
        probe_key_regs,
        0,
        fast_path_done_label,
        P4::None,
        0,
    );

    let saw_index_match_reg = b.alloc_reg();
    b.emit_op(Opcode::Integer, 0, saw_index_match_reg, 0, P4::None, 0);

    if !composite_prefix_probe {
        let rowid_floor_reg = probe_key_regs + 1;
        // Ascending seeks to `(val, i64::MIN)` (lowest rowid of the value)
        // then walks up; descending seeks to `(val, i64::MAX)` (highest
        // rowid) then walks down with `Prev`.
        b.emit_op(
            Opcode::Int64,
            0,
            rowid_floor_reg,
            0,
            P4::Int64(if descending { i64::MAX } else { i64::MIN }),
            0,
        );
    }
    let probe_record_reg = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        probe_key_regs,
        probe_field_count,
        probe_record_reg,
        P4::None,
        0,
    );

    if needs_table_lookup {
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
    }
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );
    b.emit_jump_to_label(
        if descending {
            Opcode::SeekLE
        } else {
            Opcode::SeekGE
        },
        idx_cursor,
        probe_record_reg,
        seek_miss_label,
        P4::None,
        0,
    );

    let idx_loop_top = b.current_addr();
    if idx_schema.key_term_count() == 1 && !idx_schema.key_term_descending(0) {
        let idx_key_reg = b.alloc_reg();
        b.emit_op(Opcode::Column, idx_cursor, 0, idx_key_reg, P4::None, 0);
        b.emit_jump_to_label(
            Opcode::Ne,
            probe_key_regs,
            idx_key_reg,
            duplicate_run_done,
            direct_lookup_index_comparison_p4(idx_schema),
            0x10,
        );
    } else {
        b.emit_jump_to_label(
            Opcode::IdxGT,
            idx_cursor,
            probe_record_reg,
            duplicate_run_done,
            P4::None,
            1,
        );
    }

    let idx_skip_label = b.emit_label();
    b.emit_op(Opcode::Integer, 1, saw_index_match_reg, 0, P4::None, 0);
    let covering_rowid_reg = if let Some(pk_indices) = wr_pk_indices.as_ref() {
        // WITHOUT ROWID: read the PK suffix stored after the index key terms
        // and position the table b-tree on it (prefix probe; fall-through
        // leaves the cursor on the matching row).
        emit_without_rowid_index_to_table_seek(
            b,
            table,
            cursor,
            idx_cursor,
            idx_schema,
            pk_indices,
            idx_skip_label,
        );
        None
    } else {
        let rowid_reg = b.alloc_reg();
        b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
        if needs_table_lookup {
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                cursor,
                rowid_reg,
                idx_skip_label,
                P4::None,
                0,
            );
        }
        Some(rowid_reg)
    };
    // bd-nonagg-eq-residual: apply the full WHERE as a per-row residual filter on the fast seek path
    // when the caller has a residual beyond the eq prefix. The seek already pins `col = lit` (so that
    // conjunct is redundant here) and the row is positioned (table cursor for the non-covering caller
    // this flag is gated to), so the residual (e.g. `c = 7`) narrows the eq block to the exact matches.
    // The placeholder base is reset exactly as the fallback below does, so a `?` in the residual numbers
    // identically on both runtime paths.
    if residual_filter && let Some(where_expr) = where_clause {
        b.set_next_anon_placeholder(where_placeholder_base);
        emit_where_filter(
            b,
            where_expr,
            cursor,
            table,
            table_alias,
            schema,
            idx_skip_label,
        );
    }
    // OFFSET applies to rows that satisfy WHERE, and projection expressions must
    // not run for filtered-out candidates. Keep both after the residual filter.
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, idx_skip_label, P4::None, 0);
    }
    if let Some(covering_output) = covering_output.as_ref() {
        let rowid_reg = covering_rowid_reg.ok_or_else(|| {
            CodegenError::Unsupported(
                "covering output requires a rowid-table index cursor".to_owned(),
            )
        })?;
        emit_covering_output_reads(b, idx_cursor, rowid_reg, covering_output, out_regs);
    } else {
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(
            Opcode::DecrJumpZero,
            lim_r,
            0,
            fast_path_done_label,
            P4::None,
            0,
        );
    }

    b.resolve_label(idx_skip_label);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let idx_loop_body = idx_loop_top as i32;
    b.emit_op(
        if descending {
            Opcode::Prev
        } else {
            Opcode::Next
        },
        idx_cursor,
        idx_loop_body,
        0,
        P4::None,
        0,
    );
    b.emit_jump_to_label(Opcode::Goto, 0, 0, fast_path_done_label, P4::None, 0);

    b.resolve_label(duplicate_run_done);
    b.emit_jump_to_label(
        Opcode::If,
        saw_index_match_reg,
        0,
        fast_path_done_label,
        P4::None,
        0,
    );
    // Exact seek: 0 matches is authoritative → the empty result, not the O(n) fallback scan.
    b.emit_jump_to_label(Opcode::Goto, 0, 0, seek_miss_label, P4::None, 0);

    b.resolve_label(full_scan_fallback);
    if !needs_table_lookup {
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
    }
    let loop_start = b.current_addr();
    // Affinity safety-net scan: mirror the seek's direction so `ORDER BY <rowid> DESC` stays descending
    // even on this fallback path (it is only reached for non-exact seeks; exact integer seeks resolve a
    // 0-match authoritatively without it).
    b.emit_jump_to_label(
        if descending {
            Opcode::Last
        } else {
            Opcode::Rewind
        },
        cursor,
        0,
        done_label,
        P4::None,
        0,
    );
    let skip_label = b.emit_label();
    if let Some(where_expr) = where_clause {
        b.set_next_anon_placeholder(where_placeholder_base);
        emit_where_filter(
            b,
            where_expr,
            cursor,
            table,
            table_alias,
            schema,
            skip_label,
        );
    }
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_label, P4::None, 0);
    }
    emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }
    b.resolve_label(skip_label);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = (loop_start + 1) as i32;
    b.emit_op(
        if descending {
            Opcode::Prev
        } else {
            Opcode::Next
        },
        cursor,
        loop_body,
        0,
        P4::None,
        0,
    );

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    if !needs_table_lookup {
        b.resolve_label(fast_path_done_label);
        b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    }
    b.resolve_label(end_label);
    Ok(())
}

/// Codegen for `SELECT <cols> FROM t WHERE <int col> IN (<int literals>)`.
///
/// bd-2dgf5. Seeks the index once per distinct value (ascending, matching C SQLite's
/// value-then-rowid output order), does the table lookup, and emits `ResultRow`. Non-covering
/// (always looks the row up). No scan fallback: the INTEGER-affinity + integer-literal +
/// de-duplicated gate in [`index_integer_in_list_target`] makes each probe exact and the runs
/// disjoint. The caller gates out ORDER BY / LIMIT / DISTINCT / WITHOUT ROWID.
#[allow(clippy::too_many_arguments)]
fn codegen_select_index_in_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    values: &[i64],
    where_clause: Option<&Expr>,
    // When true, the full `where_clause` is applied as a per-row residual filter after positioning on
    // each IN-list run — for `col IN (ints) AND <residual>`. The seek visits a SUPERSET (the IN runs)
    // and the residual narrows to the exact matches; the table is always open here (SeekRowid below), so
    // the residual can read any column. `false` for the exact-IN caller → byte-identical. Placeholder
    // numbering is reset before each run's filter so a `?` in the residual numbers the same on every
    // run. bd-nonagg-in-list-residual.
    residual_filter: bool,
) -> Result<(), CodegenError> {
    let idx_cursor = 1_i32;
    // Captured before any placeholder-emitting op (IN values are integer literals) so each residual
    // filter can reset to it and number a `?` in the residual identically across runs.
    let where_placeholder_base = b.current_anon_placeholder();
    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );

    for &value in values {
        let probe_key_regs = b.alloc_regs(2);
        b.emit_op(Opcode::Int64, 0, probe_key_regs, 0, P4::Int64(value), 0);
        b.emit_op(
            Opcode::Int64,
            0,
            probe_key_regs + 1,
            0,
            P4::Int64(i64::MIN),
            0,
        );
        let probe_record_reg = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            probe_key_regs,
            2,
            probe_record_reg,
            P4::None,
            0,
        );
        let next_value = b.emit_label();
        b.emit_jump_to_label(
            Opcode::SeekGE,
            idx_cursor,
            probe_record_reg,
            next_value,
            P4::None,
            0,
        );

        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let run_top = b.current_addr() as i32;
        let idx_key_reg = b.alloc_reg();
        b.emit_op(Opcode::Column, idx_cursor, 0, idx_key_reg, P4::None, 0);
        b.emit_jump_to_label(
            Opcode::Ne,
            probe_key_regs,
            idx_key_reg,
            next_value,
            direct_lookup_index_comparison_p4(idx_schema),
            0x10,
        );

        let skip_row = b.emit_label();
        let rowid_reg = b.alloc_reg();
        b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::SeekRowid, cursor, rowid_reg, skip_row, P4::None, 0);
        // bd-nonagg-in-list-residual: narrow the IN run to the exact matches with the full WHERE.
        if residual_filter && let Some(where_expr) = where_clause {
            b.set_next_anon_placeholder(where_placeholder_base);
            emit_where_filter(b, where_expr, cursor, table, table_alias, schema, skip_row);
        }
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
        b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
        b.resolve_label(skip_row);
        b.emit_op(Opcode::Next, idx_cursor, run_top, 0, P4::None, 0);
        b.resolve_label(next_value);
    }

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Codegen for `SELECT <cols> FROM t WHERE <indexed col> IN (SELECT ...)`
/// (uncorrelated) — bd-g5ys1.
///
/// Build phase: scan the subquery source once and materialize its non-NULL
/// values into a deduplicated ephemeral index (`Found`-guarded `IdxInsert`;
/// `IN` never matches NULL, and without the dedup guard a duplicate value in
/// the subquery would emit each matching outer row twice). Drive phase: for
/// each distinct value, `SeekGE` the outer index with a `(key, i64::MIN)`
/// probe and walk the equal-key run, doing the table lookup and emitting
/// `ResultRow` per matching row — the same value-then-rowid output order and
/// run-walk contract as [`codegen_select_index_in_scan`], and the same
/// build/drive shape as [`codegen_select_count_star_indexed_in_scan`]'s
/// materialized arm with the count step replaced by row output. Non-covering
/// (always looks the row up). The caller gates out ORDER BY / LIMIT /
/// DISTINCT / GROUP BY / HAVING / WITHOUT ROWID; the extractor gates out
/// `NOT IN`, correlated subqueries, index hints that exclude the index, and
/// collation mismatches.
#[allow(clippy::too_many_arguments)]
fn codegen_select_index_in_subquery_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    probe_source: &InProbeSource<'_>,
) -> Result<(), CodegenError> {
    let idx_cursor = cursor + 1;
    let probe_cursor = cursor + 2;
    let source_cursor = cursor + 3;
    let key_collation = idx_schema
        .key_term_collation(0)
        .filter(|name| !name.eq_ignore_ascii_case("BINARY"))
        .map_or(P4::None, |name| P4::Collation(name.to_owned()));

    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );
    b.emit_op(
        Opcode::OpenAutoindex,
        probe_cursor,
        1,
        0,
        key_collation.clone(),
        0,
    );
    b.emit_op(
        Opcode::OpenRead,
        source_cursor,
        probe_source.table.root_page,
        0,
        P4::Table(probe_source.table.name.clone()),
        0,
    );

    let r_value = b.alloc_temp();
    let r_key = b.alloc_temp();
    let build_done = b.emit_label();
    let build_start = b.current_addr();
    b.emit_jump_to_label(Opcode::Rewind, source_cursor, 0, build_done, P4::None, 0);
    let skip_source_row = probe_source.where_clause.map(|_| b.emit_label());
    if let (Some(where_expr), Some(skip_label)) = (probe_source.where_clause, skip_source_row) {
        emit_where_filter(
            b,
            where_expr,
            source_cursor,
            probe_source.table,
            probe_source.table_alias,
            schema,
            skip_label,
        );
    }
    let probe_scan = ScanCtx {
        cursor: source_cursor,
        table: probe_source.table,
        table_alias: probe_source.table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    emit_in_probe_value(b, source_cursor, probe_source, r_value, &probe_scan);
    let skip_insert = b.emit_label();
    let next_source = b.emit_label();
    b.emit_jump_to_label(Opcode::IsNull, r_value, 0, next_source, P4::None, 0);
    b.emit_op(Opcode::MakeRecord, r_value, 1, r_key, P4::None, 0);
    b.emit_jump_to_label(Opcode::Found, probe_cursor, r_key, skip_insert, P4::None, 0);
    b.emit_op(Opcode::IdxInsert, probe_cursor, r_key, 0, P4::None, 0);
    b.resolve_label(skip_insert);
    b.resolve_label(next_source);
    if let Some(skip_label) = skip_source_row {
        b.resolve_label(skip_label);
    }
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let build_loop_body = (build_start + 1) as i32;
    b.emit_op(Opcode::Next, source_cursor, build_loop_body, 0, P4::None, 0);
    b.resolve_label(build_done);
    b.emit_op(Opcode::Close, source_cursor, 0, 0, P4::None, 0);
    b.free_temp(r_key);
    b.free_temp(r_value);

    // `MakeRecord r_probe_value, 2` reads two consecutive registers, so
    // `r_min_rowid` must be allocated immediately after `r_probe_value`.
    let r_probe_value = b.alloc_reg();
    let r_min_rowid = b.alloc_reg();
    let r_probe_record = b.alloc_reg();
    let r_current_key = b.alloc_reg();
    let rowid_reg = b.alloc_reg();
    b.emit_jump_to_label(Opcode::Rewind, probe_cursor, 0, done_label, P4::None, 0);
    let probe_loop_top = b.current_addr();
    b.emit_op(Opcode::Column, probe_cursor, 0, r_probe_value, P4::None, 0);
    b.emit_op(Opcode::Int64, 0, r_min_rowid, 0, P4::Int64(i64::MIN), 0);
    b.emit_op(
        Opcode::MakeRecord,
        r_probe_value,
        2,
        r_probe_record,
        P4::None,
        0,
    );
    let next_probe = b.emit_label();
    b.emit_jump_to_label(
        Opcode::SeekGE,
        idx_cursor,
        r_probe_record,
        next_probe,
        P4::None,
        0,
    );

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let run_top = b.current_addr() as i32;
    b.emit_op(Opcode::Column, idx_cursor, 0, r_current_key, P4::None, 0);
    b.emit_jump_to_label(
        Opcode::Ne,
        r_probe_value,
        r_current_key,
        next_probe,
        key_collation,
        0,
    );
    let skip_output = b.emit_label();
    b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
    b.emit_jump_to_label(
        Opcode::SeekRowid,
        cursor,
        rowid_reg,
        skip_output,
        P4::None,
        0,
    );
    emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    b.resolve_label(skip_output);
    b.emit_op(Opcode::Next, idx_cursor, run_top, 0, P4::None, 0);
    b.resolve_label(next_probe);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let probe_loop_body = probe_loop_top as i32;
    b.emit_op(Opcode::Next, probe_cursor, probe_loop_body, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, probe_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Codegen for `SELECT <cols> FROM t WHERE <rowid> IN (<int literals>)`.
///
/// bd-2dgf5. Rowid is unique, so each distinct value is a single `SeekRowid` — no index
/// cursor, no duplicate-run loop. Values are ascending (matching C SQLite's IN order), and a
/// `SeekRowid` miss skips to the next value. Integer-literal gate makes each seek exact. The
/// caller gates out LIMIT / DISTINCT / WITHOUT ROWID. bd-nonagg-rowid-in-order: `ORDER BY <rowid>`
/// is served by this seek (ascending is the natural order; `descending` reverses the emit order).
#[allow(clippy::too_many_arguments)]
fn codegen_select_rowid_in_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    values: &[i64],
    where_clause: Option<&Expr>,
    // When true, the full `where_clause` is applied as a per-row residual filter after `SeekRowid` — for
    // `rowid IN (ints) AND <residual>`. The rowid lookups visit only the listed rows; the residual
    // narrows them. The table is always open here, so the residual reads any column. `false` for the
    // exact-`rowid IN` caller → byte-identical. Placeholder base reset per lookup so a `?` in the
    // residual numbers identically. bd-nonagg-rowid-in-residual.
    residual_filter: bool,
    // When true, emit the seeks in DESCENDING rowid order (for `ORDER BY <rowid> DESC`); `values` are
    // ascending, so we reverse. `false` emits ascending — the natural order and byte-identical to the
    // no-ORDER-BY callers. bd-nonagg-rowid-in-order.
    descending: bool,
) -> Result<(), CodegenError> {
    // Captured before any placeholder-emitting op (rowid values are integer literals).
    let where_placeholder_base = b.current_anon_placeholder();
    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    // `values` are ascending; reverse for `ORDER BY <rowid> DESC`. Ascending path clones in-order, so it
    // stays byte-identical to the pre-order callers.
    let mut ordered = values.to_vec();
    if descending {
        ordered.reverse();
    }
    for &value in &ordered {
        let rowid_reg = b.alloc_reg();
        b.emit_op(Opcode::Int64, 0, rowid_reg, 0, P4::Int64(value), 0);
        let next_value = b.emit_label();
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            cursor,
            rowid_reg,
            next_value,
            P4::None,
            0,
        );
        // bd-nonagg-rowid-in-residual: narrow the listed rows with the full WHERE.
        if residual_filter && let Some(where_expr) = where_clause {
            b.set_next_anon_placeholder(where_placeholder_base);
            emit_where_filter(
                b,
                where_expr,
                cursor,
                table,
                table_alias,
                schema,
                next_value,
            );
        }
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
        b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
        b.resolve_label(next_value);
    }
    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Codegen for a full table scan SELECT with optional WHERE filtering and LIMIT/OFFSET.
#[allow(clippy::too_many_arguments)]
fn codegen_select_full_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    time_travel: Option<&TimeTravelClause>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    limit_clause: Option<&LimitClause>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    // When true, walk the table b-tree in DESCENDING rowid order (`Last` + `Prev`) instead of ascending
    // (`Rewind` + `Next`) — used to serve `ORDER BY <rowid> DESC` without a sorter. Everything else
    // (WHERE filter, LIMIT/OFFSET, placeholder numbering) is identical, so `false` is byte-identical to
    // the pre-flag behavior. bd-nonagg-rowid-order-scan-desc.
    descending: bool,
) -> Result<(), CodegenError> {
    // Allocate LIMIT/OFFSET counter registers (if present).
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    emit_set_snapshot(b, cursor, time_travel);

    // Position at the first row in scan order (`Rewind` = ascending rowid, `Last` = descending); jump to
    // done if the table is empty.
    let loop_start = b.current_addr();
    b.emit_jump_to_label(
        if descending {
            Opcode::Last
        } else {
            Opcode::Rewind
        },
        cursor,
        0,
        done_label,
        P4::None,
        0,
    );

    // Evaluate WHERE condition (if any) and skip non-matching rows.
    let skip_label = b.emit_label();
    if let Some(where_expr) = where_clause {
        emit_where_filter(
            b,
            where_expr,
            cursor,
            table,
            table_alias,
            schema,
            skip_label,
        );
    }

    // OFFSET: if offset counter > 0, decrement by 1 and skip this row.
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_label, P4::None, 0);
    }

    // Read columns.
    emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;

    // ResultRow.
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    // LIMIT: decrement limit counter; jump to done when zero.
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }

    // Skip label for WHERE-filtered rows.
    b.resolve_label(skip_label);

    // Advance to the next row in scan order (`Next` ascending, `Prev` descending); jump back to the
    // start of the loop body (the instruction after Rewind/Last).
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = (loop_start + 1) as i32;
    b.emit_op(
        if descending {
            Opcode::Prev
        } else {
            Opcode::Next
        },
        cursor,
        loop_body,
        0,
        P4::None,
        0,
    );

    // Done: Close + Halt.
    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End target for Init jump.
    b.resolve_label(end_label);

    Ok(())
}

#[derive(Clone, Copy)]
struct RowidRangeBound<'a> {
    rowid_expr: &'a Expr,
    expr: &'a Expr,
    inclusive: bool,
}

#[derive(Clone, Copy, Default)]
struct RowidRangeTarget<'a> {
    lower: Option<RowidRangeBound<'a>>,
    upper: Option<RowidRangeBound<'a>>,
}

#[derive(Clone)]
enum ColumnRangeExpr<'a> {
    Borrowed(&'a Expr),
    Owned(Box<Expr>),
}

#[derive(Clone)]
struct ColumnRangeBound<'a> {
    expr: ColumnRangeExpr<'a>,
    inclusive: bool,
}

impl ColumnRangeBound<'_> {
    fn expr(&self) -> &Expr {
        match &self.expr {
            ColumnRangeExpr::Borrowed(expr) => expr,
            ColumnRangeExpr::Owned(expr) => expr,
        }
    }
}

#[derive(Clone, Default)]
struct ColumnRangeTarget<'a> {
    lower: Option<ColumnRangeBound<'a>>,
    upper: Option<ColumnRangeBound<'a>>,
}

fn planner_index_range_target_from_column_range(
    range: &ColumnRangeTarget<'_>,
) -> PlannerIndexRangeTarget {
    PlannerIndexRangeTarget {
        lower: range.lower.as_ref().map(|bound| PlannerIndexRangeBound {
            expr: bound.expr().clone(),
            inclusive: bound.inclusive,
        }),
        upper: range.upper.as_ref().map(|bound| PlannerIndexRangeBound {
            expr: bound.expr().clone(),
            inclusive: bound.inclusive,
        }),
    }
}

/// Generate VDBE bytecode for a bounded rowid/IPK scan.
///
/// This specializes the common `rowid >= low AND rowid < high` shape into a
/// SeekGE/SeekGT + Next loop so range scans do not fall back to a full table
/// scan. The optimization is intentionally conservative: it only fires when
/// the entire WHERE clause is a pure conjunction of rowid bounds.
#[allow(clippy::too_many_arguments)]
fn codegen_select_rowid_range_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    time_travel: Option<&TimeTravelClause>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    limit_clause: Option<&LimitClause>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    rowid_range: RowidRangeTarget<'_>,
    descending: bool,
    where_clause: Option<&Expr>,
    // When true, the full `where_clause` is applied as a per-row residual filter inside the walk — for
    // `rowid <range> AND <residual>`. The walk visits the `[lower, upper]` slice (a superset of the
    // matches) in rowid order; the residual narrows it. Byte-identical to the full scan (same rows, same
    // order, fewer visited). `false` for the plain-range callers → byte-identical. The residual hoist
    // requires integer-literal bounds and no LIMIT, so nothing before the filter emits a placeholder.
    // bd-nonagg-rowid-range-residual.
    residual_filter: bool,
) -> Result<(), CodegenError> {
    // Captured before any placeholder-emitting op so the re-applied WHERE re-numbers a residual `?` from
    // this base. Unused when `residual_filter` is false.
    let where_placeholder_base = b.current_anon_placeholder();
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    let lower_reg = rowid_range.lower.map(|bound| {
        let reg = b.alloc_reg();
        emit_expr(b, bound.expr, reg, None);
        b.emit_jump_to_label(Opcode::IsNull, reg, 0, done_label, P4::None, 0);
        reg
    });
    let upper_reg = rowid_range.upper.map(|bound| {
        let reg = b.alloc_reg();
        emit_expr(b, bound.expr, reg, None);
        b.emit_jump_to_label(Opcode::IsNull, reg, 0, done_label, P4::None, 0);
        reg
    });
    let lower_comparison = rowid_range
        .lower
        .map(|bound| resolved_rowid_range_comparison(table, table_alias, schema, bound));
    let upper_comparison = rowid_range
        .upper
        .map(|bound| resolved_rowid_range_comparison(table, table_alias, schema, bound));

    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    emit_set_snapshot(b, cursor, time_travel);

    if descending {
        if let Some(bound) = rowid_range.upper {
            let seek_opcode = if bound.inclusive {
                Opcode::SeekLE
            } else {
                Opcode::SeekLT
            };
            b.emit_jump_to_label(
                seek_opcode,
                cursor,
                upper_reg.expect("upper bound register should exist"),
                done_label,
                P4::None,
                0,
            );
        } else {
            b.emit_jump_to_label(Opcode::Last, cursor, 0, done_label, P4::None, 0);
        }
    } else if let Some(bound) = rowid_range.lower {
        let seek_opcode = if bound.inclusive {
            Opcode::SeekGE
        } else {
            Opcode::SeekGT
        };
        b.emit_jump_to_label(
            seek_opcode,
            cursor,
            lower_reg.expect("lower bound register should exist"),
            done_label,
            P4::None,
            0,
        );
    } else {
        b.emit_jump_to_label(Opcode::Rewind, cursor, 0, done_label, P4::None, 0);
    }

    let loop_top = b.current_addr();
    let skip_label = b.emit_label();

    if descending {
        if let Some(bound) = rowid_range.lower {
            let current_rowid_reg = b.alloc_reg();
            let stop_opcode = if bound.inclusive {
                Opcode::Lt
            } else {
                Opcode::Le
            };
            b.emit_op(Opcode::Rowid, cursor, current_rowid_reg, 0, P4::None, 0);
            b.emit_jump_to_label(
                stop_opcode,
                lower_reg.expect("lower bound register should exist"),
                current_rowid_reg,
                done_label,
                lower_comparison
                    .as_ref()
                    .map_or(P4::None, |comparison| comparison.collation_p4.clone()),
                lower_comparison
                    .as_ref()
                    .map_or(0, |comparison| comparison.cmp_p5),
            );
        }
    } else if let Some(bound) = rowid_range.upper {
        let current_rowid_reg = b.alloc_reg();
        let stop_opcode = if bound.inclusive {
            Opcode::Gt
        } else {
            Opcode::Ge
        };
        b.emit_op(Opcode::Rowid, cursor, current_rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(
            stop_opcode,
            upper_reg.expect("upper bound register should exist"),
            current_rowid_reg,
            done_label,
            upper_comparison
                .as_ref()
                .map_or(P4::None, |comparison| comparison.collation_p4.clone()),
            upper_comparison
                .as_ref()
                .map_or(0, |comparison| comparison.cmp_p5),
        );
    }

    // bd-nonagg-rowid-range-residual: narrow the [lower, upper] slice with the full WHERE. A residual
    // miss jumps to `skip_label` (the Next), so the walk continues to the next row. Applied before the
    // OFFSET count so OFFSET skips only matching rows (the residual hoist gates on no-LIMIT, so
    // offset_reg is None here anyway).
    if residual_filter && let Some(where_expr) = where_clause {
        b.set_next_anon_placeholder(where_placeholder_base);
        emit_where_filter(
            b,
            where_expr,
            cursor,
            table,
            table_alias,
            schema,
            skip_label,
        );
    }

    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_label, P4::None, 0);
    }

    emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }

    b.resolve_label(skip_label);

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = loop_top as i32;
    b.emit_op(
        if descending {
            Opcode::Prev
        } else {
            Opcode::Next
        },
        cursor,
        loop_body,
        0,
        P4::None,
        0,
    );

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);

    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn codegen_select_index_range_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    limit_clause: Option<&LimitClause>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    index_range: PlannerIndexRangeTarget,
) -> Result<(), CodegenError> {
    let idx_cursor = cursor + 1;
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    // bd-u6tbr / bd-xiojw follow-up: coerce a runtime-typed bound (a placeholder) to the indexed
    // column's affinity so the seek positions identically to the full-scan filter, which applies
    // the comparison affinity. A literal already in the column's affinity class is left
    // byte-identical (no Affinity op) — the coercion only matters for placeholders. Numeric
    // ('C'/'D'/'E') and BINARY-text ('B') columns coerce; an untyped column needs none, and an
    // expression index has no plain key column so `column_index` misses and no coercion is emitted
    // (behaviour preserved). For a 'B' column the gate only accepts the seek when the collation is
    // BINARY (`P4::None`), so the coerced probe and the seek's BINARY comparison agree.
    let bound_affinity = idx_schema
        .columns
        .first()
        .and_then(|name| table.column_index(name))
        .map(|idx| table.columns[idx].affinity)
        .filter(|&aff| matches!(aff, 'C' | 'D' | 'E' | 'B'));
    let lower_probe = index_range.lower.as_ref().map(|bound| {
        let base = b.alloc_regs(2);
        emit_expr(b, &bound.expr, base, None);
        if let Some(aff) = bound_affinity
            && !bound_matches_affinity(aff, &bound.expr)
        {
            b.emit_op(
                Opcode::Affinity,
                base,
                1,
                0,
                P4::Affinity(aff.to_string()),
                0,
            );
        }
        b.emit_jump_to_label(Opcode::IsNull, base, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::Int64, 0, base + 1, 0, P4::Int64(i64::MIN), 0);
        (base, bound.clone())
    });
    let upper_reg = index_range.upper.as_ref().map(|bound| {
        let reg = b.alloc_reg();
        emit_expr(b, &bound.expr, reg, None);
        if let Some(aff) = bound_affinity
            && !bound_matches_affinity(aff, &bound.expr)
        {
            b.emit_op(
                Opcode::Affinity,
                reg,
                1,
                0,
                P4::Affinity(aff.to_string()),
                0,
            );
        }
        b.emit_jump_to_label(Opcode::IsNull, reg, 0, done_label, P4::None, 0);
        reg
    });
    let current_key_reg = (upper_reg.is_some()
        || lower_probe
            .as_ref()
            .is_some_and(|(_, bound)| !bound.inclusive))
    .then(|| b.alloc_reg());
    // WITHOUT ROWID index entries carry a PK suffix instead of a trailing
    // rowid (bd-rjaff): covering resolution is rowid-table shaped, so route
    // WITHOUT ROWID through the table-lookup path below.
    let wr_pk_indices = if table.without_rowid {
        Some(without_rowid_pk_indices(table)?)
    } else {
        None
    };
    let covering_output = if wr_pk_indices.is_some() {
        None
    } else {
        resolve_covering_output_sources(columns, table, table_alias, idx_schema)
    };
    let needs_table_lookup = covering_output.is_none();

    if needs_table_lookup {
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
    }
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );

    if let Some((lower_reg, _)) = lower_probe.as_ref() {
        let probe_record_reg = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            *lower_reg,
            2,
            probe_record_reg,
            P4::None,
            0,
        );
        b.emit_jump_to_label(
            Opcode::SeekGE,
            idx_cursor,
            probe_record_reg,
            done_label,
            P4::None,
            0,
        );
    } else {
        b.emit_jump_to_label(Opcode::Rewind, idx_cursor, 0, done_label, P4::None, 0);
    }

    let loop_top = b.current_addr();
    let skip_label = b.emit_label();

    if let Some(key_reg) = current_key_reg {
        b.emit_op(Opcode::Column, idx_cursor, 0, key_reg, P4::None, 0);
        if lower_probe.is_none() {
            b.emit_jump_to_label(Opcode::IsNull, key_reg, 0, skip_label, P4::None, 0);
        }
    }

    if let Some((lower_reg, bound)) = lower_probe.as_ref()
        && !bound.inclusive
    {
        b.emit_jump_to_label(
            Opcode::Le,
            *lower_reg,
            current_key_reg.expect("exclusive lower bound should read current key"),
            skip_label,
            P4::None,
            0,
        );
    }

    if let Some(bound) = index_range.upper.as_ref() {
        let stop_opcode = if bound.inclusive {
            Opcode::Gt
        } else {
            Opcode::Ge
        };
        b.emit_jump_to_label(
            stop_opcode,
            upper_reg.expect("upper bound register should exist"),
            current_key_reg.expect("upper bound should read current key"),
            done_label,
            P4::None,
            0,
        );
    }

    if let Some(pk_indices) = wr_pk_indices.as_ref() {
        // WITHOUT ROWID: read the PK suffix stored after the index key terms
        // and position the table b-tree on it (prefix probe; fall-through
        // leaves the cursor on the matching row).
        emit_without_rowid_index_to_table_seek(
            b, table, cursor, idx_cursor, idx_schema, pk_indices, skip_label,
        );
        if let Some(off_r) = offset_reg {
            b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_label, P4::None, 0);
        }
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    } else {
        let rowid_reg = b.alloc_reg();
        b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);

        if needs_table_lookup {
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                cursor,
                rowid_reg,
                skip_label,
                P4::None,
                0,
            );
        }

        if let Some(off_r) = offset_reg {
            b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_label, P4::None, 0);
        }

        if let Some(covering_output) = &covering_output {
            emit_covering_output_reads(b, idx_cursor, rowid_reg, covering_output, out_regs);
        } else {
            emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
        }
    }

    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }

    b.resolve_label(skip_label);

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = loop_top as i32;
    b.emit_op(Opcode::Next, idx_cursor, loop_body, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    if needs_table_lookup {
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);

    Ok(())
}

/// Reverse (DESC) single-column index-range seek: `WHERE col <range> ORDER BY col DESC, id DESC`.
/// The mirror of [`codegen_select_index_range_scan`] — it positions at the HIGH end of the range
/// (`SeekLE(upper)` with a MAX rowid sentinel, or `Last` when there is no upper bound), walks down
/// with `Prev`, and stops at the LOWER bound (or at the NULL region at the index bottom when there
/// is no lower bound). Emits rows in `(col DESC, rowid DESC)` order — exactly what the reverse index
/// walk produces for `ORDER BY col DESC, id DESC`, so it is bit-identical without a sorter. Rowid
/// tables only (WITHOUT ROWID declined at detection).
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_select_index_range_scan_desc(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    limit_clause: Option<&LimitClause>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    range: &ColumnRangeTarget<'_>,
) -> Result<(), CodegenError> {
    let idx_cursor = cursor + 1;
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    let bound_affinity = idx_schema
        .columns
        .first()
        .and_then(|name| table.column_index(name))
        .map(|idx| table.columns[idx].affinity)
        .filter(|&aff| matches!(aff, 'C' | 'D' | 'E' | 'B'));

    // Upper bound anchors the seek (position at the high end); rowid sentinel MAX so `SeekLE`
    // lands on the LAST entry with `col == upper`.
    let upper_probe = range.upper.as_ref().map(|bound| {
        let base = b.alloc_regs(2);
        emit_expr(b, bound.expr(), base, None);
        if let Some(aff) = bound_affinity
            && !bound_matches_affinity(aff, bound.expr())
        {
            b.emit_op(
                Opcode::Affinity,
                base,
                1,
                0,
                P4::Affinity(aff.to_string()),
                0,
            );
        }
        b.emit_jump_to_label(Opcode::IsNull, base, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::Int64, 0, base + 1, 0, P4::Int64(i64::MAX), 0);
        (base, bound.inclusive)
    });
    // Lower bound is the stop (walking down).
    let lower_reg = range.lower.as_ref().map(|bound| {
        let reg = b.alloc_reg();
        emit_expr(b, bound.expr(), reg, None);
        if let Some(aff) = bound_affinity
            && !bound_matches_affinity(aff, bound.expr())
        {
            b.emit_op(
                Opcode::Affinity,
                reg,
                1,
                0,
                P4::Affinity(aff.to_string()),
                0,
            );
        }
        b.emit_jump_to_label(Opcode::IsNull, reg, 0, done_label, P4::None, 0);
        (reg, bound.inclusive)
    });
    let current_key_reg = b.alloc_reg();

    let covering_output = if table.without_rowid {
        None
    } else {
        resolve_covering_output_sources(columns, table, table_alias, idx_schema)
    };
    let needs_table_lookup = covering_output.is_none();
    if needs_table_lookup {
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
    }
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );

    if let Some((upper_base, _)) = upper_probe.as_ref() {
        let probe_record_reg = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            *upper_base,
            2,
            probe_record_reg,
            P4::None,
            0,
        );
        b.emit_jump_to_label(
            Opcode::SeekLE,
            idx_cursor,
            probe_record_reg,
            done_label,
            P4::None,
            0,
        );
    } else {
        b.emit_jump_to_label(Opcode::Last, idx_cursor, 0, done_label, P4::None, 0);
    }

    let loop_top = b.current_addr();
    let skip_label = b.emit_label();

    b.emit_op(Opcode::Column, idx_cursor, 0, current_key_reg, P4::None, 0);
    // NULLs sit at the bottom of the index and never satisfy a range predicate, but the reverse walk
    // descends into them — a lower-bound stop like `current < lower` yields NULL (not true) on a NULL
    // key, so it would NOT fire. Stop unconditionally once a NULL key is reached; every entry below
    // it is also NULL.
    b.emit_jump_to_label(Opcode::IsNull, current_key_reg, 0, done_label, P4::None, 0);
    // Lower stop (walking down): `current < lower` (inclusive `>=`) or `current <= lower`
    // (exclusive `>`) ends the scan.
    if let Some((lreg, inclusive)) = lower_reg {
        let stop = if inclusive { Opcode::Lt } else { Opcode::Le };
        b.emit_jump_to_label(stop, lreg, current_key_reg, done_label, P4::None, 0);
    }
    // Exclusive upper: `SeekLE` may land on `col == upper`; skip those (only at the very top).
    if let Some((upper_base, inclusive)) = upper_probe.as_ref()
        && !*inclusive
    {
        b.emit_jump_to_label(
            Opcode::Ge,
            *upper_base,
            current_key_reg,
            skip_label,
            P4::None,
            0,
        );
    }

    let rowid_reg = b.alloc_reg();
    b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
    if needs_table_lookup {
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            cursor,
            rowid_reg,
            skip_label,
            P4::None,
            0,
        );
    }
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_label, P4::None, 0);
    }
    if let Some(cov) = &covering_output {
        emit_covering_output_reads(b, idx_cursor, rowid_reg, cov, out_regs);
    } else {
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }

    b.resolve_label(skip_label);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = loop_top as i32;
    b.emit_op(Opcode::Prev, idx_cursor, loop_body, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    if needs_table_lookup {
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Composite-index equality-prefix + trailing-range seek (`WHERE a = 5 AND b > 10` on
/// `index(a, b)`). Mirrors [`codegen_select_index_range_scan`] but builds a multi-column probe
/// (prefix values + range lower) and bounds the walk to the matching prefix with `IdxGT`
/// (`P5` = prefix length), reading and range-checking the trailing key column at index position
/// `prefix_len`. Placeholder/text bounds are coerced to each key column's affinity like the
/// single-column path. Rowid tables only (WITHOUT ROWID is declined at detection).
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_select_composite_index_prefix_range_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    limit_clause: Option<&LimitClause>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    prefix_exprs: &[&Expr],
    range: &ColumnRangeTarget<'_>,
) -> Result<(), CodegenError> {
    let idx_cursor = cursor + 1;
    let prefix_len = prefix_exprs.len();
    let key_terms = idx_schema.key_term_count();
    let range_pos = prefix_len;

    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    // Coercing affinity ('C'/'D'/'E'/'B') of each key column, or None (untyped -> no coercion).
    let key_affinities: Vec<Option<char>> = (0..key_terms)
        .map(|pos| {
            idx_schema
                .columns
                .get(pos)
                .and_then(|name| table.column_index(name))
                .map(|i| table.columns[i].affinity)
                .filter(|&a| matches!(a, 'C' | 'D' | 'E' | 'B'))
        })
        .collect();

    // Probe record: [prefix..., range-lower-or-NULL, trailing NULLs, rowid = MIN].
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let probe = b.alloc_regs(key_terms as i32 + 1);
    for (pos, expr) in prefix_exprs.iter().enumerate() {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let reg = probe + pos as i32;
        emit_expr(b, expr, reg, None);
        if let Some(aff) = key_affinities[pos]
            && !bound_matches_affinity(aff, expr)
        {
            b.emit_op(
                Opcode::Affinity,
                reg,
                1,
                0,
                P4::Affinity(aff.to_string()),
                0,
            );
        }
        b.emit_jump_to_label(Opcode::IsNull, reg, 0, done_label, P4::None, 0);
    }
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let range_reg = probe + range_pos as i32;
    let lower_inclusive = if let Some(lower) = range.lower.as_ref() {
        emit_expr(b, lower.expr(), range_reg, None);
        if let Some(aff) = key_affinities[range_pos]
            && !bound_matches_affinity(aff, lower.expr())
        {
            b.emit_op(
                Opcode::Affinity,
                range_reg,
                1,
                0,
                P4::Affinity(aff.to_string()),
                0,
            );
        }
        b.emit_jump_to_label(Opcode::IsNull, range_reg, 0, done_label, P4::None, 0);
        Some(lower.inclusive)
    } else {
        b.emit_op(Opcode::Null, 0, range_reg, 0, P4::None, 0);
        None
    };
    for pos in (range_pos + 1)..key_terms {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let reg = probe + pos as i32;
        b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
    }
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let rowid_sentinel = probe + key_terms as i32;
    b.emit_op(Opcode::Int64, 0, rowid_sentinel, 0, P4::Int64(i64::MIN), 0);
    let probe_rec = b.alloc_reg();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::MakeRecord,
        probe,
        key_terms as i32 + 1,
        probe_rec,
        P4::None,
        0,
    );

    let upper = range.upper.as_ref().map(|u| {
        let reg = b.alloc_reg();
        emit_expr(b, u.expr(), reg, None);
        if let Some(aff) = key_affinities[range_pos]
            && !bound_matches_affinity(aff, u.expr())
        {
            b.emit_op(
                Opcode::Affinity,
                reg,
                1,
                0,
                P4::Affinity(aff.to_string()),
                0,
            );
        }
        b.emit_jump_to_label(Opcode::IsNull, reg, 0, done_label, P4::None, 0);
        (reg, u.inclusive)
    });

    let covering_output = resolve_covering_output_sources(columns, table, table_alias, idx_schema);
    let needs_table_lookup = covering_output.is_none();
    if needs_table_lookup {
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
    }
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );
    b.emit_jump_to_label(
        Opcode::SeekGE,
        idx_cursor,
        probe_rec,
        done_label,
        P4::None,
        0,
    );

    let loop_top = b.current_addr();
    let skip_label = b.emit_label();

    // Stop once the equality prefix changes (`IdxGT` compares only the first `prefix_len` columns).
    // With an EMPTY prefix (pure leading-term range, bd-bn45n) there is nothing to compare, so skip
    // the IdxGT entirely and let the range bounds alone terminate the walk: the SeekGE anchors the
    // lower end and the range-upper check below (`Gt`/`Ge` on `range_key_reg`) stops it — a
    // zero-column IdxGT would be a degenerate no-op we do not want to rely on.
    if prefix_len > 0 {
        #[allow(clippy::cast_possible_truncation)]
        b.emit_jump_to_label(
            Opcode::IdxGT,
            idx_cursor,
            probe_rec,
            done_label,
            P4::None,
            prefix_len as u16,
        );
    }

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let range_key_reg = b.alloc_reg();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::Column,
        idx_cursor,
        range_pos as i32,
        range_key_reg,
        P4::None,
        0,
    );
    if range.lower.is_none() {
        b.emit_jump_to_label(Opcode::IsNull, range_key_reg, 0, skip_label, P4::None, 0);
    }
    if lower_inclusive == Some(false) {
        b.emit_jump_to_label(
            Opcode::Le,
            range_reg,
            range_key_reg,
            skip_label,
            P4::None,
            0,
        );
    }
    if let Some((up_reg, up_inclusive)) = upper {
        let stop = if up_inclusive { Opcode::Gt } else { Opcode::Ge };
        b.emit_jump_to_label(stop, up_reg, range_key_reg, done_label, P4::None, 0);
    }

    let rowid_reg = b.alloc_reg();
    b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
    if needs_table_lookup {
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            cursor,
            rowid_reg,
            skip_label,
            P4::None,
            0,
        );
    }
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_label, P4::None, 0);
    }
    if let Some(cov) = &covering_output {
        emit_covering_output_reads(b, idx_cursor, rowid_reg, cov, out_regs);
    } else {
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }

    b.resolve_label(skip_label);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = loop_top as i32;
    b.emit_op(Opcode::Next, idx_cursor, loop_body, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    if needs_table_lookup {
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Composite-index equality-prefix + trailing-range seek in DESCENDING order
/// (`WHERE a = 5 AND b <range> ORDER BY b DESC, id DESC` on `index(a, b)`). The reverse mirror of
/// [`codegen_select_composite_index_prefix_range_scan`], and the composite analogue of
/// [`codegen_select_index_range_scan_desc`].
///
/// It anchors at the HIGH end of the `a == 5` block and walks down with `Prev`:
/// * inclusive upper (`b <= up`): `SeekLE [prefix.., up]` — the last entry with `(prefix.., b) <=
///   (prefix.., up)`;
/// * exclusive upper (`b < up`): `SeekLT [prefix.., up]` — the last entry `< (prefix.., up)`;
/// * no upper bound: `SeekLE [prefix..]` (a partial key) — the last entry in the `prefix` block.
///
/// A single `IdxLE`/`IdxLT` on `[prefix.., lower]` (`P5 = prefix_len + 1`) at the loop top ends the
/// walk: it fires when the equality prefix drops below `prefix` (left the block downward), when the
/// trailing key crosses the lower bound (`IdxLE` for exclusive `>`, `IdxLT` for inclusive `>=`), or
/// when a NULL trailing key is reached (NULLs sit at the block bottom and never satisfy a range).
/// When there is no lower bound the probe holds NULL in the trailing slot and `IdxLE` stops exactly
/// at the NULL region / prefix change. Streams `(range_col DESC, rowid DESC)` with no sorter; the
/// range column is guaranteed to be the last key term by `composite_order_by_satisfied_desc`.
/// Rowid tables only (WITHOUT ROWID is declined at detection).
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_select_composite_index_prefix_range_scan_desc(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    limit_clause: Option<&LimitClause>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    prefix_exprs: &[&Expr],
    range: &ColumnRangeTarget<'_>,
) -> Result<(), CodegenError> {
    let idx_cursor = cursor + 1;
    let prefix_len = prefix_exprs.len();
    let key_terms = idx_schema.key_term_count();
    let range_pos = prefix_len;

    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    // Coercing affinity ('C'/'D'/'E'/'B') of each key column, or None (untyped -> no coercion).
    let key_affinities: Vec<Option<char>> = (0..key_terms)
        .map(|pos| {
            idx_schema
                .columns
                .get(pos)
                .and_then(|name| table.column_index(name))
                .map(|i| table.columns[i].affinity)
                .filter(|&a| matches!(a, 'C' | 'D' | 'E' | 'B'))
        })
        .collect();

    // Emit the equality-prefix values into `reg` (coercing affinity), jumping to `done` on NULL
    // (an `= NULL` prefix matches nothing). Emitted once for the anchor and once for the stop probe.
    let emit_prefix = |b: &mut ProgramBuilder, base: i32| {
        for (pos, expr) in prefix_exprs.iter().enumerate() {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let reg = base + pos as i32;
            emit_expr(b, expr, reg, None);
            if let Some(aff) = key_affinities[pos]
                && !bound_matches_affinity(aff, expr)
            {
                b.emit_op(
                    Opcode::Affinity,
                    reg,
                    1,
                    0,
                    P4::Affinity(aff.to_string()),
                    0,
                );
            }
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, done_label, P4::None, 0);
        }
    };

    // Anchor probe: [prefix.., upper] when there is an upper bound, else [prefix..] (partial key).
    let has_upper = range.upper.is_some();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let anchor_fields = prefix_len as i32 + i32::from(has_upper);
    let anchor_base = b.alloc_regs(anchor_fields);
    emit_prefix(b, anchor_base);
    let anchor_seek_op = if let Some(upper) = range.upper.as_ref() {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let reg = anchor_base + range_pos as i32;
        emit_expr(b, upper.expr(), reg, None);
        if let Some(aff) = key_affinities[range_pos]
            && !bound_matches_affinity(aff, upper.expr())
        {
            b.emit_op(
                Opcode::Affinity,
                reg,
                1,
                0,
                P4::Affinity(aff.to_string()),
                0,
            );
        }
        b.emit_jump_to_label(Opcode::IsNull, reg, 0, done_label, P4::None, 0);
        // Inclusive upper: last entry <= (prefix.., up). Exclusive: last entry < (prefix.., up).
        if upper.inclusive {
            Opcode::SeekLE
        } else {
            Opcode::SeekLT
        }
    } else {
        // No upper bound: the partial key [prefix..] positions at the last entry of the block.
        Opcode::SeekLE
    };
    let anchor_rec = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        anchor_base,
        anchor_fields,
        anchor_rec,
        P4::None,
        0,
    );

    // Stop probe: [prefix.., lower-or-NULL] (prefix_len + 1 == key_terms fields).
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let stop_base = b.alloc_regs(key_terms as i32);
    emit_prefix(b, stop_base);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let stop_range_reg = stop_base + range_pos as i32;
    let lower_inclusive = if let Some(lower) = range.lower.as_ref() {
        emit_expr(b, lower.expr(), stop_range_reg, None);
        if let Some(aff) = key_affinities[range_pos]
            && !bound_matches_affinity(aff, lower.expr())
        {
            b.emit_op(
                Opcode::Affinity,
                stop_range_reg,
                1,
                0,
                P4::Affinity(aff.to_string()),
                0,
            );
        }
        b.emit_jump_to_label(Opcode::IsNull, stop_range_reg, 0, done_label, P4::None, 0);
        Some(lower.inclusive)
    } else {
        b.emit_op(Opcode::Null, 0, stop_range_reg, 0, P4::None, 0);
        None
    };
    let stop_rec = b.alloc_reg();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::MakeRecord,
        stop_base,
        key_terms as i32,
        stop_rec,
        P4::None,
        0,
    );
    // Inclusive lower (`b >= lo`): stop when idx_key < [prefix.., lo] (IdxLT). Exclusive (`b > lo`)
    // or no lower bound (NULL trailing slot): stop when idx_key <= [prefix.., lo/NULL] (IdxLE) —
    // which for a real trailing key only fires below `lo`, and for the NULL slot only fires at the
    // NULL region / prefix change.
    let stop_op = if lower_inclusive == Some(true) {
        Opcode::IdxLT
    } else {
        Opcode::IdxLE
    };

    let covering_output = resolve_covering_output_sources(columns, table, table_alias, idx_schema);
    let needs_table_lookup = covering_output.is_none();
    if needs_table_lookup {
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
    }
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );
    b.emit_jump_to_label(
        anchor_seek_op,
        idx_cursor,
        anchor_rec,
        done_label,
        P4::None,
        0,
    );

    let loop_top = b.current_addr();
    let skip_label = b.emit_label();

    // Prefix change / lower bound / NULL trailing key: one op ends the reverse walk.
    #[allow(clippy::cast_possible_truncation)]
    b.emit_jump_to_label(
        stop_op,
        idx_cursor,
        stop_rec,
        done_label,
        P4::None,
        (prefix_len + 1) as u16,
    );

    let rowid_reg = b.alloc_reg();
    b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
    if needs_table_lookup {
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            cursor,
            rowid_reg,
            skip_label,
            P4::None,
            0,
        );
    }
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_label, P4::None, 0);
    }
    if let Some(cov) = &covering_output {
        emit_covering_output_reads(b, idx_cursor, rowid_reg, cov, out_regs);
    } else {
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }

    b.resolve_label(skip_label);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = loop_top as i32;
    b.emit_op(Opcode::Prev, idx_cursor, loop_body, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    if needs_table_lookup {
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Whether `expr` is a compile-time numeric literal — an integer/real literal, with
/// an optional leading unary minus. NUMERIC affinity is the identity on these, which
/// is what lets [`index_range_bound_is_seek_safe`] accept them under NUMERIC
/// comparison affinity without changing which rows match.
fn is_numeric_literal_bound(expr: &Expr) -> bool {
    match expr {
        Expr::Literal(Literal::Integer(_) | Literal::Float(_), _) => true,
        Expr::UnaryOp {
            op: fsqlite_ast::UnaryOp::Negate,
            expr,
            ..
        } => matches!(
            expr.as_ref(),
            Expr::Literal(Literal::Integer(_) | Literal::Float(_), _)
        ),
        _ => false,
    }
}

/// Whether `expr` is a bind parameter (`?`, `?N`, `:name`, `@name`, `$name`). A placeholder's
/// runtime value is unknown at compile time, so the range seek coerces it to the indexed
/// column's affinity at execution ([`codegen_select_index_range_scan`]) rather than relying on
/// a compile-time-numeric bound.
fn is_placeholder_bound(expr: &Expr) -> bool {
    matches!(
        expr,
        Expr::Placeholder(
            fsqlite_ast::PlaceholderType::Numbered(_)
                | fsqlite_ast::PlaceholderType::ColonNamed(_)
                | fsqlite_ast::PlaceholderType::AtNamed(_)
                | fsqlite_ast::PlaceholderType::DollarNamed(_),
            _
        )
    )
}

/// Whether `expr` is a text string literal. A text literal compared against a BINARY-collated
/// text column needs no coercion — it is already text, and the seek's default `P4::None`
/// comparison is BINARY (the index's own order) — so the range seek is exact.
fn is_text_literal_bound(expr: &Expr) -> bool {
    matches!(expr, Expr::Literal(Literal::String(_), _))
}

/// Whether `expr` is a literal already in the seek column's affinity class, so the seek's
/// runtime `Affinity` coercion would be a no-op and can be skipped (keeping the bytecode
/// byte-identical for literals). Numeric-affinity columns match a numeric literal; a TEXT column
/// matches a text literal. A placeholder is never a match — its runtime type is unknown, so it is
/// always coerced.
fn bound_matches_affinity(affinity: char, expr: &Expr) -> bool {
    match affinity {
        'C' | 'D' | 'E' => is_numeric_literal_bound(expr),
        'B' => is_text_literal_bound(expr),
        _ => false,
    }
}

/// Whether the index-range seek can position on `bound_expr` without changing which
/// rows match relative to the equivalent full-scan filter.
///
/// The seek compares the raw bound value against the index's (already affinity-applied)
/// key entries, so it is exact only when the comparison affinity the full-scan filter
/// WOULD apply is a no-op on this bound. Two cases qualify. First, no comparison affinity
/// (`cmp_p5 & !0x80 == 0`) — e.g. an untyped/BLOB column, or two operands already in the
/// same affinity class — is always safe. Second, NUMERIC affinity (`'C'`) against a numeric
/// literal (integer/real, incl. a negated literal): coercing an already-numeric value with
/// NUMERIC affinity is the identity, so the seek visits exactly the filter's rows. That
/// second case is the common `WHERE <int/real col> BETWEEN 5 AND 55` shape that the plain
/// `cmp_p5 == 0` gate silently rejected into a full scan (see
/// `resolved_index_range_comparison_carries_affinity_for_integer_column`); it is the same
/// proven-safe subset the IN-list seek accepts by the integer argument.
///
/// A placeholder under NUMERIC affinity is also accepted: `codegen_select_index_range_scan`
/// emits an `Affinity` opcode that coerces the runtime bound to the indexed column's affinity
/// before seeking, so the positioned rows match the filter for every bound type (a numeric bind
/// is exact; a non-numeric text/blob bind coerces to a value that seeks empty, exactly as the
/// filter's numeric comparison excludes it). A TEXT/blob *literal* under NUMERIC affinity still
/// declines (kept narrow; those are rare and the correct scan is cheap enough).
///
/// A text literal OR a placeholder on a BINARY-collated text column (TEXT comparison affinity,
/// with the collation gated to None/BINARY above) is accepted. A text literal is already text and
/// text-vs-text under `P4::None` is the index's own BINARY order (no coercion); a placeholder is
/// coerced to TEXT by the seek's Affinity op, so any bind type positions to match the filter (a
/// numeric/text bind becomes its text form; a blob stays a blob and seeks past the text keys,
/// empty, exactly as the filter excludes it). Non-BINARY collations (NOCASE/RTRIM) and a
/// numeric/blob *literal* on a text column still decline.
fn index_range_bound_is_seek_safe(
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    column_name: &str,
    bound_expr: &Expr,
) -> bool {
    let comparison =
        resolved_index_range_comparison(table, table_alias, schema, column_name, bound_expr);
    if !matches!(comparison.collation_p4, P4::None) {
        return false;
    }
    // `cmp_p5 & !0x80` is the comparison affinity (`combine_comparison_affinity`): `0` = no
    // coercion (always seek-safe), `b'C'` = NUMERIC, `b'B'` = TEXT. Under NUMERIC a numeric
    // literal is already numeric (identity) and a placeholder is coerced to the column affinity
    // by the seek's Affinity op. Under TEXT (a text column, collation gated to BINARY above) a
    // text literal is already text and the seek's `P4::None` compare IS BINARY, so it is exact;
    // a non-text-literal under TEXT (numeric literal, placeholder) would need a TEXT coercion and
    // is declined.
    let affinity = comparison.cmp_p5 & !0x80;
    if affinity == 0 {
        true
    } else if affinity == u16::from(b'C') {
        is_numeric_literal_bound(bound_expr) || is_placeholder_bound(bound_expr)
    } else if affinity == u16::from(b'B') {
        is_text_literal_bound(bound_expr) || is_placeholder_bound(bound_expr)
    } else {
        false
    }
}

fn index_range_fast_path_is_safe(
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    column_name: &str,
    range: &ColumnRangeTarget<'_>,
) -> bool {
    [range.lower.as_ref(), range.upper.as_ref()]
        .into_iter()
        .flatten()
        .all(|bound| {
            index_range_bound_is_seek_safe(table, table_alias, schema, column_name, bound.expr())
        })
}

fn rowid_range_fast_path_is_safe(range: RowidRangeTarget<'_>) -> bool {
    [range.lower, range.upper]
        .into_iter()
        .flatten()
        .all(|bound| rowid_range_bound_is_seek_safe(bound.expr))
}

fn rowid_range_bound_is_seek_safe(expr: &Expr) -> bool {
    match expr {
        Expr::Literal(Literal::Integer(_), _)
        | Expr::Placeholder(
            fsqlite_ast::PlaceholderType::Numbered(_)
            | fsqlite_ast::PlaceholderType::ColonNamed(_)
            | fsqlite_ast::PlaceholderType::AtNamed(_)
            | fsqlite_ast::PlaceholderType::DollarNamed(_),
            _,
        ) => true,
        Expr::UnaryOp {
            op: fsqlite_ast::UnaryOp::Negate,
            expr,
            ..
        } => matches!(expr.as_ref(), Expr::Literal(Literal::Integer(_), _)),
        _ => false,
    }
}

fn is_simple_count_star(columns: &[ResultColumn]) -> bool {
    matches!(
        columns,
        [ResultColumn::Expr {
            expr:
                Expr::FunctionCall {
                    name,
                    args: FunctionArgs::Star,
                    distinct: false,
                    order_by,
                    filter: None,
                    over: None,
                    ..
                },
            ..
        }] if name.eq_ignore_ascii_case("count")
            && order_by.is_empty()
            && builtin_aggregate_semantics_available(name, 0)
    )
}

struct CountStarPlusSumPlan {
    count_out_idx: usize,
    sum_out_idx: usize,
    sum_col_idx: Option<usize>,
    sum_is_rowid: bool,
}

struct GroupByRowidBucketSumPlan {
    group_divisor: i64,
    group_out_idx: usize,
    sum_out_idx: usize,
    sum_col_idx: usize,
}

fn rowid_bucket_divisor(
    expr: &Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<i64> {
    let Expr::BinaryOp {
        left,
        op: BinaryOp::Divide,
        right,
        ..
    } = expr
    else {
        return None;
    };

    if !matches!(
        resolve_column_ref(left, table, table_alias),
        Some(SortKeySource::Rowid)
    ) {
        return None;
    }

    match right.as_ref() {
        Expr::Literal(Literal::Integer(divisor), _) if *divisor > 0 => Some(*divisor),
        _ => None,
    }
}

fn simple_group_by_rowid_bucket_sum_plan(
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
    group_by: &[Expr],
) -> Option<GroupByRowidBucketSumPlan> {
    if columns.len() != 2 || group_by.len() != 1 || !builtin_aggregate_semantics_available("sum", 1)
    {
        return None;
    }

    let group_expr = &group_by[0];
    let group_divisor = rowid_bucket_divisor(group_expr, table, table_alias)?;
    let mut group_out_idx = None;
    let mut sum_out_idx = None;
    let mut sum_col_idx = None;

    for (out_idx, column) in columns.iter().enumerate() {
        match column {
            ResultColumn::Expr { expr, .. } if expr == group_expr => {
                if group_out_idx.replace(out_idx).is_some() {
                    return None;
                }
            }
            ResultColumn::Expr {
                expr:
                    Expr::FunctionCall {
                        name,
                        args,
                        distinct: false,
                        order_by,
                        filter: None,
                        over: None,
                        ..
                    },
                ..
            } if name.eq_ignore_ascii_case("sum") && order_by.is_empty() => {
                let FunctionArgs::List(exprs) = args else {
                    return None;
                };
                let [arg_expr] = exprs.as_slice() else {
                    return None;
                };
                let Some(SortKeySource::Column(idx)) =
                    resolve_column_ref(arg_expr, table, table_alias)
                else {
                    return None;
                };
                if sum_out_idx.replace(out_idx).is_some() {
                    return None;
                }
                sum_col_idx = Some(idx);
            }
            _ => return None,
        }
    }
    Some(GroupByRowidBucketSumPlan {
        group_divisor,
        group_out_idx: group_out_idx?,
        sum_out_idx: sum_out_idx?,
        sum_col_idx: sum_col_idx?,
    })
}

fn simple_count_star_plus_sum_plan(
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<CountStarPlusSumPlan> {
    if columns.len() != 2
        || !builtin_aggregate_semantics_available("count", 0)
        || !builtin_aggregate_semantics_available("sum", 1)
    {
        return None;
    }

    let mut count_out_idx = None;
    let mut sum_out_idx = None;
    let mut sum_col_idx = None;
    let mut sum_is_rowid = false;

    for (out_idx, column) in columns.iter().enumerate() {
        let ResultColumn::Expr { expr, .. } = column else {
            return None;
        };
        let Expr::FunctionCall {
            name,
            args,
            distinct: false,
            order_by,
            filter: None,
            over: None,
            ..
        } = expr
        else {
            return None;
        };
        if !order_by.is_empty() {
            return None;
        }

        if name.eq_ignore_ascii_case("count") && matches!(args, FunctionArgs::Star) {
            if count_out_idx.replace(out_idx).is_some() {
                return None;
            }
            continue;
        }

        if name.eq_ignore_ascii_case("sum")
            && let FunctionArgs::List(exprs) = args
            && let [arg_expr] = exprs.as_slice()
        {
            match resolve_column_ref(arg_expr, table, table_alias) {
                Some(SortKeySource::Column(idx)) => {
                    if sum_out_idx.replace(out_idx).is_some() {
                        return None;
                    }
                    sum_col_idx = Some(idx);
                    sum_is_rowid = false;
                    continue;
                }
                Some(SortKeySource::Rowid) => {
                    if sum_out_idx.replace(out_idx).is_some() {
                        return None;
                    }
                    sum_col_idx = None;
                    sum_is_rowid = true;
                    continue;
                }
                Some(SortKeySource::Expression(_)) | None => return None,
            }
        }

        return None;
    }

    Some(CountStarPlusSumPlan {
        count_out_idx: count_out_idx?,
        sum_out_idx: sum_out_idx?,
        sum_col_idx,
        sum_is_rowid,
    })
}

#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_count_star(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    where_clause: Option<&Expr>,
    out_regs: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    rowid_range: Option<RowidRangeTarget<'_>>,
    index_hint: Option<&fsqlite_ast::IndexHint>,
) -> Result<(), CodegenError> {
    let scan_ctx = ScanCtx {
        cursor,
        table,
        table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    if let Some((idx_schema, probe_target)) =
        extract_count_indexed_exists_target(where_clause, table, table_alias, schema)
    {
        return codegen_select_count_star_indexed_in_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            out_regs,
            done_label,
            end_label,
            idx_schema,
            probe_target,
        );
    }
    if let Some((idx_schema, in_target)) = extract_count_indexed_in_target(
        where_clause,
        table,
        table_alias,
        schema,
        &scan_ctx,
        index_hint,
    ) {
        return codegen_select_count_star_indexed_in_scan(
            b,
            cursor,
            table,
            table_alias,
            schema,
            out_regs,
            done_label,
            end_label,
            idx_schema,
            in_target,
        );
    }
    // bd-count-rowid-in: `COUNT(*) WHERE <rowid> IN (<int literals>)` counts existing rows with one
    // SeekRowid per listed value instead of a full scan. Bare rowid IN only (`extract_rowid_in_list_target`
    // requires the whole WHERE be the IN); a residual falls through to the scan below. The rowid slice is
    // sorted+deduped, so each hit is counted at most once.
    if !table.without_rowid
        && let Some(values) = extract_rowid_in_list_target(where_clause, table, table_alias)
    {
        codegen_select_count_star_rowid_in(
            b,
            cursor,
            table,
            table_alias,
            schema,
            out_regs,
            done_label,
            end_label,
            &values,
            None,
            false,
        );
        return Ok(());
    }
    // bd-count-rowid-eq: `COUNT(*) WHERE <rowid> = <int literal>` counts the single row (0 or 1) with one
    // SeekRowid instead of a full scan — the rowid (IPK) has no secondary index, so this shape is NOT
    // diverted to the aggregate index-eq seek (bd-2dgf5) and would otherwise Rewind here. This first arm
    // handles integer literals directly and reuses the rowid-IN emitter with a one-element slice. Other
    // constant forms continue to the MustBeInt-coerced seek below so reals cannot be truncated and
    // placeholders receive affinity handling.
    if !table.without_rowid
        && let Some(target) = extract_rowid_target_expr(where_clause, Some(table), table_alias)
        && let Expr::Literal(Literal::Integer(value), _) = target
    {
        codegen_select_count_star_rowid_in(
            b,
            cursor,
            table,
            table_alias,
            schema,
            out_regs,
            done_label,
            end_label,
            &[*value],
            None,
            false,
        );
        return Ok(());
    }
    // bd-count-rowid-eq-coerced: `COUNT(*) WHERE <rowid> = <non-integer-literal constant>` (a placeholder,
    // real, or text constant) counts the single row via `MustBeInt` (INTEGER-affinity coerce: a non-exact
    // integer — 2.5, 'abc', NULL — rejects to count 0, exactly as SQLite; '5' / 5.0 coerce to 5) then one
    // SeekRowid, instead of a full scan. The integer-literal case is served above (no MustBeInt needed).
    if !table.without_rowid
        && let Some(target) = extract_rowid_target_expr(where_clause, Some(table), table_alias)
    {
        codegen_select_count_star_rowid_eq_coerced(
            b, cursor, table, out_regs, done_label, end_label, target,
        );
        return Ok(());
    }
    // bd-count-rowid-in-residual: `COUNT(*) WHERE <rowid> IN (<ints>) AND <residual>` — SeekRowid per value,
    // re-applying the full WHERE per hit. Reached only when no `simple_count_star` diverter matched (a
    // residual on an indexed column routes to the aggregate seek instead; the rowid IN itself has no index
    // so `index_integer_in_list_residual_target` never diverts it).
    if !table.without_rowid
        && let Some((values, true)) =
            extract_rowid_in_list_residual_target(where_clause, table, table_alias)
    {
        codegen_select_count_star_rowid_in(
            b,
            cursor,
            table,
            table_alias,
            schema,
            out_regs,
            done_label,
            end_label,
            &values,
            where_clause,
            true,
        );
        return Ok(());
    }
    // bd-count-rowid-eq-residual: `COUNT(*) WHERE <rowid> = <int> AND <residual>` — one SeekRowid + residual.
    // `extract_rowid_eq_residual_target` returns the const only when `rowid = const` is a conjunct alongside
    // others (declines the bare eq, handled above). Integer literal only.
    if !table.without_rowid
        && let Some(target) = extract_rowid_eq_residual_target(where_clause, table, table_alias)
        && let Expr::Literal(Literal::Integer(value), _) = target
    {
        codegen_select_count_star_rowid_in(
            b,
            cursor,
            table,
            table_alias,
            schema,
            out_regs,
            done_label,
            end_label,
            &[*value],
            where_clause,
            true,
        );
        return Ok(());
    }

    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);

    if where_clause.is_none() {
        // bd-wwqen.1: cheapest-index optimization for COUNT(*).
        // Open the smallest non-partial index instead of the table when
        // available — index B-trees have smaller rows and fewer pages.
        // Uses the SAME cursor ID as the table would, so the rest of the
        // program shape (Count, Close, Halt) is identical.
        let cheapest_index = table
            .indexes
            .iter()
            .filter(|idx| idx.where_clause.is_none())
            .filter(|idx| !idx.columns.is_empty())
            .min_by_key(|idx| idx.columns.len());

        if let Some(idx) = cheapest_index {
            b.emit_op(
                Opcode::OpenRead,
                cursor,
                idx.root_page,
                0,
                P4::Index(idx.name.clone()),
                0,
            );
        } else {
            b.emit_op(
                Opcode::OpenRead,
                cursor,
                table.root_page,
                0,
                P4::Table(table.name.clone()),
                0,
            );
        }

        b.emit_op(Opcode::Count, cursor, out_regs, 0, P4::None, 0);
        b.resolve_label(done_label);
        b.emit_op(Opcode::ResultRow, out_regs, 1, 0, P4::None, 0);
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);
        return Ok(());
    }

    // Non-COUNT path: open table cursor as before.
    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );

    b.emit_op(Opcode::Integer, 0, out_regs, 0, P4::None, 0);

    let upper_reg = rowid_range.and_then(|range| {
        range.upper.map(|bound| {
            let reg = b.alloc_reg();
            emit_expr(b, bound.expr, reg, None);
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, done_label, P4::None, 0);
            reg
        })
    });
    let upper_comparison = rowid_range.and_then(|range| {
        range
            .upper
            .map(|bound| resolved_rowid_range_comparison(table, table_alias, schema, bound))
    });

    if let Some(range) = rowid_range {
        if let Some(bound) = range.lower {
            let lower_reg = b.alloc_reg();
            emit_expr(b, bound.expr, lower_reg, None);
            b.emit_jump_to_label(Opcode::IsNull, lower_reg, 0, done_label, P4::None, 0);
            let seek_opcode = if bound.inclusive {
                Opcode::SeekGE
            } else {
                Opcode::SeekGT
            };
            b.emit_jump_to_label(seek_opcode, cursor, lower_reg, done_label, P4::None, 0);
        } else {
            b.emit_jump_to_label(Opcode::Rewind, cursor, 0, done_label, P4::None, 0);
        }
    } else {
        b.emit_jump_to_label(Opcode::Rewind, cursor, 0, done_label, P4::None, 0);
    }

    let loop_top = b.current_addr();
    let skip_label = b.emit_label();

    if let Some(range) = rowid_range
        && let Some(bound) = range.upper
    {
        let current_rowid_reg = b.alloc_reg();
        let stop_opcode = if bound.inclusive {
            Opcode::Gt
        } else {
            Opcode::Ge
        };
        b.emit_op(Opcode::Rowid, cursor, current_rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(
            stop_opcode,
            upper_reg.expect("upper bound register should exist"),
            current_rowid_reg,
            done_label,
            upper_comparison
                .as_ref()
                .map_or(P4::None, |comparison| comparison.collation_p4.clone()),
            upper_comparison
                .as_ref()
                .map_or(0, |comparison| comparison.cmp_p5),
        );
    }

    if let Some(where_expr) = where_clause {
        emit_where_filter(
            b,
            where_expr,
            cursor,
            table,
            table_alias,
            schema,
            skip_label,
        );
    }
    b.emit_op(Opcode::AddImm, out_regs, 1, 0, P4::None, 0);
    b.resolve_label(skip_label);

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = loop_top as i32;
    b.emit_op(Opcode::Next, cursor, loop_body, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::ResultRow, out_regs, 1, 0, P4::None, 0);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// `SELECT COUNT(*) FROM t WHERE <rowid> IN (<int literals>) [AND <residual>]` / `<rowid> = <int> [AND
/// <residual>]`: one `SeekRowid` per listed value, counting the hits, instead of a full scan. `values`
/// are sorted+deduped, so each existing row is counted once. When `residual_filter` is true, the full
/// `where_clause` is re-applied after each hit (a miss skips to the next value), so a rowid seek that
/// coexists with a predicate it cannot enforce still counts exactly; the residual's `?` placeholders
/// re-number to the same base each iteration. `false` (bare IN/eq) emits no filter → byte-identical.
/// bd-count-rowid-in / bd-count-rowid-eq (+ -residual).
#[allow(clippy::too_many_arguments)]
fn codegen_select_count_star_rowid_in(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    out_regs: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    values: &[i64],
    where_clause: Option<&Expr>,
    residual_filter: bool,
) {
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    b.emit_op(Opcode::Integer, 0, out_regs, 0, P4::None, 0);
    let rowid_reg = b.alloc_reg();
    // Residual `?` placeholders re-number to this base each iteration (the IN values are integer literals,
    // so nothing before the filter consumes a placeholder). Read even when there is no residual.
    let where_placeholder_base = b.current_anon_placeholder();
    for &value in values {
        let skip_label = b.emit_label();
        b.emit_op(Opcode::Int64, 0, rowid_reg, 0, P4::Int64(value), 0);
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            cursor,
            rowid_reg,
            skip_label,
            P4::None,
            0,
        );
        if residual_filter && let Some(where_expr) = where_clause {
            b.set_next_anon_placeholder(where_placeholder_base);
            emit_where_filter(
                b,
                where_expr,
                cursor,
                table,
                table_alias,
                schema,
                skip_label,
            );
        }
        b.emit_op(Opcode::AddImm, out_regs, 1, 0, P4::None, 0);
        b.resolve_label(skip_label);
    }
    b.resolve_label(done_label);
    b.emit_op(Opcode::ResultRow, out_regs, 1, 0, P4::None, 0);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
}

/// `SELECT COUNT(*) FROM t WHERE <rowid> = <non-integer-literal constant>` (placeholder / real / text):
/// `MustBeInt` coerces the bound value to INTEGER affinity — a non-exact integer (`2.5`, `'abc'`, NULL)
/// rejects to `skip` (count stays 0, exactly as SQLite), while `'5'` / `5.0` coerce to `5` — then one
/// `SeekRowid` counts the hit. bd-count-rowid-eq-coerced.
fn codegen_select_count_star_rowid_eq_coerced(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    out_regs: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    target_expr: &Expr,
) {
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    b.emit_op(Opcode::Integer, 0, out_regs, 0, P4::None, 0);
    let rowid_reg = b.alloc_reg();
    let skip = b.emit_label();
    emit_expr(b, target_expr, rowid_reg, None);
    b.emit_jump_to_label(Opcode::MustBeInt, rowid_reg, 0, skip, P4::None, 0);
    b.emit_jump_to_label(Opcode::SeekRowid, cursor, rowid_reg, skip, P4::None, 0);
    b.emit_op(Opcode::AddImm, out_regs, 1, 0, P4::None, 0);
    b.resolve_label(skip);
    b.resolve_label(done_label);
    b.emit_op(Opcode::ResultRow, out_regs, 1, 0, P4::None, 0);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
}

#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_count_star_plus_sum(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    plan: &CountStarPlusSumPlan,
    out_regs: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    let count_reg = out_regs + i32::try_from(plan.count_out_idx).unwrap_or_default();
    let sum_reg = out_regs + i32::try_from(plan.sum_out_idx).unwrap_or_default();

    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    b.emit_op(Opcode::Count, cursor, count_reg, 0, P4::None, 0);
    b.emit_op(Opcode::Null, 0, sum_reg, 0, P4::None, 0);

    let finalize_label = b.emit_label();
    let loop_start = b.current_addr();
    b.emit_jump_to_label(Opcode::Rewind, cursor, 0, finalize_label, P4::None, 0);

    let arg_reg = b.alloc_reg();
    if plan.sum_is_rowid {
        b.emit_op(Opcode::Rowid, cursor, arg_reg, 0, P4::None, 0);
    } else {
        b.emit_op(
            Opcode::Column,
            cursor,
            i32::try_from(plan.sum_col_idx.unwrap_or_default()).unwrap_or_default(),
            arg_reg,
            P4::None,
            0,
        );
    }
    b.emit_op(
        Opcode::AggStep,
        0,
        arg_reg,
        sum_reg,
        P4::FuncName("SUM".to_owned()),
        1,
    );

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = (loop_start + 1) as i32;
    b.emit_op(Opcode::Next, cursor, loop_body, 0, P4::None, 0);

    b.resolve_label(finalize_label);
    b.emit_op(
        Opcode::AggFinal,
        sum_reg,
        1,
        0,
        P4::FuncName("SUM".to_owned()),
        0,
    );
    b.resolve_label(done_label);
    b.emit_op(Opcode::ResultRow, out_regs, 2, 0, P4::None, 0);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_group_by_rowid_bucket_sum(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    plan: &GroupByRowidBucketSumPlan,
    out_regs: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    let group_reg = out_regs + i32::try_from(plan.group_out_idx).unwrap_or_default();
    let sum_out_reg = out_regs + i32::try_from(plan.sum_out_idx).unwrap_or_default();
    let divisor_reg = b.alloc_reg();
    let rowid_reg = b.alloc_reg();
    let cur_key_reg = b.alloc_reg();
    let prev_key_reg = b.alloc_reg();
    let sum_accum_reg = b.alloc_reg();
    let sum_arg_reg = b.alloc_reg();
    let have_group_reg = b.alloc_reg();

    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    b.emit_op(
        Opcode::Int64,
        0,
        divisor_reg,
        0,
        P4::Int64(plan.group_divisor),
        0,
    );
    b.emit_op(Opcode::Null, 0, prev_key_reg, 0, P4::None, 0);
    b.emit_op(Opcode::Null, 0, sum_accum_reg, 0, P4::None, 0);
    b.emit_op(Opcode::Integer, 0, have_group_reg, 0, P4::None, 0);

    let finalize_label = b.emit_label();
    let compare_keys_label = b.emit_label();
    let new_group_label = b.emit_label();
    let first_row_label = b.emit_label();
    let same_group_label = b.emit_label();
    let scan_start = b.current_addr();
    b.emit_jump_to_label(Opcode::Rewind, cursor, 0, finalize_label, P4::None, 0);
    b.emit_op(Opcode::Rowid, cursor, rowid_reg, 0, P4::None, 0);
    b.emit_op(
        Opcode::Divide,
        divisor_reg,
        rowid_reg,
        cur_key_reg,
        P4::None,
        0,
    );

    b.emit_jump_to_label(
        Opcode::IfPos,
        have_group_reg,
        0,
        compare_keys_label,
        P4::None,
        0,
    );
    b.emit_jump_to_label(Opcode::Goto, 0, 0, first_row_label, P4::None, 0);

    b.resolve_label(compare_keys_label);
    b.emit_jump_to_label(
        Opcode::Ne,
        cur_key_reg,
        prev_key_reg,
        new_group_label,
        P4::None,
        0x80,
    );
    b.emit_jump_to_label(Opcode::Goto, 0, 0, same_group_label, P4::None, 0);

    b.resolve_label(new_group_label);
    b.emit_op(
        Opcode::AggFinal,
        sum_accum_reg,
        1,
        0,
        P4::FuncName("SUM".to_owned()),
        0,
    );
    b.emit_op(Opcode::Copy, prev_key_reg, group_reg, 0, P4::None, 0);
    b.emit_op(Opcode::Copy, sum_accum_reg, sum_out_reg, 0, P4::None, 0);
    b.emit_op(Opcode::ResultRow, out_regs, 2, 0, P4::None, 0);
    b.emit_op(Opcode::Null, 0, sum_accum_reg, 0, P4::None, 0);

    b.resolve_label(first_row_label);
    b.emit_op(Opcode::Integer, 1, have_group_reg, 0, P4::None, 0);

    b.resolve_label(same_group_label);
    b.emit_op(Opcode::Copy, cur_key_reg, prev_key_reg, 0, P4::None, 0);
    b.emit_op(
        Opcode::Column,
        cursor,
        i32::try_from(plan.sum_col_idx).unwrap_or_default(),
        sum_arg_reg,
        P4::None,
        0,
    );
    b.emit_op(
        Opcode::AggStep,
        0,
        sum_arg_reg,
        sum_accum_reg,
        P4::FuncName("SUM".to_owned()),
        1,
    );

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let scan_body = (scan_start + 1) as i32;
    b.emit_op(Opcode::Next, cursor, scan_body, 0, P4::None, 0);

    let output_final_label = b.emit_label();
    b.resolve_label(finalize_label);
    b.emit_jump_to_label(
        Opcode::IfPos,
        have_group_reg,
        0,
        output_final_label,
        P4::None,
        0,
    );
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

    b.resolve_label(output_final_label);
    b.emit_op(
        Opcode::AggFinal,
        sum_accum_reg,
        1,
        0,
        P4::FuncName("SUM".to_owned()),
        0,
    );
    b.emit_op(Opcode::Copy, prev_key_reg, group_reg, 0, P4::None, 0);
    b.emit_op(Opcode::Copy, sum_accum_reg, sum_out_reg, 0, P4::None, 0);
    b.emit_op(Opcode::ResultRow, out_regs, 2, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_count_star_indexed_in_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    _table_alias: Option<&str>,
    schema: &[TableSchema],
    out_regs: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    in_target: CountIndexedInTarget<'_>,
) -> Result<(), CodegenError> {
    let idx_cursor = cursor + 1;
    let probe_cursor = cursor + 2;
    let source_cursor = cursor + 3;
    let count_key_collation = idx_schema
        .key_term_collation(0)
        .filter(|name| !name.eq_ignore_ascii_case("BINARY"))
        .map_or(P4::None, |name| P4::Collation(name.to_owned()));

    if let CountIndexedInTarget::ProbeSource(probe_source) = &in_target
        && count_probe_source_can_skip_materialization(probe_source)
    {
        let use_exists_semijoin_merge =
            count_exists_semijoin_merge_is_safe(table, idx_schema, probe_source);
        let source_rowid_range = extract_safe_probe_source_rowid_range(probe_source);

        b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
        b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
        b.emit_op(Opcode::Integer, 0, out_regs, 0, P4::None, 0);
        b.emit_op(
            Opcode::OpenRead,
            idx_cursor,
            idx_schema.root_page,
            0,
            P4::Index(idx_schema.name.clone()),
            0,
        );
        b.emit_op(
            Opcode::OpenRead,
            source_cursor,
            probe_source.table.root_page,
            0,
            P4::Table(probe_source.table.name.clone()),
            0,
        );

        let probe_done = b.emit_label();
        if use_exists_semijoin_merge {
            b.emit_jump_to_label(Opcode::Rewind, idx_cursor, 0, probe_done, P4::None, 0);
        }
        let source_upper_reg = source_rowid_range.and_then(|range| {
            range.upper.map(|bound| {
                let reg = b.alloc_reg();
                emit_expr(b, bound.expr, reg, None);
                b.emit_jump_to_label(Opcode::IsNull, reg, 0, probe_done, P4::None, 0);
                reg
            })
        });
        let source_upper_comparison = source_rowid_range.and_then(|range| {
            range.upper.map(|bound| {
                resolved_rowid_range_comparison(
                    probe_source.table,
                    probe_source.table_alias,
                    schema,
                    bound,
                )
            })
        });

        let source_rowid_reg = (source_rowid_range.is_some()
            && matches!(probe_source.value, InProbeValue::Rowid))
        .then(|| b.alloc_reg());
        let r_probe_value = source_rowid_reg.unwrap_or_else(|| b.alloc_reg());
        let r_current_key = b.alloc_reg();

        let probe_start = b.current_addr();
        if let Some(range) = source_rowid_range {
            if let Some(bound) = range.lower {
                let lower_reg = b.alloc_reg();
                emit_expr(b, bound.expr, lower_reg, None);
                b.emit_jump_to_label(Opcode::IsNull, lower_reg, 0, probe_done, P4::None, 0);
                let seek_opcode = if bound.inclusive {
                    Opcode::SeekGE
                } else {
                    Opcode::SeekGT
                };
                b.emit_jump_to_label(
                    seek_opcode,
                    source_cursor,
                    lower_reg,
                    probe_done,
                    P4::None,
                    0,
                );
            } else {
                b.emit_jump_to_label(Opcode::Rewind, source_cursor, 0, probe_done, P4::None, 0);
            }
        } else {
            b.emit_jump_to_label(Opcode::Rewind, source_cursor, 0, probe_done, P4::None, 0);
        }
        let probe_loop_body = if let Some(rowid_reg) = source_rowid_reg {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let loop_addr = b.current_addr() as i32;
            b.emit_op(Opcode::Rowid, source_cursor, rowid_reg, 0, P4::None, 0);
            loop_addr
        } else {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let loop_addr = (probe_start + 1) as i32;
            loop_addr
        };
        let skip_row = (probe_source.where_clause.is_some() && source_rowid_range.is_none())
            .then(|| b.emit_label());
        if let Some(range) = source_rowid_range
            && let Some(bound) = range.upper
        {
            let current_rowid_reg = source_rowid_reg.unwrap_or_else(|| b.alloc_reg());
            let stop_opcode = if bound.inclusive {
                Opcode::Gt
            } else {
                Opcode::Ge
            };
            b.emit_jump_to_label(
                stop_opcode,
                source_upper_reg.expect("upper bound register should exist"),
                current_rowid_reg,
                probe_done,
                source_upper_comparison
                    .as_ref()
                    .map_or(P4::None, |comparison| comparison.collation_p4.clone()),
                source_upper_comparison
                    .as_ref()
                    .map_or(0, |comparison| comparison.cmp_p5),
            );
        }
        if let (Some(where_expr), Some(skip_label)) = (probe_source.where_clause, skip_row) {
            emit_where_filter(
                b,
                where_expr,
                source_cursor,
                probe_source.table,
                probe_source.table_alias,
                schema,
                skip_label,
            );
        }

        let probe_scan = ScanCtx {
            cursor: source_cursor,
            table: probe_source.table,
            table_alias: probe_source.table_alias,
            schema: Some(schema),
            register_base: None,
            secondaries: &[],
        };
        if source_rowid_reg.is_none() {
            emit_in_probe_value(b, source_cursor, probe_source, r_probe_value, &probe_scan);
        }

        let next_probe = b.emit_label();
        if source_rowid_reg.is_none() {
            b.emit_jump_to_label(Opcode::IsNull, r_probe_value, 0, next_probe, P4::None, 0);
        }
        if use_exists_semijoin_merge {
            let advance_outer = b.emit_label();
            let align_outer = b.emit_label();

            b.resolve_label(align_outer);
            b.emit_op(Opcode::Column, idx_cursor, 0, r_current_key, P4::None, 0);
            // NULL is never equal to a rowid probe.  Skip nullable leading
            // index keys explicitly: comparison opcodes intentionally do not
            // order NULL against an integer for SQL predicate purposes, so
            // omitting this edge would strand the outer cursor on its NULL run.
            b.emit_jump_to_label(Opcode::IsNull, r_current_key, 0, advance_outer, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::Lt,
                r_probe_value,
                r_current_key,
                advance_outer,
                count_key_collation.clone(),
                0,
            );
            b.emit_jump_to_label(
                Opcode::Gt,
                r_probe_value,
                r_current_key,
                next_probe,
                count_key_collation.clone(),
                0,
            );

            b.emit_op(
                Opcode::CountIndexEqRun,
                idx_cursor,
                out_regs,
                r_probe_value,
                P4::None,
                0,
            );
            b.emit_jump_to_label(Opcode::IfNullRow, idx_cursor, 0, probe_done, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, next_probe, P4::None, 0);

            b.resolve_label(advance_outer);
            b.emit_jump_to_label(Opcode::Next, idx_cursor, 0, align_outer, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, probe_done, P4::None, 0);
        } else {
            // bd-2fong (latent, found during the red-5 DESC-seek trace):
            // MakeRecord packs CONSECUTIVE registers, but r_probe_value was
            // allocated far earlier with r_current_key adjacent to it — so
            // `MakeRecord(r_probe_value, 2, ..)` packed [probe, stale index
            // key] while the i64::MIN floor below was written to a register
            // nothing read. Build the (key, i64::MIN) seek record from a
            // fresh adjacent pair instead.
            let r_seek_base = b.alloc_regs(2);
            let r_probe_record = b.alloc_reg();
            b.emit_op(Opcode::SCopy, r_probe_value, r_seek_base, 0, P4::None, 0);
            b.emit_op(Opcode::Int64, 0, r_seek_base + 1, 0, P4::Int64(i64::MIN), 0);
            b.emit_op(
                Opcode::MakeRecord,
                r_seek_base,
                2,
                r_probe_record,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::SeekGE,
                idx_cursor,
                r_probe_record,
                next_probe,
                P4::None,
                0,
            );

            let idx_loop_top = b.current_addr();
            b.emit_op(Opcode::Column, idx_cursor, 0, r_current_key, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::Ne,
                r_probe_value,
                r_current_key,
                next_probe,
                count_key_collation.clone(),
                0,
            );
            b.emit_op(Opcode::AddImm, out_regs, 1, 0, P4::None, 0);
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let idx_loop_body = idx_loop_top as i32;
            b.emit_op(Opcode::Next, idx_cursor, idx_loop_body, 0, P4::None, 0);
        }

        if let Some(skip_label) = skip_row {
            b.resolve_label(skip_label);
        }
        b.resolve_label(next_probe);
        b.emit_op(Opcode::Next, source_cursor, probe_loop_body, 0, P4::None, 0);

        b.resolve_label(probe_done);
        b.emit_op(Opcode::ResultRow, out_regs, 1, 0, P4::None, 0);
        b.emit_op(Opcode::Close, source_cursor, 0, 0, P4::None, 0);
        b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);
        return Ok(());
    }

    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Integer, 0, out_regs, 0, P4::None, 0);
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );
    b.emit_op(
        Opcode::OpenAutoindex,
        probe_cursor,
        1,
        0,
        count_key_collation.clone(),
        0,
    );

    let use_materialized_semijoin_merge = matches!(
        &in_target,
        CountIndexedInTarget::MaterializedProbeSource(probe_source)
            if count_exists_semijoin_merge_is_safe(table, idx_schema, probe_source)
    );

    let r_value = b.alloc_temp();
    let r_key = b.alloc_temp();
    match in_target {
        CountIndexedInTarget::List(values) => {
            for value_expr in values {
                emit_expr(b, value_expr, r_value, None);
                let next_value = b.emit_label();
                let skip_insert = b.emit_label();
                b.emit_jump_to_label(Opcode::IsNull, r_value, 0, next_value, P4::None, 0);
                b.emit_op(Opcode::MakeRecord, r_value, 1, r_key, P4::None, 0);
                b.emit_jump_to_label(Opcode::Found, probe_cursor, r_key, skip_insert, P4::None, 0);
                b.emit_op(Opcode::IdxInsert, probe_cursor, r_key, 0, P4::None, 0);
                b.resolve_label(skip_insert);
                b.resolve_label(next_value);
            }
        }
        CountIndexedInTarget::ProbeSource(probe_source)
        | CountIndexedInTarget::MaterializedProbeSource(probe_source) => {
            b.emit_op(
                Opcode::OpenRead,
                source_cursor,
                probe_source.table.root_page,
                0,
                P4::Table(probe_source.table.name.clone()),
                0,
            );

            let build_done = b.emit_label();
            let source_rowid_range = extract_safe_probe_source_rowid_range(&probe_source);
            let source_upper_reg = source_rowid_range.and_then(|range| {
                range.upper.map(|bound| {
                    let reg = b.alloc_reg();
                    emit_expr(b, bound.expr, reg, None);
                    b.emit_jump_to_label(Opcode::IsNull, reg, 0, build_done, P4::None, 0);
                    reg
                })
            });
            let source_upper_comparison = source_rowid_range.and_then(|range| {
                range.upper.map(|bound| {
                    resolved_rowid_range_comparison(
                        probe_source.table,
                        probe_source.table_alias,
                        schema,
                        bound,
                    )
                })
            });
            let build_start = b.current_addr();
            if let Some(range) = source_rowid_range {
                if let Some(bound) = range.lower {
                    let lower_reg = b.alloc_reg();
                    emit_expr(b, bound.expr, lower_reg, None);
                    b.emit_jump_to_label(Opcode::IsNull, lower_reg, 0, build_done, P4::None, 0);
                    let seek_opcode = if bound.inclusive {
                        Opcode::SeekGE
                    } else {
                        Opcode::SeekGT
                    };
                    b.emit_jump_to_label(
                        seek_opcode,
                        source_cursor,
                        lower_reg,
                        build_done,
                        P4::None,
                        0,
                    );
                } else {
                    b.emit_jump_to_label(Opcode::Rewind, source_cursor, 0, build_done, P4::None, 0);
                }
            } else {
                b.emit_jump_to_label(Opcode::Rewind, source_cursor, 0, build_done, P4::None, 0);
            }
            let skip_row = probe_source.where_clause.map(|_| b.emit_label());
            if let Some(range) = source_rowid_range
                && let Some(bound) = range.upper
            {
                let current_rowid_reg = b.alloc_reg();
                let stop_opcode = if bound.inclusive {
                    Opcode::Gt
                } else {
                    Opcode::Ge
                };
                b.emit_op(
                    Opcode::Rowid,
                    source_cursor,
                    current_rowid_reg,
                    0,
                    P4::None,
                    0,
                );
                b.emit_jump_to_label(
                    stop_opcode,
                    source_upper_reg.expect("upper bound register should exist"),
                    current_rowid_reg,
                    build_done,
                    source_upper_comparison
                        .as_ref()
                        .map_or(P4::None, |comparison| comparison.collation_p4.clone()),
                    source_upper_comparison
                        .as_ref()
                        .map_or(0, |comparison| comparison.cmp_p5),
                );
            }
            if let (Some(where_expr), Some(skip_label)) = (probe_source.where_clause, skip_row) {
                emit_where_filter(
                    b,
                    where_expr,
                    source_cursor,
                    probe_source.table,
                    probe_source.table_alias,
                    schema,
                    skip_label,
                );
            }

            let probe_scan = ScanCtx {
                cursor: source_cursor,
                table: probe_source.table,
                table_alias: probe_source.table_alias,
                schema: Some(schema),
                register_base: None,
                secondaries: &[],
            };
            emit_in_probe_value(b, source_cursor, &probe_source, r_value, &probe_scan);

            let skip_insert = b.emit_label();
            let next_value = b.emit_label();
            b.emit_jump_to_label(Opcode::IsNull, r_value, 0, next_value, P4::None, 0);
            b.emit_op(Opcode::MakeRecord, r_value, 1, r_key, P4::None, 0);
            b.emit_jump_to_label(Opcode::Found, probe_cursor, r_key, skip_insert, P4::None, 0);
            b.emit_op(Opcode::IdxInsert, probe_cursor, r_key, 0, P4::None, 0);
            b.resolve_label(skip_insert);
            b.resolve_label(next_value);

            if let Some(skip_label) = skip_row {
                b.resolve_label(skip_label);
            }
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let build_loop_body = (build_start + 1) as i32;
            b.emit_op(Opcode::Next, source_cursor, build_loop_body, 0, P4::None, 0);
            b.resolve_label(build_done);
            b.emit_op(Opcode::Close, source_cursor, 0, 0, P4::None, 0);
        }
    }
    b.free_temp(r_key);
    b.free_temp(r_value);

    b.emit_jump_to_label(Opcode::Rewind, probe_cursor, 0, done_label, P4::None, 0);
    if use_materialized_semijoin_merge {
        b.emit_jump_to_label(Opcode::Rewind, idx_cursor, 0, done_label, P4::None, 0);

        let r_probe_value = b.alloc_reg();
        let r_current_key = b.alloc_reg();
        let probe_loop_top = b.current_addr();
        b.emit_op(Opcode::Column, probe_cursor, 0, r_probe_value, P4::None, 0);

        let next_probe = b.emit_label();
        let advance_outer = b.emit_label();
        let align_outer = b.emit_label();

        b.resolve_label(align_outer);
        b.emit_op(Opcode::Column, idx_cursor, 0, r_current_key, P4::None, 0);
        b.emit_jump_to_label(Opcode::IsNull, r_current_key, 0, advance_outer, P4::None, 0);
        b.emit_jump_to_label(
            Opcode::Lt,
            r_probe_value,
            r_current_key,
            advance_outer,
            count_key_collation.clone(),
            0,
        );
        b.emit_jump_to_label(
            Opcode::Gt,
            r_probe_value,
            r_current_key,
            next_probe,
            count_key_collation.clone(),
            0,
        );

        b.emit_op(
            Opcode::CountIndexEqRun,
            idx_cursor,
            out_regs,
            r_probe_value,
            P4::None,
            0,
        );
        b.emit_jump_to_label(Opcode::IfNullRow, idx_cursor, 0, done_label, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, next_probe, P4::None, 0);

        b.resolve_label(advance_outer);
        b.emit_jump_to_label(Opcode::Next, idx_cursor, 0, align_outer, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

        b.resolve_label(next_probe);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let probe_loop_body = probe_loop_top as i32;
        b.emit_op(Opcode::Next, probe_cursor, probe_loop_body, 0, P4::None, 0);
    } else {
        let r_probe_value = b.alloc_reg();
        let r_min_rowid = b.alloc_reg();
        let r_probe_record = b.alloc_reg();
        let r_current_key = b.alloc_reg();

        let probe_loop_top = b.current_addr();
        b.emit_op(Opcode::Column, probe_cursor, 0, r_probe_value, P4::None, 0);
        b.emit_op(Opcode::Int64, 0, r_min_rowid, 0, P4::Int64(i64::MIN), 0);
        b.emit_op(
            Opcode::MakeRecord,
            r_probe_value,
            2,
            r_probe_record,
            P4::None,
            0,
        );
        let next_probe = b.emit_label();
        b.emit_jump_to_label(
            Opcode::SeekGE,
            idx_cursor,
            r_probe_record,
            next_probe,
            P4::None,
            0,
        );

        let idx_loop_top = b.current_addr();
        b.emit_op(Opcode::Column, idx_cursor, 0, r_current_key, P4::None, 0);
        b.emit_jump_to_label(
            Opcode::Ne,
            r_probe_value,
            r_current_key,
            next_probe,
            count_key_collation,
            0,
        );
        b.emit_op(Opcode::AddImm, out_regs, 1, 0, P4::None, 0);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let idx_loop_body = idx_loop_top as i32;
        b.emit_op(Opcode::Next, idx_cursor, idx_loop_body, 0, P4::None, 0);

        b.resolve_label(next_probe);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let probe_loop_body = probe_loop_top as i32;
        b.emit_op(Opcode::Next, probe_cursor, probe_loop_body, 0, P4::None, 0);
    }

    b.resolve_label(done_label);
    b.emit_op(Opcode::ResultRow, out_regs, 1, 0, P4::None, 0);
    b.emit_op(Opcode::Close, probe_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

fn extract_safe_probe_source_rowid_range<'a>(
    probe_source: &InProbeSource<'a>,
) -> Option<RowidRangeTarget<'a>> {
    let range = extract_rowid_range_target(
        probe_source.where_clause,
        Some(probe_source.table),
        probe_source.table_alias,
    )?;
    rowid_range_fast_path_is_safe(range).then_some(range)
}

fn count_exists_semijoin_merge_is_safe(
    table: &TableSchema,
    idx_schema: &IndexSchema,
    probe_source: &InProbeSource<'_>,
) -> bool {
    if !matches!(probe_source.value, InProbeValue::Rowid) {
        return false;
    }
    count_rowid_probe_index_is_seek_compatible(table, idx_schema)
}

fn count_rowid_probe_index_is_seek_compatible(
    table: &TableSchema,
    idx_schema: &IndexSchema,
) -> bool {
    idx_schema
        .columns
        .first()
        .and_then(|column_name| table.column_index(column_name))
        .and_then(|column_idx| table.columns.get(column_idx))
        .is_some_and(|column| column.is_ipk || matches!(column.affinity, 'D' | 'd' | 'C'))
}

fn resolved_rowid_range_comparison(
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    bound: RowidRangeBound<'_>,
) -> ResolvedComparisonInfo {
    let scan = ScanCtx {
        cursor: 0,
        table,
        table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    ResolvedComparisonInfo::new(bound.rowid_expr, bound.expr, &scan)
}

fn resolved_index_range_comparison(
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    column_name: &str,
    bound_expr: &Expr,
) -> ResolvedComparisonInfo {
    let column_expr = Expr::Column(ColumnRef::bare(column_name), Span::ZERO);
    let scan = ScanCtx {
        cursor: 0,
        table,
        table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    ResolvedComparisonInfo::new(&column_expr, bound_expr, &scan)
}

fn emit_covering_output_reads(
    b: &mut ProgramBuilder,
    index_cursor: i32,
    rowid_reg: i32,
    sources: &[CoveringOutputSource],
    out_regs: i32,
) {
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for (offset, source) in sources.iter().enumerate() {
        let target_reg = out_regs + offset as i32;
        match source {
            CoveringOutputSource::IndexColumn(index_col) => {
                b.emit_op(
                    Opcode::Column,
                    index_cursor,
                    *index_col,
                    target_reg,
                    P4::None,
                    0,
                );
            }
            CoveringOutputSource::Rowid => {
                b.emit_op(Opcode::Copy, rowid_reg, target_reg, 0, P4::None, 0);
            }
        }
    }
}

/// Generate VDBE bytecode for an ORDER BY scan that can stream rows directly
/// from an index in sorted order (no sorter temp B-tree).
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_select_index_ordered_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    limit_clause: Option<&LimitClause>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    index_plan: &OrderByIndexPlan,
) -> Result<(), CodegenError> {
    let index_cursor = cursor + 1;
    let needs_table_lookup = index_plan.covering_output.is_none() || where_clause.is_some();
    let where_placeholder_base = b.current_anon_placeholder();
    let equality_prefix_exprs = if index_plan.equality_prefix_len == 0 {
        Vec::new()
    } else {
        extract_index_equality_prefix_exprs(&index_plan.index, table, table_alias, where_clause)
    };
    let use_bounded_prefix_scan = !index_plan.descending
        && index_plan.equality_prefix_len > 0
        && equality_prefix_exprs.len() >= index_plan.equality_prefix_len;

    // Allocate LIMIT/OFFSET counter registers (if present).
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    if needs_table_lookup {
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
    }

    b.emit_op(
        Opcode::OpenRead,
        index_cursor,
        index_plan.index.root_page,
        0,
        P4::Index(index_plan.index.name.clone()),
        0,
    );

    let loop_start = if use_bounded_prefix_scan {
        let probe_key_regs = b.alloc_regs((index_plan.index.key_term_count() + 1) as i32);
        for (offset, expr) in equality_prefix_exprs
            .iter()
            .take(index_plan.equality_prefix_len)
            .enumerate()
        {
            let reg = probe_key_regs + offset as i32;
            emit_expr(b, expr, reg, None);
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, done_label, P4::None, 0);
        }
        for offset in index_plan.equality_prefix_len..index_plan.index.key_term_count() {
            b.emit_op(
                Opcode::Null,
                0,
                probe_key_regs + offset as i32,
                0,
                P4::None,
                0,
            );
        }
        b.emit_op(
            Opcode::Int64,
            0,
            probe_key_regs + index_plan.index.key_term_count() as i32,
            0,
            P4::Int64(i64::MIN),
            0,
        );
        let probe_record_reg = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            probe_key_regs,
            (index_plan.index.key_term_count() + 1) as i32,
            probe_record_reg,
            P4::None,
            0,
        );
        b.emit_jump_to_label(
            Opcode::SeekGE,
            index_cursor,
            probe_record_reg,
            done_label,
            P4::None,
            0,
        );
        let loop_start = b.current_addr();
        b.emit_jump_to_label(
            Opcode::IdxGT,
            index_cursor,
            probe_record_reg,
            done_label,
            P4::None,
            index_plan.equality_prefix_len as u16,
        );
        loop_start
    } else {
        let loop_start = b.current_addr();
        if index_plan.descending {
            b.emit_jump_to_label(Opcode::Last, index_cursor, 0, done_label, P4::None, 0);
        } else {
            b.emit_jump_to_label(Opcode::Rewind, index_cursor, 0, done_label, P4::None, 0);
        }
        loop_start
    };

    let skip_row = b.emit_label();
    let rowid_reg = b.alloc_reg();
    // WITHOUT ROWID index entries carry a PK suffix instead of a trailing
    // rowid (bd-rjaff): seek the table b-tree by the PK columns read from the
    // index entry. Covering reads on WITHOUT ROWID never resolve a Rowid
    // source (rowid aliases do not resolve on WITHOUT ROWID tables), so
    // `rowid_reg` staying unwritten is safe there.
    let wr_pk_indices = if table.without_rowid {
        Some(without_rowid_pk_indices(table)?)
    } else {
        None
    };
    if let Some(pk_indices) = wr_pk_indices.as_ref() {
        if needs_table_lookup {
            emit_without_rowid_index_to_table_seek(
                b,
                table,
                cursor,
                index_cursor,
                &index_plan.index,
                pk_indices,
                skip_row,
            );
        }
    } else {
        b.emit_op(Opcode::IdxRowid, index_cursor, rowid_reg, 0, P4::None, 0);

        if needs_table_lookup {
            b.emit_jump_to_label(Opcode::SeekRowid, cursor, rowid_reg, skip_row, P4::None, 0);
        }
    }

    if let Some(where_expr) = where_clause {
        b.set_next_anon_placeholder(where_placeholder_base);
        emit_where_filter(b, where_expr, cursor, table, table_alias, schema, skip_row);
    }

    if let Some(covering_output) = &index_plan.covering_output {
        emit_covering_output_reads(b, index_cursor, rowid_reg, covering_output, out_regs);
    } else {
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    }

    // OFFSET: if offset counter > 0, decrement by 1 and skip this row.
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_row, P4::None, 0);
    }

    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    // LIMIT: decrement limit counter; jump to done when zero.
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }

    b.resolve_label(skip_row);

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = if use_bounded_prefix_scan {
        loop_start as i32
    } else {
        (loop_start + 1) as i32
    };
    if index_plan.descending {
        b.emit_op(Opcode::Prev, index_cursor, loop_body, 0, P4::None, 0);
    } else {
        b.emit_op(Opcode::Next, index_cursor, loop_body, 0, P4::None, 0);
    }

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, index_cursor, 0, 0, P4::None, 0);
    if needs_table_lookup {
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End target for Init jump.
    b.resolve_label(end_label);
    Ok(())
}

/// Generate VDBE bytecode for `SELECT DISTINCT` without ORDER BY.
///
/// Preserves source scan order by recording each projected tuple in an
/// ephemeral membership index. LIMIT/OFFSET apply only after a tuple is known
/// to be distinct, matching SQLite's first-occurrence semantics.
#[allow(
    clippy::too_many_arguments,
    clippy::too_many_lines,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap
)]
fn codegen_select_distinct_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    limit_clause: Option<&LimitClause>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    let num_data_cols = result_column_count_usize(columns, table);
    let distinct_cursor = cursor + 1;
    let distinct_collations = (0..num_data_cols)
        .map(|slot| {
            result_output_slot_collation(slot, columns, table, table_alias)
                .unwrap_or_else(|| "BINARY".to_owned())
        })
        .collect::<Vec<_>>()
        .join(",");

    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);
    b.emit_op(
        Opcode::OpenAutoindex,
        distinct_cursor,
        out_col_count,
        0,
        P4::Str(distinct_collations),
        0,
    );

    // Open table for reading.
    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );

    let scan_start = b.current_addr();
    b.emit_jump_to_label(Opcode::Rewind, cursor, 0, done_label, P4::None, 0);

    let skip_label = b.emit_label();
    if let Some(where_expr) = where_clause {
        emit_where_filter(
            b,
            where_expr,
            cursor,
            table,
            table_alias,
            schema,
            skip_label,
        );
    }

    emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;

    let distinct_record = b.alloc_temp();
    b.emit_op(
        Opcode::MakeRecord,
        out_regs,
        out_col_count,
        distinct_record,
        P4::None,
        0,
    );
    b.emit_jump_to_label(
        Opcode::Found,
        distinct_cursor,
        distinct_record,
        skip_label,
        P4::None,
        0,
    );
    b.emit_op(
        Opcode::IdxInsert,
        distinct_cursor,
        distinct_record,
        0,
        P4::None,
        0,
    );
    b.free_temp(distinct_record);

    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, skip_label, P4::None, 0);
    }

    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }

    b.resolve_label(skip_label);
    let scan_body = (scan_start + 1) as i32;
    b.emit_op(Opcode::Next, cursor, scan_body, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Close, distinct_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    b.resolve_label(end_label);

    Ok(())
}

/// Emit a LIMIT or OFFSET expression into a register.
///
/// Handles integer literals and bind parameters; evaluates arbitrary
/// expressions via `emit_expr` for computed limits (e.g. `LIMIT 5+0`).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_limit_expr(b: &mut ProgramBuilder, expr: &Expr, target_reg: i32) {
    match expr {
        Expr::Literal(Literal::Integer(n), _) => {
            if let Ok(as_i32) = i32::try_from(*n) {
                b.emit_op(Opcode::Integer, as_i32, target_reg, 0, P4::None, 0);
            } else {
                b.emit_op(Opcode::Int64, 0, target_reg, 0, P4::Int64(*n), 0);
            }
        }
        Expr::Placeholder(pt, _) => {
            let param_idx = match pt {
                fsqlite_ast::PlaceholderType::Numbered(n) => *n as i32,
                // Anonymous and named placeholders use sequential numbering.
                _ => b.next_anon_placeholder_idx() as i32,
            };
            b.emit_op(Opcode::Variable, param_idx, target_reg, 0, P4::None, 0);
        }
        _ => {
            // Evaluate arbitrary expression (e.g. `5+0`, `abs(-3)`).
            // No table context needed — LIMIT expressions don't reference columns.
            emit_expr(b, expr, target_reg, None);
        }
    }
}

/// Whether LIMIT/OFFSET cannot suppress a single aggregate output row.
///
/// This lets single-seek aggregate fast paths retain their existing complexity
/// for common `LIMIT 1` probes. Dynamic or coercible expressions take the
/// general limit-aware path because their value is known only at execution.
fn single_group_aggregate_limit_is_output_neutral(limit_clause: Option<&LimitClause>) -> bool {
    let Some(clause) = limit_clause else {
        return true;
    };
    let Expr::Literal(Literal::Integer(limit), _) = &clause.limit else {
        return false;
    };
    if *limit == 0 {
        return false;
    }
    clause.offset.as_ref().is_none_or(
        |offset| matches!(offset, Expr::Literal(Literal::Integer(value), _) if *value <= 0),
    )
}

/// Emit a guard that jumps to `done_label` when the LIMIT register is zero.
///
/// `LIMIT 0` means "return no rows". The `DecrJumpZero` instruction after
/// `ResultRow` doesn't fire when the register is already 0 (it only
/// decrements positive values), so we need a pre-loop guard.
///
/// `LIMIT -1` means "no limit" — the register is -1 (truthy), so the
/// `IfNot` check does not fire.
fn emit_limit_zero_guard(b: &mut ProgramBuilder, limit_reg: i32, done_label: crate::Label) {
    b.emit_jump_to_label(Opcode::IfNot, limit_reg, 1, done_label, P4::None, 0);
}

/// Emit LIMIT/OFFSET registers with SQLite's evaluation and coercion order.
///
/// LIMIT is evaluated and losslessly coerced to an integer first. A zero LIMIT
/// jumps directly to `done_label`, so OFFSET is not evaluated at all. Only a
/// nonzero LIMIT reaches OFFSET evaluation and its own integer coercion.
fn emit_limit_offset_registers(
    b: &mut ProgramBuilder,
    limit_clause: Option<&LimitClause>,
    done_label: crate::Label,
) -> (Option<i32>, Option<i32>) {
    let Some(clause) = limit_clause else {
        return (None, None);
    };

    let limit_reg = b.alloc_reg();
    emit_limit_expr(b, &clause.limit, limit_reg);
    if !matches!(&clause.limit, Expr::Literal(Literal::Integer(_), _)) {
        b.emit_op(Opcode::MustBeInt, limit_reg, 0, 0, P4::None, 0);
    }
    emit_limit_zero_guard(b, limit_reg, done_label);

    let offset_reg = clause.offset.as_ref().map(|offset| {
        let register = b.alloc_reg();
        emit_limit_expr(b, offset, register);
        if !matches!(offset, Expr::Literal(Literal::Integer(_), _)) {
            b.emit_op(Opcode::MustBeInt, register, 0, 0, P4::None, 0);
        }
        register
    });

    (Some(limit_reg), offset_reg)
}

/// Compute the runtime row-retention bound for a top-N sorter.
///
/// Pass 2 emits at most `LIMIT` rows after skipping `OFFSET`, so pass 1 must
/// retain `LIMIT + max(OFFSET, 0)` rows. `OffsetLimit` preserves negative
/// LIMIT as the no-limit sentinel and saturates positive overflow. The
/// returned register must be read by `SorterOpen` with
/// `SORTER_OPEN_TOP_N_REGISTER`.
fn emit_top_n_bound_register(
    b: &mut ProgramBuilder,
    limit_reg: Option<i32>,
    offset_reg: Option<i32>,
) -> Option<i32> {
    let limit_reg = limit_reg?;
    let Some(offset_reg) = offset_reg else {
        return Some(limit_reg);
    };

    // SQLite treats a negative OFFSET as zero. Clamp the shared pass-2 counter
    // before computing the retention bound so both phases observe the same
    // normalized value.
    let zero_reg = b.alloc_temp();
    b.emit_op(Opcode::Integer, 0, zero_reg, 0, P4::None, 0);
    b.emit_op(Opcode::MemMax, zero_reg, offset_reg, 0, P4::None, 0);
    b.free_temp(zero_reg);

    let bound_reg = b.alloc_reg();
    b.emit_op(
        Opcode::OffsetLimit,
        limit_reg,
        offset_reg,
        bound_reg,
        P4::None,
        0,
    );
    Some(bound_reg)
}

fn limit_clause_can_enable_top_n(limit_clause: Option<&LimitClause>) -> bool {
    limit_clause
        .is_some_and(|clause| order_by_integer_ordinal(&clause.limit).is_none_or(|limit| limit > 0))
}

// ---------------------------------------------------------------------------
// ORDER BY codegen (two-pass sorter)
// ---------------------------------------------------------------------------

/// Generate VDBE bytecode for a full-scan SELECT with ORDER BY.
///
/// Uses a two-pass sorter approach:
/// 1. Scan table rows (with WHERE), pack sort-key + data columns into sorter.
/// 2. After sorting, iterate sorted rows and emit `ResultRow`.
///
/// LIMIT/OFFSET are applied in pass 2 (on sorted output).
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::too_many_arguments,
    clippy::too_many_lines
)]
fn codegen_select_ordered_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    order_by: &[OrderingTerm],
    limit_clause: Option<&LimitClause>,
    distinct: Distinctness,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    // Connection-level compilation canonicalizes anonymous and named bind
    // parameters to explicit `?NNN` slots before VDBE codegen. Direct callers
    // can still provide a raw AST, though, and this path intentionally emits
    // LIMIT/OFFSET before the earlier textual SELECT/WHERE/ORDER expressions.
    // Sequential emission-order numbering would therefore reverse slots or
    // break named-parameter reuse. Decline the reordered path unless every
    // placeholder already carries its canonical numeric slot.
    let projection_has_non_numbered_placeholder = columns.iter().any(|column| {
        matches!(
            column,
            ResultColumn::Expr { expr, .. } if expr_contains_non_numbered_placeholder(expr)
        )
    });
    let order_has_non_numbered_placeholder = order_by
        .iter()
        .any(|term| expr_contains_non_numbered_placeholder(&term.expr));
    let limit_has_non_numbered_placeholder = limit_clause.is_some_and(|clause| {
        expr_contains_non_numbered_placeholder(&clause.limit)
            || clause
                .offset
                .as_ref()
                .is_some_and(expr_contains_non_numbered_placeholder)
    });
    if projection_has_non_numbered_placeholder
        || where_clause.is_some_and(expr_contains_non_numbered_placeholder)
        || order_has_non_numbered_placeholder
        || limit_has_non_numbered_placeholder
    {
        return Err(CodegenError::Unsupported(
            "ordered SELECT codegen requires canonical numbered bind parameters".to_owned(),
        ));
    }

    // LIMIT (then OFFSET) is evaluated before the source scan. Besides
    // matching SQLite's observable error/function order, this supplies the
    // runtime retention bound used by the bounded sorter.
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);
    let top_n_bound_reg = if limit_clause_can_enable_top_n(limit_clause) {
        emit_top_n_bound_register(b, limit_reg, offset_reg)
    } else {
        None
    };

    // Resolve ORDER BY sources (column indices, rowid, or expressions).
    let sort_keys: Vec<SortKeySource> = order_by
        .iter()
        .map(|term| resolve_sort_key(&term.expr, table, table_alias, columns))
        .collect();
    let order_output_slots: Vec<Option<usize>> = order_by
        .iter()
        .map(|term| resolve_order_by_output_slot(&term.expr, columns, table, table_alias))
        .collect();

    let num_sort_keys = sort_keys.len();
    let num_data_cols = result_column_count_usize(columns, table);

    // Sorter cursor is separate from the table cursor.
    let sorter_cursor = cursor + 1;

    // Open sorter: p2 = number of key columns, p4 = sort order + collation.
    // Sort order chars: '+' = ASC (nulls first), '-' = DESC (nulls last),
    // '>' = ASC NULLS LAST, '<' = DESC NULLS FIRST.
    let sort_order: String = order_by
        .iter()
        .map(|term| {
            let is_desc = term.direction == Some(SortDirection::Desc);
            let nulls_last = match term.nulls {
                Some(NullsOrder::Last) => true,
                Some(NullsOrder::First) => false,
                None => is_desc, // SQLite default: ASC→nulls first, DESC→nulls last
            };
            match (is_desc, nulls_last) {
                (false, false) => '+', // ASC NULLS FIRST (default)
                (false, true) => '>',  // ASC NULLS LAST
                (true, true) => '-',   // DESC NULLS LAST (default)
                (true, false) => '<',  // DESC NULLS FIRST
            }
        })
        .collect();
    // Build per-key collation info from the resolved sort keys.
    let sort_collations: Vec<String> = sort_keys
        .iter()
        .zip(order_by.iter())
        .enumerate()
        .map(|(index, (sk, term))| {
            // Explicit COLLATE on the ORDER BY term takes priority.
            if let Some(collation) = extract_collation(&term.expr) {
                return collation.to_owned();
            }
            if let Some(output_slot) = order_output_slots[index]
                && let Some(collation) =
                    result_output_slot_collation(output_slot, columns, table, table_alias)
            {
                return collation;
            }
            // Otherwise, inherit the column's declared collation.
            match sk {
                SortKeySource::Column(idx) => {
                    if let Some(collation) =
                        table.columns.get(*idx).and_then(|c| c.collation.as_deref())
                    {
                        return collation.to_owned();
                    }
                }
                SortKeySource::Expression(expr) => {
                    if let Some(collation) = extract_collation(expr)
                        .or_else(|| column_collation(expr, table, table_alias))
                    {
                        return collation.to_owned();
                    }
                }
                SortKeySource::Rowid => {}
            }
            String::new()
        })
        .collect();
    let distinct_projection_mode = ordered_distinct_projection_mode(
        distinct,
        order_by,
        &order_output_slots,
        &sort_collations,
        columns,
        table,
        table_alias,
    );
    let stored_data_cols = match distinct_projection_mode {
        OrderedDistinctProjectionMode::StoredOutput => num_data_cols,
        OrderedDistinctProjectionMode::ReprojectRepresentative if table.without_rowid => {
            table.columns.len()
        }
        OrderedDistinctProjectionMode::ReprojectRepresentative => 1,
    };
    let total_sorter_cols = num_sort_keys + stored_data_cols;
    let keep_source_cursor_open = distinct_projection_mode
        == OrderedDistinctProjectionMode::ReprojectRepresentative
        && !table.without_rowid;

    let has_collation = sort_collations.iter().any(|c| !c.is_empty());
    let p4_str = if has_collation {
        format!("{sort_order}|{}", sort_collations.join(","))
    } else {
        sort_order
    };
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::SorterOpen,
        sorter_cursor,
        num_sort_keys as i32,
        top_n_bound_reg.unwrap_or(0),
        P4::Str(p4_str),
        top_n_bound_reg.map_or(0, |_| SORTER_OPEN_TOP_N_REGISTER),
    );

    // DISTINCT is defined over the flattened output tuple, not the ORDER BY
    // key prefix. Open a separate membership index before pass 1 so duplicate
    // outputs can skip independent ORDER BY expression evaluation as well as
    // sorter insertion. Spell out BINARY for default-collation slots because
    // the OpenAutoindex P4 parser intentionally ignores empty list entries.
    let distinct_cursor = if distinct == Distinctness::Distinct {
        let distinct_cursor = sorter_cursor + 1;
        let collations = (0..num_data_cols)
            .map(|slot| {
                result_output_slot_collation(slot, columns, table, table_alias)
                    .unwrap_or_else(|| "BINARY".to_owned())
            })
            .collect::<Vec<_>>()
            .join(",");
        b.emit_op(
            Opcode::OpenAutoindex,
            distinct_cursor,
            out_col_count,
            0,
            P4::Str(collations),
            0,
        );
        Some(distinct_cursor)
    } else {
        None
    };

    // Open table for reading.
    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );

    // === Pass 1: Scan rows into sorter ===
    let scan_start = b.current_addr();
    let scan_done = b.emit_label();
    b.emit_jump_to_label(Opcode::Rewind, cursor, 0, scan_done, P4::None, 0);

    // WHERE filter.
    let skip_label = b.emit_label();
    if let Some(where_expr) = where_clause {
        emit_where_filter(
            b,
            where_expr,
            cursor,
            table,
            table_alias,
            schema,
            skip_label,
        );
    }

    // Read sort-key columns + data columns into consecutive registers.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let sorter_base = b.alloc_regs(total_sorter_cols as i32);
    let stored_data_base = sorter_base + num_sort_keys as i32;
    let output_base =
        if distinct_projection_mode == OrderedDistinctProjectionMode::ReprojectRepresentative {
            b.alloc_regs(out_col_count)
        } else {
            stored_data_base
        };
    let scan = ScanCtx {
        cursor,
        table,
        table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    {
        let mut output_emitted = vec![false; num_data_cols];

        // In the ordinary (non-merged) SQLite DISTINCT+ORDER BY shape, result
        // expressions are evaluated and deduplicated before independent ORDER
        // expressions. Besides being the correct tuple key, this ordering means
        // a duplicate output cannot invoke a volatile or failing sort-only
        // expression. Exact ORDER aliases/ordinals below reuse these registers.
        if let Some(distinct_cursor) = distinct_cursor {
            emit_column_reads_selected(b, &scan, columns, output_base, |_| true)?;
            output_emitted.fill(true);

            let distinct_record = b.alloc_temp();
            b.emit_op(
                Opcode::MakeRecord,
                output_base,
                out_col_count,
                distinct_record,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::Found,
                distinct_cursor,
                distinct_record,
                skip_label,
                P4::None,
                0,
            );
            b.emit_op(
                Opcode::IdxInsert,
                distinct_cursor,
                distinct_record,
                0,
                P4::None,
                0,
            );
            b.free_temp(distinct_record);
        }

        for (index, (reg, key)) in (sorter_base..).zip(sort_keys.iter()).enumerate() {
            if let Some(output_slot) = order_output_slots[index] {
                if !output_emitted[output_slot] {
                    emit_column_reads_selected(b, &scan, columns, output_base, |slot| {
                        slot == output_slot
                    })?;
                    output_emitted[output_slot] = true;
                }
                b.emit_op(
                    Opcode::Copy,
                    output_base + output_slot as i32,
                    reg,
                    0,
                    P4::None,
                    0,
                );
            } else {
                emit_resolved_column(b, key, cursor, reg, &scan);
            }
        }

        if top_n_bound_reg.is_some() {
            let key_record = b.alloc_temp();
            b.emit_op(
                Opcode::MakeRecord,
                sorter_base,
                num_sort_keys as i32,
                key_record,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::SorterCompare,
                sorter_cursor,
                key_record,
                skip_label,
                P4::None,
                SORTER_COMPARE_TOP_N_PREFLIGHT,
            );
            b.free_temp(key_record);
        }

        // For non-DISTINCT top-N, evaluate only outputs not already shared with
        // an exact ORDER BY key. This occurs after admission, so rejected rows
        // cannot invoke volatile or failing payload expressions. DISTINCT
        // output was already evaluated above, before its membership probe.
        emit_column_reads_selected(b, &scan, columns, output_base, |slot| !output_emitted[slot])?;

        if distinct_projection_mode == OrderedDistinctProjectionMode::ReprojectRepresentative {
            emit_ordered_distinct_source_state(b, cursor, table, stored_data_base);
        }
    }

    // MakeRecord from all sorter columns, then SorterInsert.
    let record_reg = b.alloc_reg();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::MakeRecord,
        sorter_base,
        total_sorter_cols as i32,
        record_reg,
        P4::None,
        0,
    );
    b.emit_op(
        Opcode::SorterInsert,
        sorter_cursor,
        record_reg,
        0,
        P4::None,
        0,
    );

    // Skip label (for WHERE-filtered rows).
    b.resolve_label(skip_label);

    // Next row in scan.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let scan_body = (scan_start + 1) as i32;
    b.emit_op(Opcode::Next, cursor, scan_body, 0, P4::None, 0);

    // End of pass 1. A merged ordered-DISTINCT query on a rowid table keeps
    // this read cursor open so pass 2 can seek and re-evaluate the selected
    // expressions for each retained representative.
    b.resolve_label(scan_done);
    if !keep_source_cursor_open {
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }

    // === Pass 2: Iterate the already-deduplicated sorted rows ===

    // SorterSort: sort and position at first row; jump to done if empty.
    b.emit_jump_to_label(
        Opcode::SorterSort,
        sorter_cursor,
        0,
        done_label,
        P4::None,
        0,
    );

    // Save the address of the sort loop body (SorterNext returns here).
    let sort_loop_body = b.current_addr();

    // OFFSET applies after duplicate elimination and before materializing the
    // retained sorter payload or restoring/reprojecting its source row.
    let output_skip = b.emit_label();
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, output_skip, P4::None, 0);
    }

    // SorterData: decode current sorted row into a register.
    let sorted_reg = b.alloc_reg();
    b.emit_op(
        Opcode::SorterData,
        sorter_cursor,
        sorted_reg,
        0,
        P4::None,
        0,
    );

    match distinct_projection_mode {
        OrderedDistinctProjectionMode::StoredOutput => {
            // The sorter record has sort-key columns first, followed by the
            // already-projected result tuple.
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            for i in 0..num_data_cols {
                let src_col = (num_sort_keys + i) as i32;
                b.emit_op(
                    Opcode::Column,
                    sorter_cursor,
                    src_col,
                    out_regs + i as i32,
                    P4::None,
                    0,
                );
            }
        }
        OrderedDistinctProjectionMode::ReprojectRepresentative if table.without_rowid => {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let source_base = b.alloc_regs(table.columns.len() as i32);
            for column_index in 0..table.columns.len() {
                #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                b.emit_op(
                    Opcode::Column,
                    sorter_cursor,
                    (num_sort_keys + column_index) as i32,
                    source_base + column_index as i32,
                    P4::None,
                    0,
                );
            }
            emit_projection_from_register_row(
                b,
                columns,
                table,
                table_alias,
                schema,
                source_base,
                out_regs,
            )?;
        }
        OrderedDistinctProjectionMode::ReprojectRepresentative => {
            let representative_rowid = b.alloc_reg();
            b.emit_op(
                Opcode::Column,
                sorter_cursor,
                num_sort_keys as i32,
                representative_rowid,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                cursor,
                representative_rowid,
                output_skip,
                P4::None,
                0,
            );
            emit_column_reads_selected(b, &scan, columns, out_regs, |_| true)?;
        }
    }

    // ResultRow.
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    // LIMIT: decrement limit counter; jump to done when zero.
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }

    // Output skip label (for OFFSET-skipped rows).
    b.resolve_label(output_skip);

    // SorterNext: advance to next sorted row, jump back to sort loop body.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::SorterNext,
        sorter_cursor,
        sort_loop_body as i32,
        0,
        P4::None,
        0,
    );

    // Done: Close sorter + Halt.
    b.resolve_label(done_label);
    if keep_source_cursor_open {
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }
    if let Some(distinct_cursor) = distinct_cursor {
        b.emit_op(Opcode::Close, distinct_cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Close, sorter_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End target for Init jump.
    b.resolve_label(end_label);

    Ok(())
}

// ---------------------------------------------------------------------------
// Aggregate codegen
// ---------------------------------------------------------------------------

/// Known aggregate function names (case-insensitive matching).
const AGGREGATE_FUNCTIONS: &[&str] = &[
    "avg",
    "count",
    "group_concat",
    "string_agg",
    // JSON1 collection aggregates (fsqlite-ext-json, always registered). They
    // have no scalar overload, so the name-only predicate is safe — the wrong
    // arity is rejected downstream by `find_aggregate`.
    "json_group_array",
    "json_group_object",
    "max",
    "min",
    "sum",
    "total",
    "median",
    "percentile",
    "percentile_cont",
    "percentile_disc",
];

/// Check whether a function name is a known built-in aggregate.
///
/// Custom aggregates are resolved separately by exact/variadic arity in
/// [`is_aggregate_function_call`]. Folding them into this name-only predicate
/// would make registering `custom/1` incorrectly classify `custom/2` as an
/// aggregate call.
fn is_aggregate_function(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    AGGREGATE_FUNCTIONS.contains(&lower.as_str())
}

/// Check whether any result column contains an aggregate function call.
fn has_aggregate_columns(columns: &[ResultColumn]) -> bool {
    columns.iter().any(|col| {
        if let ResultColumn::Expr { expr, .. } = col {
            is_aggregate_expr(expr)
        } else {
            false
        }
    })
}

/// Check whether any result column contains a window function call.
fn has_window_columns(columns: &[ResultColumn]) -> bool {
    columns.iter().any(|col| {
        if let ResultColumn::Expr { expr, .. } = col {
            expr_has_window(expr)
        } else {
            false
        }
    })
}

/// Recursive check for window function calls in an expression.
/// True when `expr` is safe to evaluate during a plain rowid-order scan instead of the sorter path.
///
/// The forward-scan (`codegen_select_full_scan`) and sorter (`codegen_select_ordered_scan`) paths use
/// the SAME per-row WHERE evaluation, so a tree built only of the scalar nodes below is byte-identical
/// between them (the only difference being the elided sort). The two constructs that are NOT proven
/// equivalent here — and that would need vtab / subquery machinery — are declined: a `MATCH` operator
/// (FTS virtual table) and any subquery (`EXISTS`, scalar `Subquery`, `IN (SELECT ...)` / `IN table`).
/// This is a conservative WHITELIST: any variant not explicitly listed (or a declined child) returns
/// false, so an unrecognized future `Expr` shape keeps the safe sorter path. bd-nonagg-rowid-order-scan
/// (filtered ASC variant).
fn where_is_plain_scan_safe(expr: &Expr) -> bool {
    match expr {
        Expr::Literal(..)
        | Expr::BoundOuterValue { .. }
        | Expr::Column(..)
        | Expr::Placeholder(..) => true,
        Expr::BinaryOp { left, right, .. } => {
            where_is_plain_scan_safe(left) && where_is_plain_scan_safe(right)
        }
        Expr::UnaryOp { expr: inner, .. }
        | Expr::IsNull { expr: inner, .. }
        | Expr::Cast { expr: inner, .. }
        | Expr::Collate { expr: inner, .. } => where_is_plain_scan_safe(inner),
        Expr::Between {
            expr: inner,
            low,
            high,
            ..
        } => {
            where_is_plain_scan_safe(inner)
                && where_is_plain_scan_safe(low)
                && where_is_plain_scan_safe(high)
        }
        Expr::In {
            expr: inner, set, ..
        } => {
            where_is_plain_scan_safe(inner)
                && matches!(set, fsqlite_ast::InSet::List(items) if items.iter().all(where_is_plain_scan_safe))
        }
        Expr::Like {
            expr: inner,
            pattern,
            escape,
            op,
            ..
        } => {
            *op != fsqlite_ast::LikeOp::Match
                && where_is_plain_scan_safe(inner)
                && where_is_plain_scan_safe(pattern)
                && escape.as_deref().is_none_or(where_is_plain_scan_safe)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand.as_deref().is_none_or(where_is_plain_scan_safe)
                && whens.iter().all(|(when_expr, then_expr)| {
                    where_is_plain_scan_safe(when_expr) && where_is_plain_scan_safe(then_expr)
                })
                && else_expr.as_deref().is_none_or(where_is_plain_scan_safe)
        }
        Expr::FunctionCall {
            over: None,
            filter: None,
            args,
            ..
        } => {
            matches!(args, fsqlite_ast::FunctionArgs::List(items) if items.iter().all(where_is_plain_scan_safe))
        }
        Expr::JsonAccess {
            expr: inner, path, ..
        } => where_is_plain_scan_safe(inner) && where_is_plain_scan_safe(path),
        Expr::RowValue(items, _) => items.iter().all(where_is_plain_scan_safe),
        // Declined: Exists, Subquery, Raise, IN (subquery/table), MATCH, window/filtered functions,
        // and any unrecognized variant — all keep the safe sorter path.
        _ => false,
    }
}

fn expr_has_window(expr: &Expr) -> bool {
    match expr {
        Expr::FunctionCall { over: Some(_), .. } => true,
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            ..
        } => {
            matches!(args, fsqlite_ast::FunctionArgs::List(items) if items.iter().any(expr_has_window))
                || order_by.iter().any(|term| expr_has_window(&term.expr))
                || filter.as_deref().is_some_and(expr_has_window)
        }
        Expr::BinaryOp { left, right, .. } => expr_has_window(left) || expr_has_window(right),
        Expr::UnaryOp { expr: inner, .. }
        | Expr::IsNull { expr: inner, .. }
        | Expr::Cast { expr: inner, .. }
        | Expr::Collate { expr: inner, .. } => expr_has_window(inner),
        Expr::Between {
            expr: inner,
            low,
            high,
            ..
        } => expr_has_window(inner) || expr_has_window(low) || expr_has_window(high),
        Expr::In {
            expr: inner, set, ..
        } => {
            expr_has_window(inner)
                || matches!(set, fsqlite_ast::InSet::List(items) if items.iter().any(expr_has_window))
        }
        Expr::Like {
            expr: inner,
            pattern,
            escape,
            ..
        } => {
            expr_has_window(inner)
                || expr_has_window(pattern)
                || escape.as_deref().is_some_and(expr_has_window)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand.as_deref().is_some_and(expr_has_window)
                || whens.iter().any(|(when_expr, then_expr)| {
                    expr_has_window(when_expr) || expr_has_window(then_expr)
                })
                || else_expr.as_deref().is_some_and(expr_has_window)
        }
        Expr::JsonAccess {
            expr: inner, path, ..
        } => expr_has_window(inner) || expr_has_window(path),
        Expr::RowValue(items, _) => items.iter().any(expr_has_window),
        _ => false,
    }
}

/// Check whether an expression contains an aggregate function call.
///
/// Built-in `max(x,y,...)` and `min(x,y,...)` calls with 2+ arguments are
/// scalar unless a custom aggregate registration replaces that exact arity.
fn is_aggregate_function_call(name: &str, args: &FunctionArgs) -> bool {
    let arity = match args {
        FunctionArgs::Star => 0,
        FunctionArgs::List(items) => i32::try_from(items.len()).unwrap_or(i32::MAX),
    };
    if let Some(kind) = FUNCTION_REGISTRY.with(|registry| {
        registry
            .borrow()
            .as_ref()
            .and_then(|registry| registry.resolve_application_function(name, arity))
            .map(|resolution| resolution.kind())
    }) {
        return kind.is_aggregate_callable();
    }
    if custom_aggregate_overrides_builtin(name, arity) {
        return true;
    }
    if !is_aggregate_function(name) {
        return false;
    }

    let lower = name.to_ascii_lowercase();
    !((lower == "max" || lower == "min")
        && matches!(args, fsqlite_ast::FunctionArgs::List(items) if items.len() >= 2))
}

fn custom_aggregate_overrides_builtin(name: &str, arity: i32) -> bool {
    if let Some(application_override) = FUNCTION_REGISTRY.with(|registry| {
        registry.borrow().as_ref().map(|registry| {
            registry
                .resolve_application_function(name, arity)
                .is_some_and(|resolution| resolution.kind().is_aggregate_callable())
        })
    }) {
        return application_override;
    }
    let builtin_has_exact_arity = (name.eq_ignore_ascii_case("count") && matches!(arity, 0 | 1))
        || (name.eq_ignore_ascii_case("string_agg") && arity == 2)
        || (arity == 1
            && ["avg", "max", "median", "min", "sum", "total"]
                .iter()
                .any(|builtin| name.eq_ignore_ascii_case(builtin)))
        || (arity == 2
            && ["percentile", "percentile_cont", "percentile_disc"]
                .iter()
                .any(|builtin| name.eq_ignore_ascii_case(builtin)));
    CUSTOM_AGG_KEYS.with(|keys| {
        keys.borrow().iter().any(|(custom_name, custom_arity)| {
            custom_name.eq_ignore_ascii_case(name)
                && custom_arity.accepts(arity)
                && (custom_arity.declared_args() != -1 || !builtin_has_exact_arity)
        })
    })
}

/// Whether an algebraic shortcut may rely on the named built-in aggregate's
/// exact semantics at this arity.
///
/// Generic aggregate lowering already routes an exact custom registration
/// through `AggStep`/`AggFinal`. Shortcuts such as `Count`, COUNT+SUM fusion,
/// and one-row MIN/MAX leaf seeks bypass part of that protocol and are valid
/// only when the connection has not replaced the corresponding built-in.
fn builtin_aggregate_semantics_available(name: &str, arity: i32) -> bool {
    if FUNCTION_REGISTRY.with(|registry| {
        registry
            .borrow()
            .as_ref()
            .is_some_and(|registry| registry.resolve_application_function(name, arity).is_some())
    }) {
        return false;
    }
    !custom_aggregate_overrides_builtin(name, arity)
}

fn is_aggregate_expr(expr: &Expr) -> bool {
    match expr {
        Expr::FunctionCall { name, args, .. } if is_aggregate_function_call(name, args) => true,
        Expr::BinaryOp { left, right, .. } => is_aggregate_expr(left) || is_aggregate_expr(right),
        Expr::UnaryOp { expr: inner, .. }
        | Expr::IsNull { expr: inner, .. }
        | Expr::Cast { expr: inner, .. }
        | Expr::Collate { expr: inner, .. } => is_aggregate_expr(inner),
        Expr::Between {
            expr: inner,
            low,
            high,
            ..
        } => is_aggregate_expr(inner) || is_aggregate_expr(low) || is_aggregate_expr(high),
        Expr::In {
            expr: inner, set, ..
        } => {
            if is_aggregate_expr(inner) {
                return true;
            }
            match set {
                fsqlite_ast::InSet::List(items) => items.iter().any(is_aggregate_expr),
                _ => false,
            }
        }
        Expr::Like {
            expr: inner,
            pattern,
            escape,
            ..
        } => {
            is_aggregate_expr(inner)
                || is_aggregate_expr(pattern)
                || escape.as_deref().is_some_and(is_aggregate_expr)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            if operand.as_deref().is_some_and(is_aggregate_expr) {
                return true;
            }
            if whens
                .iter()
                .any(|(cond, then_expr)| is_aggregate_expr(cond) || is_aggregate_expr(then_expr))
            {
                return true;
            }
            if else_expr.as_deref().is_some_and(is_aggregate_expr) {
                return true;
            }
            false
        }
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            over,
            ..
        } => {
            matches!(args, FunctionArgs::List(args) if args.iter().any(is_aggregate_expr))
                || order_by.iter().any(|term| is_aggregate_expr(&term.expr))
                || filter.as_deref().is_some_and(is_aggregate_expr)
                || over.as_ref().is_some_and(window_spec_has_aggregate)
        }
        Expr::RowValue(items, _) => items.iter().any(is_aggregate_expr),
        Expr::JsonAccess {
            expr: inner, path, ..
        } => is_aggregate_expr(inner) || is_aggregate_expr(path),
        _ => false,
    }
}

fn window_spec_has_aggregate(spec: &fsqlite_ast::WindowSpec) -> bool {
    spec.partition_by.iter().any(is_aggregate_expr)
        || spec
            .order_by
            .iter()
            .any(|term| is_aggregate_expr(&term.expr))
        || spec.frame.as_ref().is_some_and(|frame| {
            frame_bound_has_aggregate(&frame.start)
                || frame.end.as_ref().is_some_and(frame_bound_has_aggregate)
        })
}

fn frame_bound_has_aggregate(bound: &fsqlite_ast::FrameBound) -> bool {
    match bound {
        fsqlite_ast::FrameBound::Preceding(expr) | fsqlite_ast::FrameBound::Following(expr) => {
            is_aggregate_expr(expr)
        }
        fsqlite_ast::FrameBound::UnboundedPreceding
        | fsqlite_ast::FrameBound::CurrentRow
        | fsqlite_ast::FrameBound::UnboundedFollowing => false,
    }
}

/// Description of one aggregate column for codegen.
struct AggColumn {
    /// Aggregate function name (lowercased).
    name: String,
    /// Number of arguments (0 for count(*), 1 for sum(col), etc.).
    num_args: i32,
    /// Column index of the argument (for single-arg aggregates), or `None` for count(*) or rowid.
    arg_col_index: Option<usize>,
    /// True if the argument is the INTEGER PRIMARY KEY (rowid) column.
    arg_is_rowid: bool,
    /// True if the aggregate uses DISTINCT (e.g. `COUNT(DISTINCT col)`).
    distinct: bool,
    /// Non-column expression argument (e.g. `SUM(a + b)`), evaluated via `emit_expr`.
    /// `None` when arg is a simple column ref (use `arg_col_index` instead).
    arg_expr: Option<Box<Expr>>,
    /// Additional argument expressions beyond the first (e.g. separator for group_concat).
    extra_args: Vec<Expr>,
    /// FILTER clause expression, e.g. `COUNT(*) FILTER (WHERE x > 5)`.
    /// When present, the AggStep is only executed if this evaluates to true.
    filter: Option<Box<Expr>>,
    /// Wrapper expression applied after AggFinal.  Used when a scalar
    /// function wraps an aggregate, e.g. `COALESCE(MAX(x), 0)`.  The
    /// placeholder `Expr::Literal(Literal::Null, _)` marks where the
    /// aggregate result should be substituted.
    wrapper_expr: Option<Box<Expr>>,
    /// If true, this is a hidden aggregate that doesn't map to an output column.
    /// Used for multi-aggregate expressions like `MAX(x) - MIN(x)`.
    hidden: bool,
    /// For multi-aggregate wrappers: the indices (into the agg_columns vec) of
    /// all aggregates referenced by the wrapper expression.  Placeholder columns
    /// `__agg_0__`, `__agg_1__`, … map to these indices.
    multi_agg_indices: Vec<usize>,
    /// Bare (non-aggregate) expression in an aggregate query without GROUP BY.
    /// SQLite allows `SELECT max(x), y FROM t` — `y` takes its value from the
    /// last row scanned.  When set, no AggStep/AggFinal is emitted; instead the
    /// expression is evaluated on each scanned row and stored in the accumulator
    /// register so it retains the value from the final row.
    bare_expr: Option<Box<Expr>>,
    /// Collation sequence for the aggregate argument column (e.g. "NOCASE").
    /// When set and the aggregate is DISTINCT, the VDBE engine uses
    /// collation-aware distinct key encoding.
    collation: Option<String>,
}

/// Determine the effective collation for an aggregate argument expression.
/// Explicit COLLATE in the expression takes priority; otherwise, if the
/// argument resolved to a column index, inherit that column's declared
/// collation.  Returns `None` for the default BINARY collation.
fn expr_collation_for_agg(
    expr: &Expr,
    col_idx: Option<usize>,
    table: &TableSchema,
) -> Option<String> {
    // Explicit COLLATE wrapper takes priority.
    if let Expr::Collate { collation, .. } = expr {
        if !collation.eq_ignore_ascii_case("BINARY") {
            return Some(collation.clone());
        }
        return None;
    }
    if let Some(declared_collation) = bound_outer_declared_collation(expr) {
        return (!declared_collation.eq_ignore_ascii_case("BINARY"))
            .then(|| declared_collation.to_owned());
    }
    // Column reference: inherit from schema.
    if let Some(idx) = col_idx
        && let Some(ci) = table.columns.get(idx)
        && let Some(coll) = &ci.collation
        && !coll.eq_ignore_ascii_case("BINARY")
    {
        return Some(coll.clone());
    }
    None
}

/// Build the P4 payload for an AggStep opcode, including collation if present.
fn agg_func_p4(name: &str, collation: Option<&String>) -> P4 {
    if let Some(coll) = collation {
        P4::FuncNameCollated(name.to_owned(), coll.clone())
    } else {
        P4::FuncName(name.to_owned())
    }
}

struct GroupedInnerJoinCountSumPlan<'a> {
    left_table: &'a TableSchema,
    left_alias: Option<&'a str>,
    right_table: &'a TableSchema,
    right_alias: Option<&'a str>,
    group_key_expr: &'a Expr,
    sum_arg_expr: &'a Expr,
    join_lookup: SingleJoinLookupPlan<'a>,
}

fn grouped_inner_join_count_sum_plan<'a>(
    stmt: &'a SelectStatement,
    from: &'a FromClause,
    schema: &'a [TableSchema],
) -> Result<Option<GroupedInnerJoinCountSumPlan<'a>>, CodegenError> {
    use fsqlite_ast::{FunctionArgs, JoinConstraint, JoinKind, TableOrSubquery};

    if !builtin_aggregate_semantics_available("count", 0)
        || !builtin_aggregate_semantics_available("sum", 1)
    {
        return Ok(None);
    }

    let SelectCore::Select {
        columns,
        where_clause,
        group_by,
        having,
        distinct,
        ..
    } = &stmt.body.select
    else {
        return Ok(None);
    };

    if from.joins.len() != 1
        || columns.len() != 3
        || group_by.len() != 1
        || stmt.with.is_some()
        || !stmt.body.compounds.is_empty()
        || where_clause.is_some()
        || having.is_some()
        || !stmt.order_by.is_empty()
        || stmt.limit.is_some()
        || *distinct != Distinctness::All
        || has_window_columns(columns)
    {
        return Ok(None);
    }

    let TableOrSubquery::Table {
        name: left_name,
        alias: left_alias,
        time_travel: None,
        ..
    } = &from.source
    else {
        return Ok(None);
    };
    let join = &from.joins[0];
    if join.join_type.kind != JoinKind::Inner || join.join_type.natural {
        return Ok(None);
    }
    let TableOrSubquery::Table {
        name: right_name,
        alias: right_alias,
        time_travel: None,
        ..
    } = &join.table
    else {
        return Ok(None);
    };
    let Some(JoinConstraint::On(on_expr)) = join.constraint.as_ref() else {
        return Ok(None);
    };
    let Expr::BinaryOp {
        left: on_left,
        op: BinaryOp::Eq,
        right: on_right,
        ..
    } = on_expr
    else {
        return Ok(None);
    };
    let (Expr::Column(on_left_col, _), Expr::Column(on_right_col, _)) = (&**on_left, &**on_right)
    else {
        return Ok(None);
    };
    if on_left_col.table.is_none() || on_right_col.table.is_none() {
        return Ok(None);
    }

    let ResultColumn::Expr {
        expr: group_key_expr,
        ..
    } = &columns[0]
    else {
        return Ok(None);
    };
    let Expr::Column(group_key_col, _) = group_key_expr else {
        return Ok(None);
    };
    let Expr::Column(group_by_col, _) = &group_by[0] else {
        return Ok(None);
    };
    if group_key_col.table.is_none()
        || group_by_col.table.is_none()
        || !group_key_col
            .column
            .eq_ignore_ascii_case(&group_by_col.column)
        || !group_key_col
            .table
            .as_deref()
            .zip(group_by_col.table.as_deref())
            .is_some_and(|(left, right)| left.eq_ignore_ascii_case(right))
    {
        return Ok(None);
    }

    let ResultColumn::Expr {
        expr: count_expr, ..
    } = &columns[1]
    else {
        return Ok(None);
    };
    match count_expr {
        Expr::FunctionCall {
            name,
            args: FunctionArgs::Star,
            distinct: false,
            order_by,
            filter: None,
            over: None,
            ..
        } if name.eq_ignore_ascii_case("count") && order_by.is_empty() => {}
        _ => return Ok(None),
    }

    let ResultColumn::Expr { expr: sum_expr, .. } = &columns[2] else {
        return Ok(None);
    };
    let sum_arg_expr = match sum_expr {
        Expr::FunctionCall {
            name,
            args: FunctionArgs::List(args),
            distinct: false,
            order_by,
            filter: None,
            over: None,
            ..
        } if name.eq_ignore_ascii_case("sum") && order_by.is_empty() && args.len() == 1 => &args[0],
        _ => return Ok(None),
    };
    let Expr::Column(sum_arg_col, _) = sum_arg_expr else {
        return Ok(None);
    };
    if sum_arg_col.table.is_none() {
        return Ok(None);
    }

    let left_table = find_table(schema, &left_name.name)?;
    let right_table = find_table(schema, &right_name.name)?;
    // The lookup lane fetches rows via IdxRowid + SeekRowid, which assumes
    // rowid-table index format; WITHOUT ROWID index entries carry a PK suffix
    // instead (bd-rjaff), so fall back to the generic join path.
    if left_table.without_rowid || right_table.without_rowid {
        return Ok(None);
    }
    let tables = [
        (left_table, left_alias.as_deref()),
        (right_table, right_alias.as_deref()),
    ];
    let (group_cursor, group_col_idx) = resolve_join_column(
        group_key_col.table.as_deref(),
        &group_key_col.column,
        &tables,
    )?;
    let group_col = &tables[group_cursor as usize].0.columns[group_col_idx];
    if group_col
        .collation
        .as_deref()
        .is_some_and(|collation| !collation.eq_ignore_ascii_case("BINARY"))
    {
        return Ok(None);
    }

    let _ = resolve_join_column(sum_arg_col.table.as_deref(), &sum_arg_col.column, &tables)?;
    let Some(join_lookup) = resolve_single_join_lookup_plan(
        left_table,
        left_alias.as_deref(),
        right_table,
        right_alias.as_deref(),
        JoinKind::Inner,
        Some(on_expr),
    ) else {
        return Ok(None);
    };

    Ok(Some(GroupedInnerJoinCountSumPlan {
        left_table,
        left_alias: left_alias.as_deref(),
        right_table,
        right_alias: right_alias.as_deref(),
        group_key_expr,
        sum_arg_expr,
        join_lookup,
    }))
}

#[allow(clippy::too_many_lines)]
fn codegen_grouped_inner_join_count_sum_select(
    b: &mut ProgramBuilder,
    plan: &GroupedInnerJoinCountSumPlan<'_>,
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    let end_label = b.emit_label();
    let done_label = b.emit_label();

    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);

    let out_regs = b.alloc_regs(3);
    let left_cursor = 0_i32;
    let right_cursor = 1_i32;
    let index_cursor = if let SingleJoinLookupTarget::Index(index) = &plan.join_lookup.lookup_target
    {
        let cursor = 2_i32;
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            index.root_page,
            0,
            P4::Index(index.name.clone()),
            0,
        );
        Some(cursor)
    } else {
        None
    };
    let sorter_cursor = if index_cursor.is_some() { 3_i32 } else { 2_i32 };
    let tables = [
        (plan.left_table, plan.left_alias),
        (plan.right_table, plan.right_alias),
    ];

    b.emit_op(
        Opcode::OpenRead,
        left_cursor,
        plan.left_table.root_page,
        0,
        P4::Table(plan.left_table.name.clone()),
        0,
    );
    b.emit_op(
        Opcode::OpenRead,
        right_cursor,
        plan.right_table.root_page,
        0,
        P4::Table(plan.right_table.name.clone()),
        0,
    );
    b.emit_op(
        Opcode::SorterOpen,
        sorter_cursor,
        2,
        0,
        P4::Str("+".to_owned()),
        0,
    );

    let next_left_label = b.emit_label();
    let scan_done = b.emit_label();
    b.emit_jump_to_label(Opcode::Rewind, left_cursor, 0, scan_done, P4::None, 0);
    b.resolve_label(next_left_label);

    match &plan.join_lookup.lookup_target {
        SingleJoinLookupTarget::Rowid => {
            let probe_reg = b.alloc_reg();
            emit_join_probe_source(
                b,
                left_cursor,
                plan.left_table,
                plan.left_alias,
                &plan.join_lookup.probe_source,
                probe_reg,
            );
            let no_match = b.emit_label();
            b.emit_jump_to_label(Opcode::IsNull, probe_reg, 0, no_match, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                right_cursor,
                probe_reg,
                no_match,
                P4::None,
                0,
            );
            emit_grouped_join_sorter_insert(
                b,
                sorter_cursor,
                plan.group_key_expr,
                plan.sum_arg_expr,
                &tables,
                ctx,
            )?;
            b.resolve_label(no_match);
        }
        SingleJoinLookupTarget::Index(_index) => {
            let idx_cursor =
                index_cursor.expect("grouped index lookup join must open index cursor");
            let probe_base = b.alloc_regs(2);
            let probe_reg = probe_base;
            let min_rowid_reg = probe_base + 1;
            let comparison_p4 = direct_lookup_index_comparison_p4(_index);
            emit_join_probe_source(
                b,
                left_cursor,
                plan.left_table,
                plan.left_alias,
                &plan.join_lookup.probe_source,
                probe_reg,
            );
            let no_match = b.emit_label();
            let duplicate_run_done = b.emit_label();
            b.emit_jump_to_label(Opcode::IsNull, probe_reg, 0, no_match, P4::None, 0);
            b.emit_op(Opcode::Int64, 0, min_rowid_reg, 0, P4::Int64(i64::MIN), 0);
            let probe_record_reg = b.alloc_reg();
            b.emit_op(
                Opcode::MakeRecord,
                probe_base,
                2,
                probe_record_reg,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::SeekGE,
                idx_cursor,
                probe_record_reg,
                no_match,
                P4::None,
                0,
            );
            let idx_loop_top = b.current_addr();
            let idx_key_reg = b.alloc_reg();
            b.emit_op(Opcode::Column, idx_cursor, 0, idx_key_reg, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::Ne,
                probe_reg,
                idx_key_reg,
                duplicate_run_done,
                comparison_p4,
                0,
            );
            let rowid_reg = b.alloc_reg();
            b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
            let idx_advance = b.emit_label();
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                right_cursor,
                rowid_reg,
                idx_advance,
                P4::None,
                0,
            );
            emit_grouped_join_sorter_insert(
                b,
                sorter_cursor,
                plan.group_key_expr,
                plan.sum_arg_expr,
                &tables,
                ctx,
            )?;
            b.resolve_label(idx_advance);
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let idx_loop_body = idx_loop_top as i32;
            b.emit_op(Opcode::Next, idx_cursor, idx_loop_body, 0, P4::None, 0);
            b.resolve_label(duplicate_run_done);
            b.resolve_label(no_match);
        }
    }

    b.emit_jump_to_label(Opcode::Next, left_cursor, 0, next_left_label, P4::None, 0);
    b.resolve_label(scan_done);
    if let Some(idx_cursor) = index_cursor {
        b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Close, right_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Close, left_cursor, 0, 0, P4::None, 0);

    let cur_key_reg = b.alloc_reg();
    let prev_key_reg = b.alloc_reg();
    let count_accum_reg = b.alloc_reg();
    let sum_accum_reg = b.alloc_reg();
    let first_flag_reg = b.alloc_reg();

    b.emit_op(Opcode::Integer, 1, first_flag_reg, 0, P4::None, 0);
    b.emit_op(Opcode::Null, 0, count_accum_reg, 0, P4::None, 0);
    b.emit_op(Opcode::Null, 0, sum_accum_reg, 0, P4::None, 0);
    b.emit_jump_to_label(
        Opcode::SorterSort,
        sorter_cursor,
        0,
        done_label,
        P4::None,
        0,
    );

    let sort_loop_body = b.current_addr();
    let sorted_reg = b.alloc_reg();
    b.emit_op(
        Opcode::SorterData,
        sorter_cursor,
        sorted_reg,
        0,
        P4::None,
        0,
    );
    b.emit_op(Opcode::Column, sorter_cursor, 0, cur_key_reg, P4::None, 0);

    let first_row_label = b.emit_label();
    b.emit_jump_to_label(
        Opcode::IfPos,
        first_flag_reg,
        1,
        first_row_label,
        P4::None,
        0,
    );

    let new_group_label = b.emit_label();
    let same_group_label = b.emit_label();
    b.emit_jump_to_label(
        Opcode::Ne,
        cur_key_reg,
        prev_key_reg,
        new_group_label,
        P4::None,
        0x80,
    );
    b.emit_jump_to_label(Opcode::Goto, 0, 0, same_group_label, P4::None, 0);

    b.resolve_label(new_group_label);
    b.emit_op(
        Opcode::AggFinal,
        count_accum_reg,
        0,
        0,
        P4::FuncName("COUNT".to_owned()),
        0,
    );
    b.emit_op(
        Opcode::AggFinal,
        sum_accum_reg,
        1,
        0,
        P4::FuncName("SUM".to_owned()),
        0,
    );
    b.emit_op(Opcode::Copy, prev_key_reg, out_regs, 0, P4::None, 0);
    b.emit_op(Opcode::Copy, count_accum_reg, out_regs + 1, 0, P4::None, 0);
    b.emit_op(Opcode::Copy, sum_accum_reg, out_regs + 2, 0, P4::None, 0);
    b.emit_op(Opcode::ResultRow, out_regs, 3, 0, P4::None, 0);
    b.emit_op(Opcode::Null, 0, count_accum_reg, 0, P4::None, 0);
    b.emit_op(Opcode::Null, 0, sum_accum_reg, 0, P4::None, 0);

    b.resolve_label(first_row_label);
    b.resolve_label(same_group_label);
    b.emit_op(Opcode::Copy, cur_key_reg, prev_key_reg, 0, P4::None, 0);
    b.emit_op(
        Opcode::AggStep,
        0,
        0,
        count_accum_reg,
        P4::FuncName("COUNT".to_owned()),
        0,
    );
    let sum_arg_reg = b.alloc_reg();
    b.emit_op(Opcode::Column, sorter_cursor, 1, sum_arg_reg, P4::None, 0);
    b.emit_op(
        Opcode::AggStep,
        0,
        sum_arg_reg,
        sum_accum_reg,
        P4::FuncName("SUM".to_owned()),
        1,
    );
    b.emit_op(
        Opcode::SorterNext,
        sorter_cursor,
        sort_loop_body as i32,
        0,
        P4::None,
        0,
    );

    b.emit_jump_to_label(Opcode::IfPos, first_flag_reg, 0, done_label, P4::None, 0);
    b.emit_op(
        Opcode::AggFinal,
        count_accum_reg,
        0,
        0,
        P4::FuncName("COUNT".to_owned()),
        0,
    );
    b.emit_op(
        Opcode::AggFinal,
        sum_accum_reg,
        1,
        0,
        P4::FuncName("SUM".to_owned()),
        0,
    );
    b.emit_op(Opcode::Copy, prev_key_reg, out_regs, 0, P4::None, 0);
    b.emit_op(Opcode::Copy, count_accum_reg, out_regs + 1, 0, P4::None, 0);
    b.emit_op(Opcode::Copy, sum_accum_reg, out_regs + 2, 0, P4::None, 0);
    b.emit_op(Opcode::ResultRow, out_regs, 3, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, sorter_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);

    Ok(())
}

/// Generate VDBE bytecode for a standalone `VALUES` clause.
///
/// Pattern: `Init → Transaction → [for each row: eval exprs → ResultRow] → Halt`
#[derive(Clone)]
enum SingleJoinLookupTarget<'a> {
    Rowid,
    Index(&'a IndexSchema),
}

struct SingleJoinLookupPlan<'a> {
    join_kind: fsqlite_ast::JoinKind,
    probe_source: SortKeySource,
    lookup_target: SingleJoinLookupTarget<'a>,
}

fn resolve_single_join_lookup_plan<'a>(
    left_table: &'a TableSchema,
    left_alias: Option<&'a str>,
    right_table: &'a TableSchema,
    right_alias: Option<&'a str>,
    join_kind: fsqlite_ast::JoinKind,
    on_expr: Option<&'a Expr>,
) -> Option<SingleJoinLookupPlan<'a>> {
    // The lookup lane fetches rows via IdxRowid + SeekRowid, which assumes
    // rowid-table index format; WITHOUT ROWID index entries carry a PK suffix
    // instead (bd-rjaff), so fall back to the generic join path.
    if left_table.without_rowid || right_table.without_rowid {
        return None;
    }
    let on_expr = on_expr?;
    let Expr::BinaryOp {
        left,
        op: fsqlite_ast::BinaryOp::Eq,
        right,
        ..
    } = on_expr
    else {
        return None;
    };

    let (probe_source, lookup_source) = if let (Some(left_probe), Some(right_lookup)) = (
        resolve_column_ref(left, left_table, left_alias),
        resolve_column_ref(right, right_table, right_alias),
    ) {
        (left_probe, right_lookup)
    } else if let (Some(left_lookup), Some(right_probe)) = (
        resolve_column_ref(left, right_table, right_alias),
        resolve_column_ref(right, left_table, left_alias),
    ) {
        (right_probe, left_lookup)
    } else {
        return None;
    };

    let lookup_target = match lookup_source {
        SortKeySource::Rowid => SingleJoinLookupTarget::Rowid,
        SortKeySource::Column(col_idx) => {
            let column_name = &right_table.columns.get(col_idx)?.name;
            let comparison_tables = [(left_table, left_alias), (right_table, right_alias)];
            let comparison_collation =
                join_lookup_effective_collation(left, right, &comparison_tables);
            // The single-join direct-lookup path only materializes the join key
            // plus a rowid sentinel. Composite indexes need values for their
            // trailing key terms, so reusing them here can skip valid rows.
            let index = right_table
                .single_column_index_for_column_with_collation(column_name, comparison_collation)?;
            SingleJoinLookupTarget::Index(index)
        }
        SortKeySource::Expression(_) => return None,
    };

    Some(SingleJoinLookupPlan {
        join_kind,
        probe_source,
        lookup_target,
    })
}

fn emit_join_probe_source(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    source: &SortKeySource,
    target_reg: i32,
) {
    let scan = ScanCtx {
        cursor,
        table,
        table_alias,
        schema: None,
        register_base: None,
        secondaries: &[],
    };
    emit_resolved_column(b, source, cursor, target_reg, &scan);
}

fn emit_grouped_join_sorter_insert(
    b: &mut ProgramBuilder,
    sorter_cursor: i32,
    group_key_expr: &Expr,
    sum_arg_expr: &Expr,
    tables: &[(&TableSchema, Option<&str>)],
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    let sorter_base = b.alloc_regs(2);
    emit_join_expr(b, group_key_expr, sorter_base, tables, ctx)?;
    emit_join_expr(b, sum_arg_expr, sorter_base + 1, tables, ctx)?;
    let sorter_record = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        sorter_base,
        2,
        sorter_record,
        P4::None,
        0,
    );
    b.emit_op(
        Opcode::SorterInsert,
        sorter_cursor,
        sorter_record,
        0,
        P4::None,
        0,
    );
    Ok(())
}

fn join_lookup_effective_collation<'a>(
    left: &'a Expr,
    right: &'a Expr,
    tables: &[(&'a TableSchema, Option<&'a str>)],
) -> Option<&'a str> {
    join_comparison_collation_name(left, right, tables)
}

fn direct_lookup_index_collation_matches_join(
    index: &IndexSchema,
    comparison_collation: Option<&str>,
) -> bool {
    collation_names_equivalent(comparison_collation, index.key_term_collation(0))
}

fn direct_lookup_index_comparison_p4(index: &IndexSchema) -> P4 {
    index
        .key_term_collation(0)
        .filter(|collation| !collation.eq_ignore_ascii_case("BINARY"))
        .map_or(P4::None, |collation| P4::Collation(collation.to_owned()))
}

fn emit_join_output_or_sort(
    b: &mut ProgramBuilder,
    columns: &[ResultColumn],
    out_regs: i32,
    tables: &[(&TableSchema, Option<&str>)],
    ctx: &CodegenContext,
    sorter: Option<(i32, i32, usize, i32)>,
    order_by: &[OrderingTerm],
) -> Result<(), CodegenError> {
    let out_col_count = resolve_join_output_count(columns, tables);
    emit_join_result_columns(b, columns, out_regs, tables, ctx)?;
    if let Some((sort_cursor, sort_regs, sort_key_count, sort_record_reg)) = sorter {
        for (i, term) in order_by.iter().enumerate() {
            let sort_reg = sort_regs + i as i32;
            emit_join_expr(b, &term.expr, sort_reg, tables, ctx)?;
        }
        for i in 0..out_col_count {
            let src = out_regs + i as i32;
            let dst = sort_regs + (sort_key_count + i) as i32;
            b.emit_op(Opcode::SCopy, src, dst, 0, P4::None, 0);
        }
        b.emit_op(
            Opcode::MakeRecord,
            sort_regs,
            (sort_key_count + out_col_count) as i32,
            sort_record_reg,
            P4::None,
            0,
        );
        b.emit_op(
            Opcode::SorterInsert,
            sort_cursor,
            sort_record_reg,
            0,
            P4::None,
            0,
        );
    } else {
        b.emit_op(
            Opcode::ResultRow,
            out_regs,
            out_col_count as i32,
            0,
            P4::None,
            0,
        );
    }
    Ok(())
}

#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_single_join_lookup_select(
    b: &mut ProgramBuilder,
    stmt: &SelectStatement,
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    left_table: &TableSchema,
    left_alias: Option<&str>,
    right_table: &TableSchema,
    right_alias: Option<&str>,
    plan: &SingleJoinLookupPlan<'_>,
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    let end_label = b.emit_label();
    let done_label = b.emit_label();
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);

    let tables = [(left_table, left_alias), (right_table, right_alias)];
    let out_col_count = resolve_join_output_count(columns, &tables);
    let out_regs = b.alloc_regs(out_col_count as i32);

    let left_cursor = 0_i32;
    let right_cursor = 1_i32;
    b.emit_op(
        Opcode::OpenRead,
        left_cursor,
        left_table.root_page,
        0,
        P4::Table(left_table.name.clone()),
        0,
    );
    b.emit_op(
        Opcode::OpenRead,
        right_cursor,
        right_table.root_page,
        0,
        P4::Table(right_table.name.clone()),
        0,
    );
    let index_cursor = if let SingleJoinLookupTarget::Index(index) = &plan.lookup_target {
        let cursor = 2_i32;
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            index.root_page,
            0,
            P4::Index(index.name.clone()),
            0,
        );
        Some(cursor)
    } else {
        None
    };

    let sorter = if !stmt.order_by.is_empty() {
        let sort_cursor = if index_cursor.is_some() { 3_i32 } else { 2_i32 };
        let sort_key_count = stmt.order_by.len();
        let total_sort_cols = sort_key_count + out_col_count;
        let sort_regs = b.alloc_regs(total_sort_cols as i32);
        let sort_record_reg = b.alloc_reg();
        let sort_order = stmt
            .order_by
            .iter()
            .map(|term| {
                if term.direction == Some(fsqlite_ast::SortDirection::Desc) {
                    '-'
                } else {
                    '+'
                }
            })
            .collect::<String>();
        b.emit_op(
            Opcode::SorterOpen,
            sort_cursor,
            total_sort_cols as i32,
            0,
            P4::Affinity(sort_order),
            0,
        );
        Some((sort_cursor, sort_regs, sort_key_count, sort_record_reg))
    } else {
        None
    };

    let next_left_label = b.emit_label();
    b.emit_jump_to_label(Opcode::Rewind, left_cursor, 0, done_label, P4::None, 0);
    b.resolve_label(next_left_label);
    let left_join_match_reg = if matches!(plan.join_kind, fsqlite_ast::JoinKind::Left) {
        let reg = b.alloc_temp();
        b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
        Some(reg)
    } else {
        None
    };

    match &plan.lookup_target {
        SingleJoinLookupTarget::Rowid => {
            let probe_reg = b.alloc_reg();
            emit_join_probe_source(
                b,
                left_cursor,
                left_table,
                left_alias,
                &plan.probe_source,
                probe_reg,
            );
            let no_match = b.emit_label();
            b.emit_jump_to_label(Opcode::IsNull, probe_reg, 0, no_match, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                right_cursor,
                probe_reg,
                no_match,
                P4::None,
                0,
            );
            if let Some(match_reg) = left_join_match_reg {
                b.emit_op(Opcode::Integer, 1, match_reg, 0, P4::None, 0);
            }
            let matched_skip = b.emit_label();
            if let Some(where_expr) = where_clause {
                let cond_reg = b.alloc_reg();
                emit_join_expr(b, where_expr, cond_reg, &tables, ctx)?;
                b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, matched_skip, P4::None, 0);
            }
            emit_join_output_or_sort(b, columns, out_regs, &tables, ctx, sorter, &stmt.order_by)?;
            b.resolve_label(matched_skip);
            b.resolve_label(no_match);
        }
        SingleJoinLookupTarget::Index(_index) => {
            let idx_cursor = index_cursor.expect("index lookup join must open index cursor");
            let probe_base = b.alloc_regs(2);
            let probe_reg = probe_base;
            let min_rowid_reg = probe_base + 1;
            let comparison_p4 = direct_lookup_index_comparison_p4(_index);
            emit_join_probe_source(
                b,
                left_cursor,
                left_table,
                left_alias,
                &plan.probe_source,
                probe_reg,
            );
            let no_match = b.emit_label();
            let duplicate_run_done = b.emit_label();
            b.emit_jump_to_label(Opcode::IsNull, probe_reg, 0, no_match, P4::None, 0);
            b.emit_op(Opcode::Int64, 0, min_rowid_reg, 0, P4::Int64(i64::MIN), 0);
            let probe_record_reg = b.alloc_reg();
            b.emit_op(
                Opcode::MakeRecord,
                probe_base,
                2,
                probe_record_reg,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::SeekGE,
                idx_cursor,
                probe_record_reg,
                no_match,
                P4::None,
                0,
            );
            let idx_loop_top = b.current_addr();
            let idx_key_reg = b.alloc_reg();
            b.emit_op(Opcode::Column, idx_cursor, 0, idx_key_reg, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::Ne,
                probe_reg,
                idx_key_reg,
                duplicate_run_done,
                comparison_p4,
                0,
            );
            let rowid_reg = b.alloc_reg();
            b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
            let idx_advance = b.emit_label();
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                right_cursor,
                rowid_reg,
                idx_advance,
                P4::None,
                0,
            );
            if let Some(match_reg) = left_join_match_reg {
                b.emit_op(Opcode::Integer, 1, match_reg, 0, P4::None, 0);
            }
            if let Some(where_expr) = where_clause {
                let cond_reg = b.alloc_reg();
                emit_join_expr(b, where_expr, cond_reg, &tables, ctx)?;
                b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, idx_advance, P4::None, 0);
            }
            emit_join_output_or_sort(b, columns, out_regs, &tables, ctx, sorter, &stmt.order_by)?;
            b.resolve_label(idx_advance);
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let idx_loop_body = idx_loop_top as i32;
            b.emit_op(Opcode::Next, idx_cursor, idx_loop_body, 0, P4::None, 0);
            b.resolve_label(duplicate_run_done);
            b.resolve_label(no_match);
        }
    }

    if let Some(match_reg) = left_join_match_reg {
        let skip_left_join_null_row = b.emit_label();
        b.emit_jump_to_label(
            Opcode::IfPos,
            match_reg,
            0,
            skip_left_join_null_row,
            P4::None,
            0,
        );
        b.emit_op(Opcode::NullRow, right_cursor, 0, 0, P4::None, 0);
        if let Some(where_expr) = where_clause {
            let cond_reg = b.alloc_reg();
            emit_join_expr(b, where_expr, cond_reg, &tables, ctx)?;
            b.emit_jump_to_label(
                Opcode::IfNot,
                cond_reg,
                1,
                skip_left_join_null_row,
                P4::None,
                0,
            );
        }
        emit_join_output_or_sort(b, columns, out_regs, &tables, ctx, sorter, &stmt.order_by)?;
        b.resolve_label(skip_left_join_null_row);
    }

    b.emit_jump_to_label(Opcode::Next, left_cursor, 0, next_left_label, P4::None, 0);
    b.resolve_label(done_label);

    if let Some((sort_cursor, sort_regs, sort_key_count, _sort_record_reg)) = sorter {
        let sort_loop = b.emit_label();
        let sort_done = b.emit_label();
        b.emit_jump_to_label(Opcode::SorterSort, sort_cursor, 0, sort_done, P4::None, 0);
        b.resolve_label(sort_loop);
        b.emit_op(Opcode::SorterData, sort_cursor, sort_regs, 0, P4::None, 0);
        for i in 0..out_col_count {
            let dst = out_regs + i as i32;
            b.emit_op(
                Opcode::Column,
                sort_cursor,
                (sort_key_count + i) as i32,
                dst,
                P4::None,
                0,
            );
        }
        b.emit_op(
            Opcode::ResultRow,
            out_regs,
            out_col_count as i32,
            0,
            P4::None,
            0,
        );
        b.emit_jump_to_label(Opcode::SorterNext, sort_cursor, 0, sort_loop, P4::None, 0);
        b.resolve_label(sort_done);
        b.emit_op(Opcode::Close, sort_cursor, 0, 0, P4::None, 0);
    }

    if let Some(idx_cursor) = index_cursor {
        b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Close, right_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Close, left_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Plan for a multi-table join where every right-side table can be reached
/// via a single-row lookup (rowid or indexed equality) against columns
/// already bound by an earlier table in the chain.
///
/// This is the generalisation of [`SingleJoinLookupPlan`] to N tables and
/// is the key fast-path for the kind of "fact table joined to multiple
/// dimension tables" query that the FTS rebuild in bd_zjisk issue #62
/// hits: scanning the single largest table once and doing O(1) index
/// seeks into every dimension table turns a 4-table Cartesian blowup
/// (reported at 600× the C SQLite baseline) into O(N) work.
struct MultiJoinLookupPlan<'a> {
    steps: Vec<MultiJoinLookupStep<'a>>,
}

struct MultiJoinLookupStep<'a> {
    join_kind: fsqlite_ast::JoinKind,
    /// Which already-introduced table (0 = driver / left_table,
    /// 1..=i = join_tables[0..i]) carries the probe expression.
    probe_table_index: usize,
    probe_source: SortKeySource,
    lookup_target: SingleJoinLookupTarget<'a>,
}

/// Try to resolve every join in the chain to a single-row lookup against
/// an earlier table.  Returns `None` if any join cannot be expressed as a
/// lookup — in that case the caller falls back to the existing nested-
/// loop `Rewind`/`Next` scan path.
///
/// Restrictions (conservatively applied):
/// - Every join must be INNER or LEFT.
/// - Every join's ON clause must be a single `expr_a = expr_b` BinaryOp,
///   where one side is a column of the new right table (the lookup
///   target) and the other is a column of an already-bound table
///   (the probe source).
/// - The lookup target must be the rowid (INTEGER PRIMARY KEY) or a
///   single-column index on the right table.
/// - **At most one LEFT JOIN is allowed, and it must be the final step
///   in the chain.**  Anything else is refused so the codegen below can
///   emit a single trailing null-row block without having to re-run
///   later steps with a NullRow-poisoned probe cursor — which is
///   genuinely hard to get right in the general case and is not needed
///   for the bd_zjisk issue #62 repro (that query is INNER + INNER +
///   terminal LEFT).  Non-terminal LEFT JOINs and chains with more
///   than one LEFT fall back to the scan path.
fn resolve_multi_join_lookup_plan<'a>(
    left_table: &'a TableSchema,
    left_alias: Option<&'a str>,
    join_tables: &'a [(
        &'a TableSchema,
        Option<String>,
        fsqlite_ast::JoinKind,
        Option<&'a Expr>,
    )],
) -> Option<MultiJoinLookupPlan<'a>> {
    use fsqlite_ast::{BinaryOp, JoinKind};

    // We need at least one join — the single-join path handles the 1
    // case already with its own (sort-capable) codegen.
    if join_tables.len() < 2 {
        return None;
    }

    // The lookup lane fetches rows via IdxRowid + SeekRowid, which assumes
    // rowid-table index format; WITHOUT ROWID index entries carry a PK suffix
    // instead (bd-rjaff), so fall back to the generic join path.
    if left_table.without_rowid || join_tables.iter().any(|(table, ..)| table.without_rowid) {
        return None;
    }

    // Build the running table list so each step can resolve its probe
    // against any already-bound table.
    let mut tables: Vec<(&'a TableSchema, Option<&'a str>)> =
        Vec::with_capacity(join_tables.len() + 1);
    tables.push((left_table, left_alias));

    let mut steps: Vec<MultiJoinLookupStep<'a>> = Vec::with_capacity(join_tables.len());
    let last_index = join_tables.len() - 1;

    for (step_idx, (right_table, right_alias_opt, join_kind, on_expr)) in
        join_tables.iter().enumerate()
    {
        match join_kind {
            JoinKind::Inner => {}
            // Only the final step in the chain may be a LEFT JOIN — see
            // the doc comment above.  A LEFT miss jumps to a trailing
            // null-row block that emits the row with NULLs for the
            // left-joined table's columns and then runs the outer Next.
            // Allowing a non-terminal LEFT JOIN would require re-running
            // the rest of the chain from that null-row block against the
            // remaining probe cursors, which the current code does not
            // implement.
            JoinKind::Left if step_idx == last_index => {}
            _ => return None,
        }
        let on_expr = (*on_expr)?;
        let Expr::BinaryOp {
            left,
            op: BinaryOp::Eq,
            right,
            ..
        } = on_expr
        else {
            return None;
        };

        let right_alias = right_alias_opt.as_deref();
        let mut found: Option<(usize, SortKeySource, SortKeySource)> = None;

        // Try each already-bound table as the probe source; first hit wins.
        // Because LEFT JOINs are only allowed as the terminal step, no
        // already-bound table in this loop can be a LEFT-joined table —
        // we therefore do not need to track LEFT-joined state separately.
        for (probe_idx, (probe_table, probe_alias)) in tables.iter().enumerate() {
            if let (Some(left_probe), Some(right_lookup)) = (
                resolve_column_ref(left, probe_table, *probe_alias),
                resolve_column_ref(right, right_table, right_alias),
            ) {
                found = Some((probe_idx, left_probe, right_lookup));
                break;
            }
            if let (Some(left_lookup), Some(right_probe)) = (
                resolve_column_ref(left, right_table, right_alias),
                resolve_column_ref(right, probe_table, *probe_alias),
            ) {
                found = Some((probe_idx, right_probe, left_lookup));
                break;
            }
        }

        let (probe_table_index, probe_source, lookup_source) = found?;
        let comparison_tables = tables
            .iter()
            .copied()
            .chain(std::iter::once((*right_table, right_alias)))
            .collect::<Vec<_>>();
        let comparison_collation = join_lookup_effective_collation(left, right, &comparison_tables);

        let lookup_target = match lookup_source {
            SortKeySource::Rowid => SingleJoinLookupTarget::Rowid,
            SortKeySource::Column(col_idx) => {
                let column_name = &right_table.columns.get(col_idx)?.name;
                // The multi-join fast path is only correct when the probe key
                // yields at most one row. Pick any direct-lookup single-column
                // UNIQUE index on the join key instead of blindly taking the
                // first leftmost-column index; otherwise a preceding non-unique
                // sibling index would disable the fast path even when a safe
                // unique lookup exists.
                let index = right_table
                    .unique_single_column_index_for_column(column_name, comparison_collation)?;
                SingleJoinLookupTarget::Index(index)
            }
            SortKeySource::Expression(_) => return None,
        };

        steps.push(MultiJoinLookupStep {
            join_kind: *join_kind,
            probe_table_index,
            probe_source,
            lookup_target,
        });

        // Record the new table in the accumulator before the next step
        // resolves its probe.
        tables.push((right_table, right_alias));
    }

    Some(MultiJoinLookupPlan { steps })
}

/// Emit bytecode for a multi-join query where every join is a single-row
/// lookup.  The outer loop rewinds the driver once and, inside the loop
/// body, every right-side table is reached with a direct `SeekRowid`
/// (rowid lookup) or `SeekGE` on an index cursor — no nested Rewind/Next
/// loops.  This is the O(N) fast path that avoids the Cartesian blowup
/// in the general `codegen_join_select` scan path.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_multi_join_lookup_select(
    b: &mut ProgramBuilder,
    stmt: &SelectStatement,
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    left_table: &TableSchema,
    left_alias: Option<&str>,
    join_tables: &[(
        &TableSchema,
        Option<String>,
        fsqlite_ast::JoinKind,
        Option<&Expr>,
    )],
    plan: &MultiJoinLookupPlan<'_>,
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    use fsqlite_ast::JoinKind;

    debug_assert_eq!(plan.steps.len(), join_tables.len());

    let end_label = b.emit_label();
    let done_label = b.emit_label();
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);

    // Build the table slice that emit_join_expr / emit_join_result_columns
    // use for register resolution.  Table index i ↔ cursor id i.
    let all_tables: Vec<(&TableSchema, Option<&str>)> = std::iter::once((left_table, left_alias))
        .chain(join_tables.iter().map(|(t, a, _, _)| (*t, a.as_deref())))
        .collect();

    let out_col_count = resolve_join_output_count(columns, &all_tables);
    let out_regs = b.alloc_regs(out_col_count as i32);

    // Open data cursors for every table.  Cursor id = table index in
    // all_tables (the convention emit_join_expr already relies on).
    let left_cursor: i32 = 0;
    b.emit_op(
        Opcode::OpenRead,
        left_cursor,
        left_table.root_page,
        0,
        P4::Table(left_table.name.clone()),
        0,
    );
    for (i, (right_table, _, _, _)) in join_tables.iter().enumerate() {
        let cursor_id = (i + 1) as i32;
        b.emit_op(
            Opcode::OpenRead,
            cursor_id,
            right_table.root_page,
            0,
            P4::Table(right_table.name.clone()),
            0,
        );
    }

    // Open one extra index cursor per indexed step.  We allocate them
    // after the data cursors so that cursor IDs stay stable across
    // steps even when only some of them use an index.
    let mut index_cursors: Vec<Option<i32>> = Vec::with_capacity(plan.steps.len());
    let data_cursor_count = (join_tables.len() + 1) as i32;
    let mut next_aux_cursor = data_cursor_count;
    for step in &plan.steps {
        if let SingleJoinLookupTarget::Index(index) = &step.lookup_target {
            let cursor = next_aux_cursor;
            next_aux_cursor += 1;
            b.emit_op(
                Opcode::OpenRead,
                cursor,
                index.root_page,
                0,
                P4::Index(index.name.clone()),
                0,
            );
            index_cursors.push(Some(cursor));
        } else {
            index_cursors.push(None);
        }
    }

    // Optional sorter for ORDER BY.  The sorter is the last cursor we
    // allocate, so we do not bump `next_aux_cursor` after consuming it.
    let sorter = if !stmt.order_by.is_empty() {
        let sort_cursor = next_aux_cursor;
        let sort_key_count = stmt.order_by.len();
        let total_sort_cols = sort_key_count + out_col_count;
        let sort_regs = b.alloc_regs(total_sort_cols as i32);
        let sort_record_reg = b.alloc_reg();
        let sort_order = stmt
            .order_by
            .iter()
            .map(|term| {
                if term.direction == Some(fsqlite_ast::SortDirection::Desc) {
                    '-'
                } else {
                    '+'
                }
            })
            .collect::<String>();
        b.emit_op(
            Opcode::SorterOpen,
            sort_cursor,
            total_sort_cols as i32,
            0,
            P4::Affinity(sort_order),
            0,
        );
        Some((sort_cursor, sort_regs, sort_key_count, sort_record_reg))
    } else {
        None
    };
    // Single outer rewind over the driver.
    let next_left_label = b.emit_label();
    let row_done_label = b.emit_label();
    b.emit_jump_to_label(Opcode::Rewind, left_cursor, 0, done_label, P4::None, 0);
    b.resolve_label(next_left_label);

    // Emit each lookup in order.  For INNER joins a miss jumps to
    // row_done_label (skip this outer row entirely).  For the terminal
    // LEFT JOIN (if any) a miss jumps to `left_null_label` — a block
    // emitted past the main result row that NullRow-poisons the LEFT
    // table's cursor and re-emits the row with NULLs.
    //
    // `resolve_multi_join_lookup_plan` guarantees that a LEFT join can
    // only appear as the final step, so a miss never has to skip any
    // remaining INNER probes.
    let left_null_label = if plan
        .steps
        .last()
        .is_some_and(|step| matches!(step.join_kind, JoinKind::Left))
    {
        Some(b.emit_label())
    } else {
        None
    };

    // The "emit one result row" tail is duplicated inline below — once
    // on the all-lookups-landed path and once inside the trailing
    // null-row block for the terminal LEFT JOIN miss.  They MUST stay
    // in lock-step when someone edits the sort-vs-direct branching.
    // Extracting a helper is awkward because both call sites bind the
    // `sorter` tuple fields, the `out_regs`/`out_col_count` locals,
    // and emit bytecode through the same `ProgramBuilder` — leaving
    // them inline keeps the control-flow structure visible next to
    // the label resolution above and below.
    for (i, step) in plan.steps.iter().enumerate() {
        let right_cursor = (i + 1) as i32;
        // Tables that have been bound by the time we emit step i.
        // probe_table_index is always < i + 1 by construction.
        let probe_tables = &all_tables[..=step.probe_table_index];

        let probe_base = b.alloc_regs(1);
        let probe_cursor = step.probe_table_index as i32;
        let probe_scan = ScanCtx {
            cursor: probe_cursor,
            table: probe_tables[step.probe_table_index].0,
            table_alias: probe_tables[step.probe_table_index].1,
            schema: None,
            register_base: None,
            secondaries: &[],
        };
        emit_resolved_column(b, &step.probe_source, probe_cursor, probe_base, &probe_scan);

        // A LEFT-join miss (only allowed on the last step) jumps to the
        // trailing null-row block.  Every other miss skips the whole row.
        let miss_label = if matches!(step.join_kind, JoinKind::Left) {
            left_null_label.expect("LEFT JOIN step must have allocated its null label")
        } else {
            row_done_label
        };

        // NULL probe → miss.  (C SQLite treats NULL = X as "unknown" and
        // therefore as not matching, so the row is skipped.)
        b.emit_jump_to_label(Opcode::IsNull, probe_base, 0, miss_label, P4::None, 0);

        match &step.lookup_target {
            SingleJoinLookupTarget::Rowid => {
                b.emit_jump_to_label(
                    Opcode::SeekRowid,
                    right_cursor,
                    probe_base,
                    miss_label,
                    P4::None,
                    0,
                );
            }
            SingleJoinLookupTarget::Index(index) => {
                let idx_cursor =
                    index_cursors[i].expect("index lookup step must have an index cursor");
                let comparison_p4 = direct_lookup_index_comparison_p4(index);
                // Probe the secondary index for `probe = X`, then
                // SeekRowid on the data cursor using the resulting
                // rowid.  The resolver guarantees non-unique indexes
                // have been rejected, so the first matching key row
                // is the only one.
                //
                // `probe_base` was the last alloc_regs call and
                // `min_rowid_reg` is the very next alloc_reg, so they
                // are guaranteed adjacent — MakeRecord can read the
                // 2-register run [probe_base, probe_base+1] directly
                // without copying into a separate block.
                let min_rowid_reg = b.alloc_reg();
                debug_assert_eq!(
                    min_rowid_reg,
                    probe_base + 1,
                    "probe_base and min_rowid_reg must be adjacent for MakeRecord"
                );
                b.emit_op(Opcode::Int64, 0, min_rowid_reg, 0, P4::Int64(i64::MIN), 0);
                let probe_record_reg = b.alloc_reg();
                b.emit_op(
                    Opcode::MakeRecord,
                    probe_base,
                    2,
                    probe_record_reg,
                    P4::None,
                    0,
                );
                b.emit_jump_to_label(
                    Opcode::SeekGE,
                    idx_cursor,
                    probe_record_reg,
                    miss_label,
                    P4::None,
                    0,
                );
                let idx_key_reg = b.alloc_reg();
                b.emit_op(Opcode::Column, idx_cursor, 0, idx_key_reg, P4::None, 0);
                b.emit_jump_to_label(
                    Opcode::Ne,
                    probe_base,
                    idx_key_reg,
                    miss_label,
                    comparison_p4,
                    0,
                );
                let rowid_reg = b.alloc_reg();
                b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
                b.emit_jump_to_label(
                    Opcode::SeekRowid,
                    right_cursor,
                    rowid_reg,
                    miss_label,
                    P4::None,
                    0,
                );
            }
        }
    }

    // All lookups landed on a real row.  Evaluate the optional WHERE
    // clause against the full bound tuple.
    if let Some(where_expr) = where_clause {
        let cond_reg = b.alloc_regs(1);
        emit_join_expr(b, where_expr, cond_reg, &all_tables, ctx)?;
        b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, row_done_label, P4::None, 0);
    }

    // Emit the result tuple (either direct ResultRow or SorterInsert).
    emit_join_result_columns(b, columns, out_regs, &all_tables, ctx)?;
    if let Some((sort_cursor, sort_regs, sort_key_count, sort_record_reg)) = sorter {
        for (i, term) in stmt.order_by.iter().enumerate() {
            let sort_reg = sort_regs + i as i32;
            emit_join_expr(b, &term.expr, sort_reg, &all_tables, ctx)?;
        }
        for i in 0..out_col_count {
            let src = out_regs + i as i32;
            let dst = sort_regs + (sort_key_count + i) as i32;
            b.emit_op(Opcode::SCopy, src, dst, 0, P4::None, 0);
        }
        b.emit_op(
            Opcode::MakeRecord,
            sort_regs,
            (sort_key_count + out_col_count) as i32,
            sort_record_reg,
            P4::None,
            0,
        );
        b.emit_op(
            Opcode::SorterInsert,
            sort_cursor,
            sort_record_reg,
            0,
            P4::None,
            0,
        );
    } else {
        b.emit_op(
            Opcode::ResultRow,
            out_regs,
            out_col_count as i32,
            0,
            P4::None,
            0,
        );
    }

    // Jump past the trailing LEFT-JOIN null-row block (if any) to the
    // outer Next.  When there is no LEFT JOIN this is a harmless extra
    // unconditional jump; keeping it makes the control-flow layout
    // symmetric with the branch below.
    b.emit_jump_to_label(Opcode::Goto, 0, 0, row_done_label, P4::None, 0);

    // Trailing LEFT JOIN null-row block: the final step's lookup missed,
    // so we emit `NullRow` on its cursor, re-evaluate the WHERE clause
    // (which sees NULLs for the left-joined table's columns), and emit
    // the row with those NULLs.  `resolve_multi_join_lookup_plan`
    // guarantees the LEFT join is the terminal step, so no later steps
    // need to be re-run here.
    if let Some(null_label) = left_null_label {
        b.resolve_label(null_label);
        let last_right_cursor = join_tables.len() as i32;
        b.emit_op(Opcode::NullRow, last_right_cursor, 0, 0, P4::None, 0);
        if let Some(where_expr) = where_clause {
            let cond_reg = b.alloc_regs(1);
            emit_join_expr(b, where_expr, cond_reg, &all_tables, ctx)?;
            b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, row_done_label, P4::None, 0);
        }
        emit_join_result_columns(b, columns, out_regs, &all_tables, ctx)?;
        if let Some((sort_cursor, sort_regs, sort_key_count, sort_record_reg)) = sorter {
            for (i, term) in stmt.order_by.iter().enumerate() {
                let sort_reg = sort_regs + i as i32;
                emit_join_expr(b, &term.expr, sort_reg, &all_tables, ctx)?;
            }
            for i in 0..out_col_count {
                let src = out_regs + i as i32;
                let dst = sort_regs + (sort_key_count + i) as i32;
                b.emit_op(Opcode::SCopy, src, dst, 0, P4::None, 0);
            }
            b.emit_op(
                Opcode::MakeRecord,
                sort_regs,
                (sort_key_count + out_col_count) as i32,
                sort_record_reg,
                P4::None,
                0,
            );
            b.emit_op(
                Opcode::SorterInsert,
                sort_cursor,
                sort_record_reg,
                0,
                P4::None,
                0,
            );
        } else {
            b.emit_op(
                Opcode::ResultRow,
                out_regs,
                out_col_count as i32,
                0,
                P4::None,
                0,
            );
        }
    }

    b.resolve_label(row_done_label);
    b.emit_jump_to_label(Opcode::Next, left_cursor, 0, next_left_label, P4::None, 0);

    b.resolve_label(done_label);

    if let Some((sort_cursor, sort_regs, sort_key_count, _sort_record_reg)) = sorter {
        let sort_loop = b.emit_label();
        let sort_done = b.emit_label();
        b.emit_jump_to_label(Opcode::SorterSort, sort_cursor, 0, sort_done, P4::None, 0);
        b.resolve_label(sort_loop);
        b.emit_op(Opcode::SorterData, sort_cursor, sort_regs, 0, P4::None, 0);
        for i in 0..out_col_count {
            let dst = out_regs + i as i32;
            b.emit_op(
                Opcode::Column,
                sort_cursor,
                (sort_key_count + i) as i32,
                dst,
                P4::None,
                0,
            );
        }
        b.emit_op(
            Opcode::ResultRow,
            out_regs,
            out_col_count as i32,
            0,
            P4::None,
            0,
        );
        b.emit_jump_to_label(Opcode::SorterNext, sort_cursor, 0, sort_loop, P4::None, 0);
        b.resolve_label(sort_done);
        b.emit_op(Opcode::Close, sort_cursor, 0, 0, P4::None, 0);
    }

    for cursor in index_cursors.iter().flatten() {
        b.emit_op(Opcode::Close, *cursor, 0, 0, P4::None, 0);
    }
    for (i, _) in join_tables.iter().enumerate() {
        let cursor = (i + 1) as i32;
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Close, left_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Codegen for SELECT ... FROM t1 JOIN t2 ON ... [WHERE ...] [ORDER BY ...]
///
/// Generates a nested-loop join: scan the outer table, for each row scan the
/// inner table, evaluate the ON condition + WHERE, emit ResultRow for matches.
/// This enables JOINs to execute through the VDBE storage-cursor path instead
/// of falling back to the connection-level MemDatabase interpreter.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_join_select(
    b: &mut ProgramBuilder,
    stmt: &SelectStatement,
    from: &FromClause,
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    schema: &[TableSchema],
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    use fsqlite_ast::{JoinConstraint, JoinKind, TableOrSubquery};

    // Extract left (driving) table.
    let (left_name, left_alias) = match &from.source {
        TableOrSubquery::Table { name, alias, .. } => (&name.name, alias.as_deref()),
        _ => {
            return Err(CodegenError::Unsupported(
                "non-table left source in JOIN".to_owned(),
            ));
        }
    };
    let left_table = find_table(schema, left_name)?;

    // Build list of join sources: (table_schema, alias, join_kind, on_expr)
    let mut join_tables: Vec<(&TableSchema, Option<String>, JoinKind, Option<&Expr>)> =
        Vec::with_capacity(from.joins.len());
    for join in &from.joins {
        let (right_name, right_alias) = match &join.table {
            TableOrSubquery::Table { name, alias, .. } => (&name.name, alias.clone()),
            _ => {
                return Err(CodegenError::Unsupported(
                    "non-table right source in JOIN".to_owned(),
                ));
            }
        };
        let right_table = find_table(schema, right_name)?;
        let on_expr = match &join.constraint {
            Some(JoinConstraint::On(expr)) => Some(expr),
            Some(JoinConstraint::Using(_)) => {
                return Err(CodegenError::Unsupported(
                    "JOIN USING in codegen".to_owned(),
                ));
            }
            None => None,
        };
        join_tables.push((right_table, right_alias, join.join_type.kind, on_expr));
    }

    if join_tables.is_empty() {
        return Err(CodegenError::Unsupported("empty join list".to_owned()));
    }

    if let [(right_table, right_alias, join_kind, on_expr)] = join_tables.as_slice()
        && let Some(plan) = resolve_single_join_lookup_plan(
            left_table,
            left_alias,
            right_table,
            right_alias.as_deref(),
            *join_kind,
            *on_expr,
        )
    {
        return codegen_single_join_lookup_select(
            b,
            stmt,
            columns,
            where_clause,
            left_table,
            left_alias,
            right_table,
            right_alias.as_deref(),
            &plan,
            ctx,
        );
    }

    // Multi-table fast path (issue #62): when every join in the chain
    // can be expressed as a rowid / indexed-equality lookup against an
    // already-bound table, avoid the Cartesian nested-loop scan below
    // and emit a single outer loop with O(1) seeks into each dimension
    // table.  On the 4-table FTS rebuild reported in the bug, this
    // replaces a 600×-slower full-materialization plan.
    if join_tables.len() >= 2
        && let Some(plan) = resolve_multi_join_lookup_plan(left_table, left_alias, &join_tables)
    {
        return codegen_multi_join_lookup_select(
            b,
            stmt,
            columns,
            where_clause,
            left_table,
            left_alias,
            &join_tables,
            &plan,
            ctx,
        );
    }

    let supports_left_join = join_tables.len() == 1;
    for (_, _, kind, _) in &join_tables {
        let supported = match kind {
            JoinKind::Inner | JoinKind::Cross => true,
            JoinKind::Left if supports_left_join => true,
            _ => false,
        };
        if !supported {
            return Err(CodegenError::Unsupported(format!(
                "{kind:?} JOIN not yet supported in VDBE codegen"
            )));
        }
    }

    let end_label = b.emit_label();
    let done_label = b.emit_label();

    // Init.
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);

    // Allocate output registers.
    let all_tables: Vec<(&TableSchema, Option<&str>)> = std::iter::once((left_table, left_alias))
        .chain(join_tables.iter().map(|(t, a, _, _)| (*t, a.as_deref())))
        .collect();
    let out_col_count = resolve_join_output_count(columns, &all_tables);
    let out_regs = b.alloc_regs(out_col_count as i32);

    // Open cursors for all tables.
    let left_cursor = 0_i32;
    b.emit_op(
        Opcode::OpenRead,
        left_cursor,
        left_table.root_page,
        0,
        P4::Table(left_table.name.clone()),
        0,
    );
    let mut right_cursors: Vec<i32> = Vec::with_capacity(join_tables.len());
    for (i, (rt, _, _, _)) in join_tables.iter().enumerate() {
        let cursor_id = (i + 1) as i32;
        b.emit_op(
            Opcode::OpenRead,
            cursor_id,
            rt.root_page,
            0,
            P4::Table(rt.name.clone()),
            0,
        );
        right_cursors.push(cursor_id);
    }

    // Sorter for ORDER BY (if present).
    let sorter = if !stmt.order_by.is_empty() {
        let sort_cursor = (join_tables.len() + 1) as i32;
        let sort_key_count = stmt.order_by.len();
        let total_sort_cols = sort_key_count + out_col_count;
        let sort_regs = b.alloc_regs(total_sort_cols as i32);
        let sort_record_reg = b.alloc_reg();
        let sort_order = stmt
            .order_by
            .iter()
            .map(|term| {
                if term.direction == Some(fsqlite_ast::SortDirection::Desc) {
                    '-'
                } else {
                    '+'
                }
            })
            .collect::<String>();
        b.emit_op(
            Opcode::SorterOpen,
            sort_cursor,
            total_sort_cols as i32,
            0,
            P4::Affinity(sort_order),
            0,
        );
        Some((sort_cursor, sort_regs, sort_key_count, sort_record_reg))
    } else {
        None
    };

    // Nested loop: Rewind left, for each row rewind right, check ON + WHERE, emit.
    let next_left_label = b.emit_label();
    b.emit_jump_to_label(Opcode::Rewind, left_cursor, 0, done_label, P4::None, 0);
    b.resolve_label(next_left_label);
    let left_join_match_reg = if supports_left_join && matches!(join_tables[0].2, JoinKind::Left) {
        let reg = b.alloc_temp();
        b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
        Some(reg)
    } else {
        None
    };

    // For each right table, emit a nested Rewind+Next loop.
    let mut next_labels: Vec<Label> = Vec::with_capacity(right_cursors.len());
    let mut done_right_labels: Vec<Label> = Vec::with_capacity(right_cursors.len());
    for &rc in &right_cursors {
        let next_right_label = b.emit_label();
        let done_right_label = b.emit_label();
        b.emit_jump_to_label(Opcode::Rewind, rc, 0, done_right_label, P4::None, 0);
        b.resolve_label(next_right_label);
        next_labels.push(next_right_label);
        done_right_labels.push(done_right_label);
    }

    // Evaluate ON conditions — skip row if condition is false.
    // When the condition fails, jump forward to the innermost Next opcode
    // (not the loop start — that would re-check the same row forever).
    let skip_label = b.emit_label();
    for (_, _, _, on_expr) in &join_tables {
        if let Some(expr) = on_expr {
            let cond_reg = b.alloc_regs(1);
            emit_join_expr(b, expr, cond_reg, &all_tables, ctx)?;
            b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, skip_label, P4::None, 0);
        }
    }
    if let Some(match_reg) = left_join_match_reg {
        b.emit_op(Opcode::Integer, 1, match_reg, 0, P4::None, 0);
    }
    if let Some(where_expr) = where_clause {
        let cond_reg = b.alloc_regs(1);
        emit_join_expr(b, where_expr, cond_reg, &all_tables, ctx)?;
        b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, skip_label, P4::None, 0);
    }

    // Emit output columns.
    emit_join_result_columns(b, columns, out_regs, &all_tables, ctx)?;

    if let Some((sort_cursor, sort_regs, sort_key_count, sort_record_reg)) = sorter {
        // Copy sort keys then output columns into sorter registers.
        for (i, term) in stmt.order_by.iter().enumerate() {
            let sort_reg = sort_regs + i as i32;
            emit_join_expr(b, &term.expr, sort_reg, &all_tables, ctx)?;
        }
        for i in 0..out_col_count {
            let src = out_regs + i as i32;
            let dst = sort_regs + (sort_key_count + i) as i32;
            b.emit_op(Opcode::SCopy, src, dst, 0, P4::None, 0);
        }
        b.emit_op(
            Opcode::MakeRecord,
            sort_regs,
            (sort_key_count + out_col_count) as i32,
            sort_record_reg,
            P4::None,
            0,
        );
        b.emit_op(
            Opcode::SorterInsert,
            sort_cursor,
            sort_record_reg,
            0,
            P4::None,
            0,
        );
    } else {
        b.emit_op(
            Opcode::ResultRow,
            out_regs,
            out_col_count as i32,
            0,
            P4::None,
            0,
        );
    }

    // Close nested loops (inner to outer).
    // Resolve skip_label here so failed ON/WHERE conditions jump to the
    // innermost Next (advancing the cursor) rather than the loop body start.
    b.resolve_label(skip_label);
    for (i, &rc) in right_cursors.iter().enumerate().rev() {
        b.emit_jump_to_label(Opcode::Next, rc, 0, next_labels[i], P4::None, 0);
        b.resolve_label(done_right_labels[i]);
    }
    if let Some(match_reg) = left_join_match_reg {
        let skip_left_join_null_row = b.emit_label();
        b.emit_jump_to_label(
            Opcode::IfPos,
            match_reg,
            0,
            skip_left_join_null_row,
            P4::None,
            0,
        );
        b.emit_op(Opcode::NullRow, right_cursors[0], 0, 0, P4::None, 0);
        if let Some(where_expr) = where_clause {
            let cond_reg = b.alloc_regs(1);
            emit_join_expr(b, where_expr, cond_reg, &all_tables, ctx)?;
            b.emit_jump_to_label(
                Opcode::IfNot,
                cond_reg,
                1,
                skip_left_join_null_row,
                P4::None,
                0,
            );
        }
        emit_join_result_columns(b, columns, out_regs, &all_tables, ctx)?;
        if let Some((sort_cursor, sort_regs, sort_key_count, sort_record_reg)) = sorter {
            for (i, term) in stmt.order_by.iter().enumerate() {
                let sort_reg = sort_regs + i as i32;
                emit_join_expr(b, &term.expr, sort_reg, &all_tables, ctx)?;
            }
            for i in 0..out_col_count {
                let src = out_regs + i as i32;
                let dst = sort_regs + (sort_key_count + i) as i32;
                b.emit_op(Opcode::SCopy, src, dst, 0, P4::None, 0);
            }
            b.emit_op(
                Opcode::MakeRecord,
                sort_regs,
                (sort_key_count + out_col_count) as i32,
                sort_record_reg,
                P4::None,
                0,
            );
            b.emit_op(
                Opcode::SorterInsert,
                sort_cursor,
                sort_record_reg,
                0,
                P4::None,
                0,
            );
        } else {
            b.emit_op(
                Opcode::ResultRow,
                out_regs,
                out_col_count as i32,
                0,
                P4::None,
                0,
            );
        }
        b.resolve_label(skip_left_join_null_row);
    }
    b.emit_jump_to_label(Opcode::Next, left_cursor, 0, next_left_label, P4::None, 0);

    b.resolve_label(done_label);

    // If sorting, emit sorter output.
    if let Some((sort_cursor, sort_regs, sort_key_count, _sort_record_reg)) = sorter {
        let sort_loop = b.emit_label();
        let sort_done = b.emit_label();
        b.emit_jump_to_label(Opcode::SorterSort, sort_cursor, 0, sort_done, P4::None, 0);
        b.resolve_label(sort_loop);
        b.emit_op(Opcode::SorterData, sort_cursor, sort_regs, 0, P4::None, 0);
        // Extract output columns from sorter data.
        for i in 0..out_col_count {
            let dst = out_regs + i as i32;
            b.emit_op(
                Opcode::Column,
                sort_cursor,
                (sort_key_count + i) as i32,
                dst,
                P4::None,
                0,
            );
        }
        b.emit_op(
            Opcode::ResultRow,
            out_regs,
            out_col_count as i32,
            0,
            P4::None,
            0,
        );
        b.emit_jump_to_label(Opcode::SorterNext, sort_cursor, 0, sort_loop, P4::None, 0);
        b.resolve_label(sort_done);
    }

    // LIMIT/OFFSET (simple version).
    // (Full LIMIT support is handled by the caller's post-processing.)

    // Close cursors.
    for &rc in &right_cursors {
        b.emit_op(Opcode::Close, rc, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Close, left_cursor, 0, 0, P4::None, 0);

    // Halt.
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End target for Init jump — Init will see this points past the
    // program end and fall through to Transaction (the standard pattern
    // used by all other codegen paths).
    b.resolve_label(end_label);

    Ok(())
}

/// Count output columns for a JOIN query.
fn resolve_join_output_count(
    columns: &[ResultColumn],
    tables: &[(&TableSchema, Option<&str>)],
) -> usize {
    columns
        .iter()
        .map(|col| match col {
            ResultColumn::Star => tables.iter().map(|(t, _)| t.columns.len()).sum(),
            ResultColumn::TableStar(name) => tables
                .iter()
                .find(|(t, alias)| join_qualifier_matches(Some(&name.name), t, *alias))
                .map_or(0, |(t, _)| t.columns.len()),
            ResultColumn::Expr { .. } => 1,
        })
        .sum()
}

/// Emit a single expression for a JOIN context (multi-table column resolution).
///
/// This is a simplified expression emitter that handles the common cases:
/// column references (qualified and unqualified), literals, and simple
/// binary comparisons. Complex expressions fall back to unsupported error.
#[allow(clippy::too_many_lines)]
fn emit_join_expr(
    b: &mut ProgramBuilder,
    expr: &Expr,
    target: i32,
    tables: &[(&TableSchema, Option<&str>)],
    _ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    match expr {
        Expr::Column(col_ref, _) => {
            match resolve_join_column_ref(col_ref.table.as_deref(), &col_ref.column, tables)? {
                JoinColumnResolution::HiddenRowid(cursor) => {
                    b.emit_op(Opcode::Rowid, cursor, target, 0, P4::None, 0);
                }
                JoinColumnResolution::Column(cursor, col_idx) => {
                    let (table, table_alias) = tables[cursor as usize];
                    if table.columns[col_idx].is_ipk {
                        // bd-ghiey: an INTEGER PRIMARY KEY is stored as the
                        // b-tree rowid, not in the record, so read it via Rowid
                        // (mirroring single-table `emit_table_column_read`). The
                        // join path's plain `Column` read relies on the engine's
                        // `rowid_alias_col_by_root_page` map to substitute the
                        // rowid, but that map is keyed by pre-routing root pages
                        // built from `self.schema` — it misses TEMP tables (whose
                        // roots are routed to the temp database) and shadowed main
                        // tables (parked out of `self.schema`), so their IPK
                        // projected as NULL through a join. Emitting `Rowid`
                        // directly is what stock does and needs no runtime map.
                        b.emit_op(Opcode::Rowid, cursor, target, 0, P4::None, 0);
                    } else if virtual_generated_column_expr(&table.columns[col_idx]).is_some() {
                        // GH#227 (bd-gh-virtual-generated-columns-5e0u1): a
                        // VIRTUAL generated column is not materialized in the
                        // record — the slot holds a NULL placeholder. Reading it
                        // raw here made a JOIN predicate/projection on the column
                        // compare NULL and drop every row. Route through the
                        // canonical table-column reader so the generating
                        // expression is computed (and affinity-coerced) on read,
                        // exactly as single-table projection does.
                        //
                        // bd-3radn H1: in an OUTER JOIN the cursor can be on a
                        // NULL-extended (unmatched) row. Computing the generating
                        // expression there yields a bogus non-NULL value
                        // (e.g. COALESCE(base, 99) => 99 instead of NULL) and
                        // breaks anti-joins (`WHERE g IS NULL`). Guard with
                        // IfNullRow (C SQLite's OP_IfNullRow): a null-row leaves
                        // the column NULL and skips the computation. A REAL row
                        // whose base value happens to be NULL is NOT a null-row,
                        // so its generating expression is still evaluated.
                        let skip = b.emit_label();
                        b.emit_jump_to_label(Opcode::IfNullRow, cursor, target, skip, P4::None, 0);
                        emit_table_column_read(
                            b,
                            cursor,
                            table,
                            table_alias,
                            None,
                            col_idx,
                            target,
                        );
                        b.resolve_label(skip);
                    } else {
                        b.emit_op(Opcode::Column, cursor, col_idx as i32, target, P4::None, 0);
                    }
                }
            }
            Ok(())
        }
        Expr::Literal(lit, _) => {
            match lit {
                Literal::Integer(n) => {
                    if let Ok(small) = i32::try_from(*n) {
                        b.emit_op(Opcode::Integer, small, target, 0, P4::None, 0);
                    } else {
                        b.emit_op(Opcode::Int64, 0, target, 0, P4::Int64(*n), 0);
                    }
                }
                Literal::Float(f) => {
                    b.emit_op(Opcode::Real, 0, target, 0, P4::Real(*f), 0);
                }
                Literal::String(s) => {
                    b.emit_op(Opcode::String8, 0, target, 0, P4::Str(s.clone()), 0);
                }
                Literal::Blob(bytes) => {
                    b.emit_op(
                        Opcode::Blob,
                        bytes.len() as i32,
                        target,
                        0,
                        P4::Blob(bytes.clone()),
                        0,
                    );
                }
                Literal::Null => {
                    b.emit_op(Opcode::Null, 0, target, 0, P4::None, 0);
                }
                Literal::True => {
                    b.emit_op(Opcode::Integer, 1, target, 0, P4::None, 0);
                }
                Literal::False => {
                    b.emit_op(Opcode::Integer, 0, target, 0, P4::None, 0);
                }
                Literal::CurrentTime | Literal::CurrentDate | Literal::CurrentTimestamp => {
                    if let Some(text) = current_time_literal_text(lit) {
                        b.emit_op(Opcode::String8, 0, target, 0, P4::Str(text), 0);
                    }
                }
            }
            Ok(())
        }
        Expr::BoundOuterValue { value, .. } => {
            emit_sqlite_value(b, value, target);
            Ok(())
        }
        Expr::BinaryOp {
            left, op, right, ..
        } => {
            use fsqlite_ast::BinaryOp;
            let left_reg = b.alloc_regs(1);
            let right_reg = b.alloc_regs(1);
            emit_join_expr(b, left, left_reg, tables, _ctx)?;
            emit_join_expr(b, right, right_reg, tables, _ctx)?;
            let comparison_collation = join_comparison_collation_name(left, right, tables)
                .map_or(P4::None, |coll| P4::Collation(coll.to_owned()));
            let comparison_p5 = 0x20 | join_comparison_affinity_p5(left, right, tables);
            match op {
                BinaryOp::Eq => {
                    // Use Eq with STOREP2 to store result in target.
                    b.emit_op(
                        Opcode::Eq,
                        right_reg,
                        target,
                        left_reg,
                        comparison_collation,
                        comparison_p5,
                    );
                }
                BinaryOp::Ne => {
                    b.emit_op(
                        Opcode::Ne,
                        right_reg,
                        target,
                        left_reg,
                        comparison_collation,
                        comparison_p5,
                    );
                }
                BinaryOp::Lt => {
                    b.emit_op(
                        Opcode::Lt,
                        right_reg,
                        target,
                        left_reg,
                        comparison_collation,
                        comparison_p5,
                    );
                }
                BinaryOp::Le => {
                    b.emit_op(
                        Opcode::Le,
                        right_reg,
                        target,
                        left_reg,
                        comparison_collation,
                        comparison_p5,
                    );
                }
                BinaryOp::Gt => {
                    b.emit_op(
                        Opcode::Gt,
                        right_reg,
                        target,
                        left_reg,
                        comparison_collation,
                        comparison_p5,
                    );
                }
                BinaryOp::Ge => {
                    b.emit_op(
                        Opcode::Ge,
                        right_reg,
                        target,
                        left_reg,
                        comparison_collation,
                        comparison_p5,
                    );
                }
                BinaryOp::Add => {
                    b.emit_op(Opcode::Add, right_reg, left_reg, target, P4::None, 0);
                }
                BinaryOp::Subtract => {
                    b.emit_op(Opcode::Subtract, right_reg, left_reg, target, P4::None, 0);
                }
                BinaryOp::Multiply => {
                    b.emit_op(Opcode::Multiply, right_reg, left_reg, target, P4::None, 0);
                }
                BinaryOp::And => {
                    b.emit_op(Opcode::And, left_reg, right_reg, target, P4::None, 0);
                }
                BinaryOp::Or => {
                    b.emit_op(Opcode::Or, left_reg, right_reg, target, P4::None, 0);
                }
                BinaryOp::Divide
                | BinaryOp::Modulo
                | BinaryOp::Concat
                | BinaryOp::BitAnd
                | BinaryOp::BitOr
                | BinaryOp::ShiftLeft
                | BinaryOp::ShiftRight => {
                    b.emit_op(
                        binary_op_to_opcode(*op),
                        right_reg,
                        left_reg,
                        target,
                        P4::None,
                        0,
                    );
                }
                BinaryOp::Is | BinaryOp::IsNot => {
                    return Err(CodegenError::Unsupported(format!(
                        "binary op {op:?} in JOIN codegen"
                    )));
                }
            }
            Ok(())
        }
        Expr::IsNull {
            expr: inner, not, ..
        } => {
            let inner_reg = b.alloc_regs(1);
            emit_join_expr(b, inner, inner_reg, tables, _ctx)?;
            let skip = b.emit_label();
            // IS NULL: result is 1 when inner is null, 0 otherwise.
            // IS NOT NULL: result is 0 when inner is null, 1 otherwise.
            let (val_if_null, val_if_not_null) = if *not { (0, 1) } else { (1, 0) };
            b.emit_op(Opcode::Integer, val_if_null, target, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::IsNull, inner_reg, 0, skip, P4::None, 0);
            b.emit_op(Opcode::Integer, val_if_not_null, target, 0, P4::None, 0);
            b.resolve_label(skip);
            Ok(())
        }
        _ => Err(CodegenError::Unsupported(format!(
            "expression {expr:?} in JOIN codegen"
        ))),
    }
}

enum JoinColumnResolution {
    HiddenRowid(i32),
    Column(i32, usize),
}

fn ambiguous_join_column(name: &str) -> CodegenError {
    CodegenError::AmbiguousColumn(name.to_owned())
}

fn join_qualified_column_name(qualifier: Option<&str>, name: &str) -> String {
    qualifier.map_or_else(|| name.to_owned(), |q| format!("{q}.{name}"))
}

fn join_qualifier_matches(
    qualifier: Option<&str>,
    table: &TableSchema,
    alias: Option<&str>,
) -> bool {
    qualifier.is_none_or(|q| {
        alias.map_or_else(
            || table.name.eq_ignore_ascii_case(q),
            |a| a.eq_ignore_ascii_case(q),
        )
    })
}

fn resolve_join_column_ref(
    qualifier: Option<&str>,
    name: &str,
    tables: &[(&TableSchema, Option<&str>)],
) -> Result<JoinColumnResolution, CodegenError> {
    let name_lower = name.to_ascii_lowercase();
    let mut found = None;
    for (cursor_idx, (table, alias)) in tables.iter().enumerate() {
        if !join_qualifier_matches(qualifier, table, *alias) {
            continue;
        }
        for (col_idx, col) in table.columns.iter().enumerate() {
            if col.name.eq_ignore_ascii_case(&name_lower) {
                let resolution = JoinColumnResolution::Column(cursor_idx as i32, col_idx);
                if found.replace(resolution).is_some() {
                    return Err(ambiguous_join_column(&join_qualified_column_name(
                        qualifier, name,
                    )));
                }
            }
        }
        if table.resolves_to_hidden_rowid(name) {
            let resolution = JoinColumnResolution::HiddenRowid(cursor_idx as i32);
            if found.replace(resolution).is_some() {
                return Err(ambiguous_join_column(&join_qualified_column_name(
                    qualifier, name,
                )));
            }
        }
    }
    found.ok_or_else(|| {
        qualifier.map_or_else(
            || CodegenError::ColumnNotFound {
                table: String::new(),
                column: name.to_owned(),
            },
            |qualifier| qualified_column_not_found(qualifier, name),
        )
    })
}

/// Resolve a column reference to (cursor_id, column_index) across multiple tables.
fn resolve_join_column(
    qualifier: Option<&str>,
    name: &str,
    tables: &[(&TableSchema, Option<&str>)],
) -> Result<(i32, usize), CodegenError> {
    let name_lower = name.to_ascii_lowercase();
    let mut found = None;
    for (cursor_idx, (table, alias)) in tables.iter().enumerate() {
        // Check if qualifier matches table name or alias.
        if !join_qualifier_matches(qualifier, table, *alias) {
            continue;
        }
        for (col_idx, col) in table.columns.iter().enumerate() {
            if col.name.eq_ignore_ascii_case(&name_lower) {
                let resolution = (cursor_idx as i32, col_idx);
                if found.replace(resolution).is_some() {
                    return Err(ambiguous_join_column(&join_qualified_column_name(
                        qualifier, name,
                    )));
                }
            }
        }
    }
    found.ok_or_else(|| {
        qualifier.map_or_else(
            || CodegenError::ColumnNotFound {
                table: String::new(),
                column: name.to_owned(),
            },
            |qualifier| qualified_column_not_found(qualifier, name),
        )
    })
}

/// Emit result columns for a JOIN query.
fn emit_join_result_columns(
    b: &mut ProgramBuilder,
    columns: &[ResultColumn],
    out_regs: i32,
    tables: &[(&TableSchema, Option<&str>)],
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    let mut reg_offset = 0;
    for col in columns {
        match col {
            ResultColumn::Star => {
                // Emit all columns from all tables.
                for (cursor_idx, (table, _)) in tables.iter().enumerate() {
                    for col_idx in 0..table.columns.len() {
                        let dst = out_regs + reg_offset;
                        // bd-ghiey: an INTEGER PRIMARY KEY lives in the b-tree
                        // rowid, not the record — read it via Rowid (see the
                        // Expr-path note in `emit_join_expr`), so a `SELECT *`
                        // over a TEMP/shadowed table in a join projects the id
                        // instead of NULL.
                        if table.columns[col_idx].is_ipk {
                            b.emit_op(Opcode::Rowid, cursor_idx as i32, dst, 0, P4::None, 0);
                        } else {
                            b.emit_op(
                                Opcode::Column,
                                cursor_idx as i32,
                                col_idx as i32,
                                dst,
                                P4::None,
                                0,
                            );
                        }
                        reg_offset += 1;
                    }
                }
            }
            ResultColumn::TableStar(table_name) => {
                let mut matched = false;
                for (cursor_idx, (table, alias)) in tables.iter().enumerate() {
                    if join_qualifier_matches(Some(&table_name.name), table, *alias) {
                        matched = true;
                        for col_idx in 0..table.columns.len() {
                            let dst = out_regs + reg_offset;
                            if table.columns[col_idx].is_ipk {
                                b.emit_op(Opcode::Rowid, cursor_idx as i32, dst, 0, P4::None, 0);
                            } else {
                                b.emit_op(
                                    Opcode::Column,
                                    cursor_idx as i32,
                                    col_idx as i32,
                                    dst,
                                    P4::None,
                                    0,
                                );
                            }
                            reg_offset += 1;
                        }
                        break;
                    }
                }
                if !matched {
                    return Err(CodegenError::TableNotFound(table_name.to_string()));
                }
            }
            ResultColumn::Expr { expr, .. } => {
                let dst = out_regs + reg_offset;
                emit_join_expr(b, expr, dst, tables, ctx)?;
                reg_offset += 1;
            }
        }
    }
    Ok(())
}

///
/// Handles `VALUES (1, 'a'), (2, 'b')` etc.
fn codegen_values_select(b: &mut ProgramBuilder, rows: &[Vec<Expr>]) {
    if rows.is_empty() {
        let end_label = b.emit_label();
        b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
        b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);
        return;
    }

    let end_label = b.emit_label();

    // Init: jump to end (standard SQLite pattern).
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);

    // Transaction (read-only, p2=0).
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);

    // Determine column count from the first row.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let num_cols = rows[0].len() as i32;
    let out_regs = b.alloc_regs(num_cols);

    // Emit each row: evaluate expressions, then ResultRow.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for row in rows {
        for (i, expr) in row.iter().enumerate() {
            let reg = out_regs + i as i32;
            emit_expr(b, expr, reg, None);
        }
        b.emit_op(Opcode::ResultRow, out_regs, num_cols, 0, P4::None, 0);
    }

    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End target for Init jump.
    b.resolve_label(end_label);
}

/// Generate VDBE bytecode for SELECT without FROM clause.
///
/// Pattern: `Init → Transaction → [eval exprs] → ResultRow → Halt`
///
/// Handles `SELECT 1`, `SELECT 1+2, 'abc'`, `SELECT abs(-5)`, etc.
/// If a WHERE clause is present and evaluates to false/NULL, no row is emitted.
fn codegen_select_without_from(
    b: &mut ProgramBuilder,
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
) {
    let end_label = b.emit_label();
    let halt_label = b.emit_label();

    // Init: jump to end (standard SQLite pattern).
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);

    // Transaction (read-only, p2=0).
    b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);

    // WHERE clause: if present and false/NULL, skip to Halt.
    if let Some(where_expr) = where_clause {
        let cond_reg = b.alloc_temp();
        emit_expr(b, where_expr, cond_reg, None);
        b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, halt_label, P4::None, 0);
        b.free_temp(cond_reg);
    }

    // Evaluate each result column expression into consecutive output registers.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let num_cols = columns.len() as i32;
    let out_regs = b.alloc_regs(num_cols);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for (i, col) in columns.iter().enumerate() {
        let reg = out_regs + i as i32;
        match col {
            ResultColumn::Expr { expr, .. } => {
                emit_expr(b, expr, reg, None);
            }
            ResultColumn::Star | ResultColumn::TableStar(_) => {
                // No table → Star has no meaning; emit NULL.
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            }
        }
    }

    b.emit_op(Opcode::ResultRow, out_regs, num_cols, 0, P4::None, 0);
    b.resolve_label(halt_label);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End target for Init jump.
    b.resolve_label(end_label);
}

/// Which end of the table B-tree a `MIN`/`MAX(rowid)` extremum lives at.
#[derive(Clone, Copy)]
enum RowidSeekEnd {
    /// `MIN(rowid)` → leftmost leaf (first row).
    First,
    /// `MAX(rowid)` → rightmost leaf (last row).
    Last,
}

/// Detect the `MAX(rowid)` / `MIN(rowid)` leaf-seek special case.
///
/// Fires only when the parsed aggregate columns reduce to *exactly one* output
/// aggregate over the rowid / INTEGER PRIMARY KEY, with no other aggregate or
/// bare columns, no `DISTINCT`, and no `FILTER`. An optional scalar wrapper
/// (e.g. `COALESCE(MAX(id), 0)`) is allowed because it is applied unchanged
/// after finalization. Any additional output column (a second aggregate or a
/// bare `SELECT max(id), other` column) disqualifies the fast path so its
/// semantics — bare columns take the value of the *last scanned row* — are
/// never altered. Returns the end of the B-tree to seek when applicable.
fn minmax_rowid_seek_plan(agg_columns: &[AggColumn]) -> Option<RowidSeekEnd> {
    let [agg] = agg_columns else {
        return None;
    };
    if !agg.arg_is_rowid
        || agg.distinct
        || agg.filter.is_some()
        || agg.hidden
        || agg.bare_expr.is_some()
        || !agg.multi_agg_indices.is_empty()
        || !agg.extra_args.is_empty()
        || agg.num_args != 1
    {
        return None;
    }
    if !builtin_aggregate_semantics_available(&agg.name, 1) {
        return None;
    }
    match agg.name.as_str() {
        "MIN" => Some(RowidSeekEnd::First),
        "MAX" => Some(RowidSeekEnd::Last),
        _ => None,
    }
}

/// A single `MIN(col)` / `MAX(col)` over a secondary-indexed column, resolvable by one index seek.
struct MinMaxIndexSeek {
    /// `true` = `MAX`; `false` = `MIN`.
    is_max: bool,
    index_name: String,
    index_root: i32,
    /// `true` when the column's leading index term is DESC (extremum ends and NULL region flip).
    descending: bool,
}

/// Find an index whose extremum-of-`col_name` sits at one end of the index (index column 0), returning
/// it with its leading-term direction (`true` = DESC).
///
/// A single-column ASC collation-matched index is preferred (allows NOCASE); otherwise a BINARY-only
/// fallback accepts a composite index whose leading term is `col_name` (ASC or DESC) or a single-column
/// DESC index. BINARY-only there avoids the collation-tie representative ambiguity a non-BINARY leading
/// term would introduce among the extremum's duplicate run. Shared by the single- and pair-seek plans.
fn find_minmax_leading_index<'t>(
    table: &'t TableSchema,
    col_name: &str,
    collation: Option<&str>,
) -> Option<(&'t IndexSchema, bool)> {
    table
        .single_column_index_for_column_with_collation(col_name, collation)
        .map(|idx| (idx, false))
        .or_else(|| {
            if collation.is_some_and(|c| !c.eq_ignore_ascii_case("BINARY")) || table.without_rowid {
                return None;
            }
            table.indexes.iter().find_map(|idx| {
                let leads = idx.supports_direct_column_lookup()
                    && idx
                        .columns
                        .first()
                        .is_some_and(|c| c.eq_ignore_ascii_case(col_name))
                    && idx
                        .key_term_collation(0)
                        .is_none_or(|c| c.eq_ignore_ascii_case("BINARY"));
                // Composite leading (any direction), or a single-column DESC index (single-column ASC
                // is handled above).
                let usable = leads && (idx.key_term_count() >= 2 || idx.key_term_descending(0));
                usable.then(|| (idx, idx.key_term_descending(0)))
            })
        })
}

/// The single-column ASC BINARY-collation index a `SELECT COUNT(DISTINCT col) FROM t` (no
/// WHERE/HAVING/GROUP BY) can walk in key order — counting non-NULL key-changes — instead of a full
/// scan that maintains an ephemeral dedup B-tree. The index groups equal values adjacently under
/// BINARY, so adjacent-key counting is byte-identical to the full-scan DISTINCT path, and COUNT(*) needs
/// no table read (covering).
struct CountDistinctIndexWalk {
    index_name: String,
    index_root: i32,
}

/// Detect `SELECT COUNT(DISTINCT col) FROM t` served by a single covering index walk. Gated tight so
/// the adjacent-key count is provably byte-identical: exactly one aggregate (no bare output column), a
/// plain single-column argument (not `*`/rowid/expr), no FILTER/wrapper/DISTINCT-collation other than
/// BINARY, and a single-column ASC BINARY index on the column. A non-BINARY (e.g. NOCASE) column would
/// group case-folded values that the BINARY index/compare splits, so it declines to the scan. Searches
/// all indexes so a composite `(col, …)` index declared first does not shadow a usable single-column one
/// (bd-agg-range-shadowed-index). bd-count-distinct-index-walk.
fn count_distinct_index_walk_plan(
    agg_columns: &[AggColumn],
    columns: &[ResultColumn],
    table: &TableSchema,
) -> Option<CountDistinctIndexWalk> {
    let [agg] = agg_columns else {
        return None;
    };
    if columns.len() != 1
        || !agg.name.eq_ignore_ascii_case("count")
        || !builtin_aggregate_semantics_available(&agg.name, 1)
        || !agg.distinct
        || agg.filter.is_some()
        || agg.wrapper_expr.is_some()
        || agg.bare_expr.is_some()
        || agg.arg_expr.is_some()
        || agg.arg_is_rowid
        || agg.hidden
        || !agg.extra_args.is_empty()
    {
        return None;
    }
    // BINARY only: the index's BINARY key order must equal the DISTINCT comparison so the adjacent-key
    // (no-affinity) equality matches C SQLite's grouping.
    if agg
        .collation
        .as_deref()
        .is_some_and(|c| !c.eq_ignore_ascii_case("BINARY"))
    {
        return None;
    }
    let col_idx = agg.arg_col_index?;
    let column = table.columns.get(col_idx)?;
    // A COMPOSITE index whose LEADING key term is this column (ASC BINARY)
    // qualifies: the walk reads only index column 0 and counts leading-value
    // changes, so trailing terms are irrelevant. `supports_direct_column_lookup`
    // still excludes partial (WHERE) and expression indexes (full plain-column
    // coverage). Prefer the narrowest qualifying index (fewest entries to walk).
    let idx = table
        .indexes
        .iter()
        .filter(|idx| {
            idx.supports_direct_column_lookup()
                && idx.key_term_count() >= 1
                && !idx.key_term_descending(0)
                && idx
                    .columns
                    .first()
                    .is_some_and(|c| c.eq_ignore_ascii_case(&column.name))
                && idx
                    .key_term_collation(0)
                    .is_none_or(|c| c.eq_ignore_ascii_case("BINARY"))
        })
        .min_by_key(|idx| idx.key_term_count())?;
    Some(CountDistinctIndexWalk {
        index_name: idx.name.clone(),
        index_root: idx.root_page,
    })
}

/// A WHERE that is exactly `<col> IS NOT NULL`, where `<col>` is the column EVERY MIN/MAX aggregate
/// here reads — redundant (MIN/MAX already ignore NULLs), so the index-seek fast paths may treat it as
/// no WHERE and still be byte-identical. Handles the single aggregate and the `MIN(col), MAX(col)` pair.
/// bd-minmax-redundant-not-null.
fn minmax_where_is_redundant_not_null(
    where_clause: Option<&Expr>,
    agg_columns: &[AggColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    let Some(Expr::IsNull {
        expr, not: true, ..
    }) = where_clause
    else {
        return false;
    };
    let Some(filter_col) = column_name(expr, table, table_alias) else {
        return false;
    };
    !agg_columns.is_empty()
        && agg_columns.iter().all(|agg| {
            matches!(agg.name.as_str(), "MIN" | "MAX")
                && agg
                    .arg_col_index
                    .and_then(|i| table.columns.get(i))
                    .is_some_and(|c| c.name.eq_ignore_ascii_case(&filter_col))
        })
}

/// Detect `SELECT MIN(col)` / `SELECT MAX(col)` (no WHERE/HAVING/GROUP BY) where `col` is the leading
/// term of an index whose ordering matches the aggregate comparison.
///
/// The value extremum is then a single seek to one end of the index rather than an O(n) scan. This
/// mirrors [`minmax_rowid_seek_plan`]'s guards (exactly one output aggregate; no DISTINCT / FILTER /
/// bare output column / multi-aggregate wrapper / extra args; a single plain-column argument) so the
/// produced result is byte-identical to the full-scan path — only the row that feeds `AggStep`
/// changes. A collation-matched single-column ASC index is preferred; the BINARY fallback also
/// accepts a composite index led by the column (ASC or DESC) and a single-column DESC index. A
/// differently-collated index, non-BINARY fallback, or WITHOUT ROWID table declines to the scan. A
/// scalar wrapper (`COALESCE(MAX(x), 0)`) is allowed — it is applied unchanged after finalize.
/// bd-minmax-index-seek.
fn minmax_index_seek_plan(
    agg_columns: &[AggColumn],
    table: &TableSchema,
) -> Option<MinMaxIndexSeek> {
    let [agg] = agg_columns else {
        return None;
    };
    if agg.arg_is_rowid
        || agg.distinct
        || agg.filter.is_some()
        || agg.hidden
        || agg.bare_expr.is_some()
        || agg.arg_expr.is_some()
        || !agg.multi_agg_indices.is_empty()
        || !agg.extra_args.is_empty()
        || agg.num_args != 1
    {
        return None;
    }
    if !builtin_aggregate_semantics_available(&agg.name, 1) {
        return None;
    }
    let is_max = match agg.name.as_str() {
        "MIN" => false,
        "MAX" => true,
        _ => return None,
    };
    let col_name = table.columns.get(agg.arg_col_index?)?.name.as_str();
    let (idx, descending) = find_minmax_leading_index(table, col_name, agg.collation.as_deref())?;
    Some(MinMaxIndexSeek {
        is_max,
        index_name: idx.name.clone(),
        index_root: idx.root_page,
        descending,
    })
}

/// `SELECT MIN(col), MAX(col)` (in either order) over the SAME indexed `col` — resolvable by two seeks
/// to the two ends of the index instead of a full scan.
struct MinMaxPairSeek {
    /// SELECT-list position (register offset) of the `MIN` output and the `MAX` output.
    min_out_col: i32,
    max_out_col: i32,
    index_name: String,
    index_root: i32,
    /// `true` when the leading index term is DESC (the extremum ends and NULL region flip).
    descending: bool,
}

/// Detect `SELECT MIN(col), MAX(col)` / `SELECT MAX(col), MIN(col)` (no WHERE/HAVING/GROUP BY) over the
/// same indexed column — both extrema are at the two ends of the index, so two seeks replace the scan.
///
/// Mirrors the single-seek guards for BOTH aggregates (plain-column arg; no DISTINCT/FILTER/bare/
/// multi/extra; no scalar wrapper — kept simple), requires the same column and matching collation, and
/// reuses [`find_minmax_leading_index`]. Byte-identical: each end feeds its own accumulator exactly as
/// the single-seek path would.
fn minmax_pair_seek_plan(agg_columns: &[AggColumn], table: &TableSchema) -> Option<MinMaxPairSeek> {
    let [a0, a1] = agg_columns else {
        return None;
    };
    for agg in [a0, a1] {
        if agg.arg_is_rowid
            || agg.distinct
            || agg.filter.is_some()
            || agg.hidden
            || agg.bare_expr.is_some()
            || agg.arg_expr.is_some()
            || agg.wrapper_expr.is_some()
            || !agg.multi_agg_indices.is_empty()
            || !agg.extra_args.is_empty()
            || agg.num_args != 1
        {
            return None;
        }
        if !builtin_aggregate_semantics_available(&agg.name, 1) {
            return None;
        }
    }
    // One MIN and one MAX (either SELECT order), over the same column and matching collation.
    let (min_out_col, max_out_col) = match (a0.name.as_str(), a1.name.as_str()) {
        ("MIN", "MAX") => (0, 1),
        ("MAX", "MIN") => (1, 0),
        _ => return None,
    };
    let col = a0.arg_col_index?;
    if a1.arg_col_index? != col || a0.collation != a1.collation {
        return None;
    }
    let col_name = table.columns.get(col)?.name.as_str();
    let (idx, descending) = find_minmax_leading_index(table, col_name, a0.collation.as_deref())?;
    Some(MinMaxPairSeek {
        min_out_col,
        max_out_col,
        index_name: idx.name.clone(),
        index_root: idx.root_page,
        descending,
    })
}

/// `SELECT MIN(col) FROM t WHERE col > c` / `MAX(col) FROM t WHERE col < c` (natural pairing) over an
/// INTEGER-affinity single-column-indexed column — resolvable by ONE seek to the bound.
struct MinMaxRangeSeek {
    index_name: String,
    index_root: i32,
    /// The seek that lands on the extremum at the bound: `SeekGT`/`SeekGE` for `MIN col >[=] c`,
    /// `SeekLT`/`SeekLE` for `MAX col <[=] c`.
    seek_op: Opcode,
    /// The integer bound.
    bound: i64,
}

/// Extract `col OP <int literal>` (OP ∈ `<,<=,>,>=`, either operand order) from a WHERE that is
/// exactly that comparison.
fn extract_col_int_comparison(
    where_clause: Option<&Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
    col_name: &str,
) -> Option<(fsqlite_ast::BinaryOp, i64)> {
    use fsqlite_ast::BinaryOp::{Ge, Gt, Le, Lt};
    let Expr::BinaryOp {
        left, op, right, ..
    } = where_clause?
    else {
        return None;
    };
    if !matches!(op, Lt | Le | Gt | Ge) {
        return None;
    }
    let is_col = |e: &Expr| {
        column_name(e, table, table_alias).is_some_and(|n| n.eq_ignore_ascii_case(col_name))
    };
    let int_lit = |e: &Expr| match e {
        Expr::Literal(Literal::Integer(n), _) => Some(*n),
        _ => None,
    };
    if is_col(left)
        && let Some(n) = int_lit(right)
    {
        return Some((*op, n));
    }
    // Reversed operand order: `<int> OP col` ≡ `col <reversed-OP> <int>`.
    if is_col(right)
        && let Some(n) = int_lit(left)
    {
        let rev = match op {
            Lt => Gt,
            Le => Ge,
            Gt => Lt,
            Ge => Le,
            _ => return None,
        };
        return Some((rev, n));
    }
    None
}

/// Detect `SELECT MIN(col) WHERE col >[=] c` / `SELECT MAX(col) WHERE col <[=] c` (the "natural"
/// pairing where the bound IS the extremum) over an INTEGER-affinity, single-column ASC-indexed column
/// with an integer literal bound — resolvable by one seek to the bound instead of a full scan.
///
/// INTEGER affinity + integer literal makes the seek exact: the index's storage-class order matches the
/// WHERE comparison's, so `SeekGT([c])` lands exactly on the first `col > c` (NULLs, which fail
/// `col > c`, sort first and are skipped), and `SeekLT([c])` on the last `col < c`. The opposite
/// pairings (MIN with an upper bound, MAX with a lower bound) yield the GLOBAL extremum — a different
/// shape — and decline. bd-minmax-range-seek.
fn minmax_range_seek_plan(
    agg_columns: &[AggColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
    where_clause: Option<&Expr>,
) -> Option<MinMaxRangeSeek> {
    use fsqlite_ast::BinaryOp::{Ge, Gt, Le, Lt};
    let [agg] = agg_columns else {
        return None;
    };
    if agg.arg_is_rowid
        || agg.distinct
        || agg.filter.is_some()
        || agg.hidden
        || agg.bare_expr.is_some()
        || agg.arg_expr.is_some()
        || !agg.multi_agg_indices.is_empty()
        || !agg.extra_args.is_empty()
        || agg.num_args != 1
    {
        return None;
    }
    if !builtin_aggregate_semantics_available(&agg.name, 1) {
        return None;
    }
    let is_max = match agg.name.as_str() {
        "MIN" => false,
        "MAX" => true,
        _ => return None,
    };
    let col = table.columns.get(agg.arg_col_index?)?;
    // INTEGER affinity + integer literal ⇒ the seek is exact (no affinity-skew fallback needed).
    if col.affinity != 'D' {
        return None;
    }
    let (op, bound) = extract_col_int_comparison(where_clause, table, table_alias, &col.name)?;
    let seek_op = match (is_max, op) {
        (false, Gt) => Opcode::SeekGT, // MIN col > c  → first entry > c
        (false, Ge) => Opcode::SeekGE, // MIN col >= c → first entry >= c
        (true, Lt) => Opcode::SeekLT,  // MAX col < c  → last entry < c
        (true, Le) => Opcode::SeekLE,  // MAX col <= c → last entry <= c
        _ => return None,              // unnatural pairing → global extremum, different shape
    };
    let idx =
        table.single_column_index_for_column_with_collation(&col.name, agg.collation.as_deref())?;
    Some(MinMaxRangeSeek {
        index_name: idx.name.clone(),
        index_root: idx.root_page,
        seek_op,
        bound,
    })
}

/// Detect `SELECT MIN(id) WHERE id >[=] c` / `MAX(id) WHERE id <[=] c` over the INTEGER PRIMARY KEY
/// (rowid) with an integer bound — resolvable by one seek on the table b-tree.
///
/// The rowid is a unique, never-NULL integer, so the seek is trivially exact and needs no NULL/tie
/// handling: `SeekGT`/`SeekGE` on the table lands on the first `id > c` / `>= c` (the min), `SeekLT`/
/// `SeekLE` on the last `id < c` / `<= c` (the max). Natural pairing only. Returns the seek opcode and
/// the integer bound. bd-minmax-rowid-range-seek.
fn minmax_rowid_range_seek_plan(
    agg_columns: &[AggColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
    where_clause: Option<&Expr>,
) -> Option<(Opcode, i64)> {
    use fsqlite_ast::BinaryOp::{Ge, Gt, Le, Lt};
    let [agg] = agg_columns else {
        return None;
    };
    // The aggregate is over the rowid: resolved either as the rowid alias, or as the ipk column.
    let is_rowid_agg = agg.arg_is_rowid
        || agg
            .arg_col_index
            .is_some_and(|i| table.columns.get(i).is_some_and(|c| c.is_ipk));
    if !is_rowid_agg
        || agg.distinct
        || agg.filter.is_some()
        || agg.hidden
        || agg.bare_expr.is_some()
        || agg.arg_expr.is_some()
        || !agg.multi_agg_indices.is_empty()
        || !agg.extra_args.is_empty()
        || agg.num_args != 1
        || table.without_rowid
    {
        return None;
    }
    if !builtin_aggregate_semantics_available(&agg.name, 1) {
        return None;
    }
    let is_max = match agg.name.as_str() {
        "MIN" => false,
        "MAX" => true,
        _ => return None,
    };
    // WHERE (rowid) OP <int literal>, either operand order. Rowid references (`id`, `rowid`, …) bypass
    // `column_name` (which returns None for them), so match them with `is_rowid_expr`.
    let Expr::BinaryOp {
        left, op, right, ..
    } = where_clause?
    else {
        return None;
    };
    if !matches!(op, Lt | Le | Gt | Ge) {
        return None;
    }
    let is_rowid = |e: &Expr| is_rowid_expr(e, Some(table), table_alias);
    let int_lit = |e: &Expr| match e {
        Expr::Literal(Literal::Integer(n), _) => Some(*n),
        _ => None,
    };
    let (op, bound) = if is_rowid(left)
        && let Some(n) = int_lit(right)
    {
        (*op, n)
    } else if is_rowid(right)
        && let Some(n) = int_lit(left)
    {
        let rev = match op {
            Lt => Gt,
            Le => Ge,
            Gt => Lt,
            Ge => Le,
            _ => return None,
        };
        (rev, n)
    } else {
        return None;
    };
    let seek_op = match (is_max, op) {
        (false, Gt) => Opcode::SeekGT,
        (false, Ge) => Opcode::SeekGE,
        (true, Lt) => Opcode::SeekLT,
        (true, Le) => Opcode::SeekLE,
        _ => return None, // unnatural pairing → global extremum, different shape
    };
    Some((seek_op, bound))
}

/// A single `MIN(b)`/`MAX(b)` over the SECOND key term of a composite index, constrained by
/// `WHERE <first-term> = <const>` — resolvable by one prefix seek to the extremum of the group.
struct MinMaxPrefixSeek<'e> {
    /// `true` = `MAX`; `false` = `MIN`.
    is_max: bool,
    /// `true` when key term 1 (`b`) is DESC — then `MAX(b)` is the block's FIRST entry (`SeekGE`),
    /// not the last (`SeekLE`). Only ever set for MAX (a DESC `b` declines MIN).
    b_descending: bool,
    index_name: String,
    index_root: i32,
    /// Affinity to coerce the `a` probe to (`'C'|'D'|'E'|'B'`), or `None` (untyped → no coercion).
    a_affinity: Option<char>,
    /// Collation for the `a`-block verify comparison (index key term 0), `None` for BINARY.
    a_collation: Option<String>,
    /// The `WHERE a = <const>` right-hand side (a literal or placeholder).
    a_target: &'e Expr,
}

/// Detect `SELECT MIN(b)/MAX(b) FROM t WHERE a = <const>` where a composite index `(a, b, …)` has
/// `a` as key term 0 and `b` as key term 1 (both ASC, `b`'s collation matching the aggregate).
///
/// The extremum of `b` within the `a=?` group is then a single prefix seek — `SeekLE([a])` lands on
/// the last entry of the block (its max `b`), `SeekGE([a])` on the first (walk past leading `b`-NULLs
/// for min) — instead of scanning the whole group. Mirrors the plain-MIN/MAX guards (one output
/// aggregate; no DISTINCT/FILTER/bare/multi/extra; a single plain-column arg). Byte-identical: `b` is
/// read from the index (same affinity-applied value a scan sees) and the index order equals the
/// MIN/MAX comparison order. A DESC term, a collation mismatch, or WITHOUT ROWID declines to the scan.
/// bd-minmax-prefix-seek.
fn minmax_prefix_seek_plan<'e>(
    agg_columns: &[AggColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
    where_clause: Option<&'e Expr>,
) -> Option<MinMaxPrefixSeek<'e>> {
    let [agg] = agg_columns else {
        return None;
    };
    if agg.arg_is_rowid
        || agg.distinct
        || agg.filter.is_some()
        || agg.hidden
        || agg.bare_expr.is_some()
        || agg.arg_expr.is_some()
        || !agg.multi_agg_indices.is_empty()
        || !agg.extra_args.is_empty()
        || agg.num_args != 1
    {
        return None;
    }
    if !builtin_aggregate_semantics_available(&agg.name, 1) {
        return None;
    }
    if table.without_rowid {
        return None;
    }
    let is_max = match agg.name.as_str() {
        "MIN" => false,
        "MAX" => true,
        _ => return None,
    };
    let b_col_name = table.columns.get(agg.arg_col_index?)?.name.clone();
    // BINARY `b` only: under a non-BINARY collation (e.g. NOCASE) collation-equal values can be
    // byte-different, so the index's tie representative (chosen by rowid) may differ from the scan's
    // MIN/MAX representative — not byte-identical. Such shapes decline to the group scan.
    if agg
        .collation
        .as_deref()
        .is_some_and(|c| !c.eq_ignore_ascii_case("BINARY"))
    {
        return None;
    }
    let (a_col_name, a_target) = extract_column_eq_target(where_clause, table, table_alias)?;
    if a_col_name.eq_ignore_ascii_case(&b_col_name) {
        return None;
    }
    let idx = table.indexes.iter().find(|idx| {
        idx.supports_direct_column_lookup()
            && idx.key_term_count() >= 2
            && !idx.key_term_descending(0)
            // ASC `b`: MIN=first / MAX=last of the block. DESC `b`: MAX is the block's FIRST entry
            // (SeekGE, O(log n) — no O(block) walk); MIN over a DESC `b` (last non-NULL, SeekLE) is
            // declined here, so a DESC second term is only accepted for MAX.
            && (!idx.key_term_descending(1) || is_max)
            && idx
                .columns
                .first()
                .is_some_and(|c| c.eq_ignore_ascii_case(&a_col_name))
            && idx
                .columns
                .get(1)
                .is_some_and(|c| c.eq_ignore_ascii_case(&b_col_name))
            && idx
                .key_term_collation(1)
                .is_none_or(|c| c.eq_ignore_ascii_case("BINARY"))
    })?;
    let b_descending = idx.key_term_descending(1);
    let a_affinity = table
        .column_index(&a_col_name)
        .map(|i| table.columns[i].affinity)
        .filter(|&aff| matches!(aff, 'C' | 'D' | 'E' | 'B'));
    let a_collation = idx
        .key_term_collation(0)
        .filter(|c| !c.eq_ignore_ascii_case("BINARY"))
        .map(str::to_owned);
    Some(MinMaxPrefixSeek {
        is_max,
        b_descending,
        index_name: idx.name.clone(),
        index_root: idx.root_page,
        a_affinity,
        a_collation,
        a_target,
    })
}

/// Emit the `MAX(rowid)` / `MIN(rowid)` leaf-seek fast path.
///
/// Instead of `Rewind` + AggStep-per-row + `Next` (an O(n) walk), this seeks a
/// single leaf — `Last` for `MAX`, `Rewind` for `MIN` — feeds that one row's
/// rowid through the *same* `AggStep`/`AggFinal`/wrapper sequence the slow path
/// uses, and emits the result. On an empty table the seek jumps straight to
/// finalize with the accumulator still `NULL`, so `MAX(id)` → `NULL` and
/// `COALESCE(MAX(id), 0)` → `0`, identical to stock SQLite.
///
/// Returns `Result` to mirror the sibling codegen entry points and the
/// dispatcher's `return codegen_select_minmax_rowid_seek(...)` call site, even
/// though this path is infallible.
#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_minmax_rowid_seek(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    agg_columns: &[AggColumn],
    seek_end: RowidSeekEnd,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    let agg = &agg_columns[0];

    // Single accumulator, initialized to NULL (AggStep protocol). When the
    // table is empty the seek skips AggStep and the accumulator stays NULL.
    let accum_reg = b.alloc_reg();
    b.emit_op(Opcode::Null, 0, accum_reg, 0, P4::None, 0);

    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );

    // Seek the single extremum row; jump past AggStep to finalize when empty.
    let finalize_label = b.emit_label();
    let seek_op = match seek_end {
        RowidSeekEnd::First => Opcode::Rewind,
        RowidSeekEnd::Last => Opcode::Last,
    };
    b.emit_jump_to_label(seek_op, cursor, 0, finalize_label, P4::None, 0);

    // AggStep over exactly one row: the rowid of the leaf we landed on.
    let arg_reg = b.alloc_reg();
    b.emit_op(Opcode::Rowid, cursor, arg_reg, 0, P4::None, 0);
    let agg_p4 = agg_func_p4(&agg.name, agg.collation.as_ref());
    b.emit_op(Opcode::AggStep, 0, arg_reg, accum_reg, agg_p4, 1);

    b.resolve_label(finalize_label);
    b.emit_op(
        Opcode::AggFinal,
        accum_reg,
        agg.num_args,
        0,
        P4::FuncName(agg.name.clone()),
        0,
    );

    // Move the finalized value into the output register (when distinct).
    if accum_reg != out_regs {
        b.emit_op(Opcode::Copy, accum_reg, out_regs, 0, P4::None, 0);
    }

    // Apply any scalar wrapper (e.g. COALESCE(..., 0)) exactly as the slow path.
    if let Some(wrapper) = &agg.wrapper_expr {
        emit_agg_wrapper(b, wrapper, out_regs);
    }

    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Emit the `MIN(col)` / `MAX(col)` single-seek fast path over a secondary index on `col`.
///
/// `MAX` seeks the maximum end (ASC → `Last`, DESC → `Rewind`). `MIN` seeks the minimum end and
/// walks past the NULL region toward values (ASC → `Rewind` + `Next`, DESC → `Last` + `Prev`), since
/// `min()` ignores NULLs. An empty or all-NULL index leaves the accumulator NULL. Exactly one
/// non-NULL row's value feeds the same `AggStep`/`AggFinal`/wrapper sequence the full-scan path uses,
/// so the result is bit-identical. Only the index cursor is opened — the value is index column 0, so
/// no table lookup is needed. bd-minmax-index-seek.
#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_minmax_index_seek(
    b: &mut ProgramBuilder,
    idx_cursor: i32,
    agg_columns: &[AggColumn],
    seek: &MinMaxIndexSeek,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    let agg = &agg_columns[0];

    // Single accumulator, initialized to NULL (AggStep protocol). An empty or all-NULL index skips
    // AggStep, leaving NULL — identical to the empty/all-NULL full scan.
    let accum_reg = b.alloc_reg();
    b.emit_op(Opcode::Null, 0, accum_reg, 0, P4::None, 0);

    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        seek.index_root,
        0,
        P4::Index(seek.index_name.clone()),
        0,
    );

    let finalize_label = b.emit_label();
    let arg_reg = b.alloc_reg();

    if seek.is_max {
        // MAX: single seek to the max end — ASC index → last entry, DESC index → first entry. NULLs
        // sit at the opposite end, so this entry is non-NULL unless the column is all-NULL (then it is
        // NULL and MAX(NULL) = NULL). Empty → finalize (NULL).
        let max_end = if seek.descending {
            Opcode::Rewind
        } else {
            Opcode::Last
        };
        b.emit_jump_to_label(max_end, idx_cursor, 0, finalize_label, P4::None, 0);
        b.emit_op(Opcode::Column, idx_cursor, 0, arg_reg, P4::None, 0);
    } else {
        // MIN: start at the min end and skip the NULL region toward the values — ASC → Rewind + Next,
        // DESC → Last + Prev. The first non-NULL reached is the minimum; all-NULL/empty → NULL.
        let (min_end, skip_op) = if seek.descending {
            (Opcode::Last, Opcode::Prev)
        } else {
            (Opcode::Rewind, Opcode::Next)
        };
        b.emit_jump_to_label(min_end, idx_cursor, 0, finalize_label, P4::None, 0);
        let scan_top = b.current_addr();
        let step_label = b.emit_label();
        b.emit_op(Opcode::Column, idx_cursor, 0, arg_reg, P4::None, 0);
        // Non-NULL → accumulate it (it is the minimum). NULL → advance one entry toward the values.
        b.emit_jump_to_label(Opcode::NotNull, arg_reg, 0, step_label, P4::None, 0);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let scan_body = scan_top as i32;
        // Next/Prev jumps back to re-test; falls through (all NULL) to finalize.
        b.emit_op(skip_op, idx_cursor, scan_body, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, finalize_label, P4::None, 0);
        b.resolve_label(step_label);
    }

    let agg_p4 = agg_func_p4(&agg.name, agg.collation.as_ref());
    b.emit_op(Opcode::AggStep, 0, arg_reg, accum_reg, agg_p4, 1);

    b.resolve_label(finalize_label);
    b.emit_op(
        Opcode::AggFinal,
        accum_reg,
        agg.num_args,
        0,
        P4::FuncName(agg.name.clone()),
        0,
    );

    if accum_reg != out_regs {
        b.emit_op(Opcode::Copy, accum_reg, out_regs, 0, P4::None, 0);
    }
    if let Some(wrapper) = &agg.wrapper_expr {
        emit_agg_wrapper(b, wrapper, out_regs);
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Emit `SELECT COUNT(DISTINCT col) FROM t` as a single covering index walk: open the single-column
/// ASC index, skip the leading NULL run (DISTINCT ignores NULLs), and increment the count once per
/// key-change. No ephemeral dedup B-tree and no table read. Byte-identical to the full-scan DISTINCT
/// path because the BINARY index groups equal values adjacently. bd-count-distinct-index-walk.
#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_count_distinct_index_walk(
    b: &mut ProgramBuilder,
    idx_cursor: i32,
    walk: &CountDistinctIndexWalk,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) {
    // Count accumulates directly in the output register (COUNT is never NULL; wrappers are declined).
    let count_reg = out_regs;
    let prev_reg = b.alloc_reg();
    let have_prev_reg = b.alloc_reg();
    let key_reg = b.alloc_reg();

    b.emit_op(Opcode::Integer, 0, count_reg, 0, P4::None, 0);
    b.emit_op(Opcode::Integer, 0, have_prev_reg, 0, P4::None, 0);
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        walk.index_root,
        0,
        P4::Index(walk.index_name.clone()),
        0,
    );

    let finalize_label = b.emit_label();
    // Empty index → count stays 0.
    b.emit_jump_to_label(Opcode::Rewind, idx_cursor, 0, finalize_label, P4::None, 0);

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let scan_top = b.current_addr() as i32;
    let next_label = b.emit_label();
    let count_label = b.emit_label();
    b.emit_op(Opcode::Column, idx_cursor, 0, key_reg, P4::None, 0);
    // DISTINCT ignores NULLs — skip the leading NULL run entirely.
    b.emit_jump_to_label(Opcode::IsNull, key_reg, 0, next_label, P4::None, 0);
    // First non-NULL is a new distinct value; otherwise count only when the key differs from the prev.
    b.emit_jump_to_label(Opcode::IfNot, have_prev_reg, 0, count_label, P4::None, 0);
    // Eq p1==p3 → jump (skip): key equals the previous distinct value, not new.
    b.emit_jump_to_label(Opcode::Eq, key_reg, prev_reg, next_label, P4::None, 0);
    b.resolve_label(count_label);
    b.emit_op(Opcode::AddImm, count_reg, 1, 0, P4::None, 0);
    b.emit_op(Opcode::Copy, key_reg, prev_reg, 0, P4::None, 0);
    b.emit_op(Opcode::Integer, 1, have_prev_reg, 0, P4::None, 0);
    b.resolve_label(next_label);
    b.emit_op(Opcode::Next, idx_cursor, scan_top, 0, P4::None, 0);

    b.resolve_label(finalize_label);
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
}

/// A `SELECT DISTINCT <col> FROM t` (no WHERE/GROUP BY/HAVING/LIMIT/ORDER BY) served by a loose/skip
/// index scan: emit each distinct value once, then `SeekGT [value, i64::MAX]` past the value's whole
/// duplicate run to the next distinct value. Work scales with the number of DISTINCT values, not rows.
/// bd-distinct-loose-scan.
/// Cheap `Next` attempts per distinct leading value before the skip scan pays a root-to-leaf
/// `SeekGE [leading, const]`. Keeps a near-unique leading column at full-index-walk cost (never worse
/// than the covering scan it replaces) instead of one seek per row.
const SKIP_SCAN_WALK_PROBES: usize = 3;

/// `SELECT <cols> FROM t WHERE <second_col> = <const>` where `<second_col>` is the SECOND key term of a
/// two-column ASC BINARY index whose LEADING term is a DIFFERENT (unconstrained) column — a MySQL-style
/// skip scan candidate. bd-nax2y.
struct SkipScanEqTarget<'a> {
    index: &'a IndexSchema,
    const_expr: &'a Expr,
}

/// Detect the skip-scan shape: the WHOLE WHERE is `<col> = <const>`, `<col>` is a plain BINARY
/// non-generated column that is the SECOND term of a two-column ASC BINARY index whose leading term is
/// a different column (so the leading term is unconstrained by the WHERE). The seek is
/// residual-free (the whole WHERE is the equality), so no residual filter is dropped.
fn skip_scan_eq_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &'a TableSchema,
    table_alias: Option<&str>,
) -> Option<SkipScanEqTarget<'a>> {
    if table.without_rowid {
        return None;
    }
    let (col_name, const_expr) = extract_column_eq_target(where_clause, table, table_alias)?;
    let col_idx = table.column_index(&col_name)?;
    let column = table.columns.get(col_idx)?;
    if column.generated_expr.is_some()
        || column
            .collation
            .as_deref()
            .is_some_and(|c| !c.eq_ignore_ascii_case("BINARY"))
    {
        return None;
    }
    // If a single-column index on the target column exists, the equality seek (dispatched earlier)
    // serves `col = const` directly and more cheaply than a skip scan — decline so it wins.
    if table.indexes.iter().any(|idx| {
        idx.supports_direct_column_lookup()
            && idx.key_term_count() == 1
            && idx
                .columns
                .first()
                .is_some_and(|c| c.eq_ignore_ascii_case(&col_name))
    }) {
        return None;
    }
    // Any index with >= 2 plain ASC BINARY key terms whose SECOND term is the constrained column and
    // whose FIRST (leading) term is a different, unconstrained column. Trailing key terms beyond the
    // second (`idx(a, b, c, …)`) are unconstrained too — the seek fills them with the `i64::MIN`
    // sentinel so `SeekGE` still lands on the FIRST `(leading, const, …)` entry, and the run emits every
    // matching row regardless of the trailing columns. ALL key terms must be ASC BINARY: a DESC or
    // non-BINARY trailing term would order the sentinel wrong and the seek could overshoot.
    let index = table.indexes.iter().find(|idx| {
        let kt = idx.key_term_count();
        idx.supports_direct_column_lookup()
            && kt >= 2
            && idx.columns.len() == kt
            && (0..kt).all(|i| {
                !idx.key_term_descending(i)
                    && idx
                        .key_term_collation(i)
                        .is_none_or(|c| c.eq_ignore_ascii_case("BINARY"))
            })
            && idx
                .columns
                .get(1)
                .is_some_and(|c| c.eq_ignore_ascii_case(&col_name))
            && idx
                .columns
                .first()
                .is_some_and(|c| !c.eq_ignore_ascii_case(&col_name))
    })?;
    Some(SkipScanEqTarget { index, const_expr })
}

/// The `>= 2`-column ASC BINARY index whose SECOND key term is `col_name` (a plain non-generated BINARY
/// column) and whose LEADING term differs — the skip-scan candidate for a constraint on `col_name`.
/// Declines when a single-column index on `col_name` exists (it serves the constraint directly).
fn skip_scan_second_col_index<'a>(
    table: &'a TableSchema,
    col_name: &str,
) -> Option<&'a IndexSchema> {
    let column = table
        .column_index(col_name)
        .and_then(|i| table.columns.get(i))?;
    if column.generated_expr.is_some()
        || column
            .collation
            .as_deref()
            .is_some_and(|c| !c.eq_ignore_ascii_case("BINARY"))
    {
        return None;
    }
    if table.indexes.iter().any(|idx| {
        idx.supports_direct_column_lookup()
            && idx.key_term_count() == 1
            && idx
                .columns
                .first()
                .is_some_and(|c| c.eq_ignore_ascii_case(col_name))
    }) {
        return None;
    }
    table.indexes.iter().find(|idx| {
        let kt = idx.key_term_count();
        idx.supports_direct_column_lookup()
            && kt >= 2
            && idx.columns.len() == kt
            && (0..kt).all(|i| {
                !idx.key_term_descending(i)
                    && idx
                        .key_term_collation(i)
                        .is_none_or(|c| c.eq_ignore_ascii_case("BINARY"))
            })
            && idx
                .columns
                .get(1)
                .is_some_and(|c| c.eq_ignore_ascii_case(col_name))
            && idx
                .columns
                .first()
                .is_some_and(|c| !c.eq_ignore_ascii_case(col_name))
    })
}

/// `SELECT <cols> FROM t WHERE <second_col> IS NULL` where `<second_col>` is the SECOND key term of a
/// `>= 2`-column ASC BINARY index with an unconstrained leading term. bd-nax2y IS-NULL extension.
struct SkipScanIsNullTarget<'a> {
    index: &'a IndexSchema,
}

/// Detect `WHERE <col> IS NULL` on the second key term of a skip-scan-able index. The `(x, NULL)` run is
/// at the START of each leading block (NULLs sort first), so the scan emits it and advances past the
/// rest of the block — no seek within a block.
fn skip_scan_is_null_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &'a TableSchema,
    table_alias: Option<&str>,
) -> Option<SkipScanIsNullTarget<'a>> {
    if table.without_rowid {
        return None;
    }
    let Expr::IsNull {
        expr, not: false, ..
    } = where_clause?
    else {
        return None;
    };
    let col_name = column_name(expr, table, table_alias)?;
    let index = skip_scan_second_col_index(table, &col_name)?;
    Some(SkipScanIsNullTarget { index })
}

/// A range skip-scan target: the constrained SECOND key term carries a range (with an inclusive lower
/// bound) instead of an equality. bd-nax2y range extension.
struct SkipScanRangeTarget<'a> {
    index: &'a IndexSchema,
    range: ColumnRangeTarget<'a>,
}

/// True if `term` is a range bound (`<`,`<=`,`>`,`>=`) or `BETWEEN` on `column` and nothing else — used
/// to prove the WHOLE WHERE is a range on the target so the residual-free seek drops no predicate.
fn conjunct_is_range_bound_on_column(
    term: &Expr,
    column: &str,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    match term {
        Expr::BinaryOp {
            left, op, right, ..
        } => extract_column_range_bound(left, *op, right, table, table_alias)
            .is_some_and(|(col, _, _)| col.eq_ignore_ascii_case(column)),
        Expr::Between {
            expr,
            low,
            high,
            not: false,
            ..
        } => {
            is_index_range_constant(low)
                && is_index_range_constant(high)
                && column_name(expr, table, table_alias)
                    .is_some_and(|c| c.eq_ignore_ascii_case(column))
        }
        _ => false,
    }
}

/// Detect a RANGE skip scan: the WHOLE WHERE is a range (any of `<`,`<=`,`>`,`>=`,`BETWEEN`) on a plain
/// BINARY column that is the SECOND key term of a `>= 2`-column ASC BINARY index whose leading term
/// differs (unconstrained). Inclusive lower `>=` seeks `SeekGE(x, lo, NULL…, -inf)`; exclusive `>` seeks
/// a 2-field `SeekGT(x, lo)` past the whole `(x, lo, *)` run; a no-lower `<`/`<=` walks past the NULL
/// prefix run (no seekable lower). Residual-safe: EVERY conjunct must be a bound on the target (else the
/// seek would silently drop it). Declines when a single-column index on the target exists (a plain range
/// seek serves that directly).
fn skip_scan_range_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &'a TableSchema,
    table_alias: Option<&str>,
) -> Option<SkipScanRangeTarget<'a>> {
    if table.without_rowid {
        return None;
    }
    let where_expr = where_clause?;
    let mut conjuncts = Vec::new();
    collect_conjunctive_terms(where_expr, &mut conjuncts);
    for index in &table.indexes {
        let kt = index.key_term_count();
        if !(index.supports_direct_column_lookup()
            && kt >= 2
            && index.columns.len() == kt
            && (0..kt).all(|i| {
                !index.key_term_descending(i)
                    && index
                        .key_term_collation(i)
                        .is_none_or(|c| c.eq_ignore_ascii_case("BINARY"))
            }))
        {
            continue;
        }
        let Some(target) = index.columns.get(1) else {
            continue;
        };
        // Leading term must be a DIFFERENT (unconstrained) column.
        if index
            .columns
            .first()
            .is_none_or(|c| c.eq_ignore_ascii_case(target))
        {
            continue;
        }
        // Target must be a plain, non-generated BINARY column.
        let Some(column) = table
            .column_index(target)
            .and_then(|i| table.columns.get(i))
        else {
            continue;
        };
        if column.generated_expr.is_some()
            || column
                .collation
                .as_deref()
                .is_some_and(|c| !c.eq_ignore_ascii_case("BINARY"))
        {
            continue;
        }
        // A single-column index on the target serves the range directly and more cheaply.
        if table.indexes.iter().any(|idx| {
            idx.supports_direct_column_lookup()
                && idx.key_term_count() == 1
                && idx
                    .columns
                    .first()
                    .is_some_and(|c| c.eq_ignore_ascii_case(target))
        }) {
            continue;
        }
        // The whole WHERE must be a range on the target, with an inclusive lower bound present, and no
        // conjunct on any other column (else the residual-free seek would drop it).
        let Some(range) = extract_named_column_range(where_expr, table, table_alias, target) else {
            continue;
        };
        if !conjuncts
            .iter()
            .all(|term| conjunct_is_range_bound_on_column(term, target, table, table_alias))
        {
            continue;
        }
        return Some(SkipScanRangeTarget { index, range });
    }
    None
}

/// Whether the skip scan's emission — leading key column ASC (NULLs first, as the leftmost index
/// entries), then the second key column ASC, then rowid ASC — satisfies `order_by` as a deterministic
/// TOTAL order, so the sorter can be elided. `second_varies` is true for the range scan (the 2nd column
/// is a live sort key) and false for the equality scan (the 2nd column is a constant, so it may be
/// present or absent). Every term must be plain-ASC (no DESC, no explicit NULLS) with a collation
/// matching the (BINARY) index term; the final term is the rowid, the unique tiebreaker.
fn skip_scan_order_by_satisfied(
    index: &IndexSchema,
    second_varies: bool,
    order_by: &[OrderingTerm],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    let asc_plain = |term: &OrderingTerm| {
        term.nulls.is_none() && !matches!(term.direction, Some(SortDirection::Desc))
    };
    let is_key = |term: &OrderingTerm, key_pos: usize| {
        asc_plain(term)
            && index.columns.get(key_pos).is_some_and(|col| {
                matches!(
                    resolve_column_ref(&term.expr, table, table_alias),
                    Some(SortKeySource::Column(idx))
                        if table.columns.get(idx).is_some_and(|c| c.name.eq_ignore_ascii_case(col))
                )
            })
            && collation_names_equivalent(
                column_collation(&term.expr, table, table_alias),
                index.key_term_collation(key_pos),
            )
    };
    let is_rowid = |term: &OrderingTerm| {
        asc_plain(term)
            && matches!(
                resolve_column_ref(&term.expr, table, table_alias),
                Some(SortKeySource::Rowid)
            )
    };
    match order_by {
        // `leading, rowid` — equality only (the constant 2nd column may be omitted).
        [t0, t1] if !second_varies => is_key(t0, 0) && is_rowid(t1),
        // `leading, second, rowid`.
        [t0, t1, t2] => is_key(t0, 0) && is_key(t1, 1) && is_rowid(t2),
        _ => false,
    }
}

/// Emit the skip scan. Enumerate distinct leading values; per value, adaptively WALK a few entries
/// (checking `a == const`, emitting matches) and, only for a large block, `SeekGE [x, const]` to jump
/// to the constrained run — then `SeekGT [x]` to the next distinct leading value. A near-unique
/// leading column never seeks (the walk finds the next value first), so it degrades to a full index
/// walk (== the covering scan it replaces); a low-cardinality leading column pays ~2 seeks per value.
/// The walk NEVER emits a `(x, const)` entry that the post-walk seek would re-find: the walk only
/// falls through to the seek when the last inspected `a < const` (the const run is entirely ahead).
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_select_skip_scan(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    const_expr: &Expr,
    limit_clause: Option<&LimitClause>,
) -> Result<(), CodegenError> {
    let idx_cursor = cursor + 1;
    let target_aff = idx_schema
        .columns
        .get(1)
        .and_then(|name| table.column_index(name))
        .map(|i| table.columns[i].affinity)
        .filter(|&a| matches!(a, 'C' | 'D' | 'E' | 'B'));
    let const_reg = b.alloc_reg();
    emit_expr(b, const_expr, const_reg, None);
    if let Some(aff) = target_aff
        && !bound_matches_affinity(aff, const_expr)
    {
        b.emit_op(
            Opcode::Affinity,
            const_reg,
            1,
            0,
            P4::Affinity(aff.to_string()),
            0,
        );
    }
    // `col = NULL` matches nothing in SQLite: a NULL constant yields zero rows.
    b.emit_jump_to_label(Opcode::IsNull, const_reg, 0, done_label, P4::None, 0);

    // LIMIT/OFFSET streaming (only reached when a matching ORDER BY makes the top-N deterministic).
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    let covering = resolve_covering_output_sources(columns, table, table_alias, idx_schema);
    let needs_table = covering.is_none();
    if needs_table {
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
    }
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );
    b.emit_jump_to_label(Opcode::Rewind, idx_cursor, 0, done_label, P4::None, 0);

    let x_reg = b.alloc_reg();
    let cur_x_reg = b.alloc_reg();
    let a_reg = b.alloc_reg();
    // Probe = [leading, const, MIN × (key_terms - 1)]: a full index key (every trailing key term plus
    // the rowid filled with the `i64::MIN` sentinel). This engine pads a SHORT seek probe toward the
    // HIGH end (which is why the 1-field `SeekGT` advance below correctly lands past the whole `(x, *)`
    // run), so a bare `(x, const)` `SeekGE` would overshoot PAST the `(x, const, …)` run instead of
    // landing on its first entry. `MIN` sorts before every real value, anchoring `SeekGE` on the first
    // `(x, const, …)` across any >=2-col index — mirrors the composite prefix+range seek.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let key_terms = idx_schema.key_term_count() as i32;
    let probe_base = b.alloc_regs(key_terms + 1);
    let probe_rec = b.alloc_reg();
    let rowid_reg = b.alloc_reg();

    let emit_run = b.emit_label();
    let advance = b.emit_label();
    let bin = || P4::Collation("BINARY".to_owned());

    // outer: positioned at the first entry of a new distinct leading value.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let outer = b.current_addr() as i32;
    b.emit_op(Opcode::Column, idx_cursor, 0, x_reg, P4::None, 0);
    b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
    b.emit_jump_to_label(Opcode::Eq, a_reg, const_reg, emit_run, bin(), 0);
    // `Gt(const, a)` jumps on `a > const` (jump cond is `reg[P3] OP reg[P1]`); see the walk copy below.
    b.emit_jump_to_label(Opcode::Gt, const_reg, a_reg, advance, bin(), 0);
    // a < const (or NULL): adaptive walk.
    for _ in 0..SKIP_SCAN_WALK_PROBES {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let next_addr = b.current_addr() as i32;
        b.emit_op(Opcode::Next, idx_cursor, next_addr + 2, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::Column, idx_cursor, 0, cur_x_reg, P4::None, 0);
        b.emit_op(Opcode::Ne, x_reg, outer, cur_x_reg, bin(), 0x80);
        b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
        b.emit_jump_to_label(Opcode::Eq, a_reg, const_reg, emit_run, bin(), 0);
        // `emit_jump_to_label(OP, P1, P3)` jumps when `reg[P3] OP reg[P1]`, so to advance on `a > const`
        // the const is P1 and `a` is P3 (a bare `Gt(a, const)` would test `const > a` == `a < const` and
        // wrongly skip the whole block on its first sub-const row). `Eq`/`Ne` above are symmetric.
        b.emit_jump_to_label(Opcode::Gt, const_reg, a_reg, advance, bin(), 0);
    }
    // Large block, still a < const: seek straight to the first (x, const, NULL…, -inf). Trailing KEY
    // columns get NULL (which sorts BEFORE every value, so the seek lands on the FIRST `(x, const, …)`
    // entry — a MIN integer would skip past `(x, const, NULL, …)` rows since NULL sorts below it); only
    // the rowid slot gets `i64::MIN` (rowids are never NULL and MIN sorts before every real rowid).
    b.emit_op(Opcode::Copy, x_reg, probe_base, 0, P4::None, 0);
    b.emit_op(Opcode::Copy, const_reg, probe_base + 1, 0, P4::None, 0);
    for off in 2..key_terms {
        b.emit_op(Opcode::Null, 0, probe_base + off, 0, P4::None, 0);
    }
    b.emit_op(
        Opcode::Int64,
        0,
        probe_base + key_terms,
        0,
        P4::Int64(i64::MIN),
        0,
    );
    b.emit_op(
        Opcode::MakeRecord,
        probe_base,
        key_terms + 1,
        probe_rec,
        P4::None,
        0,
    );
    b.emit_jump_to_label(
        Opcode::SeekGE,
        idx_cursor,
        probe_rec,
        done_label,
        P4::None,
        0,
    );
    b.emit_op(Opcode::Column, idx_cursor, 0, cur_x_reg, P4::None, 0);
    b.emit_op(Opcode::Ne, x_reg, outer, cur_x_reg, bin(), 0x80);
    b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
    b.emit_jump_to_label(Opcode::Ne, a_reg, const_reg, advance, bin(), 0);
    // fall through to emit_run.

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let emit_run_addr = b.current_addr() as i32;
    b.resolve_label(emit_run);
    b.emit_op(Opcode::Column, idx_cursor, 0, cur_x_reg, P4::None, 0);
    b.emit_op(Opcode::Ne, x_reg, outer, cur_x_reg, bin(), 0x80);
    b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
    b.emit_jump_to_label(Opcode::Ne, a_reg, const_reg, advance, bin(), 0);
    b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
    let emit_next = b.emit_label();
    if needs_table {
        b.emit_jump_to_label(Opcode::SeekRowid, cursor, rowid_reg, emit_next, P4::None, 0);
    }
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, emit_next, P4::None, 0);
    }
    if let Some(cov) = &covering {
        emit_covering_output_reads(b, idx_cursor, rowid_reg, cov, out_regs);
    } else {
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }
    b.resolve_label(emit_next);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let emit_next_addr = b.current_addr() as i32;
    b.emit_op(Opcode::Next, idx_cursor, emit_next_addr + 2, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
    b.emit_op(Opcode::Goto, 0, emit_run_addr, 0, P4::None, 0);

    // advance: at (x, a>const); skip to the next distinct leading value.
    b.resolve_label(advance);
    b.emit_op(Opcode::Copy, x_reg, probe_base, 0, P4::None, 0);
    b.emit_op(Opcode::MakeRecord, probe_base, 1, probe_rec, P4::None, 0);
    b.emit_jump_to_label(
        Opcode::SeekGT,
        idx_cursor,
        probe_rec,
        done_label,
        P4::None,
        0,
    );
    b.emit_op(Opcode::Goto, 0, outer, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    if needs_table {
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Emit the three range-membership jumps for one index entry whose second-key value is in `a_reg`:
/// jump to `advance` when it is ABOVE the range (`a > up` inclusive / `a >= up` exclusive), else jump
/// to `emit_run` when it has reached the lower (`a >= lo` inclusive / `a > lo` exclusive), else fall
/// through (below the range or NULL — the caller keeps walking). `emit_jump_to_label(OP, P1, P3)` jumps
/// on `reg[P3] OP reg[P1]`, so the bound register is P1 and `a` is P3 (matches the composite emitter).
fn emit_skip_scan_range_decision(
    b: &mut ProgramBuilder,
    upper: Option<(i32, bool)>,
    lower: Option<(i32, bool)>,
    a_reg: i32,
    advance: crate::Label,
    emit_run: crate::Label,
) {
    let bin = || P4::Collation("BINARY".to_owned());
    if let Some((up_reg, up_inclusive)) = upper {
        let above = if up_inclusive { Opcode::Gt } else { Opcode::Ge };
        b.emit_jump_to_label(above, up_reg, a_reg, advance, bin(), 0);
    }
    match lower {
        Some((lo_reg, lo_inclusive)) => {
            let reached = if lo_inclusive { Opcode::Ge } else { Opcode::Gt };
            b.emit_jump_to_label(reached, lo_reg, a_reg, emit_run, bin(), 0);
        }
        // No lower bound: any NON-NULL value not above the upper is in range. NULLs sort first and are
        // excluded, so they are the only "below" — the caller keeps walking on fall-through.
        None => {
            b.emit_jump_to_label(Opcode::NotNull, a_reg, 0, emit_run, P4::None, 0);
        }
    }
}

/// Range skip scan (bd-nax2y): the second key term carries a range with a lower bound (inclusive or
/// exclusive, optionally an upper bound) instead of an equality. Same distinct-leading-value iteration +
/// adaptive walk as [`codegen_select_skip_scan`], but each entry is classified by
/// [`emit_skip_scan_range_decision`] (above → advance to the next leading value, in-range → emit,
/// below/NULL → keep walking) and the seek anchors on the first in-range entry per leading value
/// (`SeekGE (x, lo, NULL…, -inf)` for `>=`, 2-field `SeekGT (x, lo)` for `>`). Byte-identical to C SQLite.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_select_skip_scan_range(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    range: &ColumnRangeTarget<'_>,
    limit_clause: Option<&LimitClause>,
) -> Result<(), CodegenError> {
    let idx_cursor = cursor + 1;
    let target_aff = idx_schema
        .columns
        .get(1)
        .and_then(|name| table.column_index(name))
        .map(|i| table.columns[i].affinity)
        .filter(|&a| matches!(a, 'C' | 'D' | 'E' | 'B'));
    let coerce = |b: &mut ProgramBuilder, reg: i32, expr: &Expr| {
        if let Some(aff) = target_aff
            && !bound_matches_affinity(aff, expr)
        {
            b.emit_op(
                Opcode::Affinity,
                reg,
                1,
                0,
                P4::Affinity(aff.to_string()),
                0,
            );
        }
    };
    // Lower bound (optional — absent for a no-lower `< hi` / `<= hi` range). A NULL bound matches
    // nothing → zero rows.
    let lower = range.lower.as_ref().map(|bound| {
        let lo_expr = bound.expr();
        let lo_reg = b.alloc_reg();
        emit_expr(b, lo_expr, lo_reg, None);
        coerce(b, lo_reg, lo_expr);
        b.emit_jump_to_label(Opcode::IsNull, lo_reg, 0, done_label, P4::None, 0);
        (lo_reg, bound.inclusive)
    });
    // Optional upper bound.
    let upper = range.upper.as_ref().map(|bound| {
        let up_reg = b.alloc_reg();
        emit_expr(b, bound.expr(), up_reg, None);
        coerce(b, up_reg, bound.expr());
        b.emit_jump_to_label(Opcode::IsNull, up_reg, 0, done_label, P4::None, 0);
        (up_reg, bound.inclusive)
    });

    // LIMIT/OFFSET streaming (only reached when a matching ORDER BY makes the top-N deterministic).
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    let covering = resolve_covering_output_sources(columns, table, table_alias, idx_schema);
    let needs_table = covering.is_none();
    if needs_table {
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
    }
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );
    b.emit_jump_to_label(Opcode::Rewind, idx_cursor, 0, done_label, P4::None, 0);

    let x_reg = b.alloc_reg();
    let cur_x_reg = b.alloc_reg();
    let a_reg = b.alloc_reg();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let key_terms = idx_schema.key_term_count() as i32;
    let probe_base = b.alloc_regs(key_terms + 1);
    let probe_rec = b.alloc_reg();
    let rowid_reg = b.alloc_reg();

    let emit_run = b.emit_label();
    let advance = b.emit_label();
    let bin = || P4::Collation("BINARY".to_owned());

    // outer: positioned at the first entry of a new distinct leading value.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let outer = b.current_addr() as i32;
    b.emit_op(Opcode::Column, idx_cursor, 0, x_reg, P4::None, 0);
    b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
    emit_skip_scan_range_decision(b, upper, lower, a_reg, advance, emit_run);
    if let Some((lo_reg, lo_inclusive)) = lower {
        // below the lower bound (or NULL): adaptive walk, then seek to the first in-range entry.
        for _ in 0..SKIP_SCAN_WALK_PROBES {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let next_addr = b.current_addr() as i32;
            b.emit_op(Opcode::Next, idx_cursor, next_addr + 2, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
            b.emit_op(Opcode::Column, idx_cursor, 0, cur_x_reg, P4::None, 0);
            b.emit_op(Opcode::Ne, x_reg, outer, cur_x_reg, bin(), 0x80);
            b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
            emit_skip_scan_range_decision(b, upper, lower, a_reg, advance, emit_run);
        }
        // Large block, still below the lower bound: seek to the first in-range entry. Inclusive `>= lo`:
        // `SeekGE (x, lo, NULL…, -inf)` lands on the first `(x, lo, …)`. Exclusive `> lo`: a 2-field
        // `SeekGT (x, lo)` — the engine pads the short probe toward the HIGH end, so it lands past the
        // whole `(x, lo, *)` run on the first `(x, b > lo)`.
        b.emit_op(Opcode::Copy, x_reg, probe_base, 0, P4::None, 0);
        b.emit_op(Opcode::Copy, lo_reg, probe_base + 1, 0, P4::None, 0);
        if lo_inclusive {
            for off in 2..key_terms {
                b.emit_op(Opcode::Null, 0, probe_base + off, 0, P4::None, 0);
            }
            b.emit_op(
                Opcode::Int64,
                0,
                probe_base + key_terms,
                0,
                P4::Int64(i64::MIN),
                0,
            );
            b.emit_op(
                Opcode::MakeRecord,
                probe_base,
                key_terms + 1,
                probe_rec,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::SeekGE,
                idx_cursor,
                probe_rec,
                done_label,
                P4::None,
                0,
            );
        } else {
            b.emit_op(Opcode::MakeRecord, probe_base, 2, probe_rec, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::SeekGT,
                idx_cursor,
                probe_rec,
                done_label,
                P4::None,
                0,
            );
        }
        b.emit_op(Opcode::Column, idx_cursor, 0, cur_x_reg, P4::None, 0);
        b.emit_op(Opcode::Ne, x_reg, outer, cur_x_reg, bin(), 0x80);
        b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
        // Now at/after the lower bound, so this either advances (above upper) or emits.
        emit_skip_scan_range_decision(b, upper, lower, a_reg, advance, emit_run);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, advance, P4::None, 0);
    } else {
        // No lower bound: the only sub-range values are the NULL prefix run at the block start (NULLs
        // sort first and are excluded). Walk past them — unbounded, but NULL runs are short and the
        // required upper bound still terminates the emitted run. No seek is possible without a lower.
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let null_walk = b.current_addr() as i32;
        b.emit_op(Opcode::Next, idx_cursor, null_walk + 2, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::Column, idx_cursor, 0, cur_x_reg, P4::None, 0);
        b.emit_op(Opcode::Ne, x_reg, outer, cur_x_reg, bin(), 0x80);
        b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
        emit_skip_scan_range_decision(b, upper, lower, a_reg, advance, emit_run);
        b.emit_op(Opcode::Goto, 0, null_walk, 0, P4::None, 0);
    }

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let emit_run_addr = b.current_addr() as i32;
    b.resolve_label(emit_run);
    b.emit_op(Opcode::Column, idx_cursor, 0, cur_x_reg, P4::None, 0);
    b.emit_op(Opcode::Ne, x_reg, outer, cur_x_reg, bin(), 0x80);
    b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
    // Sorted ascending: once in-range the lower bound stays satisfied, so only the upper bound can end
    // the run (besides a leading-value change) — jump to advance when the value climbs above it.
    if let Some((up_reg, up_inclusive)) = upper {
        let above = if up_inclusive { Opcode::Gt } else { Opcode::Ge };
        b.emit_jump_to_label(above, up_reg, a_reg, advance, bin(), 0);
    }
    b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
    let emit_next = b.emit_label();
    if needs_table {
        b.emit_jump_to_label(Opcode::SeekRowid, cursor, rowid_reg, emit_next, P4::None, 0);
    }
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, emit_next, P4::None, 0);
    }
    if let Some(cov) = &covering {
        emit_covering_output_reads(b, idx_cursor, rowid_reg, cov, out_regs);
    } else {
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }
    b.resolve_label(emit_next);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let emit_next_addr = b.current_addr() as i32;
    b.emit_op(Opcode::Next, idx_cursor, emit_next_addr + 2, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
    b.emit_op(Opcode::Goto, 0, emit_run_addr, 0, P4::None, 0);

    // advance: skip to the next distinct leading value.
    b.resolve_label(advance);
    b.emit_op(Opcode::Copy, x_reg, probe_base, 0, P4::None, 0);
    b.emit_op(Opcode::MakeRecord, probe_base, 1, probe_rec, P4::None, 0);
    b.emit_jump_to_label(
        Opcode::SeekGT,
        idx_cursor,
        probe_rec,
        done_label,
        P4::None,
        0,
    );
    b.emit_op(Opcode::Goto, 0, outer, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    if needs_table {
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// IS-NULL skip scan (bd-nax2y): `WHERE <second_col> IS NULL`. The `(x, NULL)` run sits at the START of
/// each leading block (NULLs sort first), so per distinct leading value the scan emits that run and
/// `SeekGT [x]` to the next value — no walk or seek within a block. Streams `x ASC (NULLs first), rowid
/// ASC`, so a matching ORDER BY elides the sorter and LIMIT/OFFSET stream. Byte-identical to C SQLite.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_select_skip_scan_is_null(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    idx_schema: &IndexSchema,
    limit_clause: Option<&LimitClause>,
) -> Result<(), CodegenError> {
    let idx_cursor = cursor + 1;
    // LIMIT/OFFSET streaming (only reached when a matching ORDER BY makes the top-N deterministic).
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    let covering = resolve_covering_output_sources(columns, table, table_alias, idx_schema);
    let needs_table = covering.is_none();
    if needs_table {
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
    }
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );
    b.emit_jump_to_label(Opcode::Rewind, idx_cursor, 0, done_label, P4::None, 0);

    let x_reg = b.alloc_reg();
    let cur_x_reg = b.alloc_reg();
    let a_reg = b.alloc_reg();
    let probe_base = b.alloc_reg();
    let probe_rec = b.alloc_reg();
    let rowid_reg = b.alloc_reg();

    let emit_run = b.emit_label();
    let advance = b.emit_label();
    let bin = || P4::Collation("BINARY".to_owned());

    // outer: at the first entry of a new distinct leading value (the block's NULL run, if any).
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let outer = b.current_addr() as i32;
    b.emit_op(Opcode::Column, idx_cursor, 0, x_reg, P4::None, 0);
    b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
    // A non-NULL second key at the block start means the block has no NULL run — advance.
    b.emit_jump_to_label(Opcode::NotNull, a_reg, 0, advance, P4::None, 0);
    // fall through to emit_run (the second key is NULL).

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let emit_run_addr = b.current_addr() as i32;
    b.resolve_label(emit_run);
    b.emit_op(Opcode::Column, idx_cursor, 0, cur_x_reg, P4::None, 0);
    b.emit_op(Opcode::Ne, x_reg, outer, cur_x_reg, bin(), 0x80);
    b.emit_op(Opcode::Column, idx_cursor, 1, a_reg, P4::None, 0);
    // The NULL run ends at the first non-NULL second key (sorted ascending, NULLs first) — advance.
    b.emit_jump_to_label(Opcode::NotNull, a_reg, 0, advance, P4::None, 0);
    b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
    let emit_next = b.emit_label();
    if needs_table {
        b.emit_jump_to_label(Opcode::SeekRowid, cursor, rowid_reg, emit_next, P4::None, 0);
    }
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, emit_next, P4::None, 0);
    }
    if let Some(cov) = &covering {
        emit_covering_output_reads(b, idx_cursor, rowid_reg, cov, out_regs);
    } else {
        emit_column_reads(b, cursor, columns, table, table_alias, schema, out_regs)?;
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }
    b.resolve_label(emit_next);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let emit_next_addr = b.current_addr() as i32;
    b.emit_op(Opcode::Next, idx_cursor, emit_next_addr + 2, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
    b.emit_op(Opcode::Goto, 0, emit_run_addr, 0, P4::None, 0);

    // advance: skip to the next distinct leading value.
    b.resolve_label(advance);
    b.emit_op(Opcode::Copy, x_reg, probe_base, 0, P4::None, 0);
    b.emit_op(Opcode::MakeRecord, probe_base, 1, probe_rec, P4::None, 0);
    b.emit_jump_to_label(
        Opcode::SeekGT,
        idx_cursor,
        probe_rec,
        done_label,
        P4::None,
        0,
    );
    b.emit_op(Opcode::Goto, 0, outer, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    if needs_table {
        b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

struct DistinctLooseScan {
    index_name: String,
    index_root: i32,
    /// Number of leading index key terms that equal the DISTINCT output columns
    /// (in SELECT order). 1 for `SELECT DISTINCT a`; N for `SELECT DISTINCT a, b, …`
    /// served by an index whose leading N terms are exactly those columns.
    key_col_count: usize,
}

/// Cheap `Next` attempts per emitted value before the loose scan pays for a
/// root-to-leaf `SeekGT` past the run. Keeps all-distinct indexes at
/// emit-on-change-walk cost instead of one seek per row.
const DISTINCT_LOOSE_SCAN_NEXT_PROBES: usize = 3;

/// Detect `SELECT DISTINCT <col>` resolvable by a loose index scan. Gated tight so the loose scan is
/// provably byte-identical to the sorter path: exactly one plain-column output (not `*`/rowid/expr), a
/// BINARY column with a single-column ASC BINARY index (so index key order == the DISTINCT comparison),
/// not a generated column, and not WITHOUT ROWID. WHERE/GROUP BY/HAVING/LIMIT are excluded by the caller.
/// Searches all indexes so a composite `(col, …)` declared first does not shadow a usable single-column
/// one (bd-agg-range-shadowed-index).
fn distinct_loose_scan_plan(
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<DistinctLooseScan> {
    if table.without_rowid || columns.is_empty() {
        return None;
    }
    // Every output must be a plain, non-generated, BINARY column reference. Collect their names in
    // SELECT order — they must equal the chosen index's leading key terms in the SAME order, so the
    // emitted tuples are exactly the index's leading-prefix groups in index order (byte-identical to
    // C SQLite, which walks the same covering index for `SELECT DISTINCT <prefix cols>`).
    let mut col_names: Vec<String> = Vec::with_capacity(columns.len());
    for rc in columns {
        let ResultColumn::Expr { expr, .. } = rc else {
            return None;
        };
        let SortKeySource::Column(col_idx) = resolve_column_ref(expr, table, table_alias)? else {
            return None;
        };
        let column = table.columns.get(col_idx)?;
        // BINARY only: the index's BINARY key order must equal the DISTINCT comparison so adjacent-run
        // skipping matches C SQLite's grouping. Generated columns decline (first cut).
        if column.generated_expr.is_some()
            || column
                .collation
                .as_deref()
                .is_some_and(|c| !c.eq_ignore_ascii_case("BINARY"))
        {
            return None;
        }
        col_names.push(column.name.clone());
    }
    let n = col_names.len();
    // The loose scan reads index columns 0..N-1 and probes with an N-field prefix `[v0..vN-1]`, so
    // any index whose LEADING N key terms are exactly these columns (same order, each ASC BINARY)
    // qualifies — entries sharing that leading tuple (regardless of trailing terms) are all cleared
    // by one `SeekGT [v0..vN-1]`. `supports_direct_column_lookup` still excludes partial (WHERE) and
    // expression indexes, so the chosen index is a full-coverage plain-column index. Prefer the
    // narrowest qualifying index (fewest key terms => smallest entries to scan); this keeps the
    // historical single-column choice when one exists and never uses a wider composite unnecessarily.
    let idx = table
        .indexes
        .iter()
        .filter(|idx| {
            idx.supports_direct_column_lookup()
                && idx.key_term_count() >= n
                && (0..n).all(|i| {
                    !idx.key_term_descending(i)
                        && idx
                            .columns
                            .get(i)
                            .is_some_and(|c| c.eq_ignore_ascii_case(&col_names[i]))
                        && idx
                            .key_term_collation(i)
                            .is_none_or(|c| c.eq_ignore_ascii_case("BINARY"))
                })
        })
        .min_by_key(|idx| idx.key_term_count())?;
    Some(DistinctLooseScan {
        index_name: idx.name.clone(),
        index_root: idx.root_page,
        key_col_count: n,
    })
}

/// Emit `SELECT DISTINCT <col> FROM t` as a loose/skip index scan: open the single-column index, emit
/// the first entry's value, then repeatedly `SeekGT [value]` past the current value's entire duplicate
/// run to the next distinct value. NULL (if present) sorts first and is emitted once like any value.
/// Terminates in ≤ #distinct seeks. The probe is a 1-FIELD prefix `[value]`: `SeekGT`'s index upper-bound
/// (`index_seek_with_bias(UpperBound)`) treats a shorter prefix probe as sorting AFTER every equal-prefix
/// entry (`compare_index_key_values`: `rhs.len() <= lhs.len() => Less`), so one seek clears the whole run.
/// bd-distinct-loose-scan.
#[allow(clippy::unnecessary_wraps)]
fn codegen_select_distinct_loose_scan(
    b: &mut ProgramBuilder,
    idx_cursor: i32,
    scan: &DistinctLooseScan,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        scan.index_root,
        0,
        P4::Index(scan.index_name.clone()),
        0,
    );
    let finalize_label = b.emit_label();
    // Empty index → nothing to emit.
    b.emit_jump_to_label(Opcode::Rewind, idx_cursor, 0, finalize_label, P4::None, 0);

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_top = b.current_addr() as i32;
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let n = scan.key_col_count as i32;
    // Emit the current distinct tuple (index columns 0..N-1), then skip its whole duplicate run.
    // The probe copy MUST precede ResultRow: the engine's ResultRow drains its source
    // registers (`take_reg_range`), so a Copy placed after it reads NULL and the SeekGT
    // probe becomes a constant `[NULL, …]` — the loop then re-emits one row forever (the
    // "skip-scan hang" this bead was blocked on).
    for i in 0..n {
        b.emit_op(Opcode::Column, idx_cursor, i, out_regs + i, P4::None, 0);
    }
    let probe_base = b.alloc_regs(n);
    for i in 0..n {
        b.emit_op(Opcode::Copy, out_regs + i, probe_base + i, 0, P4::None, 0);
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    // Adaptive skip (MySQL-style loose scan): try a few cheap Next steps before paying
    // for a root-to-leaf SeekGT. Long duplicate runs fall through to the seek (one seek
    // clears the whole run); short/unique runs leave via the Ne and never seek, so an
    // all-distinct index degrades to an emit-on-change walk instead of one full-height
    // seek per row (~11x worse than the sorter when measured). Each Ne carries NULLEQ
    // (0x80) + BINARY collation so a NULL run is one distinct value, matching index key
    // order; a tuple change on ANY column jumps back to emit the new distinct tuple.
    let cur_base = b.alloc_regs(n);
    for _ in 0..DISTINCT_LOOSE_SCAN_NEXT_PROBES {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let next_addr = b.current_addr() as i32;
        // Next jumps to p2 when a next entry exists; falls through at EOF.
        b.emit_op(Opcode::Next, idx_cursor, next_addr + 2, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, finalize_label, P4::None, 0);
        for i in 0..n {
            b.emit_op(Opcode::Column, idx_cursor, i, cur_base + i, P4::None, 0);
        }
        for i in 0..n {
            b.emit_op(
                Opcode::Ne,
                probe_base + i,
                loop_top,
                cur_base + i,
                P4::Collation("BINARY".to_owned()),
                0x80,
            );
        }
    }
    let probe_record_reg = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        probe_base,
        n,
        probe_record_reg,
        P4::None,
        0,
    );
    // No entry beyond the [v0..vN-1] prefix run → the run was the last one → done.
    b.emit_jump_to_label(
        Opcode::SeekGT,
        idx_cursor,
        probe_record_reg,
        finalize_label,
        P4::None,
        0,
    );
    b.emit_op(Opcode::Goto, 0, loop_top, 0, P4::None, 0);

    b.resolve_label(finalize_label);
    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Emit `SELECT MIN(col), MAX(col)` over one indexed column as TWO seeks to the two index ends — the
/// MIN end (skipping its NULL region) and the MAX end — instead of a full scan. The cursor is
/// repositioned by the MAX seek, so the two are independent; each feeds its own accumulator exactly as
/// the single-seek path, then both finalize into their SELECT-order output registers. bd-minmax-pair-seek.
#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_minmax_pair_seek(
    b: &mut ProgramBuilder,
    idx_cursor: i32,
    agg_columns: &[AggColumn],
    seek: &MinMaxPairSeek,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    let min_agg = &agg_columns[seek.min_out_col as usize];
    let max_agg = &agg_columns[seek.max_out_col as usize];
    let min_out = out_regs + seek.min_out_col;
    let max_out = out_regs + seek.max_out_col;

    let accum_min = b.alloc_reg();
    let accum_max = b.alloc_reg();
    b.emit_op(Opcode::Null, 0, accum_min, 0, P4::None, 0);
    b.emit_op(Opcode::Null, 0, accum_max, 0, P4::None, 0);

    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        seek.index_root,
        0,
        P4::Index(seek.index_name.clone()),
        0,
    );

    let arg_reg = b.alloc_reg();

    // MIN: from the min end, skip the NULL region toward the values (ASC → Rewind+Next; DESC → Last+Prev).
    let (min_end, skip_op) = if seek.descending {
        (Opcode::Last, Opcode::Prev)
    } else {
        (Opcode::Rewind, Opcode::Next)
    };
    let after_min = b.emit_label();
    b.emit_jump_to_label(min_end, idx_cursor, 0, after_min, P4::None, 0);
    let min_loop = b.current_addr();
    let feed_min = b.emit_label();
    b.emit_op(Opcode::Column, idx_cursor, 0, arg_reg, P4::None, 0);
    b.emit_jump_to_label(Opcode::NotNull, arg_reg, 0, feed_min, P4::None, 0);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let min_body = min_loop as i32;
    b.emit_op(skip_op, idx_cursor, min_body, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, after_min, P4::None, 0);
    b.resolve_label(feed_min);
    b.emit_op(
        Opcode::AggStep,
        0,
        arg_reg,
        accum_min,
        agg_func_p4(&min_agg.name, min_agg.collation.as_ref()),
        1,
    );
    b.resolve_label(after_min);

    // MAX: single seek to the max end (ASC → Last; DESC → Rewind). Repositions the cursor.
    let max_end = if seek.descending {
        Opcode::Rewind
    } else {
        Opcode::Last
    };
    let after_max = b.emit_label();
    b.emit_jump_to_label(max_end, idx_cursor, 0, after_max, P4::None, 0);
    b.emit_op(Opcode::Column, idx_cursor, 0, arg_reg, P4::None, 0);
    b.emit_op(
        Opcode::AggStep,
        0,
        arg_reg,
        accum_max,
        agg_func_p4(&max_agg.name, max_agg.collation.as_ref()),
        1,
    );
    b.resolve_label(after_max);

    // Finalize both into their SELECT-order output registers.
    b.emit_op(
        Opcode::AggFinal,
        accum_min,
        min_agg.num_args,
        0,
        P4::FuncName(min_agg.name.clone()),
        0,
    );
    if accum_min != min_out {
        b.emit_op(Opcode::Copy, accum_min, min_out, 0, P4::None, 0);
    }
    b.emit_op(
        Opcode::AggFinal,
        accum_max,
        max_agg.num_args,
        0,
        P4::FuncName(max_agg.name.clone()),
        0,
    );
    if accum_max != max_out {
        b.emit_op(Opcode::Copy, accum_max, max_out, 0, P4::None, 0);
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Emit `SELECT MIN(col) WHERE col >[=] c` / `MAX(col) WHERE col <[=] c` as ONE seek to the bound.
///
/// The 1-field probe `[c]` (an integer, matching the INTEGER-affinity column) is `Seek*`'d: `SeekGT`/
/// `SeekGE` lands on the first `col > c` / `>= c` (the min at the bound; NULLs sort first and fail the
/// predicate, so the seek skips them), `SeekLT`/`SeekLE` on the last `col < c` / `<= c` (the max). The
/// single extremum feeds the same AggStep/AggFinal/wrapper sequence the scan uses; an empty match
/// (`Seek*` past the end, or a NULL landed for MAX) leaves the accumulator NULL. bd-minmax-range-seek.
#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_minmax_range_seek(
    b: &mut ProgramBuilder,
    idx_cursor: i32,
    agg_columns: &[AggColumn],
    seek: &MinMaxRangeSeek,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    let agg = &agg_columns[0];
    let accum_reg = b.alloc_reg();
    b.emit_op(Opcode::Null, 0, accum_reg, 0, P4::None, 0);

    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        seek.index_root,
        0,
        P4::Index(seek.index_name.clone()),
        0,
    );

    let finalize_label = b.emit_label();

    // 1-field probe [bound] for the range seek.
    let bound_reg = b.alloc_reg();
    b.emit_op(Opcode::Int64, 0, bound_reg, 0, P4::Int64(seek.bound), 0);
    let probe_rec = b.alloc_reg();
    b.emit_op(Opcode::MakeRecord, bound_reg, 1, probe_rec, P4::None, 0);
    // Seek to the bound; jump to finalize (accumulator NULL) when no row satisfies it.
    b.emit_jump_to_label(
        seek.seek_op,
        idx_cursor,
        probe_rec,
        finalize_label,
        P4::None,
        0,
    );

    let arg_reg = b.alloc_reg();
    b.emit_op(Opcode::Column, idx_cursor, 0, arg_reg, P4::None, 0);
    b.emit_op(
        Opcode::AggStep,
        0,
        arg_reg,
        accum_reg,
        agg_func_p4(&agg.name, agg.collation.as_ref()),
        1,
    );

    b.resolve_label(finalize_label);
    b.emit_op(
        Opcode::AggFinal,
        accum_reg,
        agg.num_args,
        0,
        P4::FuncName(agg.name.clone()),
        0,
    );
    if accum_reg != out_regs {
        b.emit_op(Opcode::Copy, accum_reg, out_regs, 0, P4::None, 0);
    }
    if let Some(wrapper) = &agg.wrapper_expr {
        emit_agg_wrapper(b, wrapper, out_regs);
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Emit `SELECT MIN(id) WHERE id >[=] c` / `MAX(id) WHERE id <[=] c` (rowid) as ONE table b-tree seek.
///
/// The rowid is a unique, never-NULL integer, so `Seek*` (a scalar rowid key — no `MakeRecord`) lands
/// directly on the extremum: `SeekGT`/`SeekGE` on the first `id > c` / `>= c`, `SeekLT`/`SeekLE` on the
/// last `id < c` / `<= c`. The single rowid feeds the shared AggStep/AggFinal/wrapper; an empty match
/// (`Seek*` past the end) leaves the accumulator NULL. bd-minmax-rowid-range-seek.
#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_minmax_rowid_range_seek(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    agg_columns: &[AggColumn],
    seek_op: Opcode,
    bound: i64,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    let agg = &agg_columns[0];
    let accum_reg = b.alloc_reg();
    b.emit_op(Opcode::Null, 0, accum_reg, 0, P4::None, 0);

    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );

    let finalize_label = b.emit_label();
    // Scalar rowid key (table b-tree seek — not a record); jump to finalize (NULL) when no row matches.
    let bound_reg = b.alloc_reg();
    b.emit_op(Opcode::Int64, 0, bound_reg, 0, P4::Int64(bound), 0);
    b.emit_jump_to_label(seek_op, cursor, bound_reg, finalize_label, P4::None, 0);

    let arg_reg = b.alloc_reg();
    b.emit_op(Opcode::Rowid, cursor, arg_reg, 0, P4::None, 0);
    b.emit_op(
        Opcode::AggStep,
        0,
        arg_reg,
        accum_reg,
        agg_func_p4(&agg.name, agg.collation.as_ref()),
        1,
    );

    b.resolve_label(finalize_label);
    b.emit_op(
        Opcode::AggFinal,
        accum_reg,
        agg.num_args,
        0,
        P4::FuncName(agg.name.clone()),
        0,
    );
    if accum_reg != out_regs {
        b.emit_op(Opcode::Copy, accum_reg, out_regs, 0, P4::None, 0);
    }
    if let Some(wrapper) = &agg.wrapper_expr {
        emit_agg_wrapper(b, wrapper, out_regs);
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Emit the composite-prefix `MIN(b)`/`MAX(b) WHERE a = <const>` seek: one seek to the extremum of
/// `b` within the `a=?` block of a `(a, b, …)` index, instead of scanning the whole group.
///
/// The `a` probe (a partial 1-field key) is coerced to `a`'s affinity, then:
/// - MAX → `SeekLE([a])` lands on the LAST entry of the block; its `b` (index column 1) is the maximum
///   (NULLs sort first, so a NULL there means the whole block's `b` is NULL → MAX = NULL).
/// - MIN → `SeekGE([a])` lands on the FIRST entry; a bounded walk skips leading `b`-NULLs (stopping if
///   `a` changes) to the first non-NULL `b` — the minimum (all-NULL/empty block → MIN = NULL).
///
/// After the seek a verify (`Ne a, target` with JUMPIFNULL) drops to finalize when the block is empty
/// (`SeekLE`/`SeekGE` landed outside it), leaving the accumulator NULL. The single extremum `b` feeds
/// the same `AggStep`/`AggFinal`/wrapper sequence the scan uses, so the result is bit-identical. Only
/// the index cursor is opened (`b` is covered). bd-minmax-prefix-seek.
#[allow(clippy::too_many_arguments, clippy::unnecessary_wraps)]
fn codegen_select_minmax_prefix_seek(
    b: &mut ProgramBuilder,
    idx_cursor: i32,
    agg_columns: &[AggColumn],
    seek: &MinMaxPrefixSeek,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    const JUMPIFNULL: u16 = 0x10; // Ne also jumps when either operand is NULL.

    let agg = &agg_columns[0];
    let accum_reg = b.alloc_reg();
    b.emit_op(Opcode::Null, 0, accum_reg, 0, P4::None, 0);

    b.emit_op(
        Opcode::OpenRead,
        idx_cursor,
        seek.index_root,
        0,
        P4::Index(seek.index_name.clone()),
        0,
    );

    let finalize_label = b.emit_label();

    // Emit the `a=` target, coerce to `a`'s affinity, and treat `a = NULL` as an empty match.
    let a_reg = b.alloc_reg();
    emit_expr(b, seek.a_target, a_reg, None);
    if let Some(aff) = seek.a_affinity
        && !bound_matches_affinity(aff, seek.a_target)
    {
        b.emit_op(
            Opcode::Affinity,
            a_reg,
            1,
            0,
            P4::Affinity(aff.to_string()),
            0,
        );
    }
    b.emit_jump_to_label(Opcode::IsNull, a_reg, 0, finalize_label, P4::None, 0);

    // Partial 1-field probe key [a] for the prefix seek.
    let probe_rec = b.alloc_reg();
    b.emit_op(Opcode::MakeRecord, a_reg, 1, probe_rec, P4::None, 0);

    let a_coll = || {
        seek.a_collation
            .as_deref()
            .map_or(P4::None, |c| P4::Collation(c.to_owned()))
    };
    let cur_a_reg = b.alloc_reg();
    let b_reg = b.alloc_reg();
    let agg_p4 = agg_func_p4(&agg.name, agg.collation.as_ref());

    if seek.is_max {
        // MAX is at the block's extremum-`b` end: ASC `b` → last entry (`SeekLE`); DESC `b` → first
        // entry (`SeekGE`, O(log n) with no O(block) forward walk). `b` there is the max (NULLs sit at
        // the opposite `b` end, so a NULL means the whole block's `b` is NULL → MAX = NULL).
        let max_seek = if seek.b_descending {
            Opcode::SeekGE
        } else {
            Opcode::SeekLE
        };
        b.emit_jump_to_label(max_seek, idx_cursor, probe_rec, finalize_label, P4::None, 0);
        b.emit_op(Opcode::Column, idx_cursor, 0, cur_a_reg, P4::None, 0);
        b.emit_jump_to_label(
            Opcode::Ne,
            cur_a_reg,
            a_reg,
            finalize_label,
            a_coll(),
            JUMPIFNULL,
        );
        b.emit_op(Opcode::Column, idx_cursor, 1, b_reg, P4::None, 0);
        // fall through to the shared AggStep with `b_reg` = the max `b`.
    } else {
        // MIN: first entry of the block, then skip leading `b`-NULLs within it.
        b.emit_jump_to_label(
            Opcode::SeekGE,
            idx_cursor,
            probe_rec,
            finalize_label,
            P4::None,
            0,
        );
        b.emit_op(Opcode::Column, idx_cursor, 0, cur_a_reg, P4::None, 0);
        b.emit_jump_to_label(
            Opcode::Ne,
            cur_a_reg,
            a_reg,
            finalize_label,
            a_coll(),
            JUMPIFNULL,
        );

        let min_loop = b.current_addr();
        b.emit_op(Opcode::Column, idx_cursor, 1, b_reg, P4::None, 0);
        let min_found = b.emit_label();
        b.emit_jump_to_label(Opcode::NotNull, b_reg, 0, min_found, P4::None, 0);
        // `b` is NULL: advance; on EOF fall through to finalize.
        let min_advance = b.emit_label();
        b.emit_jump_to_label(Opcode::Next, idx_cursor, 0, min_advance, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, finalize_label, P4::None, 0);
        b.resolve_label(min_advance);
        // Left the `a=?` block? then every `b` in it was NULL -> MIN = NULL.
        b.emit_op(Opcode::Column, idx_cursor, 0, cur_a_reg, P4::None, 0);
        b.emit_jump_to_label(
            Opcode::Ne,
            cur_a_reg,
            a_reg,
            finalize_label,
            a_coll(),
            JUMPIFNULL,
        );
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        b.emit_op(Opcode::Goto, 0, min_loop as i32, 0, P4::None, 0);
        b.resolve_label(min_found);
        // fall through to the shared AggStep with `b_reg` = the min `b`.
    }

    // Feed the single extremum `b` (the finalize jumps above skip this, leaving the accumulator NULL).
    b.emit_op(Opcode::AggStep, 0, b_reg, accum_reg, agg_p4, 1);

    b.resolve_label(finalize_label);
    b.emit_op(
        Opcode::AggFinal,
        accum_reg,
        agg.num_args,
        0,
        P4::FuncName(agg.name.clone()),
        0,
    );
    if accum_reg != out_regs {
        b.emit_op(Opcode::Copy, accum_reg, out_regs, 0, P4::None, 0);
    }
    if let Some(wrapper) = &agg.wrapper_expr {
        emit_agg_wrapper(b, wrapper, out_regs);
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Generate VDBE bytecode for an aggregate SELECT (no GROUP BY yet).
///
/// Pattern:
/// ```text
/// Init → Transaction → OpenRead → Rewind →
///   [AggStep per aggregate per row] → Next →
/// [AggFinal per aggregate] → ResultRow → Close → Halt
/// ```
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
/// Emit the per-row accumulate body shared by every aggregate row source.
///
/// The caller positions `cursor` on a candidate row and supplies `skip_label`
/// for rows rejected by `WHERE`. This body is row-source agnostic: it reads
/// exclusively through `cursor`, so a full-table scan and an index-driven seek
/// produce byte-identical accumulator state for the same set of rows.
///
/// Can every aggregate be fed from the index entry alone, with no table lookup?
///
/// The position (within the index's key columns) of the table column ordinal `table_col`, if that
/// column is one of the index's key columns. Reading `Column idx_cursor, <this>` yields the value
/// without a table lookup. Only plain (non-expression) key columns match, which is exactly what the
/// direct-lookup indexes these seeks use carry.
fn index_key_position_of(
    index: &IndexSchema,
    table: &TableSchema,
    table_col: usize,
) -> Option<i32> {
    index
        .columns
        .iter()
        .position(|name| table.column_index(name) == Some(table_col))
        .and_then(|p| i32::try_from(p).ok())
}

/// bd-2dgf5. True when each aggregate is `COUNT(*)` (no argument), takes the rowid (available via
/// `IdxRowid`), or takes ANY of the index's key columns (available directly from the index entry —
/// not just the leading column). Anything that needs a general expression, a `FILTER`, extra
/// arguments, a bare output column, or a non-key table column forces the table lookup.
fn aggregate_seek_is_covering(
    agg_columns: &[AggColumn],
    index: &IndexSchema,
    table: &TableSchema,
) -> bool {
    agg_columns.iter().all(|agg| {
        // Sentinel entries for multi-aggregate wrappers emit nothing.
        if agg.name.is_empty() && !agg.multi_agg_indices.is_empty() {
            return true;
        }
        agg.bare_expr.is_none()
            && agg.filter.is_none()
            && agg.arg_expr.is_none()
            && agg.extra_args.is_empty()
            && (agg.num_args == 0
                || agg.arg_is_rowid
                || agg
                    .arg_col_index
                    .is_some_and(|c| index_key_position_of(index, table, c).is_some()))
    })
}

/// Covering-index accumulate body: feeds `AggStep` straight from the index
/// entry, so no table cursor is opened and no `SeekRowid` is emitted.
///
/// Only ever reached when [`aggregate_seek_is_covering`] holds, which is why
/// this deliberately handles no expressions, no `FILTER`, and no extra
/// arguments: those shapes take the table-lookup body instead. The `AggStep`
/// opcode, its `distinct` flag, and its P4 are emitted identically to the
/// table-lookup body, so accumulator state is byte-identical for the same rows.
fn emit_aggregate_accumulate_body_covering(
    b: &mut ProgramBuilder,
    idx_cursor: i32,
    index: &IndexSchema,
    table: &TableSchema,
    agg_columns: &[AggColumn],
    accum_base: i32,
) {
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for (i, agg) in agg_columns.iter().enumerate() {
        if agg.name.is_empty() && !agg.multi_agg_indices.is_empty() {
            continue;
        }
        let accum_reg = accum_base + i as i32;
        let distinct_flag = i32::from(agg.distinct);
        let agg_p4 = agg_func_p4(&agg.name, agg.collation.as_ref());

        if agg.num_args == 0 {
            b.emit_op(Opcode::AggStep, distinct_flag, 0, accum_reg, agg_p4, 0);
            continue;
        }

        let arg_base = b.alloc_regs(agg.num_args.max(1));
        if agg.arg_is_rowid {
            // The index entry carries the rowid; read it without touching the table.
            b.emit_op(Opcode::IdxRowid, idx_cursor, arg_base, 0, P4::None, 0);
        } else {
            let key_pos = agg
                .arg_col_index
                .and_then(|c| index_key_position_of(index, table, c))
                .expect("covering aggregate seek must read one of the index's key columns");
            b.emit_op(Opcode::Column, idx_cursor, key_pos, arg_base, P4::None, 0);
        }
        let num_args = u16::try_from(agg.num_args).unwrap_or_default();
        b.emit_op(
            Opcode::AggStep,
            distinct_flag,
            arg_base,
            accum_reg,
            agg_p4,
            num_args,
        );
    }
}

#[allow(clippy::too_many_arguments)]
fn emit_aggregate_accumulate_body(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    agg_columns: &[AggColumn],
    accum_base: i32,
    // GH #226: register holding 0 until the first scanned row's bare columns
    // have been captured, then 1. Gates row-dependent bare-column stores so an
    // aggregate query's bare column keeps the FIRST scanned row (matching stock
    // sqlite3) instead of the last. Allocated + zeroed once in the caller's
    // shared preamble (before any scan strategy), so a single init serves every
    // scan path.
    first_row_flag: i32,
) {
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for (i, agg) in agg_columns.iter().enumerate() {
        // Skip sentinel entries used for multi-aggregate wrappers.
        if agg.name.is_empty() && !agg.multi_agg_indices.is_empty() {
            continue;
        }
        let accum_reg = accum_base + i as i32;

        // Bare (non-aggregate) column: evaluate expression on the FIRST row only
        // and store in the accumulator register.  No AggStep needed.
        if let Some(ref bare) = agg.bare_expr {
            // Row-independent scalars belong to the aggregate output row, not
            // an input row. Defer them until finalization so they are evaluated
            // exactly once and still have a value for an empty input group.
            if !expr_references_scan(bare, table, table_alias) {
                continue;
            }
            let scan_ctx = ScanCtx {
                cursor,
                table,
                table_alias,
                schema: Some(schema),
                register_base: None,
                secondaries: &[],
            };
            // GH #226: capture the first scanned row's value; skip on later rows.
            let skip_bare = b.emit_label();
            b.emit_jump_to_label(Opcode::If, first_row_flag, 0, skip_bare, P4::None, 0);
            emit_expr(b, bare, accum_reg, Some(&scan_ctx));
            b.resolve_label(skip_bare);
            continue;
        }

        // FILTER clause: evaluate and skip AggStep if false/NULL.
        let filter_skip_label = if let Some(ref filter_expr) = agg.filter {
            let skip_lbl = b.emit_label();
            let filter_reg = b.alloc_temp();
            let scan_ctx = ScanCtx {
                cursor,
                table,
                table_alias,
                schema: Some(schema),
                register_base: None,
                secondaries: &[],
            };
            emit_expr(b, filter_expr, filter_reg, Some(&scan_ctx));
            // p3=1: treat NULL as false (skip AggStep).
            b.emit_jump_to_label(Opcode::IfNot, filter_reg, 1, skip_lbl, P4::None, 0);
            b.free_temp(filter_reg);
            Some(skip_lbl)
        } else {
            None
        };

        let distinct_flag = i32::from(agg.distinct);
        let agg_p4 = agg_func_p4(&agg.name, agg.collation.as_ref());
        if agg.num_args == 0 {
            // count(*): no arguments, p2 is unused (0), p5=0.
            b.emit_op(
                Opcode::AggStep,
                distinct_flag,
                0,
                accum_reg,
                agg_p4.clone(),
                0,
            );
        } else {
            // Aggregate with arguments: allocate consecutive registers
            // for all args so the engine can read them as a contiguous block.
            let total_args = agg.num_args.max(1);
            // alloc_regs guarantees contiguous register block.
            let arg_base = b.alloc_regs(total_args);

            // First argument.
            if agg.arg_is_rowid {
                b.emit_op(Opcode::Rowid, cursor, arg_base, 0, P4::None, 0);
            } else if let Some(ref expr) = agg.arg_expr {
                let scan_ctx = ScanCtx {
                    cursor,
                    table,
                    table_alias,
                    schema: Some(schema),
                    register_base: None,
                    secondaries: &[],
                };
                emit_expr(b, expr, arg_base, Some(&scan_ctx));
            } else {
                let col_idx = agg.arg_col_index.unwrap_or(0);
                // bd-hx3zu (GH#227 sibling): a VIRTUAL generated column passed as
                // an aggregate argument on a table scan (no GROUP BY) read its
                // NULL placeholder, so sum/avg/min/max/count saw NULLs. Compute
                // the generating expression via the canonical reader instead.
                if virtual_generated_column_expr(&table.columns[col_idx]).is_some() {
                    emit_table_column_read(
                        b,
                        cursor,
                        table,
                        table_alias,
                        Some(schema),
                        col_idx,
                        arg_base,
                    );
                } else {
                    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                    b.emit_op(
                        Opcode::Column,
                        cursor,
                        col_idx as i32,
                        arg_base,
                        P4::None,
                        0,
                    );
                }
            }

            // Extra arguments (e.g. separator for group_concat).
            if !agg.extra_args.is_empty() {
                let scan_ctx = ScanCtx {
                    cursor,
                    table,
                    table_alias,
                    schema: Some(schema),
                    register_base: None,
                    secondaries: &[],
                };
                for (j, extra_expr) in agg.extra_args.iter().enumerate() {
                    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                    let extra_reg = arg_base + 1 + j as i32;
                    emit_expr(b, extra_expr, extra_reg, Some(&scan_ctx));
                }
            }

            let num_args = u16::try_from(agg.num_args).unwrap_or_default();
            b.emit_op(
                Opcode::AggStep,
                distinct_flag,
                arg_base,
                accum_reg,
                agg_p4,
                num_args,
            );
        }

        // Resolve FILTER skip label after AggStep.
        if let Some(skip_lbl) = filter_skip_label {
            b.resolve_label(skip_lbl);
        }
    }
    // GH #226: after the first scanned row's bare columns are captured, mark the
    // flag so subsequent rows skip the bare-column store (idempotent each row).
    b.emit_op(Opcode::Integer, 1, first_row_flag, 0, P4::None, 0);
}

/// The index a `WHERE <equality-prefix>` aggregate can seek instead of scanning.
///
/// bd-2dgf5. The probe record contains only the constrained key prefix. A true
/// partial key is the block floor regardless of the next key term's ASC/DESC
/// direction or whether that term is NULL; appending a synthetic integer floor
/// is not equivalent for either a DESC term or an ASC NULL region.
///
/// Do NOT gate this on an affinity/collation pre-check by analogy with
/// [`index_range_fast_path_is_safe`]. `cmp_p5` is `0x80 | comparison_affinity(..)`,
/// and an `INTEGER` column compared against an integer literal carries a
/// non-zero affinity, so such a gate rejects precisely the queries this seek
/// exists to accelerate and degrades silently to a full scan with no test
/// failure. See `resolved_index_range_comparison_carries_affinity_for_integer_column`.
///
/// Affinity skew is instead handled exactly as the non-aggregate path handles
/// it: the `Ne` compare uses the index's own collation via
/// [`direct_lookup_index_comparison_p4`], and a probe that matches nothing falls
/// back to the full scan through `saw_index_match_reg` rather than trusting an
/// empty result.
///
/// Shared by [`codegen_select_aggregate`] and by the `simple_count_star`
/// suppression in [`codegen_select`], so the two cannot drift apart.
/// Whether an explicit `INDEXED BY` / `NOT INDEXED` hint permits the aggregate
/// index seek.
///
/// `NOT INDEXED` must force the scan, and `INDEXED BY <name>` names an index the
/// seek does not consult, so both decline. Only an unhinted FROM source may seek.
fn aggregate_index_eq_seek_allowed(index_hint: Option<&fsqlite_ast::IndexHint>) -> bool {
    index_hint.is_none()
}

fn aggregate_index_eq_seek_target<'t, 'e>(
    where_clause: Option<&'e Expr>,
    table: &'t TableSchema,
    table_alias: Option<&str>,
) -> Option<(&'t IndexSchema, Vec<&'e Expr>)> {
    // The seek walks the block pinned by an equality PREFIX of an ASC-leading index (`WHERE a=?` on
    // `(a,b)`, or `WHERE a=? AND b=?` on `(a,b)`). A partial `[prefix..]` probe anchors at the first
    // matching entry even when the next key term is DESC or NULL; a per-term `Ne` stops at the end of
    // the run. It applies no residual filter, so it is only correct when the WHERE is EXACTLY the
    // pinned equalities: `conjunct_count == prefix_len` declines a query with a leftover predicate the
    // seek can't enforce (e.g. `a=? AND b=?` against a shorter `(a)` index would drop `b=?`), letting a
    // fuller index win.
    let where_expr = where_clause?;
    if table.without_rowid {
        return None;
    }
    let mut conjuncts = Vec::new();
    collect_conjunctive_terms(where_expr, &mut conjuncts);
    for index in &table.indexes {
        if index.key_term_descending(0) || !index.supports_direct_column_lookup() {
            continue;
        }
        let prefix = extract_index_equality_prefix_exprs(index, table, table_alias, where_clause);
        if prefix.is_empty() || prefix.len() != conjuncts.len() {
            continue;
        }
        return Some((index, prefix));
    }
    None
}

/// The index and distinct integer values a `WHERE <col> IN (<int list>)` aggregate can
/// seek per value instead of full-scanning.
///
/// bd-2dgf5. Deliberately narrow so the per-value seek needs no scan fallback:
///   * `col` has INTEGER affinity, so an integer-literal probe is exact — no false-empty
///     that an affinity-coercing scan would otherwise catch.
///   * every list value is an integer literal, and they are de-duplicated, so no two seeks
///     can visit the same duplicate run (double count). Distinct integers are disjoint runs.
///   * single ascending key term (the probe record is one key term + rowid), `IN` not
///     `NOT IN`, non-empty list.
///
/// Anything outside this (text/real/numeric column, a non-integer or non-literal element,
/// `NOT IN`) declines and the aggregate keeps its full scan.
fn index_integer_in_list_target<'t>(
    where_clause: Option<&Expr>,
    table: &'t TableSchema,
    table_alias: Option<&str>,
) -> Option<(&'t IndexSchema, Vec<i64>)> {
    let (column, ints) = column_int_list_from_predicate(where_clause, table, table_alias)?;
    let col_name = column_name(column, table, table_alias)?;
    // INTEGER-affinity column only (see the no-fallback argument above).
    if table
        .column_index(&col_name)
        .and_then(|i| table.columns.get(i))?
        .affinity
        != 'D'
    {
        return None;
    }
    // Prefer a single-column ascending index on the column (its `[value, i64::MIN]` probe is exact).
    // `index_for_column` returns the FIRST index whose LEADING column matches, which may be a
    // *composite* `(col, …)` index that shadows a usable single-column one listed after it — filtering
    // that result would then decline even though a single-column index exists. Search all indexes.
    if let Some(idx) = table.indexes.iter().find(|idx| {
        idx.supports_direct_column_lookup()
            && idx.key_term_count() == 1
            && !idx.key_term_descending(0)
            && idx
                .columns
                .first()
                .is_some_and(|c| c.eq_ignore_ascii_case(&col_name))
    }) {
        return Some((idx, ints));
    }
    // bd-in-list-composite-prefix-probe: fall back to a composite index whose ASCENDING leading column
    // is the target. The `[value, i64::MIN]` probe is WRONG here — its second field aligns with the
    // trailing key column, and a NULL trailing column (sorts before `i64::MIN`) would be skipped by
    // SeekGE. `emit_aggregate_index_value_seek` detects the composite case (`key_term_count() > 1`) and
    // probes with a 1-field PREFIX `[value]`: SeekGE anchors at the first `a=value` entry regardless of
    // the trailing column (including NULL), and the Column-0 run stop is unchanged.
    let idx = table.indexes.iter().find(|idx| {
        idx.supports_direct_column_lookup()
            && idx.key_term_count() > 1
            && !idx.key_term_descending(0)
            && idx
                .columns
                .first()
                .is_some_and(|c| c.eq_ignore_ascii_case(&col_name))
    })?;
    Some((idx, ints))
}

/// Returns `(index, ints, has_residual)`. `has_residual == false` is the residual-free case above (the
/// WHOLE WHERE is the IN-list). `has_residual == true` additionally matches an `a IN (<int list>)`
/// CONJUNCT alongside other predicates the caller re-applies as a residual filter. bd-agg-in-list-residual.
fn index_integer_in_list_residual_target<'t>(
    where_clause: Option<&Expr>,
    table: &'t TableSchema,
    table_alias: Option<&str>,
) -> Option<(&'t IndexSchema, Vec<i64>, bool)> {
    if let Some((idx, ints)) = index_integer_in_list_target(where_clause, table, table_alias) {
        return Some((idx, ints, false));
    }
    let where_expr = where_clause?;
    let mut conjuncts = Vec::new();
    collect_conjunctive_terms(where_expr, &mut conjuncts);
    if conjuncts.len() < 2 {
        return None;
    }
    for term in &conjuncts {
        if let Some((idx, ints)) = index_integer_in_list_target(Some(term), table, table_alias) {
            return Some((idx, ints, true));
        }
    }
    None
}

/// The single-column ascending index and range a `SELECT COUNT(*)/SUM(...) FROM t WHERE col <range>`
/// aggregate can seek instead of full-scanning. Reuses the SAME residual-safe extraction and safety
/// gate as the non-aggregate single-column range scan (`extract_column_range_target` +
/// `index_range_fast_path_is_safe`): `extract_column_range_target` matches only when EVERY WHERE
/// conjunct is a range bound on ONE column (an `And` requires both sides to be bounds on the same
/// column, so a residual `c = 5` or a second column declines), so the seek — which applies no
/// residual filter — is byte-exact. Rowid tables only; the trailing sentinel in the probe is the
/// rowid.
/// Returns `(index, range, has_residual)`. `has_residual == false` is the residual-free case above.
/// `has_residual == true` additionally allows a range on an INTEGER-affinity single-column index that
/// coexists with OTHER (placeholder-free) predicates the seek cannot enforce: the integer-literal
/// bounds make the seek a SUPERSET of the matching rows, and the caller re-applies the whole WHERE as a
/// residual filter per row, so it stays byte-exact. Aggregates are order-independent, so visiting a
/// superset and filtering is safe.
fn aggregate_index_range_seek_target<'t, 'e>(
    where_clause: Option<&'e Expr>,
    table: &'t TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
) -> Option<(&'t IndexSchema, ColumnRangeTarget<'e>, bool)> {
    if table.without_rowid {
        return None;
    }
    let where_expr = where_clause?;
    // Residual-free: the WHOLE WHERE is a range on one column.
    if let Some((col_name, range)) = extract_column_range_target(where_clause, table, table_alias) {
        // Search ALL indexes for a single-column ascending index on `col_name`. `index_for_column`
        // returns the FIRST leading-column match, which may be a COMPOSITE `(col, …)` index that
        // shadows a usable single-column one declared after it; filtering that result with `?` would
        // early-return None and a `COUNT(*) WHERE a <range>` (no residual) would full-scan whenever a
        // composite `(a, …)` index is declared before `idx_a` (bd-agg-range-shadowed-index — the same
        // shadowing fixed for the IN-list seek). Searching all indexes finds the single-column one.
        if let Some(idx) = table.indexes.iter().find(|idx| {
            idx.supports_direct_column_lookup()
                && idx.key_term_count() == 1
                && !idx.key_term_descending(0)
                && idx
                    .columns
                    .first()
                    .is_some_and(|c| c.eq_ignore_ascii_case(&col_name))
        }) {
            return index_range_fast_path_is_safe(table, table_alias, schema, &col_name, &range)
                .then_some((idx, range, false));
        }
    }
    // Residual: a range on a single-column index plus other predicates. The `bounds_ok` check below
    // requires LITERAL bounds, so the probe emits no placeholders and a `?` can appear only in the
    // residual, where the filter numbers it identically to the scan path (bd-agg-param-residual).
    for index in &table.indexes {
        if index.key_term_count() != 1
            || index.key_term_descending(0)
            || !index.supports_direct_column_lookup()
        {
            continue;
        }
        let col_name = &index.columns[0];
        let affinity = table
            .column_index(col_name)
            .and_then(|ci| table.columns.get(ci))
            .map(|c| c.affinity);
        let column_uses_binary_collation = table
            .column_index(col_name)
            .and_then(|ci| table.columns.get(ci))
            .and_then(|column| column.collation.as_deref())
            .is_none_or(|collation| collation.eq_ignore_ascii_case("BINARY"));
        let Some(range) = extract_named_column_range(where_expr, table, table_alias, col_name)
        else {
            continue;
        };
        // The seek is a SUPERSET (no affinity/collation miss) when the bound literals match the
        // column's storage class: an INTEGER column + integer literals, or a BINARY-collation TEXT
        // column + text literals (a bare `s <op> 'lit'` compares under the column collation, which
        // equals the BINARY index collation, so the seek range matches the WHERE range). The residual
        // filter narrows to exact.
        let bound_is = |b: &ColumnRangeBound<'_>, want_text: bool| {
            if want_text {
                matches!(b.expr(), Expr::Literal(Literal::String(_), _))
            } else {
                matches!(b.expr(), Expr::Literal(Literal::Integer(_), _))
            }
        };
        let bounds_ok = match affinity {
            Some('D') => {
                range.lower.as_ref().is_none_or(|b| bound_is(b, false))
                    && range.upper.as_ref().is_none_or(|b| bound_is(b, false))
            }
            Some('B')
                if column_uses_binary_collation
                    && index
                        .key_term_collation(0)
                        .is_none_or(|c| c.eq_ignore_ascii_case("BINARY")) =>
            {
                range.lower.as_ref().is_none_or(|b| bound_is(b, true))
                    && range.upper.as_ref().is_none_or(|b| bound_is(b, true))
            }
            _ => false,
        };
        if bounds_ok {
            return Some((index, range, true));
        }
    }
    None
}

/// The index and equality prefix a
/// `COUNT(*)/SUM(...) WHERE a = <literal> AND <residual>` aggregate can seek:
/// pin the leading key column(s) with an integer- or text-literal equality,
/// walk that block, and apply the FULL WHERE as a residual filter per row.
/// Gated tight so it is byte-exact and safe: (1) each literal's storage class
/// exactly matches its indexed column's affinity and text probes use BINARY
/// collation, so the seek cannot miss a scan match; (2) the literal probe
/// consumes no placeholders, so bound parameters in the residual keep the
/// same numbering as the scan path; (3) there is at least one residual
/// conjunct beyond the prefix (otherwise the exact eq-seek already handles
/// it). `required_key_term_count` lets callers that depend on rowid ordering
/// reject composite indexes while aggregate callers retain prefix support.
/// The residual filter enforces the whole predicate, so a dropped-predicate
/// class of bug cannot occur.
fn aggregate_index_prefix_literal_residual_target<'t, 'e>(
    where_clause: Option<&'e Expr>,
    table: &'t TableSchema,
    table_alias: Option<&str>,
    required_key_term_count: Option<usize>,
) -> Option<(&'t IndexSchema, Vec<&'e Expr>)> {
    let where_expr = where_clause?;
    // A bound parameter is allowed only in the RESIDUAL: the prefix is required to be an integer/text
    // LITERAL below, so the probe emits no placeholders and the residual filter numbers `?` exactly as
    // the scan path does (bd-agg-param-residual).
    if table.without_rowid {
        return None;
    }
    let mut conjuncts = Vec::new();
    collect_conjunctive_terms(where_expr, &mut conjuncts);
    for index in &table.indexes {
        if index.key_term_descending(0)
            || index.columns.is_empty()
            || index.columns.len() != index.key_term_count()
            || required_key_term_count.is_some_and(|required| index.key_term_count() != required)
            || !index_partial_predicate_is_covered_by_query_conjuncts(
                index,
                &conjuncts,
                table,
                table_alias,
            )
        {
            continue;
        }
        let prefix = extract_index_equality_prefix_exprs(index, table, table_alias, where_clause);
        // Need a non-empty prefix AND at least one residual conjunct (else the exact eq-seek owns it).
        if prefix.is_empty() || prefix.len() >= conjuncts.len() {
            continue;
        }
        // The seek probe must land on a SUPERSET of the matching rows (the residual filter re-applies
        // the whole WHERE and narrows to exact). An integer literal vs an INTEGER column, or a text
        // literal vs a TEXT column indexed BINARY, both seek without an affinity/collation miss.
        let exact = prefix.iter().enumerate().all(|(i, e)| {
            let column = index
                .columns
                .get(i)
                .and_then(|name| table.column_index(name))
                .and_then(|ci| table.columns.get(ci));
            match e {
                Expr::Literal(Literal::Integer(_), _) => {
                    column.is_some_and(|column| column.affinity == 'D')
                }
                Expr::Literal(Literal::String(_), _) => {
                    column.is_some_and(|column| {
                        column.affinity == 'B'
                            && column
                                .collation
                                .as_deref()
                                .is_none_or(|c| c.eq_ignore_ascii_case("BINARY"))
                    }) && index
                        .key_term_collation(i)
                        .is_none_or(|c| c.eq_ignore_ascii_case("BINARY"))
                }
                _ => false,
            }
        });
        if !exact {
            continue;
        }
        return Some((index, prefix));
    }
    None
}

fn expr_contains_function_call(expr: &Expr) -> bool {
    match expr {
        // JSON operators are SQL-visible scalar function calls (`->`/`->>`)
        // and can be replaced by an application registration. Their child
        // expressions are irrelevant once the operator itself is recognized.
        Expr::FunctionCall { .. } | Expr::JsonAccess { .. } => true,
        Expr::Subquery(select, _)
        | Expr::Exists {
            subquery: select, ..
        } => select_contains_function_call(select),
        Expr::BinaryOp { left, right, .. } => {
            expr_contains_function_call(left) || expr_contains_function_call(right)
        }
        Expr::UnaryOp { expr, .. }
        | Expr::IsNull { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. } => expr_contains_function_call(expr),
        Expr::Between {
            expr, low, high, ..
        } => {
            expr_contains_function_call(expr)
                || expr_contains_function_call(low)
                || expr_contains_function_call(high)
        }
        Expr::In { expr, set, .. } => {
            expr_contains_function_call(expr)
                || match set {
                    InSet::List(items) => items.iter().any(expr_contains_function_call),
                    InSet::Subquery(select) => select_contains_function_call(select),
                    InSet::Table(_) => false,
                }
        }
        Expr::Like {
            expr,
            pattern,
            escape,
            ..
        } => {
            expr_contains_function_call(expr)
                || expr_contains_function_call(pattern)
                || escape.as_deref().is_some_and(expr_contains_function_call)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand.as_deref().is_some_and(expr_contains_function_call)
                || whens.iter().any(|(when_expr, then_expr)| {
                    expr_contains_function_call(when_expr) || expr_contains_function_call(then_expr)
                })
                || else_expr
                    .as_deref()
                    .is_some_and(expr_contains_function_call)
        }
        Expr::RowValue(items, _) => items.iter().any(expr_contains_function_call),
        Expr::Literal(_, _)
        | Expr::BoundOuterValue { .. }
        | Expr::Column(_, _)
        | Expr::Raise { .. }
        | Expr::Placeholder(_, _) => false,
    }
}

fn select_contains_function_call(select: &SelectStatement) -> bool {
    select.with.as_ref().is_some_and(|with_clause| {
        with_clause
            .ctes
            .iter()
            .any(|cte| select_contains_function_call(&cte.query))
    }) || select_core_contains_function_call(&select.body.select)
        || select
            .body
            .compounds
            .iter()
            .any(|(_, core)| select_core_contains_function_call(core))
        || select
            .order_by
            .iter()
            .any(|term| expr_contains_function_call(&term.expr))
        || select.limit.as_ref().is_some_and(|clause| {
            expr_contains_function_call(&clause.limit)
                || clause
                    .offset
                    .as_ref()
                    .is_some_and(expr_contains_function_call)
        })
}

fn select_core_contains_function_call(core: &SelectCore) -> bool {
    match core {
        SelectCore::Select {
            columns,
            from,
            where_clause,
            group_by,
            having,
            windows,
            ..
        } => {
            columns.iter().any(|column| {
                matches!(
                    column,
                    ResultColumn::Expr { expr, .. } if expr_contains_function_call(expr)
                )
            }) || from.as_ref().is_some_and(from_contains_function_call)
                || where_clause
                    .as_deref()
                    .is_some_and(expr_contains_function_call)
                || group_by.iter().any(expr_contains_function_call)
                || having.as_deref().is_some_and(expr_contains_function_call)
                || windows
                    .iter()
                    .any(|window| window_spec_contains_function_call(&window.spec))
        }
        SelectCore::Values(rows) => rows.iter().flatten().any(expr_contains_function_call),
    }
}

fn from_contains_function_call(from: &FromClause) -> bool {
    table_or_subquery_contains_function_call(&from.source)
        || from.joins.iter().any(|join| {
            table_or_subquery_contains_function_call(&join.table)
                || matches!(
                    &join.constraint,
                    Some(fsqlite_ast::JoinConstraint::On(expr))
                        if expr_contains_function_call(expr)
                )
        })
}

fn table_or_subquery_contains_function_call(source: &TableOrSubquery) -> bool {
    match source {
        TableOrSubquery::Table { .. } => false,
        TableOrSubquery::Subquery { query, .. } => select_contains_function_call(query),
        TableOrSubquery::TableFunction { .. } => true,
        TableOrSubquery::ParenJoin(from) => from_contains_function_call(from),
    }
}

fn window_spec_contains_function_call(spec: &fsqlite_ast::WindowSpec) -> bool {
    spec.partition_by.iter().any(expr_contains_function_call)
        || spec
            .order_by
            .iter()
            .any(|term| expr_contains_function_call(&term.expr))
        || spec.frame.as_ref().is_some_and(|frame| {
            frame_bound_contains_function_call(&frame.start)
                || frame
                    .end
                    .as_ref()
                    .is_some_and(frame_bound_contains_function_call)
        })
}

fn frame_bound_contains_function_call(bound: &fsqlite_ast::FrameBound) -> bool {
    match bound {
        fsqlite_ast::FrameBound::Preceding(expr) | fsqlite_ast::FrameBound::Following(expr) => {
            expr_contains_function_call(expr)
        }
        fsqlite_ast::FrameBound::UnboundedPreceding
        | fsqlite_ast::FrameBound::CurrentRow
        | fsqlite_ast::FrameBound::UnboundedFollowing => false,
    }
}

/// A partial index is a safe source only when every row that can satisfy the
/// query is present in it. This low-level helper has no affinity proof lattice,
/// so require each partial-predicate conjunct to appear structurally in the
/// query after normalizing only the current table name or alias. An unparseable
/// predicate or foreign qualifier fails closed. A connection with any scalar
/// replacement also declines a function-bearing predicate: structural equality
/// cannot prove that the index's population-time function semantics still match
/// the current registry.
fn index_partial_predicate_is_covered_by_query_conjuncts(
    index: &IndexSchema,
    query_conjuncts: &[&Expr],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    let Some(predicate_sql) = index.where_clause.as_deref() else {
        return true;
    };
    let Ok(predicate) = parse_sql_expr(predicate_sql) else {
        return false;
    };
    if !use_builtin_scalar_function_semantics() && expr_contains_function_call(&predicate) {
        return false;
    }
    let mut predicate_conjuncts = Vec::new();
    collect_conjunctive_terms(&predicate, &mut predicate_conjuncts);
    predicate_conjuncts.iter().all(|predicate_conjunct| {
        query_conjuncts.iter().any(|query_conjunct| {
            expressions_match_table_locally(query_conjunct, predicate_conjunct, table, table_alias)
        })
    })
}

/// Emit one value's index seek + duplicate-run accumulate for the aggregate IN-list path.
///
/// bd-2dgf5. Opens no cursor itself (the caller opens `idx_cursor`, and `table_cursor` when not
/// covering). A `SeekGE` miss or a first key that is not `value` skips straight to `next_value` (this
/// value contributes nothing). No scan fallback: the INTEGER-affinity + integer-literal gate in
/// [`index_integer_in_list_target`] makes the probe exact, and de-duplicated values keep the runs
/// disjoint. When `covering`, the aggregates read only the indexed column (or are COUNT(*)/SUM(rowid))
/// so each entry accumulates straight from the index — no `IdxRowid`/`SeekRowid` and no table cursor.
#[allow(clippy::too_many_arguments)]
fn emit_aggregate_index_value_seek(
    b: &mut ProgramBuilder,
    table_cursor: i32,
    idx_cursor: i32,
    idx_schema: &IndexSchema,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    agg_columns: &[AggColumn],
    accum_base: i32,
    // GH #226: forwarded to emit_aggregate_accumulate_body so a bare column
    // keeps the first scanned row on this index-value-seek scan path too.
    first_row_flag: i32,
    value: i64,
    covering: bool,
    residual_where: Option<&Expr>,
) {
    // bd-in-list-composite-prefix-probe: a composite `(a, …)` index is probed with a 1-field PREFIX
    // `[value]` so SeekGE anchors at the first `a=value` entry regardless of the trailing key column
    // (including a NULL trailing column, which sorts before `i64::MIN`). A single-column index keeps
    // the exact 2-field `[value, i64::MIN]` probe (the second field is the rowid floor) — byte-identical.
    let prefix_probe = idx_schema.key_term_count() > 1;
    let n_probe: i32 = if prefix_probe { 1 } else { 2 };
    let probe_key_regs = b.alloc_regs(n_probe);
    b.emit_op(Opcode::Int64, 0, probe_key_regs, 0, P4::Int64(value), 0);
    if !prefix_probe {
        b.emit_op(
            Opcode::Int64,
            0,
            probe_key_regs + 1,
            0,
            P4::Int64(i64::MIN),
            0,
        );
    }
    let probe_record_reg = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        probe_key_regs,
        n_probe,
        probe_record_reg,
        P4::None,
        0,
    );
    let next_value = b.emit_label();
    b.emit_jump_to_label(
        Opcode::SeekGE,
        idx_cursor,
        probe_record_reg,
        next_value,
        P4::None,
        0,
    );

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let run_top = b.current_addr() as i32;
    let idx_key_reg = b.alloc_reg();
    b.emit_op(Opcode::Column, idx_cursor, 0, idx_key_reg, P4::None, 0);
    b.emit_jump_to_label(
        Opcode::Ne,
        probe_key_regs,
        idx_key_reg,
        next_value,
        direct_lookup_index_comparison_p4(idx_schema),
        0x10,
    );

    if covering {
        emit_aggregate_accumulate_body_covering(
            b,
            idx_cursor,
            idx_schema,
            table,
            agg_columns,
            accum_base,
        );
    } else {
        let skip_row = b.emit_label();
        let rowid_reg = b.alloc_reg();
        b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            table_cursor,
            rowid_reg,
            skip_row,
            P4::None,
            0,
        );
        if let Some(where_expr) = residual_where {
            emit_where_filter(
                b,
                where_expr,
                table_cursor,
                table,
                table_alias,
                schema,
                skip_row,
            );
        }
        emit_aggregate_accumulate_body(
            b,
            table_cursor,
            table,
            table_alias,
            schema,
            agg_columns,
            accum_base,
            first_row_flag,
        );
        b.resolve_label(skip_row);
    }
    b.emit_op(Opcode::Next, idx_cursor, run_top, 0, P4::None, 0);
    b.resolve_label(next_value);
}

// Takes the same cursor / table / schema / label bundle as every other
// `codegen_select_*` row-source emitter. Bundling those into a struct here alone
// would fork the signature shape it shares with the scan emitter it falls back to.
#[allow(clippy::too_many_arguments)]
fn codegen_select_aggregate(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    having: Option<&Expr>,
    limit_clause: Option<&LimitClause>,
    limit_anon_placeholder_base: Option<u32>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
    allow_index_seek: bool,
    // #137 sub-2: the query's FROM index hint. A forced `INDEXED BY <idx>` makes
    // the aggregate scan the index in STORED order (so order-sensitive aggregates
    // like SUM's transient overflow match stock) instead of the rowid-order table
    // scan. `allow_index_seek` is false for a forced hint (it gates the eq-SEEK
    // fast paths), so the forced index-ORDERED full scan is enabled from this hint
    // directly, orthogonally to `allow_index_seek`.
    from_index_hint: Option<&fsqlite_ast::IndexHint>,
) -> Result<(), CodegenError> {
    // Resolve SELECT-list aliases referenced from HAVING (e.g.
    // `SELECT SUM(qty) AS total_qty ... HAVING total_qty > 100`).
    let rewritten_having = having.map(|h| rewrite_having_select_aliases(h, columns, table));
    let having = rewritten_having.as_ref();
    let limit_is_output_neutral = single_group_aggregate_limit_is_output_neutral(limit_clause);

    if where_clause.is_none()
        && having.is_none()
        && limit_is_output_neutral
        && let Some(plan) = simple_count_star_plus_sum_plan(columns, table, table_alias)
    {
        return codegen_select_count_star_plus_sum(
            b, cursor, table, &plan, out_regs, done_label, end_label,
        );
    }

    // Parse aggregate columns: extract function name, arg count, arg column index.
    let mut agg_columns = parse_aggregate_columns(columns, table)?;

    // Leaf-seek fast path for `MAX(rowid)` / `MIN(rowid)` with no WHERE/HAVING
    // (this function is only reached when GROUP BY is empty). Stock SQLite
    // special-cases the extremum of the INTEGER PRIMARY KEY as a single seek to
    // the rightmost/leftmost leaf (O(log n)) instead of a full B-tree walk.
    // The accumulate/finalize/wrapper machinery is reused verbatim so the
    // produced result is bit-identical to the full-scan path; only the row that
    // feeds AggStep changes (the single extremum row instead of every row).
    if where_clause.is_none()
        && having.is_none()
        && limit_is_output_neutral
        && let Some(seek) = minmax_rowid_seek_plan(&agg_columns)
    {
        return codegen_select_minmax_rowid_seek(
            b,
            cursor,
            table,
            &agg_columns,
            seek,
            out_regs,
            out_col_count,
            done_label,
            end_label,
        );
    }

    // Secondary-index analogue of the rowid MIN/MAX seek: `SELECT MIN(col)`/`MAX(col)` where `col`
    // carries a collation-matched ASC index resolves to a single seek to one end of the index
    // instead of an O(n) scan (~800x on a 20k-row table). Gated on `allow_index_seek` because it
    // opens an index cursor; byte-identical (only the fed row changes). bd-minmax-index-seek.
    // MIN/MAX ignore NULLs, so a redundant `WHERE <col> IS NOT NULL` on the aggregate's own column can
    // still take the same no-WHERE index-seek fast paths, byte-identically. bd-minmax-redundant-not-null.
    let minmax_no_effective_where = where_clause.is_none()
        || minmax_where_is_redundant_not_null(where_clause, &agg_columns, table, table_alias);

    if allow_index_seek
        && minmax_no_effective_where
        && having.is_none()
        && limit_is_output_neutral
        && let Some(seek) = minmax_index_seek_plan(&agg_columns, table)
    {
        return codegen_select_minmax_index_seek(
            b,
            cursor,
            &agg_columns,
            &seek,
            out_regs,
            out_col_count,
            done_label,
            end_label,
        );
    }

    // `SELECT COUNT(DISTINCT col) FROM t` over a single-column ASC BINARY index walks the index and
    // counts key-changes — no ephemeral dedup B-tree, no table read — instead of a full scan that
    // deduplicates every row. Byte-identical (BINARY index order == DISTINCT grouping); gated on
    // `allow_index_seek`. bd-count-distinct-index-walk.
    if allow_index_seek
        && where_clause.is_none()
        && having.is_none()
        && limit_is_output_neutral
        && let Some(walk) = count_distinct_index_walk_plan(&agg_columns, columns, table)
    {
        codegen_select_count_distinct_index_walk(
            b,
            cursor,
            &walk,
            out_regs,
            out_col_count,
            done_label,
            end_label,
        );
        return Ok(());
    }

    // `SELECT MIN(col), MAX(col)` over one indexed column: two seeks (one per index end) instead of a
    // scan. Byte-identical; gated on `allow_index_seek`. bd-minmax-pair-seek.
    if allow_index_seek
        && minmax_no_effective_where
        && having.is_none()
        && limit_is_output_neutral
        && let Some(seek) = minmax_pair_seek_plan(&agg_columns, table)
    {
        return codegen_select_minmax_pair_seek(
            b,
            cursor,
            &agg_columns,
            &seek,
            out_regs,
            out_col_count,
            done_label,
            end_label,
        );
    }

    // Composite-prefix analogue: `SELECT MIN(b)/MAX(b) FROM t WHERE a = <const>` on a (a,b,…) index
    // seeks to the extremum of `b` within the `a=?` block (one seek) instead of scanning the whole
    // group (~800x on a large group). Byte-identical; gated on `allow_index_seek`. bd-minmax-prefix-seek.
    if allow_index_seek
        && having.is_none()
        && limit_is_output_neutral
        && let Some(seek) = minmax_prefix_seek_plan(&agg_columns, table, table_alias, where_clause)
    {
        return codegen_select_minmax_prefix_seek(
            b,
            cursor,
            &agg_columns,
            &seek,
            out_regs,
            out_col_count,
            done_label,
            end_label,
        );
    }

    // Range-bounded extremum: `SELECT MIN(col) WHERE col >[=] c` / `MAX(col) WHERE col <[=] c` on an
    // INTEGER-indexed column seeks the bound (one seek) instead of scanning. bd-minmax-range-seek.
    if allow_index_seek
        && having.is_none()
        && limit_is_output_neutral
        && let Some(seek) = minmax_range_seek_plan(&agg_columns, table, table_alias, where_clause)
    {
        return codegen_select_minmax_range_seek(
            b,
            cursor,
            &agg_columns,
            &seek,
            out_regs,
            out_col_count,
            done_label,
            end_label,
        );
    }

    // Rowid analogue: `SELECT MIN(id) WHERE id >[=] c` / `MAX(id) WHERE id <[=] c` seeks the table
    // b-tree (one seek) instead of scanning the range. bd-minmax-rowid-range-seek.
    if allow_index_seek
        && having.is_none()
        && limit_is_output_neutral
        && let Some((seek_op, bound)) =
            minmax_rowid_range_seek_plan(&agg_columns, table, table_alias, where_clause)
    {
        return codegen_select_minmax_rowid_range_seek(
            b,
            cursor,
            table,
            &agg_columns,
            seek_op,
            bound,
            out_regs,
            out_col_count,
            done_label,
            end_label,
        );
    }

    // Collect aggregates from the HAVING clause that are not in the SELECT list.
    // Without this, HAVING-only aggregates (e.g. `HAVING SUM(x) > 10` when SUM(x)
    // is not in SELECT) would never be accumulated and silently evaluate to 0.
    let mut having_output_cols: Vec<GroupByOutputCol> = Vec::new();
    if let Some(having_expr) = having {
        collect_having_aggregates(
            having_expr,
            table,
            &mut agg_columns,
            &mut having_output_cols,
        );
        // GH #225: capture bare columns referenced in HAVING (first scanned row)
        // so a HAVING predicate on an unprojected column resolves to a real
        // value instead of NULL.
        collect_having_bare_columns(having_expr, table, &mut agg_columns);
    }

    // A single-group aggregate produces at most one row, but LIMIT/OFFSET still
    // govern that row. In particular, LIMIT 0 and OFFSET >= 1 must suppress the
    // empty-group result just as they suppress a non-empty aggregate result.
    let aggregate_anon_placeholder_base = b.current_anon_placeholder();
    if let Some(limit_base) = limit_anon_placeholder_base {
        // LIMIT appears after the SELECT core, compounds, and ORDER BY in SQL
        // text even though its guard is emitted before the scan. Give anonymous
        // placeholders their textual indices, then restore the body counter.
        b.set_next_anon_placeholder(limit_base);
    }
    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);
    b.set_next_anon_placeholder(aggregate_anon_placeholder_base);

    // Allocate one accumulator register per aggregate (SELECT + HAVING-only).
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let total_agg_count = agg_columns.len() as i32;
    let accum_base = b.alloc_regs(total_agg_count);

    // Initialize accumulators to Null (required by AggStep protocol).
    for i in 0..total_agg_count {
        b.emit_op(Opcode::Null, 0, accum_base + i, 0, P4::None, 0);
    }

    // GH #226: a shared first-row flag for bare-column capture. Zeroed here in
    // the single preamble that precedes every scan strategy, so all
    // emit_aggregate_accumulate_body call sites gate on the same register and
    // the bare column keeps the FIRST scanned row (stock sqlite3), not the last.
    let first_row_flag = b.alloc_reg();
    b.emit_op(Opcode::Integer, 0, first_row_flag, 0, P4::None, 0);

    // bd-2dgf5: indexed-equality seek instead of a full table scan.
    //
    // `SELECT COUNT(*) FROM t WHERE k = ?` previously walked every row because
    // every index access path was disabled for aggregates. When the WHERE
    // clause exactly pins an equality prefix of a direct-lookup, ASC-leading
    // rowid-table index, drive the accumulate body from an index seek over the
    // matching run instead. Only the row source changes; the accumulate body
    // and finalize sequence are emitted verbatim, so results are identical.
    //
    // `aggregate_index_eq_seek_target` admits the path only when every WHERE
    // conjunct pins one term of the equality prefix, so the seek enforces the
    // whole predicate.
    //
    // The gate is deliberately identical to the non-aggregate index-seek gate in
    // `codegen_select` (`index_eq` + `table.index_for_column`): the seek visits
    // exactly the row set that `SELECT * FROM t WHERE col = <const>` already
    // visits today, and the aggregate merely accumulates over it. That row-set
    // parity, not a separate affinity analysis, is what makes this correct.
    //
    // Affinity skew is handled the way the non-aggregate path handles it: the
    // `Ne` compare below uses the index own collation, and a probe that
    // matches nothing falls back to the full scan via `saw_index_match_reg`
    // rather than trusting an empty result. An affinity pre-check here would
    // silently disable the seek (see `aggregate_index_eq_seek_target`).
    //
    // Additional aggregate-specific guards:
    //   * HAVING is not supported on this path.
    //   * A bare (non-aggregate) output column would expose *which* row the scan
    //     happened to end on, so the row source must not change.
    //   * Direct-lookup, ASC-leading indexes only; the partial probe record and
    //     per-term `Ne` guards handle composite equality prefixes.
    let index_eq_seek = if allow_index_seek
        && having.is_none()
        && agg_columns.iter().all(|agg| agg.bare_expr.is_none())
    {
        aggregate_index_eq_seek_target(where_clause, table, table_alias)
    } else {
        None
    };

    // bd-2dgf5: rowid-equality seek instead of a full table scan.
    //
    // `SELECT COUNT(*)/SUM(v) FROM t WHERE <ipk> = <int literal>` previously walked
    // every row because aggregates were gated out of the rowid access path (a rowid
    // point lookup is O(log n); the scan is O(n)). This is the rowid analogue of the
    // secondary-index seek above and only fires when the seek is provably exact:
    //   * The RHS must be an INTEGER literal. `SeekRowid` coerces its key via
    //     `to_integer()`, so `id = 2.5` would truncate to 2 and wrongly match rowid 2,
    //     and `id = '2'` / a real / a bound param carry affinity the scan handles
    //     correctly. Everything but an integer literal falls back to the scan.
    //   * Single-row: rowid is unique, so no duplicate-run loop and no scan fallback are
    //     needed — a `SeekRowid` miss means zero matches, which finalizes to the same
    //     COUNT=0 / SUM=NULL the empty scan would produce.
    // Mutually exclusive with `index_eq_seek`: the INTEGER PRIMARY KEY is the table
    // b-tree key, not a secondary index, so `extract_column_eq_target` never matches it.
    let rowid_eq_seek = if allow_index_seek
        && having.is_none()
        && index_eq_seek.is_none()
        && agg_columns.iter().all(|agg| agg.bare_expr.is_none())
    {
        // bd-agg-rowid-eq-coerced: accept any simple constant (placeholder / real /
        // text as well as an integer literal), not just an integer literal.
        // `extract_rowid_target_expr` already requires `is_simple_constant`; the
        // emission coerces a non-integer-literal bound with `MustBeInt` so 2.5 /
        // 'abc' / NULL reject to the empty result instead of `SeekRowid` truncating
        // them to a wrong rowid. Enables the seek for the prepared `WHERE rowid = ?`.
        extract_rowid_target_expr(where_clause, Some(table), table_alias)
    } else {
        None
    };

    // bd-2dgf5: rowid-range bounded scan instead of a full table scan.
    //
    // `SELECT SUM(v) FROM t WHERE <ipk> <= <const>` (and `<`, `>=`, `>`, `BETWEEN`)
    // walked every row; a rowid range visits only `[lower, upper]` by positioning with
    // `Seek*`/`Rewind` and stopping early once the cursor passes the upper bound. This
    // reuses the *exact* extraction, safety gate, and bound-comparison helpers the
    // oracle-tested non-aggregate `codegen_select_rowid_range_scan` uses
    // (`extract_rowid_range_target` + `rowid_range_fast_path_is_safe` +
    // `resolved_rowid_range_comparison`), so the aggregate inherits its affinity/collation
    // correctness; only the per-row action changes (accumulate vs `ResultRow`). Ascending
    // only — aggregates impose no order.
    let rowid_range_seek = if allow_index_seek
        && having.is_none()
        && index_eq_seek.is_none()
        && rowid_eq_seek.is_none()
        && agg_columns.iter().all(|agg| agg.bare_expr.is_none())
    {
        extract_rowid_range_residual_target(where_clause, table, table_alias)
    } else {
        None
    };

    // bd-2dgf5: seek an INTEGER-affinity index once per distinct value of a
    // `WHERE col IN (<int literals>)` instead of full-scanning. Narrowly gated so no
    // per-value scan fallback is needed (see `index_integer_in_list_target`).
    let index_in_seek = if allow_index_seek
        && having.is_none()
        && index_eq_seek.is_none()
        && rowid_eq_seek.is_none()
        && rowid_range_seek.is_none()
        && agg_columns.iter().all(|agg| agg.bare_expr.is_none())
    {
        index_integer_in_list_residual_target(where_clause, table, table_alias)
    } else {
        None
    };

    // Seek + bounded walk over a single-column index for `WHERE col <range>` (`>`, `>=`, `<`, `<=`,
    // `BETWEEN`) instead of a full scan. Reuses the residual-safe `aggregate_index_range_seek_target`
    // detection; mirrors the non-aggregate `codegen_select_index_range_scan`, only the per-row action
    // changes (accumulate vs `ResultRow`).
    let index_range_seek = if allow_index_seek
        && having.is_none()
        && index_eq_seek.is_none()
        && rowid_eq_seek.is_none()
        && rowid_range_seek.is_none()
        && index_in_seek.is_none()
        && agg_columns.iter().all(|agg| agg.bare_expr.is_none())
    {
        aggregate_index_range_seek_target(where_clause, table, table_alias, schema)
    } else {
        None
    };

    // Seek + bounded walk over a composite index for `WHERE a = v AND b <range>` (equality prefix +
    // trailing range). Reuses the now residual-safe `composite_index_prefix_range_target`
    // (bd-zqkrp-residual-drop); mirrors the non-aggregate
    // `codegen_select_composite_index_prefix_range_scan`. The demoted full-equality case (`a=? AND
    // b=?`) is claimed by the earlier `index_eq_seek`, so this only sees genuine ranges.
    let composite_prefix_range_seek = if allow_index_seek
        && having.is_none()
        && index_eq_seek.is_none()
        && rowid_eq_seek.is_none()
        && rowid_range_seek.is_none()
        && index_in_seek.is_none()
        && index_range_seek.is_none()
        && agg_columns.iter().all(|agg| agg.bare_expr.is_none())
    {
        composite_index_prefix_range_target(where_clause, table, table_alias, schema, None)
    } else {
        None
    };

    // Seek the equality-prefix block and apply the full WHERE as a residual filter
    // per row — for `WHERE a = <literal> AND <residual>` where the residual is not a range the composite
    // path handles. The literal prefix needs no bind slot, so the residual filter is emitted once from
    // the original WHERE bind base and its Variable opcodes are reused on every row.
    let index_prefix_residual_seek = if allow_index_seek
        && having.is_none()
        && index_eq_seek.is_none()
        && rowid_eq_seek.is_none()
        && rowid_range_seek.is_none()
        && index_in_seek.is_none()
        && index_range_seek.is_none()
        && composite_prefix_range_seek.is_none()
        && agg_columns.iter().all(|agg| agg.bare_expr.is_none())
    {
        aggregate_index_prefix_literal_residual_target(where_clause, table, table_alias, None)
    } else {
        None
    };

    // bd-agg-rowid-in: aggregate over `WHERE <rowid> IN (<int literals>)` by SeekRowid per distinct value,
    // accumulating each hit, instead of a full scan. The rowid analogue of `index_in_seek` (COUNT(*) is
    // served by count_star's own rowid-IN; this serves SUM/AVG/MIN/MAX/COUNT(col)). Gated LAST so no
    // existing seek gate changes — a rowid IN is mutually exclusive with every shape above. Integer
    // literals only (SeekRowid coerces via to_integer()); sorted+deduped so each row accumulates once; an
    // all-miss leaves the accumulators Null (the empty-scan result).
    let rowid_in_seek = if allow_index_seek
        && having.is_none()
        && index_eq_seek.is_none()
        && rowid_eq_seek.is_none()
        && rowid_range_seek.is_none()
        && index_in_seek.is_none()
        && index_range_seek.is_none()
        && composite_prefix_range_seek.is_none()
        && index_prefix_residual_seek.is_none()
        && !table.without_rowid
        && agg_columns.iter().all(|agg| agg.bare_expr.is_none())
    {
        extract_rowid_in_list_residual_target(where_clause, table, table_alias)
    } else {
        None
    };

    // bd-agg-rowid-eq-residual: aggregate over `WHERE <rowid> = <int> AND <residual>` by seeking the single
    // row and re-applying the residual before AggStep. `extract_rowid_eq_residual_target` returns the const
    // only when `rowid = const` is a conjunct alongside others (the bare eq is served by rowid_eq_seek).
    // Integer literal only; gated after every other seek so no existing gate changes.
    let rowid_eq_residual_seek = if allow_index_seek
        && having.is_none()
        && index_eq_seek.is_none()
        && rowid_eq_seek.is_none()
        && rowid_range_seek.is_none()
        && index_in_seek.is_none()
        && index_range_seek.is_none()
        && composite_prefix_range_seek.is_none()
        && index_prefix_residual_seek.is_none()
        && rowid_in_seek.is_none()
        && !table.without_rowid
        && agg_columns.iter().all(|agg| agg.bare_expr.is_none())
    {
        extract_rowid_eq_residual_target(where_clause, table, table_alias)
            .filter(|rhs| matches!(rhs, Expr::Literal(Literal::Integer(_), _)))
    } else {
        None
    };

    let finalize_label = b.emit_label();
    let where_placeholder_base = b.current_anon_placeholder();
    let mut skip_scan = false;

    // #137 sub-2: a forced `INDEXED BY <idx>` on an aggregate must scan the forced
    // index in its STORED order, not the rowid-order table scan. Resolve the forced
    // index (a plain, non-partial direct-lookup index — an unusable partial forced
    // index already errors at prepare per sub-1). NOT gated on `allow_index_seek`
    // (false for a forced hint). Covering only when no residual WHERE and no bare
    // output column and every aggregate reads from the index entry; otherwise the
    // table row is fetched (rowid seek, or a WITHOUT ROWID PK-suffix seek per
    // sub-4) and any residual WHERE is re-applied per row.
    let forced_index_ordered =
        if let Some(fsqlite_ast::IndexHint::IndexedBy(name)) = from_index_hint {
            table
                .indexes
                .iter()
                .find(|idx| idx.name.eq_ignore_ascii_case(name))
                .filter(|idx| idx.supports_direct_column_lookup())
                .map(|forced_idx| {
                    let covering = where_clause.is_none()
                        && agg_columns.iter().all(|agg| agg.bare_expr.is_none())
                        && aggregate_seek_is_covering(&agg_columns, forced_idx, table);
                    (forced_idx, covering)
                })
        } else {
            None
        };

    if let Some((forced_idx, covering)) = forced_index_ordered {
        // Index-ordered full scan feeding the shared accumulate/finalize. Forward
        // Rewind/Next = stored order (ascending for an ASC index, descending for a
        // DESC index), matching stock's forced-index plan.
        let idx_cursor = 1_i32;
        if !covering {
            b.emit_op(
                Opcode::OpenRead,
                cursor,
                table.root_page,
                0,
                P4::Table(table.name.clone()),
                0,
            );
        }
        b.emit_op(
            Opcode::OpenRead,
            idx_cursor,
            forced_idx.root_page,
            0,
            P4::Index(forced_idx.name.clone()),
            0,
        );
        // Empty index -> finalize with still-Null accumulators (COUNT=0 / SUM=NULL).
        b.emit_jump_to_label(Opcode::Rewind, idx_cursor, 0, finalize_label, P4::None, 0);
        let idx_loop_top = b.current_addr();
        let idx_skip_label = b.emit_label();
        if !covering {
            if table.without_rowid {
                // WITHOUT ROWID: the index entry carries a PK suffix, not a rowid;
                // seek the table b-tree by the PK columns (sub-4).
                let pk_indices = without_rowid_pk_indices(table)?;
                emit_without_rowid_index_to_table_seek(
                    b,
                    table,
                    cursor,
                    idx_cursor,
                    forced_idx,
                    &pk_indices,
                    idx_skip_label,
                );
            } else {
                let rowid_reg = b.alloc_reg();
                b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
                b.emit_jump_to_label(
                    Opcode::SeekRowid,
                    cursor,
                    rowid_reg,
                    idx_skip_label,
                    P4::None,
                    0,
                );
            }
            // Re-apply the whole WHERE per row (the forced full index scan enforces
            // no predicate). Reset the anon-placeholder base so a bound `?` in the
            // residual is numbered once, matching the non-index path.
            if let Some(where_expr) = where_clause {
                b.set_next_anon_placeholder(where_placeholder_base);
                emit_where_filter(
                    b,
                    where_expr,
                    cursor,
                    table,
                    table_alias,
                    schema,
                    idx_skip_label,
                );
            }
        }
        if covering {
            emit_aggregate_accumulate_body_covering(
                b,
                idx_cursor,
                forced_idx,
                table,
                &agg_columns,
                accum_base,
            );
        } else {
            emit_aggregate_accumulate_body(
                b,
                cursor,
                table,
                table_alias,
                schema,
                &agg_columns,
                accum_base,
                first_row_flag,
            );
        }
        b.resolve_label(idx_skip_label);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let idx_loop_body = idx_loop_top as i32;
        b.emit_op(Opcode::Next, idx_cursor, idx_loop_body, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, finalize_label, P4::None, 0);
        skip_scan = true;
    } else if let Some((idx_schema, prefix_exprs)) = index_eq_seek {
        let idx_cursor = 1_i32;
        let scan_fallback = b.emit_label();
        let duplicate_run_done = b.emit_label();
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let prefix_len = prefix_exprs.len() as i32;

        // Can every aggregate read from the index entry alone? If so the table
        // cursor is never opened and no SeekRowid is emitted, matching stock
        // SQLite's "USING COVERING INDEX" plan for e.g. `COUNT(*)`/`SUM(rowid)`.
        let covering = aggregate_seek_is_covering(&agg_columns, idx_schema, table);

        // Every pinned key column is INTEGER-affinity + integer literal ⇒ the seek is EXACT (the index's
        // storage-class order matches the WHERE comparison), so a 0-match seek is authoritative and the
        // full-scan fallback (an affinity safety net for mixed-type columns) is unnecessary: a miss
        // finalizes to the empty-aggregate result (COUNT=0 / SUM=NULL) directly, making an absent-key
        // lookup O(log n) not the O(n) fallback scan. (Non-exact keeps the fallback.) bd-eq-seek-fallback-zero-match.
        let exact_seek = prefix_exprs.iter().enumerate().all(|(i, e)| {
            matches!(e, Expr::Literal(Literal::Integer(_), _))
                && idx_schema
                    .columns
                    .get(i)
                    .and_then(|name| table.column_index(name))
                    .and_then(|ci| table.columns.get(ci))
                    .is_some_and(|c| c.affinity == 'D')
        });
        let seek_miss_label = if exact_seek {
            finalize_label
        } else {
            scan_fallback
        };

        // A true partial key `[prefix..]` is the floor of the pinned block. Do not append an
        // `i64::MIN` sentinel: it sorts at the wrong end of a DESC next term and after NULLs in an ASC
        // next term, turning an exact seek into a false miss or silently dropping NULL-bearing rows.
        let probe_key_regs = b.alloc_regs(prefix_len);
        for (i, expr) in prefix_exprs.iter().enumerate() {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let reg = probe_key_regs + i as i32;
            emit_expr(b, expr, reg, None);
            // `col = NULL` matches nothing; use the same exact/fallback miss destination as SeekGE.
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, seek_miss_label, P4::None, 0);
        }

        let saw_index_match_reg = b.alloc_reg();
        b.emit_op(Opcode::Integer, 0, saw_index_match_reg, 0, P4::None, 0);
        let probe_record_reg = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            probe_key_regs,
            prefix_len,
            probe_record_reg,
            P4::None,
            0,
        );

        if !covering {
            b.emit_op(
                Opcode::OpenRead,
                cursor,
                table.root_page,
                0,
                P4::Table(table.name.clone()),
                0,
            );
        }
        b.emit_op(
            Opcode::OpenRead,
            idx_cursor,
            idx_schema.root_page,
            0,
            P4::Index(idx_schema.name.clone()),
            0,
        );
        b.emit_jump_to_label(
            Opcode::SeekGE,
            idx_cursor,
            probe_record_reg,
            seek_miss_label,
            P4::None,
            0,
        );

        let idx_loop_top = b.current_addr();
        let idx_key_reg = b.alloc_reg();
        // End the pinned run as soon as any prefix column differs from the probe. `0x10` (JUMPIFNULL):
        // a NULL index key also ends the run — it can't equal the non-NULL probe value.
        for i in 0..prefix_exprs.len() {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let col = i as i32;
            b.emit_op(Opcode::Column, idx_cursor, col, idx_key_reg, P4::None, 0);
            let coll = idx_schema
                .key_term_collation(i)
                .filter(|c| !c.eq_ignore_ascii_case("BINARY"))
                .map_or(P4::None, |c| P4::Collation(c.to_owned()));
            b.emit_jump_to_label(
                Opcode::Ne,
                probe_key_regs + col,
                idx_key_reg,
                duplicate_run_done,
                coll,
                0x10,
            );
        }

        let idx_skip_label = b.emit_label();
        b.emit_op(Opcode::Integer, 1, saw_index_match_reg, 0, P4::None, 0);
        if !covering {
            let rowid_reg = b.alloc_reg();
            b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                cursor,
                rowid_reg,
                idx_skip_label,
                P4::None,
                0,
            );
        }

        // No WHERE filter here, by construction: `aggregate_index_eq_seek_target`
        // only matches when the entire WHERE clause is the pinned equality
        // prefix, and the SeekGE + per-term Ne guards enforce exactly those
        // predicates. Re-emitting the filter would also consume anonymous
        // placeholders a second time and misnumber bound parameters. This
        // mirrors `codegen_select_index_equality_scan`, which likewise emits no
        // filter on its index path.
        if covering {
            emit_aggregate_accumulate_body_covering(
                b,
                idx_cursor,
                idx_schema,
                table,
                &agg_columns,
                accum_base,
            );
        } else {
            emit_aggregate_accumulate_body(
                b,
                cursor,
                table,
                table_alias,
                schema,
                &agg_columns,
                accum_base,
                first_row_flag,
            );
        }

        b.resolve_label(idx_skip_label);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let idx_loop_body = idx_loop_top as i32;
        b.emit_op(Opcode::Next, idx_cursor, idx_loop_body, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, finalize_label, P4::None, 0);

        b.resolve_label(duplicate_run_done);
        if exact_seek {
            // Exact seek: 0 matches is authoritative → finalize directly (accumulators still Null).
            b.emit_jump_to_label(Opcode::Goto, 0, 0, finalize_label, P4::None, 0);
        } else {
            b.emit_jump_to_label(
                Opcode::If,
                saw_index_match_reg,
                0,
                finalize_label,
                P4::None,
                0,
            );
        }

        // No index match: fall through to the full scan. No AggStep ran, so the
        // accumulators are still Null and the scan starts from a clean slate.
        b.resolve_label(scan_fallback);
        b.set_next_anon_placeholder(where_placeholder_base);
    } else if let Some(rowid_rhs) = rowid_eq_seek {
        // bd-2dgf5 rowid point lookup: seek the single row and accumulate it. A
        // `SeekRowid` miss (or a `MustBeInt`-rejected non-exact key) jumps straight to
        // finalize, where the still-Null accumulators produce COUNT=0 / SUM=NULL — the
        // exact empty-scan result. No duplicate-run loop and no scan fallback: rowid is
        // unique and `MustBeInt` (below) makes a non-integer-literal key exact-or-reject,
        // so the full scan is skipped.
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
        let rowid_reg = b.alloc_reg();
        emit_expr(b, rowid_rhs, rowid_reg, None);
        // bd-agg-rowid-eq-coerced: coerce a non-integer-literal bound (placeholder /
        // real / text) to INTEGER affinity before the seek; a non-exact key (2.5 /
        // 'abc' / NULL) jumps to finalize (still-Null accumulators -> COUNT=0 /
        // SUM=NULL, the exact empty result), while '5' / 5.0 coerce to 5. An integer
        // literal is already exact -> no MustBeInt (byte-identical to the pre-existing
        // integer-literal callers, golden snapshots unchanged).
        if !matches!(rowid_rhs, Expr::Literal(Literal::Integer(_), _)) {
            b.emit_jump_to_label(Opcode::MustBeInt, rowid_reg, 0, finalize_label, P4::None, 0);
        }
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            cursor,
            rowid_reg,
            finalize_label,
            P4::None,
            0,
        );
        emit_aggregate_accumulate_body(
            b,
            cursor,
            table,
            table_alias,
            schema,
            &agg_columns,
            accum_base,
            first_row_flag,
        );
        skip_scan = true;
    } else if let Some((range, has_residual)) = rowid_range_seek {
        // bd-2dgf5 rowid range: position at the lower bound (or start), accumulate, and
        // stop early once the cursor rowid passes the upper bound. Mirrors the ascending
        // path of `codegen_select_rowid_range_scan`; a NULL bound yields the empty result
        // via a jump to finalize (still-Null accumulators → COUNT=0 / SUM=NULL). With a residual
        // predicate the range is a SUPERSET, so the whole (placeholder-free) WHERE is re-applied per row.
        let lower_reg = range.lower.map(|bound| {
            let reg = b.alloc_reg();
            emit_expr(b, bound.expr, reg, None);
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, finalize_label, P4::None, 0);
            reg
        });
        let upper_reg = range.upper.map(|bound| {
            let reg = b.alloc_reg();
            emit_expr(b, bound.expr, reg, None);
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, finalize_label, P4::None, 0);
            reg
        });
        let upper_comparison = range
            .upper
            .map(|bound| resolved_rowid_range_comparison(table, table_alias, schema, bound));

        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
        if let Some(bound) = range.lower {
            let seek_opcode = if bound.inclusive {
                Opcode::SeekGE
            } else {
                Opcode::SeekGT
            };
            b.emit_jump_to_label(
                seek_opcode,
                cursor,
                lower_reg.expect("lower bound register exists when range.lower is set"),
                finalize_label,
                P4::None,
                0,
            );
        } else {
            b.emit_jump_to_label(Opcode::Rewind, cursor, 0, finalize_label, P4::None, 0);
        }

        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let range_loop_top = b.current_addr() as i32;
        if let Some(bound) = range.upper {
            let current_rowid_reg = b.alloc_reg();
            let stop_opcode = if bound.inclusive {
                Opcode::Gt
            } else {
                Opcode::Ge
            };
            b.emit_op(Opcode::Rowid, cursor, current_rowid_reg, 0, P4::None, 0);
            b.emit_jump_to_label(
                stop_opcode,
                upper_reg.expect("upper bound register exists when range.upper is set"),
                current_rowid_reg,
                finalize_label,
                upper_comparison
                    .as_ref()
                    .map_or(P4::None, |c| c.collation_p4.clone()),
                upper_comparison.as_ref().map_or(0, |c| c.cmp_p5),
            );
        }
        let range_skip_label = b.emit_label();
        // Residual: re-apply the whole (placeholder-free) WHERE; the rowid range is a superset.
        if has_residual && let Some(where_expr) = where_clause {
            emit_where_filter(
                b,
                where_expr,
                cursor,
                table,
                table_alias,
                schema,
                range_skip_label,
            );
        }
        emit_aggregate_accumulate_body(
            b,
            cursor,
            table,
            table_alias,
            schema,
            &agg_columns,
            accum_base,
            first_row_flag,
        );
        b.resolve_label(range_skip_label);
        b.emit_op(Opcode::Next, cursor, range_loop_top, 0, P4::None, 0);
        skip_scan = true;
    } else if let Some((idx_schema, values, has_residual)) = index_in_seek {
        // bd-2dgf5 IN-list: open the index (and the table only when not covering), then seek each
        // distinct value's duplicate run and accumulate its rows. INTEGER-affinity + integer-literal
        // values make each probe exact and the runs disjoint, so no scan fallback is needed. Covering
        // when every aggregate reads only the indexed column or is COUNT(*)/SUM(rowid).
        let idx_cursor = 1_i32;
        let covering = !has_residual && aggregate_seek_is_covering(&agg_columns, idx_schema, table);
        let residual_where = has_residual.then_some(where_clause).flatten();
        if !covering {
            b.emit_op(
                Opcode::OpenRead,
                cursor,
                table.root_page,
                0,
                P4::Table(table.name.clone()),
                0,
            );
        }
        b.emit_op(
            Opcode::OpenRead,
            idx_cursor,
            idx_schema.root_page,
            0,
            P4::Index(idx_schema.name.clone()),
            0,
        );
        for value in values {
            emit_aggregate_index_value_seek(
                b,
                cursor,
                idx_cursor,
                idx_schema,
                table,
                table_alias,
                schema,
                &agg_columns,
                accum_base,
                first_row_flag,
                value,
                covering,
                residual_where,
            );
        }
        skip_scan = true;
    } else if let Some((idx_schema, index_range, has_residual)) = index_range_seek {
        // Single-column index range: position at the lower bound (or `Rewind` when unbounded below),
        // walk while the key stays within the range, accumulate. Mirrors the ascending half of
        // `codegen_select_index_range_scan`; a NULL bound / empty range jumps to finalize (still-Null
        // accumulators → COUNT=0 / SUM=NULL). No ORDER BY / LIMIT to satisfy here. When every aggregate
        // reads only the indexed column (or is COUNT(*)/SUM(rowid)) the walk is COVERING — the table
        // cursor is never opened and no `SeekRowid` is emitted (SQLite's "USING COVERING INDEX" plan).
        // With a residual predicate the walk is a SUPERSET, so it is forced non-covering and the whole
        // (placeholder-free) WHERE is re-applied per row.
        let idx_cursor = 1_i32;
        let covering = !has_residual && aggregate_seek_is_covering(&agg_columns, idx_schema, table);
        let bound_affinity = idx_schema
            .columns
            .first()
            .and_then(|name| table.column_index(name))
            .map(|i| table.columns[i].affinity)
            .filter(|&aff| matches!(aff, 'C' | 'D' | 'E' | 'B'));

        let lower_probe = index_range.lower.as_ref().map(|bound| {
            let base = b.alloc_regs(2);
            emit_expr(b, bound.expr(), base, None);
            if let Some(aff) = bound_affinity
                && !bound_matches_affinity(aff, bound.expr())
            {
                b.emit_op(
                    Opcode::Affinity,
                    base,
                    1,
                    0,
                    P4::Affinity(aff.to_string()),
                    0,
                );
            }
            b.emit_jump_to_label(Opcode::IsNull, base, 0, finalize_label, P4::None, 0);
            b.emit_op(Opcode::Int64, 0, base + 1, 0, P4::Int64(i64::MIN), 0);
            (base, bound.inclusive)
        });
        let upper_reg = index_range.upper.as_ref().map(|bound| {
            let reg = b.alloc_reg();
            emit_expr(b, bound.expr(), reg, None);
            if let Some(aff) = bound_affinity
                && !bound_matches_affinity(aff, bound.expr())
            {
                b.emit_op(
                    Opcode::Affinity,
                    reg,
                    1,
                    0,
                    P4::Affinity(aff.to_string()),
                    0,
                );
            }
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, finalize_label, P4::None, 0);
            (reg, bound.inclusive)
        });
        // A register holding the current key, needed to test an exclusive lower bound or any upper bound.
        let current_key_reg = (upper_reg.is_some()
            || lower_probe
                .as_ref()
                .is_some_and(|(_, inclusive)| !inclusive))
        .then(|| b.alloc_reg());

        if !covering {
            b.emit_op(
                Opcode::OpenRead,
                cursor,
                table.root_page,
                0,
                P4::Table(table.name.clone()),
                0,
            );
        }
        b.emit_op(
            Opcode::OpenRead,
            idx_cursor,
            idx_schema.root_page,
            0,
            P4::Index(idx_schema.name.clone()),
            0,
        );

        if let Some((lower_reg, _)) = lower_probe.as_ref() {
            let probe_record_reg = b.alloc_reg();
            b.emit_op(
                Opcode::MakeRecord,
                *lower_reg,
                2,
                probe_record_reg,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::SeekGE,
                idx_cursor,
                probe_record_reg,
                finalize_label,
                P4::None,
                0,
            );
        } else {
            b.emit_jump_to_label(Opcode::Rewind, idx_cursor, 0, finalize_label, P4::None, 0);
        }

        let loop_top = b.current_addr();
        let skip_label = b.emit_label();

        if let Some(key_reg) = current_key_reg {
            b.emit_op(Opcode::Column, idx_cursor, 0, key_reg, P4::None, 0);
            // With no lower probe (`Rewind` start) the leading NULLs of the index must be skipped —
            // a NULL key satisfies no range bound.
            if lower_probe.is_none() {
                b.emit_jump_to_label(Opcode::IsNull, key_reg, 0, skip_label, P4::None, 0);
            }
        }
        if let Some((lower_reg, inclusive)) = lower_probe.as_ref()
            && !inclusive
        {
            b.emit_jump_to_label(
                Opcode::Le,
                *lower_reg,
                current_key_reg.expect("exclusive lower bound reads current key"),
                skip_label,
                P4::None,
                0,
            );
        }
        if let Some((up_reg, up_inclusive)) = upper_reg {
            let stop = if up_inclusive { Opcode::Gt } else { Opcode::Ge };
            b.emit_jump_to_label(
                stop,
                up_reg,
                current_key_reg.expect("upper bound reads current key"),
                finalize_label,
                P4::None,
                0,
            );
        }

        if covering {
            emit_aggregate_accumulate_body_covering(
                b,
                idx_cursor,
                idx_schema,
                table,
                &agg_columns,
                accum_base,
            );
        } else {
            let rowid_reg = b.alloc_reg();
            b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                cursor,
                rowid_reg,
                skip_label,
                P4::None,
                0,
            );
            // Residual: re-apply the whole (placeholder-free) WHERE; the range is a superset.
            if has_residual && let Some(where_expr) = where_clause {
                emit_where_filter(
                    b,
                    where_expr,
                    cursor,
                    table,
                    table_alias,
                    schema,
                    skip_label,
                );
            }
            emit_aggregate_accumulate_body(
                b,
                cursor,
                table,
                table_alias,
                schema,
                &agg_columns,
                accum_base,
                first_row_flag,
            );
        }

        b.resolve_label(skip_label);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let loop_body = loop_top as i32;
        b.emit_op(Opcode::Next, idx_cursor, loop_body, 0, P4::None, 0);
        skip_scan = true;
    } else if let Some(comp) = composite_prefix_range_seek {
        // bd-agg-composite-prefix-range: seek the `a = v` block bounded by the range on the next key
        // column and accumulate. Mirrors `codegen_select_composite_index_prefix_range_scan`: `IdxGT`
        // on the `prefix_len`-column prefix ends the run, the range bound checks skip/stop within it.
        // Covering when the aggregates read only the leading (pinned) column or are COUNT(*)/SUM(rowid).
        let idx_schema = comp.index;
        let prefix_exprs = &comp.prefix_exprs;
        let range = &comp.range;
        let idx_cursor = 1_i32;
        let key_terms = idx_schema.key_term_count();
        let prefix_len = prefix_exprs.len();
        let range_pos = prefix_len;

        let covering = aggregate_seek_is_covering(&agg_columns, idx_schema, table);

        let key_affinities: Vec<Option<char>> = (0..key_terms)
            .map(|pos| {
                idx_schema
                    .columns
                    .get(pos)
                    .and_then(|name| table.column_index(name))
                    .map(|i| table.columns[i].affinity)
                    .filter(|&a| matches!(a, 'C' | 'D' | 'E' | 'B'))
            })
            .collect();

        // Probe record: [prefix..., range-lower-or-NULL, trailing NULLs, rowid = MIN].
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let probe = b.alloc_regs(key_terms as i32 + 1);
        for (pos, expr) in prefix_exprs.iter().enumerate() {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let reg = probe + pos as i32;
            emit_expr(b, expr, reg, None);
            if let Some(aff) = key_affinities[pos]
                && !bound_matches_affinity(aff, expr)
            {
                b.emit_op(
                    Opcode::Affinity,
                    reg,
                    1,
                    0,
                    P4::Affinity(aff.to_string()),
                    0,
                );
            }
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, finalize_label, P4::None, 0);
        }
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let range_reg = probe + range_pos as i32;
        let lower_inclusive = if let Some(lower) = range.lower.as_ref() {
            emit_expr(b, lower.expr(), range_reg, None);
            if let Some(aff) = key_affinities[range_pos]
                && !bound_matches_affinity(aff, lower.expr())
            {
                b.emit_op(
                    Opcode::Affinity,
                    range_reg,
                    1,
                    0,
                    P4::Affinity(aff.to_string()),
                    0,
                );
            }
            b.emit_jump_to_label(Opcode::IsNull, range_reg, 0, finalize_label, P4::None, 0);
            Some(lower.inclusive)
        } else {
            b.emit_op(Opcode::Null, 0, range_reg, 0, P4::None, 0);
            None
        };
        for pos in (range_pos + 1)..key_terms {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let reg = probe + pos as i32;
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
        }
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let rowid_sentinel = probe + key_terms as i32;
        b.emit_op(Opcode::Int64, 0, rowid_sentinel, 0, P4::Int64(i64::MIN), 0);
        let probe_rec = b.alloc_reg();
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        b.emit_op(
            Opcode::MakeRecord,
            probe,
            key_terms as i32 + 1,
            probe_rec,
            P4::None,
            0,
        );

        let upper = range.upper.as_ref().map(|u| {
            let reg = b.alloc_reg();
            emit_expr(b, u.expr(), reg, None);
            if let Some(aff) = key_affinities[range_pos]
                && !bound_matches_affinity(aff, u.expr())
            {
                b.emit_op(
                    Opcode::Affinity,
                    reg,
                    1,
                    0,
                    P4::Affinity(aff.to_string()),
                    0,
                );
            }
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, finalize_label, P4::None, 0);
            (reg, u.inclusive)
        });

        if !covering {
            b.emit_op(
                Opcode::OpenRead,
                cursor,
                table.root_page,
                0,
                P4::Table(table.name.clone()),
                0,
            );
        }
        b.emit_op(
            Opcode::OpenRead,
            idx_cursor,
            idx_schema.root_page,
            0,
            P4::Index(idx_schema.name.clone()),
            0,
        );
        b.emit_jump_to_label(
            Opcode::SeekGE,
            idx_cursor,
            probe_rec,
            finalize_label,
            P4::None,
            0,
        );

        let loop_top = b.current_addr();
        let skip_label = b.emit_label();
        // Stop once the equality prefix changes (`IdxGT` compares only the first `prefix_len` columns).
        // With an EMPTY prefix (pure leading-term range, bd-bn45n) there is nothing to compare, so skip
        // the IdxGT and let the range bounds alone terminate the walk (mirrors the non-aggregate
        // `codegen_select_composite_index_prefix_range_scan`): a zero-column IdxGT is a degenerate no-op.
        if prefix_len > 0 {
            #[allow(clippy::cast_possible_truncation)]
            b.emit_jump_to_label(
                Opcode::IdxGT,
                idx_cursor,
                probe_rec,
                finalize_label,
                P4::None,
                prefix_len as u16,
            );
        }

        let range_key_reg = b.alloc_reg();
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        b.emit_op(
            Opcode::Column,
            idx_cursor,
            range_pos as i32,
            range_key_reg,
            P4::None,
            0,
        );
        if range.lower.is_none() {
            b.emit_jump_to_label(Opcode::IsNull, range_key_reg, 0, skip_label, P4::None, 0);
        }
        if lower_inclusive == Some(false) {
            b.emit_jump_to_label(
                Opcode::Le,
                range_reg,
                range_key_reg,
                skip_label,
                P4::None,
                0,
            );
        }
        if let Some((up_reg, up_inclusive)) = upper {
            let stop = if up_inclusive { Opcode::Gt } else { Opcode::Ge };
            b.emit_jump_to_label(stop, up_reg, range_key_reg, finalize_label, P4::None, 0);
        }

        if covering {
            emit_aggregate_accumulate_body_covering(
                b,
                idx_cursor,
                idx_schema,
                table,
                &agg_columns,
                accum_base,
            );
        } else {
            let rowid_reg = b.alloc_reg();
            b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                cursor,
                rowid_reg,
                skip_label,
                P4::None,
                0,
            );
            emit_aggregate_accumulate_body(
                b,
                cursor,
                table,
                table_alias,
                schema,
                &agg_columns,
                accum_base,
                first_row_flag,
            );
        }

        b.resolve_label(skip_label);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let loop_body = loop_top as i32;
        b.emit_op(Opcode::Next, idx_cursor, loop_body, 0, P4::None, 0);
        skip_scan = true;
    } else if let Some((idx_schema, prefix_exprs)) = index_prefix_residual_seek {
        // bd-agg-leading-eq-residual: seek the storage-class-exact equality-prefix block, then apply
        // the full WHERE per row so the residual predicate is enforced (no dropped-predicate bug),
        // and accumulate. Always non-covering — the residual filter reads table columns.
        let idx_cursor = 1_i32;
        let duplicate_run_done = b.emit_label();
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let prefix_len = prefix_exprs.len() as i32;

        let probe_key_regs = b.alloc_regs(prefix_len);
        for (i, expr) in prefix_exprs.iter().enumerate() {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let reg = probe_key_regs + i as i32;
            emit_expr(b, expr, reg, None);
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, finalize_label, P4::None, 0);
        }
        // A true partial record is the floor of the entire prefix block. A
        // synthetic `i64::MIN` next term would sort after NULL on an ASC
        // trailing key (and at the wrong end of a DESC key), silently dropping
        // matching entries.
        let probe_record_reg = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            probe_key_regs,
            prefix_len,
            probe_record_reg,
            P4::None,
            0,
        );

        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
        b.emit_op(
            Opcode::OpenRead,
            idx_cursor,
            idx_schema.root_page,
            0,
            P4::Index(idx_schema.name.clone()),
            0,
        );
        b.emit_jump_to_label(
            Opcode::SeekGE,
            idx_cursor,
            probe_record_reg,
            finalize_label,
            P4::None,
            0,
        );

        let idx_loop_top = b.current_addr();
        let idx_key_reg = b.alloc_reg();
        for i in 0..prefix_exprs.len() {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let col = i as i32;
            b.emit_op(Opcode::Column, idx_cursor, col, idx_key_reg, P4::None, 0);
            let coll = idx_schema
                .key_term_collation(i)
                .filter(|c| !c.eq_ignore_ascii_case("BINARY"))
                .map_or(P4::None, |c| P4::Collation(c.to_owned()));
            b.emit_jump_to_label(
                Opcode::Ne,
                probe_key_regs + col,
                idx_key_reg,
                duplicate_run_done,
                coll,
                0x10,
            );
        }

        let skip_label = b.emit_label();
        let rowid_reg = b.alloc_reg();
        b.emit_op(Opcode::IdxRowid, idx_cursor, rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            cursor,
            rowid_reg,
            skip_label,
            P4::None,
            0,
        );
        // Apply the whole WHERE — the prefix equalities are redundant with the
        // seek but harmless; the residual conjuncts are the point.
        if let Some(where_expr) = where_clause {
            emit_where_filter(
                b,
                where_expr,
                cursor,
                table,
                table_alias,
                schema,
                skip_label,
            );
        }
        emit_aggregate_accumulate_body(
            b,
            cursor,
            table,
            table_alias,
            schema,
            &agg_columns,
            accum_base,
            first_row_flag,
        );

        b.resolve_label(skip_label);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let idx_loop_body = idx_loop_top as i32;
        b.emit_op(Opcode::Next, idx_cursor, idx_loop_body, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, finalize_label, P4::None, 0);
        b.resolve_label(duplicate_run_done);
        skip_scan = true;
    } else if let Some((values, has_residual)) = rowid_in_seek {
        // bd-agg-rowid-in [+ residual]: SeekRowid per distinct listed value, accumulating each hit into the
        // aggregate. A miss skips to the next value; an all-miss leaves the accumulators Null (the
        // empty-scan result). Mirrors the proven `rowid_eq_seek` block as a per-value loop;
        // `emit_aggregate_accumulate_body` reads the seeked row into `AggStep`. Values are sorted+deduped
        // so each row accumulates once. With a residual (rowid IN coexisting with a predicate the seek
        // cannot enforce) the full WHERE is re-applied per hit — its `?` placeholders re-numbered to a
        // fixed base each iteration (the IN values are integer literals, so nothing before the filter
        // consumes a placeholder); a residual miss skips to the next value. bd-agg-rowid-in-residual.
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
        let rowid_reg = b.alloc_reg();
        let where_placeholder_base = b.current_anon_placeholder();
        for value in &values {
            let skip_label = b.emit_label();
            b.emit_op(Opcode::Int64, 0, rowid_reg, 0, P4::Int64(*value), 0);
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                cursor,
                rowid_reg,
                skip_label,
                P4::None,
                0,
            );
            if has_residual && let Some(where_expr) = where_clause {
                b.set_next_anon_placeholder(where_placeholder_base);
                emit_where_filter(
                    b,
                    where_expr,
                    cursor,
                    table,
                    table_alias,
                    schema,
                    skip_label,
                );
            }
            emit_aggregate_accumulate_body(
                b,
                cursor,
                table,
                table_alias,
                schema,
                &agg_columns,
                accum_base,
                first_row_flag,
            );
            b.resolve_label(skip_label);
        }
        skip_scan = true;
    } else if let Some(rowid_rhs) = rowid_eq_residual_seek {
        // bd-agg-rowid-eq-residual: seek the single `rowid = <int>` row and re-apply the residual; a
        // SeekRowid miss OR a residual miss jumps to finalize (Null accumulators = the empty-scan result).
        // The residual is emitted once (single seek), so its `?` placeholders number naturally.
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );
        let rowid_reg = b.alloc_reg();
        emit_expr(b, rowid_rhs, rowid_reg, None);
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            cursor,
            rowid_reg,
            finalize_label,
            P4::None,
            0,
        );
        if let Some(where_expr) = where_clause {
            emit_where_filter(
                b,
                where_expr,
                cursor,
                table,
                table_alias,
                schema,
                finalize_label,
            );
        }
        emit_aggregate_accumulate_body(
            b,
            cursor,
            table,
            table_alias,
            schema,
            &agg_columns,
            accum_base,
            first_row_flag,
        );
        skip_scan = true;
    }

    if !skip_scan {
        // Open table for reading.
        b.emit_op(
            Opcode::OpenRead,
            cursor,
            table.root_page,
            0,
            P4::Table(table.name.clone()),
            0,
        );

        // Rewind to first row; jump to finalize if table is empty.
        let loop_start = b.current_addr();
        b.emit_jump_to_label(Opcode::Rewind, cursor, 0, finalize_label, P4::None, 0);

        // WHERE filter.
        let skip_label = b.emit_label();
        if let Some(where_expr) = where_clause {
            emit_where_filter(
                b,
                where_expr,
                cursor,
                table,
                table_alias,
                schema,
                skip_label,
            );
        }

        // AggStep for each aggregate column.
        emit_aggregate_accumulate_body(
            b,
            cursor,
            table,
            table_alias,
            schema,
            &agg_columns,
            accum_base,
            first_row_flag,
        );

        // Skip label for WHERE-filtered rows.
        b.resolve_label(skip_label);

        // Next: loop back to start of loop body (instruction after Rewind).
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let loop_body = (loop_start + 1) as i32;
        b.emit_op(Opcode::Next, cursor, loop_body, 0, P4::None, 0);
    }

    // Finalize: emit AggFinal for each aggregate.
    b.resolve_label(finalize_label);

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for (i, agg) in agg_columns.iter().enumerate() {
        // Skip sentinel entries (multi-aggregate wrappers have no function).
        if agg.name.is_empty() && !agg.multi_agg_indices.is_empty() {
            continue;
        }
        // Row-dependent bare expressions already hold the final scanned row's
        // value. Evaluate row-independent scalars here exactly once so empty
        // input still produces their ordinary value.
        if let Some(bare) = agg.bare_expr.as_deref() {
            let accum_reg = accum_base + i as i32;
            if !expr_references_scan(bare, table, table_alias) {
                emit_expr(b, bare, accum_reg, None);
            } else {
                // bd-9zlcs: a scan-referencing bare expression such as
                // `typeof(a)` captured its value on the first scanned row
                // (gated by `first_row_flag`). Over an EMPTY input group the
                // scan never ran, so `accum_reg` still holds its NULL init —
                // but stock evaluates the expression against NULL columns
                // (e.g. `typeof(a)` over zero rows = typeof(NULL) = 'null',
                // not NULL). Emit that empty-group evaluation, guarded so a
                // non-empty group keeps its captured value byte-for-byte.
                let skip_empty = b.emit_label();
                b.emit_jump_to_label(Opcode::If, first_row_flag, 0, skip_empty, P4::None, 0);
                let ncols = i32::try_from(table.columns.len()).unwrap_or(0);
                if ncols > 0 {
                    let null_base = b.alloc_regs(ncols);
                    b.emit_op(
                        Opcode::Null,
                        0,
                        null_base,
                        null_base + ncols - 1,
                        P4::None,
                        0,
                    );
                    let null_ctx = ScanCtx {
                        cursor,
                        table,
                        table_alias,
                        schema: Some(schema),
                        register_base: Some(null_base),
                        secondaries: &[],
                    };
                    emit_expr(b, bare, accum_reg, Some(&null_ctx));
                } else {
                    emit_expr(b, bare, accum_reg, None);
                }
                b.resolve_label(skip_empty);
            }
            continue;
        }
        let accum_reg = accum_base + i as i32;
        b.emit_op(
            Opcode::AggFinal,
            accum_reg,
            agg.num_args,
            0,
            P4::FuncName(agg.name.clone()),
            0,
        );
    }

    // Copy accumulator results to output registers, skipping hidden columns.
    // For simple (non-multi-agg) cases, out_col_index tracks the output.
    {
        let mut out_col_index = 0_i32;
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        for (i, agg) in agg_columns.iter().enumerate() {
            if agg.hidden {
                continue;
            }
            // Multi-agg sentinel: output slot but no direct accumulator copy.
            if agg.name.is_empty() && !agg.multi_agg_indices.is_empty() {
                out_col_index += 1;
                continue;
            }
            let accum_reg = accum_base + i as i32;
            let out_reg = out_regs + out_col_index;
            if accum_reg != out_reg {
                b.emit_op(Opcode::Copy, accum_reg, out_reg, 0, P4::None, 0);
            }
            out_col_index += 1;
        }
    }

    // Apply wrapper expressions after AggFinal.
    {
        let mut out_col_index = 0_i32;
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        for (i, agg) in agg_columns.iter().enumerate() {
            if agg.hidden {
                continue;
            }
            if let Some(wrapper) = &agg.wrapper_expr {
                let result_reg = out_regs + out_col_index;
                if agg.multi_agg_indices.is_empty() {
                    // Single-aggregate wrapper (existing path).
                    emit_agg_wrapper(b, wrapper, result_reg);
                } else {
                    // Multi-aggregate wrapper: build fake table with columns
                    // for each referenced accumulator.
                    emit_multi_agg_wrapper(
                        b,
                        wrapper,
                        result_reg,
                        accum_base,
                        &agg.multi_agg_indices,
                    );
                }
            }
            let _ = i; // suppress unused warning
            out_col_index += 1;
        }
    }

    // HAVING filter: skip ResultRow if HAVING predicate is false/NULL.
    // For single-group aggregate (no GROUP BY), each output column maps
    // directly to its aggregate accumulator at accum_base + i.
    let output_skip_label = b.emit_label();
    if let Some(having_expr) = having {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let output_cols: Vec<GroupByOutputCol> = (0..agg_columns.len())
            .map(|i| GroupByOutputCol::Aggregate { agg_index: i })
            .collect();
        emit_having_filter(
            b,
            having_expr,
            &output_cols,
            &agg_columns,
            &[],
            table,
            accum_base,
            output_skip_label,
        );
    }

    // OFFSET applies after HAVING. A single-group aggregate can emit only one
    // row, so any positive offset consumes that row.
    if let Some(offset_reg) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, offset_reg, 1, output_skip_label, P4::None, 0);
    }

    // ResultRow (reached when HAVING passes or when there is no HAVING).
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    if let Some(limit_reg) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, limit_reg, 0, done_label, P4::None, 0);
    }

    // Failed HAVING and consumed OFFSET both jump past ResultRow.
    b.resolve_label(output_skip_label);

    // Done: Close + Halt.
    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End target for Init jump.
    b.resolve_label(end_label);

    Ok(())
}

// Note: codegen_ordered_aggregate (for in-aggregate ORDER BY, SQLite 3.44+)
// was removed because the AggColumn.order_by field is not yet supported.

/// Parse result columns to extract aggregate function metadata.
fn push_bare_aggregate_expr(agg_cols: &mut Vec<AggColumn>, expr: Expr) {
    agg_cols.push(AggColumn {
        name: String::new(),
        num_args: 0,
        arg_col_index: None,
        arg_is_rowid: false,
        distinct: false,
        arg_expr: None,
        extra_args: Vec::new(),
        filter: None,
        wrapper_expr: None,
        hidden: false,
        multi_agg_indices: Vec::new(),
        bare_expr: Some(Box::new(expr)),
        collation: None,
    });
}

fn parse_aggregate_columns(
    columns: &[ResultColumn],
    table: &TableSchema,
) -> Result<Vec<AggColumn>, CodegenError> {
    let mut agg_cols = Vec::with_capacity(columns.len());
    for col in columns {
        match col {
            ResultColumn::Expr {
                expr:
                    Expr::FunctionCall {
                        name,
                        args,
                        distinct,
                        filter,
                        ..
                    },
                ..
            } if is_aggregate_function_call(name, args) => {
                let canon_name = name.to_ascii_uppercase();
                let filt = filter.clone();
                match args {
                    FunctionArgs::Star => {
                        // count(*)
                        agg_cols.push(AggColumn {
                            name: canon_name,
                            num_args: 0,
                            arg_col_index: None,
                            arg_is_rowid: false,
                            distinct: *distinct,
                            arg_expr: None,
                            extra_args: Vec::new(),
                            filter: filt,
                            wrapper_expr: None,
                            hidden: false,
                            multi_agg_indices: Vec::new(),
                            bare_expr: None,
                            collation: None,
                        });
                    }
                    FunctionArgs::List(exprs) => {
                        if exprs.is_empty() {
                            // count() with no args — treat like count(*)
                            agg_cols.push(AggColumn {
                                name: canon_name,
                                num_args: 0,
                                arg_col_index: None,
                                arg_is_rowid: false,
                                distinct: *distinct,
                                arg_expr: None,
                                extra_args: Vec::new(),
                                filter: filt,
                                wrapper_expr: None,
                                hidden: false,
                                multi_agg_indices: Vec::new(),
                                bare_expr: None,
                                collation: None,
                            });
                        } else {
                            // First argument: try column reference first,
                            // fall back to storing the expression for emit_expr.
                            let (col_idx, is_rowid, expr) =
                                match resolve_column_ref(&exprs[0], table, None) {
                                    Some(SortKeySource::Column(idx)) => (Some(idx), false, None),
                                    Some(SortKeySource::Rowid) => (None, true, None),
                                    _ => (None, false, Some(Box::new(exprs[0].clone()))),
                                };
                            // Resolve collation for the aggregate argument column.
                            // Explicit COLLATE in the expression takes priority,
                            // otherwise inherit from the column's schema definition.
                            let needs_collation =
                                *distinct || canon_name == "MIN" || canon_name == "MAX";
                            let agg_coll = if needs_collation {
                                expr_collation_for_agg(&exprs[0], col_idx, table)
                            } else {
                                None
                            };
                            // Extra arguments (e.g. separator for group_concat).
                            let extra: Vec<Expr> = exprs[1..].to_vec();
                            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                            agg_cols.push(AggColumn {
                                name: canon_name,
                                num_args: exprs.len() as i32,
                                arg_col_index: col_idx,
                                arg_is_rowid: is_rowid,
                                distinct: *distinct,
                                arg_expr: expr,
                                extra_args: extra,
                                filter: filt,
                                wrapper_expr: None,
                                hidden: false,
                                multi_agg_indices: Vec::new(),
                                bare_expr: None,
                                collation: agg_coll,
                            });
                        }
                    }
                }
            }
            ResultColumn::Expr { expr, .. } if is_aggregate_expr(expr) => {
                // Expression wraps aggregate(s).  Try single-aggregate
                // extraction first (fast path), then multi-aggregate.
                let single_ok =
                    if let Some((inner_agg, ref wrapper)) = extract_inner_aggregate(expr, table) {
                        if is_aggregate_expr(wrapper) {
                            // Wrapper still contains aggregates → need multi-agg path.
                            false
                        } else {
                            agg_cols.push(AggColumn {
                                wrapper_expr: Some(Box::new(wrapper.clone())),
                                ..inner_agg
                            });
                            true
                        }
                    } else {
                        false
                    };
                if !single_ok {
                    // Multi-aggregate: e.g. MAX(x) - MIN(x).
                    let (extracted, wrapper) = extract_all_inner_aggregates(expr, table);
                    if extracted.is_empty() {
                        return Err(CodegenError::Unsupported(
                            "complex aggregate wrapper expression not supported without GROUP BY"
                                .to_owned(),
                        ));
                    }
                    // Record indices of hidden agg columns for the wrapper.
                    let base_idx = agg_cols.len();
                    let indices: Vec<usize> = (base_idx..base_idx + extracted.len()).collect();
                    // Push hidden aggregates.
                    agg_cols.extend(extracted);
                    // Push a sentinel output entry with the multi-agg wrapper.
                    agg_cols.push(AggColumn {
                        name: String::new(),
                        num_args: 0,
                        arg_col_index: None,
                        arg_is_rowid: false,
                        distinct: false,
                        arg_expr: None,
                        extra_args: Vec::new(),
                        filter: None,
                        wrapper_expr: Some(Box::new(wrapper)),
                        hidden: false,
                        multi_agg_indices: indices,
                        bare_expr: None,
                        collation: None,
                    });
                }
            }
            // Bare (non-aggregate) column in an aggregate query without GROUP BY.
            ResultColumn::Expr { expr, .. } => {
                push_bare_aggregate_expr(&mut agg_cols, expr.clone());
            }
            ResultColumn::Star => {
                for column in &table.columns {
                    push_bare_aggregate_expr(
                        &mut agg_cols,
                        Expr::Column(ColumnRef::bare(column.name.as_str()), Span::ZERO),
                    );
                }
            }
            ResultColumn::TableStar(name) => {
                for column in &table.columns {
                    push_bare_aggregate_expr(
                        &mut agg_cols,
                        Expr::Column(
                            ColumnRef::qualified(name.name.as_str(), column.name.as_str()),
                            Span::ZERO,
                        ),
                    );
                }
            }
        }
    }
    Ok(agg_cols)
}

/// Emit bytecode for an aggregate wrapper expression.
///
/// Handles COALESCE/IFNULL patterns: if the aggregate result in `result_reg`
/// is NULL, substitute the first non-NULL fallback literal.
fn emit_agg_wrapper(b: &mut ProgramBuilder, wrapper: &Expr, result_reg: i32) {
    let fake_table = TableSchema {
        name: "".to_owned(),
        root_page: 0,
        columns: vec![ColumnInfo {
            name: "__agg_result__".to_owned(),
            affinity: 'A',
            is_ipk: false,
            type_name: Some("ANY".to_owned()),
            notnull: false,
            unique: false,
            default_value: None,
            strict_type: None,
            generated_expr: None,
            generated_stored: None,
            collation: None,
            conflict_action: None,
        }],
        indexes: vec![],
        strict: false,
        without_rowid: false,
        primary_key_constraints: Vec::new(),
        foreign_keys: Vec::new(),
        check_constraints: Vec::new(),
    };
    let scan = ScanCtx {
        cursor: 0,
        table: &fake_table,
        table_alias: None,
        schema: None,
        register_base: Some(result_reg),
        secondaries: &[],
    };
    let temp = b.alloc_temp();
    emit_expr(b, wrapper, temp, Some(&scan));
    b.emit_op(Opcode::Copy, temp, result_reg, 0, P4::None, 0);
    b.free_temp(temp);
}

/// Emit bytecode for a multi-aggregate wrapper expression.
///
/// Evaluate a simple aggregate wrapper expression (e.g. `COUNT(*) - 1`).
///
/// The wrapper uses a single placeholder column `__agg_result__` that maps
/// to the finalized aggregate value in `accum_reg`.
fn emit_simple_agg_wrapper(
    b: &mut ProgramBuilder,
    wrapper: &Expr,
    result_reg: i32,
    accum_reg: i32,
) {
    let columns = vec![ColumnInfo {
        name: "__agg_result__".to_owned(),
        affinity: 'A',
        is_ipk: false,
        type_name: Some("ANY".to_owned()),
        notnull: false,
        unique: false,
        default_value: None,
        strict_type: None,
        generated_expr: None,
        generated_stored: None,
        collation: None,
        conflict_action: None,
    }];
    let fake_table = TableSchema {
        name: String::new(),
        root_page: 0,
        columns,
        indexes: vec![],
        strict: false,
        without_rowid: false,
        primary_key_constraints: Vec::new(),
        foreign_keys: Vec::new(),
        check_constraints: Vec::new(),
    };
    let scan = ScanCtx {
        cursor: 0,
        table: &fake_table,
        table_alias: None,
        schema: None,
        register_base: Some(accum_reg),
        secondaries: &[],
    };
    let temp = b.alloc_temp();
    emit_expr(b, wrapper, temp, Some(&scan));
    b.emit_op(Opcode::Copy, temp, result_reg, 0, P4::None, 0);
    b.free_temp(temp);
}

/// Handles patterns like `MAX(x) - MIN(x)` where the wrapper contains
/// placeholder columns `__agg_0__`, `__agg_1__`, … that map to accumulator
/// registers at `accum_base + multi_agg_indices[N]`.
fn emit_multi_agg_wrapper(
    b: &mut ProgramBuilder,
    wrapper: &Expr,
    result_reg: i32,
    accum_base: i32,
    multi_agg_indices: &[usize],
) {
    // Build a fake table with N columns named `__agg_0__`, `__agg_1__`, …
    let columns: Vec<ColumnInfo> = (0..multi_agg_indices.len())
        .map(|i| ColumnInfo {
            name: format!("__agg_{i}__"),
            affinity: 'A',
            is_ipk: false,
            type_name: Some("ANY".to_owned()),
            notnull: false,
            unique: false,
            default_value: None,
            strict_type: None,
            generated_expr: None,
            generated_stored: None,
            collation: None,
            conflict_action: None,
        })
        .collect();
    let fake_table = TableSchema {
        name: String::new(),
        root_page: 0,
        columns,
        indexes: vec![],
        strict: false,
        without_rowid: false,
        primary_key_constraints: Vec::new(),
        foreign_keys: Vec::new(),
        check_constraints: Vec::new(),
    };

    // Copy accumulators into a contiguous register block so the fake scan
    // context can address them via register_base + column_index.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let fake_base = b.alloc_regs(multi_agg_indices.len() as i32);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for (j, &agg_idx) in multi_agg_indices.iter().enumerate() {
        let src = accum_base + agg_idx as i32;
        let dst = fake_base + j as i32;
        b.emit_op(Opcode::Copy, src, dst, 0, P4::None, 0);
    }

    let scan = ScanCtx {
        cursor: 0,
        table: &fake_table,
        table_alias: None,
        schema: None,
        register_base: Some(fake_base),
        secondaries: &[],
    };
    let temp = b.alloc_temp();
    emit_expr(b, wrapper, temp, Some(&scan));
    b.emit_op(Opcode::Copy, temp, result_reg, 0, P4::None, 0);
    b.free_temp(temp);
}

/// Extract the single aggregate function call from a wrapper expression.
///
/// Returns `(AggColumn, wrapper_expr)` where `wrapper_expr` has the aggregate
/// call replaced with a `ColumnRef` placeholder named `__agg_result__` that
/// the codegen emitter will substitute with the accumulator register.
///
/// Handles patterns like `COALESCE(MAX(x), 0)`, `ABS(SUM(x))`, etc.
fn extract_inner_aggregate(expr: &Expr, table: &TableSchema) -> Option<(AggColumn, Expr)> {
    if let Expr::FunctionCall {
        name: agg_name,
        args: agg_args,
        distinct,
        filter,
        ..
    } = expr
        && is_aggregate_function_call(agg_name, agg_args)
    {
        let canon_name = agg_name.to_ascii_uppercase();
        let filt = filter.clone();
        let agg_col = match agg_args {
            FunctionArgs::Star => AggColumn {
                name: canon_name,
                num_args: 0,
                arg_col_index: None,
                arg_is_rowid: false,
                distinct: *distinct,
                arg_expr: None,
                extra_args: Vec::new(),
                filter: filt,
                wrapper_expr: None,
                hidden: false,
                multi_agg_indices: Vec::new(),
                bare_expr: None,
                collation: None,
            },
            FunctionArgs::List(exprs) if exprs.is_empty() => AggColumn {
                name: canon_name,
                num_args: 0,
                arg_col_index: None,
                arg_is_rowid: false,
                distinct: *distinct,
                arg_expr: None,
                extra_args: Vec::new(),
                filter: filt,
                wrapper_expr: None,
                hidden: false,
                multi_agg_indices: Vec::new(),
                bare_expr: None,
                collation: None,
            },
            FunctionArgs::List(exprs) => {
                let (col_idx, is_rowid, a_expr) = match resolve_column_ref(&exprs[0], table, None) {
                    Some(SortKeySource::Column(idx)) => (Some(idx), false, None),
                    Some(SortKeySource::Rowid) => (None, true, None),
                    _ => (None, false, Some(Box::new(exprs[0].clone()))),
                };
                let extra: Vec<Expr> = exprs[1..].to_vec();
                // bd-lgwjd(a): a single aggregate wrapped in an expression
                // (`max(name)||''`) is lowered through THIS extractor; leaving
                // `collation: None` made the runtime min/max step compare BINARY,
                // ignoring the column's declared `COLLATE NOCASE`. Mirror the
                // non-wrapper single-aggregate arm (`expr_collation_for_agg`).
                let needs_collation = *distinct || canon_name == "MIN" || canon_name == "MAX";
                let agg_coll = if needs_collation {
                    expr_collation_for_agg(&exprs[0], col_idx, table)
                } else {
                    None
                };
                #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                AggColumn {
                    name: canon_name,
                    num_args: exprs.len() as i32,
                    arg_col_index: col_idx,
                    arg_is_rowid: is_rowid,
                    distinct: *distinct,
                    arg_expr: a_expr,
                    extra_args: extra,
                    filter: filt,
                    wrapper_expr: None,
                    hidden: false,
                    multi_agg_indices: Vec::new(),
                    bare_expr: None,
                    collation: agg_coll,
                }
            }
        };
        let placeholder = Expr::Column(ColumnRef::bare("__agg_result__"), fsqlite_ast::Span::ZERO);
        return Some((agg_col, placeholder));
    }

    match expr {
        Expr::FunctionCall {
            name,
            args: FunctionArgs::List(exprs),
            distinct,
            order_by,
            filter,
            over,
            span,
        } => {
            for (i, arg) in exprs.iter().enumerate() {
                if let Some((agg_col, new_arg)) = extract_inner_aggregate(arg, table) {
                    let mut new_exprs = exprs.clone();
                    new_exprs[i] = new_arg;
                    return Some((
                        agg_col,
                        Expr::FunctionCall {
                            name: name.clone(),
                            args: FunctionArgs::List(new_exprs),
                            distinct: *distinct,
                            order_by: order_by.clone(),
                            filter: filter.clone(),
                            over: over.clone(),
                            span: *span,
                        },
                    ));
                }
            }
        }
        Expr::BinaryOp {
            left,
            op,
            right,
            span,
        } => {
            if let Some((agg_col, new_left)) = extract_inner_aggregate(left, table) {
                return Some((
                    agg_col,
                    Expr::BinaryOp {
                        left: Box::new(new_left),
                        op: *op,
                        right: right.clone(),
                        span: *span,
                    },
                ));
            }
            if let Some((agg_col, new_right)) = extract_inner_aggregate(right, table) {
                return Some((
                    agg_col,
                    Expr::BinaryOp {
                        left: left.clone(),
                        op: *op,
                        right: Box::new(new_right),
                        span: *span,
                    },
                ));
            }
        }
        Expr::UnaryOp {
            op,
            expr: inner,
            span,
        } => {
            if let Some((agg_col, new_inner)) = extract_inner_aggregate(inner, table) {
                return Some((
                    agg_col,
                    Expr::UnaryOp {
                        op: *op,
                        expr: Box::new(new_inner),
                        span: *span,
                    },
                ));
            }
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            span,
        } => {
            if let Some(b) = operand
                && let Some((agg_col, new_base)) = extract_inner_aggregate(b, table)
            {
                return Some((
                    agg_col,
                    Expr::Case {
                        operand: Some(Box::new(new_base)),
                        whens: whens.clone(),
                        else_expr: else_expr.clone(),
                        span: *span,
                    },
                ));
            }
            for (i, (cond, val)) in whens.iter().enumerate() {
                if let Some((agg_col, new_cond)) = extract_inner_aggregate(cond, table) {
                    let mut new_whens = whens.clone();
                    new_whens[i].0 = new_cond;
                    return Some((
                        agg_col,
                        Expr::Case {
                            operand: operand.clone(),
                            whens: new_whens,
                            else_expr: else_expr.clone(),
                            span: *span,
                        },
                    ));
                }
                if let Some((agg_col, new_val)) = extract_inner_aggregate(val, table) {
                    let mut new_whens = whens.clone();
                    new_whens[i].1 = new_val;
                    return Some((
                        agg_col,
                        Expr::Case {
                            operand: operand.clone(),
                            whens: new_whens,
                            else_expr: else_expr.clone(),
                            span: *span,
                        },
                    ));
                }
            }
            if let Some(e) = else_expr
                && let Some((agg_col, new_else)) = extract_inner_aggregate(e, table)
            {
                return Some((
                    agg_col,
                    Expr::Case {
                        operand: operand.clone(),
                        whens: whens.clone(),
                        else_expr: Some(Box::new(new_else)),
                        span: *span,
                    },
                ));
            }
        }
        Expr::IsNull {
            expr: inner,
            not,
            span,
        } => {
            if let Some((agg_col, new_inner)) = extract_inner_aggregate(inner, table) {
                return Some((
                    agg_col,
                    Expr::IsNull {
                        expr: Box::new(new_inner),
                        not: *not,
                        span: *span,
                    },
                ));
            }
        }
        Expr::Cast {
            expr: inner,
            type_name,
            span,
        } => {
            if let Some((agg_col, new_inner)) = extract_inner_aggregate(inner, table) {
                return Some((
                    agg_col,
                    Expr::Cast {
                        expr: Box::new(new_inner),
                        type_name: type_name.clone(),
                        span: *span,
                    },
                ));
            }
        }
        Expr::Collate {
            expr: inner,
            collation,
            span,
        } => {
            if let Some((agg_col, new_inner)) = extract_inner_aggregate(inner, table) {
                return Some((
                    agg_col,
                    Expr::Collate {
                        expr: Box::new(new_inner),
                        collation: collation.clone(),
                        span: *span,
                    },
                ));
            }
        }
        _ => {}
    }
    None
}

/// Extract ALL aggregate function calls from an expression, replacing each
/// with a numbered placeholder `__agg_N__`.  Returns the list of extracted
/// aggregates and the rewritten wrapper expression.
///
/// Used for expressions like `MAX(x) - MIN(x)` that contain multiple
/// aggregate calls.
fn extract_all_inner_aggregates(expr: &Expr, table: &TableSchema) -> (Vec<AggColumn>, Expr) {
    let mut agg_cols = Vec::new();
    let rewritten = rewrite_aggregates_recursive(expr, table, &mut agg_cols);
    (agg_cols, rewritten)
}

/// Recursively rewrite an expression, replacing each aggregate function call
/// with a `ColumnRef::bare("__agg_N__")` placeholder and collecting the
/// corresponding `AggColumn`.
fn rewrite_aggregates_recursive(
    expr: &Expr,
    table: &TableSchema,
    agg_cols: &mut Vec<AggColumn>,
) -> Expr {
    // If this node IS an aggregate function call, extract it entirely.
    if let Expr::FunctionCall {
        name,
        args,
        distinct,
        filter,
        ..
    } = expr
        && is_aggregate_function_call(name, args)
    {
        let idx = agg_cols.len();
        let canon_name = name.to_ascii_uppercase();
        let filt = filter.clone();
        let agg_col = match args {
            FunctionArgs::Star => AggColumn {
                name: canon_name,
                num_args: 0,
                arg_col_index: None,
                arg_is_rowid: false,
                distinct: *distinct,
                arg_expr: None,
                extra_args: Vec::new(),
                filter: filt,
                wrapper_expr: None,
                hidden: true,
                multi_agg_indices: Vec::new(),
                bare_expr: None,
                collation: None,
            },
            FunctionArgs::List(exprs) if exprs.is_empty() => AggColumn {
                name: canon_name,
                num_args: 0,
                arg_col_index: None,
                arg_is_rowid: false,
                distinct: *distinct,
                arg_expr: None,
                extra_args: Vec::new(),
                filter: filt,
                wrapper_expr: None,
                hidden: true,
                multi_agg_indices: Vec::new(),
                bare_expr: None,
                collation: None,
            },
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            FunctionArgs::List(exprs) => {
                let (col_idx, is_rowid, a_expr) = match resolve_column_ref(&exprs[0], table, None) {
                    Some(SortKeySource::Column(i)) => (Some(i), false, None),
                    Some(SortKeySource::Rowid) => (None, true, None),
                    _ => (None, false, Some(Box::new(exprs[0].clone()))),
                };
                let extra: Vec<Expr> = exprs[1..].to_vec();
                // bd-lgwjd(a): resolve the aggregate-argument collation for MIN/MAX
                // (and DISTINCT) here too — a multi-aggregate expression like
                // `max(name)||min(name)` is lowered through THIS extractor, and
                // leaving `collation: None` made the runtime min/max step compare
                // BINARY, so a column's declared `COLLATE NOCASE` was ignored. The
                // single-aggregate arm already does this (see `needs_collation`
                // above); mirror it so the extracted aggregate carries the same
                // collation.
                let needs_collation = *distinct || canon_name == "MIN" || canon_name == "MAX";
                let agg_coll = if needs_collation {
                    expr_collation_for_agg(&exprs[0], col_idx, table)
                } else {
                    None
                };
                AggColumn {
                    name: canon_name,
                    num_args: exprs.len() as i32,
                    arg_col_index: col_idx,
                    arg_is_rowid: is_rowid,
                    distinct: *distinct,
                    arg_expr: a_expr,
                    extra_args: extra,
                    filter: filt,
                    wrapper_expr: None,
                    hidden: true,
                    multi_agg_indices: Vec::new(),
                    bare_expr: None,
                    collation: agg_coll,
                }
            }
        };
        agg_cols.push(agg_col);
        let placeholder_name = format!("__agg_{idx}__");
        return Expr::Column(
            ColumnRef::bare(placeholder_name.as_str()),
            fsqlite_ast::Span::ZERO,
        );
    }

    // Recurse into child nodes.
    match expr {
        Expr::BinaryOp {
            left,
            op,
            right,
            span,
        } => Expr::BinaryOp {
            left: Box::new(rewrite_aggregates_recursive(left, table, agg_cols)),
            op: *op,
            right: Box::new(rewrite_aggregates_recursive(right, table, agg_cols)),
            span: *span,
        },
        Expr::UnaryOp {
            op,
            expr: inner,
            span,
        } => Expr::UnaryOp {
            op: *op,
            expr: Box::new(rewrite_aggregates_recursive(inner, table, agg_cols)),
            span: *span,
        },
        Expr::Between {
            expr: inner,
            low,
            high,
            not,
            span,
        } => Expr::Between {
            expr: Box::new(rewrite_aggregates_recursive(inner, table, agg_cols)),
            low: Box::new(rewrite_aggregates_recursive(low, table, agg_cols)),
            high: Box::new(rewrite_aggregates_recursive(high, table, agg_cols)),
            not: *not,
            span: *span,
        },
        Expr::In {
            expr: inner,
            set,
            not,
            span,
        } => {
            let rewritten_set = match set {
                InSet::List(items) => InSet::List(
                    items
                        .iter()
                        .map(|item| rewrite_aggregates_recursive(item, table, agg_cols))
                        .collect(),
                ),
                other => other.clone(),
            };
            Expr::In {
                expr: Box::new(rewrite_aggregates_recursive(inner, table, agg_cols)),
                set: rewritten_set,
                not: *not,
                span: *span,
            }
        }
        Expr::Like {
            expr: inner,
            pattern,
            escape,
            op,
            not,
            span,
        } => Expr::Like {
            expr: Box::new(rewrite_aggregates_recursive(inner, table, agg_cols)),
            pattern: Box::new(rewrite_aggregates_recursive(pattern, table, agg_cols)),
            escape: escape
                .as_deref()
                .map(|expr| Box::new(rewrite_aggregates_recursive(expr, table, agg_cols))),
            op: *op,
            not: *not,
            span: *span,
        },
        Expr::Case {
            operand,
            whens,
            else_expr,
            span,
        } => Expr::Case {
            operand: operand
                .as_deref()
                .map(|expr| Box::new(rewrite_aggregates_recursive(expr, table, agg_cols))),
            whens: whens
                .iter()
                .map(|(when_expr, then_expr)| {
                    (
                        rewrite_aggregates_recursive(when_expr, table, agg_cols),
                        rewrite_aggregates_recursive(then_expr, table, agg_cols),
                    )
                })
                .collect(),
            else_expr: else_expr
                .as_deref()
                .map(|expr| Box::new(rewrite_aggregates_recursive(expr, table, agg_cols))),
            span: *span,
        },
        Expr::FunctionCall {
            name,
            args: FunctionArgs::List(exprs),
            distinct,
            order_by,
            filter,
            over,
            span,
        } => {
            let new_exprs: Vec<Expr> = exprs
                .iter()
                .map(|e| rewrite_aggregates_recursive(e, table, agg_cols))
                .collect();
            Expr::FunctionCall {
                name: name.clone(),
                args: FunctionArgs::List(new_exprs),
                distinct: *distinct,
                order_by: order_by.clone(),
                filter: filter.clone(),
                over: over.clone(),
                span: *span,
            }
        }
        Expr::Cast {
            expr: inner,
            type_name,
            span,
        } => Expr::Cast {
            expr: Box::new(rewrite_aggregates_recursive(inner, table, agg_cols)),
            type_name: type_name.clone(),
            span: *span,
        },
        Expr::Collate {
            expr: inner,
            collation,
            span,
        } => Expr::Collate {
            expr: Box::new(rewrite_aggregates_recursive(inner, table, agg_cols)),
            collation: collation.clone(),
            span: *span,
        },
        Expr::IsNull {
            expr: inner,
            not,
            span,
        } => Expr::IsNull {
            expr: Box::new(rewrite_aggregates_recursive(inner, table, agg_cols)),
            not: *not,
            span: *span,
        },
        Expr::JsonAccess {
            expr: inner,
            path,
            arrow,
            span,
        } => Expr::JsonAccess {
            expr: Box::new(rewrite_aggregates_recursive(inner, table, agg_cols)),
            path: Box::new(rewrite_aggregates_recursive(path, table, agg_cols)),
            arrow: *arrow,
            span: *span,
        },
        Expr::RowValue(items, span) => Expr::RowValue(
            items
                .iter()
                .map(|item| rewrite_aggregates_recursive(item, table, agg_cols))
                .collect(),
            *span,
        ),
        // For all other expression types, return as-is (no aggregates inside).
        other => other.clone(),
    }
}

// ---------------------------------------------------------------------------
// GROUP BY aggregate codegen
// ---------------------------------------------------------------------------

/// A GROUP BY key that is either a simple column reference or an arbitrary
/// expression (e.g. `length(name)`, `substr(city, 1, 1)`).
#[derive(Debug)]
enum GroupByKey {
    /// Direct table column — read via `Opcode::Column`.
    Column(usize),
    /// Arbitrary expression — evaluated via `emit_expr` during the scan phase.
    Expression(Box<Expr>),
}

/// Describes one output column in a GROUP BY query.
enum GroupByOutputCol {
    /// A GROUP BY key column. `key_index` is the position within the group key
    /// vector, and `sorter_col` is the column index in the sorter record.
    GroupKey {
        #[allow(dead_code)]
        key_index: usize,
        sorter_col: usize,
    },
    /// An aggregate function column. `agg_index` is the position within the
    /// aggregate accumulator vector.
    Aggregate { agg_index: usize },
    /// A non-grouped column from `SELECT *`. SQLite allows non-grouped,
    /// non-aggregated columns in GROUP BY queries, returning an arbitrary
    /// row's value. `table_col_index` is the column index in the table;
    /// `sorter_col` is the column index in the sorter record; `is_ipk` is
    /// true if this is an INTEGER PRIMARY KEY (rowid alias).
    NonGroupedColumn {
        table_col_index: usize,
        sorter_col: usize,
        is_ipk: bool,
    },
}

/// Parse result columns for a GROUP BY query into output-column descriptors,
/// a list of group keys (column refs or expressions), and aggregate metadata.
///
/// Returns `(output_cols, group_by_keys, agg_columns)`.
#[allow(clippy::type_complexity)]
fn parse_group_by_output(
    columns: &[ResultColumn],
    table: &TableSchema,
    group_by: &[Expr],
) -> Result<(Vec<GroupByOutputCol>, Vec<GroupByKey>, Vec<AggColumn>), CodegenError> {
    // Resolve GROUP BY expressions: column references become Column(idx),
    // arbitrary expressions (e.g. length(name)) become Expression(expr).
    let group_by_keys: Vec<GroupByKey> = group_by
        .iter()
        .map(|expr| {
            if let Some(col_idx) = resolve_column_index(expr, table) {
                GroupByKey::Column(col_idx)
            } else {
                GroupByKey::Expression(Box::new(expr.clone()))
            }
        })
        .collect();

    let mut output_cols = Vec::with_capacity(columns.len());
    let mut agg_columns = Vec::with_capacity(columns.len());

    for col in columns {
        match col {
            ResultColumn::Expr {
                expr:
                    Expr::FunctionCall {
                        name,
                        args,
                        distinct,
                        filter,
                        ..
                    },
                ..
            } if is_aggregate_function_call(name, args) => {
                let agg_index = agg_columns.len();
                let canon_name = name.to_ascii_uppercase();
                let filt = filter.clone();
                match args {
                    FunctionArgs::Star => {
                        agg_columns.push(AggColumn {
                            name: canon_name,
                            num_args: 0,
                            arg_col_index: None,
                            arg_is_rowid: false,
                            distinct: *distinct,
                            arg_expr: None,
                            extra_args: Vec::new(),
                            filter: filt,
                            wrapper_expr: None,
                            hidden: false,
                            multi_agg_indices: Vec::new(),
                            bare_expr: None,
                            collation: None,
                        });
                    }
                    FunctionArgs::List(exprs) => {
                        if exprs.is_empty() {
                            agg_columns.push(AggColumn {
                                name: canon_name,
                                num_args: 0,
                                arg_col_index: None,
                                arg_is_rowid: false,
                                distinct: *distinct,
                                arg_expr: None,
                                extra_args: Vec::new(),
                                filter: filt,
                                wrapper_expr: None,
                                hidden: false,
                                multi_agg_indices: Vec::new(),
                                bare_expr: None,
                                collation: None,
                            });
                        } else {
                            // Try column reference first, fall back to expression.
                            let (col_idx, is_rowid, expr) =
                                match resolve_column_ref(&exprs[0], table, None) {
                                    Some(SortKeySource::Column(idx)) => (Some(idx), false, None),
                                    Some(SortKeySource::Rowid) => (None, true, None),
                                    _ => (None, false, Some(Box::new(exprs[0].clone()))),
                                };
                            let extra: Vec<Expr> = exprs[1..].to_vec();
                            // bd-lgwjd(a): a direct MIN/MAX under GROUP BY is lowered
                            // through this substrate path; carry the argument's
                            // declared collation so the runtime step compares under it
                            // (not BINARY), mirroring the other aggregate extractors.
                            let needs_collation =
                                *distinct || canon_name == "MIN" || canon_name == "MAX";
                            let agg_coll = if needs_collation {
                                expr_collation_for_agg(&exprs[0], col_idx, table)
                            } else {
                                None
                            };
                            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                            agg_columns.push(AggColumn {
                                name: canon_name,
                                num_args: exprs.len() as i32,
                                arg_col_index: col_idx,
                                arg_is_rowid: is_rowid,
                                distinct: *distinct,
                                arg_expr: expr,
                                extra_args: extra,
                                filter: filt,
                                wrapper_expr: None,
                                hidden: false,
                                multi_agg_indices: Vec::new(),
                                bare_expr: None,
                                collation: agg_coll,
                            });
                        }
                    }
                }
                output_cols.push(GroupByOutputCol::Aggregate { agg_index });
            }
            ResultColumn::Expr { expr, .. } => {
                // Match result column to a GROUP BY key: try column index
                // first, then structural expression equality.
                let key_index = if let Some(col_idx) = resolve_column_index(expr, table) {
                    group_by_keys
                        .iter()
                        .position(|k| matches!(k, GroupByKey::Column(c) if *c == col_idx))
                } else {
                    group_by_keys
                        .iter()
                        .position(|k| matches!(k, GroupByKey::Expression(e) if e.as_ref() == expr))
                }
                .ok_or_else(|| {
                    CodegenError::Unsupported("result column not in GROUP BY clause".to_owned())
                })?;
                output_cols.push(GroupByOutputCol::GroupKey {
                    key_index,
                    sorter_col: key_index,
                });
            }
            ResultColumn::Star | ResultColumn::TableStar(_) => {
                // Expand * to all table columns. Each column is either a
                // GROUP BY key or a non-grouped column (SQLite allows this,
                // returning an arbitrary row's value for non-grouped cols).
                for (col_idx, col_info) in table.columns.iter().enumerate() {
                    if let Some(key_index) = group_by_keys
                        .iter()
                        .position(|k| matches!(k, GroupByKey::Column(c) if *c == col_idx))
                    {
                        output_cols.push(GroupByOutputCol::GroupKey {
                            key_index,
                            sorter_col: key_index,
                        });
                    } else {
                        // Non-grouped column — sorter_col assigned later
                        // in codegen_select_group_by_aggregate.
                        output_cols.push(GroupByOutputCol::NonGroupedColumn {
                            table_col_index: col_idx,
                            sorter_col: usize::MAX,
                            is_ipk: col_info.is_ipk,
                        });
                    }
                }
            }
        }
    }

    Ok((output_cols, group_by_keys, agg_columns))
}

/// Rewrite a HAVING clause so that bare references to SELECT-list output
/// aliases are replaced by the underlying SELECT expression.
///
/// C SQLite resolves a name in HAVING against the FROM tables first, and only
/// when it is not a real table column does it bind to a SELECT-list alias. For
/// example `SELECT SUM(qty) AS total_qty ... HAVING total_qty > 100` means
/// `HAVING SUM(qty) > 100`. Without this rewrite the bare `total_qty` reference
/// resolves to neither a table column nor a group key and silently becomes
/// NULL, dropping every row. We deliberately keep table columns taking
/// precedence over aliases to match SQLite's binding order.
fn rewrite_having_select_aliases(
    expr: &Expr,
    columns: &[ResultColumn],
    table: &TableSchema,
) -> Expr {
    rewrite_having_select_aliases_inner(expr, columns, table, &mut Vec::new())
}

fn rewrite_having_select_aliases_inner(
    expr: &Expr,
    columns: &[ResultColumn],
    table: &TableSchema,
    active_aliases: &mut Vec<String>,
) -> Expr {
    match expr {
        Expr::Column(col_ref, _) if col_ref.table.is_none() => {
            let name = col_ref.column.as_ref();
            // A real table column always wins over a SELECT alias.
            if table.column_index(name).is_some() || table.resolves_to_hidden_rowid(name) {
                return expr.clone();
            }
            // Find a SELECT-list column whose alias matches (case-insensitive,
            // like SQLite identifier matching).
            for col in columns {
                if let ResultColumn::Expr {
                    expr: select_expr,
                    alias: Some(alias),
                } = col
                    && alias.eq_ignore_ascii_case(name)
                {
                    if active_aliases
                        .iter()
                        .any(|active| active.eq_ignore_ascii_case(alias))
                    {
                        return expr.clone();
                    }
                    // Substitute the underlying SELECT expression, then keep
                    // walking it for further nested aliases.
                    active_aliases.push(alias.clone());
                    let rewritten = rewrite_having_select_aliases_inner(
                        select_expr,
                        columns,
                        table,
                        active_aliases,
                    );
                    active_aliases.pop();
                    return rewritten;
                }
            }
            expr.clone()
        }
        Expr::BinaryOp {
            left,
            op,
            right,
            span,
        } => Expr::BinaryOp {
            left: Box::new(rewrite_having_select_aliases_inner(
                left,
                columns,
                table,
                active_aliases,
            )),
            op: *op,
            right: Box::new(rewrite_having_select_aliases_inner(
                right,
                columns,
                table,
                active_aliases,
            )),
            span: *span,
        },
        Expr::UnaryOp { op, expr, span } => Expr::UnaryOp {
            op: *op,
            expr: Box::new(rewrite_having_select_aliases_inner(
                expr,
                columns,
                table,
                active_aliases,
            )),
            span: *span,
        },
        Expr::Between {
            expr,
            low,
            high,
            not,
            span,
        } => Expr::Between {
            expr: Box::new(rewrite_having_select_aliases_inner(
                expr,
                columns,
                table,
                active_aliases,
            )),
            low: Box::new(rewrite_having_select_aliases_inner(
                low,
                columns,
                table,
                active_aliases,
            )),
            high: Box::new(rewrite_having_select_aliases_inner(
                high,
                columns,
                table,
                active_aliases,
            )),
            not: *not,
            span: *span,
        },
        Expr::In {
            expr,
            set,
            not,
            span,
        } => Expr::In {
            expr: Box::new(rewrite_having_select_aliases_inner(
                expr,
                columns,
                table,
                active_aliases,
            )),
            set: rewrite_having_in_set_aliases(set, columns, table, active_aliases),
            not: *not,
            span: *span,
        },
        Expr::Like {
            expr,
            pattern,
            escape,
            op,
            not,
            span,
        } => Expr::Like {
            expr: Box::new(rewrite_having_select_aliases_inner(
                expr,
                columns,
                table,
                active_aliases,
            )),
            pattern: Box::new(rewrite_having_select_aliases_inner(
                pattern,
                columns,
                table,
                active_aliases,
            )),
            escape: escape.as_ref().map(|escape| {
                Box::new(rewrite_having_select_aliases_inner(
                    escape,
                    columns,
                    table,
                    active_aliases,
                ))
            }),
            op: *op,
            not: *not,
            span: *span,
        },
        Expr::IsNull { expr, not, span } => Expr::IsNull {
            expr: Box::new(rewrite_having_select_aliases_inner(
                expr,
                columns,
                table,
                active_aliases,
            )),
            not: *not,
            span: *span,
        },
        Expr::Collate {
            expr,
            collation,
            span,
        } => Expr::Collate {
            expr: Box::new(rewrite_having_select_aliases_inner(
                expr,
                columns,
                table,
                active_aliases,
            )),
            collation: collation.clone(),
            span: *span,
        },
        Expr::Cast {
            expr,
            type_name,
            span,
        } => Expr::Cast {
            expr: Box::new(rewrite_having_select_aliases_inner(
                expr,
                columns,
                table,
                active_aliases,
            )),
            type_name: type_name.clone(),
            span: *span,
        },
        Expr::Case {
            operand,
            whens,
            else_expr,
            span,
        } => Expr::Case {
            operand: operand.as_ref().map(|o| {
                Box::new(rewrite_having_select_aliases_inner(
                    o,
                    columns,
                    table,
                    active_aliases,
                ))
            }),
            whens: whens
                .iter()
                .map(|(w, t)| {
                    (
                        rewrite_having_select_aliases_inner(w, columns, table, active_aliases),
                        rewrite_having_select_aliases_inner(t, columns, table, active_aliases),
                    )
                })
                .collect(),
            else_expr: else_expr.as_ref().map(|e| {
                Box::new(rewrite_having_select_aliases_inner(
                    e,
                    columns,
                    table,
                    active_aliases,
                ))
            }),
            span: *span,
        },
        Expr::FunctionCall {
            name,
            args,
            distinct,
            order_by,
            filter,
            over,
            span,
        } if !is_aggregate_function_call(name, args) => Expr::FunctionCall {
            name: name.clone(),
            args: rewrite_having_function_args_aliases(args, columns, table, active_aliases),
            distinct: *distinct,
            order_by: rewrite_having_ordering_aliases(order_by, columns, table, active_aliases),
            filter: filter.as_ref().map(|filter| {
                Box::new(rewrite_having_select_aliases_inner(
                    filter,
                    columns,
                    table,
                    active_aliases,
                ))
            }),
            over: over.clone(),
            span: *span,
        },
        Expr::JsonAccess {
            expr,
            path,
            arrow,
            span,
        } => Expr::JsonAccess {
            expr: Box::new(rewrite_having_select_aliases_inner(
                expr,
                columns,
                table,
                active_aliases,
            )),
            path: Box::new(rewrite_having_select_aliases_inner(
                path,
                columns,
                table,
                active_aliases,
            )),
            arrow: *arrow,
            span: *span,
        },
        Expr::RowValue(values, span) => Expr::RowValue(
            values
                .iter()
                .map(|value| {
                    rewrite_having_select_aliases_inner(value, columns, table, active_aliases)
                })
                .collect(),
            *span,
        ),
        // Do not rewrite inside aggregate calls or subqueries. Aggregate
        // arguments and FILTER predicates bind within the aggregate's input-row
        // scope, and subqueries own their own SELECT-list alias scope.
        _ => expr.clone(),
    }
}

fn rewrite_having_in_set_aliases(
    set: &InSet,
    columns: &[ResultColumn],
    table: &TableSchema,
    active_aliases: &mut Vec<String>,
) -> InSet {
    match set {
        InSet::List(values) => InSet::List(
            values
                .iter()
                .map(|value| {
                    rewrite_having_select_aliases_inner(value, columns, table, active_aliases)
                })
                .collect(),
        ),
        InSet::Subquery(_) | InSet::Table(_) => set.clone(),
    }
}

fn rewrite_having_function_args_aliases(
    args: &FunctionArgs,
    columns: &[ResultColumn],
    table: &TableSchema,
    active_aliases: &mut Vec<String>,
) -> FunctionArgs {
    match args {
        FunctionArgs::Star => FunctionArgs::Star,
        FunctionArgs::List(args) => FunctionArgs::List(
            args.iter()
                .map(|arg| rewrite_having_select_aliases_inner(arg, columns, table, active_aliases))
                .collect(),
        ),
    }
}

fn rewrite_having_ordering_aliases(
    terms: &[OrderingTerm],
    columns: &[ResultColumn],
    table: &TableSchema,
    active_aliases: &mut Vec<String>,
) -> Vec<OrderingTerm> {
    terms
        .iter()
        .map(|term| OrderingTerm {
            expr: rewrite_having_select_aliases_inner(&term.expr, columns, table, active_aliases),
            direction: term.direction,
            nulls: term.nulls,
        })
        .collect()
}

/// Walk a HAVING expression to find aggregate function calls and add any that
/// are not already present in `agg_columns` / `output_cols`.  This ensures that
/// aggregates referenced only in HAVING (not in the SELECT list) still get
/// accumulator slots and `AggStep`/`AggFinal` instructions.
fn collect_having_aggregates(
    expr: &Expr,
    table: &TableSchema,
    agg_columns: &mut Vec<AggColumn>,
    output_cols: &mut Vec<GroupByOutputCol>,
) {
    match expr {
        Expr::FunctionCall {
            name,
            args,
            distinct,
            filter,
            ..
        } if is_aggregate_function_call(name, args) => {
            let upper = name.to_ascii_uppercase();
            // Check if this aggregate already exists in agg_columns.
            let already_exists = agg_columns.iter().any(|agg| {
                if agg.name != upper || agg.distinct != *distinct {
                    return false;
                }
                match args {
                    FunctionArgs::Star => agg.num_args == 0,
                    FunctionArgs::List(exprs) => {
                        if exprs.is_empty() {
                            return agg.num_args == 0;
                        }
                        if let Some(ci) = resolve_column_index(&exprs[0], table) {
                            agg.arg_col_index == Some(ci)
                        } else if let Some(ref arg_expr) = agg.arg_expr {
                            exprs.len() == 1 && **arg_expr == exprs[0]
                        } else {
                            false
                        }
                    }
                }
            });
            if !already_exists {
                let agg_index = agg_columns.len();
                let filt = filter.clone();
                match args {
                    FunctionArgs::Star => {
                        agg_columns.push(AggColumn {
                            name: upper.clone(),
                            num_args: 0,
                            arg_col_index: None,
                            arg_is_rowid: false,
                            distinct: *distinct,
                            arg_expr: None,
                            extra_args: Vec::new(),
                            filter: filt,
                            wrapper_expr: None,
                            hidden: false,
                            multi_agg_indices: Vec::new(),
                            bare_expr: None,
                            collation: None,
                        });
                    }
                    FunctionArgs::List(exprs) => {
                        if exprs.is_empty() {
                            agg_columns.push(AggColumn {
                                name: upper.clone(),
                                num_args: 0,
                                arg_col_index: None,
                                arg_is_rowid: false,
                                distinct: *distinct,
                                arg_expr: None,
                                extra_args: Vec::new(),
                                filter: filt,
                                wrapper_expr: None,
                                hidden: false,
                                multi_agg_indices: Vec::new(),
                                bare_expr: None,
                                collation: None,
                            });
                        } else {
                            let (col_idx, is_rowid, arg_e) =
                                match resolve_column_ref(&exprs[0], table, None) {
                                    Some(SortKeySource::Column(idx)) => (Some(idx), false, None),
                                    Some(SortKeySource::Rowid) => (None, true, None),
                                    _ => (None, false, Some(Box::new(exprs[0].clone()))),
                                };
                            let extra: Vec<Expr> = exprs[1..].to_vec();
                            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                            agg_columns.push(AggColumn {
                                name: upper,
                                num_args: exprs.len() as i32,
                                arg_col_index: col_idx,
                                arg_is_rowid: is_rowid,
                                distinct: *distinct,
                                arg_expr: arg_e,
                                extra_args: extra,
                                filter: filt,
                                wrapper_expr: None,
                                hidden: false,
                                multi_agg_indices: Vec::new(),
                                bare_expr: None,
                                collation: None,
                            });
                        }
                    }
                }
                output_cols.push(GroupByOutputCol::Aggregate { agg_index });
            }
        }
        // Recurse into sub-expressions to find nested aggregates.
        Expr::BinaryOp { left, right, .. } => {
            collect_having_aggregates(left, table, agg_columns, output_cols);
            collect_having_aggregates(right, table, agg_columns, output_cols);
        }
        Expr::UnaryOp { expr: inner, .. }
        | Expr::IsNull { expr: inner, .. }
        | Expr::Collate { expr: inner, .. }
        | Expr::Cast { expr: inner, .. } => {
            collect_having_aggregates(inner, table, agg_columns, output_cols);
        }
        Expr::Between {
            expr: inner,
            low,
            high,
            ..
        } => {
            collect_having_aggregates(inner, table, agg_columns, output_cols);
            collect_having_aggregates(low, table, agg_columns, output_cols);
            collect_having_aggregates(high, table, agg_columns, output_cols);
        }
        Expr::In {
            expr: inner, set, ..
        } => {
            collect_having_aggregates(inner, table, agg_columns, output_cols);
            if let InSet::List(values) = set {
                for value in values {
                    collect_having_aggregates(value, table, agg_columns, output_cols);
                }
            }
        }
        Expr::Like {
            expr: inner,
            pattern,
            escape,
            ..
        } => {
            collect_having_aggregates(inner, table, agg_columns, output_cols);
            collect_having_aggregates(pattern, table, agg_columns, output_cols);
            if let Some(escape) = escape {
                collect_having_aggregates(escape, table, agg_columns, output_cols);
            }
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            if let Some(operand) = operand {
                collect_having_aggregates(operand, table, agg_columns, output_cols);
            }
            for (when_expr, then_expr) in whens {
                collect_having_aggregates(when_expr, table, agg_columns, output_cols);
                collect_having_aggregates(then_expr, table, agg_columns, output_cols);
            }
            if let Some(else_expr) = else_expr {
                collect_having_aggregates(else_expr, table, agg_columns, output_cols);
            }
        }
        Expr::FunctionCall {
            args,
            filter,
            order_by,
            ..
        } => {
            if let FunctionArgs::List(args) = args {
                for arg in args {
                    collect_having_aggregates(arg, table, agg_columns, output_cols);
                }
            }
            if let Some(filter) = filter {
                collect_having_aggregates(filter, table, agg_columns, output_cols);
            }
            for term in order_by {
                collect_having_aggregates(&term.expr, table, agg_columns, output_cols);
            }
        }
        Expr::JsonAccess {
            expr: inner, path, ..
        } => {
            collect_having_aggregates(inner, table, agg_columns, output_cols);
            collect_having_aggregates(path, table, agg_columns, output_cols);
        }
        Expr::RowValue(values, _) => {
            for value in values {
                collect_having_aggregates(value, table, agg_columns, output_cols);
            }
        }
        _ => {}
    }
}

/// GH #225: append every bare table column referenced by a HAVING clause OUTSIDE
/// any aggregate as a HIDDEN `bare_expr` aggregate, so the implicit-aggregate
/// scan captures the FIRST scanned row's value for it (matching stock sqlite3's
/// bare-column-in-HAVING semantics). `emit_having_expr` then resolves the column
/// to this aggregate's accumulator instead of falling back to NULL. Columns
/// already covered by a `bare_expr` aggregate (e.g. also in the SELECT list) are
/// not duplicated. Aggregate arguments are intentionally NOT descended into —
/// those belong to the aggregate, not a bare column.
fn collect_having_bare_columns(expr: &Expr, table: &TableSchema, agg_columns: &mut Vec<AggColumn>) {
    match expr {
        // A column referenced directly in HAVING: capture it (first row).
        Expr::Column(_, _) => {
            let Some(ci) = resolve_column_index(expr, table) else {
                return;
            };
            let already = agg_columns.iter().any(|agg| {
                agg.bare_expr
                    .as_deref()
                    .and_then(|be| resolve_column_index(be, table))
                    == Some(ci)
            });
            if !already {
                agg_columns.push(AggColumn {
                    name: String::new(),
                    num_args: 0,
                    arg_col_index: None,
                    arg_is_rowid: false,
                    distinct: false,
                    arg_expr: None,
                    extra_args: Vec::new(),
                    filter: None,
                    wrapper_expr: None,
                    hidden: true,
                    multi_agg_indices: Vec::new(),
                    bare_expr: Some(Box::new(expr.clone())),
                    collation: None,
                });
            }
        }
        // Do not descend into an aggregate's own arguments.
        Expr::FunctionCall { name, args, .. } if is_aggregate_function_call(name, args) => {}
        Expr::BinaryOp { left, right, .. } => {
            collect_having_bare_columns(left, table, agg_columns);
            collect_having_bare_columns(right, table, agg_columns);
        }
        Expr::UnaryOp { expr: inner, .. }
        | Expr::IsNull { expr: inner, .. }
        | Expr::Collate { expr: inner, .. }
        | Expr::Cast { expr: inner, .. }
        | Expr::In { expr: inner, .. } => {
            collect_having_bare_columns(inner, table, agg_columns);
        }
        Expr::Between {
            expr: inner,
            low,
            high,
            ..
        } => {
            collect_having_bare_columns(inner, table, agg_columns);
            collect_having_bare_columns(low, table, agg_columns);
            collect_having_bare_columns(high, table, agg_columns);
        }
        Expr::Like {
            expr: inner,
            pattern,
            escape,
            ..
        } => {
            collect_having_bare_columns(inner, table, agg_columns);
            collect_having_bare_columns(pattern, table, agg_columns);
            if let Some(escape) = escape.as_deref() {
                collect_having_bare_columns(escape, table, agg_columns);
            }
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            if let Some(operand) = operand.as_deref() {
                collect_having_bare_columns(operand, table, agg_columns);
            }
            for (when_expr, then_expr) in whens {
                collect_having_bare_columns(when_expr, table, agg_columns);
                collect_having_bare_columns(then_expr, table, agg_columns);
            }
            if let Some(else_expr) = else_expr.as_deref() {
                collect_having_bare_columns(else_expr, table, agg_columns);
            }
        }
        // Non-aggregate function calls may carry bare columns in their arguments.
        Expr::FunctionCall {
            args: FunctionArgs::List(list),
            ..
        } => {
            for arg in list {
                collect_having_bare_columns(arg, table, agg_columns);
            }
        }
        _ => {}
    }
}

/// Generate VDBE bytecode for an aggregate SELECT **with GROUP BY**.
///
/// Two-pass pattern:
/// 1. Scan table rows (with WHERE), pack group-key + agg-arg columns into sorter.
/// 2. After sorting, iterate sorted rows detecting group boundaries via key
///    comparison. On each boundary, finalize accumulators and emit `ResultRow`.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn codegen_select_group_by_aggregate(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    group_by: &[Expr],
    having: Option<&Expr>,
    limit_clause: Option<&LimitClause>,
    out_regs: i32,
    out_col_count: i32,
    done_label: crate::Label,
    end_label: crate::Label,
) -> Result<(), CodegenError> {
    // Resolve SELECT-list aliases referenced from HAVING (e.g.
    // `SELECT product_id, SUM(qty) AS total_qty ... HAVING total_qty >= 10`).
    let rewritten_having = having.map(|h| rewrite_having_select_aliases(h, columns, table));
    let having = rewritten_having.as_ref();

    if where_clause.is_none()
        && having.is_none()
        && limit_clause.is_none()
        && let Some(plan) =
            simple_group_by_rowid_bucket_sum_plan(columns, table, table_alias, group_by)
    {
        return codegen_select_group_by_rowid_bucket_sum(
            b, cursor, table, &plan, out_regs, done_label, end_label,
        );
    }

    let (mut output_cols, group_by_keys, mut agg_columns) =
        parse_group_by_output(columns, table, group_by)?;

    // Collect aggregates from the HAVING clause that are not in the SELECT list.
    if let Some(having_expr) = having {
        collect_having_aggregates(having_expr, table, &mut agg_columns, &mut output_cols);
    }

    let (limit_reg, offset_reg) = emit_limit_offset_registers(b, limit_clause, done_label);

    let num_group_keys = group_by_keys.len();
    let num_aggs = agg_columns.len();

    // Collect unique table-column indices needed for aggregate arguments.
    let mut agg_arg_table_cols: Vec<usize> = Vec::new();
    for agg in &agg_columns {
        if let Some(ci) = agg.arg_col_index
            && !agg_arg_table_cols.contains(&ci)
        {
            agg_arg_table_cols.push(ci);
        }
    }

    // Count expression-arg aggregates (each gets its own sorter slot).
    let num_expr_args = agg_columns.iter().filter(|a| a.arg_expr.is_some()).count();

    // Rowid-argument aggregates (e.g. SUM(rowid)) need one shared sorter slot.
    let needs_rowid = agg_columns.iter().any(|a| a.arg_is_rowid);
    let num_rowid_slots: usize = usize::from(needs_rowid);

    // Count aggregates with FILTER clauses (each gets a boolean sorter slot).
    let num_filter_cols = agg_columns.iter().filter(|a| a.filter.is_some()).count();

    // Count non-grouped columns (from SELECT * expansion) and assign sorter slots.
    let num_nongrouped = output_cols
        .iter()
        .filter(|c| matches!(c, GroupByOutputCol::NonGroupedColumn { .. }))
        .count();
    let nongrouped_start = num_group_keys
        + agg_arg_table_cols.len()
        + num_expr_args
        + num_rowid_slots
        + num_filter_cols;
    let mut next_nongrouped_slot = nongrouped_start;
    for col in &mut output_cols {
        if let GroupByOutputCol::NonGroupedColumn { sorter_col, .. } = col {
            *sorter_col = next_nongrouped_slot;
            next_nongrouped_slot += 1;
        }
    }

    // Sorter layout: [group_keys..., col_args..., expr_args..., rowid_slot?, filter_bools..., nongrouped_cols...]
    let total_sorter_cols = num_group_keys
        + agg_arg_table_cols.len()
        + num_expr_args
        + num_rowid_slots
        + num_filter_cols
        + num_nongrouped;

    // Map each aggregate's arg to its sorter column index.
    let mut agg_sorter_col: Vec<Option<usize>> = Vec::with_capacity(agg_columns.len());
    let mut next_expr_slot = num_group_keys + agg_arg_table_cols.len();
    let rowid_slot = num_group_keys + agg_arg_table_cols.len() + num_expr_args;
    for agg in &agg_columns {
        let sorter_col = if agg.arg_expr.is_some() {
            let slot = next_expr_slot;
            next_expr_slot += 1;
            Some(slot)
        } else if agg.arg_is_rowid {
            Some(rowid_slot)
        } else if let Some(ci) = agg.arg_col_index {
            let Some(pos) = agg_arg_table_cols.iter().position(|&x| x == ci) else {
                return Err(CodegenError::Unsupported(
                    "internal: aggregate argument column missing from sorter layout".to_owned(),
                ));
            };
            Some(num_group_keys + pos)
        } else {
            None
        };
        agg_sorter_col.push(sorter_col);
    }

    // Map each FILTER-bearing aggregate to its boolean sorter column.
    let mut filter_sorter_col: Vec<Option<usize>> = Vec::with_capacity(agg_columns.len());
    let mut next_filter_slot =
        num_group_keys + agg_arg_table_cols.len() + num_expr_args + num_rowid_slots;
    for agg in &agg_columns {
        if agg.filter.is_some() {
            filter_sorter_col.push(Some(next_filter_slot));
            next_filter_slot += 1;
        } else {
            filter_sorter_col.push(None);
        }
    }

    // Sorter cursor.
    let sorter_cursor = cursor + 1;

    // Open sorter: p2 = number of key columns (for sorting by group keys).
    let sort_order: String = std::iter::repeat_n('+', num_group_keys).collect();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::SorterOpen,
        sorter_cursor,
        num_group_keys as i32,
        0,
        P4::Str(sort_order),
        0,
    );

    // Open table for reading.
    b.emit_op(
        Opcode::OpenRead,
        cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );

    // === Pass 1: Scan rows into sorter ===
    let scan_start = b.current_addr();
    let scan_done = b.emit_label();
    b.emit_jump_to_label(Opcode::Rewind, cursor, 0, scan_done, P4::None, 0);

    // WHERE filter.
    let skip_label = b.emit_label();
    if let Some(where_expr) = where_clause {
        emit_where_filter(
            b,
            where_expr,
            cursor,
            table,
            table_alias,
            schema,
            skip_label,
        );
    }

    // Read group-key values + agg-arg columns into consecutive registers.
    // For column-based keys, use Opcode::Column; for expression-based keys,
    // evaluate the expression via emit_expr.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let sorter_base = b.alloc_regs(total_sorter_cols as i32);
    {
        let scan_ctx = ScanCtx {
            cursor,
            table,
            table_alias,
            schema: Some(schema),
            register_base: None,
            secondaries: &[],
        };
        let mut reg = sorter_base;
        for key in &group_by_keys {
            match key {
                GroupByKey::Column(col_idx) => {
                    // bd-hx3zu (GH#227 sibling): a VIRTUAL generated column is not
                    // materialized in the record — reading it raw here grouped on
                    // the NULL placeholder. Route it through the canonical reader
                    // so the generating expression is computed on read, exactly
                    // as single-table projection / emit_join_expr do.
                    if virtual_generated_column_expr(&table.columns[*col_idx]).is_some() {
                        emit_table_column_read(
                            b,
                            cursor,
                            table,
                            table_alias,
                            Some(schema),
                            *col_idx,
                            reg,
                        );
                    } else {
                        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                        b.emit_op(Opcode::Column, cursor, *col_idx as i32, reg, P4::None, 0);
                    }
                }
                GroupByKey::Expression(expr) => {
                    emit_expr(b, expr, reg, Some(&scan_ctx));
                }
            }
            reg += 1;
        }
        for &col_idx in &agg_arg_table_cols {
            // bd-hx3zu (GH#227 sibling): compute a VIRTUAL generated column used
            // as an aggregate argument instead of reading its NULL placeholder.
            if virtual_generated_column_expr(&table.columns[col_idx]).is_some() {
                emit_table_column_read(b, cursor, table, table_alias, Some(schema), col_idx, reg);
            } else {
                #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                b.emit_op(Opcode::Column, cursor, col_idx as i32, reg, P4::None, 0);
            }
            reg += 1;
        }
        // Expression-arg aggregates: evaluate each expression into its sorter slot.
        for agg in &agg_columns {
            if let Some(ref expr) = agg.arg_expr {
                emit_expr(b, expr, reg, Some(&scan_ctx));
                reg += 1;
            }
        }
        // Rowid slot: store rowid if any aggregate references it (e.g. SUM(rowid)).
        if needs_rowid {
            b.emit_op(Opcode::Rowid, cursor, reg, 0, P4::None, 0);
            reg += 1;
        }
        // FILTER clause booleans: evaluate each filter and store 0/1 in sorter.
        for agg in &agg_columns {
            if let Some(ref filter_expr) = agg.filter {
                emit_expr(b, filter_expr, reg, Some(&scan_ctx));
                reg += 1;
            }
        }

        // Non-grouped columns (from SELECT * expansion): store in sorter.
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        for col in &output_cols {
            if let GroupByOutputCol::NonGroupedColumn {
                table_col_index,
                is_ipk,
                ..
            } = col
            {
                if *is_ipk {
                    b.emit_op(Opcode::Rowid, cursor, reg, 0, P4::None, 0);
                } else {
                    b.emit_op(
                        Opcode::Column,
                        cursor,
                        *table_col_index as i32,
                        reg,
                        P4::None,
                        0,
                    );
                }
                reg += 1;
            }
        }
    }

    // MakeRecord + SorterInsert.
    let record_reg = b.alloc_reg();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::MakeRecord,
        sorter_base,
        total_sorter_cols as i32,
        record_reg,
        P4::None,
        0,
    );
    b.emit_op(
        Opcode::SorterInsert,
        sorter_cursor,
        record_reg,
        0,
        P4::None,
        0,
    );

    // Skip label (for WHERE-filtered rows).
    b.resolve_label(skip_label);

    // Next row in scan.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let scan_body = (scan_start + 1) as i32;
    b.emit_op(Opcode::Next, cursor, scan_body, 0, P4::None, 0);

    // End of pass 1.
    b.resolve_label(scan_done);
    b.emit_op(Opcode::Close, cursor, 0, 0, P4::None, 0);

    // === Pass 2: Iterate sorted rows, accumulate per-group ===

    // Allocate registers for current group keys, previous group keys, accumulators,
    // and non-grouped column values.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let cur_key_base = b.alloc_regs(num_group_keys as i32);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let prev_key_base = b.alloc_regs(num_group_keys as i32);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let accum_base = b.alloc_regs(num_aggs as i32);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let prev_nongrouped_base = b.alloc_regs(num_nongrouped.max(1) as i32);
    let first_flag = b.alloc_reg();

    // Initialize: first_flag = 1, accumulators = Null.
    b.emit_op(Opcode::Integer, 1, first_flag, 0, P4::None, 0);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for i in 0..num_aggs as i32 {
        b.emit_op(Opcode::Null, 0, accum_base + i, 0, P4::None, 0);
    }

    // SorterSort: sort and position at first row; jump to done if empty.
    b.emit_jump_to_label(
        Opcode::SorterSort,
        sorter_cursor,
        0,
        done_label,
        P4::None,
        0,
    );

    let sort_loop_body = b.current_addr();

    // SorterData: decode current sorted row.
    let sorted_reg = b.alloc_reg();
    b.emit_op(
        Opcode::SorterData,
        sorter_cursor,
        sorted_reg,
        0,
        P4::None,
        0,
    );

    // Read group-key columns from sorter into cur_key registers.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for i in 0..num_group_keys {
        b.emit_op(
            Opcode::Column,
            sorter_cursor,
            i as i32,
            cur_key_base + i as i32,
            P4::None,
            0,
        );
    }

    // If first row, skip group-change comparison.
    let first_row_label = b.emit_label();
    b.emit_jump_to_label(Opcode::IfPos, first_flag, 1, first_row_label, P4::None, 0);

    // Compare current keys to previous keys. If any differ, jump to new_group.
    let new_group_label = b.emit_label();
    let same_group_label = b.emit_label();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for i in 0..num_group_keys {
        // Ne p1=cur_key, p2=new_group_label, p3=prev_key, p5=0x80 (NULLEQ)
        b.emit_jump_to_label(
            Opcode::Ne,
            cur_key_base + i as i32,
            prev_key_base + i as i32,
            new_group_label,
            P4::None,
            0x80,
        );
    }
    // All keys match — same group.
    b.emit_jump_to_label(Opcode::Goto, 0, 0, same_group_label, P4::None, 0);

    // new_group: finalize previous group and output ResultRow.
    b.resolve_label(new_group_label);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for (i, agg) in agg_columns.iter().enumerate() {
        let accum_reg = accum_base + i as i32;
        b.emit_op(
            Opcode::AggFinal,
            accum_reg,
            agg.num_args,
            0,
            P4::FuncName(agg.name.clone()),
            0,
        );
    }
    // Build output row from prev_key + accum + prev_nongrouped.
    // Only iterate the SELECT output columns (first out_col_count entries);
    // HAVING-only aggregates appended by collect_having_aggregates are
    // accumulated and used by emit_having_filter, but NOT included in the
    // output row.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    {
        let mut ng_idx = 0i32;
        for (i, out_col) in output_cols.iter().take(out_col_count as usize).enumerate() {
            match out_col {
                GroupByOutputCol::GroupKey { sorter_col, .. } => {
                    b.emit_op(
                        Opcode::Copy,
                        prev_key_base + *sorter_col as i32,
                        out_regs + i as i32,
                        0,
                        P4::None,
                        0,
                    );
                }
                GroupByOutputCol::Aggregate { agg_index } => {
                    b.emit_op(
                        Opcode::Copy,
                        accum_base + *agg_index as i32,
                        out_regs + i as i32,
                        0,
                        P4::None,
                        0,
                    );
                }
                GroupByOutputCol::NonGroupedColumn { .. } => {
                    b.emit_op(
                        Opcode::Copy,
                        prev_nongrouped_base + ng_idx,
                        out_regs + i as i32,
                        0,
                        P4::None,
                        0,
                    );
                    ng_idx += 1;
                }
            }
        }
    }
    // HAVING filter: skip this group's output if HAVING predicate is false.
    let having_skip_label = b.emit_label();
    if let Some(having_expr) = having {
        emit_having_filter(
            b,
            having_expr,
            &output_cols,
            &agg_columns,
            &group_by_keys,
            table,
            out_regs,
            having_skip_label,
        );
    }
    // OFFSET: if offset counter > 0, skip this group's output.
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, having_skip_label, P4::None, 0);
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    // LIMIT: decrement limit counter; jump to done when exhausted.
    if let Some(lim_r) = limit_reg {
        b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, done_label, P4::None, 0);
    }
    b.resolve_label(having_skip_label);
    // Reset accumulators for next group.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for i in 0..num_aggs as i32 {
        b.emit_op(Opcode::Null, 0, accum_base + i, 0, P4::None, 0);
    }

    // first_row: (jumped here when first_flag was 1, skipping comparison).
    b.resolve_label(first_row_label);

    // same_group: copy current keys to previous, then AggStep.
    b.resolve_label(same_group_label);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for i in 0..num_group_keys {
        b.emit_op(
            Opcode::Copy,
            cur_key_base + i as i32,
            prev_key_base + i as i32,
            0,
            P4::None,
            0,
        );
    }

    // Copy non-grouped columns from sorter to prev_nongrouped registers.
    // These hold the latest (arbitrary) value for each non-grouped column.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    {
        let mut ng_idx = 0i32;
        for col in &output_cols {
            if let GroupByOutputCol::NonGroupedColumn { sorter_col, .. } = col {
                b.emit_op(
                    Opcode::Column,
                    sorter_cursor,
                    *sorter_col as i32,
                    prev_nongrouped_base + ng_idx,
                    P4::None,
                    0,
                );
                ng_idx += 1;
            }
        }
    }

    // AggStep for each aggregate.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for (i, agg) in agg_columns.iter().enumerate() {
        let accum_reg = accum_base + i as i32;

        // FILTER clause: read boolean from sorter and skip AggStep if false/NULL.
        let filter_skip_label = if let Some(filt_col) = filter_sorter_col[i] {
            let skip_lbl = b.emit_label();
            let filt_reg = b.alloc_temp();
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            b.emit_op(
                Opcode::Column,
                sorter_cursor,
                filt_col as i32,
                filt_reg,
                P4::None,
                0,
            );
            // p3=1: treat NULL as false (skip AggStep).
            b.emit_jump_to_label(Opcode::IfNot, filt_reg, 1, skip_lbl, P4::None, 0);
            b.free_temp(filt_reg);
            Some(skip_lbl)
        } else {
            None
        };

        let distinct_flag = i32::from(agg.distinct);
        if agg.num_args == 0 {
            // count(*): no arguments.
            b.emit_op(
                Opcode::AggStep,
                distinct_flag,
                0,
                accum_reg,
                agg_func_p4(&agg.name, agg.collation.as_ref()),
                0,
            );
        } else {
            let total_args = agg.num_args.max(1);
            let arg_base = b.alloc_regs(total_args);
            let Some(sorter_col) = agg_sorter_col[i] else {
                return Err(CodegenError::Unsupported(
                    "internal: non-zero-arg aggregate missing sorter column".to_owned(),
                ));
            };
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            b.emit_op(
                Opcode::Column,
                sorter_cursor,
                sorter_col as i32,
                arg_base,
                P4::None,
                0,
            );
            // Extra arguments (e.g. separator for group_concat):
            // re-evaluate inline since they are typically constant expressions.
            for (j, extra_expr) in agg.extra_args.iter().enumerate() {
                #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                let extra_reg = arg_base + 1 + j as i32;
                emit_expr(b, extra_expr, extra_reg, None);
            }
            let step_p5 = u16::try_from(agg.num_args).unwrap_or_default();
            // bd-lgwjd(a): thread the aggregate's declared collation into the
            // GROUP BY substrate AggStep (a direct `max(name)` under GROUP BY was
            // emitted BINARY here, ignoring `agg.collation`). `agg_func_p4` yields
            // a plain FuncName when no collation is present, so non-collated
            // aggregates are unchanged.
            b.emit_op(
                Opcode::AggStep,
                distinct_flag,
                arg_base,
                accum_reg,
                agg_func_p4(&agg.name, agg.collation.as_ref()),
                step_p5,
            );
        }

        // Resolve FILTER skip label after AggStep.
        if let Some(skip_lbl) = filter_skip_label {
            b.resolve_label(skip_lbl);
        }
    }

    // SorterNext: advance to next sorted row.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::SorterNext,
        sorter_cursor,
        sort_loop_body as i32,
        0,
        P4::None,
        0,
    );

    // After loop: output final group (if any rows were processed).
    // If first_flag is still > 0, table was empty — skip final output.
    b.emit_jump_to_label(Opcode::IfPos, first_flag, 0, done_label, P4::None, 0);

    // Finalize last group.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    for (i, agg) in agg_columns.iter().enumerate() {
        let accum_reg = accum_base + i as i32;
        b.emit_op(
            Opcode::AggFinal,
            accum_reg,
            agg.num_args,
            0,
            P4::FuncName(agg.name.clone()),
            0,
        );
    }
    // Build output row from prev_key (last group's keys) + accum + prev_nongrouped.
    // Same as above: skip HAVING-only aggregate entries beyond out_col_count.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    {
        let mut ng_idx = 0i32;
        for (i, out_col) in output_cols.iter().take(out_col_count as usize).enumerate() {
            match out_col {
                GroupByOutputCol::GroupKey { sorter_col, .. } => {
                    b.emit_op(
                        Opcode::Copy,
                        prev_key_base + *sorter_col as i32,
                        out_regs + i as i32,
                        0,
                        P4::None,
                        0,
                    );
                }
                GroupByOutputCol::Aggregate { agg_index } => {
                    b.emit_op(
                        Opcode::Copy,
                        accum_base + *agg_index as i32,
                        out_regs + i as i32,
                        0,
                        P4::None,
                        0,
                    );
                }
                GroupByOutputCol::NonGroupedColumn { .. } => {
                    b.emit_op(
                        Opcode::Copy,
                        prev_nongrouped_base + ng_idx,
                        out_regs + i as i32,
                        0,
                        P4::None,
                        0,
                    );
                    ng_idx += 1;
                }
            }
        }
    }
    // HAVING filter for the final group.
    let final_skip = b.emit_label();
    if let Some(having_expr) = having {
        emit_having_filter(
            b,
            having_expr,
            &output_cols,
            &agg_columns,
            &group_by_keys,
            table,
            out_regs,
            final_skip,
        );
    }
    // OFFSET: if offset counter > 0, skip this group's output.
    if let Some(off_r) = offset_reg {
        b.emit_jump_to_label(Opcode::IfPos, off_r, 1, final_skip, P4::None, 0);
    }
    b.emit_op(Opcode::ResultRow, out_regs, out_col_count, 0, P4::None, 0);
    b.resolve_label(final_skip);

    // Done: Close sorter + Halt.
    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, sorter_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End target for Init jump.
    b.resolve_label(end_label);

    Ok(())
}

// ---------------------------------------------------------------------------
// INSERT codegen
// ---------------------------------------------------------------------------

/// Generate VDBE bytecode for an INSERT statement.
///
/// Pattern: `INSERT INTO t VALUES (?, ?, ...)`
///
/// Init → Transaction(write) → OpenWrite → Variable* → (IPK routing |
/// NewRowid) → MakeRecord → Insert → Close → Halt
#[allow(clippy::too_many_lines)]
pub fn codegen_insert(
    b: &mut ProgramBuilder,
    stmt: &InsertStatement,
    schema: &[TableSchema],
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    let table = find_table(schema, &stmt.table.name)?;
    if table.without_rowid {
        return codegen_insert_without_rowid(b, stmt, table, schema, ctx);
    }
    let target_alias = stmt.alias.as_deref();
    let table_cursor = 0_i32;

    let end_label = b.emit_label();

    // Init.
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);

    // Transaction (write, p2=1).
    b.emit_op(Opcode::Transaction, 0, 1, 0, P4::None, 0);

    // OpenWrite for table.
    b.emit_op(
        Opcode::OpenWrite,
        table_cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );

    // OpenWrite for each index (bd-so1h: Phase 5I.3).
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    for (idx_offset, index) in table.indexes.iter().enumerate() {
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        b.emit_op(
            Opcode::OpenWrite,
            idx_cursor,
            index.root_page,
            0,
            P4::Table(index.name.clone()),
            0,
        );
    }

    // Register table-to-index cursor metadata for REPLACE conflict resolution.
    // This allows the engine's native_replace_row to clean up secondary index
    // entries when a conflicting row is deleted.
    register_table_index_meta(b, table, table_cursor);

    // Conflict behavior. A statement-level `INSERT OR <algo>` (or the default
    // ABORT) governs BOTH the pre-insert NOT NULL/CHECK checks on the candidate
    // row and the no-conflict INSERT path's remaining (non-target) UNIQUE/PK
    // constraints. The per-constraint `ON CONFLICT` chain is routed row-by-row
    // in `codegen_insert_values`: each clause probes its own target in written
    // order and the first whose target conflicts is applied (DO UPDATE rewrites
    // the conflicting row; DO NOTHING skips the insert). A conflict on a
    // constraint that no clause targets falls through to `stmt_level`
    // (default ABORT), matching stock (multiple ON CONFLICT clauses, SQLite
    // 3.35+). Stock enforces candidate NOT NULL/CHECK even for a row that will
    // conflict, so these are NOT blanket-IGNORE'd (bd-aap9u).
    let oe_flag = conflict_action_to_oe(stmt.or_conflict.as_ref());
    let stmt_level: Option<ConflictAction> = stmt.or_conflict;
    // Validate every clause's conflict target + DO UPDATE assignment/WHERE
    // columns up front for error parity.
    for clause in &stmt.upsert {
        if let Some(target) = clause.target.as_ref()
            && find_upsert_target_index(table, Some(target)).is_none()
            && !upsert_target_matches_rowid_primary_key(table, target)
            && !upsert_target_matches_without_rowid_primary_key(table, target)
        {
            return Err(CodegenError::Unsupported(
                "ON CONFLICT clause does not match any PRIMARY KEY or UNIQUE constraint".to_owned(),
            ));
        }
        if let UpsertAction::Update {
            assignments,
            where_clause,
        } = &clause.action
        {
            for assign in assignments {
                validate_assignment_target(table, &assign.target)?;
                validate_upsert_expr_columns(&assign.value, table, target_alias)?;
            }
            if let Some(where_expr) = where_clause {
                validate_upsert_expr_columns(where_expr, table, target_alias)?;
            }
        }
    }

    match &stmt.source {
        InsertSource::Values(rows) => {
            if rows.is_empty() {
                return Err(CodegenError::Unsupported("empty VALUES".to_owned()));
            }
            let target_mapping = build_insert_target_mapping(&stmt.columns, table)?;
            if let Some(mapping) = target_mapping.as_ref() {
                codegen_insert_values(
                    b,
                    rows,
                    Some(mapping.expected_source_cols),
                    mapping.explicit_rowid_source_pos,
                    Some(&mapping.col_mapping),
                    table_cursor,
                    table,
                    schema,
                    &stmt.returning,
                    target_alias,
                    ctx,
                    oe_flag,
                    stmt_level,
                    &stmt.upsert,
                )?;
            } else {
                codegen_insert_values(
                    b,
                    rows,
                    None,
                    None,
                    None,
                    table_cursor,
                    table,
                    schema,
                    &stmt.returning,
                    target_alias,
                    ctx,
                    oe_flag,
                    stmt_level,
                    &stmt.upsert,
                )?;
            }
        }
        InsertSource::Select(select_stmt) => {
            let target_mapping = build_insert_target_mapping(&stmt.columns, table)?;

            let expected_cols = if let Some(mapping) = target_mapping.as_ref() {
                Some(mapping.expected_source_cols)
            } else {
                Some(table.columns.len())
            };

            codegen_insert_select(
                b,
                select_stmt,
                table_cursor,
                table,
                schema,
                &stmt.returning,
                target_alias,
                ctx,
                oe_flag,
                stmt_level,
                expected_cols,
                target_mapping
                    .as_ref()
                    .and_then(|mapping| mapping.explicit_rowid_source_pos),
                target_mapping
                    .as_ref()
                    .map(|mapping| mapping.col_mapping.as_slice()),
            )?;
        }
        InsertSource::DefaultValues => {
            // Insert one row using column DEFAULT values (or NULL if none).
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let n_cols = table.columns.len() as i32;
            let concurrent_flag = i32::from(ctx.concurrent_mode);
            let col_regs = b.alloc_regs(n_cols);
            for (idx, col) in table.columns.iter().enumerate() {
                #[allow(clippy::cast_possible_wrap)]
                let reg = col_regs + idx as i32;
                emit_default_value(b, col, reg)?;
            }
            let rowid_reg = b.alloc_reg();
            if let Some(ipk_idx) = ctx.rowid_alias_col_idx {
                // IPK column has a DEFAULT value — use it when non-NULL,
                // otherwise auto-generate via NewRowid (matching VALUES path).
                #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
                let ipk_reg = col_regs + ipk_idx as i32;
                let auto_label = b.emit_label();
                let done_label = b.emit_label();

                b.emit_jump_to_label(Opcode::IsNull, ipk_reg, 0, auto_label, P4::None, 0);
                b.emit_op(Opcode::Copy, ipk_reg, rowid_reg, 0, P4::None, 0);
                b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

                b.resolve_label(auto_label);
                b.emit_op(
                    Opcode::NewRowid,
                    table_cursor,
                    rowid_reg,
                    concurrent_flag,
                    P4::None,
                    0,
                );
                b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);

                b.resolve_label(done_label);
            } else {
                // No IPK column — always auto-generate.
                b.emit_op(
                    Opcode::NewRowid,
                    table_cursor,
                    rowid_reg,
                    concurrent_flag,
                    P4::None,
                    0,
                );
            }
            // Evaluate STORED generated columns before packing the record.
            emit_stored_generated_columns(b, table, col_regs);

            let rec_reg = b.alloc_reg();
            emit_strict_type_check(b, table, col_regs);
            // GH #169: coerce to column affinity before CHECK/NOT NULL so the
            // constraints see the affinity-coerced value (SQLite applies
            // affinity, then evaluates constraints).
            b.emit_op(
                Opcode::Affinity,
                col_regs,
                n_cols,
                0,
                P4::Affinity(table.affinity_string()),
                0,
            );
            emit_check_constraints(b, table, col_regs, None);
            emit_not_null_constraints(b, table, col_regs, stmt_level, None);
            let pk_oe = effective_oe(
                stmt_level,
                table
                    .columns
                    .iter()
                    .find(|c| c.is_ipk)
                    .and_then(|c| c.conflict_action),
            );
            // Apply column type affinities before packing the record.
            let aff_str = table.affinity_string();
            b.emit_op(
                Opcode::Affinity,
                col_regs,
                n_cols,
                0,
                P4::Affinity(aff_str.clone()),
                0,
            );
            b.emit_op(
                Opcode::MakeRecord,
                col_regs,
                n_cols,
                rec_reg,
                make_insert_record_p4(table, &aff_str),
                0,
            );
            b.emit_op(
                Opcode::Insert,
                table_cursor,
                rec_reg,
                rowid_reg,
                P4::Table(table.name.clone()),
                pk_oe,
            );

            // Index maintenance: insert into each index (bd-so1h).
            emit_index_inserts(b, table, table_cursor, col_regs, rowid_reg, stmt_level);

            if !stmt.returning.is_empty() {
                emit_returning(
                    b,
                    table_cursor,
                    table,
                    &stmt.returning,
                    target_alias,
                    rowid_reg,
                )?;
            }
        }
    }

    // Close table cursor.
    b.emit_op(Opcode::Close, table_cursor, 0, 0, P4::None, 0);

    // Close index cursors (bd-so1h).
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    for idx_offset in 0..table.indexes.len() {
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    }

    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End label.
    b.resolve_label(end_label);

    Ok(())
}

#[derive(Debug, Clone)]
struct InsertTargetMapping {
    expected_source_cols: usize,
    explicit_rowid_source_pos: Option<usize>,
    col_mapping: Vec<Option<usize>>,
}

fn build_insert_target_mapping(
    insert_columns: &[String],
    table: &TableSchema,
) -> Result<Option<InsertTargetMapping>, CodegenError> {
    if insert_columns.is_empty() {
        return Ok(None);
    }

    enum RowidTarget {
        Hidden(usize),
        Ipk,
    }

    let mut rowid_target = None;
    let mut col_mapping = vec![None; table.columns.len()];

    for (source_pos, col_name) in insert_columns.iter().enumerate() {
        if table.resolves_to_hidden_rowid(col_name) {
            rowid_target = Some(RowidTarget::Hidden(source_pos));
            continue;
        }

        let tbl_pos = table
            .column_index(col_name)
            .ok_or_else(|| CodegenError::ColumnNotFound {
                table: table.name.clone(),
                column: col_name.clone(),
            })?;
        if table.columns[tbl_pos].is_ipk {
            rowid_target = Some(RowidTarget::Ipk);
            col_mapping[tbl_pos] = Some(source_pos);
        } else {
            col_mapping[tbl_pos].get_or_insert(source_pos);
        }
    }

    Ok(Some(InsertTargetMapping {
        expected_source_cols: insert_columns.len(),
        explicit_rowid_source_pos: match rowid_target {
            Some(RowidTarget::Hidden(source_pos)) => Some(source_pos),
            Some(RowidTarget::Ipk) | None => None,
        },
        col_mapping,
    }))
}

/// Emit the check-before-insert conflict probe for one UPSERT `ON CONFLICT`
/// clause (rowid table).
///
/// `target` is the clause's conflict target (`None` for a bare `ON CONFLICT`).
/// On NO conflict, control jumps to `no_conflict_label` (the next clause in the
/// chain, or the normal-insert path for the last clause). On conflict, control
/// falls through with the table cursor positioned on the conflicting row; the
/// returned register holds that row's rowid.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::too_many_arguments
)]
fn emit_upsert_probe(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    cursor: i32,
    val_regs: i32,
    rowid_reg: i32,
    table_alias: Option<&str>,
    target: Option<&UpsertTarget>,
    no_conflict_label: Label,
) -> i32 {
    if let Some((idx_offset, index)) = find_upsert_target_index(table, target) {
        let attempted_row_ctx = ScanCtx {
            cursor,
            table,
            table_alias,
            schema: None,
            register_base: Some(val_regs),
            secondaries: &[],
        };
        emit_index_predicate_guard(b, index, &attempted_row_ctx, no_conflict_label);

        // UNIQUE index conflict check.
        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        let idx_cursor = cursor + 1 + idx_offset as i32;
        let n_key_cols = index.columns.len() as i32;

        // Build probe key from attempted insert values.
        let key_val_regs = b.alloc_regs(n_key_cols);
        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        for (key_pos, col_name) in index.columns.iter().enumerate() {
            if let Some(col_idx) = table.column_index(col_name) {
                b.emit_op(
                    Opcode::Copy,
                    val_regs + col_idx as i32,
                    key_val_regs + key_pos as i32,
                    0,
                    P4::None,
                    0,
                );
            }
        }
        let key_rec_reg = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            key_val_regs,
            n_key_cols,
            key_rec_reg,
            P4::None,
            0,
        );

        // NoConflict: jump to no_conflict_label if no match found.
        b.emit_jump_to_label(
            Opcode::NoConflict,
            idx_cursor,
            key_rec_reg,
            no_conflict_label,
            P4::None,
            0,
        );

        // Conflict: extract existing row's rowid from index.
        let existing_rowid_reg = b.alloc_reg();
        b.emit_op(Opcode::IdxRowid, idx_cursor, existing_rowid_reg, 0, P4::None, 0);

        // Seek table cursor to the existing row.
        b.emit_jump_to_label(
            Opcode::NotExists,
            cursor,
            existing_rowid_reg,
            no_conflict_label,
            P4::None,
            0,
        );

        existing_rowid_reg
    } else if target.is_none()
        && table
            .indexes
            .iter()
            .any(|index| index.is_unique && index.supports_direct_column_lookup())
    {
        // Omitted conflict target (SQLite 3.35+): DO UPDATE fires on whichever
        // uniqueness constraint the new row violates first. Probe the rowid/IPK
        // PRIMARY KEY, then every UNIQUE index in schema order; the first hit
        // supplies the existing row and leaves the table cursor positioned on it.
        let conflict_label = b.emit_label();
        let found_rowid_reg = b.alloc_reg();
        let pk_miss = b.emit_label();
        b.emit_jump_to_label(Opcode::NotExists, cursor, rowid_reg, pk_miss, P4::None, 0);
        b.emit_op(Opcode::Copy, rowid_reg, found_rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, conflict_label, P4::None, 0);
        b.resolve_label(pk_miss);
        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        for (idx_offset, index) in table.indexes.iter().enumerate() {
            if !index.is_unique || !index.supports_direct_column_lookup() {
                continue;
            }
            let idx_miss = b.emit_label();
            let idx_cursor = cursor + 1 + idx_offset as i32;
            let n_key_cols = index.columns.len() as i32;
            let key_val_regs = b.alloc_regs(n_key_cols);
            #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
            for (key_pos, col_name) in index.columns.iter().enumerate() {
                if let Some(col_idx) = table.column_index(col_name) {
                    b.emit_op(
                        Opcode::Copy,
                        val_regs + col_idx as i32,
                        key_val_regs + key_pos as i32,
                        0,
                        P4::None,
                        0,
                    );
                }
            }
            let key_rec_reg = b.alloc_reg();
            b.emit_op(
                Opcode::MakeRecord,
                key_val_regs,
                n_key_cols,
                key_rec_reg,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::NoConflict,
                idx_cursor,
                key_rec_reg,
                idx_miss,
                P4::None,
                0,
            );
            b.emit_op(Opcode::IdxRowid, idx_cursor, found_rowid_reg, 0, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::NotExists,
                cursor,
                found_rowid_reg,
                idx_miss,
                P4::None,
                0,
            );
            b.emit_jump_to_label(Opcode::Goto, 0, 0, conflict_label, P4::None, 0);
            b.resolve_label(idx_miss);
        }
        b.emit_jump_to_label(Opcode::Goto, 0, 0, no_conflict_label, P4::None, 0);
        b.resolve_label(conflict_label);
        found_rowid_reg
    } else {
        // PK conflict check (explicit PK/rowid target, or omitted target on a
        // table with no UNIQUE indexes).
        b.emit_jump_to_label(Opcode::NotExists, cursor, rowid_reg, no_conflict_label, P4::None, 0);
        rowid_reg
    }
}

/// Emit the DO UPDATE apply body for one UPSERT clause (rowid table): read the
/// conflicting row, evaluate the optional `WHERE`, apply the SET assignments
/// (with `excluded.*` bound to the attempted-insert registers), re-validate
/// constraints, delete the old row, and re-insert the rewritten image. The
/// table cursor must already be positioned on the conflicting row (rowid in
/// `update_rowid_reg`, from [`emit_upsert_probe`]). Does not emit the trailing
/// jump to the done label — the caller does.
#[allow(clippy::too_many_arguments)]
fn emit_upsert_do_update_apply(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    cursor: i32,
    schema: &[TableSchema],
    val_regs: i32,
    rowid_reg: i32,
    update_rowid_reg: i32,
    assignments: &[fsqlite_ast::Assignment],
    where_clause: Option<&Expr>,
    n_cols: usize,
    n_cols_i32: i32,
    aff_str: &str,
    stmt_level: Option<ConflictAction>,
    returning: &[ResultColumn],
    table_alias: Option<&str>,
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    // Allocate registers for existing row columns and read them from the cursor.
    let existing_regs = b.alloc_regs(n_cols_i32);
    for col_idx in 0..n_cols {
        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        let col_i = col_idx as i32;
        if table.columns.get(col_idx).is_some_and(|c| c.is_ipk) {
            b.emit_op(Opcode::Rowid, cursor, existing_regs + col_i, 0, P4::None, 0);
        } else {
            b.emit_op(Opcode::Column, cursor, col_i, existing_regs + col_i, P4::None, 0);
        }
    }

    // Build ScanCtx for evaluating DO UPDATE expressions. "excluded" maps to
    // val_regs (the attempted insert values); unqualified column refs resolve
    // from existing_regs (the current row). bd-xjfrt: both ctxs carry the real
    // `schema` (so subqueries resolve, not the "no schema → NULL" arm) and
    // existing_ctx exposes `excluded.*` as a register-backed secondary so
    // `... WHERE s.k = excluded.k` correlates against val_regs.
    let excluded_secondary = [SecondaryScan {
        cursor,
        table,
        table_alias: Some("excluded"),
        register_base: Some(val_regs),
    }];
    let excluded_ctx = ScanCtx {
        cursor,
        table,
        table_alias: Some("excluded"),
        schema: Some(schema),
        register_base: Some(val_regs),
        secondaries: &[],
    };
    let existing_ctx = ScanCtx {
        cursor,
        table,
        table_alias,
        schema: Some(schema),
        register_base: Some(existing_regs),
        secondaries: &excluded_secondary,
    };
    let existing_hidden_rowid_reg = ctx
        .rowid_alias_col_idx
        .map(|ipk_idx| existing_regs + ipk_idx as i32);
    let excluded_hidden_rowid_reg = rowid_reg;

    // Optional WHERE clause on the DO UPDATE action.
    let skip_update_label = if let Some(where_expr) = where_clause {
        let label = b.emit_label();
        let where_reg = b.alloc_reg();
        emit_upsert_expr(
            b,
            where_expr,
            where_reg,
            &existing_ctx,
            &excluded_ctx,
            table,
            existing_hidden_rowid_reg,
            excluded_hidden_rowid_reg,
        );
        // If WHERE is false/NULL, skip the update (jump to done).
        b.emit_jump_to_label(Opcode::IfNot, where_reg, 1, label, P4::None, 0);
        Some(label)
    } else {
        None
    };

    emit_upsert_assignments(
        b,
        assignments,
        table,
        existing_regs,
        &existing_ctx,
        &excluded_ctx,
        existing_hidden_rowid_reg,
        excluded_hidden_rowid_reg,
    )?;
    // Validate the rewritten image before removing the old row.
    emit_strict_type_check(b, table, existing_regs);
    // GH #169: coerce to column affinity before CHECK/NOT NULL so the
    // constraints see the affinity-coerced value.
    b.emit_op(
        Opcode::Affinity,
        existing_regs,
        table.columns.len() as i32,
        0,
        P4::Affinity(table.affinity_string()),
        0,
    );
    emit_check_constraints(b, table, existing_regs, None);
    emit_not_null_constraints(b, table, existing_regs, stmt_level, None);
    emit_index_deletes(b, table, cursor);
    b.emit_op(Opcode::Delete, cursor, 0, 0, P4::None, OPFLAG_ISUPDATE);

    // An UPSERT assignment may rewrite the INTEGER PRIMARY KEY. Reinsert at the
    // new rowid, not the conflict victim's old id.
    let mut final_rowid_reg = update_rowid_reg;
    if let Some(ipk_idx) = ctx
        .rowid_alias_col_idx
        .or_else(|| table.columns.iter().position(|column| column.is_ipk))
    {
        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        let ipk_reg = existing_regs + ipk_idx as i32;
        let auto_label = b.emit_label();
        let rowid_done_label = b.emit_label();
        final_rowid_reg = b.alloc_reg();
        b.emit_jump_to_label(Opcode::IsNull, ipk_reg, 0, auto_label, P4::None, 0);
        b.emit_op(Opcode::Copy, ipk_reg, final_rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, rowid_done_label, P4::None, 0);
        b.resolve_label(auto_label);
        b.emit_op(
            Opcode::NewRowid,
            cursor,
            final_rowid_reg,
            i32::from(ctx.concurrent_mode),
            P4::None,
            0,
        );
        b.emit_op(Opcode::Copy, final_rowid_reg, ipk_reg, 0, P4::None, 0);
        b.resolve_label(rowid_done_label);
    }

    let update_rec = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        existing_regs,
        n_cols_i32,
        update_rec,
        make_insert_record_p4(table, aff_str),
        0,
    );
    // bd-sque1: the DO UPDATE apply is semantically an UPDATE, so its re-insert
    // must ABORT — not REPLACE — on a uniqueness conflict. The conflict victim
    // was already deleted above, so a same-key upsert never collides; ABORT
    // fires only when the assignment rewrites the rowid/PK/UNIQUE key onto a
    // DIFFERENT existing row, matching stock.
    b.emit_op(
        Opcode::Insert,
        cursor,
        update_rec,
        final_rowid_reg,
        P4::Table(table.name.clone()),
        OE_ABORT | OPFLAG_ISUPDATE,
    );
    emit_index_inserts(
        b,
        table,
        cursor,
        existing_regs,
        final_rowid_reg,
        Some(ConflictAction::Abort),
    );
    if !returning.is_empty() {
        emit_returning(b, cursor, table, returning, table_alias, final_rowid_reg)?;
    }
    if let Some(label) = skip_update_label {
        b.resolve_label(label);
    }
    Ok(())
}

/// Emit the INSERT loop for `VALUES (row), (row), ...`.
///
/// # Arguments
/// * `oe_flag` - Conflict resolution flag (OE_ABORT, OE_IGNORE, OE_REPLACE, etc.)
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::too_many_arguments
)]
fn codegen_insert_values(
    b: &mut ProgramBuilder,
    rows: &[Vec<Expr>],
    expected_source_cols: Option<usize>,
    explicit_rowid_source_pos: Option<usize>,
    col_mapping: Option<&[Option<usize>]>,
    cursor: i32,
    table: &TableSchema,
    schema: &[TableSchema],
    returning: &[ResultColumn],
    table_alias: Option<&str>,
    ctx: &CodegenContext,
    oe_flag: u16,
    stmt_level: Option<ConflictAction>,
    upserts: &[UpsertClause],
) -> Result<(), CodegenError> {
    // Conflict action for the table (rowid/INTEGER PRIMARY KEY) row: a
    // statement-level `INSERT OR <algo>` overrides the IPK column's declared
    // `PRIMARY KEY ON CONFLICT <algo>`.
    let ipk_conflict = table
        .columns
        .iter()
        .find(|c| c.is_ipk)
        .and_then(|c| c.conflict_action);
    let pk_oe = effective_oe(stmt_level, ipk_conflict);
    let n_source_cols = rows
        .first()
        .ok_or_else(|| CodegenError::Unsupported("empty VALUES".to_owned()))?
        .len();

    let expected_source_cols = expected_source_cols.unwrap_or(table.columns.len());
    if n_source_cols != expected_source_cols {
        let message = if expected_source_cols == table.columns.len() && col_mapping.is_none() {
            format!(
                "table {} has {} columns but {} values were supplied",
                table.name,
                table.columns.len(),
                n_source_cols
            )
        } else {
            // An explicit target column list uses stock's shorter form.
            format!("{n_source_cols} values for {expected_source_cols} columns")
        };
        return Err(CodegenError::SqlError(message));
    }

    let rowid_reg = b.alloc_reg();
    let source_regs = b.alloc_regs(n_source_cols as i32);
    let mapped_regs = col_mapping.map(|_| b.alloc_regs(table.columns.len() as i32));
    let rec_reg = b.alloc_reg();
    let concurrent_flag = i32::from(ctx.concurrent_mode);

    for (row_index, row_values) in rows.iter().enumerate() {
        if row_values.len() != n_source_cols {
            return Err(CodegenError::SqlError(
                "all VALUES must have the same number of terms".to_owned(),
            ));
        }

        // Emit value expressions into registers. A bare column reference in a
        // VALUES row is never resolvable — a VALUES row has no source row — so
        // stock SQLite errors "no such column: X" rather than resolving it to
        // NULL (bd-xxqg5). DQS-ON double-quoted values are already rewritten to
        // string literals before codegen (bd-82jdw dqs_proactive_rewrite), so
        // only an unquoted bare column can reach here.
        for (i, val_expr) in row_values.iter().enumerate() {
            if let Expr::Column(col_ref, _) = val_expr
                && col_ref.table.is_none()
            {
                return Err(CodegenError::ColumnNotFound {
                    table: table.name.clone(),
                    column: col_ref.column.to_string(),
                });
            }
            let reg = source_regs + i as i32;
            emit_expr(b, val_expr, reg, None);
        }

        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        let (val_regs, n_cols) = if let Some(mapping) = col_mapping {
            let table_regs = mapped_regs.expect("mapped registers allocated");
            for (tbl_idx, src) in mapping.iter().enumerate() {
                let dest = table_regs + tbl_idx as i32;
                if let Some(source_pos) = src {
                    b.emit_op(
                        Opcode::Copy,
                        source_regs + *source_pos as i32,
                        dest,
                        0,
                        P4::None,
                        0,
                    );
                } else {
                    emit_default_value(b, &table.columns[tbl_idx], dest)?;
                }
            }
            (table_regs, table.columns.len())
        } else {
            (source_regs, n_source_cols)
        };

        // Rowid determination precedence:
        // 1. explicit rowid/_rowid_/oid in INSERT column list
        // 2. INTEGER PRIMARY KEY column value
        // 3. auto-generated rowid
        if let Some(source_pos) = explicit_rowid_source_pos {
            #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
            let rowid_value_reg = source_regs + source_pos as i32;
            #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
            let ipk_reg = ctx
                .rowid_alias_col_idx
                .map(|ipk_idx| val_regs + ipk_idx as i32);
            let auto_label = b.emit_label();
            let done_label = b.emit_label();

            b.emit_jump_to_label(Opcode::IsNull, rowid_value_reg, 0, auto_label, P4::None, 0);
            b.emit_op(Opcode::Copy, rowid_value_reg, rowid_reg, 0, P4::None, 0);
            if let Some(ipk_reg) = ipk_reg {
                b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);
            }
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

            b.resolve_label(auto_label);
            b.emit_op(
                Opcode::NewRowid,
                cursor,
                rowid_reg,
                concurrent_flag,
                P4::None,
                0,
            );
            if let Some(ipk_reg) = ipk_reg {
                b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);
            }

            b.resolve_label(done_label);
        } else if let Some(ipk_idx) = ctx.rowid_alias_col_idx {
            #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
            let ipk_reg = val_regs + ipk_idx as i32;
            let auto_label = b.emit_label();
            let done_label = b.emit_label();

            // If the user-supplied IPK value is NULL, jump to auto-generate.
            b.emit_jump_to_label(Opcode::IsNull, ipk_reg, 0, auto_label, P4::None, 0);

            // Non-NULL path: copy user value into rowid register.
            b.emit_op(Opcode::Copy, ipk_reg, rowid_reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

            // NULL path: auto-generate rowid, then sync it back into the
            // IPK column register so MakeRecord includes the real rowid.
            b.resolve_label(auto_label);
            b.emit_op(
                Opcode::NewRowid,
                cursor,
                rowid_reg,
                concurrent_flag,
                P4::None,
                0,
            );
            b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);

            b.resolve_label(done_label);
        } else {
            // No IPK column — always auto-generate.
            b.emit_op(
                Opcode::NewRowid,
                cursor,
                rowid_reg,
                concurrent_flag,
                P4::None,
                0,
            );
        }

        // Evaluate STORED generated columns before packing the record.
        emit_stored_generated_columns(b, table, val_regs);

        // STRICT type check BEFORE affinity (SQLite validates raw storage
        // classes, then applies affinity for the on-disk format).
        emit_strict_type_check(b, table, val_regs);
        // GH #169: coerce to column affinity before CHECK/NOT NULL so the
        // constraints see the affinity-coerced value (SQLite applies affinity,
        // then evaluates constraints).
        b.emit_op(
            Opcode::Affinity,
            val_regs,
            n_cols as i32,
            0,
            P4::Affinity(table.affinity_string()),
            0,
        );

        // CHECK / NOT NULL validation. A row is skipped (IGNORE) when the
        // statement is `INSERT OR IGNORE`, or when a violated NOT NULL column
        // declares its own `ON CONFLICT IGNORE`. We allocate the shared skip
        // label whenever any of those is possible.
        let nn_ignore = table.columns.iter().any(|c| {
            c.notnull && !c.is_ipk && effective_oe(stmt_level, c.conflict_action) == OE_IGNORE
        });
        let ignore_skip = if oe_flag == OE_IGNORE || nn_ignore {
            Some(b.emit_label())
        } else {
            None
        };
        // CHECK constraints have no per-column conflict clause here, so they
        // only skip under a statement-level IGNORE.
        let check_ignore = if oe_flag == OE_IGNORE {
            ignore_skip
        } else {
            None
        };
        emit_check_constraints(b, table, val_regs, check_ignore);
        emit_not_null_constraints(b, table, val_regs, stmt_level, ignore_skip);

        // Apply column type affinities before packing the record.
        let aff_str = table.affinity_string();
        b.emit_op(
            Opcode::Affinity,
            val_regs,
            n_cols as i32,
            0,
            P4::Affinity(aff_str.clone()),
            0,
        );

        // MakeRecord: pack columns into a record.
        let n_cols_i32 = n_cols as i32;
        // bd-bld9w.7 family (a): the compile-time preformatted record bakes TEXT as
        // UTF-8, so only use it for a UTF-8 database; for UTF-16 fall through to the
        // encoding-aware runtime MakeRecord path.
        let preformatted_record = if matches!(ctx.text_encoding, TextEncoding::Utf8) {
            try_build_preformatted_insert_record(row_values, table, col_mapping)
        } else {
            None
        };
        if preformatted_record.is_some() {
            tracing::debug!(
                target: "fsqlite_vdbe::insert_preformat",
                table = %table.name,
                row_index,
                explicit_column_mapping = col_mapping.is_some(),
                column_count = n_cols,
                "preformatted INSERT record at codegen"
            );
        }

        // UPSERT: a chain of ON CONFLICT clauses (SQLite 3.35+). Each clause
        // probes its own conflict target in written order; the first clause
        // whose target is violated is applied (DO UPDATE rewrites the specific
        // conflicting row; DO NOTHING skips the insert). A conflict on a
        // constraint that no clause targets falls through to the normal insert,
        // where `stmt_level` (default ABORT) raises it — matching stock.
        if !upserts.is_empty() {
            let done_label = b.emit_label();
            let insert_label = b.emit_label();
            for (clause_idx, clause) in upserts.iter().enumerate() {
                // NO conflict on this clause's target routes to the next clause;
                // the last clause routes to the normal-insert path.
                let no_conflict_label = if clause_idx + 1 == upserts.len() {
                    insert_label
                } else {
                    b.emit_label()
                };
                let existing_rowid_reg = emit_upsert_probe(
                    b,
                    table,
                    cursor,
                    val_regs,
                    rowid_reg,
                    table_alias,
                    clause.target.as_ref(),
                    no_conflict_label,
                );
                match &clause.action {
                    UpsertAction::Nothing => {
                        // Conflict on this target -> skip the insert entirely.
                        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    }
                    UpsertAction::Update {
                        assignments,
                        where_clause,
                    } => {
                        emit_upsert_do_update_apply(
                            b,
                            table,
                            cursor,
                            schema,
                            val_regs,
                            rowid_reg,
                            existing_rowid_reg,
                            assignments,
                            where_clause.as_deref(),
                            n_cols,
                            n_cols_i32,
                            &aff_str,
                            stmt_level,
                            returning,
                            table_alias,
                            ctx,
                        )?;
                        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    }
                }
                if clause_idx + 1 != upserts.len() {
                    b.resolve_label(no_conflict_label);
                }
            }

            // --- No clause matched: normal insert. Non-target UNIQUE/PK
            // constraints are enforced by emit_index_inserts under stmt_level
            // (default ABORT), so a conflict on a constraint no clause targets
            // raises the error, matching stock. ---
            b.resolve_label(insert_label);
            let insert_p4 = emit_table_insert_record(
                b,
                val_regs,
                n_cols_i32,
                rec_reg,
                table,
                &aff_str,
                preformatted_record.as_deref(),
            );
            b.emit_op(Opcode::Insert, cursor, rec_reg, rowid_reg, insert_p4, pk_oe);
            emit_index_inserts(b, table, cursor, val_regs, rowid_reg, stmt_level);
            if !returning.is_empty() {
                emit_returning(b, cursor, table, returning, table_alias, rowid_reg)?;
            }
            b.resolve_label(done_label);
        } else {
            // No upsert — normal insert path.
            // GH #158: INSERT OR IGNORE on a rowid / INTEGER-PRIMARY-KEY conflict
            // must skip the WHOLE row, RETURNING included. Opcode::Insert with
            // OE_IGNORE suppresses the write on conflict, but execution falls
            // through to emit_returning, which re-seeks the rowid and would emit
            // the PRE-EXISTING row. Pre-probe the rowid and jump to the
            // ignore-skip label on conflict, mirroring the WITHOUT ROWID path.
            if pk_oe == OE_IGNORE
                && let Some(skip) = ignore_skip
            {
                let do_insert = b.emit_label();
                // NotExists jumps to do_insert when the rowid is free (no
                // conflict); on an existing rowid we fall through and skip.
                b.emit_jump_to_label(Opcode::NotExists, cursor, rowid_reg, do_insert, P4::None, 0);
                b.emit_jump_to_label(Opcode::Goto, 0, 0, skip, P4::None, 0);
                b.resolve_label(do_insert);
            }
            let insert_p4 = emit_table_insert_record(
                b,
                val_regs,
                n_cols_i32,
                rec_reg,
                table,
                &aff_str,
                preformatted_record.as_deref(),
            );
            b.emit_op(Opcode::Insert, cursor, rec_reg, rowid_reg, insert_p4, pk_oe);
            emit_index_inserts(b, table, cursor, val_regs, rowid_reg, stmt_level);
            if !returning.is_empty() {
                emit_returning(b, cursor, table, returning, table_alias, rowid_reg)?;
            }
        }

        // Resolve OR IGNORE skip label after all insert logic for this row.
        if let Some(skip) = ignore_skip {
            b.resolve_label(skip);
        }
    }

    Ok(())
}

fn emit_table_insert_record(
    b: &mut ProgramBuilder,
    source_regs: i32,
    column_count: i32,
    target_reg: i32,
    table: &TableSchema,
    affinity: &str,
    preformatted_record: Option<&[u8]>,
) -> P4 {
    if let Some(record) = preformatted_record {
        // Keep the preformatted record off the register file entirely.
        // INSERT can consume the baked row image directly from P4.
        P4::Blob(record.to_vec())
    } else {
        b.emit_op(
            Opcode::MakeRecord,
            source_regs,
            column_count,
            target_reg,
            make_insert_record_p4(table, affinity),
            0,
        );
        P4::Table(table.name.clone())
    }
}

fn make_insert_record_p4(table: &TableSchema, affinity: &str) -> P4 {
    try_build_precomputed_record_header(table)
        .map(P4::PrecomputedHeader)
        .unwrap_or_else(|| P4::Affinity(affinity.to_owned()))
}

fn try_build_precomputed_record_header(table: &TableSchema) -> Option<PrecomputedRecordHeader> {
    let mut kinds = Vec::with_capacity(table.columns.len());
    for column in &table.columns {
        kinds.push(precomputed_serial_type_kind(column)?);
    }
    Some(PrecomputedRecordHeader::new(&kinds))
}

fn precomputed_serial_type_kind(column: &ColumnInfo) -> Option<PrecomputedSerialTypeKind> {
    if column.is_ipk {
        return Some(PrecomputedSerialTypeKind::NullPlaceholder);
    }
    match column.strict_type {
        Some(StrictColumnType::Integer) => Some(PrecomputedSerialTypeKind::IntegerOrNull),
        Some(StrictColumnType::Real) => Some(PrecomputedSerialTypeKind::RealOrNull),
        _ => None,
    }
}

/// Build a table-record blob at codegen time for rows whose stored image is
/// fully determined before execution.
///
/// This intentionally stays narrow:
/// - only literal `VALUES` expressions are admitted
/// - omitted/default/generated columns fall back to runtime `MakeRecord`
/// - rowid/IPK storage still uses the runtime key path; the record stores NULL
///   placeholders for INTEGER PRIMARY KEY aliases just like `MakeRecord`
/// - CURRENT_* literals stay on the runtime path so the value registers and
///   record blob cannot drift from separate timestamp materializations
fn try_build_preformatted_insert_record(
    row_values: &[Expr],
    table: &TableSchema,
    col_mapping: Option<&[Option<usize>]>,
) -> Option<Vec<u8>> {
    if table.columns.iter().any(|col| col.generated_expr.is_some()) {
        return None;
    }

    let mut stored_values = Vec::with_capacity(table.columns.len());
    for (table_idx, column) in table.columns.iter().enumerate() {
        if column.is_ipk {
            stored_values.push(SqliteValue::Null);
            continue;
        }

        let expr = match col_mapping {
            Some(mapping) => {
                let source_idx = mapping.get(table_idx)?.as_ref()?;
                row_values.get(*source_idx)?
            }
            None => row_values.get(table_idx)?,
        };
        let value = compile_time_insert_value(expr)?;
        let value = if let Some(strict_type) = column.strict_type {
            value.validate_strict(strict_type).ok()?
        } else {
            value
        };
        stored_values.push(value.apply_affinity(type_affinity_for_char(column.affinity)));
    }

    Some(fsqlite_types::record::serialize_record(&stored_values))
}

fn compile_time_insert_value(expr: &Expr) -> Option<SqliteValue> {
    let Expr::Literal(literal, _) = expr else {
        return None;
    };
    Some(match literal {
        Literal::Integer(value) => SqliteValue::Integer(*value),
        Literal::Float(value) => SqliteValue::Float(*value),
        Literal::String(value) => SqliteValue::Text(SmallText::new(value.as_str())),
        Literal::Blob(value) => SqliteValue::Blob(Arc::from(value.as_slice())),
        Literal::Null => SqliteValue::Null,
        Literal::True => SqliteValue::Integer(1),
        Literal::False => SqliteValue::Integer(0),
        Literal::CurrentTimestamp | Literal::CurrentDate | Literal::CurrentTime => return None,
    })
}

fn type_affinity_for_char(ch: char) -> TypeAffinity {
    match ch {
        'B' | 'b' => TypeAffinity::Text,
        'C' | 'c' => TypeAffinity::Numeric,
        'D' | 'd' => TypeAffinity::Integer,
        'E' | 'e' => TypeAffinity::Real,
        _ => TypeAffinity::Blob,
    }
}

/// Emit the INSERT loop for `INSERT INTO target SELECT ... FROM source`.
///
/// Opens the source table for reading (cursor = `write_cursor + 1`), scans
/// rows with an optional WHERE filter, reads projected columns, and inserts
/// each row into the target table.
///
/// # Arguments
/// * `oe_flag` - Conflict resolution flag (OE_ABORT, OE_IGNORE, OE_REPLACE, etc.)
#[allow(
    clippy::too_many_arguments,
    clippy::too_many_lines,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap
)]
fn codegen_insert_select(
    b: &mut ProgramBuilder,
    select_stmt: &SelectStatement,
    write_cursor: i32,
    target_table: &TableSchema,
    schema: &[TableSchema],
    returning: &[ResultColumn],
    target_alias: Option<&str>,
    ctx: &CodegenContext,
    oe_flag: u16,
    stmt_level: Option<ConflictAction>,
    expected_cols: Option<usize>,
    explicit_rowid_source_pos: Option<usize>,
    col_mapping: Option<&[Option<usize>]>,
) -> Result<(), CodegenError> {
    // Extract columns, FROM, and WHERE from the inner SELECT.
    let (columns, from, where_clause) = match &select_stmt.body.select {
        SelectCore::Select {
            columns,
            from,
            where_clause,
            ..
        } => (columns, from, where_clause),
        SelectCore::Values(_) => {
            return Err(CodegenError::Unsupported(
                "INSERT ... SELECT with VALUES body".to_owned(),
            ));
        }
    };

    if from.is_none() {
        return codegen_insert_select_without_from(
            b,
            columns,
            where_clause.as_deref(),
            write_cursor,
            target_table,
            returning,
            target_alias,
            ctx,
            oe_flag,
            stmt_level,
            expected_cols,
            explicit_rowid_source_pos,
            col_mapping,
        );
    }

    // SAFETY: `from.is_none()` is handled above; `.expect` cannot panic.
    let from_clause = from.as_ref().expect("from already checked above");

    let (src_table_name, src_table_alias) = match &from_clause.source {
        fsqlite_ast::TableOrSubquery::Table { name, alias, .. } => (&name.name, alias.as_deref()),
        _ => {
            return Err(CodegenError::Unsupported(
                "INSERT ... SELECT from non-table source".to_owned(),
            ));
        }
    };

    let src_table = find_table(schema, src_table_name)?;
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    let read_cursor = write_cursor + 1 + target_table.indexes.len() as i32;

    // Determine the number of output columns from the SELECT.
    let n_cols = result_column_count(columns, src_table);
    let n_cols_usize = usize::try_from(n_cols).unwrap_or(0);

    if let Some(expected) = expected_cols
        && n_cols_usize != expected
    {
        return Err(CodegenError::SqlError(format!(
            "table {} has {} columns but {} values were supplied",
            target_table.name, expected, n_cols_usize
        )));
    }

    // Allocate registers for the scan → insert pipeline.
    let rowid_reg = b.alloc_reg();
    let val_regs = b.alloc_regs(n_cols);
    let rec_reg = b.alloc_reg();
    let concurrent_flag = i32::from(ctx.concurrent_mode);

    let done_label = b.emit_label();

    // OpenRead on source table.
    b.emit_op(
        Opcode::OpenRead,
        read_cursor,
        src_table.root_page,
        0,
        P4::Table(src_table.name.clone()),
        0,
    );

    // Rewind to first row; jump to done if source is empty.
    let loop_start = b.current_addr();
    b.emit_jump_to_label(Opcode::Rewind, read_cursor, 0, done_label, P4::None, 0);

    // WHERE filter on source rows (skip non-matching).
    let skip_label = b.emit_label();
    if let Some(where_expr) = where_clause {
        emit_where_filter(
            b,
            where_expr,
            read_cursor,
            src_table,
            src_table_alias,
            schema,
            skip_label,
        );
    }

    // Read projected columns from source into val_regs.
    emit_column_reads(
        b,
        read_cursor,
        columns,
        src_table,
        src_table_alias,
        schema,
        val_regs,
    )?;

    // When an explicit column list is provided, reorder from SELECT output
    // order to table-schema order, filling unmentioned columns with defaults.
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    let (final_regs, final_n_cols) = if let Some(mapping) = col_mapping {
        let n_table_cols = target_table.columns.len() as i32;
        let table_regs = b.alloc_regs(n_table_cols);
        for (tbl_idx, src) in mapping.iter().enumerate() {
            let dest = table_regs + tbl_idx as i32;
            if let Some(sel_pos) = src {
                b.emit_op(
                    Opcode::Copy,
                    val_regs + *sel_pos as i32,
                    dest,
                    0,
                    P4::None,
                    0,
                );
            } else {
                emit_default_value(b, &target_table.columns[tbl_idx], dest)?;
            }
        }
        (table_regs, n_table_cols)
    } else {
        (val_regs, n_cols)
    };

    // Rowid determination: explicit hidden rowid takes precedence over IPK.
    if let Some(source_pos) = explicit_rowid_source_pos {
        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        let rowid_value_reg = val_regs + source_pos as i32;
        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        let ipk_reg = ctx
            .rowid_alias_col_idx
            .map(|ipk_idx| final_regs + ipk_idx as i32);
        let auto_label = b.emit_label();
        let done_rowid = b.emit_label();

        b.emit_jump_to_label(Opcode::IsNull, rowid_value_reg, 0, auto_label, P4::None, 0);
        b.emit_op(Opcode::Copy, rowid_value_reg, rowid_reg, 0, P4::None, 0);
        if let Some(ipk_reg) = ipk_reg {
            b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);
        }
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_rowid, P4::None, 0);

        b.resolve_label(auto_label);
        b.emit_op(
            Opcode::NewRowid,
            write_cursor,
            rowid_reg,
            concurrent_flag,
            P4::None,
            0,
        );
        if let Some(ipk_reg) = ipk_reg {
            b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);
        }

        b.resolve_label(done_rowid);
    } else if let Some(ipk_idx) = ctx.rowid_alias_col_idx {
        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        let ipk_reg = final_regs + ipk_idx as i32;
        let auto_label = b.emit_label();
        let done_rowid = b.emit_label();

        b.emit_jump_to_label(Opcode::IsNull, ipk_reg, 0, auto_label, P4::None, 0);

        // Non-NULL: use the selected value as rowid.
        b.emit_op(Opcode::Copy, ipk_reg, rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_rowid, P4::None, 0);

        // NULL: auto-generate and sync back.
        b.resolve_label(auto_label);
        b.emit_op(
            Opcode::NewRowid,
            write_cursor,
            rowid_reg,
            concurrent_flag,
            P4::None,
            0,
        );
        b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);

        b.resolve_label(done_rowid);
    } else {
        b.emit_op(
            Opcode::NewRowid,
            write_cursor,
            rowid_reg,
            concurrent_flag,
            P4::None,
            0,
        );
    }

    // Evaluate STORED generated columns before packing the record.
    emit_stored_generated_columns(b, target_table, final_regs);

    // Apply column type affinities before packing the record.
    // STRICT type check before affinity.
    emit_strict_type_check(b, target_table, final_regs);
    // GH #169: coerce to column affinity before CHECK/NOT NULL so the
    // constraints see the affinity-coerced value (SQLite applies affinity, then
    // evaluates constraints).
    b.emit_op(
        Opcode::Affinity,
        final_regs,
        final_n_cols,
        0,
        P4::Affinity(target_table.affinity_string()),
        0,
    );
    let nn_ignore = target_table.columns.iter().any(|c| {
        c.notnull && !c.is_ipk && effective_oe(stmt_level, c.conflict_action) == OE_IGNORE
    });
    let ignore_target = if oe_flag == OE_IGNORE || nn_ignore {
        Some(skip_label)
    } else {
        None
    };
    let check_ignore = if oe_flag == OE_IGNORE {
        ignore_target
    } else {
        None
    };
    emit_check_constraints(b, target_table, final_regs, check_ignore);
    emit_not_null_constraints(b, target_table, final_regs, stmt_level, ignore_target);
    let pk_oe = effective_oe(
        stmt_level,
        target_table
            .columns
            .iter()
            .find(|c| c.is_ipk)
            .and_then(|c| c.conflict_action),
    );

    let aff_str = target_table.affinity_string();
    b.emit_op(
        Opcode::Affinity,
        final_regs,
        final_n_cols,
        0,
        P4::Affinity(aff_str.clone()),
        0,
    );

    // MakeRecord from the read column values.
    b.emit_op(
        Opcode::MakeRecord,
        final_regs,
        final_n_cols,
        rec_reg,
        make_insert_record_p4(target_table, &aff_str),
        0,
    );

    // Insert into target table.
    b.emit_op(
        Opcode::Insert,
        write_cursor,
        rec_reg,
        rowid_reg,
        P4::Table(target_table.name.clone()),
        pk_oe,
    );

    // Index maintenance: insert into each index (bd-so1h).
    emit_index_inserts(
        b,
        target_table,
        write_cursor,
        final_regs,
        rowid_reg,
        stmt_level,
    );

    // RETURNING clause: position cursor on inserted row and read columns.
    if !returning.is_empty() {
        emit_returning(
            b,
            write_cursor,
            target_table,
            returning,
            target_alias,
            rowid_reg,
        )?;
    }

    // Skip label for WHERE-filtered rows.
    b.resolve_label(skip_label);

    // Next: advance to next source row.
    let loop_body = (loop_start + 1) as i32;
    b.emit_op(Opcode::Next, read_cursor, loop_body, 0, P4::None, 0);

    // Done: close source cursor.
    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, read_cursor, 0, 0, P4::None, 0);

    Ok(())
}

#[allow(
    clippy::too_many_arguments,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap
)]
fn codegen_insert_select_without_from(
    b: &mut ProgramBuilder,
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    write_cursor: i32,
    target_table: &TableSchema,
    returning: &[ResultColumn],
    target_alias: Option<&str>,
    ctx: &CodegenContext,
    oe_flag: u16,
    stmt_level: Option<ConflictAction>,
    expected_cols: Option<usize>,
    explicit_rowid_source_pos: Option<usize>,
    col_mapping: Option<&[Option<usize>]>,
) -> Result<(), CodegenError> {
    let n_cols = result_column_count_without_from(columns)?;
    let n_cols_usize = usize::try_from(n_cols).unwrap_or(0);

    if let Some(expected) = expected_cols
        && n_cols_usize != expected
    {
        return Err(CodegenError::SqlError(format!(
            "table {} has {} columns but {} values were supplied",
            target_table.name, expected, n_cols_usize
        )));
    }

    let rowid_reg = b.alloc_reg();
    let val_regs = b.alloc_regs(n_cols);
    let rec_reg = b.alloc_reg();
    let concurrent_flag = i32::from(ctx.concurrent_mode);
    let done_label = b.emit_label();

    if let Some(where_expr) = where_clause {
        let filter_reg = b.alloc_temp();
        emit_expr(b, where_expr, filter_reg, None);
        // Treat NULL WHERE results as false (skip insert).
        b.emit_jump_to_label(Opcode::IfNot, filter_reg, 1, done_label, P4::None, 0);
        b.free_temp(filter_reg);
    }

    emit_projection_without_from(b, columns, val_regs)?;

    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    let (final_regs, final_n_cols) = if let Some(mapping) = col_mapping {
        let n_table_cols = target_table.columns.len() as i32;
        let table_regs = b.alloc_regs(n_table_cols);
        for (tbl_idx, src) in mapping.iter().enumerate() {
            let dest = table_regs + tbl_idx as i32;
            if let Some(sel_pos) = src {
                b.emit_op(
                    Opcode::Copy,
                    val_regs + *sel_pos as i32,
                    dest,
                    0,
                    P4::None,
                    0,
                );
            } else {
                emit_default_value(b, &target_table.columns[tbl_idx], dest)?;
            }
        }
        (table_regs, n_table_cols)
    } else {
        (val_regs, n_cols)
    };

    // Rowid determination: explicit hidden rowid takes precedence over IPK.
    if let Some(source_pos) = explicit_rowid_source_pos {
        let rowid_value_reg = val_regs + source_pos as i32;
        let ipk_reg = ctx
            .rowid_alias_col_idx
            .map(|ipk_idx| final_regs + ipk_idx as i32);
        let auto_label = b.emit_label();
        let done_rowid = b.emit_label();

        b.emit_jump_to_label(Opcode::IsNull, rowid_value_reg, 0, auto_label, P4::None, 0);
        b.emit_op(Opcode::Copy, rowid_value_reg, rowid_reg, 0, P4::None, 0);
        if let Some(ipk_reg) = ipk_reg {
            b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);
        }
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_rowid, P4::None, 0);

        b.resolve_label(auto_label);
        b.emit_op(
            Opcode::NewRowid,
            write_cursor,
            rowid_reg,
            concurrent_flag,
            P4::None,
            0,
        );
        if let Some(ipk_reg) = ipk_reg {
            b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);
        }
        b.resolve_label(done_rowid);
    } else if let Some(ipk_idx) = ctx.rowid_alias_col_idx {
        let ipk_reg = final_regs + ipk_idx as i32;
        let auto_label = b.emit_label();
        let done_rowid = b.emit_label();

        b.emit_jump_to_label(Opcode::IsNull, ipk_reg, 0, auto_label, P4::None, 0);

        // Non-NULL: use the selected value as rowid.
        b.emit_op(Opcode::Copy, ipk_reg, rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_rowid, P4::None, 0);

        // NULL: auto-generate and sync back.
        b.resolve_label(auto_label);
        b.emit_op(
            Opcode::NewRowid,
            write_cursor,
            rowid_reg,
            concurrent_flag,
            P4::None,
            0,
        );
        b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);
        b.resolve_label(done_rowid);
    } else {
        b.emit_op(
            Opcode::NewRowid,
            write_cursor,
            rowid_reg,
            concurrent_flag,
            P4::None,
            0,
        );
    }

    // Evaluate STORED generated columns before packing the record.
    emit_stored_generated_columns(b, target_table, final_regs);

    let nn_ignore = target_table.columns.iter().any(|c| {
        c.notnull && !c.is_ipk && effective_oe(stmt_level, c.conflict_action) == OE_IGNORE
    });
    let ignore_target = if oe_flag == OE_IGNORE || nn_ignore {
        Some(done_label)
    } else {
        None
    };
    let check_ignore = if oe_flag == OE_IGNORE {
        ignore_target
    } else {
        None
    };
    let pk_oe = effective_oe(
        stmt_level,
        target_table
            .columns
            .iter()
            .find(|c| c.is_ipk)
            .and_then(|c| c.conflict_action),
    );

    // STRICT type check before affinity.
    emit_strict_type_check(b, target_table, final_regs);
    // GH #169: coerce to column affinity before CHECK/NOT NULL so the
    // constraints see the affinity-coerced value (SQLite applies affinity, then
    // evaluates constraints).
    b.emit_op(
        Opcode::Affinity,
        final_regs,
        final_n_cols,
        0,
        P4::Affinity(target_table.affinity_string()),
        0,
    );
    emit_check_constraints(b, target_table, final_regs, check_ignore);
    emit_not_null_constraints(b, target_table, final_regs, stmt_level, ignore_target);

    // Apply column type affinities before packing the record.
    let aff_str = target_table.affinity_string();
    b.emit_op(
        Opcode::Affinity,
        final_regs,
        final_n_cols,
        0,
        P4::Affinity(aff_str.clone()),
        0,
    );

    b.emit_op(
        Opcode::MakeRecord,
        final_regs,
        final_n_cols,
        rec_reg,
        make_insert_record_p4(target_table, &aff_str),
        0,
    );

    b.emit_op(
        Opcode::Insert,
        write_cursor,
        rec_reg,
        rowid_reg,
        P4::Table(target_table.name.clone()),
        pk_oe,
    );

    emit_index_inserts(
        b,
        target_table,
        write_cursor,
        final_regs,
        rowid_reg,
        stmt_level,
    );

    if !returning.is_empty() {
        emit_returning(
            b,
            write_cursor,
            target_table,
            returning,
            target_alias,
            rowid_reg,
        )?;
    }

    b.resolve_label(done_label);
    Ok(())
}

// ---------------------------------------------------------------------------
// UPDATE codegen
// ---------------------------------------------------------------------------

/// Generate VDBE bytecode for an UPDATE statement.
///
/// Pattern: `UPDATE t SET col = ? WHERE rowid = ?`
///
/// Reads ALL existing columns, replaces changed ones, writes back complete
/// record (no partial patches — this is normative per §10.6).
#[allow(clippy::too_many_lines)]
pub fn codegen_update(
    b: &mut ProgramBuilder,
    stmt: &UpdateStatement,
    schema: &[TableSchema],
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    let table_name = table_name_from_qualified(&stmt.table);
    let table = find_table(schema, table_name)?;
    if table.without_rowid {
        return codegen_update_without_rowid(b, stmt, table, schema, ctx);
    }
    let cursor = 0_i32;
    let n_cols = table.columns.len();

    let end_label = b.emit_label();
    let done_label = b.emit_label();

    if let Some(from_clause) = &stmt.from {
        return codegen_update_from(b, stmt, from_clause, schema, ctx);
    }
    if !stmt.order_by.is_empty() || stmt.limit.is_some() {
        return Err(CodegenError::Unsupported(
            "UPDATE ORDER BY/LIMIT/OFFSET must be materialized before codegen".to_owned(),
        ));
    }
    for assign in &stmt.assignments {
        validate_single_table_expr_columns(&assign.value, table, stmt.table.alias.as_deref())?;
    }
    if let Some(where_expr) = &stmt.where_clause {
        validate_single_table_expr_columns(where_expr, table, stmt.table.alias.as_deref())?;
    }
    validate_single_table_result_columns(
        &stmt.returning,
        table,
        stmt.table.alias.as_deref(),
        stmt.table.name.schema.as_deref(),
    )?;

    // Init.
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);

    // Transaction (write).
    b.emit_op(Opcode::Transaction, 0, 1, 0, P4::None, 0);

    // Resolve assignment targets to column indices.
    let assignment_cols = collect_update_assignment_columns(table, &stmt.assignments)?;
    let update_index_mask = update_index_maintenance_mask(table, &assignment_cols);

    // OpenWrite for table.
    let table_cursor = cursor;
    b.emit_op(
        Opcode::OpenWrite,
        table_cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );

    // OpenWrite for each index (bd-2f9t: Phase 5I.5).
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    for (idx_offset, index) in table.indexes.iter().enumerate() {
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        b.emit_op(
            Opcode::OpenWrite,
            idx_cursor,
            index.root_page,
            0,
            P4::Table(index.name.clone()),
            0,
        );
    }

    // Register table-to-index cursor metadata for REPLACE conflict resolution.
    register_table_index_meta(b, table, table_cursor);

    let rowid_target = extract_rowid_target_expr(stmt.where_clause.as_ref(), Some(table), None);
    // bd-update-rowid-in / bd-update-rowid-in-residual: `UPDATE ... WHERE <rowid> IN (<int literals>)
    // [AND <residual>]` collects the listed rows with one `SeekRowid` each (Pass 1) instead of
    // full-scanning; a residual is re-applied per seeked row. After `rowid = const`.
    let rowid_in_list = if rowid_target.is_none() {
        extract_rowid_in_list_residual_target(
            stmt.where_clause.as_ref(),
            table,
            stmt.table.alias.as_deref(),
        )
    } else {
        None
    };
    // bd-update-rowid-range: `UPDATE ... WHERE <rowid> <range>` collects the [lower, upper] slice with a
    // bounded seek+walk instead of full-scanning. Bare range, integer-literal bounds only (so Pass 1 emits
    // no anon placeholders — the SET placeholders are numbered in Pass 2 as before).
    let rowid_range = if rowid_target.is_none() && rowid_in_list.is_none() {
        extract_rowid_range_target(
            stmt.where_clause.as_ref(),
            Some(table),
            stmt.table.alias.as_deref(),
        )
        .filter(|range| {
            range.lower.is_some()
                && rowid_range_fast_path_is_safe(*range)
                && rowid_range_bounds_are_int_literals(range)
        })
    } else {
        None
    };
    // bd-update-rowid-eq-residual: `UPDATE ... WHERE <rowid> = <const> AND <residual>` seeks the single
    // target row and applies the residual — the common optimistic-lock shape (`WHERE id = ? AND version =
    // ?`), routed through the two-pass collect so the RowSet path (and its Halloween safety) is reused.
    let rowid_eq_residual =
        if rowid_target.is_none() && rowid_in_list.is_none() && rowid_range.is_none() {
            extract_rowid_eq_residual_target(
                stmt.where_clause.as_ref(),
                table,
                stmt.table.alias.as_deref(),
            )
        } else {
            None
        };
    // bd-update-index-eq(-residual): `UPDATE ... WHERE <single-col-int-indexed> = <int> [AND <residual>]`
    // seeks the index for the candidate rowids (fresh read cursor), applies the residual per candidate,
    // instead of full-scanning. After all rowid cases decline.
    let index_eq = if rowid_target.is_none()
        && rowid_in_list.is_none()
        && rowid_range.is_none()
        && rowid_eq_residual.is_none()
    {
        index_eq_residual_seek_target(
            stmt.where_clause.as_ref(),
            table,
            stmt.table.alias.as_deref(),
        )
    } else {
        None
    };

    let set_placeholder_count: u32 = stmt
        .assignments
        .iter()
        .map(|a| count_anon_placeholders(&a.value))
        .sum();

    let where_placeholder_count: u32 = stmt
        .where_clause
        .as_ref()
        .map_or(0, count_anon_placeholders);

    let matched_rowid_reg;
    let apply_done_label = b.emit_label();
    let (apply_seek_miss_label, apply_loop) = if let Some(target_expr) = rowid_target {
        matched_rowid_reg = b.alloc_reg();
        b.set_next_anon_placeholder(set_placeholder_count + 1);
        emit_expr(b, target_expr, matched_rowid_reg, None);
        // Coerce a non-integer-literal rowid key (placeholder / real / text) to INTEGER affinity: a
        // non-exact key (2.5 / 'abc' / NULL) rejects to `apply_done_label` (no row updated) instead of
        // raw `SeekRowid` TRUNCATING it to a wrong rowid (`WHERE id = 2.5` must not update row 2).
        // Integer literal is exact -> no MustBeInt (byte-identical). Mirrors the DELETE / SELECT paths.
        if !matches!(target_expr, Expr::Literal(Literal::Integer(_), _)) {
            b.emit_jump_to_label(
                Opcode::MustBeInt,
                matched_rowid_reg,
                0,
                apply_done_label,
                P4::None,
                0,
            );
        }
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            table_cursor,
            matched_rowid_reg,
            apply_done_label,
            P4::None,
            0,
        );
        (None, None)
    } else {
        let rowset_reg = b.alloc_reg();
        matched_rowid_reg = b.alloc_reg();
        let collect_done_label = b.emit_label();

        // Pass 1: collect matching rowids before mutating the table cursor.
        if let Some((values, has_residual)) = &rowid_in_list {
            // bd-update-rowid-in: one `SeekRowid` per listed value; a miss skips to the next value. When a
            // residual is present it is re-applied per seeked row, numbered from `set_placeholder_count + 1`
            // (after the SET placeholders, which are emitted in Pass 2) and reset each iteration so a `?`
            // in the residual numbers identically. The values are sorted+deduped and the RowSet dedups again.
            for &value in values {
                let next_value = b.emit_label();
                b.emit_op(Opcode::Int64, 0, matched_rowid_reg, 0, P4::Int64(value), 0);
                b.emit_jump_to_label(
                    Opcode::SeekRowid,
                    table_cursor,
                    matched_rowid_reg,
                    next_value,
                    P4::None,
                    0,
                );
                if *has_residual && let Some(where_expr) = &stmt.where_clause {
                    b.set_next_anon_placeholder(set_placeholder_count + 1);
                    emit_where_filter(
                        b,
                        where_expr,
                        table_cursor,
                        table,
                        stmt.table.alias.as_deref(),
                        schema,
                        next_value,
                    );
                }
                b.emit_op(
                    Opcode::RowSetAdd,
                    rowset_reg,
                    matched_rowid_reg,
                    0,
                    P4::None,
                    0,
                );
                b.resolve_label(next_value);
            }
        } else if let Some(range) = rowid_range {
            emit_rowid_range_rowset_collect(
                b,
                table,
                stmt.table.alias.as_deref(),
                schema,
                table_cursor,
                rowset_reg,
                matched_rowid_reg,
                collect_done_label,
                range,
            );
        } else if let Some(target_expr) = rowid_eq_residual {
            // Seek the single target row; a miss or a residual failure jumps to collect_done (no update).
            // The `rowid = <const>` probe and the re-applied residual both number from
            // `set_placeholder_count + 1` (after the SET placeholders, emitted in Pass 2).
            b.set_next_anon_placeholder(set_placeholder_count + 1);
            emit_expr(b, target_expr, matched_rowid_reg, None);
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                table_cursor,
                matched_rowid_reg,
                collect_done_label,
                P4::None,
                0,
            );
            if let Some(where_expr) = &stmt.where_clause {
                b.set_next_anon_placeholder(set_placeholder_count + 1);
                emit_where_filter(
                    b,
                    where_expr,
                    table_cursor,
                    table,
                    stmt.table.alias.as_deref(),
                    schema,
                    collect_done_label,
                );
            }
            b.emit_op(
                Opcode::RowSetAdd,
                rowset_reg,
                matched_rowid_reg,
                0,
                P4::None,
                0,
            );
        } else if let Some((idx_schema, target, aff, has_residual)) = index_eq {
            // Fresh read cursor beyond the table + registered index-maintenance cursors. The probe and the
            // residual (if any) number from set_placeholder_count + 1, after the SET placeholders (Pass 2).
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let idx_read_cursor = table_cursor + 1 + table.indexes.len() as i32;
            emit_index_eq_rowset_collect(
                b,
                idx_read_cursor,
                idx_schema,
                target,
                aff,
                rowset_reg,
                matched_rowid_reg,
                table,
                stmt.table.alias.as_deref(),
                schema,
                table_cursor,
                stmt.where_clause.as_ref(),
                set_placeholder_count + 1,
                has_residual,
            );
        } else {
            let collect_start = b.current_addr();
            b.emit_jump_to_label(
                Opcode::Rewind,
                table_cursor,
                0,
                collect_done_label,
                P4::None,
                0,
            );

            let collect_skip_label = b.emit_label();
            if let Some(where_expr) = &stmt.where_clause {
                b.set_next_anon_placeholder(set_placeholder_count + 1);
                emit_where_filter(
                    b,
                    where_expr,
                    table_cursor,
                    table,
                    stmt.table.alias.as_deref(),
                    schema,
                    collect_skip_label,
                );
            }

            b.emit_op(
                Opcode::Rowid,
                table_cursor,
                matched_rowid_reg,
                0,
                P4::None,
                0,
            );
            b.emit_op(
                Opcode::RowSetAdd,
                rowset_reg,
                matched_rowid_reg,
                0,
                P4::None,
                0,
            );
            b.resolve_label(collect_skip_label);
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let collect_body = (collect_start + 1) as i32;
            b.emit_op(Opcode::Next, table_cursor, collect_body, 0, P4::None, 0);
        }
        b.resolve_label(collect_done_label);

        // Pass 2: revisit each matched rowid and perform the delete+insert rewrite.
        let apply_loop = b.current_addr();
        b.emit_jump_to_label(
            Opcode::RowSetRead,
            rowset_reg,
            matched_rowid_reg,
            apply_done_label,
            P4::None,
            0,
        );
        let apply_seek_miss_label = b.emit_label();
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            table_cursor,
            matched_rowid_reg,
            apply_seek_miss_label,
            P4::None,
            0,
        );
        (Some(apply_seek_miss_label), Some(apply_loop))
    };

    // Read ALL existing columns into registers.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let col_regs = b.alloc_regs(n_cols as i32);
    for i in 0..n_cols {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let target_reg = col_regs + i as i32;
        if table.columns.get(i).is_some_and(|col| col.is_ipk) {
            // INTEGER PRIMARY KEY columns alias rowid and are not stored in
            // the record payload. Materialize from Rowid so unchanged UPDATE
            // rewrites preserve the original key instead of generating a new
            // rowid.
            b.emit_op(Opcode::Rowid, table_cursor, target_reg, 0, P4::None, 0);
        } else {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            b.emit_op(
                Opcode::Column,
                table_cursor,
                i as i32,
                target_reg,
                P4::None,
                0,
            );
        }
    }

    // Evaluate new values from AST expressions and overwrite changed columns.
    // A ScanCtx is required so that column references in SET expressions
    // (e.g., `SET val = val + 5`) resolve to the cursor's current row.
    //
    // NOTE: index deletes and the row Delete are deferred until AFTER constraint
    // validation below. Index key terms and the old indexed values are read
    // straight from the table cursor (which still points at the unchanged old
    // row), so deferring them is safe — and it is *required* so that an
    // `UPDATE OR IGNORE` whose new row fails a CHECK / NOT NULL constraint can
    // skip the row without having already destroyed it (matching C SQLite,
    // which validates constraints before applying any mutation).
    let update_ctx = ScanCtx {
        cursor: table_cursor,
        table,
        table_alias: stmt.table.alias.as_deref(),
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    // Reset placeholder counter to 1 for SET expressions (they appear first in SQL text).
    b.set_next_anon_placeholder(1);
    emit_update_assignments(b, &stmt.assignments, table, col_regs, &update_ctx)?;

    // Recompute STORED generated columns and validate constraints on the NEW
    // row image BEFORE any destructive mutation, so OR IGNORE can bail out
    // cleanly. (A second `emit_stored_generated_columns` is intentionally NOT
    // emitted later — the values computed here are reused for MakeRecord.)
    emit_stored_generated_columns(b, table, col_regs);
    // For UPDATE OR IGNORE, a failing CHECK or NOT NULL constraint must skip
    // this row silently rather than aborting the statement (C SQLite
    // semantics). Route the skip to the next matched row: the full-scan apply
    // loop re-enters via `apply_seek_miss_label` (which Gotos `apply_loop`),
    // while a single rowid-target update simply jumps to `apply_done_label`.
    let constraint_ignore_label =
        if matches!(stmt.or_conflict.as_ref(), Some(ConflictAction::Ignore)) {
            Some(apply_seek_miss_label.unwrap_or(apply_done_label))
        } else {
            None
        };
    emit_strict_type_check(b, table, col_regs);
    // GH #169: coerce to column affinity before CHECK/NOT NULL so the
    // constraints see the affinity-coerced value (SQLite applies affinity, then
    // evaluates constraints).
    b.emit_op(
        Opcode::Affinity,
        col_regs,
        n_cols as i32,
        0,
        P4::Affinity(table.affinity_string()),
        0,
    );
    emit_check_constraints(b, table, col_regs, constraint_ignore_label);
    emit_not_null_constraints(
        b,
        table,
        col_regs,
        stmt.or_conflict,
        constraint_ignore_label,
    );

    // Constraints passed: now perform the destructive delete+insert rewrite.
    // Index maintenance (bd-2f9t): Delete OLD index entries. The indexed key
    // terms are re-read from the table cursor's still-current old row.
    emit_index_deletes_for_update(b, table, table_cursor, &update_index_mask);

    // UPDATE is delete+insert: remove the current row first, then insert the
    // rewritten record (possibly at a new rowid).
    b.emit_op(
        Opcode::Delete,
        table_cursor,
        0,
        0,
        P4::None,
        OPFLAG_ISUPDATE,
    );

    // Determine destination rowid for re-insertion.
    let mut rowid_reg = matched_rowid_reg;
    let rowid_alias_col_idx = ctx
        .rowid_alias_col_idx
        .or_else(|| table.columns.iter().position(|col| col.is_ipk));
    if let Some(ipk_idx) = rowid_alias_col_idx {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let ipk_reg = col_regs + ipk_idx as i32;
        let auto_label = b.emit_label();
        let rowid_done_label = b.emit_label();
        let concurrent_flag = i32::from(ctx.concurrent_mode);

        rowid_reg = b.alloc_reg();

        // If the rewritten IPK is NULL, allocate a new rowid.
        b.emit_jump_to_label(Opcode::IsNull, ipk_reg, 0, auto_label, P4::None, 0);
        b.emit_op(Opcode::Copy, ipk_reg, rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, rowid_done_label, P4::None, 0);

        b.resolve_label(auto_label);
        b.emit_op(
            Opcode::NewRowid,
            table_cursor,
            rowid_reg,
            concurrent_flag,
            P4::None,
            0,
        );
        // Keep the IPK payload column consistent with the chosen rowid.
        b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);
        b.resolve_label(rowid_done_label);
    }

    // STORED generated columns and constraint validation already ran above on
    // the new row image (before the destructive delete), so MakeRecord can use
    // col_regs directly.
    // Apply column type affinities before packing the record.
    let aff_str = table.affinity_string();
    let rec_reg = b.alloc_reg();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let n_cols_i32 = n_cols as i32;
    b.emit_op(
        Opcode::Affinity,
        col_regs,
        n_cols_i32,
        0,
        P4::Affinity(aff_str.clone()),
        0,
    );
    b.emit_op(
        Opcode::MakeRecord,
        col_regs,
        n_cols_i32,
        rec_reg,
        P4::Affinity(aff_str),
        0,
    );

    // Conflict resolution for UPDATE: use explicit OR clause if present,
    // otherwise default to OE_ABORT (standard UPDATE raises constraint error
    // on PK/UNIQUE conflicts rather than silently replacing).
    let oe_flag = conflict_action_to_oe(stmt.or_conflict.as_ref());
    b.emit_op(
        Opcode::Insert,
        table_cursor,
        rec_reg,
        rowid_reg,
        P4::Table(table.name.clone()),
        oe_flag | OPFLAG_ISUPDATE,
    );

    // Index maintenance (bd-2f9t): Insert NEW index entries after table insert.
    // col_regs now contains NEW column values.
    emit_index_inserts_for_update(
        b,
        table,
        table_cursor,
        col_regs,
        rowid_reg,
        stmt.or_conflict,
        &update_index_mask,
    );

    // RETURNING clause: position cursor on updated row and read columns.
    if !stmt.returning.is_empty() {
        // GH #159: UPDATE OR IGNORE ... RETURNING must NOT emit a row whose
        // insert the engine suppressed on a rowid/UNIQUE conflict — it already
        // rolled the write back, so re-seeking `rowid_reg` here would wrongly
        // emit either the un-updated row (same rowid) or the CONFLICTING row's
        // data (new rowid). `constraint_ignore_label` is `Some` iff this is an
        // OR IGNORE update; jump past RETURNING to the row-skip label when the
        // engine's own conflict decision (`conflict_skip_idx`) is set.
        if let Some(skip) = constraint_ignore_label {
            b.emit_jump_to_label(Opcode::IfConflictSkip, 0, 0, skip, P4::None, 0);
        }
        // RETURNING appears after WHERE in SQL textual order; restore the
        // post-WHERE placeholder index so RETURNING placeholders don't collide
        // with SET placeholder numbering.
        b.set_next_anon_placeholder(set_placeholder_count + where_placeholder_count + 1);
        emit_returning(
            b,
            table_cursor,
            table,
            &stmt.returning,
            stmt.table.alias.as_deref(),
            rowid_reg,
        )?;
    }

    if let (Some(apply_seek_miss_label), Some(apply_loop)) = (apply_seek_miss_label, apply_loop) {
        b.resolve_label(apply_seek_miss_label);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let apply_loop_addr = apply_loop as i32;
        b.emit_op(Opcode::Goto, 0, apply_loop_addr, 0, P4::None, 0);
    }

    // Done: Close index cursors, then table cursor.
    b.resolve_label(apply_done_label);
    b.resolve_label(done_label);
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    for idx_offset in 0..table.indexes.len() {
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Close, table_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End label.
    b.resolve_label(end_label);

    Ok(())
}

fn collect_update_assignment_columns(
    table: &TableSchema,
    assignments: &[fsqlite_ast::Assignment],
) -> Result<Vec<usize>, CodegenError> {
    let mut columns = Vec::with_capacity(assignments.len());
    for assignment in assignments {
        match &assignment.target {
            AssignmentTarget::Column(name) => {
                columns.push(table.column_index(name).ok_or_else(|| {
                    CodegenError::ColumnNotFound {
                        table: table.name.clone(),
                        column: name.to_owned(),
                    }
                })?);
            }
            AssignmentTarget::ColumnList(names) => {
                if names.is_empty() {
                    return Err(CodegenError::Unsupported(
                        "multi-column SET requires at least one target column".to_owned(),
                    ));
                }
                for name in names {
                    columns.push(table.column_index(name).ok_or_else(|| {
                        CodegenError::ColumnNotFound {
                            table: table.name.clone(),
                            column: name.to_owned(),
                        }
                    })?);
                }
            }
        }
    }
    Ok(columns)
}

/// Number of statically-known result columns in a subquery used as the RHS of a
/// row-value UPDATE `SET (a, b) = (SELECT ...)`. Returns `None` for shapes whose
/// arity is not knowable here (compound SELECT, `VALUES`, or `*` / `table.*`
/// result columns), which the caller turns into a clear diagnostic.
fn row_value_subquery_arity(select: &SelectStatement) -> Option<usize> {
    if !select.body.compounds.is_empty() {
        return None;
    }
    let SelectCore::Select { columns, .. } = &select.body.select else {
        return None;
    };
    if columns
        .iter()
        .any(|c| !matches!(c, ResultColumn::Expr { .. }))
    {
        return None;
    }
    Some(columns.len())
}

/// Project a row-value subquery down to its `col_idx`-th result column so it can
/// be emitted as a scalar subquery feeding a single UPDATE `SET` target. The
/// FROM/WHERE/ORDER BY/LIMIT are preserved verbatim, so each projected column is
/// drawn from the same (first) row and correlation against the outer UPDATE row
/// is retained. Returns `None` for the same unsupported shapes as
/// [`row_value_subquery_arity`].
fn project_row_value_subquery_column(
    select: &SelectStatement,
    col_idx: usize,
) -> Option<SelectStatement> {
    if !select.body.compounds.is_empty() {
        return None;
    }
    let SelectCore::Select { columns, .. } = &select.body.select else {
        return None;
    };
    let target = columns.get(col_idx)?;
    if !matches!(target, ResultColumn::Expr { .. }) {
        return None;
    }
    let target = target.clone();
    let mut projected = select.clone();
    if let SelectCore::Select { columns, .. } = &mut projected.body.select {
        *columns = vec![target];
    }
    Some(projected)
}

fn emit_update_assignments(
    b: &mut ProgramBuilder,
    assignments: &[fsqlite_ast::Assignment],
    table: &TableSchema,
    col_regs: i32,
    scan: &ScanCtx<'_>,
) -> Result<(), CodegenError> {
    for assignment in assignments {
        match &assignment.target {
            AssignmentTarget::Column(name) => {
                let col_idx =
                    table
                        .column_index(name)
                        .ok_or_else(|| CodegenError::ColumnNotFound {
                            table: table.name.clone(),
                            column: name.to_owned(),
                        })?;
                #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                let target_reg = col_regs + col_idx as i32;
                emit_expr(b, &assignment.value, target_reg, Some(scan));
            }
            AssignmentTarget::ColumnList(names) => match &assignment.value {
                // `SET (a, b) = (e1, e2)` — parenthesized row-value of scalars.
                Expr::RowValue(values, _) => {
                    if names.len() != values.len() {
                        return Err(CodegenError::Unsupported(format!(
                            "multi-column SET arity mismatch: {} targets, {} values",
                            names.len(),
                            values.len()
                        )));
                    }
                    for (name, value) in names.iter().zip(values) {
                        let col_idx = table.column_index(name).ok_or_else(|| {
                            CodegenError::ColumnNotFound {
                                table: table.name.clone(),
                                column: name.to_owned(),
                            }
                        })?;
                        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                        let target_reg = col_regs + col_idx as i32;
                        emit_expr(b, value, target_reg, Some(scan));
                    }
                }
                // `SET (a, b) = (SELECT a, b FROM ...)` — a row-value whose RHS is
                // a (possibly correlated) subquery. Each target column is fed by
                // the matching output column of the subquery; project the subquery
                // one column at a time and reuse the scalar-subquery emitter, which
                // resolves correlation against the outer UPDATE row via `scan`.
                // bd-6utze.
                Expr::Subquery(select, _) => {
                    let arity = row_value_subquery_arity(select).ok_or_else(|| {
                        CodegenError::Unsupported(
                            "multi-column SET subquery source must be a single SELECT with \
                             explicit result columns (no '*' or compound SELECT)"
                                .to_owned(),
                        )
                    })?;
                    if names.len() != arity {
                        return Err(CodegenError::Unsupported(format!(
                            "multi-column SET arity mismatch: {} targets, {} subquery columns",
                            names.len(),
                            arity
                        )));
                    }
                    for (col_pos, name) in names.iter().enumerate() {
                        let col_idx = table.column_index(name).ok_or_else(|| {
                            CodegenError::ColumnNotFound {
                                table: table.name.clone(),
                                column: name.to_owned(),
                            }
                        })?;
                        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                        let target_reg = col_regs + col_idx as i32;
                        let projected = project_row_value_subquery_column(select, col_pos)
                            .expect("subquery shape validated by row_value_subquery_arity");
                        if let Some(schema) = scan.schema {
                            emit_scalar_subquery(b, &projected, target_reg, scan, schema);
                        } else {
                            b.emit_op(Opcode::Null, 0, target_reg, 0, P4::None, 0);
                        }
                    }
                }
                // A single-target list `(v) = <scalar>` is equivalent to
                // `v = <scalar>`. This also catches `(v) = (SELECT ...)` whose
                // uncorrelated scalar subquery the DML rewrite pass already folded
                // to a literal before codegen (so it arrives as a plain expr).
                scalar if names.len() == 1 => {
                    let name = &names[0];
                    let col_idx =
                        table
                            .column_index(name)
                            .ok_or_else(|| CodegenError::ColumnNotFound {
                                table: table.name.clone(),
                                column: name.to_owned(),
                            })?;
                    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                    let target_reg = col_regs + col_idx as i32;
                    emit_expr(b, scalar, target_reg, Some(scan));
                }
                _ => {
                    return Err(CodegenError::Unsupported(
                        "multi-column SET requires a row-value or subquery expression".to_owned(),
                    ));
                }
            },
        }
    }
    Ok(())
}

fn update_index_maintenance_mask(table: &TableSchema, assignment_cols: &[usize]) -> Vec<bool> {
    table
        .indexes
        .iter()
        .map(|index| update_must_maintain_index(table, index, assignment_cols))
        .collect()
}

fn update_must_maintain_index(
    table: &TableSchema,
    index: &IndexSchema,
    assignment_cols: &[usize],
) -> bool {
    if assignment_cols
        .iter()
        .any(|col_idx| table.columns.get(*col_idx).is_some_and(|col| col.is_ipk))
    {
        return true;
    }

    if !index.supports_direct_column_lookup() {
        return true;
    }

    if table
        .columns
        .iter()
        .any(|col| col.generated_stored.is_some())
    {
        return true;
    }

    index.columns.iter().any(|column| {
        table
            .column_index(column)
            .is_none_or(|col_idx| assignment_cols.contains(&col_idx))
    })
}

// ---------------------------------------------------------------------------
// UPDATE ... FROM codegen
// ---------------------------------------------------------------------------

/// Emit a Column or Rowid opcode for a column reference against a specific cursor.
fn emit_column_from_cursor(
    b: &mut ProgramBuilder,
    col_name: &str,
    cursor: i32,
    table: &TableSchema,
    reg: i32,
) {
    if let Some(col_idx) = table.column_index(col_name) {
        if table.columns[col_idx].is_ipk {
            b.emit_op(Opcode::Rowid, cursor, reg, 0, P4::None, 0);
        } else {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            b.emit_op(Opcode::Column, cursor, col_idx as i32, reg, P4::None, 0);
        }
    } else if table.resolves_to_hidden_rowid(col_name) {
        b.emit_op(Opcode::Rowid, cursor, reg, 0, P4::None, 0);
    } else {
        b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
    }
}

/// Emit a column read against a [`SecondaryScan`], honoring a register-backed
/// source when present. A cursor-backed secondary (UPDATE ... FROM) reads the
/// B-tree; a register-backed secondary (the UPSERT `excluded.*` pseudo-row,
/// bd-xjfrt) copies the attempted-insert value from `register_base + col_idx`.
/// The IPK column register is kept in sync with the rowid at INSERT codegen, so
/// a plain copy is correct for it too.
fn emit_secondary_column(b: &mut ProgramBuilder, col_name: &str, sec: &SecondaryScan<'_>, reg: i32) {
    if let Some(base) = sec.register_base {
        if let Some(col_idx) = sec.table.column_index(col_name) {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            b.emit_op(Opcode::Copy, base + col_idx as i32, reg, 0, P4::None, 0);
        } else {
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
        }
    } else {
        emit_column_from_cursor(b, col_name, sec.cursor, sec.table, reg);
    }
}

/// Generate VDBE bytecode for `UPDATE target SET ... FROM source WHERE ...`.
///
/// Uses a nested-loop join: outer loop scans the FROM table, inner loop scans
/// the target table. WHERE clause filters for the join condition.
#[allow(clippy::too_many_lines)]
fn codegen_update_from(
    b: &mut ProgramBuilder,
    stmt: &UpdateStatement,
    from_clause: &FromClause,
    schema: &[TableSchema],
    ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    use fsqlite_ast::{JoinConstraint, JoinKind};

    // Resolve a single FROM source to (name, alias). Only named tables are
    // supported in VDBE codegen: a single `FROM (subquery)` is flattened to a
    // named table before codegen (try_flatten_update_from_subquery in
    // connection.rs), and codegen has no general FROM-relation materialization.
    fn resolve_from_table(src: &TableOrSubquery) -> Result<(&str, Option<&str>), CodegenError> {
        match src {
            TableOrSubquery::Table { name, alias, .. } => {
                Ok((name.name.as_str(), alias.as_deref()))
            }
            TableOrSubquery::Subquery { .. } => Err(CodegenError::Unsupported(
                "UPDATE ... FROM subquery sources are not yet supported (only named tables; \
                 a single FROM (subquery) is flattened before codegen)"
                    .to_owned(),
            )),
            _ => Err(CodegenError::Unsupported(
                "UPDATE ... FROM only supports named tables".to_owned(),
            )),
        }
    }

    // Collect every FROM source (the leading source plus comma/JOIN sources)
    // and the ON conditions of any joins. Comma sources and CROSS/INNER joins
    // form a cross product filtered by (ON conditions AND WHERE); this matches
    // SQLite's UPDATE ... FROM semantics for inner joins.
    let mut from_specs: Vec<(&str, Option<&str>)> = Vec::with_capacity(1 + from_clause.joins.len());
    from_specs.push(resolve_from_table(&from_clause.source)?);

    let mut on_conditions: Vec<&Expr> = Vec::new();
    for join in &from_clause.joins {
        if join.join_type.natural {
            return Err(CodegenError::Unsupported(
                "UPDATE ... FROM with NATURAL JOIN is not yet supported".to_owned(),
            ));
        }
        match join.join_type.kind {
            JoinKind::Inner | JoinKind::Cross => {}
            JoinKind::Left | JoinKind::Right | JoinKind::Full => {
                return Err(CodegenError::Unsupported(
                    "UPDATE ... FROM with an OUTER JOIN source is not yet supported".to_owned(),
                ));
            }
        }
        from_specs.push(resolve_from_table(&join.table)?);
        match &join.constraint {
            Some(JoinConstraint::On(expr)) => on_conditions.push(expr),
            Some(JoinConstraint::Using(_)) => {
                return Err(CodegenError::Unsupported(
                    "UPDATE ... FROM with a USING(...) join constraint is not yet supported"
                        .to_owned(),
                ));
            }
            None => {}
        }
    }

    let table_name = table_name_from_qualified(&stmt.table);
    let target = find_table(schema, table_name)?;
    let n_cols = target.columns.len();

    // Resolve each FROM source to its schema and assign a read cursor.
    // Cursor allocation: 0 = target (write), 1..=K = target indexes,
    // K+1.. = one read cursor per FROM source.
    let target_cursor = 0_i32;
    let n_indexes = target.indexes.len();
    let mut secondaries: Vec<SecondaryScan> = Vec::with_capacity(from_specs.len());
    for (i, (src_name, src_alias)) in from_specs.iter().enumerate() {
        let src_table = find_table(schema, src_name)?;
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let cursor = (1 + n_indexes + i) as i32;
        secondaries.push(SecondaryScan {
            cursor,
            table: src_table,
            table_alias: *src_alias,
            register_base: None,
        });
    }

    let end_label = b.emit_label();

    // Init.
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);

    // Transaction (write).
    b.emit_op(Opcode::Transaction, 0, 1, 0, P4::None, 0);

    // Validate assignment targets before emitting loops.
    collect_update_assignment_columns(target, &stmt.assignments)?;

    // Scan context with all FROM sources for multi-table column resolution.
    let scan = ScanCtx {
        cursor: target_cursor,
        table: target,
        table_alias: stmt.table.alias.as_deref(),
        schema: Some(schema),
        register_base: None,
        secondaries: &secondaries,
    };
    for assign in &stmt.assignments {
        validate_scan_expr_columns(&assign.value, &scan)?;
    }
    for cond in &on_conditions {
        validate_scan_expr_columns(cond, &scan)?;
    }
    if let Some(where_expr) = &stmt.where_clause {
        validate_scan_expr_columns(where_expr, &scan)?;
    }
    validate_single_table_result_columns(
        &stmt.returning,
        target,
        stmt.table.alias.as_deref(),
        stmt.table.name.schema.as_deref(),
    )?;

    // OpenWrite for target table.
    b.emit_op(
        Opcode::OpenWrite,
        target_cursor,
        target.root_page,
        0,
        P4::Table(target.name.clone()),
        0,
    );

    // OpenWrite for each index on target.
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    for (idx_offset, index) in target.indexes.iter().enumerate() {
        let idx_cursor = target_cursor + 1 + idx_offset as i32;
        b.emit_op(
            Opcode::OpenWrite,
            idx_cursor,
            index.root_page,
            0,
            P4::Table(index.name.clone()),
            0,
        );
    }
    register_table_index_meta(b, target, target_cursor);

    // OpenRead for each FROM source.
    for sec in &secondaries {
        b.emit_op(
            Opcode::OpenRead,
            sec.cursor,
            sec.table.root_page,
            0,
            P4::Table(sec.table.name.clone()),
            0,
        );
    }

    // Emit one nested scan loop per FROM source (outermost = first source),
    // recording each loop's body address (Next target) and done label.
    struct LoopFrame {
        cursor: i32,
        body: i32,
        done: Label,
    }
    let mut frames: Vec<LoopFrame> = Vec::with_capacity(secondaries.len());
    for sec in &secondaries {
        let done = b.emit_label();
        b.emit_jump_to_label(Opcode::Rewind, sec.cursor, 0, done, P4::None, 0);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let body = b.current_addr() as i32;
        frames.push(LoopFrame {
            cursor: sec.cursor,
            body,
            done,
        });
    }

    // Innermost loop: scan target table.
    let target_done_label = b.emit_label();
    b.emit_jump_to_label(
        Opcode::Rewind,
        target_cursor,
        0,
        target_done_label,
        P4::None,
        0,
    );
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let target_body = b.current_addr() as i32;

    // Count anonymous placeholders so each clause numbers from the right base.
    // SQL textual order: SET, then FROM (ON conditions), then WHERE, then
    // RETURNING.
    let set_placeholder_count: u32 = stmt
        .assignments
        .iter()
        .map(|a| count_anon_placeholders(&a.value))
        .sum();
    let on_placeholder_count: u32 = on_conditions
        .iter()
        .map(|e| count_anon_placeholders(e))
        .sum();
    let where_placeholder_count: u32 = stmt
        .where_clause
        .as_ref()
        .map_or(0, count_anon_placeholders);

    // Combined filter: each ON condition (in join order) then the WHERE clause.
    // Any failed condition jumps to skip_label (the innermost loop's Next).
    let skip_label = b.emit_label();
    let filter_conditions: Vec<&Expr> = on_conditions
        .iter()
        .copied()
        .chain(stmt.where_clause.as_ref())
        .collect();
    if !filter_conditions.is_empty() {
        // Placeholders in ON/WHERE follow the SET placeholders textually.
        b.set_next_anon_placeholder(set_placeholder_count + 1);
        for cond in &filter_conditions {
            let cond_reg = b.alloc_temp();
            emit_expr(b, cond, cond_reg, Some(&scan));
            b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, skip_label, P4::None, 0);
            b.free_temp(cond_reg);
        }
    }

    // Read ALL existing columns from target into registers.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let col_regs = b.alloc_regs(n_cols as i32);
    for i in 0..n_cols {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let target_reg = col_regs + i as i32;
        if target.columns.get(i).is_some_and(|col| col.is_ipk) {
            b.emit_op(Opcode::Rowid, target_cursor, target_reg, 0, P4::None, 0);
        } else {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            b.emit_op(
                Opcode::Column,
                target_cursor,
                i as i32,
                target_reg,
                P4::None,
                0,
            );
        }
    }

    // Evaluate SET assignments. Reset placeholder counter to 1 (SET first in SQL
    // text). The scan cursor still points at the OLD row here, so `SET x = x + 1`
    // observes the pre-update value.
    b.set_next_anon_placeholder(1);
    emit_update_assignments(b, &stmt.assignments, target, col_regs, &scan)?;

    // Capture the old rowid before any destructive mutation (re-insertion base).
    let old_rowid_reg = b.alloc_reg();
    b.emit_op(Opcode::Rowid, target_cursor, old_rowid_reg, 0, P4::None, 0);

    // Recompute STORED generated columns, then validate CHECK / NOT NULL on the
    // NEW row image BEFORE any destructive mutation — so an `UPDATE OR IGNORE
    // ... FROM ...` whose new row fails a constraint can skip the row WITHOUT
    // having already deleted the old one (bd-xoixz). This mirrors the plain
    // `codegen_update` path, which defers the index deletes + row Delete until
    // after constraint validation. `constraint_ignore_label` routes a violation
    // to the innermost loop's Next (`skip_label`); the FROM-path uniqueness /
    // RETURNING conflict skip already uses this same label (IfConflictSkip).
    emit_stored_generated_columns(b, target, col_regs);
    emit_strict_type_check(b, target, col_regs);
    // GH #169: coerce to column affinity before CHECK/NOT NULL so the
    // constraints see the affinity-coerced value (SQLite applies affinity, then
    // evaluates constraints).
    b.emit_op(
        Opcode::Affinity,
        col_regs,
        n_cols as i32,
        0,
        P4::Affinity(target.affinity_string()),
        0,
    );
    let constraint_ignore_label =
        if matches!(stmt.or_conflict.as_ref(), Some(ConflictAction::Ignore)) {
            Some(skip_label)
        } else {
            None
        };
    emit_check_constraints(b, target, col_regs, constraint_ignore_label);
    emit_not_null_constraints(
        b,
        target,
        col_regs,
        stmt.or_conflict,
        constraint_ignore_label,
    );

    // Constraints passed: NOW perform the destructive delete+insert. Old index
    // entries are read from the cursor (still positioned on the unchanged old
    // row) before the row Delete.
    emit_index_deletes(b, target, target_cursor);
    b.emit_op(
        Opcode::Delete,
        target_cursor,
        0,
        0,
        P4::None,
        OPFLAG_ISUPDATE,
    );

    // Determine destination rowid.
    let mut rowid_reg = old_rowid_reg;
    let rowid_alias_col_idx = ctx
        .rowid_alias_col_idx
        .or_else(|| target.columns.iter().position(|col| col.is_ipk));
    if let Some(ipk_idx) = rowid_alias_col_idx {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let ipk_reg = col_regs + ipk_idx as i32;
        let auto_label = b.emit_label();
        let rowid_done_label = b.emit_label();
        let concurrent_flag = i32::from(ctx.concurrent_mode);

        rowid_reg = b.alloc_reg();

        b.emit_jump_to_label(Opcode::IsNull, ipk_reg, 0, auto_label, P4::None, 0);
        b.emit_op(Opcode::Copy, ipk_reg, rowid_reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, rowid_done_label, P4::None, 0);

        b.resolve_label(auto_label);
        b.emit_op(
            Opcode::NewRowid,
            target_cursor,
            rowid_reg,
            concurrent_flag,
            P4::None,
            0,
        );
        b.emit_op(Opcode::Copy, rowid_reg, ipk_reg, 0, P4::None, 0);
        b.resolve_label(rowid_done_label);
    }

    let aff_str = target.affinity_string();
    let rec_reg = b.alloc_reg();
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let n_cols_i32 = n_cols as i32;
    b.emit_op(
        Opcode::Affinity,
        col_regs,
        n_cols_i32,
        0,
        P4::Affinity(aff_str.clone()),
        0,
    );
    b.emit_op(
        Opcode::MakeRecord,
        col_regs,
        n_cols_i32,
        rec_reg,
        P4::Affinity(aff_str),
        0,
    );

    // Insert updated row.
    let oe_flag = conflict_action_to_oe(stmt.or_conflict.as_ref());
    b.emit_op(
        Opcode::Insert,
        target_cursor,
        rec_reg,
        rowid_reg,
        P4::Table(target.name.clone()),
        oe_flag | OPFLAG_ISUPDATE,
    );

    // Insert new index entries.
    emit_index_inserts(
        b,
        target,
        target_cursor,
        col_regs,
        rowid_reg,
        stmt.or_conflict,
    );

    // RETURNING clause (numbered after SET + ON + WHERE placeholders).
    if !stmt.returning.is_empty() {
        // GH #159: as in the plain UPDATE path, an OR IGNORE row whose insert
        // the engine suppressed on a rowid/UNIQUE conflict must not emit a
        // RETURNING row. Jump past RETURNING to the loop's skip label when the
        // engine's conflict_skip_idx is set.
        if matches!(stmt.or_conflict.as_ref(), Some(ConflictAction::Ignore)) {
            b.emit_jump_to_label(Opcode::IfConflictSkip, 0, 0, skip_label, P4::None, 0);
        }
        b.set_next_anon_placeholder(
            set_placeholder_count + on_placeholder_count + where_placeholder_count + 1,
        );
        emit_returning(
            b,
            target_cursor,
            target,
            &stmt.returning,
            stmt.table.alias.as_deref(),
            rowid_reg,
        )?;
    }

    // Skip label for filtered-out rows.
    b.resolve_label(skip_label);

    // Innermost (target) Next: loop back to the target loop body.
    b.emit_op(Opcode::Next, target_cursor, target_body, 0, P4::None, 0);
    b.resolve_label(target_done_label);

    // Unwind the FROM-source loops from innermost to outermost. Each loop's
    // Next jumps back to its body; its done label lands here so an exhausted or
    // empty source falls through to the next-outer loop's Next.
    for frame in frames.iter().rev() {
        b.emit_op(Opcode::Next, frame.cursor, frame.body, 0, P4::None, 0);
        b.resolve_label(frame.done);
    }

    // Close all cursors.
    for sec in &secondaries {
        b.emit_op(Opcode::Close, sec.cursor, 0, 0, P4::None, 0);
    }
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    for idx_offset in 0..target.indexes.len() {
        let idx_cursor = target_cursor + 1 + idx_offset as i32;
        b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    }
    b.emit_op(Opcode::Close, target_cursor, 0, 0, P4::None, 0);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End label.
    b.resolve_label(end_label);

    Ok(())
}

// ---------------------------------------------------------------------------
// DELETE codegen
// ---------------------------------------------------------------------------

/// True when every present bound of `range` is an integer literal — so a Pass-1 rowid-range collection
/// emits the bounds as constants (no anonymous placeholders) and the seek+stop bounds are exact (no WHERE
/// filter needed). bd-delete-rowid-range / bd-update-rowid-range.
fn rowid_range_bounds_are_int_literals(range: &RowidRangeTarget<'_>) -> bool {
    let is_int = |bound: Option<RowidRangeBound<'_>>| {
        bound.is_none_or(|b| matches!(b.expr, Expr::Literal(Literal::Integer(_), _)))
    };
    is_int(range.lower) && is_int(range.upper)
}

/// DELETE/UPDATE Pass-1 rowid-range collection: position at the lower bound (`SeekGE`/`SeekGT`, or
/// `Rewind` when unbounded below), walk forward adding each rowid to the RowSet, and stop once past the
/// upper bound (`Gt`/`Ge`). Mirrors the ascending walk of `codegen_select_rowid_range_scan` but collects
/// rowids instead of emitting rows. Requires integer-literal bounds (`rowid_range_bounds_are_int_literals`),
/// so it emits no anonymous placeholders and needs no WHERE filter (the bounds are exact). The caller
/// resolves `collect_done_label` after this returns (the trailing `Next` falls through to it on
/// exhaustion). bd-delete-rowid-range / bd-update-rowid-range.
#[allow(clippy::too_many_arguments)]
fn emit_rowid_range_rowset_collect(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    table_cursor: i32,
    rowset_reg: i32,
    rowid_reg: i32,
    collect_done_label: crate::Label,
    range: RowidRangeTarget<'_>,
) {
    let lower_reg = range.lower.map(|bound| {
        let r = b.alloc_reg();
        emit_expr(b, bound.expr, r, None);
        r
    });
    let upper_reg = range.upper.map(|bound| {
        let r = b.alloc_reg();
        emit_expr(b, bound.expr, r, None);
        r
    });
    let upper_comparison = range
        .upper
        .map(|bound| resolved_rowid_range_comparison(table, table_alias, schema, bound));

    let collect_start = b.current_addr();
    if let Some(bound) = range.lower {
        let seek_opcode = if bound.inclusive {
            Opcode::SeekGE
        } else {
            Opcode::SeekGT
        };
        b.emit_jump_to_label(
            seek_opcode,
            table_cursor,
            lower_reg.expect("lower bound register should exist"),
            collect_done_label,
            P4::None,
            0,
        );
    } else {
        b.emit_jump_to_label(
            Opcode::Rewind,
            table_cursor,
            0,
            collect_done_label,
            P4::None,
            0,
        );
    }

    // Loop body (collect_start + 1): read the rowid, stop once past the upper bound, else add it.
    b.emit_op(Opcode::Rowid, table_cursor, rowid_reg, 0, P4::None, 0);
    if let Some(bound) = range.upper {
        let stop_opcode = if bound.inclusive {
            Opcode::Gt
        } else {
            Opcode::Ge
        };
        b.emit_jump_to_label(
            stop_opcode,
            upper_reg.expect("upper bound register should exist"),
            rowid_reg,
            collect_done_label,
            upper_comparison
                .as_ref()
                .map_or(P4::None, |c| c.collation_p4.clone()),
            upper_comparison.as_ref().map_or(0, |c| c.cmp_p5),
        );
    }
    b.emit_op(Opcode::RowSetAdd, rowset_reg, rowid_reg, 0, P4::None, 0);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let collect_body = (collect_start + 1) as i32;
    b.emit_op(Opcode::Next, table_cursor, collect_body, 0, P4::None, 0);
}

/// `(index, target)` for a DELETE/UPDATE `WHERE <col> = <value>` served by a single-column ASCENDING
/// INTEGER-affinity ('D') index. The value is a literal OR a placeholder (`is_simple_constant`): the
/// collect coerces the probe to the column's affinity (`Opcode::Affinity`, like the index-range path) so
/// a runtime-typed bound seeks identically to the full-scan filter — the seek is then authoritative with
/// no affinity fallback. Bare eq only (`extract_column_eq_target` needs a top-level `col = <expr>`). The
/// rowid case is handled earlier and the IPK has no secondary index, so this never fires for it.
/// bd-delete-index-eq / bd-update-index-eq.
fn index_eq_seek_target<'a, 't>(
    where_clause: Option<&'a Expr>,
    table: &'t TableSchema,
    table_alias: Option<&str>,
) -> Option<(&'t IndexSchema, &'a Expr, char)> {
    let (col_name, target_expr) = extract_column_eq_target(where_clause, table, table_alias)?;
    if !is_simple_constant(target_expr) {
        return None;
    }
    let col_idx = table.column_index(&col_name)?;
    // INTEGER ('D'), NUMERIC ('C'), REAL ('E'), or BINARY-TEXT ('B') affinity: the collect coerces the
    // probe to this affinity so a runtime-typed bound seeks like the affinity-applying full-scan filter.
    let affinity = table.columns.get(col_idx)?.affinity;
    if !matches!(affinity, 'D' | 'C' | 'E' | 'B') {
        return None;
    }
    let idx = table.indexes.iter().find(|idx| {
        idx.supports_direct_column_lookup()
            && idx.key_term_count() == 1
            && !idx.key_term_descending(0)
            && idx
                .columns
                .first()
                .is_some_and(|c| c.eq_ignore_ascii_case(&col_name))
    })?;
    // A TEXT column's seek comparison depends on collation; only BINARY agrees with the coerced probe and
    // the full-scan filter, so a NOCASE/RTRIM index declines (a numeric column has no collation concern).
    if affinity == 'B'
        && !idx
            .key_term_collation(0)
            .is_none_or(|c| c.eq_ignore_ascii_case("BINARY"))
    {
        return None;
    }
    Some((idx, target_expr, affinity))
}

/// `(index, target, affinity, has_residual)` — like [`index_eq_seek_target`] but also admits the eq as a
/// CONJUNCT alongside other predicates the index seek cannot enforce: `<col> = <value> AND <residual>`.
/// The caller applies the full WHERE per candidate (via the table row) before adding it.
/// `has_residual == false` is the bare eq. bd-delete-index-eq-residual / bd-update-index-eq-residual.
fn index_eq_residual_seek_target<'a, 't>(
    where_clause: Option<&'a Expr>,
    table: &'t TableSchema,
    table_alias: Option<&str>,
) -> Option<(&'t IndexSchema, &'a Expr, char, bool)> {
    if let Some((idx, target, aff)) = index_eq_seek_target(where_clause, table, table_alias) {
        return Some((idx, target, aff, false));
    }
    let where_expr = where_clause?;
    let mut conjuncts = Vec::new();
    collect_conjunctive_terms(where_expr, &mut conjuncts);
    if conjuncts.len() < 2 {
        return None;
    }
    for term in conjuncts {
        if let Some((idx, target, aff)) = index_eq_seek_target(Some(term), table, table_alias) {
            return Some((idx, target, aff, true));
        }
    }
    None
}

/// DELETE/UPDATE Pass-1 collection for `WHERE <single-col-ASC-integer-indexed> = <value> [AND
/// <residual>]`: open a FRESH read cursor on the index (distinct from the table cursor and the registered
/// index-maintenance cursors, so Pass 2 is unaffected), seek `(val, i64::MIN)`, walk the equal-value run
/// adding each rowid to the RowSet, then close the cursor. The probe is coerced to the column's 'D'
/// affinity (`Opcode::Affinity`) when it is not already a numeric literal — so a runtime-typed placeholder
/// bound seeks identically to the full-scan filter and the seek is authoritative (no affinity fallback).
/// When `residual_filter` is true, each candidate is positioned on the table cursor and the full WHERE is
/// applied before `RowSetAdd` (no covering decision in a DML collect — the row is always read). Control
/// falls through to `collect_done` (resolved by the caller). bd-delete-index-eq(-residual) /
/// bd-update-index-eq(-residual).
#[allow(clippy::too_many_arguments)]
fn emit_index_eq_rowset_collect(
    b: &mut ProgramBuilder,
    idx_read_cursor: i32,
    idx_schema: &IndexSchema,
    target_expr: &Expr,
    // The indexed column's affinity ('D' integer / 'C' numeric / 'E' real / 'B' binary-text) — coerced
    // onto a runtime-typed probe so it seeks like the affinity-applying comparison would.
    affinity: char,
    rowset_reg: i32,
    rowid_reg: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    table_cursor: i32,
    where_clause: Option<&Expr>,
    // Reset target for the probe's / residual's anon placeholders (`current_anon_placeholder()` for
    // DELETE, `set_placeholder_count + 1` for UPDATE). The probe `col = ?` and the re-applied residual
    // both number from this base.
    where_placeholder_base: u32,
    residual_filter: bool,
) {
    let probe_key_regs = b.alloc_regs(2);
    let min_rowid_reg = probe_key_regs + 1;
    // Emit the probe value, numbering an anon placeholder from the base, and coerce a runtime-typed bound
    // to the column's INTEGER affinity so the seek positions like the affinity-applying comparison would.
    b.set_next_anon_placeholder(where_placeholder_base);
    emit_expr(b, target_expr, probe_key_regs, None);
    if !bound_matches_affinity(affinity, target_expr) {
        b.emit_op(
            Opcode::Affinity,
            probe_key_regs,
            1,
            0,
            P4::Affinity(affinity.to_string()),
            0,
        );
    }
    b.emit_op(Opcode::Int64, 0, min_rowid_reg, 0, P4::Int64(i64::MIN), 0);
    let probe_record_reg = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        probe_key_regs,
        2,
        probe_record_reg,
        P4::None,
        0,
    );
    b.emit_op(
        Opcode::OpenRead,
        idx_read_cursor,
        idx_schema.root_page,
        0,
        P4::Index(idx_schema.name.clone()),
        0,
    );
    let close_label = b.emit_label();
    b.emit_jump_to_label(
        Opcode::SeekGE,
        idx_read_cursor,
        probe_record_reg,
        close_label,
        P4::None,
        0,
    );
    let loop_top = b.current_addr();
    let skip_label = b.emit_label();
    let idx_key_reg = b.alloc_reg();
    b.emit_op(Opcode::Column, idx_read_cursor, 0, idx_key_reg, P4::None, 0);
    b.emit_jump_to_label(
        Opcode::Ne,
        probe_key_regs,
        idx_key_reg,
        close_label,
        direct_lookup_index_comparison_p4(idx_schema),
        0x10,
    );
    b.emit_op(Opcode::IdxRowid, idx_read_cursor, rowid_reg, 0, P4::None, 0);
    if residual_filter && let Some(where_expr) = where_clause {
        // Position the table cursor on the candidate row and apply the full WHERE; a residual miss skips
        // to the next index entry (skip_label = the Next).
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            table_cursor,
            rowid_reg,
            skip_label,
            P4::None,
            0,
        );
        b.set_next_anon_placeholder(where_placeholder_base);
        emit_where_filter(
            b,
            where_expr,
            table_cursor,
            table,
            table_alias,
            schema,
            skip_label,
        );
    }
    b.emit_op(Opcode::RowSetAdd, rowset_reg, rowid_reg, 0, P4::None, 0);
    b.resolve_label(skip_label);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = loop_top as i32;
    b.emit_op(Opcode::Next, idx_read_cursor, loop_body, 0, P4::None, 0);
    b.resolve_label(close_label);
    b.emit_op(Opcode::Close, idx_read_cursor, 0, 0, P4::None, 0);
}

/// Generate VDBE bytecode for a DELETE statement.
///
/// Uses a two-pass plan: collect exact matching rowids without mutating the table, then revisit those
/// rowids to maintain indexes, emit `RETURNING`, and delete. Equality, literal-IN, and lower-bounded
/// literal-range predicates use direct seeks; all other predicates use the general filtered table scan.
pub fn codegen_delete(
    b: &mut ProgramBuilder,
    stmt: &DeleteStatement,
    schema: &[TableSchema],
    _ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    let table_name = table_name_from_qualified(&stmt.table);
    let table = find_table(schema, table_name)?;
    if table.without_rowid {
        return codegen_delete_without_rowid(b, stmt, table, schema, _ctx);
    }
    let table_cursor = 0_i32;

    let end_label = b.emit_label();
    let _done_label = b.emit_label();

    if !stmt.order_by.is_empty() || stmt.limit.is_some() {
        return Err(CodegenError::Unsupported(
            "DELETE ORDER BY/LIMIT/OFFSET must be materialized before codegen".to_owned(),
        ));
    }
    if let Some(where_expr) = &stmt.where_clause {
        validate_single_table_expr_columns(where_expr, table, stmt.table.alias.as_deref())?;
    }
    validate_single_table_result_columns(
        &stmt.returning,
        table,
        stmt.table.alias.as_deref(),
        stmt.table.name.schema.as_deref(),
    )?;

    // Init.
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);

    // Transaction (write).
    b.emit_op(Opcode::Transaction, 0, 1, 0, P4::None, 0);

    // OpenWrite for table.
    b.emit_op(
        Opcode::OpenWrite,
        table_cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );

    // OpenWrite for each index (bd-34se: Phase 5I.4).
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    for (idx_offset, index) in table.indexes.iter().enumerate() {
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        b.emit_op(
            Opcode::OpenWrite,
            idx_cursor,
            index.root_page,
            0,
            P4::Table(index.name.clone()),
            0,
        );
    }

    // Register table-to-index cursor metadata for REPLACE conflict resolution.
    register_table_index_meta(b, table, table_cursor);

    // Two-pass DELETE (matches C SQLite behavior):
    //   Pass 1: Scan table, evaluate WHERE, collect matching rowids into a RowSet.
    //   Pass 2: Iterate collected rowids, seek, and delete.
    // This prevents WHERE subqueries from seeing partially-deleted state.
    let rowset_reg = b.alloc_reg();
    let rowid_reg = b.alloc_reg();

    // Initialize rowset register to NULL.
    b.emit_op(Opcode::Null, 0, rowset_reg, 0, P4::None, 0);

    // --- Pass 1: collect matching rowids ---
    let collect_done_label = b.emit_label();
    let rowid_target = extract_rowid_target_expr(stmt.where_clause.as_ref(), Some(table), None);
    // bd-delete-rowid-in / bd-delete-rowid-in-residual: `DELETE ... WHERE <rowid> IN (<int literals>)
    // [AND <residual>]` collects the listed rows with one `SeekRowid` each instead of full-scanning; when a
    // residual is present it is re-applied per seeked row before adding to the RowSet. After `rowid = const`.
    let rowid_in_list = if rowid_target.is_none() {
        extract_rowid_in_list_residual_target(
            stmt.where_clause.as_ref(),
            table,
            stmt.table.alias.as_deref(),
        )
    } else {
        None
    };
    // bd-delete-rowid-range: `DELETE ... WHERE <rowid> <range>` collects the [lower, upper] slice with a
    // bounded seek+walk (SeekGE/SeekGT to the lower bound, stop past the upper) instead of full-scanning.
    // Bare range only (no residual), integer-literal bounds only (so the walk emits no anon placeholders),
    // and only after the eq / IN cases decline.
    let rowid_range = if rowid_target.is_none() && rowid_in_list.is_none() {
        extract_rowid_range_target(
            stmt.where_clause.as_ref(),
            Some(table),
            stmt.table.alias.as_deref(),
        )
        .filter(|range| {
            range.lower.is_some()
                && rowid_range_fast_path_is_safe(*range)
                && rowid_range_bounds_are_int_literals(range)
        })
    } else {
        None
    };
    // bd-delete-rowid-eq-residual: `DELETE ... WHERE <rowid> = <const> AND <residual>` seeks the single
    // target row and applies the residual, instead of full-scanning — the common compare-and-delete shape.
    let rowid_eq_residual =
        if rowid_target.is_none() && rowid_in_list.is_none() && rowid_range.is_none() {
            extract_rowid_eq_residual_target(
                stmt.where_clause.as_ref(),
                table,
                stmt.table.alias.as_deref(),
            )
        } else {
            None
        };
    // bd-delete-index-eq(-residual): `DELETE ... WHERE <single-col-int-indexed> = <int> [AND <residual>]`
    // seeks the index for the candidate rowids (fresh read cursor), applies the residual per candidate,
    // instead of full-scanning. After all rowid cases decline.
    let index_eq = if rowid_target.is_none()
        && rowid_in_list.is_none()
        && rowid_range.is_none()
        && rowid_eq_residual.is_none()
    {
        index_eq_residual_seek_target(
            stmt.where_clause.as_ref(),
            table,
            stmt.table.alias.as_deref(),
        )
    } else {
        None
    };

    if let Some(target_expr) = rowid_target {
        emit_expr(b, target_expr, rowid_reg, None);
        // Coerce a non-integer-literal rowid key (placeholder / real / text) to INTEGER affinity: a
        // non-exact key (2.5 / 'abc' / NULL) rejects to `collect_done_label` (nothing collected -> no
        // delete) instead of raw `SeekRowid` TRUNCATING it to a wrong rowid (`WHERE id = 2.5` must not
        // delete row 2). Integer literal is exact -> no MustBeInt (byte-identical). Mirrors the SELECT
        // rowid lookup + count/aggregate coerced seeks.
        if !matches!(target_expr, Expr::Literal(Literal::Integer(_), _)) {
            b.emit_jump_to_label(
                Opcode::MustBeInt,
                rowid_reg,
                0,
                collect_done_label,
                P4::None,
                0,
            );
        }
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            table_cursor,
            rowid_reg,
            collect_done_label,
            P4::None,
            0,
        );
        b.emit_op(Opcode::RowSetAdd, rowset_reg, rowid_reg, 0, P4::None, 0);
    } else if let Some((values, has_residual)) = rowid_in_list {
        // One `SeekRowid` per listed value; a miss skips to the next value. When there is a residual, the
        // full WHERE is re-applied per seeked row (the placeholder base is reset each iteration so a `?` in
        // the residual numbers identically). The listed values are sorted+deduped and the RowSet dedups
        // again. Pass 2 is unchanged.
        let where_base = b.current_anon_placeholder();
        for &value in &values {
            let next_value = b.emit_label();
            b.emit_op(Opcode::Int64, 0, rowid_reg, 0, P4::Int64(value), 0);
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                table_cursor,
                rowid_reg,
                next_value,
                P4::None,
                0,
            );
            if has_residual && let Some(where_expr) = &stmt.where_clause {
                b.set_next_anon_placeholder(where_base);
                emit_where_filter(
                    b,
                    where_expr,
                    table_cursor,
                    table,
                    stmt.table.alias.as_deref(),
                    schema,
                    next_value,
                );
            }
            b.emit_op(Opcode::RowSetAdd, rowset_reg, rowid_reg, 0, P4::None, 0);
            b.resolve_label(next_value);
        }
    } else if let Some(range) = rowid_range {
        emit_rowid_range_rowset_collect(
            b,
            table,
            stmt.table.alias.as_deref(),
            schema,
            table_cursor,
            rowset_reg,
            rowid_reg,
            collect_done_label,
            range,
        );
    } else if let Some(target_expr) = rowid_eq_residual {
        // Seek the single target row; a miss or a residual failure jumps to collect_done (nothing to
        // delete). The placeholder base is reset before the re-applied WHERE so a `?` in the residual
        // numbers identically to the `rowid = ?` probe.
        let where_base = b.current_anon_placeholder();
        emit_expr(b, target_expr, rowid_reg, None);
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            table_cursor,
            rowid_reg,
            collect_done_label,
            P4::None,
            0,
        );
        if let Some(where_expr) = &stmt.where_clause {
            b.set_next_anon_placeholder(where_base);
            emit_where_filter(
                b,
                where_expr,
                table_cursor,
                table,
                stmt.table.alias.as_deref(),
                schema,
                collect_done_label,
            );
        }
        b.emit_op(Opcode::RowSetAdd, rowset_reg, rowid_reg, 0, P4::None, 0);
    } else if let Some((idx_schema, target, aff, has_residual)) = index_eq {
        // Fresh read cursor beyond the table + registered index-maintenance cursors.
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let idx_read_cursor = table_cursor + 1 + table.indexes.len() as i32;
        let where_base = b.current_anon_placeholder();
        emit_index_eq_rowset_collect(
            b,
            idx_read_cursor,
            idx_schema,
            target,
            aff,
            rowset_reg,
            rowid_reg,
            table,
            stmt.table.alias.as_deref(),
            schema,
            table_cursor,
            stmt.where_clause.as_ref(),
            where_base,
            has_residual,
        );
    } else {
        let collect_start = b.current_addr();
        b.emit_jump_to_label(
            Opcode::Rewind,
            table_cursor,
            0,
            collect_done_label,
            P4::None,
            0,
        );

        let collect_skip_label = b.emit_label();
        if let Some(where_expr) = &stmt.where_clause {
            emit_where_filter(
                b,
                where_expr,
                table_cursor,
                table,
                stmt.table.alias.as_deref(),
                schema,
                collect_skip_label,
            );
        }

        // Get rowid of matching row and add to rowset.
        b.emit_op(Opcode::Rowid, table_cursor, rowid_reg, 0, P4::None, 0);
        b.emit_op(Opcode::RowSetAdd, rowset_reg, rowid_reg, 0, P4::None, 0);

        b.resolve_label(collect_skip_label);
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let collect_body = (collect_start + 1) as i32;
        b.emit_op(Opcode::Next, table_cursor, collect_body, 0, P4::None, 0);
    }

    b.resolve_label(collect_done_label);

    // --- Pass 2: iterate rowset, seek, and delete ---
    let delete_done_label = b.emit_label();
    let delete_loop = b.current_addr();
    b.emit_jump_to_label(
        Opcode::RowSetRead,
        rowset_reg,
        rowid_reg,
        delete_done_label,
        P4::None,
        0,
    );

    // Seek to the rowid.
    let seek_miss_label = b.emit_label();
    b.emit_jump_to_label(
        Opcode::SeekRowid,
        table_cursor,
        rowid_reg,
        seek_miss_label,
        P4::None,
        0,
    );

    // RETURNING clause: read columns before deletion (row is still present).
    if !stmt.returning.is_empty() {
        let ret_count = result_column_count(&stmt.returning, table);
        let ret_regs = b.alloc_regs(ret_count);
        emit_column_reads(
            b,
            table_cursor,
            &stmt.returning,
            table,
            stmt.table.alias.as_deref(),
            schema,
            ret_regs,
        )?;
        b.emit_op(Opcode::ResultRow, ret_regs, ret_count, 0, P4::None, 0);
    }

    // Index maintenance: delete from each index before deleting the row.
    emit_index_deletes(b, table, table_cursor);

    // Delete at cursor position.
    // P5 bit 0 = OPFLAG_NCHANGE: count this deletion in changes().
    b.emit_op(
        Opcode::Delete,
        table_cursor,
        0,
        0,
        P4::Table(table.name.clone()),
        1,
    );

    b.resolve_label(seek_miss_label);

    // Loop back to read next rowid from the set.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let delete_loop_addr = delete_loop as i32;
    b.emit_op(Opcode::Goto, 0, delete_loop_addr, 0, P4::None, 0);

    b.resolve_label(delete_done_label);

    // Close table cursor.
    b.emit_op(Opcode::Close, table_cursor, 0, 0, P4::None, 0);

    // Close index cursors (bd-34se).
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    for idx_offset in 0..table.indexes.len() {
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    }

    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

    // End label.
    b.resolve_label(end_label);

    Ok(())
}

// ---------------------------------------------------------------------------
// WITHOUT ROWID tables
// ---------------------------------------------------------------------------
//
// A WITHOUT ROWID table is physically an index b-tree (root page type 0x0A)
// keyed by its PRIMARY KEY. The full row record (in declared column order) is
// the b-tree key; the leading `pk_count` columns are compared as the primary
// key (the connection registers per-root-page index ordering metadata so the
// table cursor compares on the PK). There is no integer rowid, so the normal
// `NewRowid`/`Insert`/`SeekRowid`/`Delete` opcodes do not apply — DML is lowered
// to `IdxInsert`/`IdxDelete` against the table's own (index) b-tree cursor.
//
// The current storage model stores the record in declared column order, which
// matches the read paths (`cursor_column` and reload hydration), and compares a
// leading prefix as the key. This requires the PRIMARY KEY to be exactly the
// leading declared columns in declared order; other shapes are rejected with a
// clear "not yet supported" error rather than silently mis-ordering.

/// Table-column index for each plain-column key term of `index` (leftmost
/// first). Expression key terms — and any term whose name does not resolve to a
/// declared column — map to `None`, which never dedups against a PK column.
fn without_rowid_index_key_columns(table: &TableSchema, index: &IndexSchema) -> Vec<Option<usize>> {
    (0..index.key_term_count())
        .map(|p| {
            index
                .columns
                .get(p)
                .and_then(|name| table.column_index(name))
        })
        .collect()
}

/// SQLite WITHOUT ROWID rule (bd-5ava1 / GH #353): a secondary/auto index
/// stores the index key terms followed only by the primary-key columns that are
/// **not already** part of the index. Returns the subset of `pk_indices` (in
/// PRIMARY KEY order) to append to this index's on-disk key. A PK column that
/// coincides with an index key term is elided from the suffix, so an index like
/// `UNIQUE(pk_leading, x)` on `PRIMARY KEY(pk_leading, ...)` stores each PK
/// column exactly once — matching stock sqlite3's on-disk layout.
fn without_rowid_index_appended_pk(
    table: &TableSchema,
    index: &IndexSchema,
    pk_indices: &[usize],
) -> Vec<usize> {
    let key_cols = without_rowid_index_key_columns(table, index);
    pk_indices
        .iter()
        .copied()
        .filter(|pk| !key_cols.contains(&Some(*pk)))
        .collect()
}

/// Index-record column position from which to read each primary-key column, in
/// PRIMARY KEY order, given the deduplicated WITHOUT ROWID key layout
/// (`[key terms..., appended PK...]`). A PK column that is also an index key
/// term is read from that leading key-term slot; the remaining PK columns are
/// read from the trailing appended region in PRIMARY KEY order.
fn without_rowid_index_pk_read_positions(
    table: &TableSchema,
    index: &IndexSchema,
    pk_indices: &[usize],
) -> Vec<usize> {
    let n_idx_key = index.key_term_count();
    let key_cols = without_rowid_index_key_columns(table, index);
    let mut next_trailing = n_idx_key;
    pk_indices
        .iter()
        .map(|&pk_col| {
            if let Some(p) = key_cols.iter().position(|kc| *kc == Some(pk_col)) {
                p
            } else {
                let pos = next_trailing;
                next_trailing += 1;
                pos
            }
        })
        .collect()
}

/// Position a WITHOUT ROWID table cursor on the row referenced by the current
/// entry of a secondary-index cursor (bd-rjaff).
///
/// WITHOUT ROWID secondary-index entries are `(key terms..., PK cols...)` —
/// there is no trailing rowid. This reads the PK suffix columns from the index
/// entry, packs them into a record, and probes the table b-tree with
/// `NoConflict` (prefix match over the leading PK columns). On a match the
/// table cursor is positioned on the row (fall-through); a missing row —
/// index/table inconsistency — jumps to `miss_label`.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_without_rowid_index_to_table_seek(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    idx_cursor: i32,
    idx_schema: &IndexSchema,
    pk_indices: &[usize],
    miss_label: crate::Label,
) {
    let n_pk = pk_indices.len();
    // Deduplicated layout: a PK column that is also an index key term lives in
    // its leading key-term slot, not the trailing suffix. Read each PK column
    // from its true index-record position.
    let read_positions = without_rowid_index_pk_read_positions(table, idx_schema, pk_indices);
    let pk_regs = b.alloc_regs(n_pk as i32);
    for (j, &pos) in read_positions.iter().enumerate() {
        b.emit_op(
            Opcode::Column,
            idx_cursor,
            pos as i32,
            pk_regs + j as i32,
            P4::None,
            0,
        );
    }
    let pk_rec_reg = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        pk_regs,
        n_pk as i32,
        pk_rec_reg,
        P4::None,
        0,
    );
    b.emit_jump_to_label(
        Opcode::NoConflict,
        table_cursor,
        pk_rec_reg,
        miss_label,
        P4::None,
        0,
    );
}

/// Resolve the WITHOUT ROWID primary-key column indices, in PRIMARY KEY order.
///
/// Returns the declared table-column index of each PK column. Errors only if
/// the table has no PRIMARY KEY. Non-leading / reordered PRIMARY KEYs are
/// supported: the record is stored physically PK-leading (see `emit_wr_record`)
/// and the table cursor remaps reads back to declared order.
pub fn without_rowid_pk_indices(table: &TableSchema) -> Result<Vec<usize>, CodegenError> {
    let pk_group = table.primary_key_constraints.first().ok_or_else(|| {
        CodegenError::Unsupported(format!(
            "WITHOUT ROWID table {} has no PRIMARY KEY",
            table.name
        ))
    })?;
    if pk_group.is_empty() {
        return Err(CodegenError::Unsupported(format!(
            "WITHOUT ROWID table {} has an empty PRIMARY KEY",
            table.name
        )));
    }
    let mut indices = Vec::with_capacity(pk_group.len());
    for name in pk_group {
        let idx = table
            .column_index(name)
            .ok_or_else(|| CodegenError::ColumnNotFound {
                table: table.name.clone(),
                column: name.clone(),
            })?;
        indices.push(idx);
    }
    // Storage is physically PK-leading (emit_wr_record reorders on write, the
    // table cursor remaps on read), so a non-leading / reordered PRIMARY KEY is
    // fully representable — no ordering restriction here.
    Ok(indices)
}

/// Emit the WITHOUT ROWID row record for `val_regs..val_regs+n_cols` (declared
/// order), physically reordered PK-leading — the PRIMARY KEY columns in PK
/// order, then the remaining columns in declared order — to match C SQLite's
/// on-disk WITHOUT ROWID record layout. Returns the record register.
///
/// For a leading-PK table the permutation is the identity, so this emits a
/// plain `MakeRecord` with no extra ops — byte-identical to the pre-reorder
/// path, keeping golden bytecode snapshots unchanged for the common shape.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_wr_record(
    b: &mut ProgramBuilder,
    pk_indices: &[usize],
    val_regs: i32,
    n_cols: usize,
    aff_str: &str,
) -> i32 {
    let rec_reg = b.alloc_reg();
    if without_rowid_pk_is_leading(pk_indices, n_cols) {
        b.emit_op(
            Opcode::MakeRecord,
            val_regs,
            n_cols as i32,
            rec_reg,
            P4::Affinity(aff_str.to_owned()),
            0,
        );
        return rec_reg;
    }
    // Non-leading PK: copy the declared-order value registers into a fresh
    // contiguous block in physical (PK-leading) order, and reorder the
    // per-column affinity string to match, before serializing.
    let perm = without_rowid_storage_order(pk_indices, n_cols);
    let phys_regs = b.alloc_regs(n_cols as i32);
    let aff_bytes = aff_str.as_bytes();
    let mut phys_aff = String::with_capacity(n_cols);
    for (phys_slot, &decl_col) in perm.iter().enumerate() {
        b.emit_op(
            Opcode::Copy,
            val_regs + decl_col as i32,
            phys_regs + phys_slot as i32,
            0,
            P4::None,
            0,
        );
        phys_aff.push(aff_bytes.get(decl_col).map_or('A', |&c| c as char));
    }
    b.emit_op(
        Opcode::MakeRecord,
        phys_regs,
        n_cols as i32,
        rec_reg,
        P4::Affinity(phys_aff),
        0,
    );
    rec_reg
}

/// Human-readable PK label for UNIQUE-violation error messages.
fn without_rowid_pk_label(table: &TableSchema, pk_indices: &[usize]) -> String {
    // bd-a506j F1b: qualify each PK column with the table name so the constraint
    // message reads "t.a, t.b" (stock), not "t.a, b". Callers pass this label
    // directly (no extra "{table}." prefix).
    pk_indices
        .iter()
        .filter_map(|&i| table.columns.get(i))
        .map(|c| format!("{}.{}", table.name, c.name))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Emit secondary-index inserts for a WITHOUT ROWID table row.
///
/// Index entries are keyed by `(index key terms..., primary-key columns...)`
/// — the PK columns take the place of the trailing rowid used by rowid tables.
/// Key terms and PK columns are read from `col_regs` (declared-order row image).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_without_rowid_index_inserts(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    col_regs: i32,
    pk_indices: &[usize],
    stmt_conflict: Option<ConflictAction>,
    unique_conflicts_preflighted: bool,
) {
    for (idx_offset, index) in table.indexes.iter().enumerate() {
        // When the caller has already resolved every UNIQUE victim in clustered
        // terms, hand the engine ABORT: its OE_REPLACE branch resolves victims
        // by rowid and cannot address a WITHOUT ROWID clustered row.
        let oe_flag = if unique_conflicts_preflighted && index.is_unique {
            OE_ABORT
        } else {
            effective_oe(stmt_conflict, index.conflict_action)
        };
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        let n_idx_cols = index.key_term_count();
        // GH #353: append only the PK columns not already covered by this
        // index's key terms (stock sqlite3's WITHOUT ROWID on-disk layout).
        let appended_pk = without_rowid_index_appended_pk(table, index, pk_indices);
        let n_pk = appended_pk.len();
        let skip_label = b.emit_label();
        let scan_ctx = ScanCtx {
            cursor: table_cursor,
            table,
            table_alias: None,
            schema: None,
            register_base: Some(col_regs),
            secondaries: &[],
        };
        emit_index_predicate_guard(b, index, &scan_ctx, skip_label);

        let idx_key_regs = b.alloc_regs((n_idx_cols + n_pk) as i32);
        for key_pos in 0..n_idx_cols {
            emit_index_key_term(b, index, key_pos, idx_key_regs + key_pos as i32, &scan_ctx);
        }
        for (j, &pk_col) in appended_pk.iter().enumerate() {
            b.emit_op(
                Opcode::Copy,
                col_regs + pk_col as i32,
                idx_key_regs + (n_idx_cols + j) as i32,
                0,
                P4::None,
                0,
            );
        }
        let idx_rec_reg = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            idx_key_regs,
            (n_idx_cols + n_pk) as i32,
            idx_rec_reg,
            P4::None,
            0,
        );
        let (p3_unique, p5_unique) = if index.is_unique {
            (n_idx_cols as i32, 1u16 | (oe_flag << 1))
        } else {
            (0, 0u16)
        };
        let p4_name = if index.is_unique {
            P4::Table(index.key_label_qualified(&table.name))
        } else {
            P4::Table(index.name.clone())
        };
        b.emit_op(
            Opcode::IdxInsert,
            idx_cursor,
            idx_rec_reg,
            p3_unique,
            p4_name,
            p5_unique,
        );
        b.resolve_label(skip_label);
    }
}

/// Emit secondary-index deletes for a WITHOUT ROWID table row.
///
/// When `col_regs` is `Some`, key terms and PK columns are read from the
/// register image; when `None`, they are read from the row at the current
/// `table_cursor` position (via `Opcode::Column`).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_without_rowid_index_deletes(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    col_regs: Option<i32>,
    pk_indices: &[usize],
) {
    for (idx_offset, index) in table.indexes.iter().enumerate() {
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        let n_idx_cols = index.key_term_count();
        // GH #353: the delete key must match the deduplicated insert layout —
        // only PK columns not already in this index's key terms are appended.
        let appended_pk = without_rowid_index_appended_pk(table, index, pk_indices);
        let n_pk = appended_pk.len();
        let skip_label = b.emit_label();
        let scan_ctx = ScanCtx {
            cursor: table_cursor,
            table,
            table_alias: None,
            schema: None,
            register_base: col_regs,
            secondaries: &[],
        };
        emit_index_predicate_guard(b, index, &scan_ctx, skip_label);

        let idx_key_regs = b.alloc_regs((n_idx_cols + n_pk) as i32);
        for key_pos in 0..n_idx_cols {
            emit_index_key_term(b, index, key_pos, idx_key_regs + key_pos as i32, &scan_ctx);
        }
        for (j, &pk_col) in appended_pk.iter().enumerate() {
            let dst = idx_key_regs + (n_idx_cols + j) as i32;
            if let Some(cr) = col_regs {
                b.emit_op(Opcode::Copy, cr + pk_col as i32, dst, 0, P4::None, 0);
            } else {
                b.emit_op(
                    Opcode::Column,
                    table_cursor,
                    pk_col as i32,
                    dst,
                    P4::None,
                    0,
                );
            }
        }
        b.emit_op(
            Opcode::IdxDelete,
            idx_cursor,
            idx_key_regs,
            (n_idx_cols + n_pk) as i32,
            P4::Table(index.name.clone()),
            0,
        );
        b.resolve_label(skip_label);
    }
}

/// Rewrite one located WITHOUT ROWID row from its OLD image to its NEW image.
///
/// bd-yuj70: the previous emission deleted the OLD secondary-index entries and
/// the OLD table row *before* the NEW primary key was probed, so a NEW-PK
/// collision with a **different** row reached `IdxInsert` with `OE_REPLACE`
/// and bypassed the explicit victim-secondary cleanup that
/// [`emit_without_rowid_row_insert`] performs. That left the victim's
/// secondary-index entries pointing at a deleted clustered record, and the
/// ABORT/FAIL/ROLLBACK paths had already destroyed OLD before raising.
///
/// The mutation order here is fixed:
/// 1. the caller computes, validates, and affinitizes NEW before any mutation;
/// 2. probe the NEW primary key and distinguish a *self* rewrite (NEW PK equals
///    OLD PK) from an *other* victim;
/// 3. resolve the conflict action against that other victim first — REPLACE
///    removes the victim's secondary entries and its clustered row, IGNORE
///    abandons the row without mutating anything, and the ABORT family raises
///    the UNIQUE violation while OLD is still intact;
/// 4. only then delete the OLD secondary entries and the OLD clustered row;
/// 5. insert NEW under `OE_ABORT` so the write cannot recursively REPLACE.
///
/// `new_regs` holds the NEW image (declared column order, already affinitized),
/// `old_regs` the OLD image used for the OLD secondary-index keys, and
/// `old_pk_regs` the OLD primary-key values used to re-seek the OLD row after
/// the probes have moved the cursor.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn emit_without_rowid_update_rewrite(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    new_regs: i32,
    old_regs: i32,
    old_pk_regs: i32,
    pk_indices: &[usize],
    oe_flag: u16,
    stmt_level: Option<ConflictAction>,
    row_done: Label,
) {
    let n_cols = table.columns.len();
    let n_pk = pk_indices.len();
    let pk_label = without_rowid_pk_label(table, pk_indices);
    let aff_str = table.affinity_string();

    // PHASE A — decide every conflict before mutating anything.
    //
    // Ordering follows `emit_without_rowid_row_insert` (and SQLite's
    // `sqlite3GenerateConstraintChecks`): the primary key is resolved first,
    // then each index in `table.indexes` schema order. Nothing in phase A
    // deletes: a REPLACE decision only *captures* the victim's primary key, so
    // a later IGNORE or ABORT on a different index still leaves the database
    // exactly as it was. Phase B then applies the captured deletions.
    let pk_victim_flag = b.alloc_reg();
    b.emit_op(Opcode::Integer, 0, pk_victim_flag, 0, P4::None, 0);
    let unique_index_slots: Vec<(usize, i32, i32)> = table
        .indexes
        .iter()
        .enumerate()
        .filter(|(_, index)| index.is_unique && index.key_term_count() > 0)
        .map(|(idx_offset, _)| {
            let flag = b.alloc_reg();
            b.emit_op(Opcode::Integer, 0, flag, 0, P4::None, 0);
            let victim_pk = b.alloc_regs(n_pk as i32);
            (idx_offset, flag, victim_pk)
        })
        .collect();

    // A1: is the primary key unchanged? Compare collation-aware, per key
    // column: a single differing column makes this an "other victim" probe.
    let pk_changed = b.emit_label();
    let pk_unchanged = b.emit_label();
    for (j, &pk_col) in pk_indices.iter().enumerate() {
        let pk_collation = table.columns[pk_col]
            .collation
            .as_deref()
            .filter(|name| !name.eq_ignore_ascii_case("BINARY"))
            .map_or(P4::None, |name| P4::Collation(name.to_owned()));
        b.emit_jump_to_label(
            Opcode::Ne,
            new_regs + pk_col as i32,
            old_pk_regs + j as i32,
            pk_changed,
            pk_collation,
            0,
        );
    }
    b.emit_jump_to_label(Opcode::Goto, 0, 0, pk_unchanged, P4::None, 0);

    // A2: the primary key moved — decide against any *other* row holding NEW PK.
    b.resolve_label(pk_changed);
    let new_pk_regs = b.alloc_regs(n_pk as i32);
    for (j, &pk_col) in pk_indices.iter().enumerate() {
        b.emit_op(
            Opcode::Copy,
            new_regs + pk_col as i32,
            new_pk_regs + j as i32,
            0,
            P4::None,
            0,
        );
    }
    let new_pk_rec = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        new_pk_regs,
        n_pk as i32,
        new_pk_rec,
        P4::None,
        0,
    );
    let no_victim = b.emit_label();
    b.emit_jump_to_label(
        Opcode::NoConflict,
        table_cursor,
        new_pk_rec,
        no_victim,
        P4::None,
        0,
    );
    if oe_flag == OE_REPLACE {
        // Record the decision only. The victim's primary key *is* the NEW
        // primary key, so no separate capture registers are needed; phase B
        // re-seeks it. Deleting here would be visible to a later IGNORE.
        b.emit_op(Opcode::Integer, 1, pk_victim_flag, 0, P4::None, 0);
    } else if oe_flag == OE_IGNORE {
        // Abandon the row with OLD still intact.
        b.emit_jump_to_label(Opcode::Goto, 0, 0, row_done, P4::None, 0);
    } else {
        // ABORT / FAIL / ROLLBACK: raise the UNIQUE violation now, while OLD is
        // still present, so the statement cannot lose the OLD row on the way
        // out. `NoConflict` fell through, so a conflicting row provably exists
        // and this insert cannot silently succeed.
        let abort_rec = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            new_regs,
            n_cols as i32,
            abort_rec,
            P4::Affinity(aff_str.clone()),
            0,
        );
        b.emit_op(
            Opcode::IdxInsert,
            table_cursor,
            abort_rec,
            n_pk as i32,
            P4::Table(pk_label.clone()),
            1u16 | (oe_flag << 1),
        );
    }
    b.resolve_label(no_victim);
    b.resolve_label(pk_unchanged);

    // A3: decide every UNIQUE secondary-index conflict, still without mutating.
    //
    // The engine's `IdxInsert` OE_REPLACE branch resolves its victim as a
    // *rowid* (`find_conflicting_rowid_in_index` -> `Option<i64>`, then
    // `native_replace_row`, which seeks the table B-tree by rowid). A WITHOUT
    // ROWID secondary entry ends with the PRIMARY KEY, not an integer rowid, so
    // that path cannot address the victim and instead reports the healthy
    // database as malformed. Every unique conflict is therefore resolved here,
    // in clustered terms, and phase C hands the engine a non-REPLACE action so
    // the rowid-suffix path is never entered.
    for &(idx_offset, victim_flag, victim_pk_regs) in &unique_index_slots {
        let index = &table.indexes[idx_offset];
        let idx_oe = effective_oe(stmt_level, index.conflict_action);
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        let n_idx_cols = index.key_term_count();
        // GH #353: deduplicated WITHOUT ROWID key layout — the victim PK is read
        // from these per-column positions, and the raise key appends only the
        // non-overlapping PK suffix.
        let read_positions = without_rowid_index_pk_read_positions(table, index, pk_indices);
        let appended_pk = without_rowid_index_appended_pk(table, index, pk_indices);
        let idx_done = b.emit_label();

        // A partial index only constrains rows its predicate admits: when NEW
        // is outside the predicate it cannot conflict on this index at all.
        let new_scan_ctx = ScanCtx {
            cursor: table_cursor,
            table,
            table_alias: None,
            schema: None,
            register_base: Some(new_regs),
            secondaries: &[],
        };
        emit_index_predicate_guard(b, index, &new_scan_ctx, idx_done);

        // Probe the unique prefix only (the PK suffix is what distinguishes
        // rows, so it must not participate in the conflict test).
        let probe_regs = b.alloc_regs(n_idx_cols as i32);
        for key_pos in 0..n_idx_cols {
            emit_index_key_term(
                b,
                index,
                key_pos,
                probe_regs + key_pos as i32,
                &new_scan_ctx,
            );
        }
        // SQL UNIQUE never constrains NULL keys: a NULL in any key term means
        // this row cannot collide, matching `IdxInsert`'s own NoConflict
        // semantics.
        for key_pos in 0..n_idx_cols {
            b.emit_jump_to_label(
                Opcode::IsNull,
                probe_regs + key_pos as i32,
                0,
                idx_done,
                P4::None,
                0,
            );
        }
        let probe_rec = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            probe_regs,
            n_idx_cols as i32,
            probe_rec,
            P4::None,
            0,
        );
        b.emit_jump_to_label(
            Opcode::NoConflict,
            idx_cursor,
            probe_rec,
            idx_done,
            P4::None,
            0,
        );

        // A conflicting entry exists and `idx_cursor` is positioned on it. Its
        // key terms plus non-overlapping suffix reconstruct the victim's
        // PRIMARY KEY — read each PK column from its true index-record slot.
        for (j, &pos) in read_positions.iter().enumerate() {
            b.emit_op(
                Opcode::Column,
                idx_cursor,
                pos as i32,
                victim_pk_regs + j as i32,
                P4::None,
                0,
            );
        }

        // Self-conflict: the entry belongs to the row being rewritten, so the
        // OLD delete in phase B already removes it. Comparing against OLD PK
        // (not NEW) is what makes a pure secondary-key rewrite a no-op here.
        let victim_is_other = b.emit_label();
        for (j, &pk_col) in pk_indices.iter().enumerate() {
            let pk_collation = table.columns[pk_col]
                .collation
                .as_deref()
                .filter(|name| !name.eq_ignore_ascii_case("BINARY"))
                .map_or(P4::None, |name| P4::Collation(name.to_owned()));
            b.emit_jump_to_label(
                Opcode::Ne,
                victim_pk_regs + j as i32,
                old_pk_regs + j as i32,
                victim_is_other,
                pk_collation,
                0,
            );
        }
        b.emit_jump_to_label(Opcode::Goto, 0, 0, idx_done, P4::None, 0);
        b.resolve_label(victim_is_other);

        if idx_oe == OE_IGNORE {
            // Abandon the whole row with OLD intact.
            b.emit_jump_to_label(Opcode::Goto, 0, 0, row_done, P4::None, 0);
        } else if idx_oe == OE_REPLACE {
            // Record the decision only: `victim_pk_regs` already holds the
            // victim's primary key. Phase B re-seeks and deletes it, so a
            // later IGNORE or ABORT on another index still sees an unmutated
            // database.
            b.emit_op(Opcode::Integer, 1, victim_flag, 0, P4::None, 0);
        } else {
            // ABORT / FAIL / ROLLBACK: raise the UNIQUE violation now, while
            // OLD and every captured victim are still present. The full
            // [key || pk] record is what the engine's unique check expects;
            // `NoConflict` fell through, so a conflicting entry provably exists
            // and this cannot silently succeed.
            let n_pk_app = appended_pk.len();
            let raise_regs = b.alloc_regs((n_idx_cols + n_pk_app) as i32);
            for key_pos in 0..n_idx_cols {
                b.emit_op(
                    Opcode::Copy,
                    probe_regs + key_pos as i32,
                    raise_regs + key_pos as i32,
                    0,
                    P4::None,
                    0,
                );
            }
            for (j, &pk_col) in appended_pk.iter().enumerate() {
                b.emit_op(
                    Opcode::Copy,
                    new_regs + pk_col as i32,
                    raise_regs + (n_idx_cols + j) as i32,
                    0,
                    P4::None,
                    0,
                );
            }
            let raise_rec = b.alloc_reg();
            b.emit_op(
                Opcode::MakeRecord,
                raise_regs,
                (n_idx_cols + n_pk_app) as i32,
                raise_rec,
                P4::None,
                0,
            );
            b.emit_op(
                Opcode::IdxInsert,
                idx_cursor,
                raise_rec,
                n_idx_cols as i32,
                P4::Table(index.key_label_qualified(&table.name)),
                1u16 | (idx_oe << 1),
            );
        }
        b.resolve_label(idx_done);
    }

    // PHASE B — apply the captured REPLACE deletions.
    //
    // Every decision is now final: no IGNORE or ABORT can still fire, so these
    // deletions cannot become an unintended partial mutation. Each victim is
    // re-seeked by primary key and skipped when already absent, which is what
    // makes duplicate victims safe — the same row reached through two indexes,
    // or a secondary victim that is also the primary-key victim, is deleted
    // once and the later seeks find nothing.
    let emit_captured_victim_delete = |b: &mut ProgramBuilder, flag: i32, pk_regs: i32| {
        let victim_done = b.emit_label();
        b.emit_jump_to_label(Opcode::IfNot, flag, 1, victim_done, P4::None, 0);
        let victim_seek_rec = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            pk_regs,
            n_pk as i32,
            victim_seek_rec,
            P4::None,
            0,
        );
        b.emit_jump_to_label(
            Opcode::NoConflict,
            table_cursor,
            victim_seek_rec,
            victim_done,
            P4::None,
            0,
        );
        emit_without_rowid_index_deletes(b, table, table_cursor, None, pk_indices);
        b.emit_op(
            Opcode::IdxDelete,
            table_cursor,
            0,
            0,
            P4::Table(table.name.clone()),
            OPFLAG_REPLACE_VICTIM,
        );
        b.resolve_label(victim_done);
    };

    // B1: the primary-key victim, whose primary key is the NEW primary key.
    emit_captured_victim_delete(b, pk_victim_flag, new_pk_regs);
    // B2: each captured secondary victim, in the same index order as phase A.
    for &(_, victim_flag, victim_pk_regs) in &unique_index_slots {
        emit_captured_victim_delete(b, victim_flag, victim_pk_regs);
    }

    // B3: re-seek OLD (the probes above moved the cursor) and remove its
    // secondary-index entries and clustered row.
    let old_seek_regs = b.alloc_regs(n_pk as i32);
    for j in 0..n_pk {
        b.emit_op(
            Opcode::Copy,
            old_pk_regs + j as i32,
            old_seek_regs + j as i32,
            0,
            P4::None,
            0,
        );
    }
    let old_seek_rec = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        old_seek_regs,
        n_pk as i32,
        old_seek_rec,
        P4::None,
        0,
    );
    let old_absent = b.emit_label();
    b.emit_jump_to_label(
        Opcode::NoConflict,
        table_cursor,
        old_seek_rec,
        old_absent,
        P4::None,
        0,
    );
    emit_without_rowid_index_deletes(b, table, table_cursor, Some(old_regs), pk_indices);
    b.emit_op(Opcode::IdxDelete, table_cursor, 0, 0, P4::None, 0);
    b.resolve_label(old_absent);

    // PHASE C: insert NEW. Every conflicting row has been resolved above, so
    // this insert must not itself REPLACE.
    let rec_reg = emit_wr_record(b, pk_indices, new_regs, n_cols, &aff_str);
    b.emit_op(
        Opcode::IdxInsert,
        table_cursor,
        rec_reg,
        n_pk as i32,
        P4::Table(pk_label.clone()),
        1u16 | (OE_ABORT << 1) | OPFLAG_IDX_NCHANGE,
    );
    emit_without_rowid_index_inserts(
        b,
        table,
        table_cursor,
        new_regs,
        pk_indices,
        stmt_level,
        true,
    );
}

/// Emit the per-row insert for a WITHOUT ROWID table.
///
/// `val_regs` holds the full row image in declared column order. Handles
/// constraint validation, conflict resolution (ABORT/IGNORE/REPLACE), the table
/// b-tree `IdxInsert`, and secondary-index maintenance.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
fn emit_without_rowid_row_insert(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    val_regs: i32,
    pk_indices: &[usize],
    oe_flag: u16,
    stmt_level: Option<ConflictAction>,
    upserts: &[UpsertClause],
    target_alias: Option<&str>,
    returning: &[ResultColumn],
    schema: &[TableSchema],
) -> Result<(), CodegenError> {
    let n_cols = table.columns.len();
    let n_pk = pk_indices.len();

    // Candidate-row validation runs for EVERY row BEFORE conflict routing
    // (mirrors the rowid path): STORED generated columns, STRICT type check,
    // affinity coercion (GH #169 — so CHECK/NOT NULL see the coerced value and
    // the conflict probe keys match stored format), then CHECK / NOT NULL. Stock
    // enforces these on the candidate even for a row that will conflict and
    // DO UPDATE, so they must precede the ON CONFLICT chain (bd-xa2qv). Under a
    // statement-level IGNORE the candidate is abandoned via `candidate_skip`.
    emit_stored_generated_columns(b, table, val_regs);
    emit_strict_type_check(b, table, val_regs);
    b.emit_op(
        Opcode::Affinity,
        val_regs,
        n_cols as i32,
        0,
        P4::Affinity(table.affinity_string()),
        0,
    );
    let candidate_skip = if oe_flag == OE_IGNORE {
        Some(b.emit_label())
    } else {
        None
    };
    emit_check_constraints(b, table, val_regs, candidate_skip);
    emit_not_null_constraints(b, table, val_regs, stmt_level, candidate_skip);

    // UPSERT: a chain of ON CONFLICT clauses (SQLite 3.35+). Each clause probes
    // its own conflict target in written order; the first clause whose target is
    // violated is applied (DO UPDATE rewrites the specific conflicting row; DO
    // NOTHING skips the insert). A conflict on a constraint that no clause
    // targets falls through to the plain-insert body below, which enforces the
    // remaining constraints under `oe_flag`/`stmt_level` (default ABORT) —
    // matching stock (bd-xa2qv, mirrors the rowid path bd-aap9u). The plain
    // insert is shared as the chain's fall-through, so `done_label` is resolved
    // after it.
    let upsert_done_label = if upserts.is_empty() {
        None
    } else {
        let done_label = b.emit_label();
        let insert_label = b.emit_label();
        for (clause_idx, clause) in upserts.iter().enumerate() {
            // No conflict on this clause's target routes to the next clause; the
            // last clause routes to the plain-insert fall-through.
            let no_conflict_label = if clause_idx + 1 == upserts.len() {
                insert_label
            } else {
                b.emit_label()
            };
            let conflict_label = b.emit_label();
            // Conflict-target routing:
            //  - omitted target -> DO UPDATE fires on ANY uniqueness constraint;
            //    probe the PRIMARY KEY and every UNIQUE secondary index.
            //  - explicit PRIMARY KEY -> PK-only (find_upsert_target_index
            //    returns None for the PK, which is the table btree, not in
            //    `table.indexes`).
            //  - explicit secondary UNIQUE (bd-yqjjx) -> probe just that index;
            //    a PK/other-index collision routes to `no_conflict_label`.
            let explicit_target_index =
                find_upsert_target_index(table, clause.target.as_ref()).map(|(offset, _)| offset);
            let probe_unique_secondaries = clause.target.is_none();
            emit_without_rowid_upsert_probe(
                b,
                table,
                table_cursor,
                val_regs,
                pk_indices,
                probe_unique_secondaries,
                explicit_target_index,
                conflict_label,
                no_conflict_label,
            );
            b.resolve_label(conflict_label);
            match &clause.action {
                UpsertAction::Nothing => {
                    // Conflict on this target -> skip the insert entirely.
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                }
                UpsertAction::Update {
                    assignments,
                    where_clause,
                } => {
                    emit_without_rowid_upsert_do_update_apply(
                        b,
                        table,
                        table_cursor,
                        val_regs,
                        pk_indices,
                        stmt_level,
                        assignments,
                        where_clause.as_deref(),
                        target_alias,
                        returning,
                        schema,
                    )?;
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                }
            }
            if clause_idx + 1 != upserts.len() {
                b.resolve_label(no_conflict_label);
            }
        }
        // Fall-through: no clause's target conflicted. The plain-insert body
        // below runs under `oe_flag`/`stmt_level`.
        b.resolve_label(insert_label);
        Some(done_label)
    };

    // Plain insert of the candidate row. Candidate validation (STORED generated
    // columns, STRICT type check, affinity, CHECK, NOT NULL) already ran above,
    // before conflict routing. Apply column affinities before packing the record
    // (matches stored format).
    let aff_str = table.affinity_string();
    b.emit_op(
        Opcode::Affinity,
        val_regs,
        n_cols as i32,
        0,
        P4::Affinity(aff_str.clone()),
        0,
    );

    let row_done = b.emit_label();
    let pk_label = without_rowid_pk_label(table, pk_indices);

    // Decide every UNIQUE action before mutating the clustered table. A
    // WITHOUT ROWID secondary entry ends in the composite PK, not a rowid, so
    // the engine's rowid-table REPLACE path cannot identify its victim.
    let pk_probe_regs = b.alloc_regs(n_pk as i32);
    for (j, &pk_col) in pk_indices.iter().enumerate() {
        b.emit_op(
            Opcode::Copy,
            val_regs + pk_col as i32,
            pk_probe_regs + j as i32,
            0,
            P4::None,
            0,
        );
    }
    let pk_probe_rec = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        pk_probe_regs,
        n_pk as i32,
        pk_probe_rec,
        P4::None,
        0,
    );
    let pk_victim_flag = b.alloc_reg();
    b.emit_op(Opcode::Integer, 0, pk_victim_flag, 0, P4::None, 0);
    let pk_clear = b.emit_label();
    b.emit_jump_to_label(
        Opcode::NoConflict,
        table_cursor,
        pk_probe_rec,
        pk_clear,
        P4::None,
        0,
    );
    if oe_flag == OE_IGNORE {
        b.emit_jump_to_label(Opcode::Goto, 0, 0, row_done, P4::None, 0);
    } else if oe_flag == OE_REPLACE {
        b.emit_op(Opcode::Integer, 1, pk_victim_flag, 0, P4::None, 0);
    } else {
        b.emit_op(
            Opcode::Halt,
            ErrorCode::Constraint as i32,
            0,
            0,
            P4::Str(pk_label.clone()),
            OPFLAG_HALT_UNIQUE,
        );
    }
    b.resolve_label(pk_clear);

    let unique_index_slots: Vec<(usize, i32, i32)> = table
        .indexes
        .iter()
        .enumerate()
        .filter(|(_, index)| index.is_unique && index.key_term_count() > 0)
        .map(|(idx_offset, _)| {
            let flag = b.alloc_reg();
            b.emit_op(Opcode::Integer, 0, flag, 0, P4::None, 0);
            let victim_pk = b.alloc_regs(n_pk as i32);
            (idx_offset, flag, victim_pk)
        })
        .collect();

    for &(idx_offset, victim_flag, victim_pk_regs) in &unique_index_slots {
        let index = &table.indexes[idx_offset];
        let idx_oe = effective_oe(stmt_level, index.conflict_action);
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        let n_idx_cols = index.key_term_count();
        // GH #353: reconstruct the victim PK from the deduplicated key layout.
        let read_positions = without_rowid_index_pk_read_positions(table, index, pk_indices);
        let idx_clear = b.emit_label();
        let scan_ctx = ScanCtx {
            cursor: table_cursor,
            table,
            table_alias: None,
            schema: None,
            register_base: Some(val_regs),
            secondaries: &[],
        };
        emit_index_predicate_guard(b, index, &scan_ctx, idx_clear);

        let probe_regs = b.alloc_regs(n_idx_cols as i32);
        for key_pos in 0..n_idx_cols {
            emit_index_key_term(b, index, key_pos, probe_regs + key_pos as i32, &scan_ctx);
            b.emit_jump_to_label(
                Opcode::IsNull,
                probe_regs + key_pos as i32,
                0,
                idx_clear,
                P4::None,
                0,
            );
        }
        let probe_rec = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            probe_regs,
            n_idx_cols as i32,
            probe_rec,
            P4::None,
            0,
        );
        b.emit_jump_to_label(
            Opcode::NoConflict,
            idx_cursor,
            probe_rec,
            idx_clear,
            P4::None,
            0,
        );
        for (j, &pos) in read_positions.iter().enumerate() {
            b.emit_op(
                Opcode::Column,
                idx_cursor,
                pos as i32,
                victim_pk_regs + j as i32,
                P4::None,
                0,
            );
        }
        if idx_oe == OE_IGNORE {
            b.emit_jump_to_label(Opcode::Goto, 0, 0, row_done, P4::None, 0);
        } else if idx_oe == OE_REPLACE {
            b.emit_op(Opcode::Integer, 1, victim_flag, 0, P4::None, 0);
        } else {
            b.emit_op(
                Opcode::Halt,
                ErrorCode::Constraint as i32,
                0,
                0,
                P4::Str(index.key_label_qualified(&table.name)),
                OPFLAG_HALT_UNIQUE,
            );
        }
        b.resolve_label(idx_clear);
    }

    let emit_victim_delete = |b: &mut ProgramBuilder, flag: i32, victim_pk_regs: i32| {
        let victim_done = b.emit_label();
        b.emit_jump_to_label(Opcode::IfNot, flag, 1, victim_done, P4::None, 0);
        let victim_rec = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            victim_pk_regs,
            n_pk as i32,
            victim_rec,
            P4::None,
            0,
        );
        b.emit_jump_to_label(
            Opcode::NoConflict,
            table_cursor,
            victim_rec,
            victim_done,
            P4::None,
            0,
        );
        emit_without_rowid_index_deletes(b, table, table_cursor, None, pk_indices);
        b.emit_op(
            Opcode::IdxDelete,
            table_cursor,
            0,
            0,
            P4::Table(table.name.clone()),
            OPFLAG_REPLACE_VICTIM,
        );
        b.resolve_label(victim_done);
    };
    emit_victim_delete(b, pk_victim_flag, pk_probe_regs);
    for &(_, victim_flag, victim_pk_regs) in &unique_index_slots {
        emit_victim_delete(b, victim_flag, victim_pk_regs);
    }

    let rec_reg = emit_wr_record(b, pk_indices, val_regs, n_cols, &aff_str);
    b.emit_op(
        Opcode::IdxInsert,
        table_cursor,
        rec_reg,
        n_pk as i32,
        P4::Table(pk_label.clone()),
        1u16 | (OE_ABORT << 1) | OPFLAG_IDX_NCHANGE,
    );

    // Secondary-index maintenance (skipped by the IGNORE conflict path, which
    // jumps straight to `row_done`).
    emit_without_rowid_index_inserts(
        b,
        table,
        table_cursor,
        val_regs,
        pk_indices,
        stmt_level,
        true,
    );

    // RETURNING: emit the inserted row image. Placed on the insert path so an
    // IGNORE conflict (which jumps to `row_done`) produces no RETURNING row,
    // matching SQLite. `val_regs` holds the post-affinity stored values.
    if !returning.is_empty() {
        emit_returning_from_regs(b, table, returning, target_alias, schema, val_regs)?;
    }
    b.resolve_label(row_done);
    // The DO UPDATE / DO NOTHING chain arms jump here, skipping the plain insert.
    if let Some(done_label) = upsert_done_label {
        b.resolve_label(done_label);
    }
    // A candidate CHECK/NOT NULL violation under a statement-level IGNORE
    // abandons the whole row here (skipping conflict routing and the insert).
    if let Some(label) = candidate_skip {
        b.resolve_label(label);
    }
    Ok(())
}

/// Emit the conflict probe for one UPSERT `ON CONFLICT` clause on a WITHOUT
/// ROWID table. On a uniqueness conflict against the clause's target the table
/// cursor is left positioned on the conflicting row and control jumps to
/// `conflict_label`; on no conflict (or an index/table inconsistency) control
/// jumps to `no_conflict_label`.
///
/// Routing mirrors the rowid `emit_upsert_probe`:
///  - `explicit_target_index = Some(i)` (an explicit secondary-UNIQUE target,
///    bd-yqjjx): probe ONLY that index. A PRIMARY KEY or other-index collision
///    is not the named arbiter, so it routes to `no_conflict_label`.
///  - omitted target (`probe_unique_secondaries = true`): probe the PRIMARY KEY,
///    then each UNIQUE secondary index in index order; the first hit wins.
///  - explicit PRIMARY KEY target (`explicit_target_index = None`,
///    `probe_unique_secondaries = false`): probe the PRIMARY KEY only.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
#[allow(clippy::too_many_arguments)]
fn emit_without_rowid_upsert_probe(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    val_regs: i32,
    pk_indices: &[usize],
    probe_unique_secondaries: bool,
    explicit_target_index: Option<usize>,
    conflict_label: Label,
    no_conflict_label: Label,
) {
    let n_pk = pk_indices.len();

    if let Some(target_idx) = explicit_target_index {
        // Explicit secondary-UNIQUE conflict target (bd-yqjjx): DO UPDATE fires
        // ONLY on a conflict against THIS index. A PRIMARY KEY collision, or a
        // collision on any OTHER unique index, is not this target — it routes to
        // `no_conflict_label`. So there is deliberately no PK-for-update probe
        // here; probe only the target index, exactly like a single iteration of
        // the omitted-target secondary loop below.
        let index = &table.indexes[target_idx];
        let idx_cursor = table_cursor + 1 + target_idx as i32;
        let n_idx_cols = index.key_term_count();
        let scan_ctx = ScanCtx {
            cursor: table_cursor,
            table,
            table_alias: None,
            schema: None,
            register_base: Some(val_regs),
            secondaries: &[],
        };
        let idx_key_regs = b.alloc_regs(n_idx_cols as i32);
        for key_pos in 0..n_idx_cols {
            emit_index_key_term(b, index, key_pos, idx_key_regs + key_pos as i32, &scan_ctx);
        }
        let idx_probe_rec = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            idx_key_regs,
            n_idx_cols as i32,
            idx_probe_rec,
            P4::None,
            0,
        );
        // No existing entry shares these key terms (a NULL key term never
        // conflicts — SQLite UNIQUE semantics) -> no conflict for this clause.
        b.emit_jump_to_label(
            Opcode::NoConflict,
            idx_cursor,
            idx_probe_rec,
            no_conflict_label,
            P4::None,
            0,
        );
        // Conflict: position the table cursor on the conflicting row via the
        // index entry's PK suffix. If the index and table are inconsistent (row
        // missing), route to `no_conflict_label`.
        emit_without_rowid_index_to_table_seek(
            b,
            table,
            table_cursor,
            idx_cursor,
            index,
            pk_indices,
            no_conflict_label,
        );
        b.emit_jump_to_label(Opcode::Goto, 0, 0, conflict_label, P4::None, 0);
    } else {
        // Probe the PRIMARY KEY: build a PK-prefix key and test for an existing row.
        let pk_probe_regs = b.alloc_regs(n_pk as i32);
        for (j, &pk_col) in pk_indices.iter().enumerate() {
            b.emit_op(
                Opcode::Copy,
                val_regs + pk_col as i32,
                pk_probe_regs + j as i32,
                0,
                P4::None,
                0,
            );
        }
        let pk_probe_rec = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            pk_probe_regs,
            n_pk as i32,
            pk_probe_rec,
            P4::None,
            0,
        );
        // NoConflict jumps when there is NO existing PK match; a match falls through
        // with the table cursor positioned on the conflicting row.
        let pk_no_conflict = b.emit_label();
        b.emit_jump_to_label(
            Opcode::NoConflict,
            table_cursor,
            pk_probe_rec,
            pk_no_conflict,
            P4::None,
            0,
        );
        b.emit_jump_to_label(Opcode::Goto, 0, 0, conflict_label, P4::None, 0);
        b.resolve_label(pk_no_conflict);

        // Omitted conflict target: SQLite fires DO UPDATE on whichever uniqueness
        // constraint is violated, checked in constraint order — the PRIMARY KEY
        // (above), then each UNIQUE secondary index in index order. Probe each
        // UNIQUE index against the attempted-insert values; on the first hit,
        // position the table cursor on that row via its PK suffix and route to
        // `conflict_label`. An explicit PRIMARY KEY target skips this (PK-only).
        if probe_unique_secondaries {
            for (idx_offset, index) in table.indexes.iter().enumerate() {
                if !index.is_unique {
                    continue;
                }
                let idx_cursor = table_cursor + 1 + idx_offset as i32;
                let n_idx_cols = index.key_term_count();
                let next_index = b.emit_label();
                let scan_ctx = ScanCtx {
                    cursor: table_cursor,
                    table,
                    table_alias: None,
                    schema: None,
                    register_base: Some(val_regs),
                    secondaries: &[],
                };
                let idx_key_regs = b.alloc_regs(n_idx_cols as i32);
                for key_pos in 0..n_idx_cols {
                    emit_index_key_term(
                        b,
                        index,
                        key_pos,
                        idx_key_regs + key_pos as i32,
                        &scan_ctx,
                    );
                }
                let idx_probe_rec = b.alloc_reg();
                b.emit_op(
                    Opcode::MakeRecord,
                    idx_key_regs,
                    n_idx_cols as i32,
                    idx_probe_rec,
                    P4::None,
                    0,
                );
                // NoConflict jumps to `next_index` when no existing entry shares
                // these key terms (a NULL key term never conflicts — SQLite UNIQUE
                // semantics). On a conflict the index cursor is positioned on the
                // conflicting entry.
                b.emit_jump_to_label(
                    Opcode::NoConflict,
                    idx_cursor,
                    idx_probe_rec,
                    next_index,
                    P4::None,
                    0,
                );
                // Position the table cursor on the conflicting row via the index
                // entry's PK suffix, then route to `conflict_label`. If the index
                // and table are inconsistent (row missing), route to
                // `no_conflict_label`.
                emit_without_rowid_index_to_table_seek(
                    b,
                    table,
                    table_cursor,
                    idx_cursor,
                    index,
                    pk_indices,
                    no_conflict_label,
                );
                b.emit_jump_to_label(Opcode::Goto, 0, 0, conflict_label, P4::None, 0);
                b.resolve_label(next_index);
            }
        }
        // No uniqueness conflict against this clause's target(s).
        b.emit_jump_to_label(Opcode::Goto, 0, 0, no_conflict_label, P4::None, 0);
    }
}

/// Emit the DO UPDATE apply body for one UPSERT clause on a WITHOUT ROWID table.
/// The table cursor must already be positioned on the conflicting row (by
/// [`emit_without_rowid_upsert_probe`]). Reads the existing row, evaluates the
/// optional `WHERE` (on false/NULL skips the whole update), applies the SET
/// assignments (with `excluded.*` bound to the attempted-insert registers),
/// re-validates constraints, removes the OLD row + index entries, re-inserts the
/// rewritten image, and emits RETURNING. Does not emit the trailing jump to the
/// chain's done label — the caller does.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
#[allow(clippy::too_many_arguments)]
fn emit_without_rowid_upsert_do_update_apply(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    val_regs: i32,
    pk_indices: &[usize],
    stmt_level: Option<ConflictAction>,
    assignments: &[fsqlite_ast::Assignment],
    where_clause: Option<&Expr>,
    target_alias: Option<&str>,
    returning: &[ResultColumn],
    schema: &[TableSchema],
) -> Result<(), CodegenError> {
    let n_cols = table.columns.len();
    let n_pk = pk_indices.len();

    let existing_regs = b.alloc_regs(n_cols as i32);
    for i in 0..n_cols {
        b.emit_op(
            Opcode::Column,
            table_cursor,
            i as i32,
            existing_regs + i as i32,
            P4::None,
            0,
        );
    }

    // `excluded.*` resolves to the attempted-insert values (val_regs); unqualified
    // column refs resolve to the existing row (existing_regs).
    //
    // bd-xjfrt: as in the rowid path, `existing_ctx` carries the real `schema` and
    // a register-backed `excluded.*` secondary so correlated subqueries/EXISTS in
    // a DO UPDATE SET expression resolve against the target row and val_regs
    // instead of collapsing to NULL.
    let excluded_secondary = [SecondaryScan {
        cursor: table_cursor,
        table,
        table_alias: Some("excluded"),
        register_base: Some(val_regs),
    }];
    let excluded_ctx = ScanCtx {
        cursor: table_cursor,
        table,
        table_alias: Some("excluded"),
        schema: Some(schema),
        register_base: Some(val_regs),
        secondaries: &[],
    };
    let existing_ctx = ScanCtx {
        cursor: table_cursor,
        table,
        table_alias: target_alias,
        schema: Some(schema),
        register_base: Some(existing_regs),
        secondaries: &excluded_secondary,
    };
    // WITHOUT ROWID tables have no hidden rowid, so no column ever resolves to a
    // hidden rowid; the excluded-side helper still needs a register value, so
    // pass a scratch register that is never read.
    let excluded_hidden_rowid_reg = b.alloc_reg();

    // Optional `DO UPDATE SET ... WHERE <cond>`: when false/NULL, skip the whole
    // update (and its RETURNING row), leaving the existing row unchanged. A
    // skipped update still counts the conflict as handled — the caller jumps to
    // the chain's done label, so the row is neither updated nor inserted.
    let skip_update_label = if let Some(where_expr) = where_clause {
        let label = b.emit_label();
        let where_reg = b.alloc_reg();
        emit_upsert_expr(
            b,
            where_expr,
            where_reg,
            &existing_ctx,
            &excluded_ctx,
            table,
            None,
            excluded_hidden_rowid_reg,
        );
        b.emit_jump_to_label(Opcode::IfNot, where_reg, 1, label, P4::None, 0);
        Some(label)
    } else {
        None
    };

    // Apply the assignments into the existing-row image, recompute generated
    // columns, and validate constraints on the new image.
    emit_upsert_assignments(
        b,
        assignments,
        table,
        existing_regs,
        &existing_ctx,
        &excluded_ctx,
        None,
        excluded_hidden_rowid_reg,
    )?;
    emit_stored_generated_columns(b, table, existing_regs);
    emit_strict_type_check(b, table, existing_regs);
    // GH #169: coerce to column affinity before CHECK/NOT NULL so the
    // constraints see the affinity-coerced value (SQLite applies affinity, then
    // evaluates constraints).
    b.emit_op(
        Opcode::Affinity,
        existing_regs,
        n_cols as i32,
        0,
        P4::Affinity(table.affinity_string()),
        0,
    );
    emit_check_constraints(b, table, existing_regs, None);
    emit_not_null_constraints(b, table, existing_regs, stmt_level, None);

    // Remove the OLD secondary-index entries (read from the cursor's old row)
    // and the OLD table row, then insert the rewritten row + new index entries.
    emit_without_rowid_index_deletes(b, table, table_cursor, None, pk_indices);
    b.emit_op(Opcode::IdxDelete, table_cursor, 0, 0, P4::None, 0);

    let aff_str = table.affinity_string();
    b.emit_op(
        Opcode::Affinity,
        existing_regs,
        n_cols as i32,
        0,
        P4::Affinity(aff_str.clone()),
        0,
    );
    let rec_reg = emit_wr_record(b, pk_indices, existing_regs, n_cols, &aff_str);
    b.emit_op(
        Opcode::IdxInsert,
        table_cursor,
        rec_reg,
        n_pk as i32,
        P4::Table(without_rowid_pk_label(table, pk_indices)),
        1u16 | (OE_ABORT << 1) | OPFLAG_IDX_NCHANGE,
    );
    emit_without_rowid_index_inserts(
        b,
        table,
        table_cursor,
        existing_regs,
        pk_indices,
        stmt_level,
        false,
    );

    if !returning.is_empty() {
        emit_returning_from_regs(b, table, returning, target_alias, schema, existing_regs)?;
    }
    // A false `WHERE` skips straight here (no update, no RETURNING); the caller
    // then jumps to the chain's done label.
    if let Some(label) = skip_update_label {
        b.resolve_label(label);
    }
    Ok(())
}

/// Open the table (index) cursor plus all secondary-index cursors for write.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_without_rowid_open_write(b: &mut ProgramBuilder, table: &TableSchema, table_cursor: i32) {
    b.emit_op(
        Opcode::OpenWrite,
        table_cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );
    for (idx_offset, index) in table.indexes.iter().enumerate() {
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        b.emit_op(
            Opcode::OpenWrite,
            idx_cursor,
            index.root_page,
            0,
            P4::Table(index.name.clone()),
            0,
        );
    }
}

/// Close the table cursor and all secondary-index cursors.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_without_rowid_close(b: &mut ProgramBuilder, table: &TableSchema, table_cursor: i32) {
    b.emit_op(Opcode::Close, table_cursor, 0, 0, P4::None, 0);
    for idx_offset in 0..table.indexes.len() {
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        b.emit_op(Opcode::Close, idx_cursor, 0, 0, P4::None, 0);
    }
}

/// Code generation for INSERT into a WITHOUT ROWID table.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn codegen_insert_without_rowid(
    b: &mut ProgramBuilder,
    stmt: &InsertStatement,
    table: &TableSchema,
    schema: &[TableSchema],
    _ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    let pk_indices = without_rowid_pk_indices(table)?;
    let table_cursor = 0_i32;
    let n_cols = table.columns.len();
    let target_alias = stmt.alias.as_deref();

    // Conflict behavior. A statement-level `INSERT OR <algo>` (or the default
    // ABORT) governs BOTH the pre-insert NOT NULL/CHECK checks on the candidate
    // row and the fall-through insert's remaining (non-target) UNIQUE/PK
    // constraints. The per-constraint `ON CONFLICT` chain is routed row-by-row in
    // `emit_without_rowid_row_insert`: each clause probes its own target in
    // written order and the first whose target conflicts is applied (DO UPDATE
    // rewrites the conflicting row; DO NOTHING skips the insert). A conflict on a
    // constraint that no clause targets falls through to `stmt_level` (default
    // ABORT), matching stock (multiple ON CONFLICT clauses, SQLite 3.35+). Stock
    // enforces candidate NOT NULL/CHECK even for a row that will conflict, so
    // these are NOT blanket-IGNORE'd (bd-xa2qv, mirrors bd-aap9u on the rowid
    // path).
    let oe_flag = conflict_action_to_oe(stmt.or_conflict.as_ref());
    let stmt_level: Option<ConflictAction> = stmt.or_conflict;
    // Validate every clause's conflict target + DO UPDATE assignment/WHERE
    // columns up front for error parity. Every emittable target shape is covered
    // by the WITHOUT ROWID upsert probe: the PRIMARY KEY
    // (`upsert_target_matches_without_rowid_primary_key`), an omitted target (any
    // UNIQUE constraint), and an explicit secondary-UNIQUE index target
    // (`find_upsert_target_index`, bd-yqjjx); a target that matches none raises
    // the same error stock does.
    for clause in &stmt.upsert {
        if let Some(target) = clause.target.as_ref()
            && find_upsert_target_index(table, Some(target)).is_none()
            && !upsert_target_matches_without_rowid_primary_key(table, target)
        {
            return Err(CodegenError::SqlError(
                "ON CONFLICT clause does not match any PRIMARY KEY or UNIQUE constraint".to_owned(),
            ));
        }
        if let UpsertAction::Update {
            assignments,
            where_clause,
        } = &clause.action
        {
            for assign in assignments {
                validate_assignment_target(table, &assign.target)?;
                validate_upsert_expr_columns(&assign.value, table, target_alias)?;
            }
            if let Some(where_expr) = where_clause {
                validate_upsert_expr_columns(where_expr, table, target_alias)?;
            }
        }
    }

    let end_label = b.emit_label();
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 1, 0, P4::None, 0);
    emit_without_rowid_open_write(b, table, table_cursor);

    match &stmt.source {
        InsertSource::Values(rows) => {
            if rows.is_empty() {
                return Err(CodegenError::Unsupported("empty VALUES".to_owned()));
            }
            let target_mapping = build_insert_target_mapping(&stmt.columns, table)?;
            let n_source_cols = rows[0].len();
            let expected = target_mapping
                .as_ref()
                .map_or(n_cols, |m| m.expected_source_cols);
            if n_source_cols != expected {
                return Err(CodegenError::Unsupported(format!(
                    "table {} has {} columns but {} values were supplied",
                    table.name, expected, n_source_cols
                )));
            }
            let source_regs = b.alloc_regs(n_source_cols as i32);
            let mapped_regs = target_mapping.as_ref().map(|_| b.alloc_regs(n_cols as i32));
            for row_values in rows {
                if row_values.len() != n_source_cols {
                    return Err(CodegenError::SqlError(
                        "all VALUES must have the same number of terms".to_owned(),
                    ));
                }
                for (i, val_expr) in row_values.iter().enumerate() {
                    emit_expr(b, val_expr, source_regs + i as i32, None);
                }
                let val_regs = if let Some(mapping) = target_mapping.as_ref() {
                    let table_regs = mapped_regs.expect("mapped registers allocated");
                    for (tbl_idx, src) in mapping.col_mapping.iter().enumerate() {
                        let dest = table_regs + tbl_idx as i32;
                        if let Some(pos) = src {
                            b.emit_op(
                                Opcode::Copy,
                                source_regs + *pos as i32,
                                dest,
                                0,
                                P4::None,
                                0,
                            );
                        } else {
                            emit_default_value(b, &table.columns[tbl_idx], dest)?;
                        }
                    }
                    table_regs
                } else {
                    source_regs
                };
                emit_without_rowid_row_insert(
                    b,
                    table,
                    table_cursor,
                    val_regs,
                    &pk_indices,
                    oe_flag,
                    stmt_level,
                    &stmt.upsert,
                    target_alias,
                    &stmt.returning,
                    schema,
                )?;
            }
        }
        InsertSource::DefaultValues => {
            let val_regs = b.alloc_regs(n_cols as i32);
            for (idx, col) in table.columns.iter().enumerate() {
                emit_default_value(b, col, val_regs + idx as i32)?;
            }
            emit_without_rowid_row_insert(
                b,
                table,
                table_cursor,
                val_regs,
                &pk_indices,
                oe_flag,
                stmt_level,
                &stmt.upsert,
                target_alias,
                &stmt.returning,
                schema,
            )?;
        }
        InsertSource::Select(select_stmt) => {
            let target_mapping = build_insert_target_mapping(&stmt.columns, table)?;
            emit_without_rowid_insert_select(
                b,
                stmt,
                select_stmt,
                table,
                schema,
                &pk_indices,
                oe_flag,
                stmt_level,
                &stmt.upsert,
                target_alias,
                target_mapping.as_ref(),
                table_cursor,
            )?;
        }
    }

    emit_without_rowid_close(b, table, table_cursor);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// `INSERT ... SELECT` into a WITHOUT ROWID table. Scans a single source table
/// (or evaluates a FROM-less constant projection), maps the projected columns
/// into table-declared order (honoring an explicit column list, filling the
/// rest with DEFAULTs), and routes each row through
/// [`emit_without_rowid_row_insert`] so conflict handling, constraints, index
/// maintenance, and RETURNING are shared with the VALUES path.
///
/// Only the shapes the rowid `codegen_insert_select` itself supports are
/// accepted: a single named source table or no FROM. CTEs, compound
/// (UNION/INTERSECT/EXCEPT), ORDER BY/LIMIT, DISTINCT/GROUP BY/HAVING/window,
/// joins, subquery/VALUES sources, and `source == target` are rejected with a
/// clear error rather than silently mis-executed.
#[allow(
    clippy::too_many_arguments,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap
)]
fn emit_without_rowid_insert_select(
    b: &mut ProgramBuilder,
    stmt: &InsertStatement,
    select_stmt: &SelectStatement,
    table: &TableSchema,
    schema: &[TableSchema],
    pk_indices: &[usize],
    oe_flag: u16,
    stmt_level: Option<ConflictAction>,
    upserts: &[UpsertClause],
    target_alias: Option<&str>,
    target_mapping: Option<&InsertTargetMapping>,
    table_cursor: i32,
) -> Result<(), CodegenError> {
    if select_stmt.with.is_some() {
        return Err(CodegenError::Unsupported(
            "INSERT ... WITH ... SELECT into WITHOUT ROWID tables is not yet supported".to_owned(),
        ));
    }
    if !select_stmt.body.compounds.is_empty() {
        return Err(CodegenError::Unsupported(
            "INSERT ... SELECT with a compound (UNION/INTERSECT/EXCEPT) into WITHOUT ROWID tables \
             is not yet supported"
                .to_owned(),
        ));
    }
    if !select_stmt.order_by.is_empty() || select_stmt.limit.is_some() {
        return Err(CodegenError::Unsupported(
            "INSERT ... SELECT with ORDER BY/LIMIT into WITHOUT ROWID tables is not yet supported"
                .to_owned(),
        ));
    }
    let (distinct, columns, from, where_clause, group_by, having, windows) =
        match &select_stmt.body.select {
            SelectCore::Select {
                distinct,
                columns,
                from,
                where_clause,
                group_by,
                having,
                windows,
            } => (
                distinct,
                columns,
                from,
                where_clause,
                group_by,
                having,
                windows,
            ),
            SelectCore::Values(_) => {
                return Err(CodegenError::Unsupported(
                    "INSERT ... SELECT with a VALUES body into WITHOUT ROWID tables is not yet \
                     supported"
                        .to_owned(),
                ));
            }
        };
    if *distinct != Distinctness::All
        || !group_by.is_empty()
        || having.is_some()
        || !windows.is_empty()
    {
        return Err(CodegenError::Unsupported(
            "INSERT ... SELECT with DISTINCT/GROUP BY/HAVING/window into WITHOUT ROWID tables is \
             not yet supported"
                .to_owned(),
        ));
    }

    let n_cols = table.columns.len();
    let expected = target_mapping.map_or(n_cols, |m| m.expected_source_cols);
    let returning = &stmt.returning;

    // Reorder a SELECT-output row (`sel_regs`, `n_sel` columns) into
    // table-declared order, filling unmentioned columns with DEFAULTs, then run
    // the shared WITHOUT ROWID per-row insert. Returns nothing; emits opcodes.
    // Implemented inline in both branches below because the borrow of `b` cannot
    // be shared across a closure that also calls other `&mut b` helpers.

    if let Some(from_clause) = from {
        if !from_clause.joins.is_empty() {
            return Err(CodegenError::Unsupported(
                "INSERT ... SELECT with a JOIN into WITHOUT ROWID tables is not yet supported"
                    .to_owned(),
            ));
        }
        let (src_name, src_alias) = match &from_clause.source {
            fsqlite_ast::TableOrSubquery::Table { name, alias, .. } => {
                (&name.name, alias.as_deref())
            }
            _ => {
                return Err(CodegenError::Unsupported(
                    "INSERT ... SELECT from a non-table source into WITHOUT ROWID tables is not \
                     yet supported"
                        .to_owned(),
                ));
            }
        };
        if src_name.eq_ignore_ascii_case(&table.name) {
            return Err(CodegenError::Unsupported(
                "INSERT ... SELECT where the source is the target WITHOUT ROWID table is not yet \
                 supported"
                    .to_owned(),
            ));
        }
        let src_table = find_table(schema, src_name)?;
        let read_cursor = table.indexes.len() as i32 + 1;
        let n_sel = result_column_count(columns, src_table);
        if n_sel as usize != expected {
            return Err(CodegenError::Unsupported(format!(
                "table {} has {} columns but {} values were supplied",
                table.name, expected, n_sel
            )));
        }

        b.emit_op(
            Opcode::OpenRead,
            read_cursor,
            src_table.root_page,
            0,
            P4::Table(src_table.name.clone()),
            0,
        );
        let done_label = b.emit_label();
        let loop_start = b.current_addr();
        b.emit_jump_to_label(Opcode::Rewind, read_cursor, 0, done_label, P4::None, 0);
        let skip_label = b.emit_label();
        if let Some(where_expr) = where_clause {
            emit_where_filter(
                b,
                where_expr,
                read_cursor,
                src_table,
                src_alias,
                schema,
                skip_label,
            );
        }
        let sel_regs = b.alloc_regs(n_sel);
        emit_column_reads(
            b,
            read_cursor,
            columns,
            src_table,
            src_alias,
            schema,
            sel_regs,
        )?;
        let val_regs =
            map_insert_select_row_to_table_order(b, table, target_mapping, sel_regs, n_cols)?;
        emit_without_rowid_row_insert(
            b,
            table,
            table_cursor,
            val_regs,
            pk_indices,
            oe_flag,
            stmt_level,
            upserts,
            target_alias,
            returning,
            schema,
        )?;
        b.resolve_label(skip_label);
        b.emit_op(
            Opcode::Next,
            read_cursor,
            (loop_start + 1) as i32,
            0,
            P4::None,
            0,
        );
        b.resolve_label(done_label);
        b.emit_op(Opcode::Close, read_cursor, 0, 0, P4::None, 0);
    } else {
        // FROM-less constant projection: a single row (optionally gated by a
        // constant WHERE predicate).
        let n_sel = result_column_count_without_from(columns)?;
        if n_sel as usize != expected {
            return Err(CodegenError::Unsupported(format!(
                "table {} has {} columns but {} values were supplied",
                table.name, expected, n_sel
            )));
        }
        let skip_label = b.emit_label();
        if let Some(where_expr) = where_clause {
            let pred = b.alloc_temp();
            emit_expr(b, where_expr, pred, None);
            b.emit_jump_to_label(Opcode::IfNot, pred, 1, skip_label, P4::None, 0);
            b.free_temp(pred);
        }
        let sel_regs = b.alloc_regs(n_sel);
        emit_projection_without_from(b, columns, sel_regs)?;
        let val_regs =
            map_insert_select_row_to_table_order(b, table, target_mapping, sel_regs, n_cols)?;
        emit_without_rowid_row_insert(
            b,
            table,
            table_cursor,
            val_regs,
            pk_indices,
            oe_flag,
            stmt_level,
            upserts,
            target_alias,
            returning,
            schema,
        )?;
        b.resolve_label(skip_label);
    }
    Ok(())
}

/// Reorder a SELECT-output row (`sel_regs`, in SELECT order) into table-declared
/// column order for an `INSERT ... SELECT` with an explicit column list, filling
/// unmentioned columns with their DEFAULTs. With no explicit column list the
/// SELECT row is already in table order and `sel_regs` is returned unchanged.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn map_insert_select_row_to_table_order(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    target_mapping: Option<&InsertTargetMapping>,
    sel_regs: i32,
    n_cols: usize,
) -> Result<i32, CodegenError> {
    let Some(mapping) = target_mapping else {
        return Ok(sel_regs);
    };
    let table_regs = b.alloc_regs(n_cols as i32);
    for (tbl_idx, src) in mapping.col_mapping.iter().enumerate() {
        let dest = table_regs + tbl_idx as i32;
        if let Some(pos) = src {
            b.emit_op(Opcode::Copy, sel_regs + *pos as i32, dest, 0, P4::None, 0);
        } else {
            emit_default_value(b, &table.columns[tbl_idx], dest)?;
        }
    }
    Ok(table_regs)
}

/// Emit pass 1 of a WITHOUT ROWID UPDATE/DELETE: scan the table, apply the WHERE
/// filter, and collect each matching row's full record into a sorter (so the
/// table b-tree is not mutated mid-scan). Returns the sorter cursor id.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_without_rowid_collect_matches(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    schema: &[TableSchema],
    where_clause: Option<&Expr>,
    table_alias: Option<&str>,
    // Anon-placeholder number the WHERE filter starts from. For DELETE this is
    // the current counter (1); for UPDATE it is `set_placeholder_count + 1`,
    // because the SET assignments (Pass 2) appear first in the SQL text but are
    // emitted *after* this collect pass (bd-q3hu3).
    where_placeholder_base: u32,
) -> i32 {
    let n_cols = table.columns.len();
    let sorter_cursor = table.indexes.len() as i32 + 1;
    b.emit_op(
        Opcode::SorterOpen,
        sorter_cursor,
        n_cols as i32,
        0,
        P4::Str("+".repeat(n_cols)),
        0,
    );

    let scan_start = b.current_addr();
    let scan_done = b.emit_label();
    b.emit_jump_to_label(Opcode::Rewind, table_cursor, 0, scan_done, P4::None, 0);

    let skip_label = b.emit_label();
    if let Some(where_expr) = where_clause {
        b.set_next_anon_placeholder(where_placeholder_base);
        emit_where_filter(
            b,
            where_expr,
            table_cursor,
            table,
            table_alias,
            schema,
            skip_label,
        );
    }
    let row_regs = b.alloc_regs(n_cols as i32);
    for i in 0..n_cols {
        b.emit_op(
            Opcode::Column,
            table_cursor,
            i as i32,
            row_regs + i as i32,
            P4::None,
            0,
        );
    }
    let rec_reg = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        row_regs,
        n_cols as i32,
        rec_reg,
        P4::None,
        0,
    );
    b.emit_op(Opcode::SorterInsert, sorter_cursor, rec_reg, 0, P4::None, 0);
    b.resolve_label(skip_label);
    b.emit_op(
        Opcode::Next,
        table_cursor,
        (scan_start + 1) as i32,
        0,
        P4::None,
        0,
    );
    b.resolve_label(scan_done);

    sorter_cursor
}

/// Code generation for DELETE from a WITHOUT ROWID table.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn codegen_delete_without_rowid(
    b: &mut ProgramBuilder,
    stmt: &DeleteStatement,
    table: &TableSchema,
    schema: &[TableSchema],
    _ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    if !stmt.order_by.is_empty() || stmt.limit.is_some() {
        return Err(CodegenError::Unsupported(
            "DELETE ORDER BY/LIMIT/OFFSET must be materialized before codegen".to_owned(),
        ));
    }
    if let Some(where_expr) = &stmt.where_clause {
        validate_single_table_expr_columns(where_expr, table, stmt.table.alias.as_deref())?;
    }
    let pk_indices = without_rowid_pk_indices(table)?;
    let table_cursor = 0_i32;
    let n_cols = table.columns.len();
    let n_pk = pk_indices.len();

    let end_label = b.emit_label();
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 1, 0, P4::None, 0);
    emit_without_rowid_open_write(b, table, table_cursor);

    // DELETE has no SET clause, so the WHERE placeholders keep their natural
    // numbering (the current counter, 1).
    let where_placeholder_base = b.current_anon_placeholder();
    let sorter_cursor = emit_without_rowid_collect_matches(
        b,
        table,
        table_cursor,
        schema,
        stmt.where_clause.as_ref(),
        stmt.table.alias.as_deref(),
        where_placeholder_base,
    );

    // Pass 2: re-seek each collected row by primary key and delete it.
    let pass2_done = b.emit_label();
    b.emit_jump_to_label(
        Opcode::SorterSort,
        sorter_cursor,
        0,
        pass2_done,
        P4::None,
        0,
    );
    let loop_body = b.current_addr();
    let sorted_reg = b.alloc_reg();
    b.emit_op(
        Opcode::SorterData,
        sorter_cursor,
        sorted_reg,
        0,
        P4::None,
        0,
    );
    let row_regs = b.alloc_regs(n_cols as i32);
    for i in 0..n_cols {
        b.emit_op(
            Opcode::Column,
            sorter_cursor,
            i as i32,
            row_regs + i as i32,
            P4::None,
            0,
        );
    }
    let pk_probe_regs = b.alloc_regs(n_pk as i32);
    for (j, &pk_col) in pk_indices.iter().enumerate() {
        b.emit_op(
            Opcode::Copy,
            row_regs + pk_col as i32,
            pk_probe_regs + j as i32,
            0,
            P4::None,
            0,
        );
    }
    let pk_probe_rec = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        pk_probe_regs,
        n_pk as i32,
        pk_probe_rec,
        P4::None,
        0,
    );
    let not_found = b.emit_label();
    b.emit_jump_to_label(
        Opcode::NoConflict,
        table_cursor,
        pk_probe_rec,
        not_found,
        P4::None,
        0,
    );
    emit_without_rowid_index_deletes(b, table, table_cursor, Some(row_regs), &pk_indices);
    b.emit_op(Opcode::IdxDelete, table_cursor, 0, 0, P4::None, 1);
    // RETURNING: emit the deleted row image (row_regs holds the OLD values read
    // from the sorter). Only reached when the row was actually found+deleted.
    if !stmt.returning.is_empty() {
        emit_returning_from_regs(
            b,
            table,
            &stmt.returning,
            stmt.table.alias.as_deref(),
            schema,
            row_regs,
        )?;
    }
    b.resolve_label(not_found);
    b.emit_op(
        Opcode::SorterNext,
        sorter_cursor,
        loop_body as i32,
        0,
        P4::None,
        0,
    );
    b.resolve_label(pass2_done);

    b.emit_op(Opcode::Close, sorter_cursor, 0, 0, P4::None, 0);
    emit_without_rowid_close(b, table, table_cursor);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Code generation for UPDATE of a WITHOUT ROWID table.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn codegen_update_without_rowid(
    b: &mut ProgramBuilder,
    stmt: &UpdateStatement,
    table: &TableSchema,
    schema: &[TableSchema],
    _ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    if let Some(from_clause) = &stmt.from {
        return codegen_update_from_without_rowid(b, stmt, from_clause, table, schema, _ctx);
    }
    if !stmt.order_by.is_empty() || stmt.limit.is_some() {
        return Err(CodegenError::Unsupported(
            "UPDATE ORDER BY/LIMIT/OFFSET must be materialized before codegen".to_owned(),
        ));
    }
    for assign in &stmt.assignments {
        validate_single_table_expr_columns(&assign.value, table, stmt.table.alias.as_deref())?;
    }
    if let Some(where_expr) = &stmt.where_clause {
        validate_single_table_expr_columns(where_expr, table, stmt.table.alias.as_deref())?;
    }
    let pk_indices = without_rowid_pk_indices(table)?;
    let table_cursor = 0_i32;
    let n_cols = table.columns.len();
    let n_pk = pk_indices.len();
    let oe_flag = conflict_action_to_oe(stmt.or_conflict.as_ref());

    let end_label = b.emit_label();
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 1, 0, P4::None, 0);
    emit_without_rowid_open_write(b, table, table_cursor);

    // The WHERE filter (Pass 1) is emitted before the SET assignments (Pass 2),
    // but the SET placeholders come first in the SQL text. Number the WHERE anon
    // placeholders from `set_placeholder_count + 1` so a bound `UPDATE ... SET
    // a=?, b=? WHERE k1=? AND k2=?` reads slots 3,4 in the WHERE — not 1,2, which
    // silently seeked a non-existent key and matched 0 rows (bd-q3hu3). Mirrors
    // the rowid `codegen_update` two-pass numbering.
    let set_placeholder_count: u32 = stmt
        .assignments
        .iter()
        .map(|a| count_anon_placeholders(&a.value))
        .sum();

    let sorter_cursor = emit_without_rowid_collect_matches(
        b,
        table,
        table_cursor,
        schema,
        stmt.where_clause.as_ref(),
        stmt.table.alias.as_deref(),
        set_placeholder_count + 1,
    );

    // Pass 2: for each collected row, delete the old entry then insert the
    // rewritten row. The column registers hold the OLD image first (used to
    // remove the old table + index entries), then are overwritten by the
    // assignments to become the NEW image for re-insertion.
    let pass2_done = b.emit_label();
    b.emit_jump_to_label(
        Opcode::SorterSort,
        sorter_cursor,
        0,
        pass2_done,
        P4::None,
        0,
    );
    let loop_body = b.current_addr();
    let sorted_reg = b.alloc_reg();
    b.emit_op(
        Opcode::SorterData,
        sorter_cursor,
        sorted_reg,
        0,
        P4::None,
        0,
    );
    let col_regs = b.alloc_regs(n_cols as i32);
    for i in 0..n_cols {
        b.emit_op(
            Opcode::Column,
            sorter_cursor,
            i as i32,
            col_regs + i as i32,
            P4::None,
            0,
        );
    }

    // Re-seek the OLD row by primary key (positions the table cursor).
    let pk_probe_regs = b.alloc_regs(n_pk as i32);
    for (j, &pk_col) in pk_indices.iter().enumerate() {
        b.emit_op(
            Opcode::Copy,
            col_regs + pk_col as i32,
            pk_probe_regs + j as i32,
            0,
            P4::None,
            0,
        );
    }
    let pk_probe_rec = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        pk_probe_regs,
        n_pk as i32,
        pk_probe_rec,
        P4::None,
        0,
    );
    let row_done = b.emit_label();
    b.emit_jump_to_label(
        Opcode::NoConflict,
        table_cursor,
        pk_probe_rec,
        row_done,
        P4::None,
        0,
    );

    // bd-yuj70: preserve the OLD image before the assignments overwrite
    // `col_regs`. The OLD secondary-index keys are derived from it *after* the
    // NEW primary key has been probed, so no mutation happens before the
    // conflict action is resolved.
    let old_regs = b.alloc_regs(n_cols as i32);
    for i in 0..n_cols {
        b.emit_op(
            Opcode::Copy,
            col_regs + i as i32,
            old_regs + i as i32,
            0,
            P4::None,
            0,
        );
    }

    // Compute the NEW image in place, then validate constraints. Nothing below
    // this point has mutated the table yet, so OR IGNORE can bail cleanly and
    // the ABORT family can raise with the OLD row still intact.
    let update_ctx = ScanCtx {
        cursor: table_cursor,
        table,
        table_alias: stmt.table.alias.as_deref(),
        schema: Some(schema),
        register_base: Some(col_regs),
        secondaries: &[],
    };
    // Reset the placeholder counter to 1 for the SET expressions (Pass 2): they
    // appear first in the SQL text, so their anon placeholders are slots 1..N
    // (bd-q3hu3).
    b.set_next_anon_placeholder(1);
    emit_update_assignments(b, &stmt.assignments, table, col_regs, &update_ctx)?;
    emit_stored_generated_columns(b, table, col_regs);
    emit_strict_type_check(b, table, col_regs);
    // GH #169: coerce to column affinity before CHECK/NOT NULL so the
    // constraints see the affinity-coerced value (SQLite applies affinity, then
    // evaluates constraints).
    b.emit_op(
        Opcode::Affinity,
        col_regs,
        n_cols as i32,
        0,
        P4::Affinity(table.affinity_string()),
        0,
    );
    let ignore_skip = if oe_flag == OE_IGNORE {
        Some(row_done)
    } else {
        None
    };
    emit_check_constraints(b, table, col_regs, ignore_skip);
    emit_not_null_constraints(b, table, col_regs, stmt.or_conflict, ignore_skip);

    // Apply column affinities before the primary-key probe so the comparison
    // and the stored record agree on representation.
    b.emit_op(
        Opcode::Affinity,
        col_regs,
        n_cols as i32,
        0,
        P4::Affinity(table.affinity_string()),
        0,
    );

    emit_without_rowid_update_rewrite(
        b,
        table,
        table_cursor,
        col_regs,
        old_regs,
        pk_probe_regs,
        &pk_indices,
        oe_flag,
        stmt.or_conflict,
        row_done,
    );

    // RETURNING: emit the NEW row image (col_regs now holds the rewritten row).
    if !stmt.returning.is_empty() {
        emit_returning_from_regs(
            b,
            table,
            &stmt.returning,
            stmt.table.alias.as_deref(),
            schema,
            col_regs,
        )?;
    }

    b.resolve_label(row_done);
    b.emit_op(
        Opcode::SorterNext,
        sorter_cursor,
        loop_body as i32,
        0,
        P4::None,
        0,
    );
    b.resolve_label(pass2_done);

    b.emit_op(Opcode::Close, sorter_cursor, 0, 0, P4::None, 0);
    emit_without_rowid_close(b, table, table_cursor);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

/// Code generation for `UPDATE <wr_table> SET ... FROM <sources> [WHERE ...]`
/// where the target is a WITHOUT ROWID table.
///
/// A nested-loop join (FROM sources outer, target inner) mirrors the rowid
/// [`codegen_update_from`], but because the WITHOUT ROWID table IS the index
/// b-tree being scanned, mutating it mid-scan would invalidate the cursor. So
/// this is a two-pass strategy: pass 1 runs the join, and for every matching
/// (target, source) combination collects the `[OLD image || NEW image]` into a
/// sorter (the NEW image is computed while the FROM cursors are live, since the
/// assignments may reference FROM columns); pass 2 re-seeks each target by its
/// OLD primary key and rewrites it (delete OLD table + index entries, insert the
/// NEW row + index entries). Inner-join semantics; only named table sources.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::too_many_lines
)]
fn codegen_update_from_without_rowid(
    b: &mut ProgramBuilder,
    stmt: &UpdateStatement,
    from_clause: &FromClause,
    table: &TableSchema,
    schema: &[TableSchema],
    _ctx: &CodegenContext,
) -> Result<(), CodegenError> {
    use fsqlite_ast::{JoinConstraint, JoinKind};

    if !stmt.order_by.is_empty() || stmt.limit.is_some() {
        return Err(CodegenError::Unsupported(
            "UPDATE ORDER BY/LIMIT/OFFSET must be materialized before codegen".to_owned(),
        ));
    }

    // Resolve a single FROM source to (name, alias). Only named tables are
    // supported (matching the rowid `codegen_update_from`).
    fn resolve_from_table(src: &TableOrSubquery) -> Result<(&str, Option<&str>), CodegenError> {
        match src {
            TableOrSubquery::Table { name, alias, .. } => {
                Ok((name.name.as_str(), alias.as_deref()))
            }
            TableOrSubquery::Subquery { .. } => Err(CodegenError::Unsupported(
                "UPDATE ... FROM subquery sources are not yet supported on WITHOUT ROWID tables"
                    .to_owned(),
            )),
            _ => Err(CodegenError::Unsupported(
                "UPDATE ... FROM only supports named tables on WITHOUT ROWID tables".to_owned(),
            )),
        }
    }

    // Collect FROM sources (leading + comma/JOIN) and any ON conditions.
    let mut from_specs: Vec<(&str, Option<&str>)> = Vec::with_capacity(1 + from_clause.joins.len());
    from_specs.push(resolve_from_table(&from_clause.source)?);
    let mut on_conditions: Vec<&Expr> = Vec::new();
    for join in &from_clause.joins {
        if join.join_type.natural {
            return Err(CodegenError::Unsupported(
                "UPDATE ... FROM with NATURAL JOIN is not yet supported on WITHOUT ROWID tables"
                    .to_owned(),
            ));
        }
        match join.join_type.kind {
            JoinKind::Inner | JoinKind::Cross => {}
            JoinKind::Left | JoinKind::Right | JoinKind::Full => {
                return Err(CodegenError::Unsupported(
                    "UPDATE ... FROM with an OUTER JOIN source is not yet supported on WITHOUT \
                     ROWID tables"
                        .to_owned(),
                ));
            }
        }
        from_specs.push(resolve_from_table(&join.table)?);
        match &join.constraint {
            Some(JoinConstraint::On(expr)) => on_conditions.push(expr),
            Some(JoinConstraint::Using(_)) => {
                return Err(CodegenError::Unsupported(
                    "UPDATE ... FROM with a USING(...) join constraint is not yet supported on \
                     WITHOUT ROWID tables"
                        .to_owned(),
                ));
            }
            None => {}
        }
    }

    let pk_indices = without_rowid_pk_indices(table)?;
    let n_cols = table.columns.len();
    let n_pk = pk_indices.len();
    let n_indexes = table.indexes.len();
    let target_cursor = 0_i32;
    let oe_flag = conflict_action_to_oe(stmt.or_conflict.as_ref());

    // Cursor allocation: 0 = target (write), 1..=n_indexes = target indexes,
    // then one read cursor per FROM source, then the sorter.
    let mut secondaries: Vec<SecondaryScan> = Vec::with_capacity(from_specs.len());
    for (i, (src_name, src_alias)) in from_specs.iter().enumerate() {
        let src_table = find_table(schema, src_name)?;
        let cursor = (1 + n_indexes + i) as i32;
        secondaries.push(SecondaryScan {
            cursor,
            table: src_table,
            table_alias: *src_alias,
            register_base: None,
        });
    }
    let sorter_cursor = (1 + n_indexes + from_specs.len()) as i32;

    let end_label = b.emit_label();
    b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
    b.emit_op(Opcode::Transaction, 0, 1, 0, P4::None, 0);

    // Validate all column references across the target + FROM sources.
    let scan = ScanCtx {
        cursor: target_cursor,
        table,
        table_alias: stmt.table.alias.as_deref(),
        schema: Some(schema),
        register_base: None,
        secondaries: &secondaries,
    };
    for assign in &stmt.assignments {
        validate_scan_expr_columns(&assign.value, &scan)?;
    }
    for cond in &on_conditions {
        validate_scan_expr_columns(cond, &scan)?;
    }
    if let Some(where_expr) = &stmt.where_clause {
        validate_scan_expr_columns(where_expr, &scan)?;
    }
    validate_single_table_result_columns(
        &stmt.returning,
        table,
        stmt.table.alias.as_deref(),
        stmt.table.name.schema.as_deref(),
    )?;

    // Open target (write) + its index cursors, then the FROM read cursors.
    emit_without_rowid_open_write(b, table, target_cursor);
    for sec in &secondaries {
        b.emit_op(
            Opcode::OpenRead,
            sec.cursor,
            sec.table.root_page,
            0,
            P4::Table(sec.table.name.clone()),
            0,
        );
    }

    // Sorter holds [OLD image (n_cols) || NEW image (n_cols)].
    b.emit_op(
        Opcode::SorterOpen,
        sorter_cursor,
        (2 * n_cols) as i32,
        0,
        P4::Str("+".repeat(2 * n_cols)),
        0,
    );

    // Anonymous-placeholder base counts in SQL textual order: SET, ON, WHERE,
    // RETURNING.
    let set_ph: u32 = stmt
        .assignments
        .iter()
        .map(|a| count_anon_placeholders(&a.value))
        .sum();
    let on_ph: u32 = on_conditions
        .iter()
        .map(|e| count_anon_placeholders(e))
        .sum();
    let where_ph: u32 = stmt
        .where_clause
        .as_ref()
        .map_or(0, count_anon_placeholders);

    // --- Pass 1: nested-loop join (FROM outer, target inner); collect matches. ---
    struct LoopFrame {
        cursor: i32,
        body: i32,
        done: Label,
    }
    let mut frames: Vec<LoopFrame> = Vec::with_capacity(secondaries.len());
    for sec in &secondaries {
        let done = b.emit_label();
        b.emit_jump_to_label(Opcode::Rewind, sec.cursor, 0, done, P4::None, 0);
        let body = b.current_addr() as i32;
        frames.push(LoopFrame {
            cursor: sec.cursor,
            body,
            done,
        });
    }
    // Innermost: scan the target table.
    let target_done_label = b.emit_label();
    b.emit_jump_to_label(
        Opcode::Rewind,
        target_cursor,
        0,
        target_done_label,
        P4::None,
        0,
    );
    let target_body = b.current_addr() as i32;

    // Filters: each ON condition (join order) then WHERE. A failed condition
    // skips to the innermost (target) Next.
    let skip_label = b.emit_label();
    let filter_conditions: Vec<&Expr> = on_conditions
        .iter()
        .copied()
        .chain(stmt.where_clause.as_ref())
        .collect();
    if !filter_conditions.is_empty() {
        b.set_next_anon_placeholder(set_ph + 1);
        for cond in &filter_conditions {
            let cond_reg = b.alloc_temp();
            emit_expr(b, cond, cond_reg, Some(&scan));
            b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, skip_label, P4::None, 0);
            b.free_temp(cond_reg);
        }
    }

    // Match: build the OLD image, seed the NEW image from it, apply the
    // assignments (RHS resolves target cols via the cursor and FROM cols via the
    // secondaries), validate, and stash [OLD || NEW] into the sorter.
    let row_regs = b.alloc_regs((2 * n_cols) as i32);
    let old_regs = row_regs;
    let new_regs = row_regs + n_cols as i32;
    for i in 0..n_cols {
        b.emit_op(
            Opcode::Column,
            target_cursor,
            i as i32,
            old_regs + i as i32,
            P4::None,
            0,
        );
        b.emit_op(
            Opcode::Copy,
            old_regs + i as i32,
            new_regs + i as i32,
            0,
            P4::None,
            0,
        );
    }
    b.set_next_anon_placeholder(1);
    emit_update_assignments(b, &stmt.assignments, table, new_regs, &scan)?;
    emit_stored_generated_columns(b, table, new_regs);
    emit_strict_type_check(b, table, new_regs);
    // GH #169: coerce to column affinity before CHECK/NOT NULL so the
    // constraints see the affinity-coerced value (SQLite applies affinity, then
    // evaluates constraints).
    b.emit_op(
        Opcode::Affinity,
        new_regs,
        n_cols as i32,
        0,
        P4::Affinity(table.affinity_string()),
        0,
    );
    emit_check_constraints(b, table, new_regs, None);
    emit_not_null_constraints(b, table, new_regs, stmt.or_conflict, None);
    let stash_rec = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        row_regs,
        (2 * n_cols) as i32,
        stash_rec,
        P4::None,
        0,
    );
    b.emit_op(
        Opcode::SorterInsert,
        sorter_cursor,
        stash_rec,
        0,
        P4::None,
        0,
    );

    b.resolve_label(skip_label);
    b.emit_op(Opcode::Next, target_cursor, target_body, 0, P4::None, 0);
    b.resolve_label(target_done_label);

    // Unwind the FROM-source loops from innermost to outermost.
    for frame in frames.iter().rev() {
        b.emit_op(Opcode::Next, frame.cursor, frame.body, 0, P4::None, 0);
        b.resolve_label(frame.done);
    }

    // The FROM read cursors are no longer needed once the collect pass is done.
    for sec in &secondaries {
        b.emit_op(Opcode::Close, sec.cursor, 0, 0, P4::None, 0);
    }

    // --- Pass 2: re-seek each collected row by OLD primary key and rewrite. ---
    let pass2_done = b.emit_label();
    b.emit_jump_to_label(
        Opcode::SorterSort,
        sorter_cursor,
        0,
        pass2_done,
        P4::None,
        0,
    );
    let loop_body = b.current_addr();
    let sorted_reg = b.alloc_reg();
    b.emit_op(
        Opcode::SorterData,
        sorter_cursor,
        sorted_reg,
        0,
        P4::None,
        0,
    );
    let old_img = b.alloc_regs(n_cols as i32);
    let new_img = b.alloc_regs(n_cols as i32);
    for i in 0..n_cols {
        b.emit_op(
            Opcode::Column,
            sorter_cursor,
            i as i32,
            old_img + i as i32,
            P4::None,
            0,
        );
    }
    for i in 0..n_cols {
        b.emit_op(
            Opcode::Column,
            sorter_cursor,
            (n_cols + i) as i32,
            new_img + i as i32,
            P4::None,
            0,
        );
    }

    // Re-seek the OLD row by primary key; NoConflict skips if it is gone.
    let pk_probe_regs = b.alloc_regs(n_pk as i32);
    for (j, &pk_col) in pk_indices.iter().enumerate() {
        b.emit_op(
            Opcode::Copy,
            old_img + pk_col as i32,
            pk_probe_regs + j as i32,
            0,
            P4::None,
            0,
        );
    }
    let pk_probe_rec = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        pk_probe_regs,
        n_pk as i32,
        pk_probe_rec,
        P4::None,
        0,
    );
    let row_done = b.emit_label();
    b.emit_jump_to_label(
        Opcode::NoConflict,
        target_cursor,
        pk_probe_rec,
        row_done,
        P4::None,
        0,
    );

    // bd-yuj70: apply affinities before probing, then rewrite through the
    // shared victim-safe path. UPDATE FROM computed the NEW image during pass 1
    // while the FROM cursors were live, so only conflict resolution and the
    // OLD/NEW mutation order are shared with the plain UPDATE emission.
    b.emit_op(
        Opcode::Affinity,
        new_img,
        n_cols as i32,
        0,
        P4::Affinity(table.affinity_string()),
        0,
    );
    emit_without_rowid_update_rewrite(
        b,
        table,
        target_cursor,
        new_img,
        old_img,
        pk_probe_regs,
        &pk_indices,
        oe_flag,
        stmt.or_conflict,
        row_done,
    );

    // RETURNING: the NEW image.
    if !stmt.returning.is_empty() {
        b.set_next_anon_placeholder(set_ph + on_ph + where_ph + 1);
        emit_returning_from_regs(
            b,
            table,
            &stmt.returning,
            stmt.table.alias.as_deref(),
            schema,
            new_img,
        )?;
    }

    b.resolve_label(row_done);
    b.emit_op(
        Opcode::SorterNext,
        sorter_cursor,
        loop_body as i32,
        0,
        P4::None,
        0,
    );
    b.resolve_label(pass2_done);

    b.emit_op(Opcode::Close, sorter_cursor, 0, 0, P4::None, 0);
    emit_without_rowid_close(b, table, target_cursor);
    b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
    b.resolve_label(end_label);
    Ok(())
}

// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------

/// Emit a column's DEFAULT value into a register.
///
/// Parses the column's `default_value` SQL text and emits the appropriate
/// opcode. Emits `Null` when no default is specified.
fn emit_default_value(
    b: &mut ProgramBuilder,
    col: &ColumnInfo,
    reg: i32,
) -> Result<(), CodegenError> {
    match col.default_value.as_deref() {
        None => {
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            Ok(())
        }
        Some(dv) => {
            let expr = parse_default_expr(dv).ok_or_else(|| {
                CodegenError::Unsupported(format!(
                    "failed to parse DEFAULT expression `{}` for column `{}`",
                    dv.trim(),
                    col.name
                ))
            })?;
            if !default_expr_is_self_contained(&expr) {
                return Err(CodegenError::Unsupported(format!(
                    "DEFAULT expression `{}` for column `{}` is not self-contained",
                    dv.trim(),
                    col.name
                )));
            }
            emit_expr(b, &expr, reg, None);
            Ok(())
        }
    }
}

/// Parse column DEFAULT SQL text into an expression AST.
fn parse_default_expr(default_sql: &str) -> Option<Expr> {
    let trimmed = default_sql.trim();
    if trimmed.is_empty() {
        return None;
    }
    parse_sql_expr(trimmed).ok()
}

fn default_expr_is_self_contained(expr: &Expr) -> bool {
    match expr {
        Expr::Literal(_, _) => true,
        Expr::BoundOuterValue { .. }
        | Expr::Column(_, _)
        | Expr::Exists { .. }
        | Expr::Subquery(_, _)
        | Expr::Raise { .. }
        | Expr::RowValue(_, _)
        | Expr::Placeholder(_, _) => false,
        Expr::BinaryOp { left, right, .. } => {
            default_expr_is_self_contained(left) && default_expr_is_self_contained(right)
        }
        Expr::UnaryOp { expr: inner, .. }
        | Expr::Cast { expr: inner, .. }
        | Expr::Collate { expr: inner, .. }
        | Expr::IsNull { expr: inner, .. } => default_expr_is_self_contained(inner),
        Expr::Between {
            expr: inner,
            low,
            high,
            ..
        } => {
            default_expr_is_self_contained(inner)
                && default_expr_is_self_contained(low)
                && default_expr_is_self_contained(high)
        }
        Expr::In {
            expr: inner, set, ..
        } => {
            default_expr_is_self_contained(inner)
                && match set {
                    fsqlite_ast::InSet::List(exprs) => {
                        exprs.iter().all(default_expr_is_self_contained)
                    }
                    fsqlite_ast::InSet::Subquery(_) | fsqlite_ast::InSet::Table(_) => false,
                }
        }
        Expr::Like {
            expr: inner,
            pattern,
            escape,
            ..
        } => {
            default_expr_is_self_contained(inner)
                && default_expr_is_self_contained(pattern)
                && escape.as_deref().is_none_or(default_expr_is_self_contained)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand
                .as_deref()
                .is_none_or(default_expr_is_self_contained)
                && whens.iter().all(|(when_expr, then_expr)| {
                    default_expr_is_self_contained(when_expr)
                        && default_expr_is_self_contained(then_expr)
                })
                && else_expr
                    .as_deref()
                    .is_none_or(default_expr_is_self_contained)
        }
        Expr::FunctionCall {
            args,
            distinct,
            order_by,
            filter,
            over,
            ..
        } => {
            !distinct
                && order_by.is_empty()
                && filter.is_none()
                && over.is_none()
                && match args {
                    fsqlite_ast::FunctionArgs::Star => false,
                    fsqlite_ast::FunctionArgs::List(exprs) => {
                        exprs.iter().all(default_expr_is_self_contained)
                    }
                }
        }
        Expr::JsonAccess {
            expr: inner, path, ..
        } => default_expr_is_self_contained(inner) && default_expr_is_self_contained(path),
    }
}

fn emit_index_predicate_guard(
    b: &mut ProgramBuilder,
    index: &IndexSchema,
    scan_ctx: &ScanCtx<'_>,
    skip_label: Label,
) {
    let Some(where_sql) = index.where_clause.as_deref() else {
        return;
    };
    let Some(predicate) = parse_default_expr(where_sql) else {
        // Invalid persisted predicate metadata should not panic compilation.
        // Conservatively skip maintenance for this row.
        b.emit_jump_to_label(Opcode::Goto, 0, 0, skip_label, P4::None, 0);
        return;
    };
    let result_reg = b.alloc_reg();
    b.with_schema_evaluation_context(SchemaEvaluationContext::Index, |b| {
        emit_expr(b, &predicate, result_reg, Some(scan_ctx));
    });
    // Partial indexes include only rows where the predicate is true.
    b.emit_jump_to_label(Opcode::IfNot, result_reg, 1, skip_label, P4::None, 0);
}

fn emit_index_key_term(
    b: &mut ProgramBuilder,
    index: &IndexSchema,
    key_pos: usize,
    dest_reg: i32,
    scan_ctx: &ScanCtx<'_>,
) {
    let Some(term_sql) = index.key_term_sql(key_pos) else {
        b.emit_op(Opcode::Null, 0, dest_reg, 0, P4::None, 0);
        return;
    };
    if let Some(expr) = parse_default_expr(term_sql) {
        b.with_schema_evaluation_context(SchemaEvaluationContext::Index, |b| {
            emit_expr(b, &expr, dest_reg, Some(scan_ctx));
        });
    } else {
        b.emit_op(Opcode::Null, 0, dest_reg, 0, P4::None, 0);
    }
}

/// Evaluate STORED generated column expressions during INSERT/UPDATE.
///
/// For each column with `generated_stored == Some(true)`, parses the stored
/// expression SQL, evaluates it using register-based column resolution, and
/// writes the result into the corresponding column register.
///
/// VIRTUAL generated columns are set to NULL (they are computed at SELECT time).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_stored_generated_columns(b: &mut ProgramBuilder, table: &TableSchema, val_regs: i32) {
    for (col_idx, col) in table.columns.iter().enumerate() {
        let Some(ref expr_sql) = col.generated_expr else {
            continue;
        };
        let dest_reg = val_regs + col_idx as i32;
        if col.generated_stored == Some(true) {
            // STORED: evaluate expression and write result to register.
            if let Some(expr) = parse_default_expr(expr_sql) {
                let gen_ctx = ScanCtx {
                    cursor: 0,
                    table,
                    table_alias: None,
                    schema: None,
                    register_base: Some(val_regs),
                    secondaries: &[],
                };
                b.with_schema_evaluation_context(SchemaEvaluationContext::GeneratedColumn, |b| {
                    emit_expr(b, &expr, dest_reg, Some(&gen_ctx));
                });
            } else {
                // Expression parse failed — store NULL.
                b.emit_op(Opcode::Null, 0, dest_reg, 0, P4::None, 0);
            }
        } else {
            // VIRTUAL: not stored in the record; set NULL as placeholder.
            // The real value is computed on read (bd-r3303,
            // virtual_generated_column_expr).
            b.emit_op(Opcode::Null, 0, dest_reg, 0, P4::None, 0);
        }
    }
}

/// bd-r3303: if `col` is a VIRTUAL generated column, parse and return its
/// generating expression so callers can compute it on read.
///
/// Returns `None` for non-generated columns and for STORED generated columns
/// (which are computed and persisted at write time, then read back directly).
fn virtual_generated_column_expr(col: &ColumnInfo) -> Option<Expr> {
    if col.generated_stored != Some(false) {
        return None;
    }
    parse_default_expr(col.generated_expr.as_ref()?)
}

/// bd-r3303: emit `Opcode::Affinity` to coerce a single register to a column's
/// declared type affinity. Used after computing a VIRTUAL generated column on
/// read, mirroring the per-column affinity that record packing applies to
/// STORED columns at write time.
fn emit_single_column_affinity(b: &mut ProgramBuilder, reg: i32, affinity: char) {
    b.emit_op(
        Opcode::Affinity,
        reg,
        1,
        0,
        P4::Affinity(affinity.to_string()),
        0,
    );
}

/// Emit the read of table column `col_idx` from `cursor` into `reg`.
///
/// Centralizes the three column-read shapes so every table-scan read site
/// (projection, WHERE, ORDER BY) handles them uniformly:
/// - INTEGER PRIMARY KEY columns read the rowid (`Opcode::Rowid`);
/// - VIRTUAL generated columns (bd-r3303) are not materialized in the record,
///   so compute the generating expression against the current row (the
///   referenced base columns resolve through this same path) and coerce to the
///   column's declared affinity, matching what record packing applies to STORED
///   columns at write time;
/// - all other columns read directly from the record (`Opcode::Column`).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_table_column_read(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: Option<&[TableSchema]>,
    col_idx: usize,
    reg: i32,
) {
    let col = &table.columns[col_idx];
    if col.is_ipk {
        b.emit_op(Opcode::Rowid, cursor, reg, 0, P4::None, 0);
    } else if let Some(gen_expr) = virtual_generated_column_expr(col) {
        let scan = ScanCtx {
            cursor,
            table,
            table_alias,
            schema,
            register_base: None,
            secondaries: &[],
        };
        b.with_schema_evaluation_context(SchemaEvaluationContext::GeneratedColumn, |b| {
            emit_expr(b, &gen_expr, reg, Some(&scan));
        });
        emit_single_column_affinity(b, reg, col.affinity);
    } else {
        b.emit_op(Opcode::Column, cursor, col_idx as i32, reg, P4::None, 0);
    }
}

/// Emit CHECK constraint validation for INSERT/UPDATE.
///
/// For each CHECK constraint on the table, parses the constraint expression,
/// evaluates it using register-based column resolution, and emits a `Halt`
/// with SQLITE_CONSTRAINT (19) if any constraint evaluates to false (0).
/// NULL results are treated as passing (SQLite semantics: CHECK passes
/// unless the expression is explicitly false).
///
/// When `ignore_label` is `Some`, CHECK failures jump there instead of
/// halting (used for INSERT OR IGNORE to silently skip violating rows).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_check_constraints(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    val_regs: i32,
    ignore_label: Option<Label>,
) {
    const SQLITE_CONSTRAINT: i32 = 19;

    for check in &table.check_constraints {
        let Some(expr) = parse_default_expr(&check.expr) else {
            continue;
        };

        let result_reg = b.alloc_reg();
        let ok_label = b.emit_label();

        let check_ctx = ScanCtx {
            cursor: 0,
            table,
            table_alias: None,
            schema: None,
            register_base: Some(val_regs),
            secondaries: &[],
        };

        b.with_schema_evaluation_context(SchemaEvaluationContext::CheckConstraint, |b| {
            emit_expr(b, &expr, result_reg, Some(&check_ctx));
        });

        // NULL result: CHECK passes (SQLite semantics).
        b.emit_jump_to_label(Opcode::IsNull, result_reg, 0, ok_label, P4::None, 0);

        // Non-zero (truthy): CHECK passes.
        b.emit_jump_to_label(Opcode::If, result_reg, 0, ok_label, P4::None, 0);

        // False (0): CHECK fails.
        if let Some(skip) = ignore_label {
            // OR IGNORE: skip this row silently.
            b.emit_jump_to_label(Opcode::Goto, 0, 0, skip, P4::None, 0);
        } else {
            // Default: halt with constraint error.
            b.emit_op(
                Opcode::Halt,
                SQLITE_CONSTRAINT,
                0,
                0,
                P4::Str(match &check.name {
                    Some(name) => format!("CHECK constraint failed: {name}"),
                    None => format!("CHECK constraint failed: {}", check.expr),
                }),
                0,
            );
        }

        b.resolve_label(ok_label);
    }
}

/// Emit NOT NULL constraint validation for INSERT/UPDATE.
///
/// For each column with `not_null == true` (and not an IPK, which can't be NULL),
/// emits `HaltIfNull` to abort with SQLITE_CONSTRAINT if the value is NULL.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_not_null_constraints(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    val_regs: i32,
    stmt_level: Option<ConflictAction>,
    ignore_label: Option<Label>,
) {
    const SQLITE_CONSTRAINT: i32 = 19;

    // In a WITHOUT ROWID table the PRIMARY KEY columns are implicitly NOT NULL
    // even when NOT NULL is not declared (C SQLite enforces this). For rowid
    // tables this set is empty, so behavior is unchanged.
    let wr_pk: Vec<usize> = if table.without_rowid {
        without_rowid_pk_indices(table).unwrap_or_default()
    } else {
        Vec::new()
    };

    for (col_idx, col) in table.columns.iter().enumerate() {
        if (col.notnull || wr_pk.contains(&col_idx)) && !col.is_ipk {
            let reg = val_regs + col_idx as i32;
            let ok_label = b.emit_label();
            b.emit_jump_to_label(Opcode::NotNull, reg, 0, ok_label, P4::None, 0);
            // A statement-level `INSERT OR <algo>` overrides the column's
            // declared `NOT NULL ON CONFLICT <algo>`. Only IGNORE skips the
            // row; every other action (incl. the default ABORT) errors.
            let oe = effective_oe(stmt_level, col.conflict_action);
            match (oe == OE_IGNORE, ignore_label) {
                (true, Some(skip)) => {
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, skip, P4::None, 0);
                }
                _ => {
                    b.emit_op(
                        Opcode::Halt,
                        SQLITE_CONSTRAINT,
                        0,
                        0,
                        P4::Str(format!(
                            "NOT NULL constraint failed: {}.{}",
                            table.name, col.name
                        )),
                        0,
                    );
                }
            }
            b.resolve_label(ok_label);
        }
    }
}

/// Emit `IdxInsert` opcodes for all indexes on the table (bd-so1h: Phase 5I.3).
///
/// For each index, this reads the indexed column values from the provided
/// registers, appends the rowid, builds an index key record, and inserts it.
///
/// # Arguments
/// * `b` - Program builder
/// * `table` - Table schema (includes index definitions)
/// * `table_cursor` - Cursor ID for the table (index cursors are table_cursor + 1, +2, etc.)
/// * `col_regs` - Starting register containing column values in table schema order
/// * `rowid_reg` - Register containing the rowid
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_index_inserts(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    col_regs: i32,
    rowid_reg: i32,
    stmt_conflict: Option<ConflictAction>,
) {
    emit_index_inserts_filtered(
        b,
        table,
        table_cursor,
        col_regs,
        rowid_reg,
        stmt_conflict,
        None,
    );
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_index_inserts_for_update(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    col_regs: i32,
    rowid_reg: i32,
    stmt_conflict: Option<ConflictAction>,
    update_index_mask: &[bool],
) {
    emit_index_inserts_filtered(
        b,
        table,
        table_cursor,
        col_regs,
        rowid_reg,
        stmt_conflict,
        Some(update_index_mask),
    );
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_index_inserts_filtered(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    col_regs: i32,
    rowid_reg: i32,
    stmt_conflict: Option<ConflictAction>,
    update_index_mask: Option<&[bool]>,
) {
    for (idx_offset, index) in table.indexes.iter().enumerate() {
        // A statement-level `INSERT OR <algo>` overrides the index's declared
        // `ON CONFLICT <algo>`; absent both, the default is ABORT.
        let oe_flag = effective_oe(stmt_conflict, index.conflict_action);
        if update_index_mask.is_some_and(|mask| !mask.get(idx_offset).copied().unwrap_or(true)) {
            continue;
        }
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        let n_idx_cols = index.key_term_count();
        let skip_label = b.emit_label();
        let scan_ctx = ScanCtx {
            cursor: table_cursor,
            table,
            table_alias: None,
            schema: None,
            register_base: Some(col_regs),
            secondaries: &[],
        };

        emit_index_predicate_guard(b, index, &scan_ctx, skip_label);

        // Allocate registers for index key: (indexed_cols..., rowid).
        let idx_key_regs = b.alloc_regs((n_idx_cols + 1) as i32);

        // Evaluate indexed key terms into the key registers.
        for key_pos in 0..n_idx_cols {
            let dst_reg = idx_key_regs + key_pos as i32;
            emit_index_key_term(b, index, key_pos, dst_reg, &scan_ctx);
        }

        // Append rowid as the final key component.
        let rowid_key_reg = idx_key_regs + n_idx_cols as i32;
        b.emit_op(Opcode::Copy, rowid_reg, rowid_key_reg, 0, P4::None, 0);

        // Build the index key record.
        let idx_rec_reg = b.alloc_reg();
        b.emit_op(
            Opcode::MakeRecord,
            idx_key_regs,
            (n_idx_cols + 1) as i32,
            idx_rec_reg,
            P4::None,
            0,
        );

        // Insert into the index.
        // For UNIQUE indexes, set P5=1 and P3=number of indexed columns
        // (excluding the trailing rowid) so the engine can enforce the
        // uniqueness constraint while allowing multiple NULLs.
        let (p3_unique, p5_unique) = if index.is_unique {
            (n_idx_cols as i32, 1 | (oe_flag << 1))
        } else {
            (0, 0)
        };
        let p4_name = if index.is_unique {
            // Include table name for the error message.
            P4::Table(index.key_label_qualified(&table.name))
        } else {
            P4::Table(index.name.clone())
        };
        b.emit_op(
            Opcode::IdxInsert,
            idx_cursor,
            idx_rec_reg,
            p3_unique,
            p4_name,
            p5_unique,
        );

        b.resolve_label(skip_label);
    }
}

/// Emit `IdxDelete` opcodes for all indexes on the table (bd-34se: Phase 5I.4).
///
/// For each index, this reads the indexed column values from the cursor,
/// reads the rowid, and emits `IdxDelete` with `(p2, p3)` pointing at the key
/// register span. The VDBE engine seeks to that key before deleting.
/// MUST be called BEFORE the table row is deleted, while data is still accessible.
///
/// # Arguments
/// * `b` - Program builder
/// * `table` - Table schema (includes index definitions)
/// * `table_cursor` - Cursor ID for the table (index cursors are table_cursor + 1, +2, etc.)
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_index_deletes(b: &mut ProgramBuilder, table: &TableSchema, table_cursor: i32) {
    emit_index_deletes_filtered(b, table, table_cursor, None);
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_index_deletes_for_update(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    update_index_mask: &[bool],
) {
    emit_index_deletes_filtered(b, table, table_cursor, Some(update_index_mask));
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_index_deletes_filtered(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_cursor: i32,
    update_index_mask: Option<&[bool]>,
) {
    for (idx_offset, index) in table.indexes.iter().enumerate() {
        if update_index_mask.is_some_and(|mask| !mask.get(idx_offset).copied().unwrap_or(true)) {
            continue;
        }
        let idx_cursor = table_cursor + 1 + idx_offset as i32;
        let n_idx_cols = index.key_term_count();
        let skip_label = b.emit_label();
        let scan_ctx = ScanCtx {
            cursor: table_cursor,
            table,
            table_alias: None,
            schema: None,
            register_base: None,
            secondaries: &[],
        };

        emit_index_predicate_guard(b, index, &scan_ctx, skip_label);

        // Allocate registers for index key: (indexed_cols..., rowid).
        let idx_key_regs = b.alloc_regs((n_idx_cols + 1) as i32);

        // Re-evaluate indexed key terms from the current row.
        for key_pos in 0..n_idx_cols {
            let dst_reg = idx_key_regs + key_pos as i32;
            emit_index_key_term(b, index, key_pos, dst_reg, &scan_ctx);
        }

        // Read rowid and append as the final key component.
        let rowid_key_reg = idx_key_regs + n_idx_cols as i32;
        b.emit_op(Opcode::Rowid, table_cursor, rowid_key_reg, 0, P4::None, 0);

        // Delete from the index.
        b.emit_op(
            Opcode::IdxDelete,
            idx_cursor,
            idx_key_regs,
            (n_idx_cols + 1) as i32,
            P4::Table(index.name.clone()),
            0,
        );

        b.resolve_label(skip_label);
    }
}

/// Register metadata mapping a table cursor to its index cursors and their
/// column indices. Used by the VDBE engine's REPLACE conflict resolution to
/// clean up secondary index entries when a conflicting row is deleted.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn register_table_index_meta(b: &mut ProgramBuilder, table: &TableSchema, table_cursor: i32) {
    let metas: Vec<IndexCursorMeta> = table
        .indexes
        .iter()
        .enumerate()
        .map(|(idx_offset, index)| {
            let cursor_id = table_cursor + 1 + idx_offset as i32;
            // Direct, non-partial column indexes can reconstruct their exact
            // key from the victim table payload. Partial and expression
            // indexes cannot: an empty list tells the engine to locate the
            // victim entry by its trailing rowid instead.
            let column_indices = if index.supports_replace_cleanup_meta() {
                index
                    .columns
                    .iter()
                    .filter_map(|col_name| table.column_index(col_name))
                    .collect()
            } else {
                Vec::new()
            };
            IndexCursorMeta {
                cursor_id,
                column_indices,
            }
        })
        .collect();
    b.register_table_indexes(table_cursor, metas);
}

/// Count result columns (handling `SELECT *`).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn result_column_count(columns: &[ResultColumn], table: &TableSchema) -> i32 {
    result_column_count_usize(columns, table) as i32
}

fn result_column_count_usize(columns: &[ResultColumn], table: &TableSchema) -> usize {
    let mut count = 0usize;
    for col in columns {
        match col {
            ResultColumn::Star | ResultColumn::TableStar(_) => {
                count += table.columns.len();
            }
            ResultColumn::Expr { .. } => count += 1,
        }
    }
    count
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn result_column_count_without_from(columns: &[ResultColumn]) -> Result<i32, CodegenError> {
    let mut count = 0i32;
    for col in columns {
        match col {
            ResultColumn::Expr { .. } => count += 1,
            ResultColumn::Star | ResultColumn::TableStar(_) => {
                return Err(CodegenError::Unsupported(
                    "INSERT ... SELECT without FROM does not support `*` projections".to_owned(),
                ));
            }
        }
    }
    Ok(count)
}

/// Emit Column instructions to read result columns into registers.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_column_reads(
    b: &mut ProgramBuilder,
    cursor: i32,
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    base_reg: i32,
) -> Result<(), CodegenError> {
    let scan = ScanCtx {
        cursor,
        table,
        table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    emit_column_reads_selected(b, &scan, columns, base_reg, |_| true)
}

/// Emit selected flattened result columns into their normal output slots.
///
/// `SELECT *` and table-star columns each occupy one flattened slot per table
/// column. This lets ordered codegen evaluate an exact ORDER BY output
/// expression once at its key position, then emit only the remaining output
/// slots after top-N admission.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_column_reads_selected(
    b: &mut ProgramBuilder,
    scan: &ScanCtx<'_>,
    columns: &[ResultColumn],
    base_reg: i32,
    mut should_emit: impl FnMut(usize) -> bool,
) -> Result<(), CodegenError> {
    let cursor = scan.cursor;
    let table = scan.table;
    let table_alias = scan.table_alias;
    let schema = scan.schema;
    let mut reg = base_reg;
    let mut output_slot = 0usize;
    for col in columns {
        match col {
            ResultColumn::Star => {
                for i in 0..table.columns.len() {
                    if should_emit(output_slot) {
                        emit_table_column_read(b, cursor, table, table_alias, schema, i, reg);
                    }
                    reg += 1;
                    output_slot += 1;
                }
            }
            ResultColumn::TableStar(qualifier) => {
                if !matches_table_or_alias(&qualifier.name, table, table_alias) {
                    return Err(CodegenError::TableNotFound(qualifier.to_string()));
                }
                for i in 0..table.columns.len() {
                    if should_emit(output_slot) {
                        emit_table_column_read(b, cursor, table, table_alias, schema, i, reg);
                    }
                    reg += 1;
                    output_slot += 1;
                }
            }
            ResultColumn::Expr { expr, .. } => {
                if should_emit(output_slot) {
                    if let Expr::Column(col_ref, _) = expr {
                        if let Some(qualifier) = &col_ref.table
                            && !matches_table_or_alias(qualifier, table, table_alias)
                        {
                            return Err(qualified_column_not_found(qualifier, &col_ref.column));
                        }
                        if let Some(col_idx) = table.column_index(&col_ref.column) {
                            emit_table_column_read(
                                b,
                                cursor,
                                table,
                                table_alias,
                                schema,
                                col_idx,
                                reg,
                            );
                        } else if table.resolves_to_hidden_rowid(&col_ref.column) {
                            b.emit_op(Opcode::Rowid, cursor, reg, 0, P4::None, 0);
                        } else if let Some(qualifier) = &col_ref.table {
                            return Err(qualified_column_not_found(qualifier, &col_ref.column));
                        } else {
                            return Err(CodegenError::ColumnNotFound {
                                table: table.name.clone(),
                                column: col_ref.column.to_string(),
                            });
                        }
                    } else {
                        // Evaluate non-column expressions (literals, arithmetic, CASE, CAST, etc.)
                        // against the current scan row.
                        emit_expr(b, expr, reg, Some(scan));
                    }
                }
                reg += 1;
                output_slot += 1;
            }
        }
    }
    Ok(())
}

/// Retain the representative source row needed by ordered DISTINCT's
/// second-stage projection.
///
/// Rowid tables need only their stable rowid because pass 2 keeps the source
/// cursor open and seeks the representative again. WITHOUT ROWID tables have
/// no such locator, so retain their complete physical row image. VIRTUAL
/// generated columns deliberately keep a NULL placeholder: register-backed
/// projection recomputes them from the retained base columns, preserving the
/// second-stage function and error behavior.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_ordered_distinct_source_state(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    state_base: i32,
) {
    if !table.without_rowid {
        b.emit_op(Opcode::Rowid, cursor, state_base, 0, P4::None, 0);
        return;
    }

    for (column_index, column) in table.columns.iter().enumerate() {
        let target = state_base + column_index as i32;
        if virtual_generated_column_expr(column).is_some() {
            b.emit_op(Opcode::Null, 0, target, 0, P4::None, 0);
        } else {
            b.emit_op(
                Opcode::Column,
                cursor,
                column_index as i32,
                target,
                P4::None,
                0,
            );
        }
    }
}

/// Read one logical table column from a retained register row.
///
/// Physical and STORED-generated columns are copied directly. VIRTUAL
/// generated columns are recomputed against the same retained row image and
/// receive their declared affinity, just as a live table-cursor read does.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_table_column_read_from_register_row(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: Option<&[TableSchema]>,
    source_base: i32,
    column_index: usize,
    target: i32,
) {
    let column = &table.columns[column_index];
    if let Some(generated_expr) = virtual_generated_column_expr(column) {
        let scan = ScanCtx {
            cursor: 0,
            table,
            table_alias,
            schema,
            register_base: Some(source_base),
            secondaries: &[],
        };
        b.with_schema_evaluation_context(SchemaEvaluationContext::GeneratedColumn, |b| {
            emit_expr(b, &generated_expr, target, Some(&scan));
        });
        emit_single_column_affinity(b, target, column.affinity);
    } else {
        b.emit_op(
            Opcode::Copy,
            source_base + column_index as i32,
            target,
            0,
            P4::None,
            0,
        );
    }
}

/// Re-evaluate a flattened SELECT projection against a retained WITHOUT ROWID
/// source row.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_projection_from_register_row(
    b: &mut ProgramBuilder,
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    source_base: i32,
    output_base: i32,
) -> Result<(), CodegenError> {
    let scan = ScanCtx {
        cursor: 0,
        table,
        table_alias,
        schema: Some(schema),
        register_base: Some(source_base),
        secondaries: &[],
    };
    let mut target = output_base;
    for column in columns {
        match column {
            ResultColumn::Star => {
                for column_index in 0..table.columns.len() {
                    emit_table_column_read_from_register_row(
                        b,
                        table,
                        table_alias,
                        Some(schema),
                        source_base,
                        column_index,
                        target,
                    );
                    target += 1;
                }
            }
            ResultColumn::TableStar(qualifier) => {
                if !matches_table_or_alias(&qualifier.name, table, table_alias) {
                    return Err(CodegenError::TableNotFound(qualifier.to_string()));
                }
                for column_index in 0..table.columns.len() {
                    emit_table_column_read_from_register_row(
                        b,
                        table,
                        table_alias,
                        Some(schema),
                        source_base,
                        column_index,
                        target,
                    );
                    target += 1;
                }
            }
            ResultColumn::Expr { expr, .. } => {
                emit_expr(b, expr, target, Some(&scan));
                target += 1;
            }
        }
    }
    Ok(())
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_projection_without_from(
    b: &mut ProgramBuilder,
    columns: &[ResultColumn],
    base_reg: i32,
) -> Result<(), CodegenError> {
    let mut reg = base_reg;
    for col in columns {
        match col {
            ResultColumn::Expr { expr, .. } => {
                emit_expr(b, expr, reg, None);
                reg += 1;
            }
            ResultColumn::Star | ResultColumn::TableStar(_) => {
                return Err(CodegenError::Unsupported(
                    "INSERT ... SELECT without FROM does not support `*` projections".to_owned(),
                ));
            }
        }
    }
    Ok(())
}

/// Emit RETURNING clause opcodes for a row-producing DML statement.
///
/// Positions the cursor on the just-inserted row via `SeekRowid`, reads the
/// requested columns, and emits a `ResultRow`.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_returning(
    b: &mut ProgramBuilder,
    cursor: i32,
    table: &TableSchema,
    returning: &[ResultColumn],
    table_alias: Option<&str>,
    rowid_reg: i32,
) -> Result<(), CodegenError> {
    // RETURNING is validated against the DML target, which in these single-table
    // codegen paths is always a main (or implicit) binding: attached-schema DML
    // is delegated or rejected upstream, so a `None` (implicit `main`) FROM
    // schema is the correct reconciliation base here.
    validate_single_table_result_columns(returning, table, table_alias, None)?;

    let skip_returning = b.emit_label();
    b.emit_jump_to_label(
        Opcode::SeekRowid,
        cursor,
        rowid_reg,
        skip_returning,
        P4::None,
        0,
    );
    let ret_count = result_column_count(returning, table);
    let ret_regs = b.alloc_regs(ret_count);
    emit_column_reads(b, cursor, returning, table, table_alias, &[], ret_regs)?;
    b.emit_op(Opcode::ResultRow, ret_regs, ret_count, 0, P4::None, 0);
    b.resolve_label(skip_returning);
    Ok(())
}

/// Emit a RETURNING clause for a WITHOUT ROWID DML row whose full column image
/// already lives in `col_regs` (column `i` at `col_regs + i`). Unlike
/// [`emit_returning`], there is no rowid to re-seek by, so column references and
/// expressions are evaluated directly against the in-register row image via
/// `ScanCtx::register_base`. Used for INSERT (inserted image), UPDATE (new
/// image), and DELETE (deleted image).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_returning_from_regs(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    returning: &[ResultColumn],
    table_alias: Option<&str>,
    schema: &[TableSchema],
    col_regs: i32,
) -> Result<(), CodegenError> {
    // RETURNING is validated against the DML target, which in these single-table
    // codegen paths is always a main (or implicit) binding: attached-schema DML
    // is delegated or rejected upstream, so a `None` (implicit `main`) FROM
    // schema is the correct reconciliation base here.
    validate_single_table_result_columns(returning, table, table_alias, None)?;
    let ret_count = result_column_count(returning, table);
    let ret_regs = b.alloc_regs(ret_count);
    let mut reg = ret_regs;
    for col in returning {
        match col {
            ResultColumn::Star => {
                for i in 0..table.columns.len() {
                    b.emit_op(Opcode::Copy, col_regs + i as i32, reg, 0, P4::None, 0);
                    reg += 1;
                }
            }
            ResultColumn::TableStar(qualifier) => {
                if !matches_table_or_alias(&qualifier.name, table, table_alias) {
                    return Err(CodegenError::TableNotFound(qualifier.to_string()));
                }
                for i in 0..table.columns.len() {
                    b.emit_op(Opcode::Copy, col_regs + i as i32, reg, 0, P4::None, 0);
                    reg += 1;
                }
            }
            ResultColumn::Expr { expr, .. } => {
                let scan = ScanCtx {
                    cursor: 0,
                    table,
                    table_alias,
                    schema: Some(schema),
                    register_base: Some(col_regs),
                    secondaries: &[],
                };
                emit_expr(b, expr, reg, Some(&scan));
                reg += 1;
            }
        }
    }
    b.emit_op(Opcode::ResultRow, ret_regs, ret_count, 0, P4::None, 0);
    Ok(())
}

/// Emit a HAVING filter for GROUP BY queries.
///
/// Evaluates the HAVING expression against the already-built output row.
/// Aggregate function calls and column references are resolved to the
/// corresponding output registers. If the predicate is false, jumps to
/// `skip_label` (skipping the `ResultRow`).
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::too_many_arguments
)]
fn emit_having_filter(
    b: &mut ProgramBuilder,
    having_expr: &Expr,
    output_cols: &[GroupByOutputCol],
    agg_columns: &[AggColumn],
    group_by_keys: &[GroupByKey],
    table: &TableSchema,
    out_regs: i32,
    skip_label: crate::Label,
) {
    let result_reg = b.alloc_temp();
    emit_having_expr(
        b,
        having_expr,
        result_reg,
        output_cols,
        agg_columns,
        group_by_keys,
        table,
        out_regs,
    );
    // If result is falsy (0 or NULL), skip this group's ResultRow.
    // p3=1: NULL HAVING → jump (skip row), matching SQLite semantics.
    b.emit_jump_to_label(Opcode::IfNot, result_reg, 1, skip_label, P4::None, 0);
    b.free_temp(result_reg);
}

/// Evaluate a HAVING expression into `dest_reg`.
///
/// Maps aggregate function calls and column references to the output
/// registers that already hold the finalized group results.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::too_many_arguments,
    clippy::too_many_lines
)]
fn emit_having_expr(
    b: &mut ProgramBuilder,
    expr: &Expr,
    dest_reg: i32,
    output_cols: &[GroupByOutputCol],
    agg_columns: &[AggColumn],
    group_by_keys: &[GroupByKey],
    table: &TableSchema,
    out_regs: i32,
) {
    match expr {
        // Aggregate function call — resolve to the corresponding output register.
        Expr::FunctionCall { name, args, .. } if is_aggregate_function_call(name, args) => {
            let upper = name.to_ascii_uppercase();
            // Find the matching aggregate by name + argument structure.
            let agg_idx = agg_columns.iter().position(|agg| {
                if agg.name != upper {
                    return false;
                }
                match args {
                    FunctionArgs::Star => agg.num_args == 0,
                    FunctionArgs::List(exprs) => {
                        if exprs.is_empty() {
                            return agg.num_args == 0;
                        }
                        // Match by argument column index first.
                        if let Some(ci) = resolve_column_index(&exprs[0], table) {
                            agg.arg_col_index == Some(ci)
                        } else if let Some(ref arg_expr) = agg.arg_expr {
                            // Fall back to structural expression comparison
                            // for aggregates with expression arguments.
                            exprs.len() == 1 && **arg_expr == exprs[0]
                        } else {
                            false
                        }
                    }
                }
            });
            if let Some(ai) = agg_idx {
                // Find the output register for this aggregate.
                for (i, oc) in output_cols.iter().enumerate() {
                    if matches!(oc, GroupByOutputCol::Aggregate { agg_index } if *agg_index == ai) {
                        b.emit_op(Opcode::Copy, out_regs + i as i32, dest_reg, 0, P4::None, 0);
                        return;
                    }
                }
            }
            // Fallback: treat as zero (unknown aggregate in HAVING).
            b.emit_op(Opcode::Integer, 0, dest_reg, 0, P4::None, 0);
        }

        // Column reference — resolve to the corresponding group-key output register.
        Expr::Column(col_ref, _) => {
            let col_name = &col_ref.column;
            if let Some(col_idx) = table
                .columns
                .iter()
                .position(|c| c.name == col_name.as_ref())
            {
                // Find the output column whose group key maps to this table column.
                for (i, oc) in output_cols.iter().enumerate() {
                    if let GroupByOutputCol::GroupKey { key_index, .. } = oc
                        && matches!(group_by_keys.get(*key_index), Some(GroupByKey::Column(c)) if *c == col_idx)
                    {
                        b.emit_op(Opcode::Copy, out_regs + i as i32, dest_reg, 0, P4::None, 0);
                        return;
                    }
                }
                // GH #225: a bare column referenced by HAVING (no GROUP BY, or an
                // unprojected column) is captured as a hidden bare_expr aggregate
                // holding the first scanned row's value. Resolve it to that
                // aggregate's output register instead of NULL.
                if let Some(agg_i) = agg_columns.iter().position(|agg| {
                    agg.bare_expr
                        .as_deref()
                        .and_then(|be| resolve_column_index(be, table))
                        == Some(col_idx)
                }) {
                    for (i, oc) in output_cols.iter().enumerate() {
                        if matches!(oc, GroupByOutputCol::Aggregate { agg_index } if *agg_index == agg_i)
                        {
                            b.emit_op(Opcode::Copy, out_regs + i as i32, dest_reg, 0, P4::None, 0);
                            return;
                        }
                    }
                }
            }
            // Fallback: emit NULL for unresolved column.
            b.emit_op(Opcode::Null, 0, dest_reg, 0, P4::None, 0);
        }

        // Binary comparison — evaluate both sides, then compare.
        Expr::BinaryOp {
            left, op, right, ..
        } => {
            let left_reg = b.alloc_temp();
            let right_reg = b.alloc_temp();
            emit_having_expr(
                b,
                left,
                left_reg,
                output_cols,
                agg_columns,
                group_by_keys,
                table,
                out_regs,
            );
            emit_having_expr(
                b,
                right,
                right_reg,
                output_cols,
                agg_columns,
                group_by_keys,
                table,
                out_regs,
            );

            match op {
                fsqlite_ast::BinaryOp::Gt
                | fsqlite_ast::BinaryOp::Lt
                | fsqlite_ast::BinaryOp::Ge
                | fsqlite_ast::BinaryOp::Le
                | fsqlite_ast::BinaryOp::Eq
                | fsqlite_ast::BinaryOp::Ne => {
                    let cmp_opcode = match op {
                        fsqlite_ast::BinaryOp::Gt => Opcode::Gt,
                        fsqlite_ast::BinaryOp::Lt => Opcode::Lt,
                        fsqlite_ast::BinaryOp::Ge => Opcode::Ge,
                        fsqlite_ast::BinaryOp::Le => Opcode::Le,
                        fsqlite_ast::BinaryOp::Eq => Opcode::Eq,
                        fsqlite_ast::BinaryOp::Ne => Opcode::Ne,
                        _ => unreachable!(),
                    };
                    // SQL three-valued logic: if either operand is NULL, result is NULL.
                    let null_label = b.emit_label();
                    let true_label = b.emit_label();
                    let done_label = b.emit_label();
                    b.emit_jump_to_label(Opcode::IsNull, left_reg, 0, null_label, P4::None, 0);
                    b.emit_jump_to_label(Opcode::IsNull, right_reg, 0, null_label, P4::None, 0);
                    b.emit_jump_to_label(cmp_opcode, right_reg, left_reg, true_label, P4::None, 0);
                    b.emit_op(Opcode::Integer, 0, dest_reg, 0, P4::None, 0);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    b.resolve_label(true_label);
                    b.emit_op(Opcode::Integer, 1, dest_reg, 0, P4::None, 0);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    b.resolve_label(null_label);
                    b.emit_op(Opcode::Null, 0, dest_reg, 0, P4::None, 0);
                    b.resolve_label(done_label);
                }
                fsqlite_ast::BinaryOp::And => {
                    b.emit_op(Opcode::And, left_reg, right_reg, dest_reg, P4::None, 0);
                }
                fsqlite_ast::BinaryOp::Or => {
                    b.emit_op(Opcode::Or, left_reg, right_reg, dest_reg, P4::None, 0);
                }
                _ => {
                    emit_expr(b, expr, dest_reg, None);
                }
            }
            b.free_temp(right_reg);
            b.free_temp(left_reg);
        }

        // GH #225: `x IS [NOT] NULL` in HAVING must evaluate its operand through
        // the HAVING resolver (so a bare column resolves to its captured first-row
        // aggregate register) rather than the raw evaluator, which would leave the
        // column NULL and wrongly satisfy `IS NULL`.
        Expr::IsNull {
            expr: inner, not, ..
        } => {
            let val_reg = b.alloc_temp();
            emit_having_expr(
                b,
                inner,
                val_reg,
                output_cols,
                agg_columns,
                group_by_keys,
                table,
                out_regs,
            );
            let is_null_lbl = b.emit_label();
            let done_lbl = b.emit_label();
            b.emit_jump_to_label(Opcode::IsNull, val_reg, 0, is_null_lbl, P4::None, 0);
            // Operand is non-NULL: `IS NULL` -> 0, `IS NOT NULL` -> 1.
            b.emit_op(Opcode::Integer, i32::from(*not), dest_reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_lbl, P4::None, 0);
            b.resolve_label(is_null_lbl);
            // Operand is NULL: `IS NULL` -> 1, `IS NOT NULL` -> 0.
            b.emit_op(Opcode::Integer, i32::from(!*not), dest_reg, 0, P4::None, 0);
            b.resolve_label(done_lbl);
            b.free_temp(val_reg);
        }

        // For any other expression, delegate to the standard evaluator.
        _ => {
            emit_expr(b, expr, dest_reg, None);
        }
    }
}

/// Emit a WHERE filter for scan-based UPDATE/DELETE.
///
/// Evaluates the WHERE expression against the current cursor row. If the
/// condition is false, jumps to `skip_label` (skipping the DML operation).
///
/// Handles `col = expr` comparisons by reading the column from the cursor
/// and comparing with the literal/expression value.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_where_filter(
    b: &mut ProgramBuilder,
    where_expr: &Expr,
    cursor: i32,
    table: &TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    skip_label: crate::Label,
) {
    let scan = ScanCtx {
        cursor,
        table,
        table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    emit_where_filter_with_ctx(b, where_expr, &scan, skip_label);
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_where_filter_with_ctx(
    b: &mut ProgramBuilder,
    where_expr: &Expr,
    scan: &ScanCtx<'_>,
    skip_label: crate::Label,
) {
    match where_expr {
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::Eq,
            right,
            ..
        } => {
            let comparison = ResolvedComparisonInfo::new(left, right, scan);
            if let Some(resolved) = comparison.left_resolved.as_ref() {
                let col_reg = b.alloc_temp();
                let val_reg = b.alloc_temp();
                emit_resolved_column(b, resolved, scan.cursor, col_reg, scan);
                emit_expr(b, right, val_reg, Some(scan));
                // SQL semantics: `col = NULL` is UNKNOWN (false in WHERE). If the
                // value expression evaluates to NULL, skip the row unconditionally.
                b.emit_jump_to_label(Opcode::IsNull, val_reg, 0, skip_label, P4::None, 0);
                // NULLEQ (0x80) | comparison affinity so the engine coerces correctly.
                b.emit_jump_to_label(
                    Opcode::Ne,
                    val_reg,
                    col_reg,
                    skip_label,
                    comparison.collation_p4.clone(),
                    comparison.cmp_p5,
                );
                b.free_temp(val_reg);
                b.free_temp(col_reg);
            } else if let Some(resolved) = comparison.right_resolved.as_ref() {
                let col_reg = b.alloc_temp();
                let val_reg = b.alloc_temp();
                emit_resolved_column(b, resolved, scan.cursor, col_reg, scan);
                emit_expr(b, left, val_reg, Some(scan));
                // SQL semantics: `NULL = col` is UNKNOWN (false in WHERE).
                b.emit_jump_to_label(Opcode::IsNull, val_reg, 0, skip_label, P4::None, 0);
                b.emit_jump_to_label(
                    Opcode::Ne,
                    val_reg,
                    col_reg,
                    skip_label,
                    comparison.collation_p4.clone(),
                    comparison.cmp_p5,
                );
                b.free_temp(val_reg);
                b.free_temp(col_reg);
            } else {
                // Neither side is a column ref (e.g. WHERE 1 = 0, WHERE length(name) = 5).
                // Fall through to generic boolean evaluation.
                let cond_reg = b.alloc_temp();
                emit_expr(b, where_expr, cond_reg, Some(scan));
                b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, skip_label, P4::None, 0);
                b.free_temp(cond_reg);
            }
        }
        // Inequality comparisons: Ne, Lt, Le, Gt, Ge.
        // Same structure as Eq but with the appropriate skip opcode and
        // operand order so that column affinity p5 flags are applied.
        Expr::BinaryOp {
            left,
            op:
                op @ (fsqlite_ast::BinaryOp::Ne
                | fsqlite_ast::BinaryOp::Lt
                | fsqlite_ast::BinaryOp::Le
                | fsqlite_ast::BinaryOp::Gt
                | fsqlite_ast::BinaryOp::Ge),
            right,
            ..
        } => {
            let comparison = ResolvedComparisonInfo::new(left, right, scan);

            // Determine the skip opcode — the inverse of the comparison.
            // If `col > val` is the condition, skip when `col <= val`, i.e. Le.
            let skip_opcode = match op {
                fsqlite_ast::BinaryOp::Ne => Opcode::Eq,
                fsqlite_ast::BinaryOp::Lt => Opcode::Ge,
                fsqlite_ast::BinaryOp::Le => Opcode::Gt,
                fsqlite_ast::BinaryOp::Gt => Opcode::Le,
                fsqlite_ast::BinaryOp::Ge => Opcode::Lt,
                _ => unreachable!(),
            };

            if let Some(resolved) = comparison.left_resolved.as_ref() {
                let col_reg = b.alloc_temp();
                let val_reg = b.alloc_temp();
                emit_resolved_column(b, resolved, scan.cursor, col_reg, scan);
                emit_expr(b, right, val_reg, Some(scan));
                b.emit_jump_to_label(Opcode::IsNull, val_reg, 0, skip_label, P4::None, 0);
                b.emit_jump_to_label(Opcode::IsNull, col_reg, 0, skip_label, P4::None, 0);
                b.emit_jump_to_label(
                    skip_opcode,
                    val_reg,
                    col_reg,
                    skip_label,
                    comparison.collation_p4.clone(),
                    comparison.cmp_p5,
                );
                b.free_temp(val_reg);
                b.free_temp(col_reg);
            } else if let Some(resolved) = comparison.right_resolved.as_ref() {
                // col is on the right: `val op col` → swap operand order.
                // `val < col` skip when `val >= col`, i.e. Ge(val, col).
                // The skip opcode is the inverse of `val op col`.
                let swapped_skip = match op {
                    fsqlite_ast::BinaryOp::Ne => Opcode::Eq,
                    fsqlite_ast::BinaryOp::Lt => Opcode::Ge,
                    fsqlite_ast::BinaryOp::Le => Opcode::Gt,
                    fsqlite_ast::BinaryOp::Gt => Opcode::Le,
                    fsqlite_ast::BinaryOp::Ge => Opcode::Lt,
                    _ => unreachable!(),
                };
                let col_reg = b.alloc_temp();
                let val_reg = b.alloc_temp();
                emit_resolved_column(b, resolved, scan.cursor, col_reg, scan);
                emit_expr(b, left, val_reg, Some(scan));
                b.emit_jump_to_label(Opcode::IsNull, val_reg, 0, skip_label, P4::None, 0);
                b.emit_jump_to_label(Opcode::IsNull, col_reg, 0, skip_label, P4::None, 0);
                // VDBE comparison: opcode P1=rhs P2=lhs. For `val < col` skip
                // when NOT(val < col), i.e. val >= col → Ge(val_reg, col_reg).
                b.emit_jump_to_label(
                    swapped_skip,
                    col_reg,
                    val_reg,
                    skip_label,
                    comparison.collation_p4.clone(),
                    comparison.cmp_p5,
                );
                b.free_temp(val_reg);
                b.free_temp(col_reg);
            } else {
                let cond_reg = b.alloc_temp();
                emit_expr(b, where_expr, cond_reg, Some(scan));
                b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, skip_label, P4::None, 0);
                b.free_temp(cond_reg);
            }
        }
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::And,
            right,
            ..
        } => {
            // AND: both conditions must pass.
            emit_where_filter_with_ctx(b, left, scan, skip_label);
            emit_where_filter_with_ctx(b, right, scan, skip_label);
        }
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::Or,
            right,
            ..
        } => {
            // OR: at least one condition must pass.
            // If left passes → skip right, proceed to row processing.
            // If left fails → try right; if right also fails → skip row.
            let left_skip = b.emit_label();
            let pass_label = b.emit_label();
            emit_where_filter_with_ctx(b, left, scan, left_skip);
            // Left passed — jump past right-side evaluation.
            b.emit_jump_to_label(Opcode::Goto, 0, 0, pass_label, P4::None, 0);
            b.resolve_label(left_skip);
            // Left failed — try right.
            emit_where_filter_with_ctx(b, right, scan, skip_label);
            b.resolve_label(pass_label);
        }
        _ => {
            // Generic WHERE: evaluate expression with cursor context and test truthiness.
            let cond_reg = b.alloc_temp();
            emit_expr(b, where_expr, cond_reg, Some(scan));
            b.emit_jump_to_label(Opcode::IfNot, cond_reg, 1, skip_label, P4::None, 0);
            b.free_temp(cond_reg);
        }
    }
}

struct ResolvedComparisonInfo {
    left_resolved: Option<SortKeySource>,
    right_resolved: Option<SortKeySource>,
    collation_p4: P4,
    cmp_p5: u16,
}

impl ResolvedComparisonInfo {
    fn new(left: &Expr, right: &Expr, scan: &ScanCtx<'_>) -> Self {
        let left_resolved = resolve_column_ref(left, scan.table, scan.table_alias);
        let right_resolved = resolve_column_ref(right, scan.table, scan.table_alias);
        let collation_p4 = extract_collation(left)
            .or_else(|| extract_collation(right))
            .or_else(|| bound_outer_declared_collation(left))
            .or_else(|| resolved_primary_collation(left_resolved.as_ref(), scan.table))
            .or_else(|| bound_outer_declared_collation(right))
            .or_else(|| resolved_primary_collation(right_resolved.as_ref(), scan.table))
            .map_or(P4::None, |coll| P4::Collation(coll.to_owned()));
        let cmp_p5 = 0x80
            | comparison_affinity_p5_resolved(
                left,
                left_resolved.as_ref(),
                right,
                right_resolved.as_ref(),
                scan,
            );
        Self {
            left_resolved,
            right_resolved,
            collation_p4,
            cmp_p5,
        }
    }
}

fn resolved_primary_collation<'a>(
    resolved: Option<&SortKeySource>,
    table: &'a TableSchema,
) -> Option<&'a str> {
    match resolved {
        Some(SortKeySource::Column(idx)) => table.columns.get(*idx)?.collation.as_deref(),
        Some(SortKeySource::Rowid | SortKeySource::Expression(_)) | None => None,
    }
}

fn resolved_expr_affinity(expr: &Expr, resolved: Option<&SortKeySource>, scan: &ScanCtx<'_>) -> u8 {
    match resolved {
        Some(SortKeySource::Column(idx)) => scan
            .table
            .columns
            .get(*idx)
            .map_or(b'A', schema_column_expr_affinity),
        Some(SortKeySource::Rowid) => b'D',
        Some(SortKeySource::Expression(_)) | None => expr_affinity(expr, Some(scan)),
    }
}

/// Core comparison-affinity rule (SQLite datatype3 §4.2) shared by every
/// comparison emit path: given the affinity codes (`A`=BLOB, `B`=TEXT,
/// `C`=NUMERIC, `D`=INTEGER, `E`=REAL) of the two operands, return the `p5`
/// affinity to apply — `0` for none, `b'B'` for TEXT, `b'C'` for NUMERIC.
fn combine_comparison_affinity(l_aff: u8, r_aff: u8) -> u16 {
    let is_numeric = |a: u8| matches!(a, b'C' | b'D' | b'E');

    // One side numeric (C/D/E), the other TEXT (B) or BLOB (A) → coerce the
    // text/blob side to a number (NUMERIC affinity).
    if (is_numeric(l_aff) && matches!(r_aff, b'A' | b'B'))
        || (is_numeric(r_aff) && matches!(l_aff, b'A' | b'B'))
    {
        return u16::from(b'C'); // NUMERIC
    }
    // One side TEXT (B), the other BLOB/NONE (A) → coerce the blob side to text.
    if (l_aff == b'B' && r_aff == b'A') || (l_aff == b'A' && r_aff == b'B') {
        return u16::from(b'B'); // TEXT
    }
    0 // No affinity coercion needed
}

fn comparison_affinity_p5_resolved(
    left: &Expr,
    left_resolved: Option<&SortKeySource>,
    right: &Expr,
    right_resolved: Option<&SortKeySource>,
    scan: &ScanCtx<'_>,
) -> u16 {
    combine_comparison_affinity(
        resolved_expr_affinity(left, left_resolved, scan),
        resolved_expr_affinity(right, right_resolved, scan),
    )
}

/// Check whether a column name is a hidden rowid alias (`rowid`, `_rowid_`, or `oid`).
fn is_hidden_rowid_alias_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower == "rowid" || lower == "_rowid_" || lower == "oid"
}

/// Normalize an explicit `main` schema qualifier to the implicit (`None`) form.
///
/// SQLite treats the `main` database name as equivalent to an unqualified
/// reference, so `main.t` and a bare `t` name the same object. This mirrors
/// `connection.rs::normalized_attached_schema_name` so codegen reconciles a
/// schema-qualified result-column star against a bare FROM binding without
/// collapsing a genuine cross-database qualifier (e.g. `aux`).
fn normalized_schema_qualifier(schema: Option<&str>) -> Option<&str> {
    match schema {
        Some(name) if name.eq_ignore_ascii_case("main") => None,
        other => other,
    }
}

/// Decide whether a `qualifier.*` table-star names the single FROM/DML binding.
///
/// `from_schema` is the schema qualifier written on the binding itself
/// (`None` for a bare `t`, `Some("main")` for `main.t`, `Some("aux")` for an
/// attached `aux.t`). An aliased binding is addressable only by its alias, with
/// no schema qualifier. Otherwise the star's database and the binding's database
/// must agree after `main`/implicit normalization, so `main.t.*` matches a bare
/// `FROM t` while `aux.t.*` does not.
fn table_star_qualifier_matches_binding(
    qualifier: &QualifiedName,
    table: &TableSchema,
    table_alias: Option<&str>,
    from_schema: Option<&str>,
) -> bool {
    if table_alias.is_some() {
        return qualifier.schema.is_none()
            && matches_table_or_alias(&qualifier.name, table, table_alias);
    }
    normalized_schema_qualifier(qualifier.schema.as_deref())
        == normalized_schema_qualifier(from_schema)
        && matches_table_or_alias(&qualifier.name, table, table_alias)
}

fn matches_table_or_alias(qualifier: &str, table: &TableSchema, table_alias: Option<&str>) -> bool {
    table_alias.map_or_else(
        || qualifier.eq_ignore_ascii_case(&table.name),
        |alias| qualifier.eq_ignore_ascii_case(alias),
    )
}

fn qualified_column_not_found(qualifier: &str, column: &str) -> CodegenError {
    // SQLite reports bad qualified references as "no such column: q.c",
    // including cases where `q` is a hidden base table name after aliasing.
    // Keep the qualified spelling in `column` so the public error preserves it.
    CodegenError::ColumnNotFound {
        table: qualifier.to_owned(),
        column: format!("{qualifier}.{column}"),
    }
}

/// Source for a sort key: either a table column or the implicit rowid.
#[derive(Clone)]
enum SortKeySource {
    Column(usize),
    Rowid,
    /// Arbitrary expression (e.g., `a + b`, `LENGTH(name)`, `CASE WHEN ...`).
    Expression(Box<Expr>),
}

/// Emit bytecode to load a resolved column reference into a register.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_resolved_column(
    b: &mut ProgramBuilder,
    resolved: &SortKeySource,
    cursor: i32,
    reg: i32,
    scan: &ScanCtx<'_>,
) {
    match resolved {
        SortKeySource::Column(idx) => {
            // bd-r3303: when reading from the scanned table's own cursor, route
            // through emit_table_column_read so a VIRTUAL generated column is
            // computed on read. For other cursors (e.g. a sorter/join feed where
            // base columns are already materialized) keep the direct read.
            if cursor == scan.cursor && *idx < scan.table.columns.len() {
                emit_table_column_read(
                    b,
                    cursor,
                    scan.table,
                    scan.table_alias,
                    scan.schema,
                    *idx,
                    reg,
                );
            } else {
                b.emit_op(Opcode::Column, cursor, *idx as i32, reg, P4::None, 0);
            }
        }
        SortKeySource::Rowid => {
            b.emit_op(Opcode::Rowid, cursor, reg, 0, P4::None, 0);
        }
        SortKeySource::Expression(expr) => {
            emit_expr(b, expr, reg, Some(scan));
        }
    }
}

/// Output source for a covering-index ordered scan.
enum CoveringOutputSource {
    /// Read value from index key column at this position.
    IndexColumn(i32),
    /// Read value from the rowid already extracted via `IdxRowid`.
    Rowid,
}

/// Plan for ORDER BY execution that can bypass the sorter.
struct OrderByIndexPlan {
    index: IndexSchema,
    descending: bool,
    equality_prefix_len: usize,
    /// When present, all output columns can be read from index payload/rowid
    /// and no table row lookup is required.
    covering_output: Option<Vec<CoveringOutputSource>>,
}

/// Resolve an ORDER BY expression to a `SortKeySource`.
///
/// Returns `Column` or `Rowid` for simple column references; falls back to
/// `Expression` for arbitrary expressions (arithmetic, function calls, etc.).
/// Handles numeric column indices (e.g., `ORDER BY 2`) by resolving them to
/// the corresponding result column expression.
fn resolve_sort_key(
    expr: &Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
    columns: &[ResultColumn],
) -> SortKeySource {
    if let Some(output_expr) = resolve_order_by_output_expr(expr, columns) {
        return resolve_sort_key(output_expr, table, table_alias, columns);
    }

    if let Expr::Column(col_ref, _) = expr {
        if let Some(qualifier) = &col_ref.table
            && !matches_table_or_alias(qualifier, table, table_alias)
        {
            return SortKeySource::Expression(Box::new(expr.clone()));
        }
        if let Some(idx) = table.column_index(&col_ref.column) {
            return SortKeySource::Column(idx);
        }
        if table.resolves_to_hidden_rowid(&col_ref.column) {
            return SortKeySource::Rowid;
        }
    }
    SortKeySource::Expression(Box::new(expr.clone()))
}

fn resolve_order_by_output_expr<'a>(
    expr: &'a Expr,
    columns: &'a [ResultColumn],
) -> Option<&'a Expr> {
    if let Some(ordinal) = order_by_integer_ordinal(expr) {
        let idx = usize::try_from(ordinal).ok()?;
        if idx == 0 || idx > columns.len() {
            return None;
        }
        return match &columns[idx - 1] {
            ResultColumn::Expr {
                expr: output_expr, ..
            } => Some(output_expr),
            ResultColumn::Star | ResultColumn::TableStar(_) => None,
        };
    }

    // COLLATE changes ordering semantics but not output-alias name
    // resolution. Preserve the wrapper for sorter collation metadata at the
    // caller while resolving its inner expression against the SELECT list.
    let mut expr = expr;
    while let Expr::Collate { expr: inner, .. } = expr {
        expr = inner.as_ref();
    }

    let Expr::Column(col_ref, _) = expr else {
        return None;
    };
    if col_ref.table.is_some() {
        return None;
    }

    columns.iter().find_map(|column| {
        let ResultColumn::Expr {
            alias: Some(alias),
            expr: output_expr,
        } = column
        else {
            return None;
        };
        if !alias.eq_ignore_ascii_case(&col_ref.column) {
            return None;
        }
        match output_expr {
            Expr::Column(output_col_ref, _)
                if output_col_ref.table.is_none()
                    && output_col_ref.column.eq_ignore_ascii_case(&col_ref.column) =>
            {
                None
            }
            _ => Some(output_expr),
        }
    })
}

/// Resolve an exact ORDER BY output reference to its flattened result slot.
///
/// Unlike `resolve_order_by_output_expr`, ordinals count columns expanded from
/// `*`, because sorter records store the flattened result shape. Alias and
/// structural-expression matches follow the same COLLATE distinction as
/// `resolve_single_output_order_expr`: COLLATE may wrap an alias/ordinal, but a
/// separately written collated expression remains a separate evaluation.
fn resolve_order_by_output_slot(
    order_expr: &Expr,
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<usize> {
    if let Some(ordinal) = order_by_integer_ordinal(order_expr) {
        let one_based = usize::try_from(ordinal).ok()?;
        let slot = one_based.checked_sub(1)?;
        return (slot < result_column_count_usize(columns, table)).then_some(slot);
    }

    let mut alias_expr = order_expr;
    while let Expr::Collate { expr: inner, .. } = alias_expr {
        alias_expr = inner.as_ref();
    }
    if let Expr::Column(column, _) = alias_expr
        && column.table.is_none()
    {
        let mut slot = 0usize;
        for result_column in columns {
            match result_column {
                ResultColumn::Star | ResultColumn::TableStar(_) => {
                    slot += table.columns.len();
                }
                ResultColumn::Expr {
                    expr: output_expr,
                    alias: Some(alias),
                } if alias.eq_ignore_ascii_case(&column.column) => {
                    let is_same_named_source_column = matches!(
                        output_expr,
                        Expr::Column(output_column, _)
                            if output_column.table.is_none()
                                && output_column
                                    .column
                                    .eq_ignore_ascii_case(&column.column)
                    );
                    if !is_same_named_source_column {
                        return Some(slot);
                    }
                    slot += 1;
                }
                ResultColumn::Expr { .. } => slot += 1,
            }
        }
    }

    let mut slot = 0usize;
    for result_column in columns {
        match result_column {
            ResultColumn::Star | ResultColumn::TableStar(_) => {
                slot += table.columns.len();
            }
            ResultColumn::Expr {
                expr: output_expr, ..
            } => {
                if expressions_match_table_locally(order_expr, output_expr, table, table_alias) {
                    return Some(slot);
                }
                slot += 1;
            }
        }
    }
    None
}

fn result_output_slot_collation(
    output_slot: usize,
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<String> {
    let mut slot = 0usize;
    for result_column in columns {
        match result_column {
            ResultColumn::Star | ResultColumn::TableStar(_) => {
                let relative = output_slot.checked_sub(slot)?;
                if relative < table.columns.len() {
                    return table.columns[relative].collation.clone();
                }
                slot += table.columns.len();
            }
            ResultColumn::Expr { expr, .. } => {
                if slot == output_slot {
                    return extract_collation(expr)
                        .or_else(|| column_collation(expr, table, table_alias))
                        .map(ToOwned::to_owned);
                }
                slot += 1;
            }
        }
    }
    None
}

/// How an ordered DISTINCT query produces its final result row.
///
/// SQLite has two observably different plans. A general ordered DISTINCT
/// query retains the first projected output for each DISTINCT key and emits
/// that stored value after sorting. Plain exact ascending output tuples may
/// retain only their representative source row and project it after sorting.
/// Function-bearing projections retain their stored result so a volatile
/// function is evaluated exactly once per source row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OrderedDistinctProjectionMode {
    StoredOutput,
    ReprojectRepresentative,
}

fn ordered_distinct_projection_mode(
    distinct: Distinctness,
    order_by: &[OrderingTerm],
    order_output_slots: &[Option<usize>],
    sort_collations: &[String],
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> OrderedDistinctProjectionMode {
    let output_count = result_column_count_usize(columns, table);
    if distinct != Distinctness::Distinct
        || order_by.len() != output_count
        || order_output_slots.len() != output_count
        || sort_collations.len() != output_count
        || columns.iter().any(|column| {
            matches!(
                column,
                ResultColumn::Expr { expr, .. } if expr_contains_function_call(expr)
            )
        })
    {
        return OrderedDistinctProjectionMode::StoredOutput;
    }

    for (slot, term) in order_by.iter().enumerate() {
        if order_output_slots[slot] != Some(slot)
            || term.direction == Some(SortDirection::Desc)
            || term.nulls == Some(NullsOrder::Last)
            // An explicit COLLATE in the ORDER expression forces SQLite's
            // separate DISTINCT-membership/order plan, even when it names the
            // same collation as the output expression.
            || extract_collation(&term.expr).is_some()
        {
            return OrderedDistinctProjectionMode::StoredOutput;
        }

        let output_collation = result_output_slot_collation(slot, columns, table, table_alias);
        let order_collation =
            (!sort_collations[slot].is_empty()).then_some(sort_collations[slot].as_str());
        if !collation_names_equivalent(output_collation.as_deref(), order_collation) {
            return OrderedDistinctProjectionMode::StoredOutput;
        }
    }

    OrderedDistinctProjectionMode::ReprojectRepresentative
}

/// Resolve an ORDER BY integer ordinal, including SQLite's signed-literal
/// forms (`+1` is ordinal 1 and `-1` is an out-of-range ordinal).
///
/// COLLATE wrappers do not turn an ordinal into a constant expression. The
/// checked negation keeps the pathological `-i64::MIN` AST fail-closed.
fn order_by_integer_ordinal(expr: &Expr) -> Option<i64> {
    match expr {
        Expr::Literal(Literal::Integer(value), _) => Some(*value),
        Expr::UnaryOp {
            op: fsqlite_ast::UnaryOp::Plus,
            expr,
            ..
        }
        | Expr::Collate { expr, .. } => order_by_integer_ordinal(expr),
        Expr::UnaryOp {
            op: fsqlite_ast::UnaryOp::Negate,
            expr,
            ..
        } => order_by_integer_ordinal(expr)?.checked_neg(),
        _ => None,
    }
}

fn order_by_refers_to_single_star_output(expr: &Expr, columns: &[ResultColumn]) -> bool {
    if !matches!(columns, [ResultColumn::Star | ResultColumn::TableStar(_)]) {
        return false;
    }
    order_by_integer_ordinal(expr) == Some(1)
}

/// Return the sole projected expression when an ORDER BY term names it
/// directly (alias/ordinal) or is structurally the same expression.
///
/// SQLite evaluates a volatile expression only once per source row for these
/// exact non-DISTINCT ORDER BY references. COLLATE may wrap an alias/ordinal
/// without preventing name resolution, but otherwise remains part of the
/// structural expression. Local column qualifiers, identifier case, hidden
/// rowid synonyms, and an INTEGER PRIMARY KEY alias are schema-normalized
/// before the structural comparison.
fn resolve_single_output_order_expr<'a>(
    order_expr: &'a Expr,
    columns: &'a [ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<&'a Expr> {
    if let Some(output_expr) = resolve_order_by_output_expr(order_expr, columns) {
        return Some(output_expr);
    }
    let [
        ResultColumn::Expr {
            expr: output_expr, ..
        },
    ] = columns
    else {
        return None;
    };
    // Do not strip COLLATE for structural matching. `ORDER BY alias COLLATE`
    // was already resolved above and reuses the output, but a separately
    // written `ORDER BY volatile_expr() COLLATE ...` is a distinct expression
    // that SQLite evaluates again.
    expressions_match_table_locally(order_expr, output_expr, table, table_alias)
        .then_some(output_expr)
}

/// Resolve a column reference expression to either a column index or rowid.
///
/// Validates that any table qualifier matches the table name or alias.
/// Returns `None` if the expression is not a column reference or the
/// qualifier does not match.
fn resolve_column_ref(
    expr: &Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<SortKeySource> {
    // Unwrap COLLATE wrapper to reach the inner column reference.
    let inner = if let Expr::Collate { expr: inner, .. } = expr {
        inner.as_ref()
    } else {
        expr
    };
    if let Expr::Column(col_ref, _) = inner {
        if let Some(qualifier) = &col_ref.table
            && !matches_table_or_alias(qualifier, table, table_alias)
        {
            return None;
        }
        if let Some(idx) = table.column_index(&col_ref.column) {
            // INTEGER PRIMARY KEY columns are stored as rowid, not in the record payload.
            // Return Rowid so callers emit the Rowid opcode instead of Column.
            if table.columns[idx].is_ipk {
                return Some(SortKeySource::Rowid);
            }
            return Some(SortKeySource::Column(idx));
        }
        if table.resolves_to_hidden_rowid(&col_ref.column) {
            return Some(SortKeySource::Rowid);
        }
    }
    None
}

fn validate_single_table_expr_columns(
    expr: &Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Result<(), CodegenError> {
    validate_expr_columns_with(expr, &|col_ref| {
        validate_single_table_column_ref(col_ref, table, table_alias)
    })
}

fn validate_scan_expr_columns(expr: &Expr, scan: &ScanCtx<'_>) -> Result<(), CodegenError> {
    validate_expr_columns_with(expr, &|col_ref| validate_scan_column_ref(col_ref, scan))
}

fn validate_upsert_expr_columns(
    expr: &Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Result<(), CodegenError> {
    validate_expr_columns_with(expr, &|col_ref| {
        validate_upsert_column_ref(col_ref, table, table_alias)
    })
}

fn validate_assignment_target(
    table: &TableSchema,
    target: &AssignmentTarget,
) -> Result<(), CodegenError> {
    match target {
        AssignmentTarget::Column(name) => {
            if table.column_index(name).is_some() {
                Ok(())
            } else {
                Err(CodegenError::ColumnNotFound {
                    table: table.name.clone(),
                    column: name.clone(),
                })
            }
        }
        AssignmentTarget::ColumnList(columns) => {
            if columns.is_empty() {
                return Err(CodegenError::Unsupported(
                    "multi-column SET requires at least one target column".to_owned(),
                ));
            }
            for name in columns {
                if table.column_index(name).is_none() {
                    return Err(CodegenError::ColumnNotFound {
                        table: table.name.clone(),
                        column: name.clone(),
                    });
                }
            }
            Ok(())
        }
    }
}

fn validate_expr_columns_with<F>(expr: &Expr, validate_column: &F) -> Result<(), CodegenError>
where
    F: Fn(&ColumnRef) -> Result<(), CodegenError>,
{
    match expr {
        Expr::Column(col_ref, _) => validate_column(col_ref),
        Expr::BinaryOp { left, right, .. } => {
            validate_expr_columns_with(left, validate_column)?;
            validate_expr_columns_with(right, validate_column)
        }
        Expr::UnaryOp { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. }
        | Expr::IsNull { expr, .. } => validate_expr_columns_with(expr, validate_column),
        Expr::Between {
            expr, low, high, ..
        } => {
            validate_expr_columns_with(expr, validate_column)?;
            validate_expr_columns_with(low, validate_column)?;
            validate_expr_columns_with(high, validate_column)
        }
        Expr::In { expr, set, .. } => {
            validate_expr_columns_with(expr, validate_column)?;
            if let InSet::List(values) = set {
                for value in values {
                    validate_expr_columns_with(value, validate_column)?;
                }
            }
            Ok(())
        }
        Expr::Like {
            expr,
            pattern,
            escape,
            ..
        } => {
            validate_expr_columns_with(expr, validate_column)?;
            validate_expr_columns_with(pattern, validate_column)?;
            if let Some(escape) = escape {
                validate_expr_columns_with(escape, validate_column)?;
            }
            Ok(())
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            if let Some(operand) = operand {
                validate_expr_columns_with(operand, validate_column)?;
            }
            for (when_expr, then_expr) in whens {
                validate_expr_columns_with(when_expr, validate_column)?;
                validate_expr_columns_with(then_expr, validate_column)?;
            }
            if let Some(else_expr) = else_expr {
                validate_expr_columns_with(else_expr, validate_column)?;
            }
            Ok(())
        }
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            ..
        } => {
            if let FunctionArgs::List(arg_exprs) = args {
                for arg_expr in arg_exprs {
                    validate_expr_columns_with(arg_expr, validate_column)?;
                }
            }
            for term in order_by {
                validate_expr_columns_with(&term.expr, validate_column)?;
            }
            if let Some(filter) = filter {
                validate_expr_columns_with(filter, validate_column)?;
            }
            Ok(())
        }
        Expr::JsonAccess { expr, path, .. } => {
            validate_expr_columns_with(expr, validate_column)?;
            validate_expr_columns_with(path, validate_column)
        }
        Expr::RowValue(exprs, _) => {
            for expr in exprs {
                validate_expr_columns_with(expr, validate_column)?;
            }
            Ok(())
        }
        Expr::Exists { .. }
        | Expr::Subquery(_, _)
        | Expr::Literal(_, _)
        | Expr::BoundOuterValue { .. }
        | Expr::Placeholder(_, _)
        | Expr::Raise { .. } => Ok(()),
    }
}

fn validate_single_table_result_columns(
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
    from_schema: Option<&str>,
) -> Result<(), CodegenError> {
    for column in columns {
        match column {
            ResultColumn::Star => {}
            ResultColumn::TableStar(qualifier) => {
                if !table_star_qualifier_matches_binding(qualifier, table, table_alias, from_schema)
                {
                    return Err(CodegenError::TableNotFound(qualifier.to_string()));
                }
            }
            ResultColumn::Expr { expr, .. } => {
                validate_single_table_expr_columns(expr, table, table_alias)?;
            }
        }
    }
    Ok(())
}

fn validate_single_table_order_by_terms(
    order_by: &[OrderingTerm],
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Result<(), CodegenError> {
    let output_count = result_column_count_usize(columns, table);
    for (term_index, term) in order_by.iter().enumerate() {
        if let Some(ordinal) = order_by_integer_ordinal(&term.expr) {
            let in_range = usize::try_from(ordinal)
                .is_ok_and(|one_based| (1..=output_count).contains(&one_based));
            if !in_range {
                return Err(CodegenError::Unsupported(format!(
                    "ORDER BY term {} out of range - should be between 1 and {output_count}",
                    term_index + 1
                )));
            }
        }
        let rewritten = rewrite_having_select_aliases(&term.expr, columns, table);
        let expr = resolve_order_by_output_expr(&rewritten, columns).unwrap_or(&rewritten);
        validate_single_table_expr_columns(expr, table, table_alias)?;
    }
    Ok(())
}

fn validate_single_table_column_ref(
    col_ref: &ColumnRef,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Result<(), CodegenError> {
    if let Some(qualifier) = col_ref.table.as_deref()
        && !matches_table_or_alias(qualifier, table, table_alias)
    {
        return Err(qualified_column_not_found(qualifier, &col_ref.column));
    }
    if table.column_index(&col_ref.column).is_some()
        || table.resolves_to_hidden_rowid(&col_ref.column)
    {
        return Ok(());
    }
    if let Some(qualifier) = col_ref.table.as_deref() {
        return Err(qualified_column_not_found(qualifier, &col_ref.column));
    }
    Err(CodegenError::ColumnNotFound {
        table: table.name.clone(),
        column: col_ref.column.to_string(),
    })
}

fn validate_scan_column_ref(col_ref: &ColumnRef, scan: &ScanCtx<'_>) -> Result<(), CodegenError> {
    if let Some(qualifier) = col_ref.table.as_deref() {
        if matches_table_or_alias(qualifier, scan.table, scan.table_alias) {
            if table_has_column_or_rowid(scan.table, &col_ref.column) {
                return Ok(());
            }
            return Err(qualified_column_not_found(qualifier, &col_ref.column));
        }
        if let Some(secondary) = scan.secondaries.iter().find(|secondary| {
            matches_table_or_alias(qualifier, secondary.table, secondary.table_alias)
        }) {
            if table_has_column_or_rowid(secondary.table, &col_ref.column) {
                return Ok(());
            }
            return Err(qualified_column_not_found(qualifier, &col_ref.column));
        }
        return Err(qualified_column_not_found(qualifier, &col_ref.column));
    }

    let mut match_count = usize::from(table_has_column_or_rowid(scan.table, &col_ref.column));
    match_count += scan
        .secondaries
        .iter()
        .filter(|secondary| table_has_column_or_rowid(secondary.table, &col_ref.column))
        .count();

    match match_count {
        0 => Err(CodegenError::ColumnNotFound {
            table: scan.table.name.clone(),
            column: col_ref.column.to_string(),
        }),
        1 => Ok(()),
        _ => Err(CodegenError::AmbiguousColumn(col_ref.column.to_string())),
    }
}

fn validate_upsert_column_ref(
    col_ref: &ColumnRef,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Result<(), CodegenError> {
    if is_upsert_excluded_pseudo_table(col_ref, table, table_alias) {
        if table_has_column_or_rowid(table, &col_ref.column) {
            return Ok(());
        }
        return Err(qualified_column_not_found("excluded", &col_ref.column));
    }
    validate_single_table_column_ref(col_ref, table, table_alias)
}

fn is_upsert_excluded_pseudo_table(
    col_ref: &ColumnRef,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    col_ref.table.as_deref().is_some_and(|qualifier| {
        qualifier.eq_ignore_ascii_case("excluded")
            && !matches_table_or_alias(qualifier, table, table_alias)
    })
}

fn table_has_column_or_rowid(table: &TableSchema, column: &str) -> bool {
    table.column_index(column).is_some() || table.resolves_to_hidden_rowid(column)
}

/// Compute comparison p5 flags for a column reference.
///
/// Encodes NULLEQ (0x80) and the column's type affinity so the VDBE engine
/// applies correct text↔numeric coercion during comparison (§3.2).
#[allow(dead_code)]
fn column_cmp_p5(table: &TableSchema, resolved: &SortKeySource) -> u16 {
    let affinity: u16 = match resolved {
        SortKeySource::Column(idx) => u16::from(table.columns[*idx].affinity as u8),
        SortKeySource::Rowid => u16::from(b'D'), // INTEGER
        SortKeySource::Expression(_) => u16::from(b'A'), // BLOB (no coercion)
    };
    0x80 | affinity
}

/// Resolve a column reference to its 0-based index (ignoring rowid aliases).
///
/// Convenience wrapper for call sites that only care about real table columns.
fn resolve_column_index(expr: &Expr, table: &TableSchema) -> Option<usize> {
    match resolve_column_ref(expr, table, None) {
        Some(SortKeySource::Column(idx)) => Some(idx),
        _ => None,
    }
}

fn index_column_position(index: &IndexSchema, column_name: &str) -> Option<usize> {
    index
        .columns
        .iter()
        .position(|name| name.eq_ignore_ascii_case(column_name))
}

fn collect_conjunctive_terms<'a>(expr: &'a Expr, out: &mut Vec<&'a Expr>) {
    let mut pending = vec![expr];
    while let Some(term) = pending.pop() {
        if let Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::And,
            right,
            ..
        } = term
        {
            pending.push(right);
            pending.push(left);
        } else {
            out.push(term);
        }
    }
}

fn expr_matches_index_column(
    expr: &Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
    expected_column: &str,
) -> bool {
    column_name(expr, table, table_alias)
        .is_some_and(|column_name| column_name.eq_ignore_ascii_case(expected_column))
}

fn expressions_match_table_locally(
    query: &Expr,
    stored: &Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    let mut normalized_query = query.clone();
    let mut normalized_stored = stored.clone();
    normalize_table_local_expression(&mut normalized_query, table, table_alias)
        && normalize_table_local_expression(&mut normalized_stored, table, table_alias)
        && normalized_query == normalized_stored
}

/// Canonicalize table-local columns before structural expression matching.
///
/// Schema expressions normally contain bare columns, while SELECT expressions
/// can use either the table name or its visible alias. Strip only those local
/// qualifiers and resolve every column to a stable column-index identity.
/// Hidden rowid synonyms and an INTEGER PRIMARY KEY alias share one identity.
/// Foreign qualifiers, unknown columns, and nested scopes fail closed.
fn normalize_table_local_expression(
    expr: &mut Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    let normalize = |expr: &mut Expr| normalize_table_local_expression(expr, table, table_alias);
    match expr {
        Expr::Literal(..) | Expr::BoundOuterValue { .. } | Expr::Placeholder(..) => true,
        Expr::Column(column, _) => {
            if column.table.as_deref().is_some_and(|qualifier| {
                !qualifier.eq_ignore_ascii_case(&table.name)
                    && !table_alias.is_some_and(|alias| qualifier.eq_ignore_ascii_case(alias))
            }) {
                return false;
            }
            column.table = None;
            if let Some(index) = table.column_index(&column.column) {
                column.column = if table.columns[index].is_ipk {
                    "__fsqlite_local_rowid".into()
                } else {
                    format!("__fsqlite_local_column_{index}").into()
                };
                true
            } else if table.resolves_to_hidden_rowid(&column.column) {
                column.column = "__fsqlite_local_rowid".into();
                true
            } else {
                false
            }
        }
        Expr::BinaryOp { left, right, .. }
        | Expr::JsonAccess {
            expr: left,
            path: right,
            ..
        } => normalize(left) && normalize(right),
        Expr::UnaryOp { expr, .. } | Expr::Collate { expr, .. } | Expr::IsNull { expr, .. } => {
            normalize(expr)
        }
        Expr::Cast {
            expr, type_name, ..
        } => {
            type_name.name.make_ascii_lowercase();
            if let Some(arg) = &mut type_name.arg1 {
                arg.make_ascii_lowercase();
            }
            if let Some(arg) = &mut type_name.arg2 {
                arg.make_ascii_lowercase();
            }
            normalize(expr)
        }
        Expr::Between {
            expr, low, high, ..
        } => normalize(expr) && normalize(low) && normalize(high),
        Expr::In { expr, set, .. } => {
            normalize(expr)
                && match set {
                    InSet::List(items) => items.iter_mut().all(normalize),
                    InSet::Subquery(_) | InSet::Table(_) => false,
                }
        }
        Expr::Like {
            expr,
            pattern,
            escape,
            ..
        } => normalize(expr) && normalize(pattern) && escape.as_deref_mut().is_none_or(normalize),
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand.as_deref_mut().is_none_or(normalize)
                && whens
                    .iter_mut()
                    .all(|(when, then)| normalize(when) && normalize(then))
                && else_expr.as_deref_mut().is_none_or(normalize)
        }
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            over,
            ..
        } => {
            let args_local = match args {
                FunctionArgs::Star => false,
                FunctionArgs::List(args) => args.iter_mut().all(normalize),
            };
            args_local
                && order_by.iter_mut().all(|term| normalize(&mut term.expr))
                && filter.as_deref_mut().is_none_or(normalize)
                && over.is_none()
        }
        Expr::RowValue(items, _) => items.iter_mut().all(normalize),
        Expr::Exists { .. } | Expr::Subquery(..) | Expr::Raise { .. } => false,
    }
}

fn extract_index_column_equality_expr<'a>(
    expr: &'a Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
    expected_column: &str,
) -> Option<&'a Expr> {
    let Expr::BinaryOp {
        left,
        op: fsqlite_ast::BinaryOp::Eq,
        right,
        ..
    } = expr
    else {
        return None;
    };

    if expr_matches_index_column(left, table, table_alias, expected_column)
        && is_simple_constant(right)
    {
        return Some(right);
    }
    if expr_matches_index_column(right, table, table_alias, expected_column)
        && is_simple_constant(left)
    {
        return Some(left);
    }
    None
}

fn extract_index_equality_prefix_exprs<'a>(
    index: &IndexSchema,
    table: &TableSchema,
    table_alias: Option<&str>,
    where_clause: Option<&'a Expr>,
) -> Vec<&'a Expr> {
    let Some(where_expr) = where_clause else {
        return Vec::new();
    };

    let mut conjuncts = Vec::new();
    collect_conjunctive_terms(where_expr, &mut conjuncts);

    let mut prefix_exprs = Vec::new();
    for index_column in &index.columns {
        let Some(expr) = conjuncts.iter().find_map(|term| {
            extract_index_column_equality_expr(term, table, table_alias, index_column)
        }) else {
            break;
        };
        prefix_exprs.push(expr);
    }
    prefix_exprs
}

fn resolve_covering_output_sources(
    columns: &[ResultColumn],
    table: &TableSchema,
    table_alias: Option<&str>,
    index: &IndexSchema,
) -> Option<Vec<CoveringOutputSource>> {
    let mut output = Vec::with_capacity(columns.len());

    for col in columns {
        match col {
            ResultColumn::Expr { expr, .. } => {
                match resolve_column_ref(expr, table, table_alias)? {
                    SortKeySource::Column(col_idx) => {
                        let column_name = &table.columns.get(col_idx)?.name;
                        let index_pos = index_column_position(index, column_name)?;
                        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                        output.push(CoveringOutputSource::IndexColumn(index_pos as i32));
                    }
                    SortKeySource::Rowid => output.push(CoveringOutputSource::Rowid),
                    SortKeySource::Expression(_) => return None,
                }
            }
            ResultColumn::Star | ResultColumn::TableStar(_) => return None,
        }
    }

    Some(output)
}

fn resolve_order_by_rowid_direction(
    table: &TableSchema,
    table_alias: Option<&str>,
    columns: &[ResultColumn],
    order_by: &[OrderingTerm],
) -> Option<SortDirection> {
    let [term] = order_by else {
        return None;
    };
    if term.nulls.is_some() {
        return None;
    }

    let resolved_expr = resolve_order_by_output_expr(&term.expr, columns).unwrap_or(&term.expr);

    matches!(
        resolve_column_ref(resolved_expr, table, table_alias),
        Some(SortKeySource::Rowid)
    )
    .then_some(term.direction.unwrap_or(SortDirection::Asc))
}

fn resolve_order_by_index_plan(
    table: &TableSchema,
    table_alias: Option<&str>,
    columns: &[ResultColumn],
    where_clause: Option<&Expr>,
    order_by: &[OrderingTerm],
    distinct: Distinctness,
) -> Option<OrderByIndexPlan> {
    if order_by.is_empty() || distinct == Distinctness::Distinct {
        return None;
    }

    // Keep the direction and effective collation attached to each resolved
    // column.  An equality-constrained index prefix is removed per candidate
    // index below, so its (irrelevant) direction must not constrain the
    // variable suffix.
    let mut order_columns = Vec::with_capacity(order_by.len());

    for term in order_by {
        if term.nulls.is_some() {
            return None;
        }
        let term_direction = term.direction.unwrap_or(SortDirection::Asc);

        let resolved_expr = resolve_order_by_output_expr(&term.expr, columns).unwrap_or(&term.expr);

        let Expr::Column(col_ref, _) = resolved_expr else {
            return None;
        };
        if let Some(qualifier) = &col_ref.table
            && !matches_table_or_alias(qualifier, table, table_alias)
        {
            return None;
        }
        if table.resolves_to_hidden_rowid(&col_ref.column) {
            return None;
        }
        order_columns.push((
            col_ref.column.to_string(),
            term_direction,
            column_collation(resolved_expr, table, table_alias),
        ));
    }

    let mut best_plan: Option<OrderByIndexPlan> = None;

    for index in &table.indexes {
        if !index.supports_direct_column_lookup() {
            continue;
        }

        let equality_prefix_len =
            extract_index_equality_prefix_exprs(index, table, table_alias, where_clause).len();

        // Equality probes and ORDER BY must agree with the index's collation.
        // In particular, a NOCASE index cannot prove that a BINARY equality
        // prefix is constant (or vice versa).
        if (0..equality_prefix_len).any(|key_pos| {
            let Some(column_idx) = table.column_index(&index.columns[key_pos]) else {
                return true;
            };
            !collation_names_equivalent(
                table.columns[column_idx].collation.as_deref(),
                index.key_term_collation(key_pos),
            )
        }) {
            continue;
        }

        // ORDER BY terms that repeat the leading equality-constrained index
        // columns are constants within this query scope.  Consume only the
        // exact leading sequence; this deliberately declines reordered,
        // duplicate, COLLATE-wrapped, or otherwise non-obvious forms.
        let fixed_order_prefix_len = order_columns
            .iter()
            .zip(index.columns.iter().take(equality_prefix_len))
            .enumerate()
            .take_while(|(key_pos, ((order_col, _, order_collation), index_col))| {
                order_col.eq_ignore_ascii_case(index_col)
                    && collation_names_equivalent(
                        *order_collation,
                        index.key_term_collation(*key_pos),
                    )
            })
            .count();
        let variable_order = &order_columns[fixed_order_prefix_len..];

        if equality_prefix_len + variable_order.len() > index.key_term_count() {
            continue;
        }

        let direction = variable_order.first().map(|(_, direction, _)| *direction);
        if variable_order
            .iter()
            .any(|(_, term_direction, _)| Some(*term_direction) != direction)
        {
            continue;
        }
        let descending = direction == Some(SortDirection::Desc);

        if equality_prefix_len > 0 && descending {
            // The generic bounded-prefix emitter currently walks forward.
            // Composite prefix+range DESC queries use their dedicated reverse
            // seek path before reaching this resolver.
            continue;
        }

        let matches_order_columns =
            variable_order
                .iter()
                .enumerate()
                .all(|(offset, (order_col, _, order_collation))| {
                    let key_pos = equality_prefix_len + offset;
                    !index.key_term_descending(key_pos)
                        && index.columns[key_pos].eq_ignore_ascii_case(order_col)
                        && collation_names_equivalent(
                            *order_collation,
                            index.key_term_collation(key_pos),
                        )
                });
        if !matches_order_columns {
            continue;
        }

        let covering_output = if where_clause.is_none() {
            resolve_covering_output_sources(columns, table, table_alias, index)
        } else {
            None
        };

        let candidate = OrderByIndexPlan {
            index: index.clone(),
            descending,
            equality_prefix_len,
            covering_output,
        };
        let should_replace = match best_plan.as_ref() {
            None => true,
            Some(existing) => {
                candidate.equality_prefix_len > existing.equality_prefix_len
                    || (candidate.equality_prefix_len == existing.equality_prefix_len
                        && candidate.covering_output.is_some()
                        && existing.covering_output.is_none())
            }
        };
        if should_replace {
            best_plan = Some(candidate);
        }
    }

    best_plan
}

/// Resolve result columns to table column indices.
///
/// Returns a Vec of column indices for each output column.
/// `Star` and `TableStar` expand to all table columns.
///
/// NOTE: Currently unused — `emit_column_reads` handles non-column result
/// expressions directly. Kept for potential future index-only scan codegen.
#[allow(
    dead_code,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap
)]
fn resolve_result_column_indices(
    columns: &[ResultColumn],
    table: &TableSchema,
) -> Result<Vec<usize>, CodegenError> {
    let mut indices = Vec::new();
    for col in columns {
        match col {
            ResultColumn::Star => {
                indices.extend(0..table.columns.len());
            }
            ResultColumn::TableStar(qualifier) => {
                if !qualifier.name.eq_ignore_ascii_case(&table.name) {
                    return Err(CodegenError::TableNotFound(qualifier.to_string()));
                }
                indices.extend(0..table.columns.len());
            }
            ResultColumn::Expr { expr, .. } => {
                if let Expr::Column(col_ref, _) = expr {
                    let idx = table.column_index(&col_ref.column).ok_or_else(|| {
                        CodegenError::ColumnNotFound {
                            table: table.name.clone(),
                            column: col_ref.column.to_string(),
                        }
                    })?;
                    indices.push(idx);
                } else {
                    return Err(CodegenError::Unsupported(
                        "non-column result expression in table-backed SELECT".to_owned(),
                    ));
                }
            }
        }
    }
    Ok(indices)
}

fn is_simple_constant(expr: &Expr) -> bool {
    // This predicate is used only to admit values into raw physical
    // rowid/index probes.  A bound outer value is logically constant for one
    // invocation, but its comparison still carries the outer expression's
    // affinity and declared-collation metadata.  The b-tree seek key does not
    // encode that operand-order-dependent comparison contract, so treating a
    // BoundOuterValue like a literal can make the probed key range either a
    // subset or a superset of the SQL equality result.  Keep literals and bind
    // parameters on the fast path, and make correlated values use the
    // comparator-correct scan path.
    matches!(expr, Expr::Placeholder(..) | Expr::Literal(..))
}

fn is_rowid_range_constant(expr: &Expr) -> bool {
    matches!(expr, Expr::Literal(..))
        || matches!(
            expr,
            Expr::Placeholder(
                fsqlite_ast::PlaceholderType::Numbered(_)
                    | fsqlite_ast::PlaceholderType::ColonNamed(_)
                    | fsqlite_ast::PlaceholderType::AtNamed(_)
                    | fsqlite_ast::PlaceholderType::DollarNamed(_),
                _
            )
        )
}

fn is_index_range_constant(expr: &Expr) -> bool {
    // A negative numeric literal parses as `UnaryOp(Negate, Literal(..))`, which
    // `is_rowid_range_constant` does not recognize. Accept it here so a range bound like
    // `rr BETWEEN -1.0 AND 4.0` is extracted; `index_range_fast_path_is_safe` still gates
    // whether the extracted range is seek-safe (and `is_numeric_literal_bound` mirrors this
    // negated-literal shape), so broadening extraction cannot admit an unsafe seek.
    is_rowid_range_constant(expr) || is_numeric_literal_bound(expr)
}

/// Whether an expression contains a value captured from an outer query scope.
///
/// Correlated rowid-probe extraction accepts expressions rather than only
/// literals, so the top-level constant gates above are not enough: a bound
/// value can be nested below CAST, arithmetic, CASE, or a function call.  Such
/// a value must not become an authoritative physical seek key until that seek
/// can reproduce the full SQL comparison's operand order, affinity, and
/// collation.
fn expr_contains_bound_outer_value(expr: &Expr) -> bool {
    match expr {
        Expr::BoundOuterValue { .. } => true,
        Expr::BinaryOp { left, right, .. }
        | Expr::JsonAccess {
            expr: left,
            path: right,
            ..
        } => expr_contains_bound_outer_value(left) || expr_contains_bound_outer_value(right),
        Expr::UnaryOp { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. }
        | Expr::IsNull { expr, .. } => expr_contains_bound_outer_value(expr),
        Expr::Between {
            expr, low, high, ..
        } => {
            expr_contains_bound_outer_value(expr)
                || expr_contains_bound_outer_value(low)
                || expr_contains_bound_outer_value(high)
        }
        Expr::In { expr, set, .. } => {
            expr_contains_bound_outer_value(expr)
                || matches!(
                    set,
                    InSet::List(values) if values.iter().any(expr_contains_bound_outer_value)
                )
        }
        Expr::Like {
            expr,
            pattern,
            escape,
            ..
        } => {
            expr_contains_bound_outer_value(expr)
                || expr_contains_bound_outer_value(pattern)
                || escape
                    .as_deref()
                    .is_some_and(expr_contains_bound_outer_value)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand
                .as_deref()
                .is_some_and(expr_contains_bound_outer_value)
                || whens.iter().any(|(when_expr, then_expr)| {
                    expr_contains_bound_outer_value(when_expr)
                        || expr_contains_bound_outer_value(then_expr)
                })
                || else_expr
                    .as_deref()
                    .is_some_and(expr_contains_bound_outer_value)
        }
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            ..
        } => {
            matches!(
                args,
                FunctionArgs::List(values)
                    if values.iter().any(expr_contains_bound_outer_value)
            ) || order_by
                .iter()
                .any(|term| expr_contains_bound_outer_value(&term.expr))
                || filter
                    .as_deref()
                    .is_some_and(expr_contains_bound_outer_value)
        }
        Expr::RowValue(values, _) => values.iter().any(expr_contains_bound_outer_value),
        // Nested SELECT scopes are rejected separately by the rowid-probe
        // admission gate.  They are opaque here by design.
        Expr::Exists { .. }
        | Expr::Subquery(..)
        | Expr::Literal(..)
        | Expr::Column(..)
        | Expr::Placeholder(..)
        | Expr::Raise { .. } => false,
    }
}

/// Check if a WHERE clause is a simple `rowid = ?` bind parameter.
///
/// Returns the 1-based bind parameter index if so.
#[allow(dead_code)]
fn extract_rowid_bind_param(
    where_clause: Option<&Expr>,
    table: Option<&TableSchema>,
    table_alias: Option<&str>,
) -> Option<i32> {
    let expr = extract_rowid_target_expr(where_clause, table, table_alias)?;
    bind_param_index(expr)
}

fn extract_rowid_target_expr<'a>(
    where_clause: Option<&'a Expr>,
    table: Option<&TableSchema>,
    table_alias: Option<&str>,
) -> Option<&'a Expr> {
    let expr = where_clause?;
    if let Expr::BinaryOp {
        left,
        op: fsqlite_ast::BinaryOp::Eq,
        right,
        ..
    } = expr
    {
        if is_rowid_expr(left, table, table_alias) && is_simple_constant(right) {
            return Some(right);
        }
        if is_rowid_expr(right, table, table_alias) && is_simple_constant(left) {
            return Some(left);
        }
    }
    None
}

/// The `rowid = <const>` target when it is a conjunct alongside OTHER predicates the SeekRowid cannot
/// enforce — `rowid = <const> AND <residual>`. Returns the const RHS; the caller does one SeekRowid and
/// re-applies the whole WHERE per the single row (the target row is a SUPERSET of size 1, the residual
/// narrows to exact). Declines the BARE `rowid = <const>` (single conjunct) so that shape keeps flowing
/// through the existing RowidLookup directive path unchanged (golden snapshots stable). The residual
/// sibling of [`extract_rowid_target_expr`], mirroring [`extract_rowid_in_list_residual_target`].
/// bd-nonagg-rowid-eq-residual.
fn extract_rowid_eq_residual_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<&'a Expr> {
    let where_expr = where_clause?;
    let mut conjuncts = Vec::new();
    collect_conjunctive_terms(where_expr, &mut conjuncts);
    if conjuncts.len() < 2 {
        return None;
    }
    for term in conjuncts {
        if let Some(expr) = extract_rowid_target_expr(Some(term), Some(table), table_alias) {
            return Some(expr);
        }
    }
    None
}

/// The distinct integer values a `WHERE <rowid> IN (<int list>)` predicate can seek per value.
///
/// bd-2dgf5. Integer literals only (`SeekRowid` truncates via `to_integer()`, so `id = 2.5`
/// would wrongly match rowid 2; negatives parse as unary-negate and decline), `IN` not
/// `NOT IN`, non-empty. De-duplicated. Anything else declines to the scan.
/// Collect the leaves of a pure `OR` chain of `<expr> = <integer literal>` into `out`.
///
/// Returns false if any leaf is not `something = int` / `int = something`. The caller checks
/// that every collected column expression is the SAME column, so `k = 2 OR j = 3` is rejected.
/// Precedence is respected by the AST: `k = 2 OR k = 5 AND x` parses as `k = 2 OR (k = 5 AND x)`,
/// whose right leaf is an `And` and fails here.
fn collect_or_int_eq_leaves<'a>(expr: &'a Expr, out: &mut Vec<(&'a Expr, i64)>) -> bool {
    match expr {
        Expr::BinaryOp {
            op: fsqlite_ast::BinaryOp::Or,
            left,
            right,
            ..
        } => collect_or_int_eq_leaves(left, out) && collect_or_int_eq_leaves(right, out),
        Expr::BinaryOp {
            op: fsqlite_ast::BinaryOp::Eq,
            left,
            right,
            ..
        } => {
            if let Expr::Literal(Literal::Integer(n), _) = right.as_ref() {
                out.push((left, *n));
                true
            } else if let Expr::Literal(Literal::Integer(n), _) = left.as_ref() {
                out.push((right, *n));
                true
            } else {
                false
            }
        }
        _ => false,
    }
}

/// The column expression and distinct sorted integer values of a `WHERE col IN (<int list>)`
/// OR a semantically equivalent `WHERE col = a OR col = b OR ...` predicate.
///
/// bd-2dgf5. Integer literals only (exact probe, no affinity coercion), same column across an
/// OR chain, `IN` not `NOT IN`, non-empty. Values are de-duplicated, so `col = a OR col = a`
/// and `IN (a, a)` both collapse to one seek, matching SQLite's set semantics.
fn column_int_list_from_predicate<'a>(
    where_clause: Option<&'a Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<(&'a Expr, Vec<i64>)> {
    let expr = where_clause?;
    let (column, mut ints): (&Expr, Vec<i64>) = if let Expr::In {
        expr: column,
        set: fsqlite_ast::InSet::List(values),
        not: false,
        ..
    } = expr
    {
        if values.is_empty() {
            return None;
        }
        let mut ints = Vec::with_capacity(values.len());
        for value in values {
            match value {
                Expr::Literal(Literal::Integer(n), _) => ints.push(*n),
                _ => return None,
            }
        }
        (column.as_ref(), ints)
    } else if matches!(
        expr,
        Expr::BinaryOp {
            op: fsqlite_ast::BinaryOp::Or,
            ..
        }
    ) {
        // Only an actual OR chain normalizes here. A bare `col = <int>` is left to the
        // existing rowid-equality / index-equality paths (which own its EQP shape); treating
        // it as a one-element IN-list would re-route it and change its EXPLAIN output.
        let mut leaves: Vec<(&Expr, i64)> = Vec::new();
        if !collect_or_int_eq_leaves(expr, &mut leaves) || leaves.is_empty() {
            return None;
        }
        // Same-column check, rowid-aware: `column_name` returns None for the rowid alias, so
        // fold rowid refs to a single identity. This keeps `id = 2 OR id = 3` (and `id = 2 OR
        // rowid = 3`, the same column) together while rejecting `k = 2 OR j = 3`.
        let identity = |e: &Expr| -> Option<String> {
            if is_rowid_expr(e, Some(table), table_alias) {
                Some("\0rowid".to_owned())
            } else {
                column_name(e, table, table_alias)
            }
        };
        let first_col = leaves[0].0;
        let first_ident = identity(first_col)?;
        for (col, _) in &leaves {
            if identity(col).as_deref() != Some(first_ident.as_str()) {
                return None;
            }
        }
        let ints = leaves.iter().map(|(_, n)| *n).collect();
        (first_col, ints)
    } else {
        return None;
    };
    ints.sort_unstable();
    ints.dedup();
    Some((column, ints))
}

fn extract_rowid_in_list_target(
    where_clause: Option<&Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<Vec<i64>> {
    let (column, ints) = column_int_list_from_predicate(where_clause, table, table_alias)?;
    is_rowid_expr(column, Some(table), table_alias).then_some(ints)
}

/// `(values, has_residual)`. `false` = the whole WHERE is `rowid IN (ints)`. `true` = it is a conjunct
/// alongside OTHER predicates the SeekRowid probes cannot enforce; the caller re-applies the whole WHERE
/// per row (the listed rowids are a SUPERSET, the residual narrows to exact). Mirrors
/// [`index_integer_in_list_residual_target`]. bd-nonagg-rowid-in-residual.
fn extract_rowid_in_list_residual_target(
    where_clause: Option<&Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<(Vec<i64>, bool)> {
    if let Some(ints) = extract_rowid_in_list_target(where_clause, table, table_alias) {
        return Some((ints, false));
    }
    let where_expr = where_clause?;
    let mut conjuncts = Vec::new();
    collect_conjunctive_terms(where_expr, &mut conjuncts);
    if conjuncts.len() < 2 {
        return None;
    }
    for term in &conjuncts {
        if let Some(ints) = extract_rowid_in_list_target(Some(term), table, table_alias) {
            return Some((ints, true));
        }
    }
    None
}

fn extract_rowid_range_target<'a>(
    where_clause: Option<&'a Expr>,
    table: Option<&TableSchema>,
    table_alias: Option<&str>,
) -> Option<RowidRangeTarget<'a>> {
    let expr = where_clause?;
    let mut target = RowidRangeTarget::default();
    if collect_rowid_range_bounds(expr, table, table_alias, &mut target)
        && (target.lower.is_some() || target.upper.is_some())
    {
        Some(target)
    } else {
        None
    }
}

/// Returns `(range, has_residual)`. `has_residual == false` is the plain rowid-range case (whole WHERE
/// is a rowid range). `has_residual == true` additionally allows a rowid range that coexists with OTHER
/// (placeholder-free) predicates the seek cannot enforce: the rowid range visits a SUPERSET of the
/// matching rows and the caller re-applies the whole WHERE as a residual filter per row. Aggregates are
/// order-independent, so visiting a superset and filtering is byte-exact. Both cases require the range
/// to pass `rowid_range_fast_path_is_safe`.
fn extract_rowid_range_residual_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<(RowidRangeTarget<'a>, bool)> {
    let expr = where_clause?;
    if let Some(range) = extract_rowid_range_target(where_clause, Some(table), table_alias) {
        return rowid_range_fast_path_is_safe(range).then_some((range, false));
    }
    let mut conjuncts = Vec::new();
    collect_conjunctive_terms(expr, &mut conjuncts);
    let mut target = RowidRangeTarget::default();
    for term in &conjuncts {
        match term {
            Expr::BinaryOp {
                left, op, right, ..
            } => {
                if let Some((slot, bound)) =
                    extract_rowid_range_bound(left, *op, right, Some(table), table_alias)
                    && !assign_rowid_range_bound(&mut target, slot, bound)
                {
                    return None; // conflicting duplicate bound
                }
            }
            Expr::Between {
                expr: operand,
                low,
                high,
                not: false,
                ..
            } if is_rowid_expr(operand, Some(table), table_alias)
                && is_rowid_range_constant(low)
                && is_rowid_range_constant(high) =>
            {
                let bounds_assigned = assign_rowid_range_bound(
                    &mut target,
                    RowidRangeSlot::Lower,
                    RowidRangeBound {
                        rowid_expr: operand,
                        expr: low,
                        inclusive: true,
                    },
                ) && assign_rowid_range_bound(
                    &mut target,
                    RowidRangeSlot::Upper,
                    RowidRangeBound {
                        rowid_expr: operand,
                        expr: high,
                        inclusive: true,
                    },
                );
                if !bounds_assigned {
                    return None;
                }
            }
            _ => {} // non-rowid conjunct: a residual the filter enforces
        }
    }
    if target.lower.is_none() && target.upper.is_none() {
        return None;
    }
    // The seek probe emits the bound values, so require integer-LITERAL bounds: then it emits no
    // anonymous placeholders and a `?` can appear only in the residual, where the filter numbers it
    // identically to the scan path (bd-agg-param-residual). A placeholder bound (`id > ?`) declines.
    let literal_bound = |b: &Option<RowidRangeBound<'a>>| {
        b.as_ref()
            .is_none_or(|bound| matches!(bound.expr, Expr::Literal(Literal::Integer(_), _)))
    };
    if !literal_bound(&target.lower) || !literal_bound(&target.upper) {
        return None;
    }
    rowid_range_fast_path_is_safe(target).then_some((target, true))
}

fn collect_rowid_range_bounds<'a>(
    expr: &'a Expr,
    table: Option<&TableSchema>,
    table_alias: Option<&str>,
    target: &mut RowidRangeTarget<'a>,
) -> bool {
    match expr {
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::And,
            right,
            ..
        } => {
            collect_rowid_range_bounds(left, table, table_alias, target)
                && collect_rowid_range_bounds(right, table, table_alias, target)
        }
        Expr::BinaryOp {
            left, op, right, ..
        } => extract_rowid_range_bound(left, *op, right, table, table_alias)
            .is_some_and(|(slot, bound)| assign_rowid_range_bound(target, slot, bound)),
        Expr::Between {
            expr: operand,
            low,
            high,
            not: false,
            ..
        } if is_rowid_expr(operand, table, table_alias)
            && is_rowid_range_constant(low)
            && is_rowid_range_constant(high) =>
        {
            assign_rowid_range_bound(
                target,
                RowidRangeSlot::Lower,
                RowidRangeBound {
                    rowid_expr: operand,
                    expr: low,
                    inclusive: true,
                },
            ) && assign_rowid_range_bound(
                target,
                RowidRangeSlot::Upper,
                RowidRangeBound {
                    rowid_expr: operand,
                    expr: high,
                    inclusive: true,
                },
            )
        }
        _ => false,
    }
}

#[derive(Clone, Copy)]
enum RowidRangeSlot {
    Lower,
    Upper,
}

fn extract_rowid_range_bound<'a>(
    left: &'a Expr,
    op: fsqlite_ast::BinaryOp,
    right: &'a Expr,
    table: Option<&TableSchema>,
    table_alias: Option<&str>,
) -> Option<(RowidRangeSlot, RowidRangeBound<'a>)> {
    if is_rowid_expr(left, table, table_alias) && is_rowid_range_constant(right) {
        return match op {
            fsqlite_ast::BinaryOp::Ge => Some((
                RowidRangeSlot::Lower,
                RowidRangeBound {
                    rowid_expr: left,
                    expr: right,
                    inclusive: true,
                },
            )),
            fsqlite_ast::BinaryOp::Gt => Some((
                RowidRangeSlot::Lower,
                RowidRangeBound {
                    rowid_expr: left,
                    expr: right,
                    inclusive: false,
                },
            )),
            fsqlite_ast::BinaryOp::Le => Some((
                RowidRangeSlot::Upper,
                RowidRangeBound {
                    rowid_expr: left,
                    expr: right,
                    inclusive: true,
                },
            )),
            fsqlite_ast::BinaryOp::Lt => Some((
                RowidRangeSlot::Upper,
                RowidRangeBound {
                    rowid_expr: left,
                    expr: right,
                    inclusive: false,
                },
            )),
            _ => None,
        };
    }

    if is_rowid_expr(right, table, table_alias) && is_rowid_range_constant(left) {
        return match op {
            fsqlite_ast::BinaryOp::Le => Some((
                RowidRangeSlot::Lower,
                RowidRangeBound {
                    rowid_expr: right,
                    expr: left,
                    inclusive: true,
                },
            )),
            fsqlite_ast::BinaryOp::Lt => Some((
                RowidRangeSlot::Lower,
                RowidRangeBound {
                    rowid_expr: right,
                    expr: left,
                    inclusive: false,
                },
            )),
            fsqlite_ast::BinaryOp::Ge => Some((
                RowidRangeSlot::Upper,
                RowidRangeBound {
                    rowid_expr: right,
                    expr: left,
                    inclusive: true,
                },
            )),
            fsqlite_ast::BinaryOp::Gt => Some((
                RowidRangeSlot::Upper,
                RowidRangeBound {
                    rowid_expr: right,
                    expr: left,
                    inclusive: false,
                },
            )),
            _ => None,
        };
    }

    None
}

fn assign_rowid_range_bound<'a>(
    target: &mut RowidRangeTarget<'a>,
    slot: RowidRangeSlot,
    bound: RowidRangeBound<'a>,
) -> bool {
    let target_slot = match slot {
        RowidRangeSlot::Lower => &mut target.lower,
        RowidRangeSlot::Upper => &mut target.upper,
    };
    if target_slot.is_some() {
        false
    } else {
        *target_slot = Some(bound);
        true
    }
}

/// Check if a WHERE clause is `col = ?` for an indexed column.
fn extract_column_eq_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<(String, &'a Expr)> {
    let expr = where_clause?;
    if let Expr::BinaryOp {
        left,
        op: fsqlite_ast::BinaryOp::Eq,
        right,
        ..
    } = expr
    {
        if let Some(col_name) = column_name(left, table, table_alias)
            && is_simple_constant(right)
        {
            return Some((col_name, right));
        }
        if let Some(col_name) = column_name(right, table, table_alias)
            && is_simple_constant(left)
        {
            return Some((col_name, left));
        }
    }
    None
}

/// Extract the `<directive-key-column> = <simple constant>` conjunct from a
/// conjunction-shaped WHERE clause (bd-kwaam / #377).
///
/// The planner classifies equality terms inside AND-trees when it emits an
/// `IndexEquality` directive, but [`extract_column_eq_target`] only matches
/// single-term predicates, so every multi-term guard (`cap = ? AND ord = ?`
/// against a composite UNIQUE index) used to bypass the seek to a heuristic
/// full scan — catastrophically on WITHOUT ROWID tables, which have no other
/// indexed path. This recovers the directive's own conjunct; callers lower it
/// through the residual-filtering emitter so the remaining conjuncts stay
/// enforced. OR subtrees are skipped: a disjunction is not an equality
/// conjunct and must keep declining.
fn extract_labeled_eq_conjunct_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
    key_label: &str,
) -> Option<&'a Expr> {
    let mut stack = vec![where_clause?];
    while let Some(expr) = stack.pop() {
        match expr {
            Expr::BinaryOp {
                op: fsqlite_ast::BinaryOp::And,
                left,
                right,
                ..
            } => {
                stack.push(left);
                stack.push(right);
            }
            Expr::BinaryOp {
                left,
                op: fsqlite_ast::BinaryOp::Eq,
                right,
                ..
            } => {
                if let Some(col_name) = column_name(left, table, table_alias)
                    && col_name.eq_ignore_ascii_case(key_label)
                    && is_simple_constant(right)
                {
                    return Some(right);
                }
                if let Some(col_name) = column_name(right, table, table_alias)
                    && col_name.eq_ignore_ascii_case(key_label)
                    && is_simple_constant(left)
                {
                    return Some(left);
                }
            }
            _ => {}
        }
    }
    None
}

fn extract_expression_index_equality_expr<'a>(
    where_clause: Option<&'a Expr>,
    index: &IndexSchema,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<&'a Expr> {
    let root = where_clause?;
    let key_expr = parse_sql_expr(index.key_term_sql(0)?).ok()?;
    let mut pending = vec![root];
    let mut residuals = Vec::new();
    let mut target = None;
    while let Some(expr) = pending.pop() {
        let Expr::BinaryOp {
            left, op, right, ..
        } = expr
        else {
            residuals.push(expr);
            continue;
        };
        if *op == fsqlite_ast::BinaryOp::And {
            pending.push(right);
            pending.push(left);
            continue;
        }
        if *op != fsqlite_ast::BinaryOp::Eq {
            residuals.push(expr);
            continue;
        }
        let candidate = if expressions_match_table_locally(left, &key_expr, table, table_alias)
            && is_simple_constant(right)
        {
            Some(right.as_ref())
        } else if expressions_match_table_locally(right, &key_expr, table, table_alias)
            && is_simple_constant(left)
        {
            Some(left.as_ref())
        } else {
            None
        };
        if let Some(candidate) = candidate {
            if target.replace(candidate).is_some() {
                return None;
            }
        } else {
            residuals.push(expr);
        }
    }
    target.filter(|_| expression_index_residuals_match(&residuals, index, table, table_alias))
}

#[derive(Clone, Copy)]
enum PlannerIndexRangeSlot {
    Lower,
    Upper,
}

fn extract_expression_index_range_target(
    where_clause: Option<&Expr>,
    index: &IndexSchema,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<PlannerIndexRangeTarget> {
    let expr = where_clause?;
    let key_expr = parse_sql_expr(index.key_term_sql(0)?).ok()?;
    let mut target = PlannerIndexRangeTarget::default();
    let mut residuals = Vec::new();
    if collect_expression_index_range_bounds(
        expr,
        &key_expr,
        table,
        table_alias,
        &mut target,
        &mut residuals,
    ) && (target.lower.is_some() || target.upper.is_some())
        && expression_index_residuals_match(&residuals, index, table, table_alias)
    {
        Some(target)
    } else {
        None
    }
}

fn collect_expression_index_range_bounds<'a>(
    root: &'a Expr,
    key_expr: &Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
    target: &mut PlannerIndexRangeTarget,
    residuals: &mut Vec<&'a Expr>,
) -> bool {
    let mut found_bound = false;
    let mut pending = vec![root];
    while let Some(expr) = pending.pop() {
        if let Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::And,
            right,
            ..
        } = expr
        {
            pending.push(right);
            pending.push(left);
            continue;
        }

        if let Expr::BinaryOp {
            left, op, right, ..
        } = expr
            && let Some((slot, bound)) =
                extract_expression_index_range_bound(left, *op, right, key_expr, table, table_alias)
        {
            if !assign_expression_index_range_bound(target, slot, bound) {
                return false;
            }
            found_bound = true;
            continue;
        }

        if let Expr::Between {
            expr: operand,
            low,
            high,
            not: false,
            ..
        } = expr
            && expressions_match_table_locally(operand, key_expr, table, table_alias)
            && is_index_range_constant(low)
            && is_index_range_constant(high)
        {
            if !assign_expression_index_range_bound(
                target,
                PlannerIndexRangeSlot::Lower,
                PlannerIndexRangeBound {
                    expr: low.as_ref().clone(),
                    inclusive: true,
                },
            ) || !assign_expression_index_range_bound(
                target,
                PlannerIndexRangeSlot::Upper,
                PlannerIndexRangeBound {
                    expr: high.as_ref().clone(),
                    inclusive: true,
                },
            ) {
                return false;
            }
            found_bound = true;
            continue;
        }

        residuals.push(expr);
    }
    found_bound
}

fn expression_index_residuals_match(
    residuals: &[&Expr],
    index: &IndexSchema,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    let Some(predicate_sql) = index.where_clause.as_deref() else {
        return residuals.is_empty();
    };
    let Ok(predicate) = parse_sql_expr(predicate_sql) else {
        return false;
    };
    let mut predicate_terms = Vec::new();
    collect_conjunctive_terms(&predicate, &mut predicate_terms);

    predicate_terms.iter().all(|predicate_term| {
        residuals.iter().any(|residual| {
            expressions_match_table_locally(residual, predicate_term, table, table_alias)
        })
    }) && residuals.iter().all(|residual| {
        predicate_terms.iter().any(|predicate_term| {
            expressions_match_table_locally(residual, predicate_term, table, table_alias)
        })
    })
}

fn extract_expression_index_range_bound(
    left: &Expr,
    op: fsqlite_ast::BinaryOp,
    right: &Expr,
    key_expr: &Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<(PlannerIndexRangeSlot, PlannerIndexRangeBound)> {
    use fsqlite_ast::BinaryOp::{Ge, Gt, Le, Lt};

    if expressions_match_table_locally(left, key_expr, table, table_alias)
        && is_index_range_constant(right)
    {
        return match op {
            Ge => Some((
                PlannerIndexRangeSlot::Lower,
                PlannerIndexRangeBound {
                    expr: right.clone(),
                    inclusive: true,
                },
            )),
            Gt => Some((
                PlannerIndexRangeSlot::Lower,
                PlannerIndexRangeBound {
                    expr: right.clone(),
                    inclusive: false,
                },
            )),
            Le => Some((
                PlannerIndexRangeSlot::Upper,
                PlannerIndexRangeBound {
                    expr: right.clone(),
                    inclusive: true,
                },
            )),
            Lt => Some((
                PlannerIndexRangeSlot::Upper,
                PlannerIndexRangeBound {
                    expr: right.clone(),
                    inclusive: false,
                },
            )),
            _ => None,
        };
    }

    if expressions_match_table_locally(right, key_expr, table, table_alias)
        && is_index_range_constant(left)
    {
        return match op {
            Le => Some((
                PlannerIndexRangeSlot::Lower,
                PlannerIndexRangeBound {
                    expr: left.clone(),
                    inclusive: true,
                },
            )),
            Lt => Some((
                PlannerIndexRangeSlot::Lower,
                PlannerIndexRangeBound {
                    expr: left.clone(),
                    inclusive: false,
                },
            )),
            Ge => Some((
                PlannerIndexRangeSlot::Upper,
                PlannerIndexRangeBound {
                    expr: left.clone(),
                    inclusive: true,
                },
            )),
            Gt => Some((
                PlannerIndexRangeSlot::Upper,
                PlannerIndexRangeBound {
                    expr: left.clone(),
                    inclusive: false,
                },
            )),
            _ => None,
        };
    }

    None
}

fn assign_expression_index_range_bound(
    target: &mut PlannerIndexRangeTarget,
    slot: PlannerIndexRangeSlot,
    bound: PlannerIndexRangeBound,
) -> bool {
    let target_slot = match slot {
        PlannerIndexRangeSlot::Lower => &mut target.lower,
        PlannerIndexRangeSlot::Upper => &mut target.upper,
    };
    if target_slot.is_some() {
        false
    } else {
        *target_slot = Some(bound);
        true
    }
}

enum CountIndexedInTarget<'a> {
    List(&'a [Expr]),
    ProbeSource(InProbeSource<'a>),
    MaterializedProbeSource(InProbeSource<'a>),
}

fn extract_count_indexed_in_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &'a TableSchema,
    table_alias: Option<&'a str>,
    schema: &'a [TableSchema],
    scan_ctx: &ScanCtx<'a>,
    index_hint: Option<&fsqlite_ast::IndexHint>,
) -> Option<(&'a IndexSchema, CountIndexedInTarget<'a>)> {
    let expr = where_clause?;
    let Expr::In {
        expr: operand,
        set,
        not: false,
        ..
    } = expr
    else {
        return None;
    };

    let column_name = column_name(operand, table, table_alias)?;
    // Search all indexes so a composite leading-column match cannot shadow a
    // later usable single-column index.  Composite indexes are safe only for
    // the ordered semijoin below: the materialized/list fallback seeks with a
    // two-field `(key, min-rowid)` record, whose physical contract is exactly a
    // single-key index followed by rowid.
    let find_index = |allow_composite: bool| {
        table.indexes.iter().find(|idx| {
            let matches_hint = match index_hint {
                None => true,
                Some(fsqlite_ast::IndexHint::IndexedBy(name)) => {
                    idx.name.eq_ignore_ascii_case(name)
                }
                Some(fsqlite_ast::IndexHint::NotIndexed) => false,
            };
            matches_hint
                && idx.supports_direct_column_lookup()
                && (allow_composite || idx.key_term_count() == 1)
                && !idx.key_term_descending(0)
                && idx
                    .columns
                    .first()
                    .is_some_and(|c| c.eq_ignore_ascii_case(&column_name))
                && collation_names_equivalent(
                    effective_collation_ctx(operand, Some(scan_ctx)),
                    idx.key_term_collation(0),
                )
        })
    };

    match set {
        InSet::List(values)
            if can_use_once_materialized_in_list(values, operand, Some(scan_ctx)) =>
        {
            let idx_schema = find_index(false)?;
            Some((idx_schema, CountIndexedInTarget::List(values)))
        }
        InSet::Subquery(_) => {
            let probe_source = resolve_in_probe_source(set, schema)?;
            if let Some(idx_schema) = find_index(true).filter(|idx_schema| {
                can_use_direct_count_indexed_in_subquery_probe_source(
                    table,
                    idx_schema,
                    &probe_source,
                    operand,
                    scan_ctx,
                )
            }) {
                Some((idx_schema, CountIndexedInTarget::ProbeSource(probe_source)))
            } else {
                let idx_schema = find_index(false)?;
                can_use_once_materialized_in_probe_source(&probe_source, operand, scan_ctx)
                    .then_some((
                        idx_schema,
                        CountIndexedInTarget::MaterializedProbeSource(probe_source),
                    ))
            }
        }
        InSet::Table(_) => {
            let probe_source = resolve_in_probe_source(set, schema)?;
            let idx_schema = find_index(false)?;
            can_use_once_materialized_in_probe_source(&probe_source, operand, scan_ctx).then_some((
                idx_schema,
                CountIndexedInTarget::MaterializedProbeSource(probe_source),
            ))
        }
        InSet::List(_) => None,
    }
}

fn collation_names_equivalent(left: Option<&str>, right: Option<&str>) -> bool {
    let left = match left {
        Some(collation) if !collation.eq_ignore_ascii_case("BINARY") => Some(collation),
        _ => None,
    };
    let right = match right {
        Some(collation) if !collation.eq_ignore_ascii_case("BINARY") => Some(collation),
        _ => None,
    };
    match (left, right) {
        (Some(left), Some(right)) => left.eq_ignore_ascii_case(right),
        (None, None) => true,
        _ => false,
    }
}

fn extract_count_indexed_exists_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &'a TableSchema,
    table_alias: Option<&'a str>,
    schema: &'a [TableSchema],
) -> Option<(&'a IndexSchema, CountIndexedInTarget<'a>)> {
    let expr = where_clause?;
    let Expr::Exists {
        subquery,
        not: false,
        ..
    } = expr
    else {
        return None;
    };
    if subquery.with.is_some()
        || !subquery.body.compounds.is_empty()
        || !subquery.order_by.is_empty()
        || subquery.limit.is_some()
    {
        return None;
    }

    let SelectCore::Select {
        from,
        where_clause: Some(sub_where),
        group_by,
        having,
        windows,
        ..
    } = &subquery.body.select
    else {
        return None;
    };
    if !group_by.is_empty() || having.is_some() || !windows.is_empty() {
        return None;
    }
    let from_clause = from.as_ref()?;
    if !from_clause.joins.is_empty() {
        return None;
    }
    let (sub_table_name, sub_alias) = match &from_clause.source {
        TableOrSubquery::Table { name, alias, .. } => (&name.name, alias.as_deref()),
        _ => return None,
    };
    let sub_table = find_table(schema, sub_table_name).ok()?;
    let (probe_expr, residual_terms) = extract_exists_rowid_probe(sub_where, sub_table, sub_alias)?;
    let outer_column_name = column_name(probe_expr, table, table_alias)?;
    let idx_schema = table.index_for_column(&outer_column_name)?;
    if idx_schema.key_term_count() != 1 || idx_schema.key_term_descending(0) {
        return None;
    }
    // This plan probes the outer index directly with inner rowids and cannot
    // defer to an SQL comparison opcode to apply affinity.  A TEXT/BLOB outer
    // key can compare equal only after numeric affinity while its raw index key
    // occupies a different storage-class range, so retain only the established
    // numeric-storage subset.
    if !count_rowid_probe_index_is_seek_compatible(table, idx_schema) {
        return None;
    }
    if residual_terms
        .iter()
        .any(|term| expr_references_scan(term, table, table_alias))
    {
        return None;
    }
    let residual_where = match residual_terms.as_slice() {
        [] => None,
        [single] => Some(*single),
        _ => return None,
    };
    Some((
        idx_schema,
        CountIndexedInTarget::ProbeSource(InProbeSource {
            table: sub_table,
            table_alias: sub_alias,
            where_clause: residual_where,
            value: InProbeValue::Rowid,
        }),
    ))
}

#[derive(Clone, Copy)]
enum ColumnRangeSlot {
    Lower,
    Upper,
}

fn extract_column_range_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<(String, ColumnRangeTarget<'a>)> {
    let expr = where_clause?;
    let mut column_name = None;
    let mut target = ColumnRangeTarget::default();
    if collect_column_range_bounds(expr, table, table_alias, &mut column_name, &mut target)
        && (target.lower.is_some() || target.upper.is_some())
    {
        column_name.map(|col| (col, target))
    } else {
        None
    }
}

/// Extract the range bounds on a specific named column from the conjuncts of `where_expr`,
/// ignoring every other conjunct — so a composite `a = 5 AND b > 10` yields the `b` range even
/// though `a = 5` is not a range term. Returns `None` if the column has no range term, or a
/// conflicting duplicate bound.
fn extract_named_column_range<'a>(
    where_expr: &'a Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
    column: &str,
) -> Option<ColumnRangeTarget<'a>> {
    let mut conjuncts = Vec::new();
    collect_conjunctive_terms(where_expr, &mut conjuncts);
    let mut target = ColumnRangeTarget::default();
    for term in conjuncts {
        match term {
            Expr::BinaryOp {
                left, op, right, ..
            } => {
                if let Some((col, slot, bound)) =
                    extract_column_range_bound(left, *op, right, table, table_alias)
                    && col.eq_ignore_ascii_case(column)
                {
                    match slot {
                        ColumnRangeSlot::Lower => {
                            if target.lower.is_some() {
                                return None;
                            }
                            target.lower = Some(bound);
                        }
                        ColumnRangeSlot::Upper => {
                            if target.upper.is_some() {
                                return None;
                            }
                            target.upper = Some(bound);
                        }
                    }
                }
            }
            Expr::Between {
                expr: operand,
                low,
                high,
                not: false,
                ..
            } if is_index_range_constant(low)
                && is_index_range_constant(high)
                && column_name(operand, table, table_alias)
                    .is_some_and(|c| c.eq_ignore_ascii_case(column)) =>
            {
                if target.lower.is_some() || target.upper.is_some() {
                    return None;
                }
                target.lower = Some(borrowed_column_range_bound(low, true));
                target.upper = Some(borrowed_column_range_bound(high, true));
            }
            _ => {}
        }
    }
    (target.lower.is_some() || target.upper.is_some()).then_some(target)
}

/// A composite-index seek target: an equality prefix on the leading key columns plus a range on
/// the next key column (`WHERE a = 5 AND b > 10` on `index(a, b)`).
struct CompositePrefixRange<'a> {
    index: &'a IndexSchema,
    prefix_exprs: Vec<&'a Expr>,
    range: ColumnRangeTarget<'a>,
}

/// Whether a single WHERE conjunct is fully enforced by the composite prefix+range seek — i.e. it is
/// an equality on one of the pinned prefix columns, or an equality / range comparison (`>`,`>=`,`<`,
/// `<=`) / `BETWEEN` on the range column. The seek applies NO residual filter, so any conjunct that is
/// none of these (e.g. `c = 1` on a non-key column, or a second, unpinnable predicate) would be
/// silently dropped; the caller declines then, letting the full scan enforce the whole WHERE.
fn conjunct_pins_prefix_or_range(
    term: &Expr,
    index: &IndexSchema,
    range_pos: usize,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    if index.columns[..range_pos]
        .iter()
        .any(|pcol| extract_index_column_equality_expr(term, table, table_alias, pcol).is_some())
    {
        return true;
    }
    let range_col = &index.columns[range_pos];
    // Equality on the range column covers the demoted full-eq case (last column's `=` → degenerate range).
    if extract_index_column_equality_expr(term, table, table_alias, range_col).is_some() {
        return true;
    }
    match term {
        Expr::BinaryOp {
            left, op, right, ..
        } => extract_column_range_bound(left, *op, right, table, table_alias)
            .is_some_and(|(col, _, _)| col.eq_ignore_ascii_case(range_col)),
        Expr::Between {
            expr, not: false, ..
        } => {
            column_name(expr, table, table_alias).is_some_and(|c| c.eq_ignore_ascii_case(range_col))
        }
        _ => false,
    }
}

/// Detect a composite-index equality-prefix + trailing-range seek. Requires a plain ascending
/// composite index whose leading columns are all pinned by `= <lit/param>` conjuncts and whose
/// next column has a range; the prefix and range bounds must be seek-safe (same affinity/collation
/// gate as the single-column range seek). Declines WITHOUT ROWID (PK-suffix probe not handled here).
fn composite_index_prefix_range_target<'a>(
    where_clause: Option<&'a Expr>,
    table: &'a TableSchema,
    table_alias: Option<&str>,
    schema: &[TableSchema],
    required_index: Option<&str>,
) -> Option<CompositePrefixRange<'a>> {
    if table.without_rowid {
        return None;
    }
    let where_expr = where_clause?;
    for index in &table.indexes {
        // GH #291: an `INDEXED BY` hint pins the candidate set to the named
        // index (SQLite name resolution is case-insensitive).
        if required_index.is_some_and(|name| !index.name.eq_ignore_ascii_case(name)) {
            continue;
        }
        let key_terms = index.key_term_count();
        if key_terms < 2
            || index.columns.len() != key_terms
            || (0..key_terms).any(|i| index.key_term_descending(i))
        {
            continue;
        }
        let prefix_exprs =
            extract_index_equality_prefix_exprs(index, table, table_alias, where_clause);
        // An EMPTY equality prefix is a PURE range on the LEADING key term
        // (`WHERE a <range>` on `index(a, …)`) — no equality pins. The `else`
        // branch below then extracts the range on `columns[0]` (declining if the
        // WHERE has no range on the leading term), and the residual guard rejects
        // any unpinnable conjunct. This is the composite-index analogue of the
        // single-column range fast path (bd-bn45n): without it a pure leading
        // range over a composite-only index falls all the way back to a full
        // table scan. ORDER BY is auto-declined for this shape
        // (`composite_order_by_satisfied` requires the range on the LAST key
        // term, so a leading-term range on a >=2-term index never elides the
        // sorter), so the empty-prefix seek only serves the no-ORDER-BY case and
        // any ORDER BY correctly falls to the sorter.
        // When the prefix pins EVERY key column (`WHERE a=? AND b=?` on `(a,b)` — a full composite
        // equality / point lookup), demote the last pinned column to a degenerate range `[c, c]` so the
        // same prefix+range seek resolves it as one seek instead of a full scan.
        let (prefix_exprs, range_pos, range) = if prefix_exprs.len() == key_terms {
            // Safe to demote ONLY when the WHERE is EXACTLY these key-column equalities: the seek
            // applies no residual filter, so a leftover predicate (e.g. a non-key column, as in
            // `a=? AND b=? AND z=?` matched against a shorter `(a,b)` index) would be silently dropped.
            // Requiring one conjunct per key term declines the short index and lets a fuller index win.
            let mut conjuncts = Vec::new();
            collect_conjunctive_terms(where_expr, &mut conjuncts);
            if conjuncts.len() != key_terms {
                continue;
            }
            let mut prefix = prefix_exprs;
            let last = prefix.pop().expect("prefix is non-empty");
            let range = ColumnRangeTarget {
                lower: Some(borrowed_column_range_bound(last, true)),
                upper: Some(borrowed_column_range_bound(last, true)),
            };
            (prefix, key_terms - 1, range)
        } else {
            let range_column = &index.columns[prefix_exprs.len()];
            let Some(range) =
                extract_named_column_range(where_expr, table, table_alias, range_column)
            else {
                continue;
            };
            let pos = prefix_exprs.len();
            (prefix_exprs, pos, range)
        };
        // bd-agg-range-shadowed-index: a PURE leading-term range (empty equality prefix, so
        // `range_pos == 0`) is fully served by a NARROWER single-column ascending index on that
        // leading column, if one is declared — prefer it (the single-column range planner opens
        // `idx_col`; SQLite likewise picks the narrower index). Only decline for the empty-prefix
        // case: with an equality prefix the composite is required (a single-column index cannot pin
        // `a=? AND b<range`). Mirrors the single-column range planner's usability test verbatim, so we
        // never decline into a full table scan when the single-column index is unusable (desc/collation).
        if range_pos == 0
            && table.indexes.iter().any(|other| {
                other.supports_direct_column_lookup()
                    && other.key_term_count() == 1
                    && !other.key_term_descending(0)
                    && other
                        .columns
                        .first()
                        .is_some_and(|c| c.eq_ignore_ascii_case(&index.columns[0]))
            })
        {
            continue;
        }
        // Residual guard: the seek enforces only the pinned prefix equalities and the range on
        // `columns[range_pos]`. If ANY conjunct is not one of those (a predicate on a non-key column,
        // or a second unpinnable term), decline so the full scan enforces the whole WHERE — otherwise
        // that predicate is silently dropped and wrong rows are returned. (bd-zqkrp residual bug.)
        let mut all_conjuncts = Vec::new();
        collect_conjunctive_terms(where_expr, &mut all_conjuncts);
        if !all_conjuncts
            .iter()
            .all(|term| conjunct_pins_prefix_or_range(term, index, range_pos, table, table_alias))
        {
            continue;
        }
        let range_column = &index.columns[range_pos];
        if !index_range_fast_path_is_safe(table, table_alias, schema, range_column, &range) {
            continue;
        }
        let prefix_ok = index.columns[..range_pos]
            .iter()
            .zip(prefix_exprs.iter())
            .all(|(col, expr)| {
                index_range_bound_is_seek_safe(table, table_alias, schema, col, expr)
            });
        if !prefix_ok {
            continue;
        }
        return Some(CompositePrefixRange {
            index,
            prefix_exprs,
            range,
        });
    }
    None
}

/// Whether an index-range seek that streams in `(range_col, rowid)` order satisfies `order_by`
/// bit-identically (ascending). Two forms qualify. First, `ORDER BY range_col, <rowid/ipk>` is a
/// unique total order every plan agrees on, so it is always safe. Second, a bare `ORDER BY
/// range_col` qualifies only when the index is UNIQUE: a unique index has no ties within the range
/// (each `range_col` value occurs once, and the range excludes NULLs), so ordering by `range_col`
/// alone is already a total order and is bit-identical to every plan. A bare `ORDER BY range_col`
/// on a NON-unique index is tie-ambiguous (a different plan may order equal-`range_col` rows
/// differently) and is left to the sorter; DESC/NULLS clauses decline. Shared by the single-column
/// and composite range seeks (both stream `(range_col, rowid)` when `range_col` is the last key
/// term).
fn range_order_by_is_deterministic(
    range_col: &str,
    order_by: &[OrderingTerm],
    table: &TableSchema,
    table_alias: Option<&str>,
    index_is_unique: bool,
    descending: bool,
) -> bool {
    // Every term must sort in the walk's direction (ascending seek: no DESC; reverse seek: all DESC)
    // with no NULLS clause.
    let dir_ok = |term: &OrderingTerm| {
        term.nulls.is_none() && matches!(term.direction, Some(SortDirection::Desc)) == descending
    };
    let is_range_col = |term: &OrderingTerm| {
        dir_ok(term)
            && matches!(
                resolve_column_ref(&term.expr, table, table_alias),
                Some(SortKeySource::Column(idx))
                    if table.columns.get(idx).is_some_and(|c| c.name.eq_ignore_ascii_case(range_col))
            )
    };
    let is_rowid = |term: &OrderingTerm| {
        dir_ok(term)
            && matches!(
                resolve_column_ref(&term.expr, table, table_alias),
                Some(SortKeySource::Rowid)
            )
    };
    match order_by {
        [t0] => index_is_unique && is_range_col(t0),
        [t0, t1] => is_range_col(t0) && is_rowid(t1),
        _ => false,
    }
}

/// Count leading ORDER BY terms that merely repeat equality-constrained
/// leading index columns.
///
/// Only direct column references in exact index-prefix order qualify.  A
/// COLLATE wrapper, explicit NULLS ordering, qualifier from another query
/// scope, or collation mismatch stops consumption.  Direction is intentionally
/// ignored: every qualifying row has the same value under the same collation,
/// so ASC versus DESC cannot change their order.
fn fixed_order_by_equality_prefix_len(
    index: &IndexSchema,
    equality_prefix_len: usize,
    order_by: &[OrderingTerm],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> usize {
    order_by
        .iter()
        .zip(index.columns.iter().take(equality_prefix_len))
        .enumerate()
        .take_while(|(key_pos, (term, index_col))| {
            term.nulls.is_none()
                && column_name(&term.expr, table, table_alias)
                    .is_some_and(|order_col| order_col.eq_ignore_ascii_case(index_col))
                && collation_names_equivalent(
                    column_collation(&term.expr, table, table_alias),
                    index.key_term_collation(*key_pos),
                )
        })
        .count()
}

fn composite_order_by_satisfied(
    comp: &CompositePrefixRange<'_>,
    order_by: &[OrderingTerm],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    let prefix_len = comp.prefix_exprs.len();
    let fixed_order_prefix_len =
        fixed_order_by_equality_prefix_len(comp.index, prefix_len, order_by, table, table_alias);
    // The range column must be the LAST key term so the seek's stream is exactly `(range_col, rowid)`.
    prefix_len + 1 == comp.index.key_term_count()
        && range_order_by_is_deterministic(
            &comp.index.columns[prefix_len],
            &order_by[fixed_order_prefix_len..],
            table,
            table_alias,
            comp.index.is_unique,
            false,
        )
}

/// Whether a composite prefix+range seek can satisfy `order_by` in DESCENDING order without a
/// sorter. Same shape as [`composite_order_by_satisfied`] but for the reverse walk: the range
/// column must be the last key term (so the reverse index stream is exactly `(range_col DESC,
/// rowid DESC)`), and the order must be the deterministic `range_col DESC[, id DESC]` — or a bare
/// `range_col DESC` when the index is UNIQUE (no ties within the range).
fn composite_order_by_satisfied_desc(
    comp: &CompositePrefixRange<'_>,
    order_by: &[OrderingTerm],
    table: &TableSchema,
    table_alias: Option<&str>,
) -> bool {
    let prefix_len = comp.prefix_exprs.len();
    let fixed_order_prefix_len =
        fixed_order_by_equality_prefix_len(comp.index, prefix_len, order_by, table, table_alias);
    prefix_len + 1 == comp.index.key_term_count()
        && range_order_by_is_deterministic(
            &comp.index.columns[prefix_len],
            &order_by[fixed_order_prefix_len..],
            table,
            table_alias,
            comp.index.is_unique,
            true,
        )
}

fn borrowed_column_range_bound(expr: &Expr, inclusive: bool) -> ColumnRangeBound<'_> {
    ColumnRangeBound {
        expr: ColumnRangeExpr::Borrowed(expr),
        inclusive,
    }
}

fn owned_string_column_range_bound<'a>(value: String, inclusive: bool) -> ColumnRangeBound<'a> {
    ColumnRangeBound {
        expr: ColumnRangeExpr::Owned(Box::new(Expr::Literal(Literal::String(value), Span::ZERO))),
        inclusive,
    }
}

fn extract_pure_glob_prefix(pattern: &Expr) -> Option<String> {
    let Expr::Literal(Literal::String(pattern), _) = pattern else {
        return None;
    };

    let mut prefix = String::new();
    let mut saw_trailing_star = false;
    for ch in pattern.chars() {
        match ch {
            '*' => saw_trailing_star = true,
            '?' | '[' => return None,
            _ if saw_trailing_star => return None,
            _ => prefix.push(ch),
        }
    }

    (!prefix.is_empty() && saw_trailing_star).then_some(prefix)
}

fn extract_pure_like_prefix(pattern: &Expr, escape: Option<&Expr>) -> Option<String> {
    let escape_char = match escape {
        None => None,
        Some(Expr::Literal(Literal::String(s), _)) => {
            let mut chars = s.chars();
            let ch = chars.next()?;
            if chars.next().is_some() {
                return None;
            }
            Some(ch)
        }
        Some(_) => return None,
    };

    let Expr::Literal(Literal::String(pattern), _) = pattern else {
        return None;
    };

    let mut prefix = String::new();
    let mut saw_trailing_percent = false;
    let mut chars = pattern.chars();
    while let Some(ch) = chars.next() {
        if escape_char.is_some_and(|esc| esc == ch) {
            if saw_trailing_percent {
                return None;
            }
            prefix.push(chars.next()?);
            continue;
        }
        match ch {
            '%' => saw_trailing_percent = true,
            '_' => return None,
            _ if saw_trailing_percent => return None,
            _ => prefix.push(ch),
        }
    }

    (!prefix.is_empty() && saw_trailing_percent).then_some(prefix)
}

fn is_case_stable_like_prefix(prefix: &str) -> bool {
    prefix.chars().all(|ch| !ch.is_ascii_alphabetic())
}

fn prefix_upper_bound(prefix: &str) -> Option<String> {
    let mut chars: Vec<char> = prefix.chars().collect();
    for idx in (0..chars.len()).rev() {
        let codepoint = u32::from(chars[idx]);
        if codepoint == u32::from(char::MAX) {
            continue;
        }
        if let Some(next) = char::from_u32(codepoint + 1) {
            chars[idx] = next;
            chars.truncate(idx + 1);
            return Some(chars.into_iter().collect());
        }
    }
    None
}

fn extract_like_glob_prefix_range<'a>(
    operand: &'a Expr,
    pattern: &'a Expr,
    op: fsqlite_ast::LikeOp,
    escape: Option<&'a Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<(String, ColumnRangeBound<'a>, ColumnRangeBound<'a>)> {
    let column_name = column_name(operand, table, table_alias)?;
    let prefix = match op {
        fsqlite_ast::LikeOp::Glob if use_builtin_like_glob_semantics() => {
            extract_pure_glob_prefix(pattern)
        }
        fsqlite_ast::LikeOp::Like if use_builtin_like_glob_semantics() => {
            extract_pure_like_prefix(pattern, escape)
                .filter(|prefix| is_case_stable_like_prefix(prefix))
        }
        fsqlite_ast::LikeOp::Glob
        | fsqlite_ast::LikeOp::Like
        | fsqlite_ast::LikeOp::Match
        | fsqlite_ast::LikeOp::Regexp => None,
    }?;
    let upper_bound = prefix_upper_bound(&prefix)?;
    Some((
        column_name,
        owned_string_column_range_bound(prefix, true),
        owned_string_column_range_bound(upper_bound, false),
    ))
}

fn collect_column_range_bounds<'a>(
    expr: &'a Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
    target_column: &mut Option<String>,
    target: &mut ColumnRangeTarget<'a>,
) -> bool {
    match expr {
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::And,
            right,
            ..
        } => {
            collect_column_range_bounds(left, table, table_alias, target_column, target)
                && collect_column_range_bounds(right, table, table_alias, target_column, target)
        }
        Expr::BinaryOp {
            left, op, right, ..
        } => extract_column_range_bound(left, *op, right, table, table_alias).is_some_and(
            |(column_name, slot, bound)| {
                assign_column_range_bound(target_column, target, column_name, slot, bound)
            },
        ),
        Expr::Between {
            expr: operand,
            low,
            high,
            not: false,
            ..
        } if is_index_range_constant(low) && is_index_range_constant(high) => {
            column_name(operand, table, table_alias).is_some_and(|column_name| {
                assign_column_range_bound(
                    target_column,
                    target,
                    column_name.clone(),
                    ColumnRangeSlot::Lower,
                    borrowed_column_range_bound(low, true),
                ) && assign_column_range_bound(
                    target_column,
                    target,
                    column_name,
                    ColumnRangeSlot::Upper,
                    borrowed_column_range_bound(high, true),
                )
            })
        }
        Expr::Like {
            expr: operand,
            pattern,
            op,
            not: false,
            escape,
            ..
        } => extract_like_glob_prefix_range(
            operand,
            pattern,
            *op,
            escape.as_deref(),
            table,
            table_alias,
        )
        .is_some_and(|(column_name, lower, upper)| {
            assign_column_range_bound(
                target_column,
                target,
                column_name.clone(),
                ColumnRangeSlot::Lower,
                lower,
            ) && assign_column_range_bound(
                target_column,
                target,
                column_name,
                ColumnRangeSlot::Upper,
                upper,
            )
        }),
        _ => false,
    }
}

fn extract_column_range_bound<'a>(
    left: &'a Expr,
    op: fsqlite_ast::BinaryOp,
    right: &'a Expr,
    table: &TableSchema,
    table_alias: Option<&str>,
) -> Option<(String, ColumnRangeSlot, ColumnRangeBound<'a>)> {
    if let Some(column_name) = column_name(left, table, table_alias)
        && is_index_range_constant(right)
    {
        return match op {
            fsqlite_ast::BinaryOp::Ge => Some((
                column_name,
                ColumnRangeSlot::Lower,
                borrowed_column_range_bound(right, true),
            )),
            fsqlite_ast::BinaryOp::Gt => Some((
                column_name,
                ColumnRangeSlot::Lower,
                borrowed_column_range_bound(right, false),
            )),
            fsqlite_ast::BinaryOp::Le => Some((
                column_name,
                ColumnRangeSlot::Upper,
                borrowed_column_range_bound(right, true),
            )),
            fsqlite_ast::BinaryOp::Lt => Some((
                column_name,
                ColumnRangeSlot::Upper,
                borrowed_column_range_bound(right, false),
            )),
            _ => None,
        };
    }

    if let Some(column_name) = column_name(right, table, table_alias)
        && is_index_range_constant(left)
    {
        return match op {
            fsqlite_ast::BinaryOp::Le => Some((
                column_name,
                ColumnRangeSlot::Lower,
                borrowed_column_range_bound(left, true),
            )),
            fsqlite_ast::BinaryOp::Lt => Some((
                column_name,
                ColumnRangeSlot::Lower,
                borrowed_column_range_bound(left, false),
            )),
            fsqlite_ast::BinaryOp::Ge => Some((
                column_name,
                ColumnRangeSlot::Upper,
                borrowed_column_range_bound(left, true),
            )),
            fsqlite_ast::BinaryOp::Gt => Some((
                column_name,
                ColumnRangeSlot::Upper,
                borrowed_column_range_bound(left, false),
            )),
            _ => None,
        };
    }

    None
}

fn assign_column_range_bound<'a>(
    target_column: &mut Option<String>,
    target: &mut ColumnRangeTarget<'a>,
    column_name: String,
    slot: ColumnRangeSlot,
    bound: ColumnRangeBound<'a>,
) -> bool {
    if let Some(existing) = target_column.as_deref() {
        if !existing.eq_ignore_ascii_case(&column_name) {
            return false;
        }
    } else {
        *target_column = Some(column_name);
    }

    let target_slot = match slot {
        ColumnRangeSlot::Lower => &mut target.lower,
        ColumnRangeSlot::Upper => &mut target.upper,
    };
    if target_slot.is_some() {
        false
    } else {
        *target_slot = Some(bound);
        true
    }
}

/// Extract a column name from an expression if it's a simple column reference.
#[allow(dead_code)]
fn column_name(expr: &Expr, table: &TableSchema, table_alias: Option<&str>) -> Option<String> {
    if let Expr::Column(col_ref, _) = expr {
        if let Some(qualifier) = &col_ref.table
            && !matches_table_or_alias(qualifier, table, table_alias)
        {
            return None;
        }
        if !is_rowid_ref(col_ref, Some(table), table_alias) {
            return Some(col_ref.column.to_string());
        }
    }
    None
}

/// Check if an expression is a rowid reference.
fn is_rowid_expr(expr: &Expr, table: Option<&TableSchema>, table_alias: Option<&str>) -> bool {
    if let Expr::Column(col_ref, _) = expr {
        if is_rowid_ref(col_ref, table, table_alias) {
            return true;
        }
        if let Some(t) = table {
            if let Some(qualifier) = &col_ref.table
                && !matches_table_or_alias(qualifier, t, table_alias)
            {
                return false;
            }
            for col in &t.columns {
                if col.is_ipk && col.name.eq_ignore_ascii_case(&col_ref.column) {
                    return true;
                }
            }
        }
    }
    false
}

fn is_rowid_ref(
    col_ref: &ColumnRef,
    table: Option<&TableSchema>,
    table_alias: Option<&str>,
) -> bool {
    if let Some(t) = table {
        if let Some(qualifier) = &col_ref.table
            && !matches_table_or_alias(qualifier, t, table_alias)
        {
            return false;
        }
        if let Some(col_idx) = t.column_index(&col_ref.column) {
            return t.columns[col_idx].is_ipk;
        }
        return t.resolves_to_hidden_rowid(&col_ref.column);
    }
    is_hidden_rowid_alias_name(&col_ref.column)
}

/// Extract a bind parameter index from a `?` or `?NNN` placeholder.
#[allow(dead_code)]
fn bind_param_index(expr: &Expr) -> Option<i32> {
    if let Expr::Placeholder(pt, _) = expr {
        match pt {
            fsqlite_ast::PlaceholderType::Anonymous => Some(1),
            fsqlite_ast::PlaceholderType::Numbered(n) =>
            {
                #[allow(clippy::cast_possible_wrap)]
                Some(*n as i32)
            }
            _ => None,
        }
    } else {
        None
    }
}

/// Emit an expression value into a register.
///
/// For bind parameters, emits a Variable instruction.
/// Emit bytecode for an expression, placing the result in `reg`.
///
/// Cursor context for expression emission inside table scans.
///
/// When present, allows `emit_expr` to resolve `Expr::Column` references
/// by emitting `Opcode::Column` against the given cursor.
struct ScanCtx<'a> {
    cursor: i32,
    table: &'a TableSchema,
    table_alias: Option<&'a str>,
    schema: Option<&'a [TableSchema]>,
    /// When set, column references are resolved by copying from registers
    /// (`register_base + col_index`) instead of reading from the B-tree cursor.
    /// Used for generated column expression evaluation during INSERT.
    register_base: Option<i32>,
    /// Secondary table contexts for UPDATE ... FROM multi-table resolution.
    ///
    /// A single-table `UPDATE ... FROM src` carries one entry; a multi-source
    /// `UPDATE ... FROM a JOIN b` / `FROM a, b` carries one entry per FROM
    /// source. Column references are resolved against the primary (target)
    /// table first, then each secondary in order.
    secondaries: &'a [SecondaryScan<'a>],
}

/// Secondary table scan context for UPDATE ... FROM (and the register-backed
/// `excluded.*` pseudo-table threaded into UPSERT DO UPDATE subquery
/// correlation).
struct SecondaryScan<'a> {
    cursor: i32,
    table: &'a TableSchema,
    table_alias: Option<&'a str>,
    /// When set, a qualified reference to this secondary resolves by copying
    /// from `register_base + col_index` instead of reading the B-tree cursor.
    /// Used for the UPSERT `excluded.*` pseudo-row, whose attempted-insert
    /// values live in registers (`val_regs`), not on a cursor (bd-xjfrt).
    register_base: Option<i32>,
}

fn literal_integer_value(expr: &Expr) -> Option<i64> {
    match expr {
        Expr::Literal(Literal::Integer(value), _) => Some(*value),
        _ => None,
    }
}

fn try_emit_column_substr_prefix(
    b: &mut ProgramBuilder,
    name: &str,
    arg_list: &[Expr],
    reg: i32,
    ctx: &ScanCtx<'_>,
) -> bool {
    if !(name.eq_ignore_ascii_case("substr") || name.eq_ignore_ascii_case("substring"))
        || arg_list.len() != 3
        || ctx.register_base.is_some()
        || !use_builtin_scalar_implementation_for_codegen(name, 3)
    {
        return false;
    }

    let Expr::Column(col_ref, _) = &arg_list[0] else {
        return false;
    };
    let Some(col_idx) = resolve_column_in_ctx(col_ref, ctx) else {
        return false;
    };
    if ctx.table.columns.get(col_idx).is_some_and(|col| col.is_ipk)
        || literal_integer_value(&arg_list[1]) != Some(1)
    {
        return false;
    }
    let Some(prefix_len) = literal_integer_value(&arg_list[2]) else {
        return false;
    };
    let Ok(prefix_len) = i32::try_from(prefix_len) else {
        return false;
    };
    if prefix_len < 0 {
        return false;
    }
    let Ok(col_idx) = i32::try_from(col_idx) else {
        return false;
    };

    b.emit_op(
        Opcode::ColumnSubstrPrefix,
        ctx.cursor,
        col_idx,
        reg,
        P4::Int(prefix_len),
        0,
    );
    true
}

fn try_emit_column_octet_length(
    b: &mut ProgramBuilder,
    name: &str,
    arg_list: &[Expr],
    reg: i32,
    ctx: &ScanCtx<'_>,
) -> bool {
    if !name.eq_ignore_ascii_case("octet_length")
        || arg_list.len() != 1
        || ctx.register_base.is_some()
        || !use_builtin_scalar_implementation_for_codegen(name, 1)
    {
        return false;
    }
    let Expr::Column(col_ref, _) = &arg_list[0] else {
        return false;
    };
    let Some(col_idx) = resolve_column_in_ctx(col_ref, ctx) else {
        return false;
    };
    if ctx
        .table
        .columns
        .get(col_idx)
        .is_some_and(|column| column.generated_stored == Some(false))
    {
        return false;
    }
    let Ok(col_idx) = i32::try_from(col_idx) else {
        return false;
    };
    b.emit_op(
        Opcode::ColumnOctetLength,
        ctx.cursor,
        col_idx,
        reg,
        P4::None,
        0,
    );
    true
}

enum InProbeValue<'a> {
    Expr(&'a Expr),
    FirstColumn,
    Rowid,
}

struct InProbeSource<'a> {
    table: &'a TableSchema,
    table_alias: Option<&'a str>,
    where_clause: Option<&'a Expr>,
    value: InProbeValue<'a>,
}

#[derive(Clone, Copy)]
struct ScalarInOperandMetadata {
    affinity: u8,
}

/// Recognize a scalar-subquery IN operand that native codegen can evaluate
/// once, after materializing the uncorrelated RHS.
///
/// Keep this deliberately narrower than the general scalar-subquery emitter:
/// one plain SELECT, one output value, no ordering/cardinality modifiers, and
/// no reference outside the scalar SELECT's own optional single-table scope.
/// Function calls are excluded because codegen cannot distinguish a custom
/// aggregate from a scalar override here.
fn scalar_in_operand_metadata(
    operand: &Expr,
    schema: &[TableSchema],
) -> Option<ScalarInOperandMetadata> {
    let Expr::Subquery(select, _) = operand else {
        return None;
    };
    if select.with.is_some()
        || !select.body.compounds.is_empty()
        || !select.order_by.is_empty()
        || select.limit.is_some()
    {
        return None;
    }
    let SelectCore::Select {
        columns,
        from,
        where_clause,
        group_by,
        having,
        windows,
        ..
    } = &select.body.select
    else {
        return None;
    };
    if !group_by.is_empty()
        || having.is_some()
        || !windows.is_empty()
        || has_aggregate_columns(columns)
        || has_window_columns(columns)
        || columns.iter().any(|column| {
            matches!(
                column,
                ResultColumn::Expr { expr, .. }
                    if in_probe_expr_requires_semantic_fallback(expr)
                        || expr_contains_function_call(expr)
            )
        })
        || where_clause.as_deref().is_some_and(|expr| {
            in_probe_expr_requires_semantic_fallback(expr)
                || expr_contains_function_call(expr)
                || is_aggregate_expr(expr)
                || expr_has_window(expr)
        })
    {
        return None;
    }

    let Some(from_clause) = from.as_ref() else {
        if where_clause.is_some() {
            return None;
        }
        let [ResultColumn::Expr { expr, .. }] = columns.as_slice() else {
            return None;
        };
        let has_column = validate_expr_columns_with(expr, &|column| {
            Err(CodegenError::ColumnNotFound {
                table: String::new(),
                column: column.column.to_string(),
            })
        })
        .is_err();
        return (!has_column).then_some(ScalarInOperandMetadata {
            affinity: expr_affinity(expr, None),
        });
    };

    if !from_clause.joins.is_empty() {
        return None;
    }
    let (qualified_table_name, table_alias) = match &from_clause.source {
        TableOrSubquery::Table {
            name,
            alias,
            index_hint: None,
            time_travel: None,
        } => (name, alias.as_deref()),
        _ => return None,
    };
    if qualified_table_name.schema.is_some() {
        return None;
    }
    let table = find_table(schema, &qualified_table_name.name).ok()?;
    if validate_single_table_result_columns(columns, table, table_alias, None).is_err()
        || where_clause.as_deref().is_some_and(|expr| {
            validate_single_table_expr_columns(expr, table, table_alias).is_err()
        })
    {
        return None;
    }

    let scalar_scan = ScanCtx {
        cursor: 0,
        table,
        table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    let affinity = match columns.as_slice() {
        [ResultColumn::Expr { expr, .. }] => {
            let resolved = resolve_column_ref(expr, table, table_alias);
            resolved_expr_affinity(expr, resolved.as_ref(), &scalar_scan)
        }
        [ResultColumn::Star | ResultColumn::TableStar(_)] if table.columns.len() == 1 => table
            .columns
            .first()
            .map_or(b'A', schema_column_expr_affinity),
        _ => return None,
    };
    Some(ScalarInOperandMetadata { affinity })
}

fn emit_in_probe_value(
    b: &mut ProgramBuilder,
    source_cursor: i32,
    probe_source: &InProbeSource<'_>,
    reg: i32,
    probe_scan: &ScanCtx<'_>,
) {
    match probe_source.value {
        InProbeValue::Expr(expr) => emit_expr(b, expr, reg, Some(probe_scan)),
        InProbeValue::FirstColumn => {
            // A one-column `SELECT *` still needs the centralized table-read
            // semantics: an INTEGER PRIMARY KEY is stored as the rowid rather
            // than in record column 0, and a VIRTUAL generated column must be
            // computed instead of reading its NULL storage placeholder.
            if let Some(source_base) = probe_scan.register_base {
                emit_table_column_read_from_register_row(
                    b,
                    probe_source.table,
                    probe_source.table_alias,
                    probe_scan.schema,
                    source_base,
                    0,
                    reg,
                );
            } else {
                emit_table_column_read(
                    b,
                    source_cursor,
                    probe_source.table,
                    probe_source.table_alias,
                    probe_scan.schema,
                    0,
                    reg,
                );
            }
        }
        InProbeValue::Rowid => {
            b.emit_op(Opcode::Rowid, source_cursor, reg, 0, P4::None, 0);
        }
    }
}

fn in_probe_value_explicit_collation(probe_source: &InProbeSource<'_>) -> Option<String> {
    match probe_source.value {
        InProbeValue::Expr(expr) => extract_collation(expr).map(str::to_owned),
        InProbeValue::FirstColumn | InProbeValue::Rowid => None,
    }
}

fn in_probe_value_effective_collation(
    probe_source: &InProbeSource<'_>,
    probe_scan: &ScanCtx<'_>,
) -> Option<String> {
    match probe_source.value {
        InProbeValue::Rowid => None,
        InProbeValue::FirstColumn => probe_source
            .table
            .columns
            .first()
            .and_then(|column| column.collation.clone()),
        InProbeValue::Expr(expr) => {
            effective_collation_ctx(expr, Some(probe_scan)).map(str::to_owned)
        }
    }
}

fn in_probe_value_affinity(probe_source: &InProbeSource<'_>, probe_scan: &ScanCtx<'_>) -> u8 {
    match probe_source.value {
        InProbeValue::Rowid => b'D',
        InProbeValue::FirstColumn => probe_source
            .table
            .columns
            .first()
            .map_or(b'A', schema_column_expr_affinity),
        InProbeValue::Expr(expr) => expr_affinity(expr, Some(probe_scan)),
    }
}

/// Resolve the collation for `lhs IN (SELECT rhs ...)` with SQLite's
/// comparison precedence: explicit COLLATE on either side (left wins a tie),
/// then a declared column collation (again left before right).
fn in_probe_comparison_collation(
    operand: &Expr,
    operand_ctx: &ScanCtx<'_>,
    probe_source: &InProbeSource<'_>,
    probe_scan: &ScanCtx<'_>,
) -> Option<String> {
    extract_collation(operand)
        .map(str::to_owned)
        .or_else(|| in_probe_value_explicit_collation(probe_source))
        .or_else(|| effective_collation_ctx(operand, Some(operand_ctx)).map(str::to_owned))
        .or_else(|| in_probe_value_effective_collation(probe_source, probe_scan))
}

fn probe_source_value_is_unique(probe_source: &InProbeSource<'_>) -> bool {
    match probe_source.value {
        InProbeValue::Rowid => true,
        InProbeValue::FirstColumn => probe_source.table.columns.first().is_some_and(|column| {
            column.is_ipk
                || column.unique
                || probe_source
                    .table
                    .index_for_column(&column.name)
                    .is_some_and(|idx| idx.is_unique && idx.key_term_count() == 1)
        }),
        InProbeValue::Expr(expr) => {
            let Expr::Column(col_ref, _) = expr else {
                return false;
            };
            if is_rowid_ref(col_ref, Some(probe_source.table), probe_source.table_alias) {
                return true;
            }
            probe_source
                .table
                .column_index(&col_ref.column)
                .and_then(|idx| probe_source.table.columns.get(idx))
                .is_some_and(|column| {
                    column.is_ipk
                        || column.unique
                        || probe_source
                            .table
                            .index_for_column(&column.name)
                            .is_some_and(|idx| idx.is_unique && idx.key_term_count() == 1)
                })
        }
    }
}

fn count_probe_source_can_skip_materialization(probe_source: &InProbeSource<'_>) -> bool {
    probe_source_value_is_unique(probe_source)
}

fn can_use_direct_count_indexed_in_subquery_probe_source(
    table: &TableSchema,
    idx_schema: &IndexSchema,
    probe_source: &InProbeSource<'_>,
    operand: &Expr,
    scan_ctx: &ScanCtx<'_>,
) -> bool {
    matches!(probe_source.value, InProbeValue::Rowid)
        && can_use_once_materialized_in_probe_source(probe_source, operand, scan_ctx)
        && count_probe_source_can_skip_materialization(probe_source)
        && count_exists_semijoin_merge_is_safe(table, idx_schema, probe_source)
}

/// Whether generic expression lowering would silently lose semantics needed by
/// an IN-subquery probe.
///
/// `emit_expr` does not lower row values or RAISE, and its scalar-function arm
/// deliberately ignores aggregate-only FILTER / in-call ORDER BY modifiers.
/// Nested SELECT scopes are also outside these single-table probe helpers.
/// Decline all of those shapes so connection-level semantic evaluation can
/// either execute them correctly or report SQLite's preparation error.
fn in_probe_expr_requires_semantic_fallback(expr: &Expr) -> bool {
    match expr {
        Expr::RowValue(..) | Expr::Raise { .. } | Expr::Exists { .. } | Expr::Subquery(..) => true,
        Expr::BinaryOp { left, right, .. }
        | Expr::JsonAccess {
            expr: left,
            path: right,
            ..
        } => {
            in_probe_expr_requires_semantic_fallback(left)
                || in_probe_expr_requires_semantic_fallback(right)
        }
        Expr::UnaryOp { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. }
        | Expr::IsNull { expr, .. } => in_probe_expr_requires_semantic_fallback(expr),
        Expr::Between {
            expr, low, high, ..
        } => {
            in_probe_expr_requires_semantic_fallback(expr)
                || in_probe_expr_requires_semantic_fallback(low)
                || in_probe_expr_requires_semantic_fallback(high)
        }
        Expr::In { expr, set, .. } => {
            in_probe_expr_requires_semantic_fallback(expr)
                || match set {
                    InSet::List(values) => {
                        values.iter().any(in_probe_expr_requires_semantic_fallback)
                    }
                    InSet::Table(_) | InSet::Subquery(_) => true,
                }
        }
        Expr::Like {
            expr,
            pattern,
            escape,
            ..
        } => {
            in_probe_expr_requires_semantic_fallback(expr)
                || in_probe_expr_requires_semantic_fallback(pattern)
                || escape
                    .as_deref()
                    .is_some_and(in_probe_expr_requires_semantic_fallback)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand
                .as_deref()
                .is_some_and(in_probe_expr_requires_semantic_fallback)
                || whens.iter().any(|(when_expr, then_expr)| {
                    in_probe_expr_requires_semantic_fallback(when_expr)
                        || in_probe_expr_requires_semantic_fallback(then_expr)
                })
                || else_expr
                    .as_deref()
                    .is_some_and(in_probe_expr_requires_semantic_fallback)
        }
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            over,
            ..
        } => {
            !order_by.is_empty()
                || filter.is_some()
                || over.is_some()
                || matches!(
                    args,
                    FunctionArgs::List(values)
                        if values
                            .iter()
                            .any(in_probe_expr_requires_semantic_fallback)
                )
        }
        Expr::Literal(..)
        | Expr::BoundOuterValue { .. }
        | Expr::Column(..)
        | Expr::Placeholder(..) => false,
    }
}

fn in_probe_result_columns_require_semantic_fallback(columns: &[ResultColumn]) -> bool {
    columns.iter().any(|column| {
        matches!(
            column,
            ResultColumn::Expr { expr, .. }
                if in_probe_expr_requires_semantic_fallback(expr)
        )
    })
}

fn resolve_in_probe_source<'a>(
    set: &'a fsqlite_ast::InSet,
    schema: &'a [TableSchema],
) -> Option<InProbeSource<'a>> {
    match set {
        fsqlite_ast::InSet::List(_) => None,
        fsqlite_ast::InSet::Table(name) => {
            if name.schema.is_some() {
                return None;
            }
            let table = find_table(schema, &name.name).ok()?;
            if table.columns.len() != 1 {
                return None;
            }
            Some(InProbeSource {
                table,
                table_alias: None,
                where_clause: None,
                value: InProbeValue::FirstColumn,
            })
        }
        fsqlite_ast::InSet::Subquery(subquery) => {
            if subquery.with.is_some()
                || !subquery.body.compounds.is_empty()
                || !subquery.order_by.is_empty()
                || subquery.limit.is_some()
            {
                return None;
            }

            let fsqlite_ast::SelectCore::Select {
                columns,
                from,
                where_clause,
                group_by,
                having,
                windows,
                ..
            } = &subquery.body.select
            else {
                return None;
            };

            if has_aggregate_columns(columns)
                || has_window_columns(columns)
                || !group_by.is_empty()
                || having.is_some()
                || !windows.is_empty()
                || in_probe_result_columns_require_semantic_fallback(columns)
                || where_clause
                    .as_deref()
                    .is_some_and(in_probe_expr_requires_semantic_fallback)
            {
                return None;
            }

            let from_clause = from.as_ref()?;
            if !from_clause.joins.is_empty() {
                return None;
            }

            let (qualified_table_name, table_alias) = match &from_clause.source {
                fsqlite_ast::TableOrSubquery::Table {
                    name,
                    alias,
                    index_hint: None,
                    time_travel: None,
                } => (name, alias.as_deref()),
                _ => return None,
            };
            if qualified_table_name.schema.is_some() {
                return None;
            }
            let table = find_table(schema, &qualified_table_name.name).ok()?;
            if validate_single_table_result_columns(columns, table, table_alias, None).is_err()
                || where_clause.as_deref().is_some_and(|expr| {
                    validate_single_table_expr_columns(expr, table, table_alias).is_err()
                })
            {
                return None;
            }

            let value = match columns.as_slice() {
                [fsqlite_ast::ResultColumn::Expr { expr, .. }] => {
                    if is_rowid_expr(expr, Some(table), table_alias) {
                        InProbeValue::Rowid
                    } else {
                        InProbeValue::Expr(expr)
                    }
                }
                [fsqlite_ast::ResultColumn::Star | fsqlite_ast::ResultColumn::TableStar(_)] => {
                    if table.columns.len() != 1 {
                        return None;
                    }
                    InProbeValue::FirstColumn
                }
                _ => return None,
            };

            Some(InProbeSource {
                table,
                table_alias,
                where_clause: where_clause.as_deref(),
                value,
            })
        }
    }
}

/// Attempt to emit bytecode for a complex IN subquery with ORDER BY and/or LIMIT.
///
/// Returns `true` if the subquery was handled, `false` if it cannot be handled
/// and must be routed through connection-level semantic evaluation. Direct
/// callers fail closed at the caller rather than synthesizing a SQL value.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::too_many_lines
)]
fn try_emit_complex_in_subquery(
    b: &mut ProgramBuilder,
    operand: &Expr,
    subquery: &SelectStatement,
    not: bool,
    reg: i32,
    scan_ctx: &ScanCtx<'_>,
) -> bool {
    let Some(schema) = scan_ctx.schema else {
        return false;
    };
    let scalar_operand = scalar_in_operand_metadata(operand, schema);
    if in_probe_expr_requires_semantic_fallback(operand) && scalar_operand.is_none() {
        return false;
    }

    // Reject WITH and compound queries.
    if subquery.with.is_some() || !subquery.body.compounds.is_empty() {
        return false;
    }

    let fsqlite_ast::SelectCore::Select {
        distinct,
        columns,
        from,
        where_clause,
        group_by,
        having,
        windows,
        ..
    } = &subquery.body.select
    else {
        return false;
    };

    // Per-row IN probing cannot reproduce aggregate or window-query
    // cardinality. Decline those shapes, including implicit aggregate/window
    // queries without an explicit GROUP BY or named WINDOW clause.
    let where_has_aggregate_or_window = where_clause
        .as_deref()
        .is_some_and(|expr| is_aggregate_expr(expr) || expr_has_window(expr));
    let order_has_aggregate_or_window = subquery
        .order_by
        .iter()
        .any(|term| is_aggregate_expr(&term.expr) || expr_has_window(&term.expr));
    let limit_has_aggregate_or_window = subquery.limit.as_ref().is_some_and(|clause| {
        is_aggregate_expr(&clause.limit)
            || expr_has_window(&clause.limit)
            || clause
                .offset
                .as_ref()
                .is_some_and(|expr| is_aggregate_expr(expr) || expr_has_window(expr))
    });
    if has_aggregate_columns(columns)
        || has_window_columns(columns)
        || where_has_aggregate_or_window
        || order_has_aggregate_or_window
        || limit_has_aggregate_or_window
        || !group_by.is_empty()
        || having.is_some()
        || !windows.is_empty()
        || in_probe_result_columns_require_semantic_fallback(columns)
        || where_clause
            .as_deref()
            .is_some_and(in_probe_expr_requires_semantic_fallback)
        || subquery
            .order_by
            .iter()
            .any(|term| in_probe_expr_requires_semantic_fallback(&term.expr))
        || subquery.limit.as_ref().is_some_and(|clause| {
            in_probe_expr_requires_semantic_fallback(&clause.limit)
                || clause
                    .offset
                    .as_ref()
                    .is_some_and(in_probe_expr_requires_semantic_fallback)
        })
    {
        return false;
    }

    let Some(from_clause) = from.as_ref() else {
        return false;
    };

    // Reject JOINs.
    if !from_clause.joins.is_empty() {
        return false;
    }

    let (qualified_table_name, table_alias) = match &from_clause.source {
        fsqlite_ast::TableOrSubquery::Table {
            name,
            alias,
            index_hint: None,
            time_travel: None,
        } => (name, alias.as_deref()),
        _ => return false,
    };
    if qualified_table_name.schema.is_some() {
        return false;
    }

    let Ok(table) = find_table(schema, &qualified_table_name.name) else {
        return false;
    };

    // WHERE references and aliases nested inside ORDER expressions fall back
    // to a SELECT alias only when no real source column has that name. Exact
    // ORDER aliases/ordinals have output-column precedence and are resolved
    // separately below. Reuse the general rewrite for the former cases so
    // unknown names never degrade into emitted NULL values.
    let where_clause_rewritten = where_clause
        .as_deref()
        .map(|expr| rewrite_having_select_aliases(expr, columns, table));
    let where_clause = where_clause_rewritten.as_ref();
    let order_by_exprs: Vec<Expr> = subquery
        .order_by
        .iter()
        .map(|term| rewrite_having_select_aliases(&term.expr, columns, table))
        .collect();
    if validate_single_table_result_columns(columns, table, table_alias, None).is_err()
        || where_clause.is_some_and(|expr| {
            validate_single_table_expr_columns(expr, table, table_alias).is_err()
        })
        || order_by_exprs
            .iter()
            .any(|expr| validate_single_table_expr_columns(expr, table, table_alias).is_err())
    {
        return false;
    }
    // This helper accepts exactly one output column. Integer ORDER BY terms
    // are ordinals, so anything other than 1 is an out-of-range error rather
    // than a constant sort expression.
    if subquery
        .order_by
        .iter()
        .any(|term| order_by_integer_ordinal(&term.expr).is_some_and(|ordinal| ordinal != 1))
    {
        return false;
    }
    if subquery.limit.as_ref().is_some_and(|clause| {
        let has_unsupported_reference = |expr: &Expr| {
            expr_contains_nested_subquery(expr)
                || validate_expr_columns_with(expr, &|column| {
                    Err(CodegenError::ColumnNotFound {
                        table: table.name.clone(),
                        column: column.column.to_string(),
                    })
                })
                .is_err()
        };
        has_unsupported_reference(&clause.limit)
            || clause
                .offset
                .as_ref()
                .is_some_and(has_unsupported_reference)
    }) {
        return false;
    }

    // Determine the value expression to compare. `SELECT *` is a legal
    // single-column IN source only when the source table itself has one column.
    let value = match columns.as_slice() {
        [fsqlite_ast::ResultColumn::Expr { expr, .. }] => {
            if is_rowid_expr(expr, Some(table), table_alias) {
                InProbeValue::Rowid
            } else {
                InProbeValue::Expr(expr)
            }
        }
        [fsqlite_ast::ResultColumn::Star | fsqlite_ast::ResultColumn::TableStar(_)] => {
            if table.columns.len() != 1 {
                return false;
            }
            InProbeValue::FirstColumn
        }
        _ => return false,
    };
    let has_order_by = !subquery.order_by.is_empty();
    let is_distinct = *distinct == Distinctness::Distinct;

    // The selected RHS is retained for the lifetime of the statement, so each
    // complex IN expression needs its own stable cursor range.
    let cursor_base = b.alloc_aux_cursor_range(4);
    let subq_cursor = cursor_base;
    let sorter_cursor = cursor_base + 1;
    let distinct_cursor = cursor_base + 2;
    let membership_cursor = cursor_base + 3;
    let subq_scan = ScanCtx {
        cursor: subq_cursor,
        table,
        table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    let probe_source = InProbeSource {
        table,
        table_alias,
        where_clause,
        value,
    };

    // Connection-level compilation canonicalizes all parameters to explicit
    // slots. Raw codegen callers cannot safely use emission-order numbering
    // here because LIMIT is intentionally evaluated before WHERE/ORDER BY.
    if expr_contains_non_numbered_placeholder(operand)
        || select_contains_non_numbered_placeholder(subquery)
    {
        return false;
    }

    // This implementation materializes an uncorrelated RHS once per statement.
    // Decline correlated references instead of accidentally resolving them
    // against the RHS table cursor.
    let sort_keys: Vec<SortKeySource> = order_by_exprs
        .iter()
        .zip(subquery.order_by.iter())
        .map(|(resolved_expr, term)| {
            if order_by_refers_to_single_star_output(&term.expr, columns) {
                SortKeySource::Column(0)
            } else if let Some(output_expr) =
                resolve_single_output_order_expr(&term.expr, columns, table, table_alias)
            {
                // Exact output aliases/ordinals win over a same-named source
                // column in ORDER BY. Resolve the projected expression without
                // re-applying SELECT-list alias lookup.
                resolve_sort_key(output_expr, table, table_alias, &[])
            } else {
                resolve_sort_key(resolved_expr, table, table_alias, columns)
            }
        })
        .collect();
    let order_by_references_outer = sort_keys.iter().any(|key| {
        matches!(
            key,
            SortKeySource::Expression(expr)
                if probe_expr_references_outer_scan(expr, &probe_source, scan_ctx)
        )
    });
    let limit_references_outer = subquery.limit.as_ref().is_some_and(|clause| {
        probe_expr_references_outer_scan(&clause.limit, &probe_source, scan_ctx)
            || clause.offset.as_ref().is_some_and(|offset| {
                probe_expr_references_outer_scan(offset, &probe_source, scan_ctx)
            })
    });
    if in_probe_source_references_outer_scan(&probe_source, scan_ctx)
        || order_by_references_outer
        || limit_references_outer
    {
        return false;
    }

    let order_output_slots: Vec<Option<usize>> = subquery
        .order_by
        .iter()
        .map(|term| resolve_order_by_output_slot(&term.expr, columns, table, table_alias))
        .collect();
    let sort_order: String = subquery
        .order_by
        .iter()
        .map(|term| {
            let is_desc = term.direction == Some(SortDirection::Desc);
            let nulls_last = match term.nulls {
                Some(NullsOrder::Last) => true,
                Some(NullsOrder::First) => false,
                None => is_desc,
            };
            match (is_desc, nulls_last) {
                (false, false) => '+',
                (false, true) => '>',
                (true, true) => '-',
                (true, false) => '<',
            }
        })
        .collect();
    let sort_collations: Vec<String> = sort_keys
        .iter()
        .zip(subquery.order_by.iter())
        .enumerate()
        .map(|(index, (key, term))| {
            if let Some(collation) = extract_collation(&term.expr) {
                return collation.to_owned();
            }
            if let Some(output_slot) = order_output_slots[index]
                && let Some(collation) =
                    result_output_slot_collation(output_slot, columns, table, table_alias)
            {
                return collation;
            }
            match key {
                SortKeySource::Column(index) => table
                    .columns
                    .get(*index)
                    .and_then(|column| column.collation.as_deref())
                    .unwrap_or_default()
                    .to_owned(),
                SortKeySource::Expression(expr) => effective_collation_ctx(expr, Some(&subq_scan))
                    .unwrap_or_default()
                    .to_owned(),
                SortKeySource::Rowid => String::new(),
            }
        })
        .collect();
    let distinct_projection_mode = ordered_distinct_projection_mode(
        *distinct,
        &subquery.order_by,
        &order_output_slots,
        &sort_collations,
        columns,
        table,
        table_alias,
    );
    let keep_subq_cursor_open = has_order_by
        && distinct_projection_mode == OrderedDistinctProjectionMode::ReprojectRepresentative
        && !table.without_rowid;

    let probe_aff = in_probe_value_affinity(&probe_source, &subq_scan);
    let operand_affinity = scalar_operand.map_or_else(
        || expr_affinity(operand, Some(scan_ctx)),
        |metadata| metadata.affinity,
    );
    let comparison_affinity = combine_comparison_affinity(operand_affinity, probe_aff);
    let comparison_affinity_string = u8::try_from(comparison_affinity)
        .ok()
        .filter(|&code| code != 0)
        .map(|code| (code as char).to_string());
    let probe_collation = in_probe_value_effective_collation(&probe_source, &subq_scan);
    let comparison_collation =
        in_probe_comparison_collation(operand, scan_ctx, &probe_source, &subq_scan);

    // Reserve the operand register now, but evaluate it only after the
    // uncorrelated RHS has been materialized (SQLite's observable order for
    // volatile functions and errors).
    let r_operand = if scalar_operand.is_some() {
        // The Once-guarded scalar result must survive later result-expression
        // code and subsequent outer rows, so it cannot use the temp pool.
        b.alloc_reg()
    } else {
        b.alloc_temp()
    };

    let matched_label = b.emit_label();
    let null_result_label = b.emit_label();
    let done_label = b.emit_label();

    // Materialize the final RHS membership set exactly once. Besides avoiding
    // an O(outer rows × RHS rows) rebuild, this prevents an uncorrelated RHS
    // from being reevaluated separately for every outer row.
    let r_rhs_nonempty = b.alloc_reg();
    let r_rhs_saw_null = b.alloc_reg();
    let build_done = b.emit_label();
    b.emit_jump_to_label(Opcode::Once, 0, 0, build_done, P4::None, 0);
    b.emit_op(Opcode::Integer, 0, r_rhs_nonempty, 0, P4::None, 0);
    b.emit_op(Opcode::Integer, 0, r_rhs_saw_null, 0, P4::None, 0);
    b.emit_op(
        Opcode::OpenAutoindex,
        membership_cursor,
        1,
        0,
        comparison_collation
            .as_ref()
            .map_or(P4::None, |collation| P4::Collation(collation.clone())),
        0,
    );

    // SQLite validates LIMIT before OFFSET and skips OFFSET evaluation for
    // LIMIT 0. It also performs this validation before opening the RHS table,
    // while applying both counters after WHERE/DISTINCT and after ORDER BY.
    // Keep this inside the Once-guarded build so a reused complex IN expression
    // does not reevaluate a dynamic LIMIT for every outer row.
    let selected_done = b.emit_label();
    let (limit_reg, offset_reg) =
        emit_limit_offset_registers(b, subquery.limit.as_ref(), selected_done);
    let top_n_bound_reg = if has_order_by && limit_clause_can_enable_top_n(subquery.limit.as_ref())
    {
        emit_top_n_bound_register(b, limit_reg, offset_reg)
    } else {
        None
    };

    if has_order_by {
        // Build the same sort metadata as a top-level ordered SELECT.
        let sorter_p4 = if sort_collations
            .iter()
            .any(|collation| !collation.is_empty())
        {
            format!("{sort_order}|{}", sort_collations.join(","))
        } else {
            sort_order
        };
        let num_sort_keys = sort_keys.len();

        b.emit_op(
            Opcode::SorterOpen,
            sorter_cursor,
            num_sort_keys as i32,
            top_n_bound_reg.unwrap_or(0),
            P4::Str(sorter_p4),
            top_n_bound_reg.map_or(0, |_| SORTER_OPEN_TOP_N_REGISTER),
        );
    }

    if is_distinct {
        b.emit_op(
            Opcode::OpenAutoindex,
            distinct_cursor,
            1,
            0,
            probe_collation.map_or(P4::None, |collation| P4::Collation(collation.clone())),
            0,
        );
    }

    b.emit_op(
        Opcode::OpenRead,
        subq_cursor,
        table.root_page,
        0,
        P4::Table(table.name.clone()),
        0,
    );

    if has_order_by {
        // === Pass 1: scan, DISTINCT-filter, and materialize into the sorter. ===
        let scan_start = b.current_addr();
        let scan_done = b.emit_label();
        b.emit_jump_to_label(Opcode::Rewind, subq_cursor, 0, scan_done, P4::None, 0);

        let next_source_row = b.emit_label();
        if let Some(where_expr) = where_clause {
            emit_where_filter(
                b,
                where_expr,
                subq_cursor,
                table,
                table_alias,
                schema,
                next_source_row,
            );
        }

        let num_sort_keys = sort_keys.len();
        let stored_data_cols = if distinct_projection_mode
            == OrderedDistinctProjectionMode::ReprojectRepresentative
            && table.without_rowid
        {
            table.columns.len()
        } else {
            1
        };
        let num_sorter_cols = num_sort_keys + stored_data_cols;
        let sorter_base = b.alloc_regs(num_sorter_cols as i32);
        let stored_data_base = sorter_base + num_sort_keys as i32;
        let value_reg =
            if distinct_projection_mode == OrderedDistinctProjectionMode::ReprojectRepresentative {
                b.alloc_reg()
            } else {
                stored_data_base
            };

        // DISTINCT is defined on the result value, so evaluate and deduplicate
        // it before any ORDER BY-only expressions. A non-DISTINCT top-N query,
        // by contrast, evaluates independent sort keys before the projected
        // value; this preserves the selected value when both are volatile.
        if is_distinct {
            emit_in_probe_value(b, subq_cursor, &probe_source, value_reg, &subq_scan);
            let distinct_record = b.alloc_temp();
            b.emit_op(
                Opcode::MakeRecord,
                value_reg,
                1,
                distinct_record,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::Found,
                distinct_cursor,
                distinct_record,
                next_source_row,
                P4::None,
                0,
            );
            b.emit_op(
                Opcode::IdxInsert,
                distinct_cursor,
                distinct_record,
                0,
                P4::None,
                0,
            );
            b.free_temp(distinct_record);
        }

        let mut value_emitted = is_distinct;
        for (index, (register, key)) in (sorter_base..).zip(sort_keys.iter()).enumerate() {
            let order_uses_output_value = resolve_single_output_order_expr(
                &subquery.order_by[index].expr,
                columns,
                table,
                table_alias,
            )
            .is_some()
                || order_by_refers_to_single_star_output(&subquery.order_by[index].expr, columns);
            if order_uses_output_value {
                if !value_emitted {
                    // Exact output aliases, ordinals, and structurally equal
                    // expressions share the projected value in a
                    // non-DISTINCT ordered SELECT. Evaluate it lazily at this
                    // key's position so earlier independent keys retain
                    // SQLite's observable evaluation order.
                    emit_in_probe_value(b, subq_cursor, &probe_source, value_reg, &subq_scan);
                    value_emitted = true;
                }
                b.emit_op(Opcode::Copy, value_reg, register, 0, P4::None, 0);
            } else {
                emit_resolved_column(b, key, subq_cursor, register, &subq_scan);
            }
        }

        if top_n_bound_reg.is_some() {
            let key_record = b.alloc_temp();
            b.emit_op(
                Opcode::MakeRecord,
                sorter_base,
                num_sort_keys as i32,
                key_record,
                P4::None,
                0,
            );
            b.emit_jump_to_label(
                Opcode::SorterCompare,
                sorter_cursor,
                key_record,
                next_source_row,
                P4::None,
                SORTER_COMPARE_TOP_N_PREFLIGHT,
            );
            b.free_temp(key_record);
        }

        if !value_emitted {
            emit_in_probe_value(b, subq_cursor, &probe_source, value_reg, &subq_scan);
        }

        if distinct_projection_mode == OrderedDistinctProjectionMode::ReprojectRepresentative {
            emit_ordered_distinct_source_state(b, subq_cursor, table, stored_data_base);
        }

        let record_reg = b.alloc_temp();
        b.emit_op(
            Opcode::MakeRecord,
            sorter_base,
            num_sorter_cols as i32,
            record_reg,
            P4::None,
            0,
        );
        b.emit_op(
            Opcode::SorterInsert,
            sorter_cursor,
            record_reg,
            0,
            P4::None,
            0,
        );
        b.free_temp(record_reg);

        b.resolve_label(next_source_row);
        let scan_body = (scan_start + 1) as i32;
        b.emit_op(Opcode::Next, subq_cursor, scan_body, 0, P4::None, 0);
        b.resolve_label(scan_done);
        if !keep_subq_cursor_open {
            b.emit_op(Opcode::Close, subq_cursor, 0, 0, P4::None, 0);
        }

        // === Pass 2: apply OFFSET/LIMIT to sorted, distinct RHS values. ===
        b.emit_jump_to_label(
            Opcode::SorterSort,
            sorter_cursor,
            0,
            selected_done,
            P4::None,
            0,
        );

        let probe_loop = b.current_addr();
        let next_sorted_row = b.emit_label();
        if let Some(offset) = offset_reg {
            b.emit_jump_to_label(Opcode::IfPos, offset, 1, next_sorted_row, P4::None, 0);
        }

        let sorted_reg = b.alloc_temp();
        b.emit_op(
            Opcode::SorterData,
            sorter_cursor,
            sorted_reg,
            0,
            P4::None,
            0,
        );
        let r_probe = b.alloc_temp();
        match distinct_projection_mode {
            OrderedDistinctProjectionMode::StoredOutput => {
                b.emit_op(
                    Opcode::Column,
                    sorter_cursor,
                    num_sort_keys as i32,
                    r_probe,
                    P4::None,
                    0,
                );
            }
            OrderedDistinctProjectionMode::ReprojectRepresentative if table.without_rowid => {
                #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                let source_base = b.alloc_regs(table.columns.len() as i32);
                for column_index in 0..table.columns.len() {
                    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                    b.emit_op(
                        Opcode::Column,
                        sorter_cursor,
                        (num_sort_keys + column_index) as i32,
                        source_base + column_index as i32,
                        P4::None,
                        0,
                    );
                }
                let replay_scan = ScanCtx {
                    cursor: 0,
                    table,
                    table_alias,
                    schema: Some(schema),
                    register_base: Some(source_base),
                    secondaries: &[],
                };
                emit_in_probe_value(b, 0, &probe_source, r_probe, &replay_scan);
            }
            OrderedDistinctProjectionMode::ReprojectRepresentative => {
                let representative_rowid = b.alloc_temp();
                b.emit_op(
                    Opcode::Column,
                    sorter_cursor,
                    num_sort_keys as i32,
                    representative_rowid,
                    P4::None,
                    0,
                );
                b.emit_jump_to_label(
                    Opcode::SeekRowid,
                    subq_cursor,
                    representative_rowid,
                    next_sorted_row,
                    P4::None,
                    0,
                );
                b.free_temp(representative_rowid);
                emit_in_probe_value(b, subq_cursor, &probe_source, r_probe, &subq_scan);
            }
        }

        b.emit_op(Opcode::Integer, 1, r_rhs_nonempty, 0, P4::None, 0);
        if let Some(ref affinity) = comparison_affinity_string {
            b.emit_op(
                Opcode::Affinity,
                r_probe,
                1,
                0,
                P4::Affinity(affinity.clone()),
                0,
            );
        }
        let saw_null = b.emit_label();
        let value_materialized = b.emit_label();
        b.emit_jump_to_label(Opcode::IsNull, r_probe, 0, saw_null, P4::None, 0);
        let membership_record = b.alloc_temp();
        b.emit_op(
            Opcode::MakeRecord,
            r_probe,
            1,
            membership_record,
            P4::None,
            0,
        );
        b.emit_op(
            Opcode::IdxInsert,
            membership_cursor,
            membership_record,
            0,
            P4::None,
            0,
        );
        b.emit_jump_to_label(Opcode::Goto, 0, 0, value_materialized, P4::None, 0);
        b.resolve_label(saw_null);
        b.emit_op(Opcode::Integer, 1, r_rhs_saw_null, 0, P4::None, 0);
        b.resolve_label(value_materialized);
        b.free_temp(membership_record);

        if let Some(lim_r) = limit_reg {
            b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, selected_done, P4::None, 0);
        }

        b.resolve_label(next_sorted_row);
        b.emit_op(
            Opcode::SorterNext,
            sorter_cursor,
            probe_loop as i32,
            0,
            P4::None,
            0,
        );
        b.free_temp(r_probe);
        b.free_temp(sorted_reg);
    } else {
        // A LIMIT-only subquery must preserve the source scan order. Applying a
        // value-keyed sorter here would silently reorder rows before LIMIT.
        let loop_start = b.current_addr();
        b.emit_jump_to_label(Opcode::Rewind, subq_cursor, 0, selected_done, P4::None, 0);

        let next_source_row = b.emit_label();
        if let Some(where_expr) = where_clause {
            emit_where_filter(
                b,
                where_expr,
                subq_cursor,
                table,
                table_alias,
                schema,
                next_source_row,
            );
        }

        // Without DISTINCT, OFFSET discards source rows before their SELECT
        // expression is evaluated. This avoids invoking volatile/erroring
        // projections for skipped rows. DISTINCT must still evaluate and
        // deduplicate the value before applying OFFSET.
        if !is_distinct && let Some(offset) = offset_reg {
            b.emit_jump_to_label(Opcode::IfPos, offset, 1, next_source_row, P4::None, 0);
        }

        let r_probe = b.alloc_temp();
        emit_in_probe_value(b, subq_cursor, &probe_source, r_probe, &subq_scan);
        if is_distinct {
            let distinct_record = b.alloc_temp();
            b.emit_op(Opcode::MakeRecord, r_probe, 1, distinct_record, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::Found,
                distinct_cursor,
                distinct_record,
                next_source_row,
                P4::None,
                0,
            );
            b.emit_op(
                Opcode::IdxInsert,
                distinct_cursor,
                distinct_record,
                0,
                P4::None,
                0,
            );
            b.free_temp(distinct_record);
            if let Some(offset) = offset_reg {
                b.emit_jump_to_label(Opcode::IfPos, offset, 1, next_source_row, P4::None, 0);
            }
        }

        b.emit_op(Opcode::Integer, 1, r_rhs_nonempty, 0, P4::None, 0);
        if let Some(ref affinity) = comparison_affinity_string {
            b.emit_op(
                Opcode::Affinity,
                r_probe,
                1,
                0,
                P4::Affinity(affinity.clone()),
                0,
            );
        }
        let saw_null = b.emit_label();
        let value_materialized = b.emit_label();
        b.emit_jump_to_label(Opcode::IsNull, r_probe, 0, saw_null, P4::None, 0);
        let membership_record = b.alloc_temp();
        b.emit_op(
            Opcode::MakeRecord,
            r_probe,
            1,
            membership_record,
            P4::None,
            0,
        );
        b.emit_op(
            Opcode::IdxInsert,
            membership_cursor,
            membership_record,
            0,
            P4::None,
            0,
        );
        b.emit_jump_to_label(Opcode::Goto, 0, 0, value_materialized, P4::None, 0);
        b.resolve_label(saw_null);
        b.emit_op(Opcode::Integer, 1, r_rhs_saw_null, 0, P4::None, 0);
        b.resolve_label(value_materialized);
        b.free_temp(membership_record);

        if let Some(lim_r) = limit_reg {
            b.emit_jump_to_label(Opcode::DecrJumpZero, lim_r, 0, selected_done, P4::None, 0);
        }

        b.resolve_label(next_source_row);
        let loop_body = (loop_start + 1) as i32;
        b.emit_op(Opcode::Next, subq_cursor, loop_body, 0, P4::None, 0);

        b.free_temp(r_probe);
    }

    b.resolve_label(selected_done);
    if has_order_by {
        b.emit_op(Opcode::Close, sorter_cursor, 0, 0, P4::None, 0);
    }
    if is_distinct {
        b.emit_op(Opcode::Close, distinct_cursor, 0, 0, P4::None, 0);
    }
    if !has_order_by || keep_subq_cursor_open {
        b.emit_op(Opcode::Close, subq_cursor, 0, 0, P4::None, 0);
    }
    b.resolve_label(build_done);

    if scalar_operand.is_some() {
        let scalar_done = b.emit_label();
        b.emit_jump_to_label(Opcode::Once, 0, 0, scalar_done, P4::None, 0);
        emit_expr(b, operand, r_operand, Some(scan_ctx));
        b.resolve_label(scalar_done);
    } else {
        emit_expr(b, operand, r_operand, Some(scan_ctx));
    }

    // Probe the once-built, non-NULL membership index for this outer row.
    // Keep the explicit empty-set branch separate: NULL IN (empty) is false,
    // while NULL IN (any non-empty set) is unknown.
    let operand_null_label = b.emit_label();
    let no_match_label = b.emit_label();
    b.emit_jump_to_label(
        Opcode::IsNull,
        r_operand,
        0,
        operand_null_label,
        P4::None,
        0,
    );
    if let Some(ref affinity) = comparison_affinity_string {
        b.emit_op(
            Opcode::Affinity,
            r_operand,
            1,
            0,
            P4::Affinity(affinity.clone()),
            0,
        );
    }
    let operand_record = b.alloc_temp();
    b.emit_op(
        Opcode::MakeRecord,
        r_operand,
        1,
        operand_record,
        P4::None,
        0,
    );
    b.emit_jump_to_label(
        Opcode::Found,
        membership_cursor,
        operand_record,
        matched_label,
        P4::None,
        0,
    );
    b.free_temp(operand_record);
    b.emit_jump_to_label(
        Opcode::If,
        r_rhs_saw_null,
        0,
        null_result_label,
        P4::None,
        0,
    );
    b.emit_jump_to_label(Opcode::Goto, 0, 0, no_match_label, P4::None, 0);

    b.resolve_label(operand_null_label);
    b.emit_jump_to_label(
        Opcode::If,
        r_rhs_nonempty,
        0,
        null_result_label,
        P4::None,
        0,
    );

    b.resolve_label(no_match_label);
    b.emit_op(Opcode::Integer, i32::from(not), reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

    b.resolve_label(matched_label);
    b.emit_op(Opcode::Integer, i32::from(!not), reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

    b.resolve_label(null_result_label);
    b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);

    b.resolve_label(done_label);
    if scalar_operand.is_none() {
        b.free_temp(r_operand);
    }

    true
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_in_probe_expr(
    b: &mut ProgramBuilder,
    operand: &Expr,
    set: &fsqlite_ast::InSet,
    not: bool,
    reg: i32,
    ctx: Option<&ScanCtx<'_>>,
) {
    let Some(scan_ctx) = ctx else {
        emit_in_probe_codegen_failure(b, "missing scan context");
        return;
    };
    let Some(schema) = scan_ctx.schema else {
        emit_in_probe_codegen_failure(b, "missing schema");
        return;
    };
    let Some(probe_source) = resolve_in_probe_source(set, schema) else {
        // Try to handle complex subqueries with ORDER BY/LIMIT.
        if let fsqlite_ast::InSet::Subquery(subquery) = set
            && try_emit_complex_in_subquery(b, operand, subquery, not, reg, scan_ctx)
        {
            return;
        }
        emit_in_probe_codegen_failure(b, "unsupported probe source");
        return;
    };

    if in_probe_expr_requires_semantic_fallback(operand) {
        emit_in_probe_codegen_failure(b, "unsupported probe operand");
        return;
    }

    if in_probe_source_references_outer_scan(&probe_source, scan_ctx) {
        emit_in_probe_codegen_failure(b, "correlated probe source requires outer substitution");
        return;
    }

    if can_use_once_materialized_in_probe_source(&probe_source, operand, scan_ctx) {
        emit_once_materialized_in_probe_source(
            b,
            operand,
            &probe_source,
            not,
            reg,
            scan_ctx,
            schema,
        );
        return;
    }

    // Keep probe cursors far from primary scan/sorter cursors used by main paths.
    let probe_cursor = scan_ctx.cursor + 64;
    let r_operand = b.alloc_temp();
    let r_probe = b.alloc_temp();

    emit_expr(b, operand, r_operand, Some(scan_ctx));

    let null_label = b.emit_label();
    let no_match_label = b.emit_label();
    let matched_label = b.emit_label();
    let done_label = b.emit_label();

    b.emit_op(
        Opcode::OpenRead,
        probe_cursor,
        probe_source.table.root_page,
        0,
        P4::Table(probe_source.table.name.clone()),
        0,
    );

    // Track whether any subquery row value is NULL (for three-valued IN).
    let r_saw_null = b.alloc_temp();
    b.emit_op(Opcode::Integer, 0, r_saw_null, 0, P4::None, 0);

    let loop_start = b.current_addr();
    b.emit_jump_to_label(Opcode::Rewind, probe_cursor, 0, no_match_label, P4::None, 0);

    let skip_label = probe_source.where_clause.map(|_| b.emit_label());
    if let (Some(where_expr), Some(skip)) = (probe_source.where_clause, skip_label) {
        emit_where_filter(
            b,
            where_expr,
            probe_cursor,
            probe_source.table,
            probe_source.table_alias,
            schema,
            skip,
        );
    }

    let probe_scan = ScanCtx {
        cursor: probe_cursor,
        table: probe_source.table,
        table_alias: probe_source.table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    emit_in_probe_value(b, probe_cursor, &probe_source, r_probe, &probe_scan);
    // Apply the comparison affinity between the outer operand and the subquery
    // probe column, mirroring `=`/value-list IN coercion (bd-56aj2 IN-subquery).
    let probe_aff = in_probe_value_affinity(&probe_source, &probe_scan);
    let probe_aff_p5 =
        combine_comparison_affinity(expr_affinity(operand, Some(scan_ctx)), probe_aff);
    let comparison_collation =
        in_probe_comparison_collation(operand, scan_ctx, &probe_source, &probe_scan)
            .map_or(P4::None, P4::Collation);
    b.emit_jump_to_label(
        Opcode::Eq,
        r_probe,
        r_operand,
        matched_label,
        comparison_collation,
        probe_aff_p5,
    );
    // A NULL on either side makes a no-match unknown, but only after at least
    // one qualifying RHS row exists. An empty RHS remains a definite miss.
    let after_flag = b.emit_label();
    let set_flag = b.emit_label();
    b.emit_jump_to_label(Opcode::IsNull, r_operand, 0, set_flag, P4::None, 0);
    b.emit_jump_to_label(Opcode::IsNull, r_probe, 0, set_flag, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, after_flag, P4::None, 0);
    b.resolve_label(set_flag);
    b.emit_op(Opcode::Integer, 1, r_saw_null, 0, P4::None, 0);
    b.resolve_label(after_flag);

    if let Some(skip) = skip_label {
        b.resolve_label(skip);
    }
    let loop_body = (loop_start + 1) as i32;
    b.emit_op(Opcode::Next, probe_cursor, loop_body, 0, P4::None, 0);

    b.resolve_label(no_match_label);
    // No match.  If any subquery value was NULL → result is NULL.
    b.emit_jump_to_label(Opcode::If, r_saw_null, 0, null_label, P4::None, 0);
    b.emit_op(Opcode::Integer, i32::from(not), reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

    b.resolve_label(null_label);
    b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

    b.resolve_label(matched_label);
    b.emit_op(Opcode::Integer, i32::from(!not), reg, 0, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, probe_cursor, 0, 0, P4::None, 0);

    b.free_temp(r_saw_null);
    b.free_temp(r_probe);
    b.free_temp(r_operand);
}

/// Fail closed when routing and expression lowering disagree about an `IN`
/// probe. Returning SQL `NULL` here would silently turn an internal codegen
/// defect into a query result.
fn emit_in_probe_codegen_failure(b: &mut ProgramBuilder, reason: &str) {
    b.emit_op(
        Opcode::Halt,
        ErrorCode::Internal as i32,
        0,
        0,
        P4::Str(format!("IN probe codegen invariant failed: {reason}")),
        0,
    );
}

/// Lower a materialized row-value `IN` list without collapsing the row into a
/// scalar register.
///
/// SQLite compares each candidate tuple field by field. A definite inequality
/// rejects that candidate even if an earlier field comparison was unknown;
/// only a candidate with no unequal field and at least one NULL contributes an
/// UNKNOWN result. The final syntactic RHS tuple supplies comparison affinity
/// and collation metadata for every candidate, matching SQLite's vector-IN
/// expression metadata rules.
fn emit_row_value_in_list(
    b: &mut ProgramBuilder,
    lhs_exprs: &[Expr],
    values: &[Expr],
    not: bool,
    reg: i32,
    ctx: Option<&ScanCtx<'_>>,
) {
    if lhs_exprs.is_empty() {
        emit_in_probe_codegen_failure(b, "row-value operand has no fields");
        return;
    }

    let mut rhs_rows = Vec::with_capacity(values.len());
    for value in values {
        let Expr::RowValue(rhs_exprs, _) = value else {
            emit_in_probe_codegen_failure(b, "row-value IN list contains a scalar candidate");
            return;
        };
        if rhs_exprs.len() != lhs_exprs.len() {
            emit_in_probe_codegen_failure(
                b,
                &format!(
                    "row-value IN arity mismatch: expected {}, found {}",
                    lhs_exprs.len(),
                    rhs_exprs.len()
                ),
            );
            return;
        }
        rhs_rows.push(rhs_exprs.as_slice());
    }

    let Some(donor_exprs) = rhs_rows.last().copied() else {
        // The caller handles the empty-list truth table before evaluating the
        // LHS. Keep this defensive branch correct if the helper is reused.
        b.emit_op(Opcode::Integer, i32::from(not), reg, 0, P4::None, 0);
        return;
    };
    let Ok(lhs_arity) = i32::try_from(lhs_exprs.len()) else {
        emit_in_probe_codegen_failure(b, "row-value IN arity exceeds VDBE register limits");
        return;
    };

    // These must remain stable while every candidate is inspected: volatile
    // LHS expressions are evaluated exactly once, not once per candidate.
    let lhs_base = b.alloc_regs(lhs_arity);
    for (field_index, lhs_expr) in lhs_exprs.iter().enumerate() {
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        emit_expr(b, lhs_expr, lhs_base + field_index as i32, ctx);
    }

    let matched_label = b.emit_label();
    let null_label = b.emit_label();
    let done_label = b.emit_label();
    let saw_unknown = b.alloc_temp();
    let candidate_unknown = b.alloc_temp();
    let rhs_reg = b.alloc_temp();
    b.emit_op(Opcode::Integer, 0, saw_unknown, 0, P4::None, 0);

    for rhs_exprs in rhs_rows {
        let candidate_rejected = b.emit_label();
        b.emit_op(Opcode::Integer, 0, candidate_unknown, 0, P4::None, 0);

        for (field_index, ((lhs_expr, rhs_expr), donor_expr)) in
            lhs_exprs.iter().zip(rhs_exprs).zip(donor_exprs).enumerate()
        {
            emit_expr(b, rhs_expr, rhs_reg, ctx);
            let next_field = b.emit_label();
            let field_unknown = b.emit_label();
            let comparison_p4 =
                comparison_collation_ctx(lhs_expr, donor_expr, ctx).map_or(P4::None, P4::Collation);
            let comparison_affinity = comparison_affinity_p5(lhs_expr, donor_expr, ctx);
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let lhs_reg = lhs_base + field_index as i32;

            b.emit_jump_to_label(
                Opcode::Eq,
                rhs_reg,
                lhs_reg,
                next_field,
                comparison_p4,
                comparison_affinity,
            );
            b.emit_jump_to_label(Opcode::IsNull, lhs_reg, 0, field_unknown, P4::None, 0);
            b.emit_jump_to_label(Opcode::IsNull, rhs_reg, 0, field_unknown, P4::None, 0);
            // Both fields are non-NULL and unequal. This candidate is FALSE,
            // even if an earlier field had produced UNKNOWN.
            b.emit_jump_to_label(Opcode::Goto, 0, 0, candidate_rejected, P4::None, 0);

            b.resolve_label(field_unknown);
            b.emit_op(Opcode::Integer, 1, candidate_unknown, 0, P4::None, 0);
            b.resolve_label(next_field);
        }

        let mark_unknown = b.emit_label();
        b.emit_jump_to_label(Opcode::If, candidate_unknown, 0, mark_unknown, P4::None, 0);
        // Every field was definitely equal.
        b.emit_jump_to_label(Opcode::Goto, 0, 0, matched_label, P4::None, 0);
        b.resolve_label(mark_unknown);
        b.emit_op(Opcode::Integer, 1, saw_unknown, 0, P4::None, 0);
        b.resolve_label(candidate_rejected);
    }

    b.emit_jump_to_label(Opcode::If, saw_unknown, 0, null_label, P4::None, 0);
    b.emit_op(Opcode::Integer, i32::from(not), reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
    b.resolve_label(matched_label);
    b.emit_op(Opcode::Integer, i32::from(!not), reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
    b.resolve_label(null_label);
    b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
    b.resolve_label(done_label);

    b.free_temp(rhs_reg);
    b.free_temp(candidate_unknown);
    b.free_temp(saw_unknown);
}

/// Handles literals, bind parameters, binary/unary operators, CASE, CAST,
/// and (when `ctx` is provided) column references from a table scan cursor.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::too_many_lines,
    clippy::many_single_char_names
)]
fn emit_expr(b: &mut ProgramBuilder, expr: &Expr, reg: i32, ctx: Option<&ScanCtx<'_>>) {
    match expr {
        Expr::Placeholder(pt, _) => {
            let idx = match pt {
                fsqlite_ast::PlaceholderType::Numbered(n) => *n as i32,
                // Anonymous and named placeholders are assigned sequentially.
                _ => b.next_anon_placeholder_idx() as i32,
            };
            b.emit_op(Opcode::Variable, idx, reg, 0, P4::None, 0);
        }
        Expr::Literal(lit, _) => match lit {
            Literal::Integer(n) => {
                if let Ok(as_i32) = i32::try_from(*n) {
                    b.emit_op(Opcode::Integer, as_i32, reg, 0, P4::None, 0);
                } else {
                    b.emit_op(Opcode::Int64, 0, reg, 0, P4::Int64(*n), 0);
                }
            }
            Literal::Float(f) => {
                b.emit_op(Opcode::Real, 0, reg, 0, P4::Real(*f), 0);
            }
            Literal::String(s) => {
                b.emit_op(Opcode::String8, 0, reg, 0, P4::Str(s.clone()), 0);
            }
            Literal::Blob(bytes) => {
                b.emit_op(
                    Opcode::Blob,
                    bytes.len() as i32,
                    reg,
                    0,
                    P4::Blob(bytes.clone()),
                    0,
                );
            }
            Literal::True => {
                b.emit_op(Opcode::Integer, 1, reg, 0, P4::None, 0);
            }
            Literal::False => {
                b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
            }
            Literal::CurrentTimestamp | Literal::CurrentDate | Literal::CurrentTime => {
                let ts = current_time_literal_text(lit)
                    .expect("current-time literals should resolve to a string");
                b.emit_op(Opcode::String8, 0, reg, 0, P4::Str(ts), 0);
            }
            Literal::Null => {
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            }
        },
        Expr::BoundOuterValue { value, .. } => emit_sqlite_value(b, value, reg),
        Expr::BinaryOp {
            left, op, right, ..
        } => {
            emit_binary_op(b, left, *op, right, reg, ctx);
        }
        Expr::UnaryOp {
            op, expr: operand, ..
        } => {
            emit_expr(b, operand, reg, ctx);
            match op {
                fsqlite_ast::UnaryOp::Negate => {
                    // Multiply by -1: Integer(-1) into temp, then Multiply.
                    let tmp = b.alloc_temp();
                    b.emit_op(Opcode::Integer, -1, tmp, 0, P4::None, 0);
                    b.emit_op(Opcode::Multiply, tmp, reg, reg, P4::None, 0);
                    b.free_temp(tmp);
                }
                fsqlite_ast::UnaryOp::Plus => { /* no-op */ }
                fsqlite_ast::UnaryOp::BitNot => {
                    b.emit_op(Opcode::BitNot, reg, reg, 0, P4::None, 0);
                }
                fsqlite_ast::UnaryOp::Not => {
                    b.emit_op(Opcode::Not, reg, reg, 0, P4::None, 0);
                }
            }
        }
        Expr::Cast {
            expr: inner,
            type_name,
            ..
        } => {
            emit_expr(b, inner, reg, ctx);
            let affinity = type_name_to_affinity(type_name);
            b.emit_op(Opcode::Cast, reg, i32::from(affinity), 0, P4::None, 0);
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            emit_case_expr(b, operand.as_deref(), whens, else_expr.as_deref(), reg, ctx);
        }
        Expr::IsNull {
            expr: inner, not, ..
        } => {
            // IS NULL → result 1 if null, 0 otherwise.
            // IS NOT NULL → result 0 if null, 1 otherwise.
            emit_expr(b, inner, reg, ctx);
            let lbl_null = b.emit_label();
            let lbl_done = b.emit_label();
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, lbl_null, P4::None, 0);
            // Not null path.
            let val_not_null = i32::from(*not); // IS NOT NULL: 1; IS NULL: 0
            let val_null = i32::from(!*not); // IS NOT NULL: 0; IS NULL: 1
            b.emit_op(Opcode::Integer, val_not_null, reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, lbl_done, P4::None, 0);
            b.resolve_label(lbl_null);
            b.emit_op(Opcode::Integer, val_null, reg, 0, P4::None, 0);
            b.resolve_label(lbl_done);
        }
        Expr::Like {
            expr: operand,
            pattern,
            escape,
            op: like_op,
            not,
            ..
        } => {
            if use_builtin_like_glob_semantics()
                && matches!(like_op, fsqlite_ast::LikeOp::Like)
                && escape.is_none()
                && let Expr::Literal(Literal::String(pattern_text), _) = pattern.as_ref()
                && let Some((kind, literal)) = classify_sql_like_fast_path(pattern_text, None)
            {
                emit_expr(b, operand, reg, ctx);
                b.emit_op(
                    Opcode::LikeConstFast,
                    reg,
                    reg,
                    kind.opcode_tag(),
                    P4::Str(literal.to_owned()),
                    u16::from(*not),
                );
                return;
            }

            let func_name = match like_op {
                fsqlite_ast::LikeOp::Like => "LIKE",
                fsqlite_ast::LikeOp::Glob => "GLOB",
                fsqlite_ast::LikeOp::Match => "MATCH",
                fsqlite_ast::LikeOp::Regexp => "REGEXP",
            };
            let nargs: u16 = if escape.is_some() { 3 } else { 2 };
            let arg_base = b.alloc_regs(i32::from(nargs));
            // like(pattern, string [, escape])
            emit_expr(b, pattern, arg_base, ctx);
            emit_expr(b, operand, arg_base + 1, ctx);
            if let Some(esc) = escape {
                emit_expr(b, esc, arg_base + 2, ctx);
            }
            let function_p4 =
                if scalar_consumes_argument_collation_for_codegen(func_name, i32::from(nargs)) {
                    scalar_function_argument_collation_ctx(
                        [pattern.as_ref(), operand.as_ref()]
                            .into_iter()
                            .chain(escape.as_deref()),
                        ctx,
                    )
                    .map_or_else(
                        || P4::FuncName(func_name.to_owned()),
                        |collation| P4::FuncNameCollated(func_name.to_owned(), collation),
                    )
                } else {
                    P4::FuncName(func_name.to_owned())
                };
            b.emit_op(Opcode::PureFunc, 0, arg_base, reg, function_p4, nargs);
            if *not {
                b.emit_op(Opcode::Not, reg, reg, 0, P4::None, 0);
            }
        }
        Expr::Between {
            expr: operand,
            low,
            high,
            not,
            ..
        } => {
            // BETWEEN low AND high → (operand >= low) AND (operand <= high)
            // with three-valued NULL logic:
            //   NULL BETWEEN x AND y  → NULL
            //   v BETWEEN NULL AND y  → NULL when v <= y, FALSE when v > y
            //   v BETWEEN x AND NULL  → NULL when v >= x, FALSE when v < x
            let r_operand = b.alloc_temp();
            let r_low = b.alloc_temp();
            let r_high = b.alloc_temp();
            emit_expr(b, operand, r_operand, ctx);
            emit_expr(b, low, r_low, ctx);
            emit_expr(b, high, r_high, ctx);
            // BETWEEN is two comparisons. Each independently uses the
            // operand's collation first, then that comparison's RHS.
            let low_collation_p4 =
                comparison_collation_ctx(operand, low, ctx).map_or(P4::None, P4::Collation);
            let high_collation_p4 =
                comparison_collation_ctx(operand, high, ctx).map_or(P4::None, P4::Collation);
            let low_aff = comparison_affinity_p5(operand, low, ctx);
            let high_aff = comparison_affinity_p5(operand, high, ctx);
            let false_label = b.emit_label();
            let null_label = b.emit_label();
            let done_label = b.emit_label();
            // If operand is NULL, short-circuit to NULL result.
            b.emit_jump_to_label(Opcode::IsNull, r_operand, 0, null_label, P4::None, 0);
            // Jump to false if operand < low (NULL low → no jump, handled below).
            b.emit_jump_to_label(
                Opcode::Lt,
                r_low,
                r_operand,
                false_label,
                low_collation_p4,
                low_aff,
            );
            // Jump to false if operand > high (NULL high → no jump, handled below).
            b.emit_jump_to_label(
                Opcode::Gt,
                r_high,
                r_operand,
                false_label,
                high_collation_p4,
                high_aff,
            );
            // Passed both comparisons.  If either bound was NULL the comparison
            // silently fell through instead of confirming the range, so the
            // correct three-valued result is NULL, not TRUE.
            b.emit_jump_to_label(Opcode::IsNull, r_low, 0, null_label, P4::None, 0);
            b.emit_jump_to_label(Opcode::IsNull, r_high, 0, null_label, P4::None, 0);
            // Genuinely in range with no NULLs involved.
            b.emit_op(Opcode::Integer, i32::from(!*not), reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
            b.resolve_label(false_label);
            b.emit_op(Opcode::Integer, i32::from(*not), reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
            b.resolve_label(null_label);
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            b.resolve_label(done_label);
            b.free_temp(r_high);
            b.free_temp(r_low);
            b.free_temp(r_operand);
        }
        Expr::In {
            expr: operand,
            set,
            not,
            ..
        } => {
            if let fsqlite_ast::InSet::List(values) = set {
                if values.is_empty() {
                    // x IN () is always FALSE, x NOT IN () is always TRUE, even if x is NULL.
                    b.emit_op(Opcode::Integer, i32::from(*not), reg, 0, P4::None, 0);
                    return;
                }
                if let Expr::RowValue(lhs_exprs, _) = operand.as_ref() {
                    emit_row_value_in_list(b, lhs_exprs, values, *not, reg, ctx);
                    return;
                }
                if values
                    .iter()
                    .any(|value| matches!(value, Expr::RowValue(..)))
                {
                    emit_in_probe_codegen_failure(
                        b,
                        "scalar IN list contains a row-value candidate",
                    );
                    return;
                }
                if can_use_once_materialized_in_list(values, operand, ctx) {
                    emit_once_materialized_in_list(b, operand, values, *not, reg, ctx);
                    return;
                }
                // IN (v1, v2, ...) → chain of equality checks with
                // three-valued NULL semantics (SQL standard):
                //   NULL IN (...)            → NULL
                //   v IN (a, NULL, b) miss   → NULL  (NULL in list)
                //   v IN (a, b, c) miss      → FALSE (no NULLs)
                //   v IN (...) hit           → TRUE
                let r_operand = b.alloc_temp();
                emit_expr(b, operand, r_operand, ctx);
                // A constant singleton IN-list is comparison-equivalent in
                // SQLite, so its RHS may supply an explicit/declared collation.
                // Longer or row-dependent lists use only the LHS collation.
                let in_collation = if values.len() == 1 && singleton_in_rhs_is_constant(&values[0])
                {
                    comparison_collation_ctx(operand, &values[0], ctx)
                } else {
                    extract_collation(operand)
                        .map(str::to_owned)
                        .or_else(|| declared_collation_ctx(operand, ctx).map(str::to_owned))
                };
                let collation_p4 = in_collation.map_or(P4::None, P4::Collation);
                // Apply the operand's comparison affinity to each list value, so
                // `INTEGER_col IN ('1','5')` coerces the text literals to numbers
                // exactly like a plain `=`/BETWEEN comparison (bd-cfmf6/bd-56aj2).
                let in_aff = in_operand_affinity_p5(operand, ctx);
                let null_label = b.emit_label();
                let true_label = b.emit_label();
                let done_label = b.emit_label();
                // If operand is NULL, short-circuit to NULL result.
                b.emit_jump_to_label(Opcode::IsNull, r_operand, 0, null_label, P4::None, 0);
                // r_saw_null: set to 1 at runtime if any list element is NULL.
                let r_saw_null = b.alloc_temp();
                b.emit_op(Opcode::Integer, 0, r_saw_null, 0, P4::None, 0);
                let r_val = b.alloc_temp();
                for val_expr in values {
                    emit_expr(b, val_expr, r_val, ctx);
                    b.emit_jump_to_label(
                        Opcode::Eq,
                        r_val,
                        r_operand,
                        true_label,
                        collation_p4.clone(),
                        in_aff,
                    );
                    // Eq with NULL never jumps.  If this value was NULL, flag it.
                    let next_val = b.emit_label();
                    let set_flag = b.emit_label();
                    b.emit_jump_to_label(Opcode::IsNull, r_val, 0, set_flag, P4::None, 0);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, next_val, P4::None, 0);
                    b.resolve_label(set_flag);
                    b.emit_op(Opcode::Integer, 1, r_saw_null, 0, P4::None, 0);
                    b.resolve_label(next_val);
                }
                b.free_temp(r_val);
                // No match.  If any list element was NULL → result is NULL.
                b.emit_jump_to_label(Opcode::If, r_saw_null, 0, null_label, P4::None, 0);
                b.free_temp(r_saw_null);
                // Definite no-match with no NULLs → FALSE (or TRUE for NOT IN).
                b.emit_op(Opcode::Integer, i32::from(*not), reg, 0, P4::None, 0);
                b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                b.resolve_label(null_label);
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                b.resolve_label(true_label);
                b.emit_op(Opcode::Integer, i32::from(!*not), reg, 0, P4::None, 0);
                b.resolve_label(done_label);
                b.free_temp(r_operand);
            } else {
                if matches!(operand.as_ref(), Expr::RowValue(..)) {
                    emit_in_probe_codegen_failure(
                        b,
                        "multi-column subquery/table probes require prior list materialization",
                    );
                    return;
                }
                emit_in_probe_expr(b, operand, set, *not, reg, ctx);
            }
        }
        Expr::FunctionCall { name, args, .. } if !is_aggregate_function_call(name, args) => {
            // Scalar function call: emit args, then PureFunc.
            let canon = name.to_ascii_uppercase();
            match args {
                fsqlite_ast::FunctionArgs::Star => {
                    // func(*) for non-aggregate → 0 args.
                    b.emit_op(Opcode::PureFunc, 0, 0, reg, P4::FuncName(canon), 0);
                }
                fsqlite_ast::FunctionArgs::List(arg_list) => {
                    if let Some(scan_ctx) = ctx
                        && (try_emit_column_substr_prefix(b, name, arg_list, reg, scan_ctx)
                            || try_emit_column_octet_length(b, name, arg_list, reg, scan_ctx))
                    {
                        return;
                    }
                    let Ok(nargs) = u16::try_from(arg_list.len()) else {
                        b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                        return;
                    };
                    let arg_base = b.alloc_regs(i32::from(nargs));
                    for (i, arg_expr) in arg_list.iter().enumerate() {
                        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                        emit_expr(b, arg_expr, arg_base + i as i32, ctx);
                    }
                    b.emit_op(
                        Opcode::PureFunc,
                        0,
                        arg_base,
                        reg,
                        scalar_function_p4(canon, arg_list, ctx),
                        nargs,
                    );
                }
            }
        }
        Expr::Column(col_ref, _) => {
            let Some(sc) = ctx else {
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                return;
            };
            if let Some(qualifier) = &col_ref.table
                && !matches_table_or_alias(qualifier, sc.table, sc.table_alias)
            {
                // Check secondary table contexts (UPDATE ... FROM, possibly
                // multiple FROM sources joined together).
                if let Some(sec) = sc
                    .secondaries
                    .iter()
                    .find(|sec| matches_table_or_alias(qualifier, sec.table, sec.table_alias))
                {
                    emit_secondary_column(b, &col_ref.column, sec, reg);
                    return;
                }
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                return;
            }
            // Register-based resolution for generated column expressions
            // during INSERT: copy from the register holding that column's value.
            if let Some(reg_base) = sc.register_base {
                if let Some(col_idx) = sc.table.column_index(&col_ref.column) {
                    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                    if let Some(gen_expr) =
                        virtual_generated_column_expr(&sc.table.columns[col_idx])
                    {
                        // bd-r3303: a VIRTUAL generated column has only a NULL
                        // placeholder register (it is never materialized), so when
                        // it is referenced in a write-time context — building an
                        // index key over it, or a STORED column / CHECK constraint
                        // that reads it — recompute it from the sibling column
                        // registers and coerce to its declared affinity.
                        b.with_schema_evaluation_context(
                            SchemaEvaluationContext::GeneratedColumn,
                            |b| emit_expr(b, &gen_expr, reg, Some(sc)),
                        );
                        emit_single_column_affinity(b, reg, sc.table.columns[col_idx].affinity);
                    } else {
                        b.emit_op(Opcode::Copy, reg_base + col_idx as i32, reg, 0, P4::None, 0);
                    }
                } else {
                    b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                }
            } else if let Some(col_idx) = sc.table.column_index(&col_ref.column) {
                #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                if sc.table.columns[col_idx].is_ipk {
                    b.emit_op(Opcode::Rowid, sc.cursor, reg, 0, P4::None, 0);
                } else if let Some(gen_expr) =
                    virtual_generated_column_expr(&sc.table.columns[col_idx])
                {
                    // bd-r3303: a VIRTUAL generated column is not materialized in
                    // the stored record, so compute it on read by emitting its
                    // generating expression against the current cursor row (the
                    // referenced base columns resolve through this same path),
                    // then coerce to the column's declared affinity — matching
                    // what record packing applies to STORED columns at write.
                    b.with_schema_evaluation_context(
                        SchemaEvaluationContext::GeneratedColumn,
                        |b| emit_expr(b, &gen_expr, reg, Some(sc)),
                    );
                    emit_single_column_affinity(b, reg, sc.table.columns[col_idx].affinity);
                } else {
                    b.emit_op(Opcode::Column, sc.cursor, col_idx as i32, reg, P4::None, 0);
                }
            } else if sc.table.resolves_to_hidden_rowid(&col_ref.column) {
                b.emit_op(Opcode::Rowid, sc.cursor, reg, 0, P4::None, 0);
            } else if let Some(sec) = sc
                .secondaries
                .iter()
                .find(|sec| table_has_column_or_rowid(sec.table, &col_ref.column))
            {
                // Unqualified column not found in primary — resolve against the
                // first secondary FROM source that has it.
                emit_secondary_column(b, &col_ref.column, sec, reg);
            } else {
                // Unknown column — emit Null.
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            }
        }
        Expr::Collate { expr: inner, .. } => {
            // Evaluate the inner expression; collation affects comparisons
            // rather than value computation, so a pass-through is correct.
            emit_expr(b, inner, reg, ctx);
        }
        Expr::Exists { subquery, not, .. } => {
            if let Some(scan_ctx) = ctx
                && let Some(schema) = scan_ctx.schema
            {
                emit_exists_subquery(b, subquery, *not, reg, scan_ctx, schema);
                return;
            }
            // No schema context — emit 0 (false) for EXISTS, 1 for NOT EXISTS.
            let val = i32::from(*not);
            b.emit_op(Opcode::Integer, val, reg, 0, P4::None, 0);
        }
        Expr::Subquery(subquery, _) => {
            if let Some(scan_ctx) = ctx
                && let Some(schema) = scan_ctx.schema
            {
                emit_scalar_subquery(b, subquery, reg, scan_ctx, schema);
                return;
            }
            // No schema context — emit NULL.
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
        }
        Expr::JsonAccess {
            expr: inner,
            path,
            arrow,
            ..
        } => {
            let arg_base = b.alloc_regs(2);
            emit_expr(b, inner, arg_base, ctx);
            emit_expr(b, path, arg_base + 1, ctx);
            let function_name = json_access_func_name(*arrow);
            let function_p4 = if scalar_consumes_argument_collation_for_codegen(function_name, 2) {
                scalar_function_argument_collation_ctx([inner.as_ref(), path.as_ref()], ctx)
                    .map_or_else(
                        || P4::FuncName(function_name.to_owned()),
                        |collation| P4::FuncNameCollated(function_name.to_owned(), collation),
                    )
            } else {
                P4::FuncName(function_name.to_owned())
            };
            b.emit_op(Opcode::PureFunc, 0, arg_base, reg, function_p4, 2);
        }
        _ => {
            // Column refs without scan context and other unhandled expressions: Null.
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
        }
    }
}

fn current_time_literal_text(literal: &Literal) -> Option<String> {
    use fsqlite_types::sync_primitives::SystemTime;

    let secs = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let days = secs / 86400;
    let day_secs = secs % 86400;
    let h = day_secs / 3600;
    let m = (day_secs % 3600) / 60;
    let s = day_secs % 60;
    let (y, mo, d) = epoch_days_to_ymd(days);

    Some(match *literal {
        Literal::CurrentTimestamp => format!("{y:04}-{mo:02}-{d:02} {h:02}:{m:02}:{s:02}"),
        Literal::CurrentDate => format!("{y:04}-{mo:02}-{d:02}"),
        Literal::CurrentTime => format!("{h:02}:{m:02}:{s:02}"),
        _ => return None,
    })
}

/// Emit bytecode for an EXISTS or NOT EXISTS subquery expression.
///
/// Pattern: open cursor on subquery table, scan with WHERE filter, set reg to
/// 1 (found) or 0 (not found). For NOT EXISTS, the result is inverted.
fn flatten_and_terms<'a>(expr: &'a Expr, terms: &mut Vec<&'a Expr>) {
    if let Expr::BinaryOp {
        left,
        op: fsqlite_ast::BinaryOp::And,
        right,
        ..
    } = expr
    {
        flatten_and_terms(left, terms);
        flatten_and_terms(right, terms);
    } else {
        terms.push(expr);
    }
}

fn expr_references_scan(expr: &Expr, table: &TableSchema, table_alias: Option<&str>) -> bool {
    match expr {
        Expr::Column(_, _) => resolve_column_ref(expr, table, table_alias).is_some(),
        Expr::BinaryOp { left, right, .. } => {
            expr_references_scan(left, table, table_alias)
                || expr_references_scan(right, table, table_alias)
        }
        Expr::UnaryOp { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. }
        | Expr::IsNull { expr, .. } => expr_references_scan(expr, table, table_alias),
        Expr::Between {
            expr, low, high, ..
        } => {
            expr_references_scan(expr, table, table_alias)
                || expr_references_scan(low, table, table_alias)
                || expr_references_scan(high, table, table_alias)
        }
        Expr::In { expr, set, .. } => {
            expr_references_scan(expr, table, table_alias)
                || match set {
                    fsqlite_ast::InSet::List(values) => values
                        .iter()
                        .any(|value| expr_references_scan(value, table, table_alias)),
                    fsqlite_ast::InSet::Table(_) | fsqlite_ast::InSet::Subquery(_) => true,
                }
        }
        Expr::Like {
            expr,
            pattern,
            escape,
            ..
        } => {
            expr_references_scan(expr, table, table_alias)
                || expr_references_scan(pattern, table, table_alias)
                || escape
                    .as_deref()
                    .is_some_and(|esc| expr_references_scan(esc, table, table_alias))
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand
                .as_deref()
                .is_some_and(|inner| expr_references_scan(inner, table, table_alias))
                || whens.iter().any(|(when_expr, then_expr)| {
                    expr_references_scan(when_expr, table, table_alias)
                        || expr_references_scan(then_expr, table, table_alias)
                })
                || else_expr
                    .as_deref()
                    .is_some_and(|inner| expr_references_scan(inner, table, table_alias))
        }
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            over,
            ..
        } => {
            over.is_some()
                || match args {
                    FunctionArgs::Star => false,
                    FunctionArgs::List(values) => values
                        .iter()
                        .any(|value| expr_references_scan(value, table, table_alias)),
                }
                || order_by
                    .iter()
                    .any(|term| expr_references_scan(&term.expr, table, table_alias))
                || filter
                    .as_deref()
                    .is_some_and(|inner| expr_references_scan(inner, table, table_alias))
        }
        Expr::JsonAccess { expr, path, .. } => {
            expr_references_scan(expr, table, table_alias)
                || expr_references_scan(path, table, table_alias)
        }
        Expr::Exists { .. } | Expr::Subquery(_, _) => true,
        _ => false,
    }
}

const ONCE_MATERIALIZED_IN_LIST_THRESHOLD: usize = 8;

fn in_list_value_supports_once_materialization(expr: &Expr) -> bool {
    match expr {
        Expr::Literal(_, _) | Expr::Placeholder(_, _) => true,
        Expr::UnaryOp { expr: inner, .. }
        | Expr::Cast { expr: inner, .. }
        | Expr::Collate { expr: inner, .. } => in_list_value_supports_once_materialization(inner),
        _ => false,
    }
}

/// Whether SQLite may treat a one-element IN-list as an ordinary binary
/// comparison for collation precedence.  This is narrower than "evaluates to
/// one value": table columns, scalar subqueries, and non-deterministic calls
/// remain genuine IN-list terms and therefore cannot donate an RHS collation.
/// Registry metadata admits both deterministic and SQLite slow-changing scalar
/// calls, provided every argument is recursively query-constant.
fn singleton_in_rhs_is_constant(expr: &Expr) -> bool {
    match expr {
        Expr::Literal(_, _) | Expr::Placeholder(_, _) => true,
        Expr::BinaryOp { left, right, .. } => {
            singleton_in_rhs_is_constant(left) && singleton_in_rhs_is_constant(right)
        }
        Expr::JsonAccess {
            expr: left,
            path: right,
            arrow,
            ..
        } => {
            let name = json_access_func_name(*arrow);
            scalar_is_query_constant_for_codegen(name, 2)
                && singleton_in_rhs_is_constant(left)
                && singleton_in_rhs_is_constant(right)
        }
        Expr::UnaryOp { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. }
        | Expr::IsNull { expr, .. } => singleton_in_rhs_is_constant(expr),
        Expr::Between {
            expr, low, high, ..
        } => {
            singleton_in_rhs_is_constant(expr)
                && singleton_in_rhs_is_constant(low)
                && singleton_in_rhs_is_constant(high)
        }
        Expr::In { expr, set, .. } => {
            singleton_in_rhs_is_constant(expr)
                && matches!(set, InSet::List(values) if values.iter().all(singleton_in_rhs_is_constant))
        }
        Expr::Like {
            expr,
            pattern,
            escape,
            op,
            ..
        } => {
            let (name, arity) = match op {
                fsqlite_ast::LikeOp::Like => ("like", if escape.is_some() { 3 } else { 2 }),
                fsqlite_ast::LikeOp::Glob => ("glob", 2),
                fsqlite_ast::LikeOp::Match => ("match", 2),
                fsqlite_ast::LikeOp::Regexp => ("regexp", 2),
            };
            scalar_is_query_constant_for_codegen(name, arity)
                && singleton_in_rhs_is_constant(expr)
                && singleton_in_rhs_is_constant(pattern)
                && escape.as_deref().is_none_or(singleton_in_rhs_is_constant)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand.as_deref().is_none_or(singleton_in_rhs_is_constant)
                && whens.iter().all(|(condition, value)| {
                    singleton_in_rhs_is_constant(condition) && singleton_in_rhs_is_constant(value)
                })
                && else_expr
                    .as_deref()
                    .is_none_or(singleton_in_rhs_is_constant)
        }
        Expr::FunctionCall {
            name,
            args,
            distinct,
            order_by,
            filter,
            over,
            ..
        } => {
            if *distinct || !order_by.is_empty() || filter.is_some() || over.is_some() {
                return false;
            }
            let (arity, arguments_are_constant) = match args {
                FunctionArgs::Star => return false,
                FunctionArgs::List(values) => {
                    let Ok(arity) = i32::try_from(values.len()) else {
                        return false;
                    };
                    (arity, values.iter().all(singleton_in_rhs_is_constant))
                }
            };
            arguments_are_constant && scalar_is_query_constant_for_codegen(name, arity)
        }
        Expr::RowValue(values, _) => {
            !values.is_empty() && values.iter().all(singleton_in_rhs_is_constant)
        }
        Expr::BoundOuterValue { .. }
        | Expr::Column(_, _)
        | Expr::Subquery(_, _)
        | Expr::Exists { .. }
        | Expr::Raise { .. } => false,
    }
}

fn can_use_once_materialized_in_list(
    values: &[Expr],
    _operand: &Expr,
    _ctx: Option<&ScanCtx<'_>>,
) -> bool {
    if values.len() < ONCE_MATERIALIZED_IN_LIST_THRESHOLD {
        return false;
    }
    if !values
        .iter()
        .all(in_list_value_supports_once_materialization)
    {
        return false;
    }
    true
}

fn probe_expr_references_outer_scan(
    expr: &Expr,
    probe_source: &InProbeSource<'_>,
    scan_ctx: &ScanCtx<'_>,
) -> bool {
    match expr {
        Expr::Column(_, _) => {
            if resolve_column_ref(expr, probe_source.table, probe_source.table_alias).is_some() {
                return false;
            }
            resolve_column_ref(expr, scan_ctx.table, scan_ctx.table_alias).is_some()
                || scan_ctx.secondaries.iter().any(|secondary| {
                    resolve_column_ref(expr, secondary.table, secondary.table_alias).is_some()
                })
        }
        Expr::BinaryOp { left, right, .. } => {
            probe_expr_references_outer_scan(left, probe_source, scan_ctx)
                || probe_expr_references_outer_scan(right, probe_source, scan_ctx)
        }
        Expr::UnaryOp { expr: inner, .. }
        | Expr::IsNull { expr: inner, .. }
        | Expr::Cast { expr: inner, .. }
        | Expr::Collate { expr: inner, .. } => {
            probe_expr_references_outer_scan(inner, probe_source, scan_ctx)
        }
        Expr::Between {
            expr: inner,
            low,
            high,
            ..
        } => {
            probe_expr_references_outer_scan(inner, probe_source, scan_ctx)
                || probe_expr_references_outer_scan(low, probe_source, scan_ctx)
                || probe_expr_references_outer_scan(high, probe_source, scan_ctx)
        }
        Expr::In {
            expr: inner, set, ..
        } => {
            probe_expr_references_outer_scan(inner, probe_source, scan_ctx)
                || match set {
                    fsqlite_ast::InSet::List(items) => items
                        .iter()
                        .any(|item| probe_expr_references_outer_scan(item, probe_source, scan_ctx)),
                    // Recursively resolving a nested SELECT would require a
                    // separate scope stack. Fail closed instead of overlooking
                    // a correlation hidden inside that SELECT.
                    fsqlite_ast::InSet::Subquery(_) => true,
                    // A table-name shorthand contains no expression that can
                    // reference the outer scan.
                    fsqlite_ast::InSet::Table(_) => false,
                }
        }
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            over,
            ..
        } => {
            matches!(
                args,
                FunctionArgs::List(items)
                    if items
                        .iter()
                        .any(|item| probe_expr_references_outer_scan(item, probe_source, scan_ctx))
            ) || order_by
                .iter()
                .any(|term| probe_expr_references_outer_scan(&term.expr, probe_source, scan_ctx))
                || filter.as_deref().is_some_and(|expr| {
                    probe_expr_references_outer_scan(expr, probe_source, scan_ctx)
                })
                || over.as_ref().is_some_and(|spec| {
                    probe_window_spec_references_outer_scan(spec, probe_source, scan_ctx)
                })
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand.as_ref().is_some_and(|inner| {
                probe_expr_references_outer_scan(inner, probe_source, scan_ctx)
            }) || whens.iter().any(|(cond, then_expr)| {
                probe_expr_references_outer_scan(cond, probe_source, scan_ctx)
                    || probe_expr_references_outer_scan(then_expr, probe_source, scan_ctx)
            }) || else_expr.as_ref().is_some_and(|inner| {
                probe_expr_references_outer_scan(inner, probe_source, scan_ctx)
            })
        }
        Expr::Like {
            expr: inner,
            pattern,
            escape,
            ..
        } => {
            probe_expr_references_outer_scan(inner, probe_source, scan_ctx)
                || probe_expr_references_outer_scan(pattern, probe_source, scan_ctx)
                || escape.as_ref().is_some_and(|inner| {
                    probe_expr_references_outer_scan(inner, probe_source, scan_ctx)
                })
        }
        Expr::JsonAccess {
            expr: inner, path, ..
        } => {
            probe_expr_references_outer_scan(inner, probe_source, scan_ctx)
                || probe_expr_references_outer_scan(path, probe_source, scan_ctx)
        }
        Expr::RowValue(items, _) => items
            .iter()
            .any(|item| probe_expr_references_outer_scan(item, probe_source, scan_ctx)),
        // As above, nested SELECT scoping is deliberately unsupported here.
        Expr::Exists { .. } | Expr::Subquery(_, _) => true,
        Expr::Literal(_, _)
        | Expr::BoundOuterValue { .. }
        | Expr::Placeholder(_, _)
        | Expr::Raise { .. } => false,
    }
}

fn probe_window_spec_references_outer_scan(
    spec: &fsqlite_ast::WindowSpec,
    probe_source: &InProbeSource<'_>,
    scan_ctx: &ScanCtx<'_>,
) -> bool {
    spec.partition_by
        .iter()
        .any(|expr| probe_expr_references_outer_scan(expr, probe_source, scan_ctx))
        || spec
            .order_by
            .iter()
            .any(|term| probe_expr_references_outer_scan(&term.expr, probe_source, scan_ctx))
        || spec.frame.as_ref().is_some_and(|frame| {
            probe_frame_bound_references_outer_scan(&frame.start, probe_source, scan_ctx)
                || frame.end.as_ref().is_some_and(|bound| {
                    probe_frame_bound_references_outer_scan(bound, probe_source, scan_ctx)
                })
        })
}

fn probe_frame_bound_references_outer_scan(
    bound: &fsqlite_ast::FrameBound,
    probe_source: &InProbeSource<'_>,
    scan_ctx: &ScanCtx<'_>,
) -> bool {
    match bound {
        fsqlite_ast::FrameBound::Preceding(expr) | fsqlite_ast::FrameBound::Following(expr) => {
            probe_expr_references_outer_scan(expr, probe_source, scan_ctx)
        }
        fsqlite_ast::FrameBound::UnboundedPreceding
        | fsqlite_ast::FrameBound::CurrentRow
        | fsqlite_ast::FrameBound::UnboundedFollowing => false,
    }
}

fn in_probe_source_references_outer_scan(
    probe_source: &InProbeSource<'_>,
    scan_ctx: &ScanCtx<'_>,
) -> bool {
    probe_source.where_clause.is_some_and(|where_expr| {
        probe_expr_references_outer_scan(where_expr, probe_source, scan_ctx)
    }) || matches!(
        probe_source.value,
        InProbeValue::Expr(expr)
            if probe_expr_references_outer_scan(expr, probe_source, scan_ctx)
    )
}

fn can_use_once_materialized_in_probe_source(
    probe_source: &InProbeSource<'_>,
    _operand: &Expr,
    scan_ctx: &ScanCtx<'_>,
) -> bool {
    if in_probe_source_references_outer_scan(probe_source, scan_ctx) {
        return false;
    }
    true
}

fn expr_contains_nested_subquery(expr: &Expr) -> bool {
    match expr {
        Expr::Exists { .. } | Expr::Subquery(_, _) => true,
        Expr::BinaryOp { left, right, .. } => {
            expr_contains_nested_subquery(left) || expr_contains_nested_subquery(right)
        }
        Expr::UnaryOp { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::Collate { expr, .. }
        | Expr::IsNull { expr, .. } => expr_contains_nested_subquery(expr),
        Expr::Between {
            expr, low, high, ..
        } => {
            expr_contains_nested_subquery(expr)
                || expr_contains_nested_subquery(low)
                || expr_contains_nested_subquery(high)
        }
        Expr::In { expr, set, .. } => {
            expr_contains_nested_subquery(expr)
                || match set {
                    InSet::List(values) => values.iter().any(expr_contains_nested_subquery),
                    InSet::Table(_) | InSet::Subquery(_) => true,
                }
        }
        Expr::Like {
            expr,
            pattern,
            escape,
            ..
        } => {
            expr_contains_nested_subquery(expr)
                || expr_contains_nested_subquery(pattern)
                || escape.as_deref().is_some_and(expr_contains_nested_subquery)
        }
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            operand
                .as_deref()
                .is_some_and(expr_contains_nested_subquery)
                || whens.iter().any(|(when_expr, then_expr)| {
                    expr_contains_nested_subquery(when_expr)
                        || expr_contains_nested_subquery(then_expr)
                })
                || else_expr
                    .as_deref()
                    .is_some_and(expr_contains_nested_subquery)
        }
        Expr::FunctionCall {
            args,
            order_by,
            filter,
            over,
            ..
        } => {
            over.is_some()
                || match args {
                    FunctionArgs::Star => false,
                    FunctionArgs::List(values) => values.iter().any(expr_contains_nested_subquery),
                }
                || order_by
                    .iter()
                    .any(|term| expr_contains_nested_subquery(&term.expr))
                || filter.as_deref().is_some_and(expr_contains_nested_subquery)
        }
        Expr::JsonAccess {
            expr: inner, path, ..
        } => expr_contains_nested_subquery(inner) || expr_contains_nested_subquery(path),
        Expr::RowValue(values, _) => values.iter().any(expr_contains_nested_subquery),
        _ => false,
    }
}

fn can_use_once_materialized_exists_subquery(
    where_clause: Option<&Expr>,
    table: &TableSchema,
    table_alias: Option<&str>,
    outer_ctx: &ScanCtx<'_>,
) -> bool {
    let Some(where_expr) = where_clause else {
        return true;
    };
    if expr_contains_nested_subquery(where_expr) {
        return false;
    }
    let probe_source = InProbeSource {
        table,
        table_alias,
        where_clause: Some(where_expr),
        value: InProbeValue::FirstColumn,
    };
    !probe_expr_references_outer_scan(where_expr, &probe_source, outer_ctx)
}

fn emit_once_materialized_in_list(
    b: &mut ProgramBuilder,
    operand: &Expr,
    values: &[Expr],
    not: bool,
    reg: i32,
    ctx: Option<&ScanCtx<'_>>,
) {
    let r_operand = b.alloc_temp();
    emit_expr(b, operand, r_operand, ctx);

    // SQLite applies the operand's affinity to both the materialized IN-set
    // values and the probe key (bd-cfmf6/bd-56aj2): an INTEGER operand coerces
    // text list literals to numbers before they enter / are probed against the
    // ephemeral autoindex. `None` means BLOB/NONE affinity (no coercion).
    let in_aff_str: Option<String> = u8::try_from(in_operand_affinity_p5(operand, ctx))
        .ok()
        .filter(|&code| code != 0)
        .map(|code| (code as char).to_string());

    let null_label = b.emit_label();
    let found_label = b.emit_label();
    let done_label = b.emit_label();
    b.emit_jump_to_label(Opcode::IsNull, r_operand, 0, null_label, P4::None, 0);

    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let autoindex_cursor = 4096 + b.current_addr() as i32;
    let r_saw_null = b.alloc_reg();
    let build_done = b.emit_label();
    b.emit_jump_to_label(Opcode::Once, 0, 0, build_done, P4::None, 0);
    b.emit_op(Opcode::Integer, 0, r_saw_null, 0, P4::None, 0);
    let autoindex_collation = effective_collation_ctx(operand, ctx)
        .map_or(P4::None, |coll| P4::Collation(coll.to_owned()));
    b.emit_op(
        Opcode::OpenAutoindex,
        autoindex_cursor,
        1,
        0,
        autoindex_collation,
        0,
    );
    let r_value = b.alloc_temp();
    let r_key = b.alloc_temp();
    for value_expr in values {
        emit_expr(b, value_expr, r_value, ctx);
        if let Some(ref aff) = in_aff_str {
            b.emit_op(
                Opcode::Affinity,
                r_value,
                1,
                0,
                P4::Affinity(aff.clone()),
                0,
            );
        }
        let next_value = b.emit_label();
        let saw_null_label = b.emit_label();
        b.emit_jump_to_label(Opcode::IsNull, r_value, 0, saw_null_label, P4::None, 0);
        b.emit_op(Opcode::MakeRecord, r_value, 1, r_key, P4::None, 0);
        b.emit_op(Opcode::IdxInsert, autoindex_cursor, r_key, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, next_value, P4::None, 0);
        b.resolve_label(saw_null_label);
        b.emit_op(Opcode::Integer, 1, r_saw_null, 0, P4::None, 0);
        b.resolve_label(next_value);
    }
    b.free_temp(r_key);
    b.free_temp(r_value);
    b.resolve_label(build_done);

    let r_probe_key = b.alloc_temp();
    if let Some(ref aff) = in_aff_str {
        b.emit_op(
            Opcode::Affinity,
            r_operand,
            1,
            0,
            P4::Affinity(aff.clone()),
            0,
        );
    }
    b.emit_op(Opcode::MakeRecord, r_operand, 1, r_probe_key, P4::None, 0);
    b.emit_jump_to_label(
        Opcode::Found,
        autoindex_cursor,
        r_probe_key,
        found_label,
        P4::None,
        0,
    );
    b.free_temp(r_probe_key);

    b.emit_jump_to_label(Opcode::If, r_saw_null, 0, null_label, P4::None, 0);
    b.emit_op(Opcode::Integer, i32::from(not), reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

    b.resolve_label(found_label);
    b.emit_op(Opcode::Integer, i32::from(!not), reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

    b.resolve_label(null_label);
    b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
    b.resolve_label(done_label);
    b.free_temp(r_operand);
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_once_materialized_in_probe_source(
    b: &mut ProgramBuilder,
    operand: &Expr,
    probe_source: &InProbeSource<'_>,
    not: bool,
    reg: i32,
    scan_ctx: &ScanCtx<'_>,
    schema: &[TableSchema],
) {
    let r_operand = b.alloc_temp();

    let null_label = b.emit_label();
    let found_label = b.emit_label();
    let done_label = b.emit_label();

    let source_cursor = 8192 + b.current_addr() as i32;
    let autoindex_cursor = 12288 + b.current_addr() as i32;
    let r_saw_null = b.alloc_reg();
    let r_rhs_nonempty = b.alloc_reg();
    let probe_scan = ScanCtx {
        cursor: source_cursor,
        table: probe_source.table,
        table_alias: probe_source.table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };
    let build_done = b.emit_label();
    b.emit_jump_to_label(Opcode::Once, 0, 0, build_done, P4::None, 0);
    b.emit_op(Opcode::Integer, 0, r_saw_null, 0, P4::None, 0);
    b.emit_op(Opcode::Integer, 0, r_rhs_nonempty, 0, P4::None, 0);
    let autoindex_collation =
        in_probe_comparison_collation(operand, scan_ctx, probe_source, &probe_scan)
            .map_or(P4::None, P4::Collation);
    b.emit_op(
        Opcode::OpenAutoindex,
        autoindex_cursor,
        1,
        0,
        autoindex_collation,
        0,
    );
    b.emit_op(
        Opcode::OpenRead,
        source_cursor,
        probe_source.table.root_page,
        0,
        P4::Table(probe_source.table.name.clone()),
        0,
    );

    let build_scan_done = b.emit_label();
    let build_scan_start = b.current_addr();
    b.emit_jump_to_label(
        Opcode::Rewind,
        source_cursor,
        0,
        build_scan_done,
        P4::None,
        0,
    );

    let skip_label = probe_source.where_clause.map(|_| b.emit_label());
    if let (Some(where_expr), Some(skip)) = (probe_source.where_clause, skip_label) {
        emit_where_filter(
            b,
            where_expr,
            source_cursor,
            probe_source.table,
            probe_source.table_alias,
            schema,
            skip,
        );
    }

    // Apply the comparison affinity between the outer operand and the subquery
    // probe column to both the materialized values and the probe key, mirroring
    // the per-row IN-subquery path (bd-56aj2 IN-subquery).
    let probe_aff = in_probe_value_affinity(probe_source, &probe_scan);
    let in_aff_str: Option<String> = u8::try_from(combine_comparison_affinity(
        expr_affinity(operand, Some(scan_ctx)),
        probe_aff,
    ))
    .ok()
    .filter(|&code| code != 0)
    .map(|code| (code as char).to_string());
    let r_value = b.alloc_temp();
    let r_key = b.alloc_temp();
    b.emit_op(Opcode::Integer, 1, r_rhs_nonempty, 0, P4::None, 0);
    emit_in_probe_value(b, source_cursor, probe_source, r_value, &probe_scan);
    if let Some(ref aff) = in_aff_str {
        b.emit_op(
            Opcode::Affinity,
            r_value,
            1,
            0,
            P4::Affinity(aff.clone()),
            0,
        );
    }
    let next_value = b.emit_label();
    let saw_null_label = b.emit_label();
    b.emit_jump_to_label(Opcode::IsNull, r_value, 0, saw_null_label, P4::None, 0);
    b.emit_op(Opcode::MakeRecord, r_value, 1, r_key, P4::None, 0);
    b.emit_op(Opcode::IdxInsert, autoindex_cursor, r_key, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, next_value, P4::None, 0);
    b.resolve_label(saw_null_label);
    b.emit_op(Opcode::Integer, 1, r_saw_null, 0, P4::None, 0);
    b.resolve_label(next_value);

    if let Some(skip) = skip_label {
        b.resolve_label(skip);
    }
    let loop_body = (build_scan_start + 1) as i32;
    b.emit_op(Opcode::Next, source_cursor, loop_body, 0, P4::None, 0);
    b.resolve_label(build_scan_done);
    b.emit_op(Opcode::Close, source_cursor, 0, 0, P4::None, 0);
    b.free_temp(r_key);
    b.free_temp(r_value);
    b.resolve_label(build_done);

    emit_expr(b, operand, r_operand, Some(scan_ctx));

    let r_probe_key = b.alloc_temp();
    if let Some(ref aff) = in_aff_str {
        b.emit_op(
            Opcode::Affinity,
            r_operand,
            1,
            0,
            P4::Affinity(aff.clone()),
            0,
        );
    }
    b.emit_op(Opcode::MakeRecord, r_operand, 1, r_probe_key, P4::None, 0);
    b.emit_jump_to_label(
        Opcode::Found,
        autoindex_cursor,
        r_probe_key,
        found_label,
        P4::None,
        0,
    );
    b.free_temp(r_probe_key);

    b.emit_jump_to_label(Opcode::If, r_saw_null, 0, null_label, P4::None, 0);
    let definite_miss = b.emit_label();
    let check_null_operand = b.emit_label();
    b.emit_jump_to_label(
        Opcode::IsNull,
        r_operand,
        0,
        check_null_operand,
        P4::None,
        0,
    );
    b.emit_jump_to_label(Opcode::Goto, 0, 0, definite_miss, P4::None, 0);
    b.resolve_label(check_null_operand);
    b.emit_jump_to_label(Opcode::If, r_rhs_nonempty, 0, null_label, P4::None, 0);
    b.resolve_label(definite_miss);
    b.emit_op(Opcode::Integer, i32::from(not), reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

    b.resolve_label(found_label);
    b.emit_op(Opcode::Integer, i32::from(!not), reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

    b.resolve_label(null_label);
    b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
    b.resolve_label(done_label);
    b.free_temp(r_operand);
}

fn extract_exists_rowid_probe<'a>(
    where_expr: &'a Expr,
    table: &'a TableSchema,
    table_alias: Option<&'a str>,
) -> Option<(&'a Expr, Vec<&'a Expr>)> {
    let mut terms = Vec::new();
    flatten_and_terms(where_expr, &mut terms);

    let mut probe_expr = None;
    let mut residual_terms = Vec::new();
    for term in terms {
        if let Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::Eq,
            right,
            ..
        } = term
        {
            let left_rowid = matches!(
                resolve_column_ref(left, table, table_alias),
                Some(SortKeySource::Rowid)
            );
            let right_rowid = matches!(
                resolve_column_ref(right, table, table_alias),
                Some(SortKeySource::Rowid)
            );
            if left_rowid
                && !expr_references_scan(right, table, table_alias)
                && !expr_contains_bound_outer_value(right)
                && !expr_contains_nested_subquery(right)
                && probe_expr.is_none()
            {
                probe_expr = Some(right.as_ref());
                continue;
            }
            if right_rowid
                && !expr_references_scan(left, table, table_alias)
                && !expr_contains_bound_outer_value(left)
                && !expr_contains_nested_subquery(left)
                && probe_expr.is_none()
            {
                probe_expr = Some(left.as_ref());
                continue;
            }
        }
        residual_terms.push(term);
    }

    probe_expr.map(|probe| (probe, residual_terms))
}

#[allow(clippy::too_many_arguments)]
fn emit_once_materialized_exists_subquery(
    b: &mut ProgramBuilder,
    table: &TableSchema,
    table_alias: Option<&str>,
    where_clause: Option<&Expr>,
    not: bool,
    reg: i32,
    outer_ctx: &ScanCtx<'_>,
    schema: &[TableSchema],
) {
    let sub_cursor = outer_ctx.cursor + 128;
    let cached_reg = b.alloc_reg();
    let build_done = b.emit_label();
    b.emit_jump_to_label(Opcode::Once, 0, 0, build_done, P4::None, 0);

    let default_val = i32::from(not);
    b.emit_op(Opcode::Integer, default_val, cached_reg, 0, P4::None, 0);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::OpenRead,
        sub_cursor,
        table.root_page as i32,
        0,
        P4::Int(table.columns.len() as i32),
        0,
    );

    let sub_ctx = ScanCtx {
        cursor: sub_cursor,
        table,
        table_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };

    let scan_done = b.emit_label();
    let rewind_addr = b.current_addr();
    b.emit_jump_to_label(Opcode::Rewind, sub_cursor, 0, scan_done, P4::None, 0);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = (rewind_addr + 1) as i32;

    if let Some(where_expr) = where_clause {
        let r_cond = b.alloc_temp();
        let next_label = b.emit_label();
        emit_expr_with_fallback(b, where_expr, r_cond, &sub_ctx, Some(outer_ctx));
        b.emit_jump_to_label(Opcode::IfNot, r_cond, 1, next_label, P4::None, 0);
        b.free_temp(r_cond);
        b.emit_op(Opcode::Integer, i32::from(!not), cached_reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, scan_done, P4::None, 0);
        b.resolve_label(next_label);
    } else {
        b.emit_op(Opcode::Integer, i32::from(!not), cached_reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, scan_done, P4::None, 0);
    }

    b.emit_op(Opcode::Next, sub_cursor, loop_body, 0, P4::None, 0);
    b.resolve_label(scan_done);
    b.emit_op(Opcode::Close, sub_cursor, 0, 0, P4::None, 0);
    b.resolve_label(build_done);
    b.emit_op(Opcode::Copy, cached_reg, reg, 0, P4::None, 0);
}

#[allow(clippy::too_many_lines)]
fn emit_exists_subquery(
    b: &mut ProgramBuilder,
    subquery: &SelectStatement,
    not: bool,
    reg: i32,
    outer_ctx: &ScanCtx<'_>,
    schema: &[TableSchema],
) {
    // Extract the subquery's FROM table and WHERE clause.
    let (from, where_clause) = match &subquery.body.select {
        SelectCore::Select {
            from, where_clause, ..
        } => (from, where_clause),
        _ => {
            let val = i32::from(not);
            b.emit_op(Opcode::Integer, val, reg, 0, P4::None, 0);
            return;
        }
    };

    let from_clause = match from {
        Some(f) => f,
        None => {
            // EXISTS on a no-FROM query like `EXISTS (SELECT 1)` — always true.
            let val = i32::from(!not);
            b.emit_op(Opcode::Integer, val, reg, 0, P4::None, 0);
            return;
        }
    };

    let (table_name, sub_alias) = match &from_clause.source {
        fsqlite_ast::TableOrSubquery::Table { name, alias, .. } => (&name.name, alias.as_deref()),
        _ => {
            let val = i32::from(not);
            b.emit_op(Opcode::Integer, val, reg, 0, P4::None, 0);
            return;
        }
    };

    let table = match find_table(schema, table_name) {
        Ok(t) => t,
        Err(_) => {
            let val = i32::from(not);
            b.emit_op(Opcode::Integer, val, reg, 0, P4::None, 0);
            return;
        }
    };

    // Use cursor offset far from the main scan cursors.
    let sub_cursor = outer_ctx.cursor + 128;
    let done_label = b.emit_label();

    // Default result: 0 (not found) for EXISTS, 1 for NOT EXISTS.
    let default_val = i32::from(not);
    b.emit_op(Opcode::Integer, default_val, reg, 0, P4::None, 0);

    // Open a read cursor on the subquery table.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::OpenRead,
        sub_cursor,
        table.root_page as i32,
        0,
        P4::Int(table.columns.len() as i32),
        0,
    );

    let sub_ctx = ScanCtx {
        cursor: sub_cursor,
        table,
        table_alias: sub_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };

    if subquery.with.is_none()
        && subquery.body.compounds.is_empty()
        && subquery.order_by.is_empty()
        && subquery.limit.is_none()
        && from_clause.joins.is_empty()
        && matches!(
            &subquery.body.select,
            SelectCore::Select {
                group_by,
                having,
                windows,
                ..
            } if group_by.is_empty() && having.is_none() && windows.is_empty()
        )
        && can_use_once_materialized_exists_subquery(
            where_clause.as_deref(),
            table,
            sub_alias,
            outer_ctx,
        )
    {
        emit_once_materialized_exists_subquery(
            b,
            table,
            sub_alias,
            where_clause.as_deref(),
            not,
            reg,
            outer_ctx,
            schema,
        );
        return;
    }

    if let Some(where_expr) = where_clause
        && let Some((probe_expr, residual_terms)) =
            extract_exists_rowid_probe(where_expr, table, sub_alias)
    {
        let probe_reg = b.alloc_temp();
        emit_expr_with_fallback(b, probe_expr, probe_reg, &sub_ctx, Some(outer_ctx));
        b.emit_jump_to_label(Opcode::IsNull, probe_reg, 0, done_label, P4::None, 0);
        b.emit_jump_to_label(
            Opcode::SeekRowid,
            sub_cursor,
            probe_reg,
            done_label,
            P4::None,
            0,
        );
        b.free_temp(probe_reg);

        for residual_term in residual_terms {
            let residual_reg = b.alloc_temp();
            emit_expr_with_fallback(b, residual_term, residual_reg, &sub_ctx, Some(outer_ctx));
            b.emit_jump_to_label(Opcode::IfNot, residual_reg, 1, done_label, P4::None, 0);
            b.free_temp(residual_reg);
        }

        let found_val = i32::from(!not);
        b.emit_op(Opcode::Integer, found_val, reg, 0, P4::None, 0);
        b.resolve_label(done_label);
        b.emit_op(Opcode::Close, sub_cursor, 0, 0, P4::None, 0);
        return;
    }

    let rewind_addr = b.current_addr();
    b.emit_jump_to_label(Opcode::Rewind, sub_cursor, 0, done_label, P4::None, 0);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = (rewind_addr + 1) as i32;

    // Apply WHERE filter if present.
    if let Some(where_expr) = where_clause {
        let r_cond = b.alloc_temp();
        emit_expr_with_fallback(b, where_expr, r_cond, &sub_ctx, Some(outer_ctx));
        let next_label = b.emit_label();
        b.emit_jump_to_label(Opcode::IfNot, r_cond, 1, next_label, P4::None, 0);
        b.free_temp(r_cond);

        // Row matches WHERE — found.
        let found_val = i32::from(!not);
        b.emit_op(Opcode::Integer, found_val, reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

        b.resolve_label(next_label);
    } else {
        // No WHERE — if any row exists, result is found.
        let found_val = i32::from(!not);
        b.emit_op(Opcode::Integer, found_val, reg, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
    }

    // Next row.
    b.emit_op(Opcode::Next, sub_cursor, loop_body, 0, P4::None, 0);

    // Fall through: no row matched.
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

    b.resolve_label(done_label);
    b.emit_op(Opcode::Close, sub_cursor, 0, 0, P4::None, 0);
}

/// Emit the first scalar result expression against an already-positioned
/// single-table subquery cursor.
fn emit_scalar_subquery_result_value(
    b: &mut ProgramBuilder,
    columns: &[ResultColumn],
    reg: i32,
    sub_ctx: &ScanCtx<'_>,
    outer_ctx: &ScanCtx<'_>,
) {
    match columns.first() {
        Some(ResultColumn::Expr { expr, .. }) => {
            emit_expr_with_fallback(b, expr, reg, sub_ctx, Some(outer_ctx));
        }
        Some(ResultColumn::Star | ResultColumn::TableStar(_))
            if sub_ctx.table.columns.len() == 1 =>
        {
            emit_table_column_read(
                b,
                sub_ctx.cursor,
                sub_ctx.table,
                sub_ctx.table_alias,
                sub_ctx.schema,
                0,
                reg,
            );
        }
        _ => {}
    }
}

/// Emit bytecode for a scalar subquery expression `(SELECT expr FROM ...)`.
///
/// Evaluates the subquery and places the first result value into `reg`.
/// If the subquery returns no rows, `reg` is set to NULL.
#[allow(clippy::too_many_lines)]
fn emit_scalar_subquery(
    b: &mut ProgramBuilder,
    subquery: &SelectStatement,
    reg: i32,
    outer_ctx: &ScanCtx<'_>,
    schema: &[TableSchema],
) {
    let (columns, from, where_clause, group_by, having) = match &subquery.body.select {
        SelectCore::Select {
            columns,
            from,
            where_clause,
            group_by,
            having,
            ..
        } => (columns, from, where_clause, group_by, having),
        _ => {
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            return;
        }
    };

    // No-FROM scalar subquery: `(SELECT 1)`, `(SELECT 1 + 2)`.
    if from.is_none() {
        if let Some(ResultColumn::Expr { expr, .. }) = columns.first() {
            emit_expr(b, expr, reg, Some(outer_ctx));
            return;
        }
        b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
        return;
    }

    let from_clause = from.as_ref().expect("checked is_none() above");
    let (table_name, sub_alias) = match &from_clause.source {
        fsqlite_ast::TableOrSubquery::Table { name, alias, .. } => (&name.name, alias.as_deref()),
        _ => {
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            return;
        }
    };

    let table = match find_table(schema, table_name) {
        Ok(t) => t,
        Err(_) => {
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            return;
        }
    };

    // Keep each scalar source open across outer rows without colliding with
    // complex-IN or sibling scalar-subquery cursors.
    let sub_cursor = b.alloc_aux_cursor_range(1);

    let done_label = b.emit_label();

    // Default: NULL (subquery returns no rows).
    b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);

    let open_done = b.emit_label();
    b.emit_jump_to_label(Opcode::Once, 0, 0, open_done, P4::None, 0);
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    b.emit_op(
        Opcode::OpenRead,
        sub_cursor,
        table.root_page as i32,
        0,
        P4::Int(table.columns.len() as i32),
        0,
    );
    b.resolve_label(open_done);

    let sub_ctx = ScanCtx {
        cursor: sub_cursor,
        table,
        table_alias: sub_alias,
        schema: Some(schema),
        register_base: None,
        secondaries: &[],
    };

    // Check if this is an aggregate query (e.g., SELECT MAX(x) FROM t).
    let is_agg = has_aggregate_columns(columns);

    if is_agg && group_by.is_empty() {
        if is_simple_count_star(columns) && having.is_none() {
            emit_scalar_count_star_subquery(b, &sub_ctx, outer_ctx, where_clause.as_deref(), reg);
        } else {
            // Simple aggregate subquery without GROUP BY:
            // e.g., (SELECT COUNT(*) FROM t), (SELECT MAX(x) FROM t WHERE ...)
            emit_scalar_aggregate_subquery(
                b,
                columns,
                &sub_ctx,
                outer_ctx,
                where_clause.as_deref(),
                reg,
                done_label,
            );
        }
    } else {
        if let Some(where_expr) = where_clause
            && let Some((probe_expr, residual_terms)) =
                extract_exists_rowid_probe(where_expr, table, sub_alias)
        {
            let probe_reg = b.alloc_temp();
            emit_expr_with_fallback(b, probe_expr, probe_reg, &sub_ctx, Some(outer_ctx));
            b.emit_jump_to_label(Opcode::IsNull, probe_reg, 0, done_label, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::SeekRowid,
                sub_cursor,
                probe_reg,
                done_label,
                P4::None,
                0,
            );
            b.free_temp(probe_reg);

            for residual_term in residual_terms {
                let residual_reg = b.alloc_temp();
                emit_expr_with_fallback(b, residual_term, residual_reg, &sub_ctx, Some(outer_ctx));
                b.emit_jump_to_label(Opcode::IfNot, residual_reg, 1, done_label, P4::None, 0);
                b.free_temp(residual_reg);
            }

            emit_scalar_subquery_result_value(b, columns, reg, &sub_ctx, outer_ctx);

            b.resolve_label(done_label);
            return;
        }

        // GH #172: an ORDER BY (with optional LIMIT/OFFSET) selects a specific
        // ordered row, not the first row in scan order. Route to a sorter-based
        // path that materializes the matching rows, sorts by the ORDER BY terms,
        // and reads the (OFFSET+1)-th result value. (An OFFSET without ORDER BY
        // has an unspecified order in SQLite, so that keeps the first-row scan.)
        if subquery.order_by.is_empty() {
            // Non-aggregate scalar subquery: grab first row's first column value.
            let rewind_addr = b.current_addr();
            b.emit_jump_to_label(Opcode::Rewind, sub_cursor, 0, done_label, P4::None, 0);
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let loop_body = (rewind_addr + 1) as i32;

            // Apply WHERE filter.
            let next_label = b.emit_label();
            if let Some(where_expr) = where_clause {
                let r_cond = b.alloc_temp();
                emit_expr_with_fallback(b, where_expr, r_cond, &sub_ctx, Some(outer_ctx));
                b.emit_jump_to_label(Opcode::IfNot, r_cond, 1, next_label, P4::None, 0);
                b.free_temp(r_cond);
            }

            // Evaluate the first result column expression.
            emit_scalar_subquery_result_value(b, columns, reg, &sub_ctx, outer_ctx);

            // Got our value — jump to done (only need one row).
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

            b.resolve_label(next_label);
            b.emit_op(Opcode::Next, sub_cursor, loop_body, 0, P4::None, 0);
        } else {
            emit_scalar_subquery_ordered(
                b,
                subquery,
                columns,
                sub_cursor,
                &sub_ctx,
                outer_ctx,
                where_clause.as_deref(),
                reg,
                done_label,
            );
        }
    }

    b.resolve_label(done_label);
}

/// GH #172: emit an ordered non-aggregate scalar subquery.
///
/// Materializes every WHERE-matching row of the subquery into a sorter as
/// `[order_key_0, .., order_key_{n-1}, result_value]`, sorts by the ORDER BY
/// directions, skips `OFFSET` rows, and reads the result value of the next row
/// into `reg`. `reg` is left as its pre-set NULL default when the subquery
/// yields no row at the requested offset (empty match set, `OFFSET` past the
/// end, or `LIMIT 0`). The caller resolves `done_label`.
#[allow(
    clippy::too_many_arguments,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap
)]
fn emit_scalar_subquery_ordered(
    b: &mut ProgramBuilder,
    subquery: &SelectStatement,
    columns: &[ResultColumn],
    sub_cursor: i32,
    sub_ctx: &ScanCtx<'_>,
    outer_ctx: &ScanCtx<'_>,
    where_clause: Option<&Expr>,
    reg: i32,
    done_label: crate::Label,
) {
    let n_key = subquery.order_by.len();
    // Sort-direction string: '+' ascending (default) / '-' descending per term.
    let dir: String = subquery
        .order_by
        .iter()
        .map(|term| match term.direction {
            Some(SortDirection::Desc) => '-',
            _ => '+',
        })
        .collect();

    // LIMIT 0 short-circuits to NULL before any work.
    if let Some(limit) = subquery.limit.as_ref() {
        let r_lim = b.alloc_temp();
        emit_expr(b, &limit.limit, r_lim, Some(outer_ctx));
        // IfPos jumps (and decrements) when > 0; fall through means <= 0 -> NULL.
        let lim_ok = b.emit_label();
        b.emit_jump_to_label(Opcode::IfPos, r_lim, 0, lim_ok, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
        b.resolve_label(lim_ok);
        b.free_temp(r_lim);
    }

    let sorter_cursor = b.alloc_aux_cursor_range(1);
    b.emit_op(
        Opcode::SorterOpen,
        sorter_cursor,
        n_key as i32,
        0,
        P4::Str(dir),
        0,
    );

    // Scan the subquery source, filter by WHERE, and insert
    // [order_keys.., result_value] into the sorter.
    let scan_done = b.emit_label();
    let rewind_addr = b.current_addr();
    b.emit_jump_to_label(Opcode::Rewind, sub_cursor, 0, scan_done, P4::None, 0);
    let loop_body = (rewind_addr + 1) as i32;

    let skip_label = b.emit_label();
    if let Some(where_expr) = where_clause {
        let r_cond = b.alloc_temp();
        emit_expr_with_fallback(b, where_expr, r_cond, sub_ctx, Some(outer_ctx));
        b.emit_jump_to_label(Opcode::IfNot, r_cond, 1, skip_label, P4::None, 0);
        b.free_temp(r_cond);
    }

    let rec_regs = b.alloc_regs((n_key + 1) as i32);
    for (j, term) in subquery.order_by.iter().enumerate() {
        emit_expr_with_fallback(b, &term.expr, rec_regs + j as i32, sub_ctx, Some(outer_ctx));
    }
    emit_scalar_subquery_result_value(b, columns, rec_regs + n_key as i32, sub_ctx, outer_ctx);
    let rec_reg = b.alloc_reg();
    b.emit_op(
        Opcode::MakeRecord,
        rec_regs,
        (n_key + 1) as i32,
        rec_reg,
        P4::None,
        0,
    );
    b.emit_op(Opcode::SorterInsert, sorter_cursor, rec_reg, 0, P4::None, 0);

    b.resolve_label(skip_label);
    b.emit_op(Opcode::Next, sub_cursor, loop_body, 0, P4::None, 0);
    b.resolve_label(scan_done);

    // Sort; SorterSort jumps to `close` when the sorter is empty (NULL stays).
    let close_label = b.emit_label();
    b.emit_jump_to_label(
        Opcode::SorterSort,
        sorter_cursor,
        0,
        close_label,
        P4::None,
        0,
    );

    // Skip OFFSET rows (default 0). IfPos decrements r_off and jumps to
    // `advance` while positive; falling through means offset exhausted -> read.
    if let Some(offset_expr) = subquery.limit.as_ref().and_then(|l| l.offset.as_ref()) {
        let r_off = b.alloc_temp();
        emit_expr(b, offset_expr, r_off, Some(outer_ctx));
        let skip_check = b.emit_label();
        let advance = b.emit_label();
        let read = b.emit_label();
        b.resolve_label(skip_check);
        b.emit_jump_to_label(Opcode::IfPos, r_off, 1, advance, P4::None, 0);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, read, P4::None, 0);
        b.resolve_label(advance);
        // SorterNext jumps to skip_check when another row exists; otherwise the
        // sorter is exhausted mid-skip and the result stays NULL.
        b.emit_jump_to_label(
            Opcode::SorterNext,
            sorter_cursor,
            0,
            skip_check,
            P4::None,
            0,
        );
        b.emit_jump_to_label(Opcode::Goto, 0, 0, close_label, P4::None, 0);
        b.resolve_label(read);
        b.free_temp(r_off);
    }

    // Materialize the current sorter record, then read the result value (the
    // final field, at index n_key) into `reg`.
    let scratch = b.alloc_reg();
    b.emit_op(Opcode::SorterData, sorter_cursor, scratch, 0, P4::None, 0);
    b.emit_op(
        Opcode::Column,
        sorter_cursor,
        n_key as i32,
        reg,
        P4::None,
        0,
    );

    b.resolve_label(close_label);
    b.emit_op(Opcode::Close, sorter_cursor, 0, 0, P4::None, 0);
}

fn emit_scalar_count_star_subquery(
    b: &mut ProgramBuilder,
    sub_ctx: &ScanCtx<'_>,
    outer_ctx: &ScanCtx<'_>,
    where_clause: Option<&Expr>,
    reg: i32,
) {
    if where_clause.is_none() {
        b.emit_op(Opcode::Count, sub_ctx.cursor, reg, 0, P4::None, 0);
        return;
    }

    b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);

    let finalize_label = b.emit_label();
    let rewind_addr = b.current_addr();
    b.emit_jump_to_label(
        Opcode::Rewind,
        sub_ctx.cursor,
        0,
        finalize_label,
        P4::None,
        0,
    );
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = (rewind_addr + 1) as i32;

    let skip_label = b.emit_label();
    if let Some(where_expr) = where_clause {
        let r_cond = b.alloc_temp();
        emit_expr_with_fallback(b, where_expr, r_cond, sub_ctx, Some(outer_ctx));
        b.emit_jump_to_label(Opcode::IfNot, r_cond, 1, skip_label, P4::None, 0);
        b.free_temp(r_cond);
    }

    b.emit_op(Opcode::AddImm, reg, 1, 0, P4::None, 0);
    b.resolve_label(skip_label);
    b.emit_op(Opcode::Next, sub_ctx.cursor, loop_body, 0, P4::None, 0);
    b.resolve_label(finalize_label);
}

/// Emit bytecode for a simple aggregate scalar subquery (no GROUP BY).
///
/// Handles `(SELECT COUNT(*) FROM t)`, `(SELECT MAX(x) FROM t WHERE ...)`, etc.
fn emit_scalar_aggregate_subquery(
    b: &mut ProgramBuilder,
    columns: &[ResultColumn],
    sub_ctx: &ScanCtx<'_>,
    outer_ctx: &ScanCtx<'_>,
    where_clause: Option<&Expr>,
    reg: i32,
    _done_label: crate::Label,
) {
    // Parse the aggregate columns.
    let Ok(agg_cols) = parse_aggregate_columns(columns, sub_ctx.table) else {
        return;
    };

    if agg_cols.is_empty() {
        return;
    }

    let accum_reg = b.alloc_temp();
    b.emit_op(Opcode::Null, 0, accum_reg, 0, P4::None, 0);

    let finalize_label = b.emit_label();
    let rewind_addr = b.current_addr();
    b.emit_jump_to_label(
        Opcode::Rewind,
        sub_ctx.cursor,
        0,
        finalize_label,
        P4::None,
        0,
    );
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let loop_body = (rewind_addr + 1) as i32;

    // Apply WHERE filter.
    let skip_label = b.emit_label();
    if let Some(where_expr) = where_clause {
        let r_cond = b.alloc_temp();
        emit_expr_with_fallback(b, where_expr, r_cond, sub_ctx, Some(outer_ctx));
        b.emit_jump_to_label(Opcode::IfNot, r_cond, 1, skip_label, P4::None, 0);
        b.free_temp(r_cond);
    }

    // Separate real (hidden) aggregates from the output entry (which may
    // have a wrapper_expr for complex expressions like COUNT(*) - 1).
    let real_aggs: Vec<&AggColumn> = agg_cols.iter().filter(|a| !a.name.is_empty()).collect();
    let output_entry = agg_cols.last();

    // Allocate one accumulator per real aggregate.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let accum_base = if real_aggs.len() > 1 {
        b.alloc_regs(real_aggs.len() as i32)
    } else {
        accum_reg
    };

    // Initialize all accumulators to NULL.
    for i in 0..real_aggs.len() {
        #[allow(clippy::cast_possible_wrap)]
        b.emit_op(Opcode::Null, 0, accum_base + i as i32, 0, P4::None, 0);
    }

    // AggStep for each real aggregate in the loop body.
    for (i, agg) in real_aggs.iter().enumerate() {
        let total_args = agg.num_args.max(1);
        let arg_base = b.alloc_regs(total_args);
        if agg.num_args > 0 {
            if agg.arg_is_rowid {
                b.emit_op(Opcode::Rowid, sub_ctx.cursor, arg_base, 0, P4::None, 0);
            } else if let Some(expr) = &agg.arg_expr {
                emit_expr_with_fallback(b, expr, arg_base, sub_ctx, Some(outer_ctx));
            } else if let Some(col_idx) = agg.arg_col_index {
                #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                b.emit_op(
                    Opcode::Column,
                    sub_ctx.cursor,
                    col_idx as i32,
                    arg_base,
                    P4::None,
                    0,
                );
            }
            for (j, extra_expr) in agg.extra_args.iter().enumerate() {
                #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                let extra_reg = arg_base + 1 + j as i32;
                emit_expr_with_fallback(b, extra_expr, extra_reg, sub_ctx, Some(outer_ctx));
            }
        }

        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        {
            let num_args = agg.num_args as u16;
            let distinct_flag = i32::from(agg.distinct);
            b.emit_op(
                Opcode::AggStep,
                distinct_flag,
                arg_base,
                accum_base + i as i32,
                P4::FuncName(agg.name.clone()),
                num_args,
            );
        }
    }

    b.resolve_label(skip_label);
    b.emit_op(Opcode::Next, sub_ctx.cursor, loop_body, 0, P4::None, 0);

    // Finalize all accumulators.
    b.resolve_label(finalize_label);
    for (i, agg) in real_aggs.iter().enumerate() {
        #[allow(clippy::cast_possible_wrap)]
        b.emit_op(
            Opcode::AggFinal,
            accum_base + i as i32,
            agg.num_args,
            0,
            P4::FuncName(agg.name.clone()),
            0,
        );
    }

    // Evaluate wrapper expression or copy the single result.
    if let Some(entry) = output_entry {
        if let Some(ref wrapper) = entry.wrapper_expr {
            if entry.multi_agg_indices.is_empty() {
                // Simple wrapper (e.g. COUNT(*) - 1): evaluate the wrapper
                // expression with __agg_result__ mapped to accum_reg.
                emit_simple_agg_wrapper(b, wrapper, reg, accum_reg);
            } else {
                emit_multi_agg_wrapper(b, wrapper, reg, accum_base, &entry.multi_agg_indices);
            }
        } else {
            b.emit_op(Opcode::Copy, accum_base, reg, 0, P4::None, 0);
        }
    } else {
        b.emit_op(Opcode::Copy, accum_base, reg, 0, P4::None, 0);
    }

    if real_aggs.len() > 1 {
        // Free the extra accumulators (accum_reg was already allocated).
    }
    b.free_temp(accum_reg);
}

/// Evaluate an expression with fallback context for correlated subqueries.
///
/// For column references, tries the inner (subquery) context first; if the
/// column doesn't belong to the inner table, falls back to the outer context.
/// For compound expressions, recurses so nested column refs get fallback logic.
fn fallback_declared_collation(
    expr: &Expr,
    inner_ctx: &ScanCtx<'_>,
    outer_ctx: Option<&ScanCtx<'_>>,
) -> Option<String> {
    declared_collation_ctx(expr, Some(inner_ctx))
        .or_else(|| outer_ctx.and_then(|outer| declared_collation_ctx(expr, Some(outer))))
        .map(str::to_owned)
}

fn fallback_comparison_collation(
    left: &Expr,
    right: &Expr,
    inner_ctx: &ScanCtx<'_>,
    outer_ctx: Option<&ScanCtx<'_>>,
) -> Option<String> {
    extract_collation(left)
        .or_else(|| extract_collation(right))
        .map(str::to_owned)
        .or_else(|| fallback_declared_collation(left, inner_ctx, outer_ctx))
        .or_else(|| fallback_declared_collation(right, inner_ctx, outer_ctx))
}

fn fallback_effective_collation(
    expr: &Expr,
    inner_ctx: &ScanCtx<'_>,
    outer_ctx: Option<&ScanCtx<'_>>,
) -> Option<String> {
    extract_collation(expr)
        .map(str::to_owned)
        .or_else(|| fallback_declared_collation(expr, inner_ctx, outer_ctx))
}

fn fallback_scalar_function_collation<'expr>(
    args: impl IntoIterator<Item = &'expr Expr>,
    inner_ctx: &ScanCtx<'_>,
    outer_ctx: Option<&ScanCtx<'_>>,
) -> Option<String> {
    args.into_iter().find_map(|argument| {
        extract_collation(argument)
            .map(str::to_owned)
            .or_else(|| fallback_declared_collation(argument, inner_ctx, outer_ctx))
    })
}

fn emit_expr_with_fallback(
    b: &mut ProgramBuilder,
    expr: &Expr,
    reg: i32,
    inner_ctx: &ScanCtx<'_>,
    outer_ctx: Option<&ScanCtx<'_>>,
) {
    match expr {
        Expr::BoundOuterValue { value, .. } => emit_sqlite_value(b, value, reg),
        Expr::Column(col_ref, _) => {
            if column_ref_resolves_in_ctx(col_ref, inner_ctx) {
                emit_expr(b, expr, reg, Some(inner_ctx));
            } else if let Some(outer) =
                outer_ctx.filter(|outer| column_ref_resolves_in_ctx(col_ref, outer))
            {
                emit_expr(b, expr, reg, Some(outer));
            } else {
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            }
        }
        Expr::BinaryOp {
            left, op, right, ..
        } => {
            // Recursively resolve column refs in children, then apply the op.
            let r_left = b.alloc_temp();
            let r_right = b.alloc_temp();
            emit_expr_with_fallback(b, left, r_left, inner_ctx, outer_ctx);
            emit_expr_with_fallback(b, right, r_right, inner_ctx, outer_ctx);

            if matches!(
                op,
                fsqlite_ast::BinaryOp::Eq
                    | fsqlite_ast::BinaryOp::Ne
                    | fsqlite_ast::BinaryOp::Lt
                    | fsqlite_ast::BinaryOp::Le
                    | fsqlite_ast::BinaryOp::Gt
                    | fsqlite_ast::BinaryOp::Ge
            ) {
                let cmp_opcode = match op {
                    fsqlite_ast::BinaryOp::Eq => Opcode::Eq,
                    fsqlite_ast::BinaryOp::Ne => Opcode::Ne,
                    fsqlite_ast::BinaryOp::Lt => Opcode::Lt,
                    fsqlite_ast::BinaryOp::Le => Opcode::Le,
                    fsqlite_ast::BinaryOp::Gt => Opcode::Gt,
                    fsqlite_ast::BinaryOp::Ge => Opcode::Ge,
                    _ => unreachable!(),
                };
                // SQL three-valued logic: if either operand is NULL, result is NULL.
                let null_label = b.emit_label();
                let true_label = b.emit_label();
                let done_label = b.emit_label();
                let comparison_collation =
                    fallback_comparison_collation(left, right, inner_ctx, outer_ctx)
                        .map_or(P4::None, P4::Collation);
                let comparison_affinity = combine_comparison_affinity(
                    fallback_expr_affinity(left, inner_ctx, outer_ctx),
                    fallback_expr_affinity(right, inner_ctx, outer_ctx),
                );
                b.emit_jump_to_label(Opcode::IsNull, r_left, 0, null_label, P4::None, 0);
                b.emit_jump_to_label(Opcode::IsNull, r_right, 0, null_label, P4::None, 0);
                b.emit_jump_to_label(
                    cmp_opcode,
                    r_right,
                    r_left,
                    true_label,
                    comparison_collation,
                    comparison_affinity,
                );
                b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
                b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                b.resolve_label(true_label);
                b.emit_op(Opcode::Integer, 1, reg, 0, P4::None, 0);
                b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                b.resolve_label(null_label);
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                b.resolve_label(done_label);
            } else if matches!(op, fsqlite_ast::BinaryOp::Is | fsqlite_ast::BinaryOp::IsNot) {
                if let Some((p3, p4)) = is_true_false_params(*op, right) {
                    b.emit_op(Opcode::IsTrue, r_left, reg, p3, p4, 0);
                } else {
                    let (cmp_opcode, flag) = match op {
                        fsqlite_ast::BinaryOp::Is => (Opcode::Eq, 0x80_u16),
                        _ => (Opcode::Ne, 0x80_u16),
                    };
                    let true_label = b.emit_label();
                    let done_label = b.emit_label();
                    let comparison_collation =
                        fallback_comparison_collation(left, right, inner_ctx, outer_ctx)
                            .map_or(P4::None, P4::Collation);
                    let comparison_affinity = combine_comparison_affinity(
                        fallback_expr_affinity(left, inner_ctx, outer_ctx),
                        fallback_expr_affinity(right, inner_ctx, outer_ctx),
                    );
                    b.emit_jump_to_label(
                        cmp_opcode,
                        r_right,
                        r_left,
                        true_label,
                        comparison_collation,
                        flag | comparison_affinity,
                    );
                    b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    b.resolve_label(true_label);
                    b.emit_op(Opcode::Integer, 1, reg, 0, P4::None, 0);
                    b.resolve_label(done_label);
                }
            } else {
                // Arithmetic / logical / bitwise.
                // VDBE convention: P3 = P2 op P1 (P1=rhs, P2=lhs).
                let vdbe_op = binary_op_to_opcode(*op);
                b.emit_op(vdbe_op, r_right, r_left, reg, P4::None, 0);
            }
            b.free_temp(r_left);
            b.free_temp(r_right);
        }
        Expr::UnaryOp {
            op, expr: inner, ..
        } => {
            emit_expr_with_fallback(b, inner, reg, inner_ctx, outer_ctx);
            match op {
                fsqlite_ast::UnaryOp::Negate => {
                    let tmp = b.alloc_temp();
                    b.emit_op(Opcode::Integer, -1, tmp, 0, P4::None, 0);
                    b.emit_op(Opcode::Multiply, tmp, reg, reg, P4::None, 0);
                    b.free_temp(tmp);
                }
                fsqlite_ast::UnaryOp::Plus => {}
                fsqlite_ast::UnaryOp::BitNot => {
                    b.emit_op(Opcode::BitNot, reg, reg, 0, P4::None, 0);
                }
                fsqlite_ast::UnaryOp::Not => {
                    b.emit_op(Opcode::Not, reg, reg, 0, P4::None, 0);
                }
            }
        }
        // ── BETWEEN ─────────────────────────────────────────────────────
        Expr::Between {
            expr: operand,
            low,
            high,
            not,
            ..
        } => {
            let r_operand = b.alloc_temp();
            let r_low = b.alloc_temp();
            let r_high = b.alloc_temp();
            emit_expr_with_fallback(b, operand, r_operand, inner_ctx, outer_ctx);
            emit_expr_with_fallback(b, low, r_low, inner_ctx, outer_ctx);
            emit_expr_with_fallback(b, high, r_high, inner_ctx, outer_ctx);
            let low_collation = fallback_comparison_collation(operand, low, inner_ctx, outer_ctx)
                .map_or(P4::None, P4::Collation);
            let high_collation = fallback_comparison_collation(operand, high, inner_ctx, outer_ctx)
                .map_or(P4::None, P4::Collation);
            let low_affinity = combine_comparison_affinity(
                fallback_expr_affinity(operand, inner_ctx, outer_ctx),
                fallback_expr_affinity(low, inner_ctx, outer_ctx),
            );
            let high_affinity = combine_comparison_affinity(
                fallback_expr_affinity(operand, inner_ctx, outer_ctx),
                fallback_expr_affinity(high, inner_ctx, outer_ctx),
            );
            let false_label = b.emit_label();
            let null_label = b.emit_label();
            let done_label = b.emit_label();
            b.emit_jump_to_label(Opcode::IsNull, r_operand, 0, null_label, P4::None, 0);
            b.emit_jump_to_label(
                Opcode::Lt,
                r_low,
                r_operand,
                false_label,
                low_collation,
                low_affinity,
            );
            b.emit_jump_to_label(
                Opcode::Gt,
                r_high,
                r_operand,
                false_label,
                high_collation,
                high_affinity,
            );
            b.emit_jump_to_label(Opcode::IsNull, r_low, 0, null_label, P4::None, 0);
            b.emit_jump_to_label(Opcode::IsNull, r_high, 0, null_label, P4::None, 0);
            b.emit_op(Opcode::Integer, i32::from(!*not), reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
            b.resolve_label(false_label);
            b.emit_op(Opcode::Integer, i32::from(*not), reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
            b.resolve_label(null_label);
            b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            b.resolve_label(done_label);
            b.free_temp(r_high);
            b.free_temp(r_low);
            b.free_temp(r_operand);
        }
        // ── LIKE / GLOB ────────────────────────────────────────────────
        Expr::Like {
            expr: operand,
            pattern,
            not,
            escape,
            op: like_op,
            ..
        } => {
            if use_builtin_like_glob_semantics()
                && matches!(like_op, fsqlite_ast::LikeOp::Like)
                && escape.is_none()
                && let Expr::Literal(Literal::String(pattern_text), _) = pattern.as_ref()
                && let Some((kind, literal)) = classify_sql_like_fast_path(pattern_text, None)
            {
                emit_expr_with_fallback(b, operand, reg, inner_ctx, outer_ctx);
                b.emit_op(
                    Opcode::LikeConstFast,
                    reg,
                    reg,
                    kind.opcode_tag(),
                    P4::Str(literal.to_owned()),
                    u16::from(*not),
                );
                return;
            }

            let func_name = match like_op {
                fsqlite_ast::LikeOp::Like => "LIKE",
                fsqlite_ast::LikeOp::Glob => "GLOB",
                fsqlite_ast::LikeOp::Match => "MATCH",
                fsqlite_ast::LikeOp::Regexp => "REGEXP",
            };
            let nargs: u16 = if escape.is_some() { 3 } else { 2 };
            let arg_base = b.alloc_regs(i32::from(nargs));
            // like(pattern, string [, escape])
            emit_expr_with_fallback(b, pattern, arg_base, inner_ctx, outer_ctx);
            emit_expr_with_fallback(b, operand, arg_base + 1, inner_ctx, outer_ctx);
            if let Some(esc) = escape {
                emit_expr_with_fallback(b, esc, arg_base + 2, inner_ctx, outer_ctx);
            }
            let function_p4 =
                if scalar_consumes_argument_collation_for_codegen(func_name, i32::from(nargs)) {
                    fallback_scalar_function_collation(
                        [pattern.as_ref(), operand.as_ref()]
                            .into_iter()
                            .chain(escape.as_deref()),
                        inner_ctx,
                        outer_ctx,
                    )
                    .map_or_else(
                        || P4::FuncName(func_name.to_owned()),
                        |collation| P4::FuncNameCollated(func_name.to_owned(), collation),
                    )
                } else {
                    P4::FuncName(func_name.to_owned())
                };
            b.emit_op(Opcode::PureFunc, 0, arg_base, reg, function_p4, nargs);
            if *not {
                b.emit_op(Opcode::Not, reg, reg, 0, P4::None, 0);
            }
        }
        // ── JSON extraction operators ─────────────────────────────────
        Expr::JsonAccess {
            expr: inner,
            path,
            arrow,
            ..
        } => {
            let arg_base = b.alloc_regs(2);
            emit_expr_with_fallback(b, inner, arg_base, inner_ctx, outer_ctx);
            emit_expr_with_fallback(b, path, arg_base + 1, inner_ctx, outer_ctx);
            let function_name = json_access_func_name(*arrow);
            let function_p4 = if scalar_consumes_argument_collation_for_codegen(function_name, 2) {
                fallback_scalar_function_collation(
                    [inner.as_ref(), path.as_ref()],
                    inner_ctx,
                    outer_ctx,
                )
                .map_or_else(
                    || P4::FuncName(function_name.to_owned()),
                    |collation| P4::FuncNameCollated(function_name.to_owned(), collation),
                )
            } else {
                P4::FuncName(function_name.to_owned())
            };
            b.emit_op(Opcode::PureFunc, 0, arg_base, reg, function_p4, 2);
        }
        // ── Function call ──────────────────────────────────────────────
        Expr::FunctionCall { name, args, .. } => {
            let canon = name.to_ascii_uppercase();
            match args {
                fsqlite_ast::FunctionArgs::Star => {
                    b.emit_op(Opcode::PureFunc, 0, 0, reg, P4::FuncName(canon), 0);
                }
                fsqlite_ast::FunctionArgs::List(arg_list) => {
                    if try_emit_column_substr_prefix(b, name, arg_list, reg, inner_ctx)
                        || try_emit_column_octet_length(b, name, arg_list, reg, inner_ctx)
                        || outer_ctx.is_some_and(|outer| {
                            try_emit_column_substr_prefix(b, name, arg_list, reg, outer)
                                || try_emit_column_octet_length(b, name, arg_list, reg, outer)
                        })
                    {
                        return;
                    }
                    let Ok(nargs) = u16::try_from(arg_list.len()) else {
                        b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                        return;
                    };
                    let arg_base = b.alloc_regs(i32::from(nargs));
                    for (i, arg_expr) in arg_list.iter().enumerate() {
                        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
                        emit_expr_with_fallback(
                            b,
                            arg_expr,
                            arg_base + i as i32,
                            inner_ctx,
                            outer_ctx,
                        );
                    }
                    let function_p4 =
                        if scalar_consumes_argument_collation_for_codegen(&canon, i32::from(nargs))
                        {
                            fallback_scalar_function_collation(arg_list, inner_ctx, outer_ctx)
                                .map_or_else(
                                    || P4::FuncName(canon.clone()),
                                    |collation| P4::FuncNameCollated(canon.clone(), collation),
                                )
                        } else {
                            P4::FuncName(canon.clone())
                        };
                    b.emit_op(Opcode::PureFunc, 0, arg_base, reg, function_p4, nargs);
                }
            }
        }
        // ── CASE ───────────────────────────────────────────────────────
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => {
            let done_label = b.emit_label();
            if let Some(op_expr) = operand {
                let r_op = b.alloc_temp();
                emit_expr_with_fallback(b, op_expr, r_op, inner_ctx, outer_ctx);
                let op_aff = fallback_expr_affinity(op_expr, inner_ctx, outer_ctx);
                for (when_expr, then_expr) in whens {
                    let r_when = b.alloc_temp();
                    emit_expr_with_fallback(b, when_expr, r_when, inner_ctx, outer_ctx);
                    let next = b.emit_label();
                    // Simple CASE desugars to `operand = when`; apply comparison
                    // affinity like a plain `=` would (bd-w4r25).
                    let cmp_aff = combine_comparison_affinity(
                        op_aff,
                        fallback_expr_affinity(when_expr, inner_ctx, outer_ctx),
                    );
                    let comparison_collation =
                        fallback_comparison_collation(op_expr, when_expr, inner_ctx, outer_ctx)
                            .map_or(P4::None, P4::Collation);
                    b.emit_jump_to_label(Opcode::IsNull, r_op, 0, next, P4::None, 0);
                    b.emit_jump_to_label(Opcode::IsNull, r_when, 0, next, P4::None, 0);
                    b.emit_jump_to_label(
                        Opcode::Ne,
                        r_when,
                        r_op,
                        next,
                        comparison_collation,
                        cmp_aff,
                    );
                    b.free_temp(r_when);
                    emit_expr_with_fallback(b, then_expr, reg, inner_ctx, outer_ctx);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    b.resolve_label(next);
                }
                b.free_temp(r_op);
            } else {
                for (when_expr, then_expr) in whens {
                    // Searched CASE WHEN is a TRUTH context: short-circuit AND/OR
                    // left-to-right so a would-be-skipped erroring operand is
                    // never evaluated (bd-and-or-short-circuit-value-jump-gaps-dkswh
                    // GAP-2). Non-AND/OR conditions emit byte-identically.
                    let next = b.emit_label();
                    emit_searched_case_when_condition_with_fallback(
                        b, when_expr, next, inner_ctx, outer_ctx,
                    );
                    emit_expr_with_fallback(b, then_expr, reg, inner_ctx, outer_ctx);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    b.resolve_label(next);
                }
            }
            if let Some(el) = else_expr {
                emit_expr_with_fallback(b, el, reg, inner_ctx, outer_ctx);
            } else {
                b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
            }
            b.resolve_label(done_label);
        }
        // ── IN (list) ──────────────────────────────────────────────────
        Expr::In {
            expr: operand,
            set,
            not,
            ..
        } => {
            if let fsqlite_ast::InSet::List(values) = set {
                if values.is_empty() {
                    b.emit_op(Opcode::Integer, i32::from(*not), reg, 0, P4::None, 0);
                } else {
                    let r_op = b.alloc_temp();
                    emit_expr_with_fallback(b, operand, r_op, inner_ctx, outer_ctx);
                    // Apply the operand's affinity to each list value (bd-cfmf6/bd-56aj2).
                    let in_aff = combine_comparison_affinity(
                        fallback_expr_affinity(operand, inner_ctx, outer_ctx),
                        b'A',
                    );
                    let found_label = b.emit_label();
                    let done_label = b.emit_label();
                    let null_label = b.emit_label();
                    b.emit_jump_to_label(Opcode::IsNull, r_op, 0, null_label, P4::None, 0);
                    let in_collation =
                        if values.len() == 1 && singleton_in_rhs_is_constant(&values[0]) {
                            fallback_comparison_collation(operand, &values[0], inner_ctx, outer_ctx)
                        } else {
                            fallback_effective_collation(operand, inner_ctx, outer_ctx)
                        };
                    let comparison_p4 = in_collation.map_or(P4::None, P4::Collation);
                    let r_saw_null = b.alloc_temp();
                    b.emit_op(Opcode::Integer, 0, r_saw_null, 0, P4::None, 0);
                    let r_val = b.alloc_temp();
                    for val in values {
                        emit_expr_with_fallback(b, val, r_val, inner_ctx, outer_ctx);
                        b.emit_jump_to_label(
                            Opcode::Eq,
                            r_val,
                            r_op,
                            found_label,
                            comparison_p4.clone(),
                            in_aff,
                        );
                        let next_value = b.emit_label();
                        let mark_null = b.emit_label();
                        b.emit_jump_to_label(Opcode::IsNull, r_val, 0, mark_null, P4::None, 0);
                        b.emit_jump_to_label(Opcode::Goto, 0, 0, next_value, P4::None, 0);
                        b.resolve_label(mark_null);
                        b.emit_op(Opcode::Integer, 1, r_saw_null, 0, P4::None, 0);
                        b.resolve_label(next_value);
                    }
                    b.free_temp(r_val);
                    b.emit_jump_to_label(Opcode::If, r_saw_null, 0, null_label, P4::None, 0);
                    b.free_temp(r_saw_null);
                    b.emit_op(Opcode::Integer, i32::from(*not), reg, 0, P4::None, 0);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    b.resolve_label(found_label);
                    b.emit_op(Opcode::Integer, i32::from(!*not), reg, 0, P4::None, 0);
                    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
                    b.resolve_label(null_label);
                    b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
                    b.resolve_label(done_label);
                    b.free_temp(r_op);
                }
            } else {
                // Subquery / table IN — delegate to inner context.
                emit_expr(b, expr, reg, Some(inner_ctx));
            }
        }
        // ── CAST ───────────────────────────────────────────────────────
        Expr::Cast {
            expr: inner,
            type_name,
            ..
        } => {
            emit_expr_with_fallback(b, inner, reg, inner_ctx, outer_ctx);
            let affinity = type_name_to_affinity(type_name);
            if affinity != 0 {
                b.emit_op(
                    Opcode::Affinity,
                    reg,
                    1,
                    0,
                    P4::Str(String::from(affinity as char)),
                    0,
                );
            }
        }
        // ── IS [NOT] NULL ──────────────────────────────────────────────
        Expr::IsNull {
            expr: inner, not, ..
        } => {
            emit_expr_with_fallback(b, inner, reg, inner_ctx, outer_ctx);
            let lbl_null = b.emit_label();
            let lbl_done = b.emit_label();
            b.emit_jump_to_label(Opcode::IsNull, reg, 0, lbl_null, P4::None, 0);
            let val_not_null = i32::from(*not);
            let val_null = i32::from(!*not);
            b.emit_op(Opcode::Integer, val_not_null, reg, 0, P4::None, 0);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, lbl_done, P4::None, 0);
            b.resolve_label(lbl_null);
            b.emit_op(Opcode::Integer, val_null, reg, 0, P4::None, 0);
            b.resolve_label(lbl_done);
        }
        // ── Collate ────────────────────────────────────────────────────
        Expr::Collate { expr: inner, .. } => {
            emit_expr_with_fallback(b, inner, reg, inner_ctx, outer_ctx);
        }
        // ── Remaining types: delegate to inner context ─────────────────
        _ => {
            emit_expr(b, expr, reg, Some(inner_ctx));
        }
    }
}

/// Check if a column reference resolves in a given scan context.
fn resolve_column_in_ctx(col_ref: &ColumnRef, ctx: &ScanCtx<'_>) -> Option<usize> {
    // Qualified: table.column (case-insensitive per SQL standard)
    if let Some(ref table_name) = col_ref.table {
        // When the table has an alias, only the alias matches qualified
        // references. This prevents `inventory.col` from resolving to
        // `FROM inventory i2` — only `i2.col` should match.
        let table_match = if let Some(alias) = ctx.table_alias {
            table_name.eq_ignore_ascii_case(alias)
        } else {
            table_name.eq_ignore_ascii_case(&ctx.table.name)
        };
        if table_match {
            return ctx
                .table
                .columns
                .iter()
                .position(|c| c.name.eq_ignore_ascii_case(&col_ref.column));
        }
        return None;
    }
    // Unqualified: just column name
    ctx.table
        .columns
        .iter()
        .position(|c| c.name.eq_ignore_ascii_case(&col_ref.column))
}

fn column_ref_resolves_in_ctx(col_ref: &ColumnRef, ctx: &ScanCtx<'_>) -> bool {
    if resolve_column_in_ctx(col_ref, ctx).is_some() {
        return true;
    }
    if let Some(qualifier) = col_ref.table.as_deref() {
        if matches_table_or_alias(qualifier, ctx.table, ctx.table_alias) {
            return ctx.table.resolves_to_hidden_rowid(&col_ref.column);
        }
        return ctx.secondaries.iter().any(|secondary| {
            matches_table_or_alias(qualifier, secondary.table, secondary.table_alias)
                && table_has_column_or_rowid(secondary.table, &col_ref.column)
        });
    }
    ctx.table.resolves_to_hidden_rowid(&col_ref.column)
        || ctx
            .secondaries
            .iter()
            .any(|secondary| table_has_column_or_rowid(secondary.table, &col_ref.column))
}

/// Map an AST `BinaryOp` to the corresponding VDBE opcode.
fn binary_op_to_opcode(op: fsqlite_ast::BinaryOp) -> Opcode {
    match op {
        fsqlite_ast::BinaryOp::Add => Opcode::Add,
        fsqlite_ast::BinaryOp::Subtract => Opcode::Subtract,
        fsqlite_ast::BinaryOp::Multiply => Opcode::Multiply,
        fsqlite_ast::BinaryOp::Divide => Opcode::Divide,
        fsqlite_ast::BinaryOp::Modulo => Opcode::Remainder,
        fsqlite_ast::BinaryOp::Concat => Opcode::Concat,
        fsqlite_ast::BinaryOp::BitAnd => Opcode::BitAnd,
        fsqlite_ast::BinaryOp::BitOr => Opcode::BitOr,
        fsqlite_ast::BinaryOp::ShiftLeft => Opcode::ShiftLeft,
        fsqlite_ast::BinaryOp::ShiftRight => Opcode::ShiftRight,
        fsqlite_ast::BinaryOp::And => Opcode::And,
        fsqlite_ast::BinaryOp::Or => Opcode::Or,
        // Comparison ops use jump instructions; map to Eq as placeholder.
        fsqlite_ast::BinaryOp::Eq
        | fsqlite_ast::BinaryOp::Ne
        | fsqlite_ast::BinaryOp::Lt
        | fsqlite_ast::BinaryOp::Le
        | fsqlite_ast::BinaryOp::Gt
        | fsqlite_ast::BinaryOp::Ge
        | fsqlite_ast::BinaryOp::Is
        | fsqlite_ast::BinaryOp::IsNot => Opcode::Eq, // handled separately
    }
}

/// Emit bytecode for a binary operation expression.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_binary_op(
    b: &mut ProgramBuilder,
    left: &Expr,
    op: fsqlite_ast::BinaryOp,
    right: &Expr,
    reg: i32,
    ctx: Option<&ScanCtx<'_>>,
) {
    // For comparison operators, emit a conditional jump pattern that
    // produces 1 (true) or 0 (false) as an integer result.
    if matches!(
        op,
        fsqlite_ast::BinaryOp::Eq
            | fsqlite_ast::BinaryOp::Ne
            | fsqlite_ast::BinaryOp::Lt
            | fsqlite_ast::BinaryOp::Le
            | fsqlite_ast::BinaryOp::Gt
            | fsqlite_ast::BinaryOp::Ge
    ) {
        emit_comparison(b, left, op, right, reg, ctx);
        return;
    }

    if matches!(op, fsqlite_ast::BinaryOp::Is | fsqlite_ast::BinaryOp::IsNot) {
        emit_is_comparison(b, left, op, right, reg, ctx);
        return;
    }

    // Arithmetic / logical / bitwise: evaluate left into reg, right into tmp,
    // then apply the opcode.
    let tmp = b.alloc_temp();
    emit_expr(b, left, reg, ctx);
    emit_expr(b, right, tmp, ctx);
    let opcode = binary_op_to_opcode(op);
    // VDBE arithmetic: OP p1=rhs, p2=lhs, p3=dest
    b.emit_op(opcode, tmp, reg, reg, P4::None, 0);
    b.free_temp(tmp);
}

/// Extract the leftmost explicit COLLATE from an expression operand.
///
/// SQLite treats a COLLATE operator anywhere inside a comparison operand as
/// explicit for that operand; it is not limited to a wrapper at the root.
/// Nested SELECT scopes and window-control clauses are deliberately excluded:
/// their collations do not become collations of the containing scalar value.
fn extract_collation(expr: &Expr) -> Option<&str> {
    match expr {
        Expr::Collate { collation, .. } => Some(collation.as_str()),
        Expr::BinaryOp { left, right, .. }
        | Expr::JsonAccess {
            expr: left,
            path: right,
            ..
        } => extract_collation(left).or_else(|| extract_collation(right)),
        Expr::UnaryOp { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
            extract_collation(expr)
        }
        Expr::Between {
            expr, low, high, ..
        } => extract_collation(expr)
            .or_else(|| extract_collation(low))
            .or_else(|| extract_collation(high)),
        Expr::In { expr, set, .. } => extract_collation(expr).or_else(|| match set {
            InSet::List(values) => values.iter().find_map(extract_collation),
            InSet::Table(_) | InSet::Subquery(_) => None,
        }),
        Expr::Like {
            expr,
            pattern,
            escape,
            ..
        } => extract_collation(pattern)
            .or_else(|| extract_collation(expr))
            .or_else(|| escape.as_deref().and_then(extract_collation)),
        Expr::Case {
            operand,
            whens,
            else_expr,
            ..
        } => operand
            .as_deref()
            .and_then(extract_collation)
            .or_else(|| {
                whens.iter().find_map(|(when_expr, then_expr)| {
                    extract_collation(when_expr).or_else(|| extract_collation(then_expr))
                })
            })
            .or_else(|| else_expr.as_deref().and_then(extract_collation)),
        Expr::FunctionCall { args, .. } => match args {
            FunctionArgs::Star => None,
            FunctionArgs::List(values) => values.iter().find_map(extract_collation),
        },
        Expr::RowValue(values, _) => values.iter().find_map(extract_collation),
        Expr::Literal(..)
        | Expr::BoundOuterValue { .. }
        | Expr::Column(..)
        | Expr::Exists { .. }
        | Expr::Subquery(..)
        | Expr::Raise { .. }
        | Expr::Placeholder(..) => None,
    }
}

fn join_declared_collation<'a>(
    expr: &'a Expr,
    tables: &[(&'a TableSchema, Option<&str>)],
) -> Option<&'a str> {
    let source = declared_collation_source_expr(expr);
    if let Expr::BoundOuterValue { collation, .. } = source {
        return collation.as_name();
    }
    let Expr::Column(col_ref, _) = source else {
        return None;
    };
    tables.iter().find_map(|(table, alias)| {
        if let Some(qualifier) = col_ref.table.as_deref()
            && !matches_table_or_alias(qualifier, table, *alias)
        {
            return None;
        }
        if let Some(index) = table.column_index(&col_ref.column) {
            return Some(
                table.columns[index]
                    .collation
                    .as_deref()
                    .unwrap_or("BINARY"),
            );
        }
        table
            .resolves_to_hidden_rowid(&col_ref.column)
            .then_some("BINARY")
    })
}

fn join_comparison_collation_name<'a>(
    left: &'a Expr,
    right: &'a Expr,
    tables: &[(&'a TableSchema, Option<&'a str>)],
) -> Option<&'a str> {
    extract_collation(left)
        .or_else(|| extract_collation(right))
        .or_else(|| join_declared_collation(left, tables))
        .or_else(|| join_declared_collation(right, tables))
}

fn join_expr_affinity(expr: &Expr, tables: &[(&TableSchema, Option<&str>)]) -> u8 {
    let inner = strip_collate_wrappers(expr);
    match inner {
        Expr::BoundOuterValue { affinity, .. } => bound_outer_affinity_code(*affinity),
        Expr::Column(col_ref, _) => tables
            .iter()
            .find_map(|(table, alias)| {
                if let Some(qualifier) = col_ref.table.as_deref()
                    && !matches_table_or_alias(qualifier, table, *alias)
                {
                    return None;
                }
                if let Some(index) = table.column_index(&col_ref.column) {
                    return Some(schema_column_expr_affinity(&table.columns[index]));
                }
                table
                    .resolves_to_hidden_rowid(&col_ref.column)
                    .then_some(b'D')
            })
            .unwrap_or(b'A'),
        Expr::Cast { type_name, .. } => type_name_to_affinity(type_name),
        Expr::Subquery(select, _) => {
            scalar_subquery_affinity_in_join(select, tables).unwrap_or(b'A')
        }
        _ => b'A',
    }
}

fn join_comparison_affinity_p5(
    left: &Expr,
    right: &Expr,
    tables: &[(&TableSchema, Option<&str>)],
) -> u16 {
    let left_affinity = join_expr_affinity(left, tables);
    let right_affinity = join_expr_affinity(right, tables);
    let is_numeric = |affinity: u8| matches!(affinity, b'C' | b'D' | b'E');

    if is_numeric(left_affinity) && matches!(right_affinity, b'A' | b'B') {
        return u16::from(b'C');
    }
    if is_numeric(right_affinity) && matches!(left_affinity, b'A' | b'B') {
        return u16::from(b'C');
    }
    if (left_affinity == b'B' && right_affinity == b'A')
        || (left_affinity == b'A' && right_affinity == b'B')
    {
        return u16::from(b'B');
    }
    0
}

/// Extract explicit COLLATE from an ORDER BY term's expression.
#[allow(dead_code)]
fn extract_collation_from_ordering_term(term: &OrderingTerm) -> Option<&str> {
    extract_collation(&term.expr)
}

/// Get the column-level collation for an expression from the table schema.
/// Only checks schema-declared collation (e.g. `TEXT COLLATE NOCASE`), NOT
/// explicit COLLATE wrappers on the expression — use `extract_collation` for that.
/// Returns `None` for BINARY (the default) or when the expression is not a column ref.
fn column_collation<'a>(
    expr: &'a Expr,
    table: &'a TableSchema,
    table_alias: Option<&str>,
) -> Option<&'a str> {
    let inner = declared_collation_source_expr(expr);
    if let Expr::BoundOuterValue { collation, .. } = inner {
        return collation
            .as_name()
            .filter(|collation| !collation.eq_ignore_ascii_case("BINARY"));
    }
    if let Expr::Column(col_ref, _) = inner {
        if let Some(qualifier) = &col_ref.table
            && !matches_table_or_alias(qualifier, table, table_alias)
        {
            return None;
        }
        if let Some(idx) = table.column_index(&col_ref.column) {
            return table.columns[idx].collation.as_deref();
        }
    }
    None
}

/// Resolve the declared collation of the column value carried by `expr`.
///
/// The outer `Option` is deliberately significant: a resolved column with no
/// named declaration still defines the BINARY collation and must stop SQLite's
/// precedence search.  Returning `None` means that the expression does not
/// derive its collation from a column in this scan scope.
fn declared_collation_ctx<'a>(expr: &'a Expr, ctx: Option<&'a ScanCtx<'_>>) -> Option<&'a str> {
    let source = declared_collation_source_expr(expr);
    if let Expr::BoundOuterValue { collation, .. } = source {
        return collation.as_name();
    }
    let ctx = ctx?;
    let Expr::Column(col_ref, _) = source else {
        return None;
    };

    let in_table = |table: &'a TableSchema, alias: Option<&str>| -> Option<&'a str> {
        if col_ref
            .table
            .as_deref()
            .is_some_and(|qualifier| !matches_table_or_alias(qualifier, table, alias))
        {
            return None;
        }
        if let Some(index) = table.column_index(&col_ref.column) {
            return Some(
                table.columns[index]
                    .collation
                    .as_deref()
                    .unwrap_or("BINARY"),
            );
        }
        table
            .resolves_to_hidden_rowid(&col_ref.column)
            .then_some("BINARY")
    };

    if col_ref.table.is_some() {
        return in_table(ctx.table, ctx.table_alias).or_else(|| {
            ctx.secondaries
                .iter()
                .find_map(|secondary| in_table(secondary.table, secondary.table_alias))
        });
    }

    let mut winner = in_table(ctx.table, ctx.table_alias);
    for secondary in ctx.secondaries {
        if let Some(collation) = in_table(secondary.table, secondary.table_alias) {
            if winner.is_some() {
                // Validation reports the ambiguous column before execution.
                // Do not guess a collation if this defensive path is reached.
                return None;
            }
            winner = Some(collation);
        }
    }
    winner
}

/// Resolve a comparison collation with SQLite precedence: an explicit
/// COLLATE on either operand (left wins a tie), then a declared collation on
/// either operand (again left first).  BINARY remains an explicit winner so a
/// later named declaration cannot override it.
fn comparison_collation_ctx(
    left: &Expr,
    right: &Expr,
    ctx: Option<&ScanCtx<'_>>,
) -> Option<String> {
    extract_collation(left)
        .or_else(|| extract_collation(right))
        .map(str::to_owned)
        .or_else(|| declared_collation_ctx(left, ctx).map(str::to_owned))
        .or_else(|| declared_collation_ctx(right, ctx).map(str::to_owned))
}

/// NULLIF and scalar MIN/MAX choose the first argument that defines a
/// collation.  A bare BINARY column therefore stops the search before a later
/// argument's explicit or declared named collation.
fn scalar_function_argument_collation_ctx<'expr>(
    args: impl IntoIterator<Item = &'expr Expr>,
    ctx: Option<&ScanCtx<'_>>,
) -> Option<String> {
    args.into_iter().find_map(|argument| {
        extract_collation(argument)
            .map(str::to_owned)
            .or_else(|| declared_collation_ctx(argument, ctx).map(str::to_owned))
    })
}

/// Reach a column whose declared collation is inherited by this expression.
///
/// SQLite preserves a column's collation through COLLATE (when the explicit
/// wrapper itself is being inspected separately), CAST, and unary plus. Other
/// unary operators produce a new expression with no declared column
/// collation.
fn declared_collation_source_expr(expr: &Expr) -> &Expr {
    match expr {
        Expr::Collate { expr, .. }
        | Expr::Cast { expr, .. }
        | Expr::UnaryOp {
            op: fsqlite_ast::UnaryOp::Plus,
            expr,
            ..
        } => declared_collation_source_expr(expr),
        _ => expr,
    }
}

fn bound_outer_declared_collation(expr: &Expr) -> Option<&str> {
    let Expr::BoundOuterValue { collation, .. } = declared_collation_source_expr(expr) else {
        return None;
    };
    collation.as_name()
}

/// Get effective collation via `ScanCtx`: explicit COLLATE first, then column-level.
fn effective_collation_ctx<'a>(expr: &'a Expr, ctx: Option<&'a ScanCtx<'a>>) -> Option<&'a str> {
    if let Some(coll) = extract_collation(expr) {
        return Some(coll);
    }
    declared_collation_ctx(expr, ctx).filter(|collation| !collation.eq_ignore_ascii_case("BINARY"))
}

/// Emit a comparison expression that produces 1 (true) or 0 (false).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_comparison(
    b: &mut ProgramBuilder,
    left: &Expr,
    op: fsqlite_ast::BinaryOp,
    right: &Expr,
    reg: i32,
    ctx: Option<&ScanCtx<'_>>,
) {
    let r_left = b.alloc_temp();
    let r_right = b.alloc_temp();
    emit_expr(b, left, r_left, ctx);
    emit_expr(b, right, r_right, ctx);

    let cmp_opcode = match op {
        fsqlite_ast::BinaryOp::Eq => Some(Opcode::Eq),
        fsqlite_ast::BinaryOp::Ne => Some(Opcode::Ne),
        fsqlite_ast::BinaryOp::Lt => Some(Opcode::Lt),
        fsqlite_ast::BinaryOp::Le => Some(Opcode::Le),
        fsqlite_ast::BinaryOp::Gt => Some(Opcode::Gt),
        fsqlite_ast::BinaryOp::Ge => Some(Opcode::Ge),
        _ => None,
    };
    let Some(cmp_opcode) = cmp_opcode else {
        b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
        b.free_temp(r_right);
        b.free_temp(r_left);
        return;
    };

    // Check for COLLATE on either operand, then column-level collation.
    let p4 = comparison_collation_ctx(left, right, ctx).map_or(P4::None, P4::Collation);

    // SQL three-valued logic: if either operand is NULL, the result is NULL.
    // Check for NULL before the comparison.
    let null_label = b.emit_label();
    let true_label = b.emit_label();
    let done_label = b.emit_label();

    b.emit_jump_to_label(Opcode::IsNull, r_left, 0, null_label, P4::None, 0);
    b.emit_jump_to_label(Opcode::IsNull, r_right, 0, null_label, P4::None, 0);

    // Compute comparison affinity for TEXT↔numeric coercion (SQLite §4.2).
    let cmp_aff = comparison_affinity_p5(left, right, ctx);

    // Comparison: p1=rhs_reg, p2=jump_target (label), p3=lhs_reg
    b.emit_jump_to_label(cmp_opcode, r_right, r_left, true_label, p4, cmp_aff);
    b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
    b.resolve_label(true_label);
    b.emit_op(Opcode::Integer, 1, reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
    b.resolve_label(null_label);
    b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
    b.resolve_label(done_label);

    b.free_temp(r_right);
    b.free_temp(r_left);
}

/// Emit IS / IS NOT comparison (NULLEQ semantics).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn emit_is_comparison(
    b: &mut ProgramBuilder,
    left: &Expr,
    op: fsqlite_ast::BinaryOp,
    right: &Expr,
    reg: i32,
    ctx: Option<&ScanCtx<'_>>,
) {
    // IS TRUE / IS FALSE / IS NOT TRUE / IS NOT FALSE → IsTrue opcode.
    if let Some((p3, p4)) = is_true_false_params(op, right) {
        let r_left = b.alloc_temp();
        emit_expr(b, left, r_left, ctx);
        b.emit_op(Opcode::IsTrue, r_left, reg, p3, p4, 0);
        b.free_temp(r_left);
        return;
    }

    let r_left = b.alloc_temp();
    let r_right = b.alloc_temp();
    emit_expr(b, left, r_left, ctx);
    emit_expr(b, right, r_right, ctx);

    let true_label = b.emit_label();
    let done_label = b.emit_label();

    // IS uses Eq with NULLEQ flag (p5=0x80). IS NOT uses Ne with NULLEQ.
    let cmp_and_flag = match op {
        fsqlite_ast::BinaryOp::Is => Some((Opcode::Eq, 0x80_u16)),
        fsqlite_ast::BinaryOp::IsNot => Some((Opcode::Ne, 0x80_u16)),
        _ => None,
    };
    let Some((cmp_opcode, nulleq_flag)) = cmp_and_flag else {
        b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
        b.free_temp(r_right);
        b.free_temp(r_left);
        return;
    };

    let p4 = comparison_collation_ctx(left, right, ctx).map_or(P4::None, P4::Collation);

    let comparison_affinity = comparison_affinity_p5(left, right, ctx);
    b.emit_jump_to_label(
        cmp_opcode,
        r_right,
        r_left,
        true_label,
        p4,
        nulleq_flag | comparison_affinity,
    );
    b.emit_op(Opcode::Integer, 0, reg, 0, P4::None, 0);
    b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);
    b.resolve_label(true_label);
    b.emit_op(Opcode::Integer, 1, reg, 0, P4::None, 0);
    b.resolve_label(done_label);

    b.free_temp(r_right);
    b.free_temp(r_left);
}

/// Check if a `BinaryOp::Is/IsNot` with `Literal::True/False` should use
/// the `IsTrue` opcode.  Returns `(p3, p4)` for the IsTrue instruction.
///
/// Mapping:
///   IS TRUE      → (p3=0, P4::None)        — truthy, NULL→0
///   IS FALSE     → (p3=1, P4::Int(1))      — !truthy, NULL→0
///   IS NOT TRUE  → (p3=0, P4::Int(1))      — !truthy, NULL→1
///   IS NOT FALSE → (p3=1, P4::None)        — truthy inverted, NULL→1
fn is_true_false_params(op: fsqlite_ast::BinaryOp, rhs: &Expr) -> Option<(i32, P4)> {
    let is_not = matches!(op, fsqlite_ast::BinaryOp::IsNot);
    match rhs {
        Expr::Literal(Literal::True, _) => {
            if is_not {
                // IS NOT TRUE: p3=0, p4=1
                Some((0, P4::Int(1)))
            } else {
                // IS TRUE: p3=0, p4=0
                Some((0, P4::None))
            }
        }
        Expr::Literal(Literal::False, _) => {
            if is_not {
                // IS NOT FALSE: p3=1, p4=0
                Some((1, P4::None))
            } else {
                // IS FALSE: p3=1, p4=1
                Some((1, P4::Int(1)))
            }
        }
        _ => None,
    }
}

/// Emit CASE \[operand\] WHEN ... THEN ... \[ELSE ...\] END.
fn emit_case_expr(
    b: &mut ProgramBuilder,
    operand: Option<&Expr>,
    whens: &[(Expr, Expr)],
    else_expr: Option<&Expr>,
    reg: i32,
    ctx: Option<&ScanCtx<'_>>,
) {
    let done_label = b.emit_label();
    let r_operand = operand.map(|op_expr| {
        let r = b.alloc_temp();
        emit_expr(b, op_expr, r, ctx);
        r
    });

    for (when_expr, then_expr) in whens {
        let next_when = b.emit_label();

        if let Some(r_op) = r_operand {
            // Simple CASE: compare operand to each WHEN value.
            let r_when = b.alloc_temp();
            emit_expr(b, when_expr, r_when, ctx);
            // NULL in either operand or WHEN value means no match
            // (NULL = x is UNKNOWN in SQL, which is falsy for CASE).
            b.emit_jump_to_label(Opcode::IsNull, r_op, 0, next_when, P4::None, 0);
            b.emit_jump_to_label(Opcode::IsNull, r_when, 0, next_when, P4::None, 0);
            // Simple CASE desugars to `operand = when_value`, so apply the same
            // comparison affinity a plain `=` would (bd-w4r25): an INTEGER
            // operand coerces a text WHEN literal to a number before comparing.
            let cmp_aff =
                operand.map_or(0, |op_expr| comparison_affinity_p5(op_expr, when_expr, ctx));
            let comparison_collation = operand
                .and_then(|op_expr| comparison_collation_ctx(op_expr, when_expr, ctx))
                .map_or(P4::None, P4::Collation);
            // If operand != when_value, skip to next WHEN.
            b.emit_jump_to_label(
                Opcode::Ne,
                r_when,
                r_op,
                next_when,
                comparison_collation,
                cmp_aff,
            );
            b.free_temp(r_when);
        } else {
            // Searched CASE: each WHEN is a boolean condition in a TRUTH context.
            // Stock sqlite3 short-circuits AND/OR left-to-right here (an
            // sqlite3ExprIfFalse analog), so a would-be-skipped operand that
            // errors is never evaluated — matching WHERE-filter behavior
            // (bd-and-or-short-circuit-value-jump-gaps-dkswh GAP-2). A non-AND/OR
            // condition emits byte-identically to the prior eager sequence.
            emit_searched_case_when_condition(b, when_expr, reg, next_when, ctx);
        }

        // Emit THEN expression.
        emit_expr(b, then_expr, reg, ctx);
        b.emit_jump_to_label(Opcode::Goto, 0, 0, done_label, P4::None, 0);

        b.resolve_label(next_when);
    }

    // ELSE clause (or NULL if no ELSE).
    if let Some(el) = else_expr {
        emit_expr(b, el, reg, ctx);
    } else {
        b.emit_op(Opcode::Null, 0, reg, 0, P4::None, 0);
    }

    b.resolve_label(done_label);

    if let Some(r_op) = r_operand {
        b.free_temp(r_op);
    }
}

/// Emit a searched-CASE `WHEN` condition in TRUTH context: jump to `false_label`
/// when the condition is NOT TRUE (i.e. FALSE or NULL), short-circuiting AND/OR
/// left-to-right so a would-be-skipped operand is never evaluated. This mirrors
/// stock sqlite3's `sqlite3ExprIfFalse(jumpIfNull=1)` polarity used for WHERE /
/// CASE-WHEN — the same structure `emit_where_filter_with_ctx` already applies to
/// WHERE conjuncts/disjuncts (bd-and-or-short-circuit-value-jump-gaps-dkswh
/// GAP-2). `scratch` is a register the caller no longer needs after the branch
/// (the WHEN result is transient). A non-AND/OR condition emits exactly the prior
/// eager sequence — `emit_expr(cond, scratch); IfNot scratch,1 -> false_label` —
/// so bytecode is unchanged for every condition except an AND/OR-topped one.
///
/// Three-valued correctness (seeking TRUE):
/// - leaf: `IfNot p2=1` jumps iff cond is FALSE or NULL (i.e. not TRUE);
/// - `A AND B`: jump if either is not TRUE -> taken iff both TRUE;
/// - `A OR B`: if A is TRUE the whole is TRUE (skip B); else the result is B's
///   truth value -> taken iff A TRUE or B TRUE.
fn emit_searched_case_when_condition(
    b: &mut ProgramBuilder,
    cond: &Expr,
    scratch: i32,
    false_label: crate::Label,
    ctx: Option<&ScanCtx<'_>>,
) {
    match cond {
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::And,
            right,
            ..
        } => {
            emit_searched_case_when_condition(b, left, scratch, false_label, ctx);
            emit_searched_case_when_condition(b, right, scratch, false_label, ctx);
        }
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::Or,
            right,
            ..
        } => {
            let left_false = b.emit_label();
            let pass = b.emit_label();
            emit_searched_case_when_condition(b, left, scratch, left_false, ctx);
            b.emit_jump_to_label(Opcode::Goto, 0, 0, pass, P4::None, 0);
            b.resolve_label(left_false);
            emit_searched_case_when_condition(b, right, scratch, false_label, ctx);
            b.resolve_label(pass);
        }
        _ => {
            emit_expr(b, cond, scratch, ctx);
            b.emit_jump_to_label(Opcode::IfNot, scratch, 1, false_label, P4::None, 0);
        }
    }
}

/// Correlation-aware (inner/outer `ScanCtx`) counterpart of
/// [`emit_searched_case_when_condition`], for the searched-CASE arm of
/// `emit_expr_with_fallback`. Leaves are emitted through `emit_expr_with_fallback`
/// (each into its own temp, exactly as the prior eager code did), so outer-column
/// correlation resolution is preserved; only AND/OR-topped conditions change,
/// gaining left-to-right short-circuit.
fn emit_searched_case_when_condition_with_fallback(
    b: &mut ProgramBuilder,
    cond: &Expr,
    false_label: crate::Label,
    inner_ctx: &ScanCtx<'_>,
    outer_ctx: Option<&ScanCtx<'_>>,
) {
    match cond {
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::And,
            right,
            ..
        } => {
            emit_searched_case_when_condition_with_fallback(
                b,
                left,
                false_label,
                inner_ctx,
                outer_ctx,
            );
            emit_searched_case_when_condition_with_fallback(
                b,
                right,
                false_label,
                inner_ctx,
                outer_ctx,
            );
        }
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::Or,
            right,
            ..
        } => {
            let left_false = b.emit_label();
            let pass = b.emit_label();
            emit_searched_case_when_condition_with_fallback(
                b, left, left_false, inner_ctx, outer_ctx,
            );
            b.emit_jump_to_label(Opcode::Goto, 0, 0, pass, P4::None, 0);
            b.resolve_label(left_false);
            emit_searched_case_when_condition_with_fallback(
                b,
                right,
                false_label,
                inner_ctx,
                outer_ctx,
            );
            b.resolve_label(pass);
        }
        _ => {
            let r_when = b.alloc_temp();
            emit_expr_with_fallback(b, cond, r_when, inner_ctx, outer_ctx);
            b.emit_jump_to_label(Opcode::IfNot, r_when, 1, false_label, P4::None, 0);
            b.free_temp(r_when);
        }
    }
}

/// Upsert-context (`ON CONFLICT DO UPDATE`) counterpart of
/// [`emit_searched_case_when_condition`]. Leaves emit through `emit_upsert_expr`
/// (preserving existing/excluded pseudo-table + hidden-rowid dispatch); only
/// AND/OR-topped WHEN conditions change, gaining left-to-right short-circuit so a
/// would-be-skipped erroring operand is never evaluated. Byte-identical for every
/// non-AND/OR condition (bd-and-or-short-circuit GAP-2).
#[allow(clippy::too_many_arguments)]
fn emit_upsert_case_when_condition(
    b: &mut ProgramBuilder,
    cond: &Expr,
    scratch: i32,
    false_label: crate::Label,
    existing_ctx: &ScanCtx<'_>,
    excluded_ctx: &ScanCtx<'_>,
    table: &TableSchema,
    existing_hidden_rowid_reg: Option<i32>,
    excluded_hidden_rowid_reg: i32,
) {
    match cond {
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::And,
            right,
            ..
        } => {
            emit_upsert_case_when_condition(
                b,
                left,
                scratch,
                false_label,
                existing_ctx,
                excluded_ctx,
                table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            emit_upsert_case_when_condition(
                b,
                right,
                scratch,
                false_label,
                existing_ctx,
                excluded_ctx,
                table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
        }
        Expr::BinaryOp {
            left,
            op: fsqlite_ast::BinaryOp::Or,
            right,
            ..
        } => {
            let left_false = b.emit_label();
            let pass = b.emit_label();
            emit_upsert_case_when_condition(
                b,
                left,
                scratch,
                left_false,
                existing_ctx,
                excluded_ctx,
                table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            b.emit_jump_to_label(Opcode::Goto, 0, 0, pass, P4::None, 0);
            b.resolve_label(left_false);
            emit_upsert_case_when_condition(
                b,
                right,
                scratch,
                false_label,
                existing_ctx,
                excluded_ctx,
                table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            b.resolve_label(pass);
        }
        _ => {
            emit_upsert_expr(
                b,
                cond,
                scratch,
                existing_ctx,
                excluded_ctx,
                table,
                existing_hidden_rowid_reg,
                excluded_hidden_rowid_reg,
            );
            b.emit_jump_to_label(Opcode::IfNot, scratch, 1, false_label, P4::None, 0);
        }
    }
}

fn strip_collate_wrappers(mut expr: &Expr) -> &Expr {
    while let Expr::Collate { expr: inner, .. } = expr {
        expr = inner;
    }
    expr
}

#[derive(Clone)]
struct AffinityTableBinding<'a> {
    table: &'a TableSchema,
    alias: Option<String>,
}

enum ScopedColumnAffinity {
    Missing,
    Resolved(u8),
    Ambiguous,
}

fn schema_column_expr_affinity(column: &ColumnInfo) -> u8 {
    if column.is_ipk {
        b'D'
    } else {
        match column.affinity.to_ascii_uppercase() {
            'B' => b'B',
            'C' => b'C',
            'D' => b'D',
            'E' => b'E',
            _ => b'A',
        }
    }
}

fn table_column_expr_affinity(table: &TableSchema, column_name: &str) -> Option<u8> {
    if let Some(index) = table.column_index(column_name) {
        return table.columns.get(index).map(schema_column_expr_affinity);
    }
    table.resolves_to_hidden_rowid(column_name).then_some(b'D')
}

fn column_affinity_in_scope(
    column: &ColumnRef,
    scope: &[AffinityTableBinding<'_>],
) -> ScopedColumnAffinity {
    let mut resolved = None;
    let mut qualifier_matched = false;
    for binding in scope {
        if let Some(qualifier) = column.table.as_deref() {
            if !matches_table_or_alias(qualifier, binding.table, binding.alias.as_deref()) {
                continue;
            }
            qualifier_matched = true;
        }
        let Some(affinity) = table_column_expr_affinity(binding.table, &column.column) else {
            continue;
        };
        if resolved.replace(affinity).is_some() {
            return ScopedColumnAffinity::Ambiguous;
        }
    }
    if let Some(affinity) = resolved {
        ScopedColumnAffinity::Resolved(affinity)
    } else if qualifier_matched {
        // A matching local qualifier shadows outer scopes even when the named
        // column is invalid.  Treat that shape as unprovable rather than
        // accidentally borrowing affinity from an outer table.
        ScopedColumnAffinity::Ambiguous
    } else {
        ScopedColumnAffinity::Missing
    }
}

fn scoped_column_affinity(
    column: &ColumnRef,
    scopes: &[&[AffinityTableBinding<'_>]],
) -> Option<u8> {
    for scope in scopes {
        match column_affinity_in_scope(column, scope) {
            ScopedColumnAffinity::Missing => {}
            ScopedColumnAffinity::Resolved(affinity) => return Some(affinity),
            ScopedColumnAffinity::Ambiguous => return None,
        }
    }
    None
}

fn push_affinity_catalog_table<'a>(catalog: &mut Vec<&'a TableSchema>, table: &'a TableSchema) {
    if !catalog
        .iter()
        .any(|candidate| std::ptr::eq(*candidate, table))
    {
        catalog.push(table);
    }
}

fn extend_affinity_catalog_from_scan<'a>(catalog: &mut Vec<&'a TableSchema>, ctx: &ScanCtx<'a>) {
    if let Some(schema) = ctx.schema {
        for table in schema {
            push_affinity_catalog_table(catalog, table);
        }
    }
    push_affinity_catalog_table(catalog, ctx.table);
    for secondary in ctx.secondaries {
        push_affinity_catalog_table(catalog, secondary.table);
    }
}

fn affinity_scope_from_scan<'a>(ctx: &ScanCtx<'a>) -> Vec<AffinityTableBinding<'a>> {
    std::iter::once(AffinityTableBinding {
        table: ctx.table,
        alias: ctx.table_alias.map(str::to_owned),
    })
    .chain(
        ctx.secondaries
            .iter()
            .map(|secondary| AffinityTableBinding {
                table: secondary.table,
                alias: secondary.table_alias.map(str::to_owned),
            }),
    )
    .collect()
}

fn find_affinity_catalog_table<'a>(
    name: &QualifiedName,
    catalog: &[&'a TableSchema],
) -> Option<&'a TableSchema> {
    // TableSchema does not retain attached-database identity, so a qualified
    // source cannot be proven to name a particular catalog entry here.
    if name.schema.is_some() {
        return None;
    }
    let mut found: Option<&'a TableSchema> = None;
    for table in catalog {
        if !table.name.eq_ignore_ascii_case(&name.name) {
            continue;
        }
        if let Some(previous) = found
            && !std::ptr::eq(previous, *table)
        {
            return None;
        }
        found = Some(*table);
    }
    found
}

fn collect_affinity_source_bindings<'a>(
    source: &TableOrSubquery,
    catalog: &[&'a TableSchema],
    bindings: &mut Vec<AffinityTableBinding<'a>>,
) -> Option<()> {
    match source {
        TableOrSubquery::Table { name, alias, .. } => {
            let table = find_affinity_catalog_table(name, catalog)?;
            bindings.push(AffinityTableBinding {
                table,
                alias: alias.clone(),
            });
            Some(())
        }
        TableOrSubquery::ParenJoin(from) => collect_affinity_from_bindings(from, catalog, bindings),
        // Derived tables and table-valued functions do not expose result
        // affinity metadata through TableSchema.  Decline rather than guessing.
        TableOrSubquery::Subquery { .. } | TableOrSubquery::TableFunction { .. } => None,
    }
}

fn collect_affinity_from_bindings<'a>(
    from: &FromClause,
    catalog: &[&'a TableSchema],
    bindings: &mut Vec<AffinityTableBinding<'a>>,
) -> Option<()> {
    collect_affinity_source_bindings(&from.source, catalog, bindings)?;
    for join in &from.joins {
        collect_affinity_source_bindings(&join.table, catalog, bindings)?;
    }
    Some(())
}

fn first_star_affinity(scope: &[AffinityTableBinding<'_>]) -> Option<u8> {
    scope
        .iter()
        .find_map(|binding| binding.table.columns.first())
        .map(schema_column_expr_affinity)
}

fn first_table_star_affinity(
    name: &QualifiedName,
    scope: &[AffinityTableBinding<'_>],
) -> Option<u8> {
    if name.schema.is_some() {
        return None;
    }
    let mut found = None;
    for binding in scope {
        if !matches_table_or_alias(&name.name, binding.table, binding.alias.as_deref()) {
            continue;
        }
        let affinity = binding
            .table
            .columns
            .first()
            .map(schema_column_expr_affinity)?;
        if found.replace(affinity).is_some() {
            return None;
        }
    }
    found
}

fn scoped_expr_affinity(
    expr: &Expr,
    scopes: &[&[AffinityTableBinding<'_>]],
    catalog: &[&TableSchema],
) -> Option<u8> {
    match strip_collate_wrappers(expr) {
        Expr::BoundOuterValue { affinity, .. } => Some(bound_outer_affinity_code(*affinity)),
        Expr::Column(column, _) => scoped_column_affinity(column, scopes),
        Expr::Cast { type_name, .. } => Some(type_name_to_affinity(type_name)),
        Expr::Subquery(select, _) => scalar_subquery_result_affinity(select, scopes, catalog),
        // Literals and every other computed expression have NONE affinity.
        _ => Some(b'A'),
    }
}

fn intrinsic_expr_affinity(expr: &Expr) -> Option<u8> {
    match strip_collate_wrappers(expr) {
        Expr::BoundOuterValue { affinity, .. } => Some(bound_outer_affinity_code(*affinity)),
        Expr::Column(..) | Expr::Subquery(..) => None,
        Expr::Cast { type_name, .. } => Some(type_name_to_affinity(type_name)),
        // Every other expression shape is computed and therefore has NONE
        // affinity even when it contains column references.
        _ => Some(b'A'),
    }
}

fn select_core_first_result_affinity(
    core: &SelectCore,
    outer_scopes: &[&[AffinityTableBinding<'_>]],
    catalog: &[&TableSchema],
) -> Option<u8> {
    match core {
        SelectCore::Select { columns, from, .. } => {
            let local_scope = from.as_ref().and_then(|from| {
                let mut bindings = Vec::new();
                collect_affinity_from_bindings(from, catalog, &mut bindings)?;
                Some(bindings)
            });
            let result = columns.first()?;
            if from.is_some() && local_scope.is_none() {
                return match result {
                    ResultColumn::Expr { expr, .. } => intrinsic_expr_affinity(expr),
                    ResultColumn::Star | ResultColumn::TableStar(_) => None,
                };
            }
            let mut scopes = Vec::with_capacity(outer_scopes.len() + usize::from(from.is_some()));
            if let Some(local_scope) = local_scope.as_deref() {
                scopes.push(local_scope);
            }
            scopes.extend_from_slice(outer_scopes);
            match result {
                ResultColumn::Expr { expr, .. } => scoped_expr_affinity(expr, &scopes, catalog),
                ResultColumn::Star => local_scope.as_deref().and_then(first_star_affinity),
                ResultColumn::TableStar(name) => local_scope
                    .as_deref()
                    .and_then(|scope| first_table_star_affinity(name, scope)),
            }
        }
        SelectCore::Values(values) => {
            // VALUES comparison metadata follows the representation selected
            // before rewrites.  A deferred clause has not consulted the active
            // function registry yet, so declining affinity is the only safe
            // answer here; guessing from a syntactic row can change comparison
            // coercion and therefore query results.
            let expr = values.donor_row()?.first()?;
            scoped_expr_affinity(expr, outer_scopes, catalog)
        }
    }
}

/// Determine the affinity of a scalar subquery's first result column.
///
/// SQLite preserves this affinity across the scalar-subquery boundary, while
/// result collation remains local to the SELECT.  Direct scalar codegen takes
/// affinity from the parser-root SELECT, which is the rightmost compound arm.
/// A VALUES core instead uses its frozen representation donor and declines to
/// provide affinity while donor selection is still deferred.
fn scalar_subquery_result_affinity(
    select: &SelectStatement,
    outer_scopes: &[&[AffinityTableBinding<'_>]],
    catalog: &[&TableSchema],
) -> Option<u8> {
    let parser_root = select
        .body
        .compounds
        .last()
        .map_or(&select.body.select, |(_, core)| core);
    select_core_first_result_affinity(parser_root, outer_scopes, catalog)
}

fn scalar_subquery_affinity_in_scan(
    select: &SelectStatement,
    ctx: Option<&ScanCtx<'_>>,
) -> Option<u8> {
    let mut catalog = Vec::new();
    let scope = ctx.map(affinity_scope_from_scan);
    if let Some(ctx) = ctx {
        extend_affinity_catalog_from_scan(&mut catalog, ctx);
    }
    let outer_scopes = scope.as_deref().map_or_else(Vec::new, |scope| vec![scope]);
    scalar_subquery_result_affinity(select, &outer_scopes, &catalog)
}

fn scalar_subquery_affinity_with_fallback(
    select: &SelectStatement,
    inner: &ScanCtx<'_>,
    outer: Option<&ScanCtx<'_>>,
) -> Option<u8> {
    let inner_scope = affinity_scope_from_scan(inner);
    let outer_scope = outer.map(affinity_scope_from_scan);
    let mut scopes = vec![inner_scope.as_slice()];
    if let Some(outer_scope) = outer_scope.as_deref() {
        scopes.push(outer_scope);
    }
    let mut catalog = Vec::new();
    extend_affinity_catalog_from_scan(&mut catalog, inner);
    if let Some(outer) = outer {
        extend_affinity_catalog_from_scan(&mut catalog, outer);
    }
    scalar_subquery_result_affinity(select, &scopes, &catalog)
}

fn scalar_subquery_affinity_in_join(
    select: &SelectStatement,
    tables: &[(&TableSchema, Option<&str>)],
) -> Option<u8> {
    let scope = tables
        .iter()
        .map(|(table, alias)| AffinityTableBinding {
            table,
            alias: alias.map(str::to_owned),
        })
        .collect::<Vec<_>>();
    let mut catalog = Vec::new();
    for (table, _) in tables {
        push_affinity_catalog_table(&mut catalog, table);
    }
    scalar_subquery_result_affinity(select, &[scope.as_slice()], &catalog)
}

/// Determine the type affinity of an expression for comparison coercion.
///
/// Per SQLite §3.2 (comparisonAffinity), column references and CAST expressions
/// have affinity for comparison purposes, and a scalar subquery preserves the
/// affinity of its first projected result. Literals and other computed
/// expressions have BLOB/NONE affinity (i.e., no coercion influence).
///
/// Returns SQLite affinity codes: A=BLOB, B=TEXT, C=NUMERIC, D=INTEGER, E=REAL.
fn expr_affinity(expr: &Expr, ctx: Option<&ScanCtx<'_>>) -> u8 {
    // COLLATE changes comparison ordering but preserves the underlying
    // expression affinity, including through repeated postfix wrappers.
    // Do not unwrap unary plus: SQLite intentionally strips affinity there.
    let inner = strip_collate_wrappers(expr);
    match inner {
        Expr::BoundOuterValue { affinity, .. } => bound_outer_affinity_code(*affinity),
        Expr::Column(col_ref, _) => {
            // Look up column type in the table schema
            if let Some(ctx) = ctx {
                // Check primary table
                let check_table = |table: &TableSchema, alias: Option<&str>| -> Option<u8> {
                    if let Some(qualifier) = &col_ref.table
                        && !matches_table_or_alias(qualifier, table, alias)
                    {
                        return None;
                    }
                    if let Some(idx) = table.column_index(&col_ref.column) {
                        return Some(schema_column_expr_affinity(&table.columns[idx]));
                    }
                    table
                        .resolves_to_hidden_rowid(&col_ref.column)
                        .then_some(b'D')
                };
                if let Some(aff) = check_table(ctx.table, ctx.table_alias) {
                    return aff;
                }
                // Check secondary tables (UPDATE ... FROM, possibly multi-source)
                for sec in ctx.secondaries {
                    if let Some(aff) = check_table(sec.table, sec.table_alias) {
                        return aff;
                    }
                }
                // Check full schema
                if let Some(schema) = ctx.schema {
                    for table in schema {
                        if let Some(qualifier) = &col_ref.table
                            && !table.name.eq_ignore_ascii_case(qualifier)
                        {
                            continue;
                        }
                        if let Some(idx) = table.column_index(&col_ref.column) {
                            return schema_column_expr_affinity(&table.columns[idx]);
                        }
                        if table.resolves_to_hidden_rowid(&col_ref.column) {
                            return b'D';
                        }
                    }
                }
            }
            b'A' // BLOB/NONE affinity if not found
        }
        // Literals have NO column affinity for comparison purposes.
        // Per C SQLite: only TK_COLUMN and TK_CAST produce comparison affinity.
        Expr::Cast { type_name, .. } => type_name_to_affinity(type_name),
        Expr::Subquery(select, _) => scalar_subquery_affinity_in_scan(select, ctx).unwrap_or(b'A'),
        _ => b'A', // BLOB/NONE affinity for literals and computed expressions
    }
}

/// Compute the comparison affinity P5 value for a binary comparison.
/// Implements SQLite's Section 4.2 type conversion rules.
fn comparison_affinity_p5(left: &Expr, right: &Expr, ctx: Option<&ScanCtx<'_>>) -> u16 {
    combine_comparison_affinity(expr_affinity(left, ctx), expr_affinity(right, ctx))
}

/// Affinity that SQLite applies to every element of a value-list / subquery
/// `IN` comparison: the affinity of the left-hand operand applied uniformly
/// (datatype3 §4.2 — IN uses `sqlite3ExprAffinity(LHS)` against the RHS set).
/// Returns a `p5` affinity code (`0`, `b'B'`, or `b'C'`).
fn in_operand_affinity_p5(operand: &Expr, ctx: Option<&ScanCtx<'_>>) -> u16 {
    // The RHS set elements contribute NONE/BLOB affinity, so the result is
    // governed entirely by the operand's own affinity.
    combine_comparison_affinity(expr_affinity(operand, ctx), b'A')
}

/// Resolve an expression's comparison affinity in the correlated-subquery
/// fallback path: prefer the inner (subquery) context, but fall back to the
/// outer context when the column does not resolve in the inner scope.
fn fallback_expr_affinity(expr: &Expr, inner: &ScanCtx<'_>, outer: Option<&ScanCtx<'_>>) -> u8 {
    match strip_collate_wrappers(expr) {
        Expr::Column(col_ref, _) => {
            if column_ref_resolves_in_ctx(col_ref, inner) {
                return expr_affinity(expr, Some(inner));
            }
            outer
                .filter(|outer| column_ref_resolves_in_ctx(col_ref, outer))
                .map_or(b'A', |outer| expr_affinity(expr, Some(outer)))
        }
        Expr::Subquery(select, _) => {
            scalar_subquery_affinity_with_fallback(select, inner, outer).unwrap_or(b'A')
        }
        // CAST has intrinsic affinity; every other computed expression has NONE.
        _ => expr_affinity(expr, Some(inner)),
    }
}

/// Convert a SQL type name to an affinity character code.
fn type_name_to_affinity(type_name: &fsqlite_ast::TypeName) -> u8 {
    // Encoding: A..E maps to BLOB, TEXT, NUMERIC, INTEGER, REAL:
    // 'A' = BLOB, 'B' = TEXT, 'C' = NUMERIC, 'D' = INTEGER, 'E' = REAL.
    let name = type_name.name.to_uppercase();
    if name.contains("INT") {
        b'D' // INTEGER affinity
    } else if name.contains("CHAR") || name.contains("TEXT") || name.contains("CLOB") {
        b'B' // TEXT affinity
    } else if name.contains("BLOB") {
        b'A' // BLOB affinity
    } else if name.contains("REAL") || name.contains("FLOA") || name.contains("DOUB") {
        b'E' // REAL affinity
    } else {
        // NUMERIC affinity — also the SQLite default for an EMPTY CAST type
        // name (`CAST(x AS)`), which is `sqlite3AffinityType`'s fallback:
        // it behaves like `CAST(x AS NUMERIC)`. bd-errmsg-parity-batch4-deqcb.
        b'C'
    }
}

/// Convert days since 1970-01-01 (Unix epoch) to (year, month, day).
fn epoch_days_to_ymd(days: u64) -> (u64, u64, u64) {
    // Civil-date algorithm from Howard Hinnant (public domain).
    let z = days + 719_468;
    let era = z / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

// ---------------------------------------------------------------------------
// Public helpers for cross-crate partial-index support
// ---------------------------------------------------------------------------

/// Emit VDBE bytecode that evaluates `where_expr` against the current row of
/// `cursor` (which scans `table`) and jumps to `skip_label` when the predicate
/// is **not** satisfied.
///
/// Used by `backfill_index` in `fsqlite-core` to skip rows that don't match a
/// partial index WHERE clause.
pub fn emit_scan_filter(
    b: &mut ProgramBuilder,
    where_expr: &Expr,
    cursor: i32,
    table: &TableSchema,
    skip_label: Label,
) {
    let scan = ScanCtx {
        cursor,
        table,
        table_alias: None,
        schema: None,
        register_base: None,
        secondaries: &[],
    };
    let filter_reg = b.alloc_temp();
    emit_expr(b, where_expr, filter_reg, Some(&scan));
    b.emit_jump_to_label(Opcode::IfNot, filter_reg, 1, skip_label, P4::None, 0);
    b.free_temp(filter_reg);
}

/// Emit opcodes that evaluate `expr` and store the result in `target_reg`,
/// reading column values from `cursor` which is opened on `table`.
/// Used by index backfill to evaluate expression-index key terms.
pub fn emit_backfill_key_expr(
    b: &mut ProgramBuilder,
    expr: &Expr,
    target_reg: i32,
    cursor: i32,
    table: &TableSchema,
) {
    let scan = ScanCtx {
        cursor,
        table,
        table_alias: None,
        schema: None,
        register_base: None,
        secondaries: &[],
    };
    emit_expr(b, expr, target_reg, Some(&scan));
}

/// Emit the read of a plain-column index key term during index backfill.
///
/// Delegates to `emit_table_column_read` so a plain (non-expression) index on a
/// VIRTUAL generated column (bd-gh-virtual-generated-columns-5e0u1 / GH#227)
/// computes the generating expression on read instead of reading the NULL
/// placeholder record slot. Without this, pre-existing rows backfilled at
/// `CREATE INDEX` time would get NULL index keys, silently diverging from keys
/// written by post-creation DML. INTEGER PRIMARY KEY columns read the rowid;
/// all other columns read the record slot directly, so this is a drop-in
/// replacement for a raw `Opcode::Column` read.
pub fn emit_backfill_column_read(
    b: &mut ProgramBuilder,
    col_idx: usize,
    target_reg: i32,
    cursor: i32,
    table: &TableSchema,
) {
    emit_table_column_read(b, cursor, table, None, None, col_idx, target_reg);
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn test_failure() -> bool {
        false
    }
    use crate::ProgramBuilder;
    use crate::engine::{ExecOutcome, MemDatabase, VdbeEngine};
    use asupersync::runtime::RuntimeBuilder;
    use fsqlite_ast::{
        Assignment, AssignmentTarget, BinaryOp as AstBinaryOp, BoundCollation, ColumnRef,
        DeleteStatement, Distinctness, Expr, FromClause, InSet, InsertSource, InsertStatement,
        JoinClause, JoinConstraint, JoinKind, JoinType, LimitClause, Literal, OrderingTerm,
        PlaceholderType, QualifiedName, QualifiedTableRef, ResultColumn, SelectBody, SelectCore,
        SelectStatement, SortDirection, Span, Statement, TableOrSubquery, UpdateStatement,
    };
    use fsqlite_func::{FunctionRegistry, register_builtins};
    use fsqlite_parser::parse_first_statement_with_tail;
    use fsqlite_types::opcode::{Opcode, P4, VdbeOp};
    use proptest::prelude::*;
    use proptest::{prop_oneof, proptest};
    use std::panic::{AssertUnwindSafe, catch_unwind};

    fn test_schema() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', false),
                ColumnInfo::basic("b", 'C', false),
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    #[test]
    fn fallback_json_operator_resolves_inner_and_outer_operands_positionally() {
        let schema = test_schema_with_subquery_source();
        let outer = ScanCtx {
            cursor: 3,
            table: &schema[0],
            table_alias: Some("o"),
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };
        let inner = ScanCtx {
            cursor: 4,
            table: &schema[1],
            table_alias: Some("i"),
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };

        for (left, right, expected_left_cursor, expected_right_cursor) in [
            (("o", "a"), ("i", "b"), 3, 4),
            (("i", "b"), ("o", "a"), 4, 3),
        ] {
            let expr = Expr::JsonAccess {
                expr: Box::new(Expr::Column(
                    ColumnRef::qualified(left.0, left.1),
                    Span::ZERO,
                )),
                path: Box::new(Expr::Column(
                    ColumnRef::qualified(right.0, right.1),
                    Span::ZERO,
                )),
                arrow: JsonArrow::Arrow,
                span: Span::ZERO,
            };
            let mut builder = ProgramBuilder::new();
            let result = builder.alloc_reg();
            emit_expr_with_fallback(&mut builder, &expr, result, &inner, Some(&outer));
            // A finished program must terminate with Halt (V2.3 invariant); the
            // expression-fragment emit above does not, so append it exactly as
            // the statement codegen paths do before `finish()`.
            builder.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
            let program = builder
                .finish()
                .expect("JSON fallback program should finish");
            let function = program
                .ops()
                .iter()
                .find(|op| op.opcode == Opcode::PureFunc)
                .expect("JSON fallback must emit a scalar function call");
            assert_eq!(function.p4, P4::FuncName("->".to_owned()));
            assert_eq!(function.p5, 2);
            let arg_base = function.p2;
            assert!(program.ops().iter().any(|op| {
                op.opcode == Opcode::Column && op.p1 == expected_left_cursor && op.p3 == arg_base
            }));
            assert!(program.ops().iter().any(|op| {
                op.opcode == Opcode::Column
                    && op.p1 == expected_right_cursor
                    && op.p3 == arg_base + 1
            }));
        }
    }

    #[test]
    fn fallback_json_operator_resolves_secondary_outer_scan_columns() {
        let schema = test_schema_with_subquery_source();
        let secondary_table = TableSchema {
            name: "u".to_owned(),
            root_page: 4,
            columns: vec![ColumnInfo::basic("b", 'd', false)],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        };
        let secondaries = [SecondaryScan {
            cursor: 7,
            table: &secondary_table,
            table_alias: Some("u"),
            register_base: None,
        }];
        let outer = ScanCtx {
            cursor: 3,
            table: &schema[0],
            table_alias: Some("o"),
            schema: Some(&schema),
            register_base: None,
            secondaries: &secondaries,
        };
        let inner = ScanCtx {
            cursor: 4,
            table: &schema[1],
            table_alias: Some("i"),
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };
        let expr = Expr::JsonAccess {
            expr: Box::new(Expr::Column(ColumnRef::qualified("u", "b"), Span::ZERO)),
            path: Box::new(Expr::Column(ColumnRef::qualified("i", "b"), Span::ZERO)),
            arrow: JsonArrow::DoubleArrow,
            span: Span::ZERO,
        };
        let mut builder = ProgramBuilder::new();
        let result = builder.alloc_reg();
        emit_expr_with_fallback(&mut builder, &expr, result, &inner, Some(&outer));
        // A finished program must terminate with Halt (V2.3 invariant); append
        // it exactly as the statement codegen paths do before `finish()`.
        builder.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        let program = builder
            .finish()
            .expect("JSON fallback program should finish");
        let function = program
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::PureFunc)
            .expect("JSON fallback must emit a scalar function call");
        assert_eq!(function.p4, P4::FuncName("->>".to_owned()));
        assert!(
            program
                .ops()
                .iter()
                .any(|op| { op.opcode == Opcode::Column && op.p1 == 7 && op.p3 == function.p2 })
        );
        assert!(
            !program
                .ops()
                .iter()
                .any(|op| { op.opcode == Opcode::Null && op.p2 == function.p2 }),
            "a secondary outer reference must never degrade to SQL NULL",
        );
    }

    fn create_index_sql(sql: &str) -> CreateIndexStatement {
        let Some((statement, tail)) =
            parse_first_statement_with_tail(sql).expect("test CREATE INDEX SQL should parse")
        else {
            unreachable!("expected parsed CREATE INDEX statement");
        };
        assert_eq!(
            tail,
            sql.len(),
            "parser should consume the whole SQL string"
        );
        match statement {
            Statement::CreateIndex(stmt) => stmt,
            other => unreachable!("expected CREATE INDEX statement, got {other:?}"),
        }
    }

    #[test]
    fn bind_explicit_index_binds_rootless_simple_index_metadata() {
        let mut schema = test_schema();
        schema[0].columns[0].collation = Some("NOCASE".to_owned());
        let stmt = create_index_sql("CREATE UNIQUE INDEX MiXeD ON T(a DESC)");

        let bound =
            bind_explicit_index(&stmt, "mixed", "t", &schema[0]).expect("simple index should bind");

        assert_eq!(bound.name, "MiXeD");
        assert_eq!(bound.columns, ["a"]);
        assert!(bound.key_expressions.is_empty());
        assert_eq!(bound.key_sort_directions, [SortDirection::Desc]);
        assert_eq!(bound.key_collations, [Some("NOCASE".to_owned())]);
        assert!(bound.where_clause.is_none());
        assert!(bound.is_unique);

        let index = bound.into_index_schema(41);
        assert_eq!(index.root_page, 41);
        assert_eq!(index.name, "MiXeD");
        assert_eq!(index.conflict_action, None);
    }

    #[test]
    fn bind_explicit_index_binds_expression_terms_and_preserves_custom_collation() {
        let schema = test_schema();
        let stmt = create_index_sql(
            "CREATE INDEX idx_expr ON t(lower(a) COLLATE custom_sort DESC, b + 1 ASC)",
        );

        let bound = bind_explicit_index(&stmt, "idx_expr", "t", &schema[0])
            .expect("expression index should bind before registry validation");

        assert!(bound.columns.is_empty());
        assert_eq!(bound.key_expressions.len(), 2);
        assert_eq!(bound.key_expressions[0], "lower(a) COLLATE custom_sort");
        assert_eq!(bound.key_expressions[1], "b + 1");
        assert_eq!(
            bound.key_sort_directions,
            [SortDirection::Desc, SortDirection::Asc]
        );
        assert_eq!(bound.key_collations, [Some("custom_sort".to_owned()), None]);
    }

    #[test]
    fn bind_explicit_index_keeps_nested_and_derived_collations_out_of_key_metadata() {
        let mut schema = test_schema();
        schema[0].columns[0].collation = Some("declared_sort".to_owned());
        for expression in [
            "lower(a COLLATE nested_sort)",
            "nullif(a COLLATE nested_sort, 'z')",
            "+(a COLLATE nested_sort)",
            "CAST(a COLLATE nested_sort AS TEXT)",
            "+a",
            "CAST(a AS TEXT)",
            "0 AND (a COLLATE nested_sort = 'x')",
            "(a COLLATE nested_sort = 'x') AND 0",
        ] {
            let sql = format!("CREATE INDEX idx_expr ON t({expression})");
            let stmt = create_index_sql(&sql);
            let bound = bind_explicit_index(&stmt, "idx_expr", "t", &schema[0])
                .expect("derived expression index should bind");
            assert_eq!(
                bound.key_collations,
                [None],
                "{expression} must keep BINARY key ordering"
            );
        }

        for (expression, expected) in [
            ("a", "declared_sort"),
            ("a COLLATE root_sort", "root_sort"),
            ("lower(a) COLLATE root_sort", "root_sort"),
        ] {
            let sql = format!("CREATE INDEX idx_expr ON t({expression})");
            let stmt = create_index_sql(&sql);
            let bound = bind_explicit_index(&stmt, "idx_expr", "t", &schema[0])
                .expect("root-collated expression index should bind");
            assert_eq!(
                bound.key_collations,
                [Some(expected.to_owned())],
                "{expression} must retain its key collation"
            );
        }
    }

    #[test]
    fn bind_explicit_index_binds_partial_predicate() {
        let schema = test_schema();
        let stmt = create_index_sql("CREATE INDEX idx_partial ON t(a) WHERE t.b > 0 AND rowid > 0");

        let bound = bind_explicit_index(&stmt, "idx_partial", "t", &schema[0])
            .expect("partial index should bind");

        assert_eq!(bound.columns, ["a"]);
        assert_eq!(bound.where_clause.as_deref(), Some("t.b > 0 AND rowid > 0"));
    }

    #[test]
    fn bind_explicit_index_rejects_catalog_identity_and_unknown_table() {
        let schema = test_schema();
        let stmt = create_index_sql("CREATE INDEX declared_name ON t(a)");
        let error = bind_explicit_index(&stmt, "catalog_name", "t", &schema[0])
            .expect_err("catalog index-name mismatch must fail");
        assert!(
            matches!(error, CodegenError::Unsupported(message) if message.contains("identity mismatch"))
        );

        let stmt = create_index_sql("CREATE INDEX idx_other ON other(a)");
        let error = bind_explicit_index(&stmt, "idx_other", "other", &schema[0])
            .expect_err("supplied schema must match the target table");
        assert_eq!(error, CodegenError::TableNotFound("other".to_owned()));
    }

    #[test]
    fn bind_explicit_index_rejects_unknown_simple_and_expression_columns() {
        let schema = test_schema();
        for sql in [
            "CREATE INDEX idx_missing ON t(missing)",
            "CREATE INDEX idx_missing ON t(lower(missing))",
        ] {
            let stmt = create_index_sql(sql);
            let error = bind_explicit_index(&stmt, "idx_missing", "t", &schema[0])
                .expect_err("unknown indexed column must fail");
            assert!(matches!(error, CodegenError::ColumnNotFound { .. }));
        }
    }

    #[test]
    fn bind_explicit_index_rejects_qualified_and_hidden_rowid_key_references() {
        let schema = test_schema();
        for sql in [
            "CREATE INDEX idx_invalid ON t(t.a)",
            "CREATE INDEX idx_invalid ON t(lower(t.a))",
        ] {
            let stmt = create_index_sql(sql);
            let error = bind_explicit_index(&stmt, "idx_invalid", "t", &schema[0])
                .expect_err("qualified index key reference must fail");
            assert!(
                matches!(error, CodegenError::Unsupported(message) if message.contains("operator"))
            );
        }

        let stmt = create_index_sql("CREATE INDEX idx_invalid ON t(rowid + 1)");
        let error = bind_explicit_index(&stmt, "idx_invalid", "t", &schema[0])
            .expect_err("hidden rowid aliases are not indexable columns");
        assert_eq!(
            error,
            CodegenError::ColumnNotFound {
                table: "t".to_owned(),
                column: "rowid".to_owned(),
            }
        );
    }

    #[test]
    fn bind_explicit_index_rejects_unknown_partial_predicate_column() {
        let schema = test_schema();
        let stmt = create_index_sql("CREATE INDEX idx_partial_missing ON t(a) WHERE missing > 0");

        let error = bind_explicit_index(&stmt, "idx_partial_missing", "t", &schema[0])
            .expect_err("unknown partial-index predicate column must fail");

        assert_eq!(
            error,
            CodegenError::ColumnNotFound {
                table: "t".to_owned(),
                column: "missing".to_owned(),
            }
        );
    }

    #[test]
    fn bind_explicit_index_rejects_malformed_terms_and_collation_shape() {
        let schema = test_schema();
        let mut empty = create_index_sql("CREATE INDEX idx_empty ON t(a)");
        empty.columns.clear();
        let error = bind_explicit_index(&empty, "idx_empty", "t", &schema[0])
            .expect_err("empty key-term list must fail");
        assert!(
            matches!(error, CodegenError::Unsupported(message) if message.contains("at least one key term"))
        );

        let mut placeholder_term = create_index_sql("CREATE INDEX idx_param ON t(a)");
        placeholder_term.columns[0].expr = placeholder(1);
        let error = bind_explicit_index(&placeholder_term, "idx_param", "t", &schema[0])
            .expect_err("bind parameter key term must fail");
        assert!(
            matches!(error, CodegenError::Unsupported(message) if message.contains("bind parameters"))
        );

        let mut empty_collation = create_index_sql("CREATE INDEX idx_coll ON t(a)");
        empty_collation.columns[0].collation = Some(String::new());
        let error = bind_explicit_index(&empty_collation, "idx_coll", "t", &schema[0])
            .expect_err("empty collation name must fail");
        assert!(
            matches!(error, CodegenError::Unsupported(message) if message.contains("empty collation"))
        );
    }

    fn test_schema_with_index() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', false),
                ColumnInfo::basic("b", 'C', false),
            ],
            indexes: vec![IndexSchema {
                name: "idx_t_b".to_owned(),
                root_page: 3,
                columns: vec!["b".to_owned()],
                key_expressions: vec!["b".to_owned()],
                key_sort_directions: vec![],
                where_clause: None,
                is_unique: false,
                key_collations: vec![],
                conflict_action: None,
            }],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    /// Like [`test_schema_with_index`] but column `b` has TEXT affinity (`'B'`)
    /// with the default BINARY collation. A case-stable LIKE/GLOB prefix
    /// (`'123%'`) only lowers to an index range seek when the derived TEXT
    /// bounds compare byte-exactly against the index — i.e. a TEXT-affinity,
    /// BINARY-collated column. On the NUMERIC-affinity `test_schema_with_index`
    /// the text bounds would be coerced to numbers and the range seek would
    /// silently skip lexical matches, so `index_range_fast_path_is_safe`
    /// correctly declines it there (matching stock sqlite3, which SCANs).
    fn test_schema_with_text_index() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', false),
                ColumnInfo::basic("b", 'B', false),
            ],
            indexes: vec![IndexSchema {
                name: "idx_t_b".to_owned(),
                root_page: 3,
                columns: vec!["b".to_owned()],
                key_expressions: vec!["b".to_owned()],
                key_sort_directions: vec![],
                where_clause: None,
                is_unique: false,
                key_collations: vec![],
                conflict_action: None,
            }],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn test_schema_with_expression_index() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', false),
                ColumnInfo::basic("name", 'B', false),
            ],
            indexes: vec![IndexSchema {
                name: "idx_t_lower_name".to_owned(),
                root_page: 3,
                columns: Vec::new(),
                key_expressions: vec!["lower(name)".to_owned()],
                key_sort_directions: vec![],
                where_clause: None,
                is_unique: false,
                key_collations: vec![],
                conflict_action: None,
            }],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn test_small_bench_schema() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "bench".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("id", 'D', true),
                ColumnInfo::basic("name", 'B', false),
                ColumnInfo::basic("value", 'E', false),
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn seed_small_bench_db(row_count: usize) -> MemDatabase {
        let mut db = MemDatabase::new();
        db.create_table_at(2, 3);
        let table = db.get_table_mut(2).expect("bench table should exist");
        for id in 0..row_count {
            let id = i64::try_from(id).expect("row ids should fit in i64");
            table.insert_row(
                id,
                vec![
                    SqliteValue::Integer(id),
                    SqliteValue::Text(format!("name{id}").into()),
                    SqliteValue::Float(((id * 3) + 1) as f64),
                ],
            );
        }
        db
    }

    fn execute_codegen_select_with_storage_cursor(
        stmt: &SelectStatement,
        schema: &[TableSchema],
        db: MemDatabase,
    ) -> Vec<Vec<SqliteValue>> {
        let mut registry = FunctionRegistry::new();
        register_builtins(&mut registry);
        execute_codegen_select_with_registry(stmt, schema, db, registry)
    }

    fn execute_codegen_select_with_registry(
        stmt: &SelectStatement,
        schema: &[TableSchema],
        db: MemDatabase,
        registry: FunctionRegistry,
    ) -> Vec<Vec<SqliteValue>> {
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, stmt, schema, &ctx).expect("select should codegen");
        let prog = b.finish().expect("program should build");
        let mut engine = VdbeEngine::new(prog.register_count());
        engine.enable_storage_read_cursors(true);
        engine.set_database(db);
        engine.set_reject_mem_fallback(false);
        engine.set_function_registry(std::sync::Arc::new(registry));
        let runtime = RuntimeBuilder::current_thread()
            .blocking_threads(1, 2)
            .build()
            .expect("build codegen storage-cursor test runtime");
        let outcome = runtime
            .block_on(async { engine.execute(&prog).await })
            .expect("execution should succeed");
        assert_eq!(outcome, ExecOutcome::Done);
        engine
            .take_results()
            .into_iter()
            .map(|row| row.into_vec())
            .collect()
    }

    fn test_schema_with_nocase_text_column() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', false),
                ColumnInfo {
                    name: "name".to_owned(),
                    affinity: 'B',
                    is_ipk: false,
                    type_name: Some("TEXT".to_owned()),
                    notnull: false,
                    unique: false,
                    default_value: None,
                    strict_type: None,
                    generated_expr: None,
                    generated_stored: None,
                    collation: Some("NOCASE".to_owned()),
                    conflict_action: None,
                },
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn test_schema_with_nocase_text_index() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![ColumnInfo {
                name: "name".to_owned(),
                affinity: 'B',
                is_ipk: false,
                type_name: Some("TEXT".to_owned()),
                notnull: false,
                unique: false,
                default_value: None,
                strict_type: None,
                generated_expr: None,
                generated_stored: None,
                collation: Some("NOCASE".to_owned()),
                conflict_action: None,
            }],
            indexes: vec![IndexSchema {
                name: "idx_t_name".to_owned(),
                root_page: 3,
                columns: vec!["name".to_owned()],
                key_expressions: vec!["name".to_owned()],
                key_sort_directions: vec![],
                where_clause: None,
                is_unique: false,
                key_collations: vec![Some("NOCASE".to_owned())],
                conflict_action: None,
            }],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn test_schema_with_typed_numeric_index() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![ColumnInfo {
                name: "n".to_owned(),
                affinity: 'D',
                is_ipk: false,
                type_name: Some("INTEGER".to_owned()),
                notnull: false,
                unique: false,
                default_value: None,
                strict_type: None,
                generated_expr: None,
                generated_stored: None,
                collation: None,
                conflict_action: None,
            }],
            indexes: vec![IndexSchema {
                name: "idx_t_n".to_owned(),
                root_page: 3,
                columns: vec!["n".to_owned()],
                key_expressions: vec!["n".to_owned()],
                key_sort_directions: vec![],
                where_clause: None,
                is_unique: false,
                key_collations: vec![],
                conflict_action: None,
            }],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn test_schema_with_subquery_source() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "t".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo {
                        name: "a".to_owned(),
                        affinity: 'd',
                        is_ipk: false,
                        type_name: None,
                        notnull: false,
                        unique: false,
                        default_value: None,
                        strict_type: None,
                        generated_expr: None,
                        generated_stored: None,
                        collation: None,
                        conflict_action: None,
                    },
                    ColumnInfo {
                        name: "b".to_owned(),
                        affinity: 'C',
                        is_ipk: false,
                        type_name: None,
                        notnull: false,
                        unique: false,
                        default_value: None,
                        strict_type: None,
                        generated_expr: None,
                        generated_stored: None,
                        collation: None,
                        conflict_action: None,
                    },
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "s".to_owned(),
                root_page: 3,
                columns: vec![ColumnInfo::basic("b", 'd', false)],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn scalar_affinity_test_schema() -> Vec<TableSchema> {
        let typed_column = |name: &str, affinity: char, type_name: &str| {
            let mut column = ColumnInfo::basic(name, affinity, false);
            column.type_name = Some(type_name.to_owned());
            column
        };
        let mut schema = test_schema_with_subquery_source();
        schema[0].columns = vec![
            typed_column("outer_n", 'C', "NUMERIC"),
            typed_column("outer_t", 'B', "TEXT"),
            typed_column("outer_b", 'A', "BLOB"),
        ];
        schema[1].columns = vec![
            typed_column("n", 'C', "NUMERIC"),
            typed_column("txt", 'B', "TEXT"),
            typed_column("raw", 'A', "BLOB"),
        ];
        schema[1].columns[1].collation = Some("NOCASE".to_owned());
        schema
    }

    fn test_schema_with_index_and_subquery_source() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "t".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("a", 'd', false),
                    ColumnInfo::basic("b", 'd', false),
                ],
                indexes: vec![IndexSchema {
                    name: "idx_t_b".to_owned(),
                    root_page: 4,
                    columns: vec!["b".to_owned()],
                    key_expressions: vec!["b".to_owned()],
                    key_sort_directions: vec![],
                    where_clause: None,
                    is_unique: false,
                    key_collations: vec![],
                    conflict_action: None,
                }],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "s".to_owned(),
                root_page: 3,
                columns: vec![ColumnInfo::basic("b", 'd', false)],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn test_schema_with_join_lookup() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "customers".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("name", 'B', false),
                    ColumnInfo::basic("region", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "orders".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("customer_id", 'D', false),
                    ColumnInfo::basic("amount", 'E', false),
                    ColumnInfo::basic("status", 'B', false),
                ],
                indexes: vec![IndexSchema {
                    name: "idx_orders_customer_id".to_owned(),
                    root_page: 4,
                    columns: vec!["customer_id".to_owned()],
                    key_expressions: vec!["customer_id".to_owned()],
                    key_sort_directions: vec![],
                    where_clause: None,
                    is_unique: false,
                    key_collations: vec![],
                    conflict_action: None,
                }],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn grouped_join_count_sum_index_lookup_stmt() -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("c", "name"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "count".to_owned(),
                                args: FunctionArgs::Star,
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "sum".to_owned(),
                                args: FunctionArgs::List(vec![Expr::Column(
                                    ColumnRef::qualified("o", "amount"),
                                    Span::ZERO,
                                )]),
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("customers"),
                            alias: Some("c".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![fsqlite_ast::JoinClause {
                            join_type: fsqlite_ast::JoinType {
                                kind: fsqlite_ast::JoinKind::Inner,
                                natural: false,
                            },
                            table: TableOrSubquery::Table {
                                name: QualifiedName::bare("orders"),
                                alias: Some("o".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            constraint: Some(fsqlite_ast::JoinConstraint::On(Expr::BinaryOp {
                                left: Box::new(Expr::Column(
                                    ColumnRef::qualified("o", "customer_id"),
                                    Span::ZERO,
                                )),
                                op: AstBinaryOp::Eq,
                                right: Box::new(Expr::Column(
                                    ColumnRef::qualified("c", "id"),
                                    Span::ZERO,
                                )),
                                span: Span::ZERO,
                            })),
                        }],
                    }),
                    where_clause: None,
                    group_by: vec![Expr::Column(ColumnRef::qualified("c", "name"), Span::ZERO)],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    fn grouped_join_count_sum_rowid_lookup_stmt() -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("c", "name"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "count".to_owned(),
                                args: FunctionArgs::Star,
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "sum".to_owned(),
                                args: FunctionArgs::List(vec![Expr::Column(
                                    ColumnRef::qualified("o", "amount"),
                                    Span::ZERO,
                                )]),
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("orders"),
                            alias: Some("o".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![fsqlite_ast::JoinClause {
                            join_type: fsqlite_ast::JoinType {
                                kind: fsqlite_ast::JoinKind::Inner,
                                natural: false,
                            },
                            table: TableOrSubquery::Table {
                                name: QualifiedName::bare("customers"),
                                alias: Some("c".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            constraint: Some(fsqlite_ast::JoinConstraint::On(Expr::BinaryOp {
                                left: Box::new(Expr::Column(
                                    ColumnRef::qualified("c", "id"),
                                    Span::ZERO,
                                )),
                                op: AstBinaryOp::Eq,
                                right: Box::new(Expr::Column(
                                    ColumnRef::qualified("o", "customer_id"),
                                    Span::ZERO,
                                )),
                                span: Span::ZERO,
                            })),
                        }],
                    }),
                    where_clause: None,
                    group_by: vec![Expr::Column(ColumnRef::qualified("c", "name"), Span::ZERO)],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    fn from_table(name: &str) -> FromClause {
        FromClause {
            source: TableOrSubquery::Table {
                name: QualifiedName::bare(name),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            joins: vec![],
        }
    }

    fn from_table_as(name: &str, alias: &str) -> FromClause {
        FromClause {
            source: TableOrSubquery::Table {
                name: QualifiedName::bare(name),
                alias: Some(alias.to_owned()),
                index_hint: None,
                time_travel: None,
            },
            joins: vec![],
        }
    }

    fn placeholder(n: u32) -> Expr {
        Expr::Placeholder(PlaceholderType::Numbered(n), Span::ZERO)
    }

    fn anonymous_placeholder() -> Expr {
        Expr::Placeholder(PlaceholderType::Anonymous, Span::ZERO)
    }

    fn rowid_eq_param() -> Box<Expr> {
        Box::new(Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
            op: AstBinaryOp::Eq,
            right: Box::new(placeholder(1)),
            span: Span::ZERO,
        })
    }

    fn col_cmp_param(col: &str, op: AstBinaryOp, n: u32) -> Box<Expr> {
        Box::new(Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare(col), Span::ZERO)),
            op,
            right: Box::new(placeholder(n)),
            span: Span::ZERO,
        })
    }

    fn qualified_col_cmp_param(table: &str, col: &str, op: AstBinaryOp, n: u32) -> Box<Expr> {
        Box::new(Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::qualified(table, col), Span::ZERO)),
            op,
            right: Box::new(placeholder(n)),
            span: Span::ZERO,
        })
    }

    fn and_expr(left: Box<Expr>, right: Box<Expr>) -> Box<Expr> {
        Box::new(Expr::BinaryOp {
            left,
            op: AstBinaryOp::And,
            right,
            span: Span::ZERO,
        })
    }

    fn expr_sql(sql: &str) -> Expr {
        parse_sql_expr(sql).expect("test expression SQL should parse")
    }

    #[test]
    fn singleton_in_rhs_uses_sealed_query_constancy_metadata() {
        let mut registry = FunctionRegistry::new();
        register_builtins(&mut registry);

        with_connection_function_registry_context(
            Some(Arc::new(registry)),
            Vec::new(),
            true,
            true,
            || {
                assert!(singleton_in_rhs_is_constant(&expr_sql("CURRENT_TIMESTAMP")));
                assert!(singleton_in_rhs_is_constant(&expr_sql("sqlite_version()")));
                assert!(singleton_in_rhs_is_constant(&expr_sql(
                    "date('2000-01-01')"
                )));
                assert!(singleton_in_rhs_is_constant(&expr_sql("abs(1)")));
                assert!(!singleton_in_rhs_is_constant(&expr_sql("random()")));
                assert!(!singleton_in_rhs_is_constant(&expr_sql("abs(random())")));

                let mut distinct = expr_sql("abs(1)");
                let Expr::FunctionCall {
                    distinct: is_distinct,
                    ..
                } = &mut distinct
                else {
                    unreachable!("abs(1) should parse as a function call");
                };
                *is_distinct = true;
                assert!(!singleton_in_rhs_is_constant(&distinct));

                let mut star = expr_sql("abs(1)");
                let Expr::FunctionCall { args, .. } = &mut star else {
                    unreachable!("abs(1) should parse as a function call");
                };
                *args = FunctionArgs::Star;
                assert!(!singleton_in_rhs_is_constant(&star));
                assert!(!singleton_in_rhs_is_constant(&Expr::RowValue(
                    Vec::new(),
                    Span::ZERO,
                )));
            },
        );

        with_connection_function_registry_context(None, Vec::new(), true, true, || {
            assert!(
                !singleton_in_rhs_is_constant(&expr_sql("abs(1)")),
                "missing frozen registry metadata must fail closed"
            );
        });
    }

    fn scalar_values_with_frozen_donor(sql: &str, donor_row: usize) -> Expr {
        let mut expr = expr_sql(sql);
        let Expr::Subquery(select, _) = &mut expr else {
            unreachable!("expected scalar VALUES subquery expression");
        };
        assert!(
            select.body.compounds.is_empty(),
            "VALUES donor fixture must have one parser-root core"
        );
        let SelectCore::Values(values) = &mut select.body.select else {
            unreachable!("expected VALUES parser-root core");
        };
        values.freeze_donor_row(Some(donor_row));
        expr
    }

    fn select_sql(sql: &str) -> SelectStatement {
        let Some((statement, tail)) =
            parse_first_statement_with_tail(sql).expect("test SELECT SQL should parse")
        else {
            unreachable!("expected parsed SELECT statement");
        };
        assert_eq!(
            tail,
            sql.len(),
            "parser should consume the whole SQL string"
        );
        match statement {
            Statement::Select(stmt) => stmt,
            other => unreachable!("expected SELECT statement, got {other:?}"),
        }
    }

    fn fuzz_literal() -> impl Strategy<Value = String> {
        prop_oneof![
            any::<i16>().prop_map(|n| {
                if n.is_negative() {
                    format!("({n})")
                } else {
                    n.to_string()
                }
            }),
            Just("NULL".to_owned()),
            Just("TRUE".to_owned()),
            Just("FALSE".to_owned()),
        ]
    }

    fn fuzz_column() -> impl Strategy<Value = &'static str> {
        prop_oneof![Just("a"), Just("b")]
    }

    fn fuzz_expr(depth: u32) -> BoxedStrategy<String> {
        if depth == 0 {
            prop_oneof![fuzz_literal(), fuzz_column().prop_map(str::to_owned),].boxed()
        } else {
            prop_oneof![
                4 => fuzz_expr(0),
                2 => (fuzz_expr(depth - 1), prop_oneof![
                    Just("+"), Just("-"), Just("*"), Just("/"),
                    Just("="), Just("!="), Just("<"), Just("<="),
                    Just(">"), Just(">="), Just("AND"), Just("OR"),
                ], fuzz_expr(depth - 1))
                    .prop_map(|(l, op, r)| format!("({l} {op} {r})")),
                1 => fuzz_expr(depth - 1).prop_map(|e| format!("(-{e})")),
                1 => fuzz_expr(depth - 1).prop_map(|e| format!("(NOT {e})")),
                1 => fuzz_expr(depth - 1).prop_map(|e| format!("ABS({e})")),
            ]
            .boxed()
        }
    }

    fn fuzz_predicate() -> BoxedStrategy<String> {
        fuzz_expr(2)
    }

    fn fuzz_select_sql() -> BoxedStrategy<String> {
        use std::fmt::Write as _;

        (
            prop::collection::vec(fuzz_expr(2), 1..=3),
            prop::option::of(fuzz_predicate()),
            prop::option::of(fuzz_column()),
            prop::option::of(0_u8..=5),
        )
            .prop_map(|(cols, where_clause, order_by, limit)| {
                let mut sql = format!("SELECT {} FROM t", cols.join(", "));
                if let Some(pred) = where_clause {
                    write!(sql, " WHERE {pred}").expect("writing to String should not fail");
                }
                if let Some(col) = order_by {
                    write!(sql, " ORDER BY {col}").expect("writing to String should not fail");
                }
                if let Some(lim) = limit {
                    write!(sql, " LIMIT {lim}").expect("writing to String should not fail");
                }
                sql
            })
            .boxed()
    }

    fn fuzz_window_func() -> impl Strategy<Value = &'static str> {
        prop_oneof![
            Just("ROW_NUMBER"),
            Just("RANK"),
            Just("DENSE_RANK"),
            Just("SUM"),
            Just("COUNT"),
            Just("AVG"),
        ]
    }

    fn fuzz_window_frame() -> impl Strategy<Value = String> {
        prop_oneof![
            Just("ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW".to_owned()),
            Just("ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING".to_owned()),
            Just("ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING".to_owned()),
            Just("RANGE BETWEEN CURRENT ROW AND CURRENT ROW".to_owned()),
            Just("GROUPS BETWEEN CURRENT ROW AND CURRENT ROW".to_owned()),
        ]
    }

    fn fuzz_window_exclude() -> impl Strategy<Value = &'static str> {
        prop_oneof![
            Just(""),
            Just(" EXCLUDE CURRENT ROW"),
            Just(" EXCLUDE TIES"),
            Just(" EXCLUDE GROUP"),
        ]
    }

    fn fuzz_window_select_sql() -> BoxedStrategy<String> {
        (
            fuzz_window_func(),
            fuzz_column(),
            prop::option::of(Just("b")),
            fuzz_window_frame(),
            fuzz_window_exclude(),
        )
            .prop_map(|(func, order_col, partition_col, frame, exclude)| {
                let over = if let Some(partition_col) = partition_col {
                    format!("PARTITION BY {partition_col} ORDER BY {order_col} {frame}{exclude}")
                } else {
                    format!("ORDER BY {order_col} {frame}{exclude}")
                };

                let call = match func {
                    "ROW_NUMBER" | "RANK" | "DENSE_RANK" => format!("{func}() OVER ({over})"),
                    _ => format!("{func}(a) OVER ({over})"),
                };

                format!("SELECT a, b, {call} AS w FROM t")
            })
            .boxed()
    }

    fn fuzz_insert_sql() -> BoxedStrategy<String> {
        (fuzz_literal(), fuzz_literal())
            .prop_map(|(a, b)| format!("INSERT INTO t (a, b) VALUES ({a}, {b})"))
            .boxed()
    }

    fn fuzz_update_sql() -> BoxedStrategy<String> {
        (fuzz_column(), fuzz_expr(2), fuzz_predicate())
            .prop_map(|(col, expr, pred)| format!("UPDATE t SET {col} = {expr} WHERE {pred}"))
            .boxed()
    }

    fn fuzz_delete_sql() -> BoxedStrategy<String> {
        fuzz_predicate()
            .prop_map(|pred| format!("DELETE FROM t WHERE {pred}"))
            .boxed()
    }

    fn fuzz_supported_sql() -> BoxedStrategy<String> {
        prop_oneof![
            4 => fuzz_select_sql(),
            2 => fuzz_window_select_sql(),
            2 => fuzz_insert_sql(),
            1 => fuzz_update_sql(),
            1 => fuzz_delete_sql(),
        ]
        .boxed()
    }

    fn first_result_expr(select: &SelectStatement) -> &Expr {
        let SelectCore::Select { columns, .. } = &select.body.select else {
            unreachable!("expected SELECT core");
        };
        let ResultColumn::Expr { expr, .. } = &columns[0] else {
            unreachable!("expected expression result column");
        };
        expr
    }

    #[test]
    fn test_window_spec_placeholder_count_tracks_bounded_rows_frame_and_exclude_ties() {
        let stmt = select_sql(
            "SELECT SUM(a) OVER (PARTITION BY ? ORDER BY ? ROWS BETWEEN ? PRECEDING AND ? FOLLOWING EXCLUDE TIES) FROM t",
        );
        let Expr::FunctionCall {
            over: Some(spec), ..
        } = first_result_expr(&stmt)
        else {
            unreachable!("expected window function expression");
        };

        assert_eq!(count_anon_placeholders_in_window_spec(spec), 4);
        let frame = spec.frame.as_ref().expect("window frame should exist");
        assert_eq!(frame.exclude, Some(fsqlite_ast::FrameExclude::Ties));
    }

    #[test]
    fn test_window_spec_placeholder_count_ignores_groups_current_row_exclude_group() {
        let stmt = select_sql(
            "SELECT SUM(a) OVER (ORDER BY a GROUPS BETWEEN CURRENT ROW AND CURRENT ROW EXCLUDE GROUP) FROM t",
        );
        let Expr::FunctionCall {
            over: Some(spec), ..
        } = first_result_expr(&stmt)
        else {
            unreachable!("expected window function expression");
        };

        assert_eq!(count_anon_placeholders_in_window_spec(spec), 0);
        let frame = spec.frame.as_ref().expect("window frame should exist");
        assert_eq!(frame.exclude, Some(fsqlite_ast::FrameExclude::Group));
    }

    #[test]
    fn test_function_placeholder_count_includes_in_call_order_by_and_filter() {
        let expr = expr_sql("group_concat(a ORDER BY ?) FILTER (WHERE b = ?)");
        assert_eq!(
            count_anon_placeholders(&expr),
            2,
            "function modifiers participate in lexical bind-slot accounting"
        );
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(256))]

        #[test]
        fn test_parser_vdbe_codegen_supported_sql_no_panic(sql in fuzz_supported_sql()) {
            let Some((statement, tail)) =
                parse_first_statement_with_tail(&sql).expect("generated SQL should parse without parser panics")
            else {
                prop_assert!(false, "generator produced no statement: {}", sql);
                return Ok(());
            };
            prop_assert_eq!(tail, sql.len(), "parser left trailing SQL for generated input: {}", sql);

            let mut builder = ProgramBuilder::new();
            let schema = test_schema();
            let ctx = CodegenContext::default();
            let result = match statement {
                Statement::Select(stmt) => catch_unwind(AssertUnwindSafe(|| {
                        let _ = codegen_select(&mut builder, &stmt, &schema, &ctx);
                })),
                Statement::Insert(stmt) => catch_unwind(AssertUnwindSafe(|| {
                        let _ = codegen_insert(&mut builder, &stmt, &schema, &ctx);
                })),
                Statement::Update(stmt) => catch_unwind(AssertUnwindSafe(|| {
                        let _ = codegen_update(&mut builder, &stmt, &schema, &ctx);
                })),
                Statement::Delete(stmt) => catch_unwind(AssertUnwindSafe(|| {
                        let _ = codegen_delete(&mut builder, &stmt, &schema, &ctx);
                })),
                other => {
                    prop_assert!(
                        false,
                        "unsupported generated statement variant for sql {sql}: {other:?}"
                    );
                    return Ok(());
                }
            };

            prop_assert!(result.is_ok(), "parser->vdbe codegen panicked for sql: {}", sql);
        }
    }

    fn lower_name_eq_param(n: u32) -> Box<Expr> {
        Box::new(expr_sql(&format!("lower(name) = ?{n}")))
    }

    fn lower_name_range_params(lower: u32, upper: u32) -> Box<Expr> {
        Box::new(expr_sql(&format!(
            "lower(name) >= ?{lower} AND lower(name) < ?{upper}"
        )))
    }

    fn col_eq_param(col: &str, n: u32) -> Box<Expr> {
        Box::new(Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare(col), Span::ZERO)),
            op: AstBinaryOp::Eq,
            right: Box::new(placeholder(n)),
            span: Span::ZERO,
        })
    }

    fn simple_select(
        cols: &[&str],
        table: &str,
        where_clause: Option<Box<Expr>>,
    ) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: cols
                        .iter()
                        .map(|c| ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare(*c), Span::ZERO),
                            alias: None,
                        })
                        .collect(),
                    from: Some(from_table(table)),
                    where_clause,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    fn simple_select_as(
        cols: &[&str],
        table: &str,
        alias: &str,
        where_clause: Option<Box<Expr>>,
    ) -> SelectStatement {
        let mut stmt = simple_select(cols, table, where_clause);
        let SelectCore::Select { from, .. } = &mut stmt.body.select else {
            unreachable!("simple_select always constructs a SELECT core");
        };
        *from = Some(from_table_as(table, alias));
        stmt
    }

    fn star_select(table: &str) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    fn star_select_with_limit(table: &str, limit: i64) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: Some(LimitClause {
                limit: Expr::Literal(Literal::Integer(limit), Span::ZERO),
                offset: None,
            }),
        }
    }

    fn star_select_with_limit_offset(table: &str, limit: i64, offset: i64) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: Some(LimitClause {
                limit: Expr::Literal(Literal::Integer(limit), Span::ZERO),
                offset: Some(Expr::Literal(Literal::Integer(offset), Span::ZERO)),
            }),
        }
    }

    /// bd-2dgf5 regression fixture: `t(id INTEGER PRIMARY KEY, k INTEGER, v TEXT)`
    /// with a single-column ascending index on `k`.
    ///
    /// Keep `type_name` populated so the fixture mirrors an ordinary parsed
    /// schema. Comparison code nevertheless treats `ColumnInfo::affinity` as
    /// authoritative; statement-local materialized schemas legitimately have
    /// expression affinity while carrying no declared SQL type text.
    fn bd_2dgf5_table() -> TableSchema {
        let typed = |name: &str, affinity: char, is_ipk: bool, ty: &str| {
            let mut col = ColumnInfo::basic(name, affinity, is_ipk);
            col.type_name = Some(ty.to_owned());
            col
        };
        TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                typed("id", 'D', true, "INTEGER"),
                typed("k", 'D', false, "INTEGER"),
                typed("v", 'B', false, "TEXT"),
            ],
            indexes: vec![IndexSchema {
                name: "idx_t_k".to_owned(),
                root_page: 3,
                columns: vec!["k".to_owned()],
                key_expressions: vec!["k".to_owned()],
                key_sort_directions: vec![],
                where_clause: None,
                is_unique: false,
                key_collations: vec![],
                conflict_action: None,
            }],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            check_constraints: Vec::new(),
            foreign_keys: Vec::new(),
        }
    }

    /// bd-2dgf5. `cmp_p5` is `0x80 | comparison_affinity(...)`. For an INTEGER
    /// column compared against an integer literal no affinity conversion is
    /// needed, so the low bits are clear and the affinity gate in
    /// `aggregate_index_eq_seek_target` ADMITS the seek.
    ///
    /// This assertion is load-bearing: it is the reason the affinity gate can be
    /// kept as cheap insurance against skewed comparisons (`k = '2'`) without
    /// disabling the common indexed-integer-equality case. If it ever flips,
    /// the aggregate index seek silently degrades to a full scan and the
    /// bd-2dgf5 speedup disappears with no test failure elsewhere.
    #[test]
    fn resolved_index_range_comparison_carries_affinity_for_integer_column() {
        let table = bd_2dgf5_table();
        let schema = vec![table.clone()];
        let target = Expr::Literal(Literal::Integer(2), Span::ZERO);

        let comparison = resolved_index_range_comparison(&table, None, &schema, "k", &target);

        assert_eq!(
            comparison.cmp_p5 & 0x80,
            0x80,
            "the 0x80 bit is always set by ResolvedComparisonInfo::new"
        );
        assert_ne!(
            comparison.cmp_p5 & !0x80,
            0,
            "an INTEGER column compared against an integer literal DOES carry a \
             comparison affinity; gating the aggregate index seek on \
             `(cmp_p5 & !0x80) == 0` therefore rejects exactly the case it was \
             meant to accelerate, turning the seek into a silent no-op"
        );
    }

    /// bd-2dgf5: the aggregate seek must engage for a plain single-column
    /// ascending index and must decline everything it cannot probe with a
    /// one-key-term + rowid record.
    #[test]
    fn aggregate_index_eq_seek_target_contract() {
        let table = bd_2dgf5_table();
        let two = Expr::Literal(Literal::Integer(2), Span::ZERO);

        let indexed_eq = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("k"), Span::ZERO)),
            op: fsqlite_ast::BinaryOp::Eq,
            right: Box::new(two.clone()),
            span: Span::ZERO,
        };
        let (idx, targets) = aggregate_index_eq_seek_target(Some(&indexed_eq), &table, None)
            .expect("indexed column equality must select the index seek");
        assert_eq!(idx.name, "idx_t_k");
        assert_eq!(targets.len(), 1);
        assert!(matches!(targets[0], Expr::Literal(Literal::Integer(2), _)));

        // Unindexed column: no seek.
        let unindexed_eq = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("v"), Span::ZERO)),
            op: fsqlite_ast::BinaryOp::Eq,
            right: Box::new(two.clone()),
            span: Span::ZERO,
        };
        assert!(aggregate_index_eq_seek_target(Some(&unindexed_eq), &table, None).is_none());

        // Rowid / INTEGER PRIMARY KEY has no secondary index: no seek here.
        let rowid_eq = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("id"), Span::ZERO)),
            op: fsqlite_ast::BinaryOp::Eq,
            right: Box::new(two.clone()),
            span: Span::ZERO,
        };
        assert!(aggregate_index_eq_seek_target(Some(&rowid_eq), &table, None).is_none());

        // No WHERE clause at all: no seek.
        assert!(aggregate_index_eq_seek_target(None, &table, None).is_none());

        // Non-equality predicate: no seek.
        let range = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("k"), Span::ZERO)),
            op: fsqlite_ast::BinaryOp::Gt,
            right: Box::new(two),
            span: Span::ZERO,
        };
        assert!(aggregate_index_eq_seek_target(Some(&range), &table, None).is_none());
    }

    #[test]
    fn in_list_residual_detection_and_routing() {
        let table = bd_2dgf5_table();
        // Detection: `k IN (1, 2) AND v = 3` — an IN-list CONJUNCT plus a residual.
        let e = parse_sql_expr("k IN (1, 2) AND v = 3").expect("parse");
        let r = index_integer_in_list_residual_target(Some(&e), &table, None);
        assert!(r.is_some(), "IN-list + residual must be detected");
        let (idx, ints, has_residual) = r.unwrap();
        assert_eq!(idx.name, "idx_t_k");
        assert_eq!(ints, vec![1, 2]);
        assert!(has_residual);
        // Residual-free still reported (has_residual = false).
        let e2 = parse_sql_expr("k IN (1, 2)").expect("parse");
        assert_eq!(
            index_integer_in_list_residual_target(Some(&e2), &table, None).map(|(_, _, h)| h),
            Some(false)
        );
        // Routing: COUNT(*) with an IN-list + residual must reach the seek (SeekGE in the program).
        let ops = bd_2dgf5_program("SELECT COUNT(*) FROM t WHERE k IN (1, 2) AND v = 3");
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "COUNT(*) IN-list + residual must seek (SeekGE), got: {:?}",
            ops.iter().map(|o| o.opcode).collect::<Vec<_>>()
        );
    }

    /// Compile `sql` against [`bd_2dgf5_table`] and return the emitted opcodes.
    fn bd_2dgf5_program(sql: &str) -> Vec<VdbeOp> {
        let stmt = select_sql(sql);
        let schema = vec![bd_2dgf5_table()];
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default())
            .expect("bd-2dgf5 fixture SELECT should compile");
        b.finish().expect("program should finish").ops().to_vec()
    }

    #[test]
    fn single_group_aggregate_limit_preserves_textual_placeholder_indices() {
        let ops = bd_2dgf5_program("SELECT COUNT(*) FROM t WHERE id > ? LIMIT ?");
        let variable_indices: Vec<i32> = ops
            .iter()
            .filter(|op| op.opcode == Opcode::Variable)
            .map(|op| op.p1)
            .collect();
        assert_eq!(
            variable_indices,
            vec![2, 1],
            "LIMIT is emitted before the scan, but its anonymous parameter must retain \
             its second-in-SQL index"
        );

        let limit_variable = ops
            .iter()
            .position(|op| op.opcode == Opcode::Variable && op.p1 == 2)
            .expect("LIMIT parameter must be emitted");
        assert_eq!(
            ops.get(limit_variable + 1).map(|op| op.opcode),
            Some(Opcode::MustBeInt),
            "dynamic LIMIT must be validated as a losslessly coercible integer"
        );

        let ops = bd_2dgf5_program("SELECT COUNT(*) FROM t LIMIT ? OFFSET ?");
        let variable_indices: Vec<i32> = ops
            .iter()
            .filter(|op| op.opcode == Opcode::Variable)
            .map(|op| op.p1)
            .collect();
        assert_eq!(variable_indices, vec![1, 2]);
        for variable in ops
            .iter()
            .enumerate()
            .filter(|(_, op)| op.opcode == Opcode::Variable)
            .map(|(index, _)| index)
        {
            assert_eq!(
                ops.get(variable + 1).map(|op| op.opcode),
                Some(Opcode::MustBeInt),
                "dynamic LIMIT and OFFSET must both receive integer validation"
            );
        }
    }

    #[test]
    fn grouped_aggregate_limit_validates_and_preserves_numbered_slots() {
        let ops = bd_2dgf5_program(
            "SELECT k, COUNT(*) FROM t WHERE v = ?1 GROUP BY k LIMIT ?2 OFFSET ?3",
        );
        let variables: Vec<i32> = ops
            .iter()
            .filter(|op| op.opcode == Opcode::Variable)
            .map(|op| op.p1)
            .collect();
        assert_eq!(
            variables,
            vec![2, 3, 1],
            "GROUP BY codegen emits LIMIT/OFFSET before the scan, but numbered \
             parameters must keep their SQL-text slots"
        );

        let limit_variable = ops
            .iter()
            .position(|op| op.opcode == Opcode::Variable && op.p1 == 2)
            .expect("GROUP BY LIMIT parameter must be emitted");
        assert_eq!(
            ops.get(limit_variable + 1).map(|op| op.opcode),
            Some(Opcode::MustBeInt),
            "GROUP BY LIMIT must be losslessly coerced to integer"
        );
        let zero_guard = ops
            .iter()
            .enumerate()
            .skip(limit_variable + 1)
            .find(|(_, op)| op.opcode == Opcode::IfNot)
            .map(|(index, _)| index)
            .expect("GROUP BY LIMIT zero guard must be emitted");
        let offset_variable = ops
            .iter()
            .position(|op| op.opcode == Opcode::Variable && op.p1 == 3)
            .expect("GROUP BY OFFSET parameter must be emitted");
        assert!(
            zero_guard < offset_variable,
            "GROUP BY LIMIT zero must short-circuit before OFFSET evaluation"
        );
        assert_eq!(
            ops.get(offset_variable + 1).map(|op| op.opcode),
            Some(Opcode::MustBeInt),
            "GROUP BY OFFSET must be losslessly coerced to integer"
        );

        let integer_literal_ops =
            bd_2dgf5_program("SELECT k, COUNT(*) FROM t GROUP BY k LIMIT 2 OFFSET 1");
        assert!(
            !integer_literal_ops
                .iter()
                .any(|op| op.opcode == Opcode::MustBeInt),
            "exact integer LIMIT/OFFSET literals must avoid redundant coercion opcodes"
        );

        let text_literal_ops =
            bd_2dgf5_program("SELECT k, COUNT(*) FROM t GROUP BY k LIMIT '2' OFFSET '1'");
        assert_eq!(
            text_literal_ops
                .iter()
                .filter(|op| op.opcode == Opcode::MustBeInt)
                .count(),
            2,
            "coercible text LIMIT/OFFSET literals must each be validated at runtime"
        );
    }

    #[test]
    fn nonaggregate_eq_residual_limit_validates_and_preserves_numbered_slots() {
        let ops = bd_2dgf5_program("SELECT id FROM t WHERE k = 2 AND v = ?1 LIMIT ?2 OFFSET ?3");
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_k")),
            "canonicalized/numbered residual + LIMIT/OFFSET must retain the equality seek"
        );

        let variables: Vec<i32> = ops
            .iter()
            .filter(|op| op.opcode == Opcode::Variable)
            .map(|op| op.p1)
            .collect();
        assert_eq!(
            variables,
            vec![2, 3, 1, 1],
            "LIMIT and OFFSET emit first, but must retain their second/third textual slots; \
             the residual is emitted once per mutually-exclusive seek/fallback path at slot 1"
        );

        let limit_variable = ops
            .iter()
            .position(|op| op.opcode == Opcode::Variable && op.p1 == 2)
            .expect("LIMIT parameter must be emitted");
        assert_eq!(
            ops.get(limit_variable + 1).map(|op| op.opcode),
            Some(Opcode::MustBeInt),
            "dynamic equality-scan LIMIT must be losslessly coerced to integer"
        );
        let zero_guard = ops
            .iter()
            .enumerate()
            .skip(limit_variable + 1)
            .find(|(_, op)| op.opcode == Opcode::IfNot)
            .map(|(index, _)| index)
            .expect("LIMIT zero guard must be emitted");
        let offset_variable = ops
            .iter()
            .position(|op| op.opcode == Opcode::Variable && op.p1 == 3)
            .expect("OFFSET parameter must be emitted");
        assert!(
            zero_guard < offset_variable,
            "LIMIT zero must short-circuit before OFFSET is evaluated"
        );
        assert_eq!(
            ops.get(offset_variable + 1).map(|op| op.opcode),
            Some(Opcode::MustBeInt),
            "dynamic equality-scan OFFSET must be losslessly coerced to integer"
        );
    }

    #[test]
    fn nonaggregate_eq_residual_raw_non_numbered_slots_decline_seek() {
        for sql in [
            "SELECT id FROM t WHERE k = 2 AND v = ? LIMIT ? OFFSET ?",
            "SELECT id FROM t WHERE k = 2 AND v = :residual LIMIT :lim OFFSET :off",
        ] {
            let ops = bd_2dgf5_program(sql);
            assert!(
                !ops.iter().any(|op| op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "idx_t_k")),
                "raw anonymous/named AST must decline the residual optimization until \
                 connection-level canonicalization assigns stable slots: `{sql}`"
            );
        }
    }

    /// Index of the first instruction of the scan fallback.
    ///
    /// The fallback always opens the table and immediately rewinds it. The
    /// *non-covering* seek also opens the table, but follows that with the index
    /// `OpenRead`, never a `Rewind` — so "first `OpenRead` of the table" is not the
    /// boundary, and using it silently yields an empty fast path.
    fn bd_2dgf5_fallback_start(ops: &[VdbeOp]) -> usize {
        ops.windows(2)
            .position(|pair| {
                pair[0].opcode == Opcode::OpenRead
                    && matches!(&pair[0].p4, P4::Table(name) if name == "t")
                    && pair[1].opcode == Opcode::Rewind
            })
            .unwrap_or(ops.len())
    }

    /// The seek fast path: everything the program runs before falling back to a scan.
    fn bd_2dgf5_seek_fast_path(ops: &[VdbeOp]) -> &[VdbeOp] {
        &ops[..bd_2dgf5_fallback_start(ops)]
    }

    /// bd-2dgf5: an aggregate over `<ipk> = <int literal>` must seek the single row by
    /// rowid (`SeekRowid`) with no `Rewind`/`Next` table walk. The neighbouring shapes
    /// that carry affinity or are not a bare rowid equality must decline the seek and
    /// keep scanning, so the seek stays exact. Asserted on the emitted program because
    /// EQP renders separately and can disagree (bd-jyyae); the differential oracle test
    /// `rowid_eq_aggregate_matches_sqlite` covers the results.
    #[test]
    fn bd_2dgf5_rowid_equality_aggregate_seeks_single_row() {
        // Scope: a POSITIVE integer literal on the rowid. `SUM`/`MIN`/`COUNT(col)` route
        // through codegen_select_aggregate (COUNT(*) is intercepted elsewhere).
        for sql in [
            "SELECT SUM(v) FROM t WHERE id = 2",
            "SELECT SUM(k) FROM t WHERE 2 = id",
            "SELECT MIN(v) FROM t WHERE id = 2",
            "SELECT COUNT(k) FROM t WHERE id = 100",
        ] {
            let ops = bd_2dgf5_program(sql);
            assert!(
                ops.iter().any(|op| op.opcode == Opcode::SeekRowid),
                "`{sql}` must seek the row by rowid"
            );
            assert!(
                !ops.iter().any(|op| op.opcode == Opcode::Rewind),
                "`{sql}` is a unique rowid point lookup: it must not scan (no Rewind)"
            );
            assert!(
                ops.iter().any(|op| op.opcode == Opcode::AggStep),
                "`{sql}` must still accumulate the seeked row"
            );
        }

        // A secondary-index equality plus a rowid residual takes the later
        // equality-prefix residual path.  It must seek the index, visit the table row,
        // re-apply the full WHERE, and never fall back to a table scan.
        let residual_ops = bd_2dgf5_program("SELECT SUM(v) FROM t WHERE id = 2 AND k = 3");
        assert!(
            residual_ops
                .iter()
                .any(|op| matches!(&op.p4, P4::Index(name) if name == "idx_t_k")),
            "indexed residual path must open idx_t_k"
        );
        for required in [
            Opcode::SeekGE,
            Opcode::IdxRowid,
            Opcode::SeekRowid,
            Opcode::AggStep,
            Opcode::Next,
        ] {
            assert!(
                residual_ops.iter().any(|op| op.opcode == required),
                "indexed residual path must emit {required:?}"
            );
        }
        assert!(
            !residual_ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "indexed residual path must not full-scan the table"
        );

        // Non-integer literal constants use the newer exact-or-reject rowid
        // probe: MustBeInt converts values such as '2' losslessly and jumps to
        // aggregate finalization for a non-integral real such as 2.5.  Both
        // shapes avoid a table scan, as covered by agg_rowid_eq_coerced_oracle.
        for sql in [
            "SELECT SUM(v) FROM t WHERE id = 2.5",
            "SELECT SUM(v) FROM t WHERE id = '2'",
        ] {
            let ops = bd_2dgf5_program(sql);
            assert!(
                ops.iter().any(|op| op.opcode == Opcode::MustBeInt),
                "`{sql}` must coerce the rowid probe exactly"
            );
            assert!(
                ops.iter().any(|op| op.opcode == Opcode::SeekRowid),
                "`{sql}` must use the exact-or-reject rowid probe"
            );
            assert!(
                !ops.iter().any(|op| op.opcode == Opcode::Rewind),
                "`{sql}` must not scan after exact-or-reject coercion"
            );
        }

        // A rowid equality with an unindexed residual still probes the unique
        // row directly and re-applies the full predicate before AggStep.
        let residual_ops = bd_2dgf5_program("SELECT SUM(v) FROM t WHERE id = 2 AND v = '3'");
        assert!(
            residual_ops.iter().any(|op| op.opcode == Opcode::SeekRowid),
            "rowid equality plus residual must still use the unique rowid probe"
        );
        assert!(
            residual_ops.iter().any(|op| op.opcode == Opcode::AggStep),
            "rowid equality plus residual must retain aggregate accumulation"
        );
        assert!(
            !residual_ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "rowid equality plus residual must not scan the table"
        );

        // Shapes the direct rowid seek still MUST decline. `id = -5` parses as
        // unary-negate over an integer literal (not a simple constant), while
        // NOT INDEXED explicitly retains the scan contract.
        for sql in [
            "SELECT SUM(v) FROM t WHERE id = -5",
            "SELECT SUM(v) FROM t NOT INDEXED WHERE id = 2",
        ] {
            let ops = bd_2dgf5_program(sql);
            assert!(
                ops.iter().any(|op| op.opcode == Opcode::Rewind),
                "`{sql}` must decline the rowid seek and scan (Rewind present)"
            );
        }
    }

    /// bd-2dgf5: an aggregate over a rowid *range* must position with `SeekGE`/`SeekGT`
    /// on a lower bound (not a full `Rewind` of every row), and an upper bound must add a
    /// `Gt`/`Ge` early-exit. Results are covered by `rowid_range_aggregate_matches_sqlite`.
    #[test]
    fn bd_2dgf5_rowid_range_aggregate_positions_and_bounds() {
        // Lower-bounded ranges seek to the start instead of rewinding.
        for sql in [
            "SELECT SUM(v) FROM t WHERE id >= 3",
            "SELECT COUNT(k) FROM t WHERE id > 3",
            "SELECT SUM(k) FROM t WHERE id BETWEEN 2 AND 5",
        ] {
            let ops = bd_2dgf5_program(sql);
            assert!(
                ops.iter()
                    .any(|op| matches!(op.opcode, Opcode::SeekGE | Opcode::SeekGT)),
                "`{sql}` must seek to the lower bound"
            );
            assert!(
                !ops.iter().any(|op| op.opcode == Opcode::Rewind),
                "`{sql}` has a lower bound: it must not rewind the whole table"
            );
            assert!(
                ops.iter().any(|op| op.opcode == Opcode::AggStep),
                "`{sql}` must still accumulate"
            );
        }
        // Upper-bounded ranges early-exit once the cursor passes the bound.
        for sql in [
            "SELECT SUM(v) FROM t WHERE id <= 3",
            "SELECT COUNT(*) FROM t WHERE id < 3",
        ] {
            let ops = bd_2dgf5_program(sql);
            assert!(
                ops.iter()
                    .any(|op| matches!(op.opcode, Opcode::Gt | Opcode::Ge)),
                "`{sql}` must emit an upper-bound early-exit (Gt/Ge)"
            );
        }
        // GROUP BY / extra predicates / NOT INDEXED must not take the lone-range path.
        let grouped = bd_2dgf5_program("SELECT SUM(k) FROM t WHERE id <= 3 GROUP BY k");
        assert!(
            grouped.iter().any(|op| op.opcode == Opcode::Rewind),
            "GROUP BY must not take the rowid-range aggregate path"
        );
    }

    /// bd-2dgf5: `SUM(v) FROM t WHERE k IN (<int literals>)` (k INTEGER-affinity, indexed)
    /// seeks the index once per DISTINCT value and never full-scans. Duplicate values are
    /// de-duped (one seek). Results are covered by `index_in_list_aggregate_matches_sqlite`.
    #[test]
    fn bd_2dgf5_index_in_list_aggregate_seeks_per_distinct_value() {
        let seeks = |sql: &str| -> usize {
            bd_2dgf5_program(sql)
                .iter()
                .filter(|op| op.opcode == Opcode::SeekGE)
                .count()
        };
        // Three distinct values -> three seeks, no Rewind.
        let ops = bd_2dgf5_program("SELECT SUM(v) FROM t WHERE k IN (1, 2, 3)");
        assert_eq!(
            ops.iter().filter(|op| op.opcode == Opcode::SeekGE).count(),
            3,
            "k IN (1,2,3) must seek once per distinct value"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "k IN (1,2,3) must not full-scan"
        );
        assert!(ops.iter().any(|op| op.opcode == Opcode::AggStep));
        // Duplicates collapse to a single seek.
        assert_eq!(seeks("SELECT SUM(v) FROM t WHERE k IN (2, 2, 2)"), 1);
        assert_eq!(seeks("SELECT COUNT(k) FROM t WHERE k IN (1, 1, 2)"), 2);

        // Shapes the seek MUST decline (must Rewind-scan): text/real elements, NOT IN, extra
        // predicate, GROUP BY, NOT INDEXED, and a non-INTEGER-affinity column.
        for sql in [
            "SELECT SUM(v) FROM t WHERE k IN (2, 3.0)",
            "SELECT SUM(v) FROM t WHERE k IN ('2', '3')",
            "SELECT SUM(v) FROM t WHERE k NOT IN (1, 2)",
            "SELECT SUM(v) FROM t WHERE k IN (1, 2) AND id < 3",
            "SELECT SUM(v) FROM t WHERE k IN (1, 2) GROUP BY k",
            "SELECT SUM(v) FROM t NOT INDEXED WHERE k IN (1, 2)",
            // `v` is TEXT-affinity in the fixture: an integer-list seek would be unsafe.
            "SELECT SUM(k) FROM t WHERE v IN (1, 2)",
        ] {
            assert!(
                bd_2dgf5_program(sql)
                    .iter()
                    .any(|op| op.opcode == Opcode::Rewind),
                "`{sql}` must decline the IN-list seek and scan (Rewind present)"
            );
        }
    }

    /// bd-2dgf5: non-aggregate `SELECT <cols> FROM t WHERE <int col> IN (<int literals>)`
    /// seeks the index once per DISTINCT value and never full-scans; ORDER BY / LIMIT /
    /// DISTINCT / a non-INTEGER column / NOT IN decline to the scan. Results are covered by
    /// `index_in_list_nonaggregate_matches_sqlite`.
    #[test]
    fn bd_2dgf5_nonaggregate_in_list_seeks_per_distinct_value() {
        let seeks = |sql: &str| -> usize {
            bd_2dgf5_program(sql)
                .iter()
                .filter(|op| op.opcode == Opcode::SeekGE)
                .count()
        };
        let ops = bd_2dgf5_program("SELECT id, v FROM t WHERE k IN (1, 2, 3)");
        assert_eq!(seeks("SELECT id, v FROM t WHERE k IN (1, 2, 3)"), 3);
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "k IN (1,2,3) must not full-scan"
        );
        assert!(ops.iter().any(|op| op.opcode == Opcode::ResultRow));
        assert_eq!(seeks("SELECT id FROM t WHERE k IN (2, 2)"), 1);

        for sql in [
            "SELECT id FROM t WHERE k IN (1, 2) ORDER BY id",
            "SELECT id FROM t WHERE k IN (1, 2) LIMIT 3",
            "SELECT DISTINCT id FROM t WHERE k IN (1, 2)",
            "SELECT id FROM t WHERE k IN (2, 3.0)",
            "SELECT id FROM t WHERE k NOT IN (1, 2)",
            "SELECT id FROM t WHERE v IN (1, 2)",
            "SELECT id FROM t NOT INDEXED WHERE k IN (1, 2)",
        ] {
            assert!(
                bd_2dgf5_program(sql)
                    .iter()
                    .any(|op| op.opcode == Opcode::Rewind),
                "`{sql}` must decline the non-aggregate IN-list seek (Rewind present)"
            );
        }
    }

    /// bd-2dgf5: `SELECT <cols> FROM t WHERE <rowid> IN (<int literals>)` does one `SeekRowid`
    /// per distinct value and never full-scans. A single rowid ASC/DESC ordering is served by
    /// the sorted seek sequence; LIMIT / DISTINCT / unsupported ORDER BY / non-integer or
    /// negative elements / NOT IN decline to a Rewind scan. Covered by
    /// `rowid_in_list_matches_sqlite`.
    #[test]
    fn bd_2dgf5_rowid_in_list_point_lookups() {
        let seek_rowids = |sql: &str| -> usize {
            bd_2dgf5_program(sql)
                .iter()
                .filter(|op| op.opcode == Opcode::SeekRowid)
                .count()
        };
        let ops = bd_2dgf5_program("SELECT id, v FROM t WHERE id IN (5, 10, 15)");
        assert_eq!(
            seek_rowids("SELECT id, v FROM t WHERE id IN (5, 10, 15)"),
            3
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "id IN (5,10,15) must not full-scan"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "rowid IN uses SeekRowid, not an index SeekGE"
        );
        assert!(ops.iter().any(|op| op.opcode == Opcode::ResultRow));
        assert_eq!(seek_rowids("SELECT id FROM t WHERE id IN (5, 5, 10)"), 2);

        for sql in [
            "SELECT id FROM t WHERE id IN (5, 10) ORDER BY id ASC",
            "SELECT id FROM t WHERE id IN (5, 10) ORDER BY id DESC",
        ] {
            let ordered_ops = bd_2dgf5_program(sql);
            assert_eq!(
                ordered_ops
                    .iter()
                    .filter(|op| op.opcode == Opcode::SeekRowid)
                    .count(),
                2,
                "`{sql}` must seek each distinct rowid"
            );
            assert!(
                !ordered_ops.iter().any(|op| op.opcode == Opcode::Rewind),
                "`{sql}` must not full-scan"
            );
            assert!(
                !ordered_ops.iter().any(|op| op.opcode == Opcode::SorterOpen),
                "`{sql}` must not open a sorter"
            );
        }

        for sql in [
            "SELECT id FROM t WHERE id IN (5, 10) LIMIT 1",
            "SELECT DISTINCT id FROM t WHERE id IN (5, 10)",
            "SELECT id FROM t WHERE id IN (2.0, 5)",
            "SELECT id FROM t WHERE id IN (-5, 2)",
            "SELECT id FROM t WHERE id NOT IN (5, 10)",
            "SELECT id FROM t NOT INDEXED WHERE id IN (5, 10)",
        ] {
            assert!(
                bd_2dgf5_program(sql)
                    .iter()
                    .any(|op| op.opcode == Opcode::Rewind),
                "`{sql}` must decline the rowid IN-list seek (Rewind present)"
            );
        }
    }

    /// bd-2dgf5: `col = a OR col = b OR ...` on one indexed column normalizes to the IN-list
    /// seek (secondary index -> SeekGE per value; rowid -> SeekRowid per value). Mixed columns,
    /// mixed operators, NOT IN, real literals, and AND-mixed precedence decline to the scan.
    /// Results are covered by `or_of_equalities_matches_sqlite`.
    #[test]
    fn bd_2dgf5_or_of_equalities_normalizes_to_seek() {
        // Secondary index (k): SeekGE per distinct value, no Rewind.
        let ki = bd_2dgf5_program("SELECT id FROM t WHERE k = 2 OR k = 5");
        assert_eq!(
            ki.iter().filter(|op| op.opcode == Opcode::SeekGE).count(),
            2,
            "k = 2 OR k = 5 must seek per distinct value"
        );
        assert!(!ki.iter().any(|op| op.opcode == Opcode::Rewind));
        // Duplicate values collapse.
        assert_eq!(
            bd_2dgf5_program("SELECT id FROM t WHERE k = 2 OR k = 2")
                .iter()
                .filter(|op| op.opcode == Opcode::SeekGE)
                .count(),
            1
        );
        // Rowid (id): SeekRowid per distinct value.
        let ri = bd_2dgf5_program("SELECT id FROM t WHERE id = 2 OR id = 3");
        assert_eq!(
            ri.iter()
                .filter(|op| op.opcode == Opcode::SeekRowid)
                .count(),
            2
        );
        assert!(!ri.iter().any(|op| op.opcode == Opcode::Rewind));

        for sql in [
            "SELECT id FROM t WHERE k = 2 OR v = 3",
            "SELECT id FROM t WHERE k = 2 OR k > 5",
            "SELECT id FROM t WHERE k = 2.0 OR k = 3",
            "SELECT id FROM t WHERE k = 2 OR k = 3 AND id < 5",
            "SELECT id FROM t WHERE k = 2 OR k = 3 ORDER BY id",
            "SELECT id FROM t NOT INDEXED WHERE k = 2 OR k = 3",
        ] {
            assert!(
                bd_2dgf5_program(sql)
                    .iter()
                    .any(|op| op.opcode == Opcode::Rewind),
                "`{sql}` must decline OR normalization and scan (Rewind present)"
            );
        }
    }

    /// bd-2dgf5: a covering aggregate seek must read the index entry and nothing
    /// else — no table cursor, no `SeekRowid`.
    ///
    /// This asserts on the *emitted program*, not on `EXPLAIN QUERY PLAN` text.
    /// EQP renders from the planner directive rather than from the program, and
    /// the two diverge in both directions (bd-jyyae), so EQP can report a plan the
    /// program never executes. Opcodes are the only ground truth here.
    #[test]
    fn bd_2dgf5_covering_aggregate_seek_omits_table_lookup() {
        // COUNT(*) needs no column at all; SUM(id) reads the rowid, which the index
        // entry carries via IdxRowid; SUM(k) reads the index key itself.
        for sql in [
            "SELECT COUNT(*) FROM t WHERE k = 2",
            "SELECT SUM(id) FROM t WHERE k = 2",
            "SELECT SUM(k) FROM t WHERE k = 2",
            "SELECT MIN(id), MAX(id) FROM t WHERE k = 2",
            "SELECT COUNT(*) FROM t WHERE k = 2 ORDER BY 1",
        ] {
            let ops = bd_2dgf5_program(sql);
            let fast_path = bd_2dgf5_seek_fast_path(&ops);

            assert!(
                fast_path.iter().any(|op| op.opcode == Opcode::SeekGE),
                "`{sql}` must seek the index rather than scan"
            );
            assert!(
                !fast_path.iter().any(|op| op.opcode == Opcode::SeekRowid),
                "`{sql}` is covering: it must not look the row up in the table"
            );
            assert!(
                !fast_path.iter().any(|op| op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Table(name) if name == "t")),
                "`{sql}` is covering: it must not open the table cursor at all"
            );
            assert!(
                fast_path.iter().any(|op| op.opcode == Opcode::AggStep),
                "`{sql}` must still accumulate over the seeked run"
            );
        }
    }

    /// bd-2dgf5: an aggregate that needs a column the index does not carry must
    /// keep the table lookup. `v` is not in `idx_t_k`, so `SUM(v)` still seeks the
    /// index and then fetches the row.
    ///
    /// This is the negative half of the covering contract: without it, a bug that
    /// declared everything covering would silently read `v` from the wrong cursor
    /// and every assertion in the positive test would still pass.
    #[test]
    fn bd_2dgf5_non_covering_aggregate_seek_keeps_table_lookup() {
        for sql in [
            "SELECT SUM(v) FROM t WHERE k = 2",
            "SELECT group_concat(v) FROM t WHERE k = 2",
            "SELECT COUNT(*) FILTER (WHERE id > 100) FROM t WHERE k = 2",
        ] {
            let ops = bd_2dgf5_program(sql);
            let fast_path = bd_2dgf5_seek_fast_path(&ops);

            assert!(
                fast_path.iter().any(|op| op.opcode == Opcode::SeekGE),
                "`{sql}` should still seek the index"
            );
            assert!(
                fast_path.iter().any(|op| op.opcode == Opcode::SeekRowid),
                "`{sql}` needs a column the index does not carry, so it must \
                 look the row up in the table"
            );
        }
    }

    /// bd-2dgf5: the seek body and the scan-fallback body must emit the *same*
    /// `AggStep` sequence — same DISTINCT flag, same function P4, same argument
    /// count. Only the instruction that loads the argument may differ
    /// (`IdxRowid`/`Column idx` vs `Rowid`/`Column table`).
    ///
    /// Every seek program carries both bodies: the seek runs first, and the scan
    /// fallback follows for the probe-matched-nothing case. They are emitted by two
    /// different functions, so nothing but this test stops them from drifting — and
    /// if they drift, the same query returns different answers depending on whether
    /// the probe hit, which no value test on a populated table would catch.
    #[test]
    fn bd_2dgf5_seek_and_fallback_bodies_emit_identical_agg_steps() {
        for sql in [
            "SELECT COUNT(*) FROM t WHERE k = 2",
            "SELECT SUM(id) FROM t WHERE k = 2",
            "SELECT SUM(k) FROM t WHERE k = 2",
            "SELECT COUNT(DISTINCT k) FROM t WHERE k = 2",
            "SELECT MIN(id), MAX(id) FROM t WHERE k = 2",
            "SELECT SUM(v) FROM t WHERE k = 2",
        ] {
            let ops = bd_2dgf5_program(sql);
            let split = bd_2dgf5_fallback_start(&ops);
            assert!(
                split < ops.len(),
                "`{sql}` should take the seek path and emit a scan fallback"
            );

            let agg_steps = |slice: &[VdbeOp]| -> Vec<(i32, P4, u16)> {
                slice
                    .iter()
                    .filter(|op| op.opcode == Opcode::AggStep)
                    .map(|op| (op.p1, op.p4.clone(), op.p5))
                    .collect()
            };
            let seek_body = agg_steps(&ops[..split]);
            let fallback_body = agg_steps(&ops[split..]);

            assert!(
                !seek_body.is_empty(),
                "`{sql}` seek body must accumulate at least one aggregate"
            );
            assert_eq!(
                seek_body, fallback_body,
                "AggStep drifted between the seek body and the scan-fallback body \
                 for `{sql}`"
            );
        }
    }

    fn opcode_sequence(prog: &crate::VdbeProgram) -> Vec<Opcode> {
        prog.ops().iter().map(|op| op.opcode).collect()
    }

    fn has_opcodes(prog: &crate::VdbeProgram, expected: &[Opcode]) -> bool {
        let ops = opcode_sequence(prog);
        // Check that expected opcodes appear in order (not necessarily adjacent).
        let mut ops_iter = ops.iter();
        for expected_op in expected {
            if !ops_iter.any(|op| op == expected_op) {
                return false;
            }
        }
        true
    }

    fn schema_with_ipk_alias() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', true),
                ColumnInfo::basic("b", 'C', false),
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn schema_with_ipk_and_strict_real_notnull() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo {
                    name: "id".to_owned(),
                    affinity: 'D',
                    is_ipk: true,
                    type_name: Some("INTEGER".to_owned()),
                    notnull: true,
                    unique: true,
                    default_value: None,
                    strict_type: Some(StrictColumnType::Integer),
                    generated_expr: None,
                    generated_stored: None,
                    collation: None,
                    conflict_action: None,
                },
                ColumnInfo {
                    name: "score".to_owned(),
                    affinity: 'E',
                    is_ipk: false,
                    type_name: Some("REAL".to_owned()),
                    notnull: true,
                    unique: false,
                    default_value: None,
                    strict_type: Some(StrictColumnType::Real),
                    generated_expr: None,
                    generated_stored: None,
                    collation: None,
                    conflict_action: None,
                },
            ],
            indexes: vec![],
            strict: true,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn schema_with_ipk_and_strict_text() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo {
                    name: "id".to_owned(),
                    affinity: 'D',
                    is_ipk: true,
                    type_name: Some("INTEGER".to_owned()),
                    notnull: true,
                    unique: true,
                    default_value: None,
                    strict_type: Some(StrictColumnType::Integer),
                    generated_expr: None,
                    generated_stored: None,
                    collation: None,
                    conflict_action: None,
                },
                ColumnInfo {
                    name: "payload".to_owned(),
                    affinity: 'B',
                    is_ipk: false,
                    type_name: Some("TEXT".to_owned()),
                    notnull: false,
                    unique: false,
                    default_value: None,
                    strict_type: Some(StrictColumnType::Text),
                    generated_expr: None,
                    generated_stored: None,
                    collation: None,
                    conflict_action: None,
                },
            ],
            indexes: vec![],
            strict: true,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn schema_with_visible_rowid_column() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("rowid", 'C', false),
                ColumnInfo::basic("b", 'C', false),
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn schema_with_without_rowid_ipk() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', true),
                ColumnInfo::basic("b", 'C', false),
            ],
            indexes: vec![],
            strict: false,
            without_rowid: true,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn schema_with_visible_rowid_column_and_a_indexes() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', false),
                ColumnInfo::basic("rowid", 'C', false),
            ],
            indexes: vec![
                IndexSchema {
                    name: "idx_t_a".to_owned(),
                    root_page: 3,
                    columns: vec!["a".to_owned()],
                    key_expressions: vec!["a".to_owned()],
                    key_sort_directions: vec![],
                    where_clause: None,
                    is_unique: false,
                    key_collations: vec![],
                    conflict_action: None,
                },
                IndexSchema {
                    name: "idx_t_rowid".to_owned(),
                    root_page: 4,
                    columns: vec!["rowid".to_owned()],
                    key_expressions: vec!["rowid".to_owned()],
                    key_sort_directions: vec![],
                    where_clause: None,
                    is_unique: false,
                    key_collations: vec![],
                    conflict_action: None,
                },
            ],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    // === Test 1: SELECT by rowid ===
    #[test]
    fn test_codegen_select_by_rowid() {
        let stmt = simple_select(&["b"], "t", Some(rowid_eq_param()));
        let schema = test_schema();
        let ctx = CodegenContext {
            planner_select_directive: Some(SelectPlannerDirective {
                plan_id: "plan-messages-prefix-equality".to_owned(),
                plan_generation: 1,
                planner_surface: "single_table_access_path_v1".to_owned(),
                table_name: "messages".to_owned(),
                index_name: Some("sqlite_autoindex_messages_1".to_owned()),
                index_key_label: Some("conversation_id".to_owned()),
                index_key_is_expression: false,
                index_equality_target: None,
                index_range_target: None,
                covering: false,
                access_kind: PlannerSelectAccessKind::IndexEquality,
            }),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Init,
                Opcode::Transaction,
                Opcode::Variable,
                Opcode::OpenRead,
                Opcode::SeekRowid,
                Opcode::Column,
                Opcode::ResultRow,
                Opcode::Close,
                Opcode::Halt,
            ]
        ));
        // Transaction should be read-only (p2=0).
        let txn = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Transaction)
            .unwrap();
        assert_eq!(txn.p2, 0);
    }

    #[test]
    fn test_codegen_b3_rowid_and_ipk_equality_use_direct_seek() {
        let cases = [
            (
                "hidden rowid",
                simple_select(&["b"], "t", Some(rowid_eq_param())),
                test_schema(),
            ),
            (
                "INTEGER PRIMARY KEY alias",
                simple_select(&["b"], "t", Some(col_cmp_param("a", AstBinaryOp::Eq, 1))),
                schema_with_ipk_alias(),
            ),
        ];

        for (name, stmt, schema) in cases {
            let mut b = ProgramBuilder::new();
            if let Err(err) = codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()) {
                assert!(test_failure(), "{name} SELECT should codegen: {err:?}");
                continue;
            }
            let prog = match b.finish() {
                Ok(prog) => prog,
                Err(err) => {
                    assert!(test_failure(), "{name} program should finish: {err:?}");
                    continue;
                }
            };
            let ops = prog.ops();

            let Some(seek_pos) = ops.iter().position(|op| op.opcode == Opcode::SeekRowid) else {
                assert!(test_failure(), "{name} lookup must emit SeekRowid");
                continue;
            };
            let Some(column_pos) = ops.iter().position(|op| op.opcode == Opcode::Column) else {
                assert!(test_failure(), "{name} lookup must read the matched row");
                continue;
            };

            assert!(
                seek_pos < column_pos,
                "{name} lookup must seek before reading output columns"
            );
            assert!(
                !ops.iter()
                    .any(|op| matches!(op.opcode, Opcode::Rewind | Opcode::Next)),
                "{name} equality lookup must not carry a full-scan loop"
            );
        }
    }

    #[test]
    fn test_codegen_b3_index_equality_uses_index_probe_before_any_scan_fallback() {
        let stmt = simple_select(&["a"], "t", Some(col_cmp_param("b", AstBinaryOp::Eq, 1)));
        let schema = test_schema_with_index();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        let seek_ge_pos = ops
            .iter()
            .position(|op| op.opcode == Opcode::SeekGE && op.p1 == 1)
            .expect("indexed equality should seek into the index cursor");
        let first_table_rewind = ops
            .iter()
            .position(|op| op.opcode == Opcode::Rewind && op.p1 == 0)
            .unwrap_or(ops.len());

        assert!(
            ops.iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")
            }),
            "indexed equality should open the matching index"
        );
        assert!(
            seek_ge_pos < first_table_rewind,
            "indexed equality must probe the index before any scan fallback"
        );
        assert!(
            ops[..first_table_rewind]
                .iter()
                .any(|op| op.opcode == Opcode::IdxRowid && op.p1 == 1),
            "non-covering indexed equality should recover table rowids from the index"
        );
        assert!(
            ops[..first_table_rewind]
                .iter()
                .any(|op| op.opcode == Opcode::SeekRowid && op.p1 == 0),
            "non-covering indexed equality should seek the table by rowid, not scan it"
        );
    }

    #[test]
    fn test_codegen_b3_covering_index_fast_path_projects_without_table_lookup() {
        let stmt = simple_select(&["b"], "t", Some(col_cmp_param("b", AstBinaryOp::Eq, 1)));
        let schema = test_schema_with_index();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        let seek_ge_pos = ops
            .iter()
            .position(|op| op.opcode == Opcode::SeekGE && op.p1 == 1)
            .expect("covering equality should seek into the index cursor");
        let fast_path_end = ops
            .iter()
            .position(|op| {
                op.opcode == Opcode::OpenRead && matches!(&op.p4, P4::Table(name) if name == "t")
            })
            .unwrap_or(ops.len());

        assert!(
            seek_ge_pos < fast_path_end,
            "covering equality must run the index probe before any scan fallback"
        );
        assert!(
            !ops[..fast_path_end]
                .iter()
                .any(|op| op.opcode == Opcode::SeekRowid),
            "covering equality fast path should not perform table rowid lookups"
        );
        assert!(
            ops[..fast_path_end]
                .iter()
                .any(|op| op.opcode == Opcode::Column && op.p1 == 1),
            "covering equality should project output from the index cursor"
        );
    }

    #[test]
    fn test_codegen_select_ipk_range_uses_bounded_seek_scan() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(and_expr(
                Box::new(Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                    op: AstBinaryOp::Ge,
                    right: Box::new(Expr::Literal(Literal::Integer(1), Span::ZERO)),
                    span: Span::ZERO,
                }),
                Box::new(Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                    op: AstBinaryOp::Lt,
                    right: Box::new(Expr::Literal(Literal::Integer(2), Span::ZERO)),
                    span: Span::ZERO,
                }),
            )),
        );
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "range scan should position with SeekGE instead of a full-table Rewind"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Ge),
            "exclusive upper bound should stop once current rowid reaches the high key"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "bounded rowid/IPK range should not fall back to a full-table rewind"
        );

        let next = ops
            .iter()
            .find(|op| op.opcode == Opcode::Next)
            .expect("bounded range scan should advance with Next");
        assert_eq!(next.p1, 0, "Next should advance the table cursor");
    }

    #[test]
    fn test_codegen_select_ipk_between_uses_seek_and_upper_guard() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(Box::new(Expr::Between {
                expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                low: Box::new(Expr::Literal(Literal::Integer(10), Span::ZERO)),
                high: Box::new(Expr::Literal(Literal::Integer(20), Span::ZERO)),
                not: false,
                span: Span::ZERO,
            })),
        );
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "BETWEEN should reuse the rowid/IPK range seek path"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Gt),
            "inclusive upper bound should stop only after the current rowid exceeds the high key"
        );
    }

    #[test]
    fn test_codegen_select_ipk_range_with_anonymous_params_stays_on_full_scan() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(and_expr(
                Box::new(Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                    op: AstBinaryOp::Ge,
                    right: Box::new(anonymous_placeholder()),
                    span: Span::ZERO,
                }),
                Box::new(Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                    op: AstBinaryOp::Lt,
                    right: Box::new(anonymous_placeholder()),
                    span: Span::ZERO,
                }),
            )),
        );
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "anonymous placeholder ranges must stay on the original full-scan path"
        );
        assert!(
            !ops.iter()
                .any(|op| matches!(op.opcode, Opcode::SeekGE | Opcode::SeekGT)),
            "fast-path range seek must not reorder anonymous placeholders"
        );
    }

    #[test]
    fn test_codegen_select_ipk_range_with_numbered_params_uses_bounded_seek_scan() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(and_expr(
                col_cmp_param("a", AstBinaryOp::Ge, 1),
                col_cmp_param("a", AstBinaryOp::Lt, 2),
            )),
        );
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "numbered rowid/IPK ranges should reuse the bounded seek fast path"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "numbered rowid/IPK ranges should no longer fall back to a full-table rewind"
        );
    }

    #[test]
    fn test_codegen_select_ipk_range_with_order_by_ipk_avoids_sorter() {
        let mut stmt = simple_select(
            &["a", "b"],
            "t",
            Some(col_cmp_param("a", AstBinaryOp::Gt, 1)),
        );
        stmt.order_by = vec![OrderingTerm {
            expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
            direction: Some(SortDirection::Asc),
            nulls: None,
        }];
        stmt.limit = Some(LimitClause {
            limit: placeholder(2),
            offset: None,
        });
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            has_opcodes(
                &prog,
                &[
                    Opcode::Variable,
                    Opcode::SeekGT,
                    Opcode::Rowid,
                    Opcode::Column,
                    Opcode::ResultRow,
                    Opcode::DecrJumpZero,
                    Opcode::Next,
                ]
            ),
            "ORDER BY on an IPK range should stay on the bounded rowid scan path"
        );
        assert!(
            !ops.iter().any(|op| {
                matches!(
                    op.opcode,
                    Opcode::SorterOpen
                        | Opcode::SorterInsert
                        | Opcode::SorterSort
                        | Opcode::SorterData
                )
            }),
            "ORDER BY on an IPK range must not allocate a sorter temp B-tree"
        );
    }

    #[test]
    fn test_codegen_select_ipk_range_with_desc_order_by_ipk_uses_reverse_scan() {
        let mut stmt = simple_select(
            &["a", "b"],
            "t",
            Some(col_cmp_param("a", AstBinaryOp::Lt, 1)),
        );
        stmt.order_by = vec![OrderingTerm {
            expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
            direction: Some(SortDirection::Desc),
            nulls: None,
        }];
        stmt.limit = Some(LimitClause {
            limit: placeholder(2),
            offset: None,
        });
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            has_opcodes(
                &prog,
                &[
                    Opcode::Variable,
                    Opcode::SeekLT,
                    Opcode::Rowid,
                    Opcode::Column,
                    Opcode::ResultRow,
                    Opcode::DecrJumpZero,
                    Opcode::Prev,
                ]
            ),
            "descending ORDER BY on an IPK range should use the reverse rowid scan path"
        );
        assert!(
            !ops.iter().any(|op| {
                matches!(
                    op.opcode,
                    Opcode::SorterOpen
                        | Opcode::SorterInsert
                        | Opcode::SorterSort
                        | Opcode::SorterData
                )
            }),
            "descending ORDER BY on an IPK range must not allocate a sorter temp B-tree"
        );
    }

    #[test]
    fn test_codegen_select_ipk_range_with_wrong_qualifier_errors() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(and_expr(
                qualified_col_cmp_param("u", "a", AstBinaryOp::Ge, 1),
                qualified_col_cmp_param("u", "a", AstBinaryOp::Lt, 2),
            )),
        );
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect_err("mismatched qualifier should be a semantic error");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "u" && column == "u.a"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_select_ipk_range_with_non_numeric_text_literal_falls_back() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(Box::new(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                op: AstBinaryOp::Gt,
                right: Box::new(Expr::Literal(Literal::String("abc".to_owned()), Span::ZERO)),
                span: Span::ZERO,
            })),
        );
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "non-numeric text rowid/IPK bounds must stay on the generic scan path"
        );
        assert!(
            !ops.iter()
                .any(|op| matches!(op.opcode, Opcode::SeekGE | Opcode::SeekGT)),
            "non-numeric text rowid/IPK bounds must not use the bounded seek fast path"
        );
    }

    #[test]
    fn test_codegen_select_ipk_range_with_quoted_numeric_bounds_falls_back() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(and_expr(
                Box::new(Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                    op: AstBinaryOp::Ge,
                    right: Box::new(Expr::Literal(Literal::String("10".to_owned()), Span::ZERO)),
                    span: Span::ZERO,
                }),
                Box::new(Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                    op: AstBinaryOp::Lt,
                    right: Box::new(Expr::Literal(Literal::String("20".to_owned()), Span::ZERO)),
                    span: Span::ZERO,
                }),
            )),
        );
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "quoted numeric rowid/IPK bounds must fall back until affinity-aware seeks exist"
        );
        assert!(
            !ops.iter()
                .any(|op| matches!(op.opcode, Opcode::SeekGE | Opcode::SeekGT)),
            "quoted numeric rowid/IPK bounds must not use the bounded seek fast path"
        );
    }

    #[test]
    fn test_codegen_select_ipk_column_uses_rowid_opcode() {
        let stmt = simple_select(&["a"], "t", None);
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        assert!(
            ops.contains(&Opcode::Rowid),
            "IPK column projection should read rowid"
        );
        assert!(
            !ops.contains(&Opcode::Column),
            "single IPK projection should not read record columns"
        );
    }

    #[test]
    fn test_codegen_select_shadowed_rowid_column_uses_column_opcode() {
        let stmt = simple_select(&["rowid"], "t", None);
        let schema = schema_with_visible_rowid_column();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        assert!(
            ops.contains(&Opcode::Column),
            "shadowed rowid column should read from the record payload"
        );
        assert!(
            !ops.contains(&Opcode::Rowid),
            "shadowed rowid column must not be compiled as hidden rowid access"
        );
    }

    #[test]
    fn test_codegen_select_hidden_rowid_alias_when_rowid_is_shadowed() {
        let stmt = simple_select(&["_rowid_"], "t", None);
        let schema = schema_with_visible_rowid_column();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        assert!(
            ops.contains(&Opcode::Rowid),
            "unshadowed hidden alias should still use OP_Rowid"
        );
        assert!(
            !ops.contains(&Opcode::Column),
            "hidden rowid alias should not read the visible shadowing column"
        );
    }

    #[test]
    fn test_codegen_select_hidden_rowid_alias_on_without_rowid_table_errors() {
        let stmt = simple_select(&["_rowid_"], "t", None);
        let schema = schema_with_without_rowid_ipk();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &stmt, &schema, &ctx).unwrap_err();

        assert_eq!(
            err,
            CodegenError::ColumnNotFound {
                table: "t".to_owned(),
                column: "_rowid_".to_owned(),
            }
        );
    }

    #[test]
    fn test_codegen_select_star_uses_rowid_for_ipk_column() {
        let stmt = star_select("t");
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Rewind,
                Opcode::Rowid,
                Opcode::Column,
                Opcode::ResultRow
            ]
        ));
    }

    // === Test 2: INSERT VALUES ===
    #[test]
    fn test_codegen_insert_values() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Init,
                Opcode::Transaction,
                Opcode::OpenWrite,
                Opcode::Variable,
                Opcode::Variable,
                Opcode::NewRowid,
                Opcode::MakeRecord,
                Opcode::Insert,
                Opcode::Close,
                Opcode::Halt,
            ]
        ));
        // Transaction should be write (p2=1).
        let txn = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Transaction)
            .unwrap();
        assert_eq!(txn.p2, 1);
    }

    #[test]
    fn test_codegen_insert_values_large_integer_literal_uses_int64_opcode() {
        let big = 4_102_444_800_000_000_i64;
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![
                Expr::Literal(Literal::Integer(big), Span::ZERO),
                Expr::Literal(Literal::String("payload".to_owned()), Span::ZERO),
            ]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Int64
                && matches!(op.p4, P4::Int64(value) if value == big)),
            "expected OP_Int64 carrying the full i64 literal in INSERT VALUES codegen"
        );
    }

    #[test]
    fn test_codegen_insert_literal_values_preformats_record_blob() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![
                Expr::Literal(Literal::Integer(99), Span::ZERO),
                Expr::Literal(Literal::String("test".to_owned()), Span::ZERO),
            ]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);
        let insert = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Insert)
            .expect("literal INSERT should emit Insert");

        assert!(
            !ops.contains(&Opcode::Blob),
            "literal-only INSERT VALUES should not need a standalone Blob opcode"
        );
        assert!(
            !ops.contains(&Opcode::MakeRecord),
            "literal-only INSERT VALUES should preformat the table record"
        );
        assert!(
            matches!(&insert.p4, P4::Blob(record) if !record.is_empty()),
            "Insert should carry the preformatted table record directly in P4"
        );
    }

    #[test]
    fn test_preformatted_insert_record_stores_null_for_ipk_payload() {
        let schema = schema_with_ipk_alias();
        let table = &schema[0];
        let row_values = vec![
            Expr::Literal(Literal::Integer(42), Span::ZERO),
            Expr::Literal(Literal::String("payload".to_owned()), Span::ZERO),
        ];

        let record = try_build_preformatted_insert_record(&row_values, table, None)
            .expect("literal IPK row should preformat");
        let parsed = fsqlite_types::record::parse_record(&record)
            .expect("preformatted record should decode");

        assert_eq!(
            parsed,
            vec![
                SqliteValue::Null,
                SqliteValue::Text(SmallText::new("payload")),
            ],
            "INTEGER PRIMARY KEY aliases must remain rowid keys, not payload values"
        );
    }

    #[test]
    fn test_preformatted_insert_record_honors_lowercase_affinity_chars() {
        let schema = vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![ColumnInfo::basic("a", 'd', false)],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }];
        let row_values = vec![Expr::Literal(Literal::String("42".to_owned()), Span::ZERO)];

        let record = try_build_preformatted_insert_record(&row_values, &schema[0], None)
            .expect("literal row should preformat");
        let parsed = fsqlite_types::record::parse_record(&record)
            .expect("preformatted record should decode");

        assert_eq!(
            parsed,
            vec![SqliteValue::Integer(42)],
            "lowercase INTEGER affinity must not silently fall back to BLOB affinity"
        );
    }

    #[test]
    fn test_preformatted_insert_record_omitted_default_column_falls_back() {
        let schema = vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'D', false),
                ColumnInfo {
                    name: "b".to_owned(),
                    affinity: 'D',
                    is_ipk: false,
                    type_name: None,
                    notnull: false,
                    unique: false,
                    default_value: Some("7".to_owned()),
                    strict_type: None,
                    generated_expr: None,
                    generated_stored: None,
                    collation: None,
                    conflict_action: None,
                },
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }];
        let row_values = vec![Expr::Literal(Literal::Integer(1), Span::ZERO)];
        let mapping = [Some(0), None];

        assert!(
            try_build_preformatted_insert_record(&row_values, &schema[0], Some(&mapping)).is_none(),
            "omitted non-IPK columns must stay on the runtime DEFAULT path"
        );
    }

    #[test]
    fn test_preformatted_insert_record_distinguishes_explicit_null_from_omitted_column() {
        let schema = vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'D', false),
                ColumnInfo {
                    name: "b".to_owned(),
                    affinity: 'D',
                    is_ipk: false,
                    type_name: None,
                    notnull: false,
                    unique: false,
                    default_value: Some("7".to_owned()),
                    strict_type: None,
                    generated_expr: None,
                    generated_stored: None,
                    collation: None,
                    conflict_action: None,
                },
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }];
        let explicit_null_values = vec![
            Expr::Literal(Literal::Integer(1), Span::ZERO),
            Expr::Literal(Literal::Null, Span::ZERO),
        ];
        let omitted_values = vec![Expr::Literal(Literal::Integer(1), Span::ZERO)];
        let omitted_mapping = [Some(0), None];

        let record = try_build_preformatted_insert_record(&explicit_null_values, &schema[0], None)
            .expect("explicit NULL is a fully determined stored value");
        let parsed = fsqlite_types::record::parse_record(&record)
            .expect("preformatted record should decode");
        assert_eq!(parsed, vec![SqliteValue::Integer(1), SqliteValue::Null]);
        assert!(
            try_build_preformatted_insert_record(
                &omitted_values,
                &schema[0],
                Some(&omitted_mapping),
            )
            .is_none(),
            "omitted columns must not be treated as explicit NULL literals"
        );
    }

    #[test]
    fn test_codegen_insert_mixed_preformatable_rows_keeps_runtime_fallback() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![
                vec![
                    Expr::Literal(Literal::Integer(1), Span::ZERO),
                    Expr::Literal(Literal::String("literal".to_owned()), Span::ZERO),
                ],
                vec![
                    Expr::BinaryOp {
                        left: Box::new(Expr::Literal(Literal::Integer(1), Span::ZERO)),
                        op: AstBinaryOp::Add,
                        right: Box::new(Expr::Literal(Literal::Integer(1), Span::ZERO)),
                        span: Span::ZERO,
                    },
                    Expr::Literal(Literal::String("runtime".to_owned()), Span::ZERO),
                ],
            ]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let preformatted_inserts = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Insert && matches!(op.p4, P4::Blob(_)))
            .count();
        let runtime_records = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::MakeRecord)
            .count();

        assert_eq!(
            preformatted_inserts, 1,
            "only the literal row should carry a baked record"
        );
        assert_eq!(
            runtime_records, 1,
            "the non-literal row must still use runtime MakeRecord"
        );
    }

    #[test]
    fn test_emit_limit_expr_large_integer_literal_uses_int64_opcode() {
        let big = 4_102_444_800_000_000_i64;
        let mut b = ProgramBuilder::new();
        let reg = b.alloc_reg();
        let expr = Expr::Literal(Literal::Integer(big), Span::ZERO);

        emit_limit_expr(&mut b, &expr, reg);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

        let prog = b.finish().unwrap();
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Int64
                && op.p2 == reg
                && matches!(op.p4, P4::Int64(value) if value == big)),
            "expected OP_Int64 for large LIMIT literals"
        );
    }

    #[test]
    fn test_codegen_insert_values_rejects_mixed_arity_rows() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![
                vec![placeholder(1), placeholder(2)],
                vec![placeholder(3)],
            ]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap_err();
        // a0e51891e switched ragged VALUES to the verbatim stock message under
        // SQLITE_ERROR (CodegenError::SqlError, no "unsupported:" prefix).
        assert!(
            matches!(err, CodegenError::SqlError(ref msg) if msg.contains("same number of terms")),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_emit_comparison_invalid_operator_emits_false() {
        let mut b = ProgramBuilder::new();
        let reg = b.alloc_reg();
        let one = Expr::Literal(Literal::Integer(1), Span::ZERO);
        let two = Expr::Literal(Literal::Integer(2), Span::ZERO);

        emit_comparison(&mut b, &one, AstBinaryOp::Add, &two, reg, None);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

        let prog = b.finish().unwrap();
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::Integer && op.p1 == 0 && op.p2 == reg),
            "expected fallback false assignment for invalid comparison op"
        );
    }

    #[test]
    fn test_emit_is_comparison_invalid_operator_emits_false() {
        let mut b = ProgramBuilder::new();
        let reg = b.alloc_reg();
        let one = Expr::Literal(Literal::Integer(1), Span::ZERO);
        let two = Expr::Literal(Literal::Integer(2), Span::ZERO);

        emit_is_comparison(&mut b, &one, AstBinaryOp::Eq, &two, reg, None);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);

        let prog = b.finish().unwrap();
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::Integer && op.p1 == 0 && op.p2 == reg),
            "expected fallback false assignment for invalid IS/IS NOT op"
        );
    }

    // === Test: INSERT ... SELECT ===
    #[test]
    #[allow(clippy::too_many_lines)]
    fn test_codegen_insert_select() {
        // Schema with two tables: source "s" and target "t".
        let schema = vec![
            TableSchema {
                name: "t".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo {
                        name: "a".to_owned(),
                        affinity: 'd',
                        is_ipk: false,
                        type_name: None,
                        notnull: false,
                        unique: false,
                        default_value: None,
                        strict_type: None,
                        generated_expr: None,
                        generated_stored: None,
                        collation: None,
                        conflict_action: None,
                    },
                    ColumnInfo {
                        name: "b".to_owned(),
                        affinity: 'C',
                        is_ipk: false,
                        type_name: None,
                        notnull: false,
                        unique: false,
                        default_value: None,
                        strict_type: None,
                        generated_expr: None,
                        generated_stored: None,
                        collation: None,
                        conflict_action: None,
                    },
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "s".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo {
                        name: "x".to_owned(),
                        affinity: 'd',
                        is_ipk: false,
                        type_name: None,
                        notnull: false,
                        unique: false,
                        default_value: None,
                        strict_type: None,
                        generated_expr: None,
                        generated_stored: None,
                        collation: None,
                        conflict_action: None,
                    },
                    ColumnInfo {
                        name: "y".to_owned(),
                        affinity: 'C',
                        is_ipk: false,
                        type_name: None,
                        notnull: false,
                        unique: false,
                        default_value: None,
                        strict_type: None,
                        generated_expr: None,
                        generated_stored: None,
                        collation: None,
                        conflict_action: None,
                    },
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ];

        // INSERT INTO t SELECT * FROM s
        let inner_select = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("s"),
                            alias: None,
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Select(Box::new(inner_select)),
            upsert: vec![],
            returning: vec![],
        };

        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Should contain: Init, Transaction(write), OpenWrite(target),
        // OpenRead(source), Rewind, Column reads, NewRowid, MakeRecord,
        // Insert, Next, Close(source), Close(target), Halt.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Init,
                Opcode::Transaction,
                Opcode::OpenWrite,
                Opcode::OpenRead,
                Opcode::Rewind,
                Opcode::Column,
                Opcode::Column,
                Opcode::NewRowid,
                Opcode::MakeRecord,
                Opcode::Insert,
                Opcode::Next,
                Opcode::Close,
                Opcode::Close,
                Opcode::Halt,
            ]
        ));

        // Transaction should be write (p2=1).
        let txn = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Transaction)
            .unwrap();
        assert_eq!(txn.p2, 1);

        // OpenWrite should target table "t" (root_page=2).
        let open_write = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::OpenWrite)
            .unwrap();
        assert_eq!(open_write.p2, 2);

        // OpenRead should target table "s" (root_page=3).
        let open_read = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::OpenRead)
            .unwrap();
        assert_eq!(open_read.p2, 3);
    }

    #[test]
    fn test_codegen_insert_select_without_from_emits_single_insert_path() {
        let schema = vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', false),
                ColumnInfo::basic("b", 'C', false),
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }];

        let inner_select = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Literal(Literal::Integer(7), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Literal(Literal::String("seven".to_owned()), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: None,
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Select(Box::new(inner_select)),
            upsert: vec![],
            returning: vec![],
        };

        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        assert!(ops.contains(&Opcode::Insert));
        assert!(ops.contains(&Opcode::Integer));
        assert!(ops.contains(&Opcode::String8));
        assert!(!ops.contains(&Opcode::OpenRead));
        assert!(!ops.contains(&Opcode::Rewind));
        assert!(!ops.contains(&Opcode::Next));
    }

    #[test]
    fn test_codegen_insert_select_without_from_where_emits_filter_jump() {
        let schema = vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![ColumnInfo::basic("a", 'd', false)],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }];

        let inner_select = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Literal(Literal::Integer(1), Span::ZERO),
                        alias: None,
                    }],
                    from: None,
                    where_clause: Some(Box::new(Expr::Literal(Literal::False, Span::ZERO))),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Select(Box::new(inner_select)),
            upsert: vec![],
            returning: vec![],
        };

        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
        let prog = b.finish().unwrap();
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::IfNot),
            "expected WHERE filter in no-FROM INSERT ... SELECT path"
        );
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn test_codegen_insert_select_propagates_or_conflict_to_insert_p5() {
        let schema = vec![
            TableSchema {
                name: "t".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("a", 'd', false),
                    ColumnInfo::basic("b", 'C', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "s".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("x", 'd', false),
                    ColumnInfo::basic("y", 'C', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ];

        let inner_select = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("s"),
                            alias: None,
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let stmt = InsertStatement {
            with: None,
            or_conflict: Some(fsqlite_ast::ConflictAction::Ignore),
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Select(Box::new(inner_select)),
            upsert: vec![],
            returning: vec![],
        };

        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let insert = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Insert)
            .expect("expected Insert opcode");
        assert_eq!(insert.p5, OE_IGNORE);
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn test_codegen_insert_select_emits_index_inserts() {
        // Target has one secondary index; source has none.
        let schema = vec![
            TableSchema {
                name: "t".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("a", 'd', false),
                    ColumnInfo::basic("b", 'C', false),
                ],
                indexes: vec![IndexSchema {
                    name: "idx_t_a".to_owned(),
                    root_page: 4,
                    columns: vec!["a".to_owned()],
                    key_expressions: vec!["a".to_owned()],
                    key_sort_directions: vec![],
                    where_clause: None,
                    is_unique: false,
                    key_collations: vec![],
                    conflict_action: None,
                }],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "s".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("x", 'd', false),
                    ColumnInfo::basic("y", 'C', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ];

        let inner_select = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("s"),
                            alias: None,
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Select(Box::new(inner_select)),
            upsert: vec![],
            returning: vec![],
        };

        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenWrite && op.p2 == 4),
            "expected OpenWrite for target secondary index root page"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::IdxInsert),
            "INSERT ... SELECT should maintain target indexes via IdxInsert"
        );
    }

    // === Test: INSERT ... SELECT with specific columns ===
    #[test]
    #[allow(clippy::too_many_lines)]
    fn test_codegen_insert_select_with_explicit_columns_reorders_projection() {
        // Schema with source "s" having 3 columns, target "t" with 2.
        let schema = vec![
            TableSchema {
                name: "t".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo {
                        name: "a".to_owned(),
                        affinity: 'd',
                        is_ipk: false,
                        type_name: None,
                        notnull: false,
                        unique: false,
                        default_value: None,
                        strict_type: None,
                        generated_expr: None,
                        generated_stored: None,
                        collation: None,
                        conflict_action: None,
                    },
                    ColumnInfo {
                        name: "b".to_owned(),
                        affinity: 'C',
                        is_ipk: false,
                        type_name: None,
                        notnull: false,
                        unique: false,
                        default_value: None,
                        strict_type: None,
                        generated_expr: None,
                        generated_stored: None,
                        collation: None,
                        conflict_action: None,
                    },
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "s".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo {
                        name: "x".to_owned(),
                        affinity: 'd',
                        is_ipk: false,
                        type_name: None,
                        notnull: false,
                        unique: false,
                        default_value: None,
                        strict_type: None,
                        generated_expr: None,
                        generated_stored: None,
                        collation: None,
                        conflict_action: None,
                    },
                    ColumnInfo {
                        name: "y".to_owned(),
                        affinity: 'C',
                        is_ipk: false,
                        type_name: None,
                        notnull: false,
                        unique: false,
                        default_value: None,
                        strict_type: None,
                        generated_expr: None,
                        generated_stored: None,
                        collation: None,
                        conflict_action: None,
                    },
                    ColumnInfo::basic("z", 'e', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ];

        // INSERT INTO t(b, a) SELECT x, y FROM s
        let inner_select = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("x"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("y"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("s"),
                            alias: None,
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec!["b".to_owned(), "a".to_owned()],
            source: InsertSource::Select(Box::new(inner_select)),
            upsert: vec![],
            returning: vec![],
        };

        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Should have exactly 2 Column reads (x and y), not 3.
        let column_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Column)
            .count();
        assert_eq!(column_count, 2);
        let copy_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Copy)
            .count();
        assert!(
            copy_count >= 2,
            "explicit target-column mapping should reorder both projected values"
        );
    }

    #[test]
    fn test_codegen_empty_values_select_emits_no_rows() -> Result<(), String> {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Values(vec![].into()),
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).map_err(|err| format!("{err:?}"))?;
        let prog = b.finish().map_err(|err| format!("{err:?}"))?;

        let ops = opcode_sequence(&prog);
        if ops.contains(&Opcode::ResultRow) {
            return Err("empty VALUES should not emit result rows".to_owned());
        }
        if !has_opcodes(&prog, &[Opcode::Init, Opcode::Transaction, Opcode::Halt]) {
            return Err(format!(
                "empty VALUES should emit a valid no-row program, got {ops:?}"
            ));
        }

        Ok(())
    }

    // === Test: SELECT DISTINCT full scan ===
    #[test]
    fn test_codegen_select_distinct_full_scan() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::Distinct,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Unordered DISTINCT preserves source order and probes a membership
        // index before emitting each first-occurrence tuple.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Init,
                Opcode::Transaction,
                Opcode::OpenAutoindex,
                Opcode::OpenRead,
                Opcode::Rewind,
                Opcode::Column,
                Opcode::Column,
                Opcode::MakeRecord,
                Opcode::Found,
                Opcode::IdxInsert,
                Opcode::ResultRow,
                Opcode::Next,
                Opcode::Close,
                Opcode::Close,
            ]
        ));
    }

    #[test]
    fn test_codegen_select_distinct_star_preserves_flattened_collations() {
        let mut schema = test_schema();
        schema[0].columns[1].collation = Some("NOCASE".to_owned());

        for sql in ["SELECT DISTINCT * FROM t", "SELECT DISTINCT t.* FROM t"] {
            let stmt = select_sql(sql);
            let mut b = ProgramBuilder::new();
            codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
            let prog = b.finish().unwrap();

            let distinct_open = prog
                .ops()
                .iter()
                .find(|op| op.opcode == Opcode::OpenAutoindex)
                .expect("unordered DISTINCT should open a membership index");
            assert_eq!(distinct_open.p2, 2, "{sql}");
            assert_eq!(
                distinct_open.p4,
                P4::Str("BINARY,NOCASE".to_owned()),
                "{sql}: expanded output slots must retain positional column collations"
            );
        }
    }

    #[test]
    fn test_codegen_select_distinct_full_scan_offset_after_dedup() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::Distinct,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: Some(LimitClause {
                limit: Expr::Literal(Literal::Integer(5), Span::ZERO),
                offset: Some(Expr::Literal(Literal::Integer(1), Span::ZERO)),
            }),
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let found_pos = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::Found)
            .expect("missing DISTINCT membership probe");
        let ifpos_pos = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::IfPos)
            .expect("missing OFFSET IfPos opcode");
        assert!(
            found_pos < ifpos_pos,
            "DISTINCT dedup must run before OFFSET filtering"
        );
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::SorterOpen),
            "unordered DISTINCT must not sort before LIMIT/OFFSET"
        );
    }

    // === Test: SELECT DISTINCT with ORDER BY ===
    #[test]
    fn test_codegen_select_distinct_with_order_by() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::Distinct,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                direction: None,
                nulls: None,
            }],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // ORDER BY + DISTINCT uses a sorter for ordering and a separate
        // output-tuple membership index for deduplication.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Init,
                Opcode::SorterOpen,
                Opcode::OpenAutoindex,
                Opcode::OpenRead,
                Opcode::Rewind,
                Opcode::MakeRecord,
                Opcode::Found,
                Opcode::IdxInsert,
                Opcode::SorterInsert,
                Opcode::Next,
                Opcode::SorterSort,
                Opcode::SorterData,
                Opcode::ResultRow,
                Opcode::SorterNext,
            ]
        ));
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| op.opcode == Opcode::SorterCompare),
            "ordered DISTINCT must not compare an output tuple against the ORDER BY key prefix"
        );
    }

    #[test]
    fn test_codegen_select_distinct_with_order_by_offset_after_dedup() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::Distinct,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                direction: Some(SortDirection::Asc),
                nulls: None,
            }],
            limit: Some(LimitClause {
                limit: Expr::Literal(Literal::Integer(5), Span::ZERO),
                offset: Some(Expr::Literal(Literal::Integer(2), Span::ZERO)),
            }),
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let found_pos = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::Found)
            .expect("missing DISTINCT membership probe");
        let ifpos_pos = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::IfPos)
            .expect("missing OFFSET IfPos opcode");
        assert!(
            found_pos < ifpos_pos,
            "DISTINCT dedup must run before OFFSET filtering"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::IdxInsert),
            "a novel output tuple must be added to the DISTINCT membership index"
        );
        let distinct_insert_pos = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::IdxInsert)
            .expect("missing DISTINCT membership insert");
        let top_n_preflight_pos = prog
            .ops()
            .iter()
            .position(|op| {
                op.opcode == Opcode::SorterCompare && op.p5 == SORTER_COMPARE_TOP_N_PREFLIGHT
            })
            .expect("bounded ordered DISTINCT should preflight sorter admission");
        assert!(
            found_pos < distinct_insert_pos && distinct_insert_pos < top_n_preflight_pos,
            "DISTINCT membership must precede bounded-sorter admission so rejected first \
             representatives still suppress later duplicates"
        );
        assert!(
            !prog.ops().iter().any(|op| {
                op.opcode == Opcode::SorterCompare && op.p5 != SORTER_COMPARE_TOP_N_PREFLIGHT
            }),
            "ordered DISTINCT must not use the old output-record-versus-sort-key comparison"
        );
    }

    #[test]
    fn test_codegen_ordered_distinct_membership_preserves_output_collation_slots() {
        let mut schema = test_schema();
        schema[0].columns[1].collation = Some("NOCASE".to_owned());
        let stmt = select_sql("SELECT DISTINCT a, b FROM t ORDER BY b");
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
        let prog = b.finish().unwrap();

        let membership_open = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::OpenAutoindex)
            .expect("ordered DISTINCT should open an output membership index");
        assert_eq!(membership_open.p2, 2);
        assert_eq!(
            membership_open.p4,
            P4::Str("BINARY,NOCASE".to_owned()),
            "default-collation slots must remain explicit so later named collations keep their positions"
        );
        assert!(
            prog.ops().iter().any(|op| {
                op.opcode == Opcode::Found && op.p1 == membership_open.p1 && op.p3 > 0
            }),
            "the flattened output record must probe the membership index"
        );
        assert!(
            prog.ops().iter().any(|op| {
                op.opcode == Opcode::IdxInsert && op.p1 == membership_open.p1 && op.p2 > 0
            }),
            "novel flattened output records must enter the membership index"
        );
    }

    #[test]
    fn test_codegen_ordered_distinct_dedups_before_independent_order_expression() {
        let schema = test_schema();
        let stmt = select_sql("SELECT DISTINCT out(b) AS x FROM t ORDER BY key(a), x DESC");
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        let output_pos = ops
            .iter()
            .position(|op| {
                op.opcode == Opcode::PureFunc
                    && matches!(&op.p4, P4::FuncName(name) if name == "OUT")
            })
            .expect("DISTINCT output should evaluate out()");
        let found_pos = ops
            .iter()
            .position(|op| op.opcode == Opcode::Found)
            .expect("DISTINCT output should be membership-tested");
        let independent_order_pos = ops
            .iter()
            .position(|op| {
                op.opcode == Opcode::PureFunc
                    && matches!(&op.p4, P4::FuncName(name) if name == "KEY")
            })
            .expect("independent ORDER BY expression should evaluate key()");
        assert!(
            output_pos < found_pos && found_pos < independent_order_pos,
            "duplicate output rows must skip evaluation of independent ORDER BY expressions"
        );
        assert_eq!(
            ops.iter()
                .filter(|op| {
                    op.opcode == Opcode::PureFunc
                        && matches!(&op.p4, P4::FuncName(name) if name == "OUT")
                })
                .count(),
            1,
            "the exact ORDER alias should reuse the already-deduplicated output value"
        );
    }

    // === Test 3: UPDATE by rowid ===
    #[test]
    fn test_codegen_update_by_rowid() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Rowid equality should use the direct SeekRowid fast path instead of
        // scanning the whole table.
        let ops = prog.ops();
        let seek_pos = ops
            .iter()
            .position(|op| op.opcode == Opcode::SeekRowid)
            .expect("UPDATE by rowid must probe directly with SeekRowid");
        let delete_pos = ops
            .iter()
            .position(|op| op.opcode == Opcode::Delete)
            .expect("UPDATE must delete the old row before reinserting");
        let delete = ops
            .iter()
            .find(|op| op.opcode == Opcode::Delete)
            .expect("Delete opcode should exist");
        let insert_pos = ops
            .iter()
            .position(|op| op.opcode == Opcode::Insert)
            .expect("UPDATE must reinsert the rewritten row");
        let insert = ops
            .iter()
            .find(|op| op.opcode == Opcode::Insert)
            .expect("Insert opcode should exist");
        assert!(
            seek_pos < delete_pos && delete_pos < insert_pos,
            "UPDATE by rowid should seek first, then delete, then reinsert"
        );
        assert!(
            ops.iter()
                .skip(seek_pos)
                .any(|op| op.opcode == Opcode::Column),
            "UPDATE should read the non-IPK column from the current row"
        );
        assert!(
            !ops.iter()
                .any(|op| matches!(op.opcode, Opcode::RowSetAdd | Opcode::RowSetRead)),
            "single-rowid UPDATE should not materialize a one-row RowSet"
        );
        assert_eq!(
            delete.p5 & OPFLAG_ISUPDATE,
            OPFLAG_ISUPDATE,
            "UPDATE delete must carry OPFLAG_ISUPDATE so conflict restore can recover the old row"
        );
        assert_eq!(
            insert.p5 & OPFLAG_ISUPDATE,
            OPFLAG_ISUPDATE,
            "UPDATE insert must carry OPFLAG_ISUPDATE so runtime last_insert_rowid() handling stays SQLite-compatible"
        );

        // MakeRecord should have 2 columns (the full record).
        let mr = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::MakeRecord)
            .unwrap();
        assert_eq!(mr.p2, 2); // ALL columns, not just the changed one.
    }

    #[test]
    fn test_codegen_update_ipk_assignment_updates_rowid() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("a".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };

        let mut schema = test_schema();
        schema[0].columns[0].is_ipk = true;

        let ctx = CodegenContext {
            concurrent_mode: true,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let ops: Vec<Opcode> = prog.ops().iter().map(|op| op.opcode).collect();
        assert!(
            ops.contains(&Opcode::Delete),
            "UPDATE must delete old row before reinsert"
        );
        assert!(
            ops.contains(&Opcode::IsNull) && ops.contains(&Opcode::NewRowid),
            "IPK update should handle NULL rowid by generating NewRowid"
        );

        let delete_pos = ops
            .iter()
            .position(|&op| op == Opcode::Delete)
            .expect("Delete opcode should exist");
        let delete = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Delete)
            .expect("Delete opcode should exist");
        let insert = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Insert)
            .expect("Insert opcode should exist");
        let insert_pos = ops
            .iter()
            .position(|&op| op == Opcode::Insert)
            .expect("Insert opcode should exist");
        assert!(
            delete_pos < insert_pos,
            "Delete must execute before Insert in UPDATE rewrite"
        );
        assert_eq!(
            delete.p5 & OPFLAG_ISUPDATE,
            OPFLAG_ISUPDATE,
            "UPDATE delete must carry OPFLAG_ISUPDATE so conflict restore can recover the old row"
        );
        assert_eq!(
            insert.p5 & OPFLAG_ISUPDATE,
            OPFLAG_ISUPDATE,
            "UPDATE insert must carry OPFLAG_ISUPDATE so runtime last_insert_rowid() handling stays SQLite-compatible"
        );
    }

    // === Test 4: DELETE by rowid ===
    #[test]
    fn test_codegen_delete_by_rowid() {
        let stmt = DeleteStatement {
            with: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(1)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_delete(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Rowid equality should use a direct probe in pass 1, then delete via
        // the collected rowset in pass 2.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Init,
                Opcode::Transaction,
                Opcode::OpenWrite,
                Opcode::Variable,   // target rowid
                Opcode::SeekRowid,  // direct probe
                Opcode::RowSetAdd,  // into rowset
                Opcode::RowSetRead, // pass 2: iterate collected rowids
                Opcode::SeekRowid,  // seek to rowid
                Opcode::Delete,     // delete row
                Opcode::Close,
                Opcode::Halt,
            ]
        ));
    }

    #[test]
    fn test_codegen_update_with_index_emits_keyed_idxdelete() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let idx_delete = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::IdxDelete)
            .expect("expected IdxDelete for indexed UPDATE");
        assert!(
            idx_delete.p3 > 0,
            "IdxDelete must carry key register count (p3 > 0) so engine seeks by key"
        );
    }

    #[test]
    fn test_codegen_update_skips_unchanged_simple_index_maintenance() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("a".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::IdxDelete | Opcode::IdxInsert)),
            "UPDATE of non-indexed columns should leave unchanged simple indexes in place"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::Delete | Opcode::Insert)),
            "table row rewrite should remain unchanged"
        );
    }

    #[test]
    fn test_codegen_update_non_rowid_predicate_uses_two_pass_rowset() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("a".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Rewind,
                Opcode::RowSetAdd,
                Opcode::Next,
                Opcode::RowSetRead,
                Opcode::SeekRowid,
                Opcode::Delete,
                Opcode::Insert,
            ]
        ));

        let rowset_add_pos = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::RowSetAdd)
            .expect("RowSetAdd should be emitted before mutation");
        let delete_pos = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::Delete)
            .expect("Delete opcode should exist");
        let delete = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Delete)
            .expect("Delete opcode should exist");
        let insert = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Insert)
            .expect("Insert opcode should exist");
        assert!(
            rowset_add_pos < delete_pos,
            "UPDATE must collect rowids before deleting rows from a scan cursor"
        );
        assert_eq!(
            delete.p5 & OPFLAG_ISUPDATE,
            OPFLAG_ISUPDATE,
            "UPDATE delete must carry OPFLAG_ISUPDATE so conflict restore can recover the old row"
        );
        assert_eq!(
            insert.p5 & OPFLAG_ISUPDATE,
            OPFLAG_ISUPDATE,
            "UPDATE insert must carry OPFLAG_ISUPDATE so runtime last_insert_rowid() handling stays SQLite-compatible"
        );
    }

    #[test]
    fn test_codegen_delete_with_index_emits_keyed_idxdelete() {
        let stmt = DeleteStatement {
            with: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(1)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_delete(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let idx_delete = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::IdxDelete)
            .expect("expected IdxDelete for indexed DELETE");
        assert!(
            idx_delete.p3 > 0,
            "IdxDelete must carry key register count (p3 > 0) so engine seeks by key"
        );
    }

    // === Test 5: Label resolution ===
    #[test]
    fn test_codegen_label_resolution() {
        let stmt = simple_select(&["a"], "t", Some(rowid_eq_param()));
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // All p2 fields that are jumps should have valid addresses (>= 0).
        for op in prog.ops() {
            if op.opcode.is_jump() {
                assert!(
                    op.p2 >= 0,
                    "unresolved jump at {:?}: p2 = {}",
                    op.opcode,
                    op.p2
                );
                assert!(
                    usize::try_from(op.p2).unwrap() <= prog.len(),
                    "jump target out of range at {:?}: p2 = {} (prog len = {})",
                    op.opcode,
                    op.p2,
                    prog.len()
                );
            }
        }
    }

    // === Test 6: Register allocation ===
    #[test]
    fn test_codegen_register_allocation() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // All register references (p1, p2, p3 where applicable) should be
        // within the allocated range.
        let max_reg = prog.register_count();
        assert!(max_reg > 0);

        // Variable instructions: p2 is the target register.
        for op in prog.ops() {
            if op.opcode == Opcode::Variable {
                assert!(
                    op.p2 >= 1 && op.p2 <= max_reg,
                    "Variable register out of range: p2 = {}, max = {}",
                    op.p2,
                    max_reg
                );
            }
        }
    }

    // === Test 7: Concurrent mode NewRowid ===
    #[test]
    fn test_codegen_concurrent_newrowid() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema();
        let ctx = CodegenContext {
            concurrent_mode: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // In concurrent mode, NewRowid p3 should be non-zero.
        let nr = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::NewRowid)
            .unwrap();
        assert_ne!(
            nr.p3, 0,
            "NewRowid p3 should be non-zero in concurrent mode"
        );

        // In non-concurrent mode, p3 should be 0.
        let ctx_normal = CodegenContext::default();
        let mut b2 = ProgramBuilder::new();
        codegen_insert(&mut b2, &stmt, &schema, &ctx_normal).unwrap();
        let prog2 = b2.finish().unwrap();
        let nr2 = prog2
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::NewRowid)
            .unwrap();
        assert_eq!(nr2.p3, 0, "NewRowid p3 should be 0 in normal mode");
    }

    #[test]
    fn test_codegen_concurrent_newrowid_default_values() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::DefaultValues,
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema();
        let ctx = CodegenContext {
            concurrent_mode: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let nr = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::NewRowid)
            .unwrap();
        assert_ne!(
            nr.p3, 0,
            "NewRowid p3 should be non-zero in concurrent mode for DEFAULT VALUES"
        );

        // In non-concurrent mode, p3 should be 0 for DEFAULT VALUES as well.
        let ctx_normal = CodegenContext::default();
        let mut b2 = ProgramBuilder::new();
        codegen_insert(&mut b2, &stmt, &schema, &ctx_normal).unwrap();
        let prog2 = b2.finish().unwrap();
        let nr2 = prog2
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::NewRowid)
            .unwrap();
        assert_eq!(
            nr2.p3, 0,
            "NewRowid p3 should be 0 in normal mode for DEFAULT VALUES"
        );
    }

    // === Test 8: SELECT full scan ===
    #[test]
    fn test_codegen_select_full_scan() {
        let stmt = star_select("t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Init,
                Opcode::Transaction,
                Opcode::OpenRead,
                Opcode::Rewind,
                Opcode::Column,
                Opcode::Column,
                Opcode::ResultRow,
                Opcode::Next,
                Opcode::Close,
                Opcode::Halt,
            ]
        ));

        // ResultRow should cover 2 columns (a and b).
        let rr = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::ResultRow)
            .unwrap();
        assert_eq!(rr.p2, 2);
    }

    #[test]
    fn test_codegen_select_honors_planner_full_scan_directive_over_index_probe() {
        let stmt = simple_select(&["a"], "t", Some(col_cmp_param("b", AstBinaryOp::Eq, 1)));
        let schema = test_schema_with_index();
        let ctx = CodegenContext {
            planner_select_directive: Some(SelectPlannerDirective {
                plan_id: "plan-full-scan".to_owned(),
                plan_generation: 1,
                planner_surface: "single_table_access_path_v1".to_owned(),
                table_name: "t".to_owned(),
                index_name: None,
                index_key_label: None,
                index_key_is_expression: false,
                index_equality_target: None,
                index_range_target: None,
                covering: false,
                access_kind: PlannerSelectAccessKind::FullTableScan,
            }),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "planner full-scan directive should bypass the index probe fast path"
        );
        assert!(
            !ops.iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")
            }),
            "planner full-scan directive should not open the candidate index"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "planner full-scan directive should not emit an index seek"
        );
    }

    #[test]
    fn test_codegen_select_bypasses_stale_planner_rowid_directive() {
        let stmt = simple_select(&["a"], "t", Some(col_cmp_param("b", AstBinaryOp::Eq, 1)));
        let schema = test_schema_with_index();
        let ctx = CodegenContext {
            planner_select_directive: Some(SelectPlannerDirective {
                plan_id: "plan-stale-rowid".to_owned(),
                plan_generation: 1,
                planner_surface: "single_table_access_path_v1".to_owned(),
                table_name: "t".to_owned(),
                index_name: None,
                index_key_label: None,
                index_key_is_expression: false,
                index_equality_target: None,
                index_range_target: None,
                covering: false,
                access_kind: PlannerSelectAccessKind::RowidLookup,
            }),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")
            }),
            "stale rowid directive should be bypassed so heuristic index lowering can still run"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "stale rowid directive should fall back to the ordinary index-equality fast path"
        );
    }

    #[test]
    fn test_codegen_select_honors_covering_planner_index_directive_without_table_lookup() {
        let stmt = simple_select(&["b"], "t", Some(col_cmp_param("b", AstBinaryOp::Eq, 1)));
        let schema = test_schema_with_index();
        let ctx = CodegenContext {
            planner_select_directive: Some(SelectPlannerDirective {
                plan_id: "plan-covering-equality".to_owned(),
                plan_generation: 1,
                planner_surface: "single_table_access_path_v1".to_owned(),
                table_name: "t".to_owned(),
                index_name: Some("idx_t_b".to_owned()),
                index_key_label: Some("b".to_owned()),
                index_key_is_expression: false,
                index_equality_target: None,
                index_range_target: None,
                covering: true,
                access_kind: PlannerSelectAccessKind::IndexEquality,
            }),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();
        let seek_ge_idx = ops
            .iter()
            .position(|op| op.opcode == Opcode::SeekGE)
            .expect("covering equality fast path should probe the chosen index");

        assert!(
            ops.iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")
            }),
            "covering planner directive should still open the chosen index"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::SeekRowid),
            "covering planner directive should avoid table lookups in equality scans"
        );
        assert!(
            !ops[..seek_ge_idx].iter().any(|op| {
                op.opcode == Opcode::OpenRead && matches!(&op.p4, P4::Table(name) if name == "t")
            }),
            "covering equality fast path should defer opening the table cursor until fallback"
        );
        assert!(
            ops[seek_ge_idx + 1..].iter().any(|op| {
                op.opcode == Opcode::OpenRead && matches!(&op.p4, P4::Table(name) if name == "t")
            }),
            "covering equality fast path should retain a lazy table-open fallback"
        );
    }

    #[test]
    fn test_codegen_select_honors_expression_planner_index_equality_directive() {
        let stmt = simple_select(&["name"], "t", Some(lower_name_eq_param(1)));
        let schema = test_schema_with_expression_index();
        let ctx = CodegenContext {
            planner_select_directive: Some(SelectPlannerDirective {
                plan_id: "plan-expression-equality".to_owned(),
                plan_generation: 1,
                planner_surface: "single_table_access_path_v1".to_owned(),
                table_name: "t".to_owned(),
                index_name: Some("idx_t_lower_name".to_owned()),
                index_key_label: Some("lower(name)".to_owned()),
                index_key_is_expression: true,
                index_equality_target: Some(placeholder(1)),
                index_range_target: None,
                covering: false,
                access_kind: PlannerSelectAccessKind::IndexEquality,
            }),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "idx_t_lower_name")
            }),
            "expression planner directive should open the chosen expression index"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "expression equality directive should lower to an index probe"
        );
    }

    #[test]
    fn test_codegen_composite_expression_equality_uses_true_prefix_probe() {
        let stmt = simple_select(&["name"], "t", Some(lower_name_eq_param(1)));
        let mut schema = test_schema_with_expression_index();
        schema[0].indexes[0].key_expressions.push("a".to_owned());
        schema[0].indexes[0].key_sort_directions = vec![SortDirection::Asc, SortDirection::Desc];
        let ctx = CodegenContext {
            planner_select_directive: Some(SelectPlannerDirective {
                plan_id: "plan-composite-expression-equality".to_owned(),
                plan_generation: 1,
                planner_surface: "single_table_access_path_v1".to_owned(),
                table_name: "t".to_owned(),
                index_name: Some("idx_t_lower_name".to_owned()),
                index_key_label: Some("lower(name)".to_owned()),
                index_key_is_expression: true,
                index_equality_target: Some(placeholder(1)),
                index_range_target: None,
                covering: false,
                access_kind: PlannerSelectAccessKind::IndexEquality,
            }),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();
        let seek_idx = ops
            .iter()
            .position(|op| op.opcode == Opcode::SeekGE)
            .expect("composite expression equality should seek its index");
        let probe = ops[..seek_idx]
            .iter()
            .rev()
            .find(|op| op.opcode == Opcode::MakeRecord)
            .expect("index seek must build a probe record");

        assert_eq!(
            probe.p2, 1,
            "unconstrained DESC trailing terms must not be padded with NULL"
        );
    }

    #[test]
    fn test_codegen_select_honors_partial_expression_index_equality_directive() {
        let stmt = simple_select_as(
            &["name"],
            "t",
            "x",
            Some(Box::new(expr_sql("lower(x.Name) = ?1 AND x.A = 1"))),
        );
        let mut schema = test_schema_with_expression_index();
        schema[0].indexes[0].key_expressions[0] = "LOWER(NAME)".to_owned();
        schema[0].indexes[0].where_clause = Some("A = 1".to_owned());
        let ctx = CodegenContext {
            planner_select_directive: Some(SelectPlannerDirective {
                plan_id: "plan-partial-expression-equality".to_owned(),
                plan_generation: 1,
                planner_surface: "single_table_access_path_v1".to_owned(),
                table_name: "t".to_owned(),
                index_name: Some("idx_t_lower_name".to_owned()),
                index_key_label: Some("LOWER(NAME)".to_owned()),
                index_key_is_expression: true,
                index_equality_target: Some(placeholder(1)),
                index_range_target: None,
                covering: false,
                access_kind: PlannerSelectAccessKind::IndexEquality,
            }),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "idx_t_lower_name")
            }),
            "a residual guaranteed by the partial index must not make the VDBE reject the directive"
        );
        assert!(prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE));
    }

    #[test]
    fn test_codegen_select_honors_expression_planner_index_range_directive() {
        let stmt = simple_select(&["name"], "t", Some(lower_name_range_params(1, 2)));
        let schema = test_schema_with_expression_index();
        let ctx = CodegenContext {
            planner_select_directive: Some(SelectPlannerDirective {
                plan_id: "plan-expression-range".to_owned(),
                plan_generation: 1,
                planner_surface: "single_table_access_path_v1".to_owned(),
                table_name: "t".to_owned(),
                index_name: Some("idx_t_lower_name".to_owned()),
                index_key_label: Some("lower(name)".to_owned()),
                index_key_is_expression: true,
                index_equality_target: None,
                index_range_target: Some(PlannerIndexRangeTarget {
                    lower: Some(PlannerIndexRangeBound {
                        expr: placeholder(1),
                        inclusive: true,
                    }),
                    upper: Some(PlannerIndexRangeBound {
                        expr: placeholder(2),
                        inclusive: false,
                    }),
                }),
                covering: false,
                access_kind: PlannerSelectAccessKind::IndexRange,
            }),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "idx_t_lower_name")
            }),
            "expression range directive should open the chosen expression index"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "expression range directive should lower to an index range probe"
        );
    }

    #[test]
    fn test_codegen_select_honors_partial_expression_index_range_directive() {
        let stmt = simple_select_as(
            &["name"],
            "t",
            "x",
            Some(Box::new(expr_sql(
                "lower(x.Name) >= ?1 AND lower(x.name) < ?2 AND x.A = 1",
            ))),
        );
        let mut schema = test_schema_with_expression_index();
        schema[0].indexes[0].key_expressions[0] = "LOWER(NAME)".to_owned();
        schema[0].indexes[0].where_clause = Some("A = 1".to_owned());
        let ctx = CodegenContext {
            planner_select_directive: Some(SelectPlannerDirective {
                plan_id: "plan-partial-expression-range".to_owned(),
                plan_generation: 1,
                planner_surface: "single_table_access_path_v1".to_owned(),
                table_name: "t".to_owned(),
                index_name: Some("idx_t_lower_name".to_owned()),
                index_key_label: Some("LOWER(NAME)".to_owned()),
                index_key_is_expression: true,
                index_equality_target: None,
                index_range_target: Some(PlannerIndexRangeTarget {
                    lower: Some(PlannerIndexRangeBound {
                        expr: placeholder(1),
                        inclusive: true,
                    }),
                    upper: Some(PlannerIndexRangeBound {
                        expr: placeholder(2),
                        inclusive: false,
                    }),
                }),
                covering: false,
                access_kind: PlannerSelectAccessKind::IndexRange,
            }),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "idx_t_lower_name")
            }),
            "partial-index range proof must survive the independent VDBE verifier"
        );
        assert!(prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE));
    }

    #[test]
    fn test_codegen_select_bypasses_expression_planner_index_directive_with_residual_filter() {
        let stmt = simple_select(
            &["name"],
            "t",
            Some(and_expr(
                lower_name_eq_param(1),
                col_cmp_param("a", AstBinaryOp::Eq, 2),
            )),
        );
        let schema = test_schema_with_expression_index();
        let ctx = CodegenContext {
            planner_select_directive: Some(SelectPlannerDirective {
                plan_id: "plan-expression-residual".to_owned(),
                plan_generation: 1,
                planner_surface: "single_table_access_path_v1".to_owned(),
                table_name: "t".to_owned(),
                index_name: Some("idx_t_lower_name".to_owned()),
                index_key_label: Some("lower(name)".to_owned()),
                index_key_is_expression: true,
                index_equality_target: Some(placeholder(1)),
                index_range_target: None,
                covering: false,
                access_kind: PlannerSelectAccessKind::IndexEquality,
            }),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            !ops.iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "idx_t_lower_name")
            }),
            "residual predicates should bypass the expression-index directive fast path"
        );
        assert!(
            ops.iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "bypassed expression directive should fall back to a scan"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "bypassed expression directive must not emit an index seek"
        );
    }

    #[test]
    fn test_codegen_select_non_column_expr_with_from_accepted() {
        // Non-column expressions in SELECT list with FROM are now supported
        // via ScanCtx-aware emit_expr in emit_column_reads.
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::BinaryOp {
                            left: Box::new(Expr::Literal(Literal::Integer(1), Span::ZERO)),
                            op: AstBinaryOp::Add,
                            right: Box::new(Expr::Literal(Literal::Integer(2), Span::ZERO)),
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect("non-column expression in SELECT list should succeed");
        let prog = b.finish().unwrap();

        // Should contain Add opcode for the 1 + 2 expression.
        assert!(
            has_opcodes(
                &prog,
                &[Opcode::Init, Opcode::OpenRead, Opcode::Rewind, Opcode::Add]
            ),
            "expected Add opcode for expression evaluation"
        );
    }

    #[test]
    fn test_codegen_select_substr_prefix_column_uses_direct_opcode() {
        let stmt = select_sql("SELECT substr(b, 1, 3) FROM t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        assert!(
            ops.contains(&Opcode::ColumnSubstrPrefix),
            "literal prefix substr(column, 1, N) should avoid full column materialization"
        );
        assert!(
            !ops.contains(&Opcode::PureFunc),
            "direct prefix substr should not emit scalar function dispatch"
        );
    }

    #[test]
    fn test_codegen_select_substr_prefix_column_executes() {
        let stmt = select_sql("SELECT substr(name, 1, 4), substring(name, 1, 99) FROM bench");
        let results = execute_codegen_select_with_storage_cursor(
            &stmt,
            &test_small_bench_schema(),
            seed_small_bench_db(3),
        );

        assert_eq!(
            results,
            vec![
                vec![
                    SqliteValue::Text("name".into()),
                    SqliteValue::Text("name0".into()),
                ],
                vec![
                    SqliteValue::Text("name".into()),
                    SqliteValue::Text("name1".into()),
                ],
                vec![
                    SqliteValue::Text("name".into()),
                    SqliteValue::Text("name2".into()),
                ],
            ]
        );
    }

    #[test]
    fn test_codegen_select_substr_prefix_column_preserves_unicode_and_blob_edges() {
        let mut db = MemDatabase::new();
        db.create_table_at(2, 3);
        let table = db.get_table_mut(2).expect("bench table should exist");
        table.insert_row(
            1,
            vec![
                SqliteValue::Integer(1),
                SqliteValue::Text("éclair".into()),
                SqliteValue::Float(1.0),
            ],
        );
        table.insert_row(
            2,
            vec![
                SqliteValue::Integer(2),
                SqliteValue::Blob(Arc::from(&b"abcdef"[..])),
                SqliteValue::Float(2.0),
            ],
        );

        let stmt = select_sql("SELECT substr(name, 1, 2) FROM bench");
        let results =
            execute_codegen_select_with_storage_cursor(&stmt, &test_small_bench_schema(), db);

        assert_eq!(
            results,
            vec![
                vec![SqliteValue::Text("éc".into())],
                vec![SqliteValue::Blob(Arc::from(&b"ab"[..]))],
            ]
        );
    }

    #[test]
    fn test_codegen_select_octet_length_column_uses_record_metadata_opcode() {
        let stmt = select_sql("SELECT octet_length(name) FROM bench");
        let schema = test_small_bench_schema();
        let ctx = CodegenContext::default();
        let mut builder = ProgramBuilder::new();
        codegen_select(&mut builder, &stmt, &schema, &ctx).unwrap();
        let program = builder.finish().unwrap();
        let ops = opcode_sequence(&program);

        assert!(
            ops.contains(&Opcode::ColumnOctetLength),
            "octet_length(column) must inspect record metadata before source materialization"
        );
        assert!(
            !ops.contains(&Opcode::PureFunc),
            "direct octet length should not decode the source for scalar dispatch"
        );

        let mut db = MemDatabase::new();
        db.create_table_at(2, 3);
        let table = db.get_table_mut(2).expect("bench table should exist");
        for (rowid, value) in [
            SqliteValue::Text("éclair".into()),
            SqliteValue::Blob(Arc::from(&b"abcdef"[..])),
            SqliteValue::Integer(123),
            SqliteValue::Null,
        ]
        .into_iter()
        .enumerate()
        {
            table.insert_row(
                i64::try_from(rowid + 1).unwrap(),
                vec![
                    SqliteValue::Integer(i64::try_from(rowid + 1).unwrap()),
                    value,
                    SqliteValue::Float(1.0),
                ],
            );
        }

        let results = execute_codegen_select_with_storage_cursor(&stmt, &schema, db);
        assert_eq!(
            results,
            vec![
                vec![SqliteValue::Integer(7)],
                vec![SqliteValue::Integer(6)],
                vec![SqliteValue::Integer(3)],
                vec![SqliteValue::Null],
            ]
        );
    }

    #[test]
    fn test_codegen_octet_length_virtual_generated_column_recomputes_value() {
        let stmt = select_sql("SELECT octet_length(c) FROM t");
        let schema = test_schema_with_virtual_generated();
        let ctx = CodegenContext::default();
        let mut builder = ProgramBuilder::new();
        codegen_select(&mut builder, &stmt, &schema, &ctx).unwrap();
        let program = builder.finish().unwrap();

        assert!(
            !opcode_sequence(&program).contains(&Opcode::ColumnOctetLength),
            "a VIRTUAL generated column must be recomputed before octet_length"
        );

        let mut db = MemDatabase::new();
        db.create_table_at(2, 3);
        db.get_table_mut(2).expect("table should exist").insert_row(
            1,
            vec![
                SqliteValue::Integer(7),
                SqliteValue::Integer(0),
                SqliteValue::Null,
            ],
        );

        let results = execute_codegen_select_with_storage_cursor(&stmt, &schema, db);
        assert_eq!(results, vec![vec![SqliteValue::Integer(2)]]);
    }

    #[test]
    fn test_codegen_select_table_star_wrong_table_rejected() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::TableStar(QualifiedName::bare("u"))],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err =
            codegen_select(&mut b, &stmt, &schema, &ctx).expect_err("unknown table qualifier");
        assert_eq!(err, CodegenError::TableNotFound("u".to_owned()));
    }

    #[test]
    fn test_codegen_select_with_clause_fails_closed() {
        let stmt = select_sql("WITH picked AS (SELECT b FROM s) SELECT a FROM t");
        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect_err("WITH lowering must not silently bypass CTE semantics");

        match err {
            CodegenError::Unsupported(message) => assert!(
                message.contains("WITH clauses require connection-level CTE lowering"),
                "unexpected unsupported message: {message}"
            ),
            other => assert!(
                false,
                "expected explicit unsupported WITH boundary, got {other:?}"
            ),
        }
        assert_eq!(
            b.current_addr(),
            0,
            "fail-closed WITH handling should not emit partial bytecode"
        );
    }

    // === Test 9: SELECT with indexed predicate ===
    #[test]
    fn test_codegen_select_with_index() {
        let stmt = simple_select(&["a"], "t", Some(col_eq_param("b", 1)));
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Indexed equality should probe the index, anchor on the first
        // duplicate using [param, i64::MIN], and iterate the duplicate run.
        let open_reads = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::OpenRead)
            .count();
        assert_eq!(
            open_reads, 2,
            "indexed equality should open both table and index cursors"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")),
            "expected index cursor open for indexed equality probe"
        );

        let int64 = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Int64)
            .expect("Int64 should load i64::MIN for duplicate-range seek lower bound");
        assert_eq!(int64.p4, P4::Int64(i64::MIN));

        let make_record = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::MakeRecord)
            .expect("MakeRecord should build the composite probe key");
        assert_eq!(
            make_record.p1 + 1,
            int64.p2,
            "MakeRecord should consume [param_reg, min_rowid_reg]"
        );

        let seek_ge = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::SeekGE)
            .expect("SeekGE should be emitted for index probe");
        assert_eq!(
            seek_ge.p3, make_record.p3,
            "SeekGE must read probe key from MakeRecord destination register"
        );

        let is_null_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::IsNull)
            .count();
        assert!(
            is_null_count >= 1,
            "indexed equality should guard NULL probe"
        );

        let seek_rowid = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::SeekRowid)
            .expect("SeekRowid should follow IdxRowid");
        assert_ne!(
            seek_rowid.p2, 0,
            "SeekRowid miss target must not jump to pc=0"
        );

        let next = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Next)
            .expect("index equality path must iterate duplicates");
        assert_eq!(next.p1, 1, "Next should advance the index cursor");

        let boundary_column = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Column && op.p1 == 1 && op.p2 == 0)
            .expect("single-column duplicate-run boundary should read the index key");
        let boundary_ne = prog
            .ops()
            .iter()
            .find(|op| {
                op.opcode == Opcode::Ne && op.p1 == make_record.p1 && op.p3 == boundary_column.p3
            })
            .expect("single-column duplicate-run boundary should compare against the probe value");
        let if_addr = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::If)
            .expect("normal duplicate-run exit should branch through a match gate");
        assert_eq!(
            usize::try_from(boundary_ne.p2).unwrap(),
            if_addr,
            "duplicate-run boundary must not jump directly into the full-scan fallback"
        );
        assert_eq!(
            boundary_ne.p5 & 0x10,
            0x10,
            "duplicate-run boundary should jump when the index cursor reaches EOF"
        );
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::IdxGT),
            "single-column equality should not need the generic record-prefix boundary"
        );
    }

    fn test_schema_with_composite_prefix_index() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "messages".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("id", 'D', true),
                ColumnInfo::basic("conversation_id", 'D', false),
                ColumnInfo::basic("idx", 'D', false),
                ColumnInfo::basic("content", 'B', false),
            ],
            indexes: vec![IndexSchema {
                name: "sqlite_autoindex_messages_1".to_owned(),
                root_page: 3,
                columns: vec!["conversation_id".to_owned(), "idx".to_owned()],
                key_expressions: vec!["conversation_id".to_owned(), "idx".to_owned()],
                key_sort_directions: vec![],
                where_clause: None,
                is_unique: true,
                key_collations: vec![],
                conflict_action: None,
            }],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn test_schema_with_three_column_composite_index() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "events".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("id", 'D', true),
                ColumnInfo::basic("tenant_id", 'D', false),
                ColumnInfo::basic("stream_id", 'D', false),
                ColumnInfo::basic("sequence", 'D', false),
            ],
            indexes: vec![IndexSchema {
                name: "sqlite_autoindex_events_1".to_owned(),
                root_page: 3,
                columns: vec![
                    "tenant_id".to_owned(),
                    "stream_id".to_owned(),
                    "sequence".to_owned(),
                ],
                key_expressions: vec![
                    "tenant_id".to_owned(),
                    "stream_id".to_owned(),
                    "sequence".to_owned(),
                ],
                key_sort_directions: vec![],
                where_clause: None,
                is_unique: true,
                key_collations: vec![],
                conflict_action: None,
            }],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn test_schema_with_collated_composite_prefix_index() -> Vec<TableSchema> {
        let mut tenant = ColumnInfo::basic("tenant", 'B', false);
        tenant.collation = Some("NOCASE".to_owned());
        vec![TableSchema {
            name: "collated_events".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("id", 'D', true),
                tenant,
                ColumnInfo::basic("sequence", 'D', false),
            ],
            indexes: vec![IndexSchema {
                name: "sqlite_autoindex_collated_events_1".to_owned(),
                root_page: 3,
                columns: vec!["tenant".to_owned(), "sequence".to_owned()],
                key_expressions: vec!["tenant".to_owned(), "sequence".to_owned()],
                key_sort_directions: vec![],
                where_clause: None,
                is_unique: true,
                key_collations: vec![Some("NOCASE".to_owned()), None],
                conflict_action: None,
            }],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    #[test]
    fn test_codegen_select_with_composite_index_prefix_equality_anchors_full_key() {
        let schema = test_schema_with_composite_prefix_index();
        let table = &schema[0];
        let idx_schema = &table.indexes[0];
        let columns = vec![
            ResultColumn::Expr {
                expr: Expr::Column(ColumnRef::bare("id"), Span::ZERO),
                alias: None,
            },
            ResultColumn::Expr {
                expr: Expr::Column(ColumnRef::bare("idx"), Span::ZERO),
                alias: None,
            },
            ResultColumn::Expr {
                expr: Expr::Column(ColumnRef::bare("content"), Span::ZERO),
                alias: None,
            },
        ];
        let where_clause = col_eq_param("conversation_id", 1);
        let mut b = ProgramBuilder::new();
        let out_regs = b.alloc_regs(columns.len() as i32);
        let done_label = b.emit_label();
        let end_label = b.emit_label();
        codegen_select_index_equality_scan(
            &mut b,
            0,
            table,
            None,
            &schema,
            &columns,
            Some(&where_clause),
            None,
            out_regs,
            columns.len() as i32,
            done_label,
            end_label,
            idx_schema,
            &placeholder(1),
            false,
            false,
        )
        .unwrap();
        b.resolve_label(done_label);
        b.resolve_label(end_label);
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        let seek_ge = ops
            .iter()
            .find(|op| op.opcode == Opcode::SeekGE)
            .expect("composite equality scan should probe the autoindex");
        let make_record = ops
            .iter()
            .find(|op| op.opcode == Opcode::MakeRecord && op.p3 == seek_ge.p3)
            .expect("SeekGE should consume a dedicated composite probe record");
        assert_eq!(
            seek_ge.p3, make_record.p3,
            "SeekGE must read the composite probe key from MakeRecord"
        );
        // DESC-safety (bd-2fong seek-record rework): a COMPOSITE index is
        // positioned with a TRUE one-field prefix record — just the leading
        // `conversation_id` term — NOT the leading term NULL-padded across the
        // trailing indexed columns plus a rowid floor. Padding trailing terms
        // with NULL is not a valid block floor when any trailing term is DESC:
        // SeekGE would start in the trailing-NULL region and silently skip
        // preceding non-NULL entries. The equality-prefix duplicate run is
        // instead bounded by the IdxGT recheck (see the sibling ordered-scan
        // test), so the one-field prefix probe is exact.
        assert_eq!(
            make_record.p2, 1,
            "composite prefix probe must be a single leading-term record, not a NULL-padded full key"
        );
        assert!(
            !ops.iter()
                .any(|op| op.opcode == Opcode::Null && op.p2 == make_record.p1 + 1),
            "composite prefix probe must not NULL-pad the trailing indexed term"
        );
        assert!(
            !ops.iter()
                .any(|op| op.opcode == Opcode::Int64 && op.p4 == P4::Int64(i64::MIN)),
            "single-key probes append a rowid floor; a composite prefix probe must not"
        );
    }

    #[test]
    fn test_codegen_ordered_scan_with_composite_equality_rechecks_prefix_boundary_each_next() {
        let schema = test_schema_with_composite_prefix_index();
        let table = schema
            .iter()
            .find(|table| table.name == "messages")
            .expect("messages table");
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("id"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("idx"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("content"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("messages"),
                            alias: None,
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![],
                    }),
                    where_clause: Some(col_eq_param("conversation_id", 1)),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare("idx"), Span::ZERO),
                direction: Some(fsqlite_ast::SortDirection::Asc),
                nulls: None,
            }],
            limit: None,
        };
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).expect("codegen ordered scan");
        let prog = b.finish().expect("finish program");
        let ops = prog.ops();

        let idx_gt_addr = ops
            .iter()
            .position(|op| op.opcode == Opcode::IdxGT)
            .expect("bounded ordered scan should emit IdxGT boundary");
        let next = ops
            .iter()
            .find(|op| op.opcode == Opcode::Next)
            .expect("ordered composite scan should iterate index entries");

        assert_eq!(
            next.p2, idx_gt_addr as i32,
            "Next must jump back to the IdxGT boundary check so each scanned row stays within the equality-prefix duplicate run"
        );
        assert!(
            ops.iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "sqlite_autoindex_messages_1")
            }),
            "ordered scan should open the composite autoindex"
        );
        assert_eq!(
            table.indexes[0].columns,
            vec!["conversation_id".to_owned(), "idx".to_owned()],
            "test assumes the composite ordered index is keyed by conversation_id then idx"
        );
    }

    #[test]
    fn test_codegen_select_with_index_wrong_qualifier_errors() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(Box::new(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::qualified("u", "b"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(1)),
                span: Span::ZERO,
            })),
        );
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect_err("mismatched qualifier should be a semantic error");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "u" && column == "u.b"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_select_with_index_range() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(and_expr(
                col_cmp_param("b", AstBinaryOp::Gt, 1),
                col_cmp_param("b", AstBinaryOp::Lt, 2),
            )),
        );
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "indexed range should position with SeekGE on the index cursor"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Le),
            "exclusive lower bound should skip entries equal to the low key"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Ge),
            "exclusive upper bound should stop once the current key reaches the high key"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")),
            "range scan should open the matching index"
        );
        assert!(
            !ops.iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "index range should not fall back to rewinding the table cursor"
        );

        let next = ops
            .iter()
            .find(|op| op.opcode == Opcode::Next)
            .expect("index range should advance through index entries");
        assert_eq!(next.p1, 1, "Next should advance the index cursor");
    }

    #[test]
    fn test_codegen_select_with_index_like_pure_prefix_uses_range_scan() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(Box::new(Expr::Like {
                expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                pattern: Box::new(Expr::Literal(
                    Literal::String("123%".to_owned()),
                    Span::ZERO,
                )),
                escape: None,
                op: fsqlite_ast::LikeOp::Like,
                not: false,
                span: Span::ZERO,
            })),
        );
        // TEXT+BINARY column: the case-stable prefix range is byte-exact here.
        let schema = test_schema_with_text_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "pure trailing-percent LIKE prefixes should lower to indexed range seeks"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Ge),
            "LIKE prefix range should stop once the current key reaches the derived upper bound"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")),
            "LIKE prefix range should open the matching index"
        );
        assert!(
            !ops.iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "LIKE prefix range should not fall back to a table rewind"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::LikeConstFast),
            "pure prefix LIKE lowered as an index range should not keep the full-scan LIKE filter path"
        );
    }

    #[test]
    fn test_codegen_select_with_index_like_escaped_prefix_uses_range_scan() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(Box::new(Expr::Like {
                expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                pattern: Box::new(Expr::Literal(
                    Literal::String("123\\%%".to_owned()),
                    Span::ZERO,
                )),
                escape: Some(Box::new(Expr::Literal(
                    Literal::String("\\".to_owned()),
                    Span::ZERO,
                ))),
                op: fsqlite_ast::LikeOp::Like,
                not: false,
                span: Span::ZERO,
            })),
        );
        // TEXT+BINARY column: the case-stable escaped prefix range is byte-exact here.
        let schema = test_schema_with_text_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "escaped pure-prefix LIKE patterns should lower to indexed range seeks"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Ge),
            "escaped pure-prefix LIKE patterns should still stop at the derived upper bound"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")),
            "escaped pure-prefix LIKE range should open the matching index"
        );
        assert!(
            !ops.iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "escaped pure-prefix LIKE range should not fall back to a table rewind"
        );
        assert!(
            !ops.iter().any(|op| {
                op.opcode == Opcode::PureFunc
                    && matches!(&op.p4, P4::FuncName(name) if name == "LIKE")
            }),
            "escaped pure-prefix LIKE range should not keep the generic LIKE runtime filter"
        );
    }

    #[test]
    fn test_codegen_select_with_index_like_escaped_underscore_prefix_uses_range_scan() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(Box::new(Expr::Like {
                expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                pattern: Box::new(Expr::Literal(
                    Literal::String("123\\_%".to_owned()),
                    Span::ZERO,
                )),
                escape: Some(Box::new(Expr::Literal(
                    Literal::String("\\".to_owned()),
                    Span::ZERO,
                ))),
                op: fsqlite_ast::LikeOp::Like,
                not: false,
                span: Span::ZERO,
            })),
        );
        // TEXT+BINARY column: the case-stable escaped prefix range is byte-exact here.
        let schema = test_schema_with_text_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "escaped underscore-prefix LIKE patterns should lower to indexed range seeks"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Ge),
            "escaped underscore-prefix LIKE patterns should still stop at the derived upper bound"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")),
            "escaped underscore-prefix LIKE range should open the matching index"
        );
        assert!(
            !ops.iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "escaped underscore-prefix LIKE range should not fall back to a table rewind"
        );
        assert!(
            !ops.iter().any(|op| {
                op.opcode == Opcode::PureFunc
                    && matches!(&op.p4, P4::FuncName(name) if name == "LIKE")
            }),
            "escaped underscore-prefix LIKE range should not keep the generic LIKE runtime filter"
        );
    }

    #[test]
    fn test_codegen_select_with_index_like_embedded_wildcard_stays_on_filter_path() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(Box::new(Expr::Like {
                expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                pattern: Box::new(Expr::Literal(
                    Literal::String("123%tail".to_owned()),
                    Span::ZERO,
                )),
                escape: None,
                op: fsqlite_ast::LikeOp::Like,
                not: false,
                span: Span::ZERO,
            })),
        );
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "embedded-wildcard LIKE patterns should not be mis-lowered as exact range scans"
        );
        assert!(
            ops.iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "unsupported LIKE shapes should stay on the ordinary scan path"
        );
    }

    #[test]
    fn test_codegen_select_upper_only_index_range_guards_null_keys() {
        let stmt = simple_select(&["a"], "t", Some(col_cmp_param("b", AstBinaryOp::Lt, 1)));
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        let key_read_idx = ops
            .iter()
            .position(|op| op.opcode == Opcode::Column && op.p1 == 1 && op.p2 == 0)
            .expect("upper-only range should read the current index key");
        let key_reg = ops[key_read_idx].p3;
        let key_null_guard_idx = ops
            .iter()
            .position(|op| op.opcode == Opcode::IsNull && op.p1 == key_reg)
            .expect("upper-only range should skip NULL index keys");
        let upper_guard_idx = ops
            .iter()
            .position(|op| op.opcode == Opcode::Ge)
            .expect("exclusive upper bound should emit Ge stop guard");

        assert!(
            key_read_idx < key_null_guard_idx,
            "NULL guard should run after reading the current index key"
        );
        assert!(
            key_null_guard_idx < upper_guard_idx,
            "NULL guard should run before the upper-bound comparison"
        );
    }

    #[test]
    fn test_codegen_select_with_index_between_can_be_covering() {
        let stmt = simple_select(
            &["b"],
            "t",
            Some(Box::new(Expr::Between {
                expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                low: Box::new(placeholder(1)),
                high: Box::new(placeholder(2)),
                not: false,
                span: Span::ZERO,
            })),
        );
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "BETWEEN should reuse the indexed range seek path"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Gt),
            "inclusive upper bound should stop only after the current key exceeds the high key"
        );

        let table_open_count = ops
            .iter()
            .filter(|op| {
                op.opcode == Opcode::OpenRead && matches!(&op.p4, P4::Table(name) if name == "t")
            })
            .count();
        assert_eq!(
            table_open_count, 0,
            "covering index range should not open the table cursor"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::SeekRowid),
            "covering index range should not perform table rowid lookups"
        );
    }

    #[test]
    fn test_codegen_select_index_range_checks_offset_before_projection() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: Some(and_expr(
                        col_cmp_param("b", AstBinaryOp::Ge, 1),
                        col_cmp_param("b", AstBinaryOp::Lt, 2),
                    )),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: Some(LimitClause {
                limit: Expr::Literal(Literal::Integer(5), Span::ZERO),
                offset: Some(Expr::Literal(Literal::Integer(3), Span::ZERO)),
            }),
        };
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        let ifpos_idx = ops
            .iter()
            .position(|op| op.opcode == Opcode::IfPos)
            .expect("range scan with OFFSET should emit IfPos");
        let seek_rowid_idx = ops
            .iter()
            .position(|op| op.opcode == Opcode::SeekRowid)
            .expect("non-covering index range should seek into the table");
        let projected_column_idx = ops
            .iter()
            .position(|op| op.opcode == Opcode::Column && op.p1 == 0 && op.p2 == 0)
            .expect("non-covering index range should project table columns");

        assert!(
            seek_rowid_idx < ifpos_idx,
            "OFFSET should only decrement after the row lookup succeeds"
        );
        assert!(
            ifpos_idx < projected_column_idx,
            "OFFSET skipping should happen before decoding projected columns"
        );
    }

    #[test]
    fn test_codegen_select_index_range_with_nocase_collation_falls_back() {
        let stmt = simple_select(
            &["name"],
            "t",
            Some(col_cmp_param("name", AstBinaryOp::Lt, 1)),
        );
        let schema = test_schema_with_nocase_text_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "NOCASE range should stay on the generic full-scan path"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_name")),
            "unsafe collation semantics should not use the index-range fast path"
        );
    }

    #[test]
    fn test_codegen_select_index_range_with_numeric_affinity_uses_index() {
        // bd-u6tbr enabled the placeholder-bound numeric-affinity range seek: the bound is coerced
        // to the column's affinity ('D') so the seek positions identically to the WHERE comparison,
        // making the index-range fast path byte-exact (differential oracle: index_range_seek_oracle_e2e).
        // (Was previously asserted to "fall back" to a full scan; bd-u6tbr made that assertion stale.)
        let stmt = simple_select(
            &["n"],
            "t",
            Some(and_expr(
                col_cmp_param("n", AstBinaryOp::Ge, 1),
                col_cmp_param("n", AstBinaryOp::Lt, 2),
            )),
        );
        let schema = test_schema_with_typed_numeric_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_n")),
            "numeric-affinity placeholder range should use the index-range seek (bd-u6tbr)"
        );
        assert!(
            !ops.iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "the index-range seek must not fall back to a full table scan (Rewind on cursor 0)"
        );
        assert!(
            ops.iter()
                .any(|op| op.opcode == Opcode::Affinity
                    && matches!(&op.p4, P4::Affinity(a) if a == "D")),
            "the placeholder bound should be coerced to the column's numeric affinity before the seek"
        );
    }

    #[test]
    fn test_codegen_select_index_range_with_anonymous_params_stays_on_full_scan() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(and_expr(
                Box::new(Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                    op: AstBinaryOp::Ge,
                    right: Box::new(anonymous_placeholder()),
                    span: Span::ZERO,
                }),
                Box::new(Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                    op: AstBinaryOp::Lt,
                    right: Box::new(anonymous_placeholder()),
                    span: Span::ZERO,
                }),
            )),
        );
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Rewind),
            "anonymous placeholder ranges must stay on the original full-scan path"
        );
        assert!(
            !ops.iter()
                .any(|op| matches!(op.opcode, Opcode::SeekGE | Opcode::SeekGT)),
            "fast-path index range seek must not reorder anonymous placeholders"
        );
    }

    #[test]
    fn test_codegen_select_index_range_with_wrong_qualifier_errors() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(and_expr(
                qualified_col_cmp_param("u", "b", AstBinaryOp::Ge, 1),
                qualified_col_cmp_param("u", "b", AstBinaryOp::Lt, 2),
            )),
        );
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect_err("mismatched qualifier should be a semantic error");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "u" && column == "u.b"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_select_where_in_subquery_supported_without_rewrite() {
        let subquery = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::bare("b"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(from_table("s")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
            set: InSet::Subquery(Box::new(subquery)),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let open_reads = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::OpenRead)
            .count();
        assert_eq!(open_reads, 2, "outer + probe OpenRead expected");
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::Eq | Opcode::Found)),
            "expected IN membership probe"
        );
    }

    #[test]
    fn test_resolve_in_probe_source_subquery_supported() {
        let subquery = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::bare("b"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(from_table("s")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let set = InSet::Subquery(Box::new(subquery));
        let schema = test_schema_with_subquery_source();
        assert!(super::resolve_in_probe_source(&set, &schema).is_some());
    }

    #[test]
    fn test_resolve_in_probe_source_table_supported() {
        let set = InSet::Table(QualifiedName::bare("s"));
        let schema = test_schema_with_subquery_source();
        assert!(super::resolve_in_probe_source(&set, &schema).is_some());
    }

    #[test]
    fn test_emit_in_probe_expr_fails_closed_when_probe_lowering_is_unsupported() {
        let schema = test_schema_with_subquery_source();
        let scan_ctx = ScanCtx {
            cursor: 0,
            table: &schema[0],
            table_alias: None,
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };
        let unsupported_subquery = select_sql("SELECT b, b FROM s");
        let set = InSet::Subquery(Box::new(unsupported_subquery));
        let operand = Expr::Column(ColumnRef::bare("a"), Span::ZERO);
        let mut b = ProgramBuilder::new();
        let result_reg = b.alloc_reg();

        emit_in_probe_expr(&mut b, &operand, &set, false, result_reg, Some(&scan_ctx));

        let program = b.finish().expect("error program should be valid VDBE");
        assert_eq!(
            program.ops(),
            &[VdbeOp {
                opcode: Opcode::Halt,
                p1: ErrorCode::Internal as i32,
                p2: 0,
                p3: 0,
                p4: P4::Str(
                    "IN probe codegen invariant failed: unsupported probe source".to_owned()
                ),
                p5: 0,
            }],
            "an unsupported compiled IN probe must fail explicitly, never yield SQL NULL"
        );
    }

    #[test]
    fn row_value_in_list_executes_match_miss_unknown_not_and_empty_truth_tables() {
        let stmt = select_sql(
            "SELECT \
             (1, 2) IN ((9, 9), (1, 2)), \
             (1, 2) IN ((9, 9), (3, 4)), \
             (1, 2) IN ((1, NULL), (3, 4)), \
             (1, 2) IN ((NULL, 3)), \
             (1, 2) NOT IN ((9, 9), (3, 4)), \
             (1, 2) NOT IN ((1, NULL), (3, 4)), \
             (NULL, 2) IN (), \
             (NULL, 2) NOT IN ()",
        );

        let rows = execute_codegen_select_with_storage_cursor(&stmt, &[], MemDatabase::new());

        assert_eq!(
            rows,
            vec![vec![
                SqliteValue::Integer(1),
                SqliteValue::Integer(0),
                SqliteValue::Null,
                SqliteValue::Integer(0),
                SqliteValue::Integer(1),
                SqliteValue::Null,
                SqliteValue::Integer(0),
                SqliteValue::Integer(1),
            ]],
            "vector IN must preserve candidate-local NULL semantics and invert only definite results"
        );
    }

    #[test]
    fn row_value_in_list_uses_final_rhs_tuple_as_field_metadata_donor() {
        let stmt = select_sql(
            "SELECT \
             (1, 2) IN ((CAST('1' AS TEXT), 2), (CAST('x' AS BLOB), 3)), \
             (1, 2) IN ((CAST('x' AS BLOB), 3), (CAST('1' AS TEXT), 2)), \
             ('a', 1) IN (('A', 1), ('x' COLLATE NOCASE, 2)), \
             ('a', 1) IN (('x' COLLATE NOCASE, 2), ('A', 1))",
        );

        let rows = execute_codegen_select_with_storage_cursor(&stmt, &[], MemDatabase::new());

        assert_eq!(
            rows,
            vec![vec![
                SqliteValue::Integer(0),
                SqliteValue::Integer(1),
                SqliteValue::Integer(1),
                SqliteValue::Integer(0),
            ]],
            "reversing the final syntactic tuple must reverse affinity/collation donation"
        );
    }

    #[test]
    fn row_value_in_list_evaluates_each_volatile_lhs_field_once() {
        use fsqlite_func::ScalarFunction;
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct NextVectorValue(Arc<AtomicUsize>);

        impl ScalarFunction for NextVectorValue {
            fn invoke(&self, _args: &[SqliteValue]) -> fsqlite_error::Result<SqliteValue> {
                let value = self.0.fetch_add(1, Ordering::Relaxed) + 1;
                Ok(SqliteValue::Integer(
                    i64::try_from(value).expect("test counter should fit in i64"),
                ))
            }

            fn is_deterministic(&self) -> bool {
                false
            }

            fn num_args(&self) -> i32 {
                0
            }

            fn name(&self) -> &str {
                "next_vector_value"
            }
        }

        let calls = Arc::new(AtomicUsize::new(0));
        let mut registry = FunctionRegistry::new();
        register_builtins(&mut registry);
        registry.register_scalar(NextVectorValue(Arc::clone(&calls)));
        let stmt = select_sql(
            "SELECT (next_vector_value(), next_vector_value()) \
             IN ((9, 9), (1, 2))",
        );

        let rows = execute_codegen_select_with_registry(&stmt, &[], MemDatabase::new(), registry);

        assert_eq!(rows, vec![vec![SqliteValue::Integer(1)]]);
        assert_eq!(
            calls.load(Ordering::Relaxed),
            2,
            "each volatile LHS field must run once, independent of candidate count"
        );
    }

    #[test]
    fn row_value_in_list_fails_closed_on_arity_and_probe_shape_mismatches() {
        let scalar = |value| Expr::Literal(Literal::Integer(value), Span::ZERO);
        let lhs = Expr::RowValue(vec![scalar(1), scalar(2)], Span::ZERO);
        let malformed_list = Expr::In {
            expr: Box::new(lhs.clone()),
            set: InSet::List(vec![Expr::RowValue(vec![scalar(1)], Span::ZERO)]),
            not: false,
            span: Span::ZERO,
        };
        let unmaterialized_probe = Expr::In {
            expr: Box::new(lhs),
            set: InSet::Subquery(Box::new(select_sql("SELECT 1, 2"))),
            not: false,
            span: Span::ZERO,
        };
        let runtime = RuntimeBuilder::current_thread()
            .blocking_threads(1, 2)
            .build()
            .expect("build fail-closed row-value test runtime");

        for (expr, expected_reason) in [
            (
                malformed_list,
                "row-value IN arity mismatch: expected 2, found 1",
            ),
            (
                unmaterialized_probe,
                "multi-column subquery/table probes require prior list materialization",
            ),
        ] {
            let mut builder = ProgramBuilder::new();
            let result = builder.alloc_reg();
            emit_expr(&mut builder, &expr, result, None);
            let program = builder
                .finish()
                .expect("fail-closed row-value program should finish");

            assert_eq!(
                program.ops(),
                &[VdbeOp {
                    opcode: Opcode::Halt,
                    p1: ErrorCode::Internal as i32,
                    p2: 0,
                    p3: 0,
                    p4: P4::Str(format!(
                        "IN probe codegen invariant failed: {expected_reason}"
                    )),
                    p5: 0,
                }],
                "unsupported vector probe shape must never degrade to a scalar NULL result"
            );

            let mut engine = VdbeEngine::new(program.register_count());
            let outcome = runtime
                .block_on(async { engine.execute(&program).await })
                .expect("fail-closed program execution should return a VDBE outcome");
            assert_eq!(
                outcome,
                ExecOutcome::Error {
                    code: ErrorCode::Internal as i32,
                    message: format!("IN probe codegen invariant failed: {expected_reason}"),
                },
                "unsupported vector probe shape must surface the codegen invariant at runtime"
            );
        }
    }

    fn in_subquery_program_ops(sql: &str, schema: &[TableSchema]) -> Vec<VdbeOp> {
        let stmt = select_sql(sql);
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, schema, &CodegenContext::default())
            .expect("IN-subquery fixture should compile");
        b.finish()
            .expect("IN-subquery program should finish")
            .ops()
            .to_vec()
    }

    #[test]
    fn complex_in_ordered_top_n_emits_independent_key_before_projection() {
        let schema = test_schema_with_subquery_source();
        let ops = in_subquery_program_ops(
            "SELECT a IN (SELECT out() FROM s ORDER BY key() LIMIT 1) FROM t",
            &schema,
        );
        let function_index = |name: &str| {
            ops.iter()
                .position(|op| {
                    op.opcode == Opcode::PureFunc
                        && matches!(&op.p4, P4::FuncName(actual) if actual == name)
                })
                .unwrap_or_else(|| {
                    assert!(test_failure(), "expected {name} function opcode");
                    usize::MAX
                })
        };

        assert!(
            function_index("KEY") < function_index("OUT"),
            "a non-DISTINCT bounded sorter must compute an independent ORDER key \
             before the projected RHS value"
        );
        let preflight_index = ops
            .iter()
            .position(|op| {
                op.opcode == Opcode::SorterCompare && op.p5 == SORTER_COMPARE_TOP_N_PREFLIGHT
            })
            .expect("bounded complex-IN sorter should preflight each candidate key");
        assert!(
            function_index("KEY") < preflight_index && preflight_index < function_index("OUT"),
            "a rejected candidate must branch around its projected RHS value"
        );
        let sorter_open = ops
            .iter()
            .find(|op| op.opcode == Opcode::SorterOpen)
            .expect("ordered RHS should open a sorter");
        assert_eq!(
            sorter_open.p5, SORTER_OPEN_TOP_N_REGISTER,
            "complex-IN sorter should read its top-N bound from the LIMIT register"
        );
        assert!(
            ops.iter().any(|op| {
                op.opcode == Opcode::Integer && op.p1 == 1 && op.p2 == sorter_open.p3
            }),
            "constant LIMIT 1 should populate the complex-IN top-N bound register"
        );
    }

    #[test]
    fn complex_in_exact_output_order_reference_reuses_volatile_projection() {
        let schema = test_schema_with_subquery_source();
        for sql in [
            "SELECT a IN (SELECT out() FROM s ORDER BY out() LIMIT 1) FROM t",
            "SELECT a IN (SELECT out() AS x FROM s ORDER BY x COLLATE BINARY LIMIT 1) FROM t",
            "SELECT a IN (SELECT out() FROM s ORDER BY +1 LIMIT 1) FROM t",
            "SELECT a IN (SELECT out(b) FROM s ORDER BY out(s.b) LIMIT 1) FROM t",
            "SELECT a IN (SELECT out(b) FROM s ORDER BY out(B) LIMIT 1) FROM t",
            "SELECT a IN (SELECT out(b) FROM s AS x ORDER BY out(x.b) LIMIT 1) FROM t",
            "SELECT a IN (SELECT out(rowid) FROM s ORDER BY out(_rowid_) LIMIT 1) FROM t",
            "SELECT a IN (SELECT out(rowid) FROM s ORDER BY out(oid) LIMIT 1) FROM t",
        ] {
            let ops = in_subquery_program_ops(sql, &schema);
            let output_calls = ops
                .iter()
                .filter(|op| {
                    op.opcode == Opcode::PureFunc
                        && matches!(&op.p4, P4::FuncName(name) if name == "OUT")
                })
                .count();
            assert_eq!(
                output_calls, 1,
                "exact output alias/ordinal/expression should share one emitted value: `{sql}`"
            );
        }

        let collated_expr_ops = in_subquery_program_ops(
            "SELECT a IN \
             (SELECT out() FROM s ORDER BY out() COLLATE BINARY LIMIT 1) FROM t",
            &schema,
        );
        let output_calls = collated_expr_ops
            .iter()
            .filter(|op| {
                op.opcode == Opcode::PureFunc
                    && matches!(&op.p4, P4::FuncName(name) if name == "OUT")
            })
            .count();
        assert_eq!(
            output_calls, 2,
            "a separately written COLLATE-wrapped output expression is not an alias reference"
        );
    }

    #[test]
    fn complex_in_exact_output_reuses_integer_primary_key_for_rowid_order_reference() {
        let mut schema = test_schema_with_subquery_source();
        schema[1].columns = vec![ColumnInfo::basic("id", 'D', true)];
        let sql = "SELECT a IN (SELECT out(id) FROM s ORDER BY out(rowid) LIMIT 1) FROM t";
        let ops = in_subquery_program_ops(sql, &schema);
        let output_calls = ops
            .iter()
            .filter(|op| {
                op.opcode == Opcode::PureFunc
                    && matches!(&op.p4, P4::FuncName(name) if name == "OUT")
            })
            .count();
        assert_eq!(
            output_calls, 1,
            "an INTEGER PRIMARY KEY alias and rowid name the same projected value"
        );
    }

    #[test]
    fn scalar_subquery_affinity_reaches_comparison_codegen_in_both_operand_orders() {
        let schema = scalar_affinity_test_schema();
        let compile = |sql: &str| {
            let stmt = select_sql(sql);
            let mut builder = ProgramBuilder::new();
            codegen_select(&mut builder, &stmt, &schema, &CodegenContext::default())
                .expect("scalar-subquery comparison should compile");
            builder
                .finish()
                .expect("scalar-subquery comparison program should finish")
                .ops()
                .to_vec()
        };

        for (scalar, other, expected_p5) in [
            ("(SELECT n FROM s)", "'5'", u16::from(b'C')),
            ("(SELECT txt FROM s)", "5", u16::from(b'B')),
            ("(SELECT raw FROM s)", "5", 0),
        ] {
            for sql in [
                format!("SELECT {scalar} = {other} FROM t"),
                format!("SELECT {other} = {scalar} FROM t"),
            ] {
                let ops = compile(&sql);
                let comparisons = ops
                    .iter()
                    .filter(|op| op.opcode == Opcode::Eq)
                    .collect::<Vec<_>>();
                assert_eq!(
                    comparisons.len(),
                    1,
                    "fixture must emit one equality comparison: `{sql}`",
                );
                assert_eq!(comparisons[0].p5, expected_p5, "wrong P5 for `{sql}`");
                assert_eq!(
                    comparisons[0].p4,
                    P4::None,
                    "a scalar result's inner declared collation must not cross the subquery boundary: `{sql}`",
                );
            }
        }

        let case_ops = compile("SELECT CASE (SELECT n FROM s) WHEN '5' THEN 1 ELSE 0 END FROM t");
        let case_comparison = case_ops
            .iter()
            .find(|op| op.opcode == Opcode::Ne)
            .expect("simple CASE should emit a comparison");
        assert_eq!(case_comparison.p5, u16::from(b'C'));

        let between_ops = compile("SELECT (SELECT txt FROM s) BETWEEN 1 AND 2 FROM t");
        let between_comparisons = between_ops
            .iter()
            .filter(|op| matches!(op.opcode, Opcode::Lt | Opcode::Gt))
            .collect::<Vec<_>>();
        assert_eq!(between_comparisons.len(), 2);
        assert!(
            between_comparisons
                .iter()
                .all(|op| { op.p5 == u16::from(b'B') && matches!(op.p4, P4::None) })
        );
    }

    #[test]
    fn fallback_and_join_scalar_subquery_affinity_use_the_local_result_scope() {
        let schema = scalar_affinity_test_schema();
        let inner = ScanCtx {
            cursor: 3,
            table: &schema[0],
            table_alias: Some("t"),
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };
        let join_tables = [(&schema[0], Some("t")), (&schema[1], Some("outer_s"))];

        for (scalar, other, expected_p5) in [
            ("(SELECT n FROM s)", "'5'", u16::from(b'C')),
            ("(SELECT txt FROM s)", "5", u16::from(b'B')),
            ("(SELECT raw FROM s)", "5", 0),
        ] {
            for sql in [format!("{scalar} = {other}"), format!("{other} = {scalar}")] {
                let expr = expr_sql(&sql);
                let Expr::BinaryOp { left, right, .. } = &expr else {
                    unreachable!("expected comparison expression");
                };

                let mut builder = ProgramBuilder::new();
                let result = builder.alloc_reg();
                emit_expr_with_fallback(&mut builder, &expr, result, &inner, None);
                builder.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
                let program = builder
                    .finish()
                    .expect("fallback scalar-subquery program should finish");
                let comparison = program
                    .ops()
                    .iter()
                    .find(|op| op.opcode == Opcode::Eq)
                    .expect("fallback expression should emit equality");
                assert_eq!(comparison.p5, expected_p5, "wrong fallback P5 for `{sql}`");
                assert_eq!(
                    join_comparison_affinity_p5(left, right, &join_tables),
                    expected_p5,
                    "wrong join-codegen P5 for `{sql}`",
                );
            }
        }
    }

    #[test]
    fn comparison_metadata_uses_column_info_without_declared_type_text() {
        let mut column = ColumnInfo::basic("value", 'B', false);
        column.collation = Some("NOCASE".to_owned());
        let schema = vec![TableSchema {
            name: "materialized_view".to_owned(),
            root_page: 2,
            columns: vec![column],
            indexes: Vec::new(),
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }];
        let scan = ScanCtx {
            cursor: 3,
            table: &schema[0],
            table_alias: None,
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };
        let literal = expr_sql("1");
        let column = expr_sql("value");
        let resolved = resolve_column_ref(&column, scan.table, scan.table_alias);

        assert_eq!(expr_affinity(&column, Some(&scan)), b'B');
        assert_eq!(
            resolved_expr_affinity(&column, resolved.as_ref(), &scan),
            b'B'
        );
        assert_eq!(join_expr_affinity(&column, &[(&schema[0], None)]), b'B');

        let comparison = ResolvedComparisonInfo::new(&literal, &column, &scan);
        assert_eq!(comparison.cmp_p5, 0x80 | u16::from(b'B'));
        assert!(matches!(
            comparison.collation_p4,
            P4::Collation(ref name) if name == "NOCASE"
        ));
    }

    #[test]
    fn scalar_subquery_affinity_uses_outer_and_parser_root_metadata() {
        let schema = scalar_affinity_test_schema();
        let outer = ScanCtx {
            cursor: 3,
            table: &schema[0],
            table_alias: Some("t"),
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };
        let inner = ScanCtx {
            cursor: 4,
            table: &schema[1],
            table_alias: Some("s"),
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };
        let join_tables = [(&schema[0], Some("t")), (&schema[1], Some("s"))];

        let compact_schema = test_schema_with_subquery_source();
        let compact_outer = ScanCtx {
            cursor: 5,
            table: &compact_schema[0],
            table_alias: Some("t"),
            schema: Some(&compact_schema),
            register_base: None,
            secondaries: &[],
        };
        assert_eq!(
            expr_affinity(&expr_sql("(SELECT b FROM s)"), Some(&compact_outer)),
            b'D',
            "scalar result affinity must use ColumnInfo.affinity when declared type text is absent",
        );

        let correlated_outer = expr_sql("(SELECT t.outer_n)");
        assert_eq!(expr_affinity(&correlated_outer, Some(&outer)), b'C');
        assert_eq!(
            fallback_expr_affinity(&correlated_outer, &inner, Some(&outer)),
            b'C',
        );
        assert_eq!(join_expr_affinity(&correlated_outer, &join_tables), b'C');

        let mut bound_select = select_sql("SELECT 0");
        let SelectCore::Select { columns, .. } = &mut bound_select.body.select else {
            unreachable!("expected SELECT core");
        };
        columns[0] = ResultColumn::Expr {
            expr: Expr::BoundOuterValue {
                value: SqliteValue::Text("5".into()),
                collation: BoundCollation::Named("NOCASE".to_owned()),
                affinity: Some(TypeAffinity::Numeric),
                span: Span::ZERO,
            },
            alias: None,
        };
        let bound_scalar = Expr::Subquery(Box::new(bound_select), Span::ZERO);
        assert_eq!(expr_affinity(&bound_scalar, None), b'C');
        assert_eq!(
            fallback_expr_affinity(&bound_scalar, &inner, Some(&outer)),
            b'C'
        );
        assert_eq!(join_expr_affinity(&bound_scalar, &join_tables), b'C');

        let deferred_values = expr_sql("(VALUES (CAST(1 AS INTEGER)), (CAST('2' AS TEXT)))");
        assert_eq!(
            expr_affinity(&deferred_values, None),
            b'A',
            "an unresolved VALUES representation must not guess a donor affinity",
        );
        assert_eq!(
            fallback_expr_affinity(&deferred_values, &inner, Some(&outer)),
            b'A'
        );
        assert_eq!(join_expr_affinity(&deferred_values, &join_tables), b'A');

        let values_agree = scalar_values_with_frozen_donor(
            "(VALUES (CAST(1 AS INTEGER)), (CAST(2 AS INTEGER)))",
            0,
        );
        let values_integer_then_text = scalar_values_with_frozen_donor(
            "(VALUES (CAST(1 AS INTEGER)), (CAST('2' AS TEXT)))",
            0,
        );
        let values_text_then_integer = scalar_values_with_frozen_donor(
            "(VALUES (CAST('2' AS TEXT)), (CAST(1 AS INTEGER)))",
            0,
        );
        assert_eq!(expr_affinity(&values_agree, None), b'D');
        assert_eq!(expr_affinity(&values_integer_then_text, None), b'D');
        assert_eq!(expr_affinity(&values_text_then_integer, None), b'B');
        assert_eq!(
            fallback_expr_affinity(&values_integer_then_text, &inner, Some(&outer)),
            b'D'
        );
        assert_eq!(
            join_expr_affinity(&values_integer_then_text, &join_tables),
            b'D'
        );

        let values_integer_then_text_second_donor = scalar_values_with_frozen_donor(
            "(VALUES (CAST(1 AS INTEGER)), (CAST('2' AS TEXT)))",
            1,
        );
        let values_text_then_integer_second_donor = scalar_values_with_frozen_donor(
            "(VALUES (CAST('2' AS TEXT)), (CAST(1 AS INTEGER)))",
            1,
        );
        assert_eq!(
            expr_affinity(&values_integer_then_text_second_donor, None),
            b'B'
        );
        assert_eq!(
            expr_affinity(&values_text_then_integer_second_donor, None),
            b'D'
        );

        let compound_agrees =
            expr_sql("(SELECT CAST(1 AS INTEGER) UNION ALL SELECT CAST(2 AS INTEGER))");
        let compound_integer_then_text =
            expr_sql("(SELECT CAST(1 AS INTEGER) UNION ALL SELECT CAST('2' AS TEXT))");
        let compound_text_then_integer =
            expr_sql("(SELECT CAST('2' AS TEXT) UNION ALL SELECT CAST(1 AS INTEGER))");
        assert_eq!(expr_affinity(&compound_agrees, None), b'D');
        assert_eq!(expr_affinity(&compound_integer_then_text, None), b'B');
        assert_eq!(expr_affinity(&compound_text_then_integer, None), b'D');

        let with_base_table = expr_sql("(WITH c(x) AS (VALUES (0)) SELECT n FROM s)");
        assert_eq!(expr_affinity(&with_base_table, Some(&outer)), b'C');

        let with_integer_then_text = expr_sql(
            "(WITH c(x) AS (VALUES (0)) \
             SELECT CAST(1 AS INTEGER) UNION ALL SELECT CAST('2' AS TEXT))",
        );
        let with_text_then_integer = expr_sql(
            "(WITH c(x) AS (VALUES (0)) \
             SELECT CAST('2' AS TEXT) UNION ALL SELECT CAST(1 AS INTEGER))",
        );
        assert_eq!(expr_affinity(&with_integer_then_text, None), b'B');
        assert_eq!(expr_affinity(&with_text_then_integer, None), b'D');
    }

    #[test]
    fn complex_in_uncorrelated_scalar_lhs_preserves_affinity_and_rhs_first_order() {
        let mut schema = test_schema_with_subquery_source();
        schema[1].columns[0].affinity = 'B';
        schema[1].columns[0].type_name = Some("TEXT".to_owned());
        let mut integer_column = ColumnInfo::basic("x", 'D', false);
        integer_column.type_name = Some("INTEGER".to_owned());
        schema.push(TableSchema {
            name: "scalar_lhs".to_owned(),
            root_page: 4,
            columns: vec![integer_column],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        });

        for sql in [
            "SELECT (SELECT x FROM scalar_lhs) IN \
             (SELECT b FROM s ORDER BY rowid LIMIT 1) FROM t",
            "SELECT (SELECT CAST(1 AS INTEGER)) IN \
             (SELECT b FROM s ORDER BY rowid LIMIT 1) FROM t",
        ] {
            let ops = in_subquery_program_ops(sql, &schema);
            let rhs_open = ops
                .iter()
                .position(|op| {
                    op.opcode == Opcode::OpenRead
                        && matches!(&op.p4, P4::Table(name) if name == "s")
                })
                .expect("complex RHS should open s");
            let scalar_open = ops
                .iter()
                .position(|op| op.opcode == Opcode::OpenRead && op.p2 == schema[2].root_page);
            if sql.contains("FROM scalar_lhs") {
                assert!(
                    scalar_open.is_some_and(|index| rhs_open < index),
                    "the RHS must be materialized before opening the scalar-LHS source"
                );
            } else {
                assert!(
                    scalar_open.is_none(),
                    "a FROM-less scalar LHS should not open a source cursor"
                );
            }
            let opened_cursors = ops
                .iter()
                .filter(|op| {
                    matches!(
                        op.opcode,
                        Opcode::OpenRead | Opcode::OpenAutoindex | Opcode::SorterOpen
                    )
                })
                .map(|op| op.p1)
                .collect::<Vec<_>>();
            assert_eq!(
                opened_cursors
                    .iter()
                    .copied()
                    .collect::<std::collections::HashSet<_>>()
                    .len(),
                opened_cursors.len(),
                "nested scalar and complex-IN sources must use disjoint cursor identifiers"
            );
            assert!(
                ops.iter()
                    .filter(|op| {
                        op.opcode == Opcode::Affinity
                            && matches!(&op.p4, P4::Affinity(affinity) if affinity == "C")
                    })
                    .count()
                    >= 2,
                "INTEGER scalar-result affinity must numerically coerce the TEXT RHS and probe"
            );
            assert!(
                !ops.iter().any(|op| op.opcode == Opcode::Halt && op.p1 != 0),
                "eligible uncorrelated scalar LHS must remain on native complex-IN codegen"
            );
        }
    }

    #[test]
    fn complex_in_uncorrelated_scalar_lhs_applies_affinity_at_runtime() {
        let mut schema = test_schema_with_subquery_source();
        schema[1].columns[0].affinity = 'B';
        schema[1].columns[0].type_name = Some("TEXT".to_owned());
        let mut integer_column = ColumnInfo::basic("x", 'D', false);
        integer_column.type_name = Some("INTEGER".to_owned());
        schema.push(TableSchema {
            name: "scalar_lhs".to_owned(),
            root_page: 4,
            columns: vec![integer_column],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        });

        let mut db = MemDatabase::new();
        db.create_table_at(2, 2);
        db.get_table_mut(2)
            .expect("outer table should exist")
            .insert_row(1, vec![SqliteValue::Integer(0), SqliteValue::Integer(0)]);
        db.create_table_at(3, 1);
        db.get_table_mut(3)
            .expect("RHS table should exist")
            .insert_row(1, vec![SqliteValue::Text("01".into())]);
        db.create_table_at(4, 1);
        db.get_table_mut(4)
            .expect("scalar table should exist")
            .insert_row(1, vec![SqliteValue::Integer(1)]);

        let stmt = select_sql(
            "SELECT (SELECT x FROM scalar_lhs) IN \
             (SELECT b FROM s ORDER BY rowid LIMIT 1) FROM t",
        );
        let rows = execute_codegen_select_with_storage_cursor(&stmt, &schema, db);
        assert_eq!(
            rows,
            vec![vec![SqliteValue::Integer(1)]],
            "INTEGER scalar-result affinity must make text '01' match integer 1"
        );
    }

    #[test]
    fn complex_in_scalar_lhs_does_not_inherit_inner_result_collation() {
        let mut schema = test_schema_with_subquery_source();
        schema[1].columns[0].type_name = Some("TEXT".to_owned());
        let mut nocase_column = ColumnInfo::basic("x", 'B', false);
        nocase_column.type_name = Some("TEXT".to_owned());
        nocase_column.collation = Some("NOCASE".to_owned());
        schema.push(TableSchema {
            name: "scalar_lhs".to_owned(),
            root_page: 4,
            columns: vec![nocase_column],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        });

        for sql in [
            "SELECT (SELECT x FROM scalar_lhs) IN \
             (SELECT b FROM s ORDER BY rowid LIMIT 1) FROM t",
            "SELECT (SELECT x COLLATE NOCASE FROM scalar_lhs) IN \
             (SELECT b FROM s ORDER BY rowid LIMIT 1) FROM t",
        ] {
            let ops = in_subquery_program_ops(sql, &schema);
            let membership = ops
                .iter()
                .find(|op| op.opcode == Opcode::OpenAutoindex)
                .expect("complex IN should open its membership index");
            assert_eq!(
                membership.p4,
                P4::None,
                "a scalar subquery's inner result collation does not cross its SQL boundary: `{sql}`"
            );
        }
    }

    #[test]
    fn complex_in_rejects_correlated_or_function_bearing_scalar_lhs() {
        let mut schema = test_schema_with_subquery_source();
        schema.push(TableSchema {
            name: "scalar_lhs".to_owned(),
            root_page: 4,
            columns: vec![ColumnInfo::basic("x", 'D', false)],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        });

        for sql in [
            "SELECT (SELECT a) IN \
             (SELECT b FROM s ORDER BY rowid LIMIT 1) FROM t",
            "SELECT (SELECT t.a FROM scalar_lhs) IN \
             (SELECT b FROM s ORDER BY rowid LIMIT 1) FROM t",
            "SELECT (SELECT out()) IN \
             (SELECT b FROM s ORDER BY rowid LIMIT 1) FROM t",
        ] {
            let ops = in_subquery_program_ops(sql, &schema);
            assert!(
                !ops.iter().any(|op| op.opcode == Opcode::SorterOpen),
                "a scalar LHS with outer scope or function semantics must not enter native complex-IN lowering: `{sql}`"
            );
            assert!(
                ops.iter()
                    .any(|op| op.opcode == Opcode::Halt && op.p1 == ErrorCode::Internal as i32),
                "direct codegen must fail closed for an ineligible scalar LHS: `{sql}`"
            );
        }
    }

    #[test]
    fn complex_in_distinct_function_output_order_reference_is_stored() {
        let schema = test_schema_with_subquery_source();
        for sql in [
            "SELECT a IN \
             (SELECT DISTINCT out(b) AS x FROM s ORDER BY x LIMIT 1) FROM t",
            "SELECT a IN \
             (SELECT DISTINCT out(b) FROM s ORDER BY 1 LIMIT 1) FROM t",
            "SELECT a IN \
             (SELECT DISTINCT out(b) FROM s ORDER BY out(s.b) LIMIT 1) FROM t",
        ] {
            let ops = in_subquery_program_ops(sql, &schema);
            let output_calls = ops
                .iter()
                .enumerate()
                .filter_map(|(index, op)| {
                    (op.opcode == Opcode::PureFunc
                        && matches!(&op.p4, P4::FuncName(name) if name == "OUT"))
                    .then_some(index)
                })
                .collect::<Vec<_>>();
            assert_eq!(
                output_calls.len(),
                1,
                "exact alias/ordinal/qualified-structural ordered DISTINCT must emit \
                 exactly one projected function evaluation: `{sql}`"
            );

            let distinct_probe = ops
                .iter()
                .position(|op| op.opcode == Opcode::Found)
                .expect("ordered DISTINCT should probe pass-1 membership");
            let source_cursor = ops
                .iter()
                .find(|op| {
                    op.opcode == Opcode::OpenRead
                        && matches!(&op.p4, P4::Table(name) if name == "s")
                })
                .map(|op| op.p1)
                .expect("complex-IN should open source table s");
            let source_close = ops
                .iter()
                .position(|op| op.opcode == Opcode::Close && op.p1 == source_cursor)
                .expect("complex-IN should close source table s");
            assert!(
                output_calls[0] < distinct_probe && distinct_probe < source_close,
                "pass 1 must preserve output-first membership and retain that value \
                 before closing its source cursor: `{sql}`"
            );
            assert!(
                !ops.iter().any(|op| op.opcode == Opcode::SeekRowid),
                "function-bearing ordered DISTINCT must not re-evaluate a representative: `{sql}`"
            );
            assert!(
                ops.iter().any(|op| op.opcode == Opcode::SorterOpen)
                    && !ops
                        .iter()
                        .any(|op| op.opcode == Opcode::Halt && op.p1 == ErrorCode::Internal as i32),
                "supported ordered-DISTINCT projection must stay in native complex-IN lowering: `{sql}`"
            );
        }
    }

    #[test]
    fn table_local_expression_matching_rejects_foreign_qualifiers() {
        let schema = test_schema_with_subquery_source();
        let stored = expr_sql("out(b)");
        let foreign = expr_sql("out(other.b)");
        assert!(
            !expressions_match_table_locally(&foreign, &stored, &schema[1], None),
            "a foreign qualifier must never be stripped into a local expression match"
        );
    }

    #[test]
    fn complex_in_no_order_offset_skips_before_projection() {
        let schema = test_schema_with_subquery_source();
        let ops = in_subquery_program_ops(
            "SELECT a IN (SELECT tick() FROM s LIMIT 1 OFFSET 1) FROM t",
            &schema,
        );
        let offset_skip = ops
            .iter()
            .position(|op| op.opcode == Opcode::IfPos)
            .expect("OFFSET should emit IfPos");
        let projection = ops
            .iter()
            .position(|op| {
                op.opcode == Opcode::PureFunc
                    && matches!(&op.p4, P4::FuncName(name) if name == "TICK")
            })
            .expect("projection should emit tick()");
        assert!(
            offset_skip < projection,
            "non-DISTINCT OFFSET rows must be skipped before evaluating the RHS projection"
        );
    }

    #[test]
    fn complex_in_validates_limit_before_opening_source_table() {
        let schema = test_schema_with_subquery_source();
        let ops = in_subquery_program_ops(
            "SELECT a IN (SELECT b FROM s ORDER BY b LIMIT ?1) FROM t",
            &schema,
        );
        let limit_variable = ops
            .iter()
            .position(|op| op.opcode == Opcode::Variable && op.p1 == 1)
            .expect("dynamic LIMIT should emit Variable ?1");
        let limit_coercion = ops
            .iter()
            .position(|op| op.opcode == Opcode::MustBeInt)
            .expect("dynamic LIMIT should emit MustBeInt");
        let source_open = ops
            .iter()
            .position(|op| {
                op.opcode == Opcode::OpenRead && matches!(&op.p4, P4::Table(name) if name == "s")
            })
            .expect("complex RHS should open source table s");
        assert!(
            limit_variable < limit_coercion && limit_coercion < source_open,
            "LIMIT evaluation/coercion must precede RHS table I/O"
        );
        let sorter_open = ops
            .iter()
            .find(|op| op.opcode == Opcode::SorterOpen)
            .expect("ordered complex-IN RHS should open a sorter");
        assert_eq!(
            sorter_open.p5, SORTER_OPEN_TOP_N_REGISTER,
            "dynamic complex-IN LIMIT should supply a runtime top-N bound"
        );
        assert_eq!(
            sorter_open.p3, ops[limit_variable].p2,
            "without OFFSET, SorterOpen should read the coerced LIMIT register directly"
        );
        assert!(
            ops.iter().any(|op| {
                op.opcode == Opcode::SorterCompare && op.p5 == SORTER_COMPARE_TOP_N_PREFLIGHT
            }),
            "dynamic complex-IN LIMIT should preflight keys before projection"
        );
    }

    #[test]
    fn complex_in_raw_non_numbered_operand_and_limit_fail_closed() {
        let schema = test_schema_with_subquery_source();
        for sql in [
            "SELECT ? IN (SELECT b FROM s ORDER BY b LIMIT ?) FROM t",
            "SELECT :lhs IN (SELECT b FROM s ORDER BY b LIMIT :lim) FROM t",
        ] {
            let ops = in_subquery_program_ops(sql, &schema);
            assert!(
                !ops.iter().any(|op| op.opcode == Opcode::SorterOpen),
                "raw non-numbered parameters must not enter emission-reordered complex IN: `{sql}`"
            );
            assert!(
                ops.iter()
                    .any(|op| { op.opcode == Opcode::Halt && op.p1 == ErrorCode::Internal as i32 }),
                "direct raw codegen must fail closed until slots are canonicalized: `{sql}`"
            );
        }
    }

    #[test]
    fn complex_in_rejects_negative_order_ordinal() {
        let schema = test_schema_with_subquery_source();
        let ops = in_subquery_program_ops(
            "SELECT a IN (SELECT b FROM s ORDER BY -1 LIMIT 1) FROM t",
            &schema,
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::SorterOpen),
            "negative ORDER ordinal must not degrade into a constant sort key"
        );
        assert!(
            ops.iter()
                .any(|op| op.opcode == Opcode::Halt && op.p1 == ErrorCode::Internal as i32),
            "connection routing should intercept the declined out-of-range ordinal"
        );
    }

    #[test]
    fn complex_in_single_star_reads_integer_primary_key_as_rowid() {
        let mut schema = test_schema_with_subquery_source();
        schema[1].columns = vec![ColumnInfo::basic("id", 'D', true)];
        let ops = in_subquery_program_ops(
            "SELECT a IN (SELECT * FROM s ORDER BY +1 LIMIT 1) FROM t",
            &schema,
        );
        let source_cursor = ops
            .iter()
            .find_map(|op| {
                (op.opcode == Opcode::OpenRead && matches!(&op.p4, P4::Table(name) if name == "s"))
                    .then_some(op.p1)
            })
            .expect("complex RHS should open s");
        assert!(
            ops.iter()
                .any(|op| op.opcode == Opcode::Rowid && op.p1 == source_cursor),
            "one-column star over an INTEGER PRIMARY KEY must read the rowid value"
        );

        let probe_source = InProbeSource {
            table: &schema[1],
            table_alias: None,
            where_clause: None,
            value: InProbeValue::FirstColumn,
        };
        let probe_scan = ScanCtx {
            cursor: source_cursor,
            table: &schema[1],
            table_alias: None,
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };
        assert_eq!(
            in_probe_value_affinity(&probe_source, &probe_scan),
            b'D',
            "INTEGER PRIMARY KEY star output must retain INTEGER affinity"
        );
    }

    #[test]
    fn complex_in_exact_alias_collision_uses_output_collation() {
        let mut schema = test_schema_with_subquery_source();
        schema[1].columns = vec![
            ColumnInfo {
                name: "k".to_owned(),
                affinity: 'B',
                is_ipk: false,
                type_name: Some("TEXT".to_owned()),
                notnull: false,
                unique: false,
                default_value: None,
                strict_type: None,
                generated_expr: None,
                generated_stored: None,
                collation: Some("BINARY".to_owned()),
                conflict_action: None,
            },
            ColumnInfo {
                name: "v".to_owned(),
                affinity: 'B',
                is_ipk: false,
                type_name: Some("TEXT".to_owned()),
                notnull: false,
                unique: false,
                default_value: None,
                strict_type: None,
                generated_expr: None,
                generated_stored: None,
                collation: Some("NOCASE".to_owned()),
                conflict_action: None,
            },
        ];
        let ops = in_subquery_program_ops(
            "SELECT a IN (SELECT v AS k FROM s ORDER BY k LIMIT 1) FROM t",
            &schema,
        );
        let sorter_open = ops
            .iter()
            .find(|op| op.opcode == Opcode::SorterOpen)
            .expect("ordered RHS should open sorter");
        let P4::Str(sorter_p4) = &sorter_open.p4 else {
            assert!(
                test_failure(),
                "unexpected sorter metadata: {:?}",
                sorter_open.p4
            );
            return;
        };
        assert_eq!(
            sorter_p4, "+|NOCASE",
            "bare ORDER alias wins a same-named BINARY source column and inherits output NOCASE"
        );
        let membership_open = ops
            .iter()
            .find(|op| op.opcode == Opcode::OpenAutoindex)
            .expect("complex IN should materialize its selected membership set");
        assert_eq!(
            membership_open.p4,
            P4::Collation("NOCASE".to_owned()),
            "the RHS output collation must govern the final membership probe"
        );
    }

    #[test]
    fn complex_in_rewrites_aliases_nested_in_order_expressions() {
        let ops = in_subquery_program_ops(
            "SELECT a IN (SELECT b AS k FROM s ORDER BY k + 0 LIMIT 1) FROM t",
            &test_schema_with_subquery_source(),
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::SorterOpen),
            "nested ORDER alias should stay in native complex-IN lowering"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Add),
            "nested ORDER alias should emit its rewritten arithmetic expression"
        );
        let source_cursor = ops
            .iter()
            .find_map(|op| {
                (op.opcode == Opcode::OpenRead && matches!(&op.p4, P4::Table(name) if name == "s"))
                    .then_some(op.p1)
            })
            .expect("complex RHS should open s");
        let add_index = ops
            .iter()
            .position(|op| op.opcode == Opcode::Add)
            .expect("rewritten ORDER expression should add");
        assert!(
            ops[..add_index]
                .iter()
                .any(|op| op.opcode == Opcode::Column && op.p1 == source_cursor && op.p2 == 0),
            "rewritten ORDER expression should read source column b"
        );
        assert!(
            !ops.iter()
                .any(|op| op.opcode == Opcode::Halt && op.p1 == ErrorCode::Internal as i32),
            "validation must apply the same nested alias rewrite as code generation"
        );
    }

    #[test]
    fn nested_explicit_and_preserved_declared_collations_are_discovered() {
        let nested = expr_sql("('a' COLLATE NOCASE) || ''");
        assert_eq!(extract_collation(&nested), Some("NOCASE"));

        let schema = test_schema_with_nocase_text_column();
        let scan = ScanCtx {
            cursor: 0,
            table: &schema[0],
            table_alias: None,
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };
        for sql in ["+name", "CAST(name AS TEXT)"] {
            let expr = expr_sql(sql);
            assert_eq!(
                effective_collation_ctx(&expr, Some(&scan)),
                Some("NOCASE"),
                "declared collation should survive `{sql}`"
            );
        }
    }

    #[test]
    fn bound_outer_text_value_emits_losslessly_and_retains_only_declared_metadata() {
        let expr = Expr::BoundOuterValue {
            value: SqliteValue::Text("outer value".into()),
            collation: BoundCollation::Named("NOCASE".to_owned()),
            affinity: Some(TypeAffinity::Text),
            span: Span::ZERO,
        };

        assert_eq!(extract_collation(&expr), None);
        assert_eq!(declared_collation_ctx(&expr, None), Some("NOCASE"));
        assert_eq!(expr_affinity(&expr, None), b'B');
        assert!(!expr_contains_non_numbered_placeholder(&expr));
        assert!(!expr_contains_function_call(&expr));
        assert!(!expr_has_window(&expr));
        assert!(!is_aggregate_expr(&expr));
        assert!(validate_explicit_index_expr_shape(&expr, "index key").is_err());

        let binary_no_affinity = Expr::BoundOuterValue {
            value: SqliteValue::Null,
            collation: BoundCollation::Binary,
            affinity: None,
            span: Span::ZERO,
        };
        assert_eq!(
            declared_collation_ctx(&binary_no_affinity, None),
            Some("BINARY"),
        );
        assert_eq!(expr_affinity(&binary_no_affinity, None), b'A');

        let unspecified = Expr::BoundOuterValue {
            value: SqliteValue::Text("outer value".into()),
            collation: BoundCollation::Unspecified,
            affinity: None,
            span: Span::ZERO,
        };
        assert_eq!(declared_collation_ctx(&unspecified, None), None);
        assert_eq!(bound_outer_declared_collation(&unspecified), None);
        assert_eq!(
            comparison_collation_ctx(&unspecified, &expr, None),
            Some("NOCASE".to_owned()),
            "metadata-neutral bound values must not prevent a later operand from donating collation",
        );
        assert_eq!(
            comparison_collation_ctx(&binary_no_affinity, &expr, None),
            Some("BINARY".to_owned()),
            "known BINARY bound columns must stop declared-collation precedence",
        );

        let mut builder = ProgramBuilder::new();
        let output = builder.alloc_reg();
        emit_expr(&mut builder, &expr, output, None);
        let op = builder
            .op_at(0)
            .expect("bound value emission should produce one opcode");
        assert_eq!(op.opcode, Opcode::String8);
        assert_eq!(op.p2, output);
        assert_eq!(op.p4, P4::Str("outer value".to_owned()));
    }

    #[test]
    fn bound_outer_values_are_not_admitted_as_raw_physical_seek_keys() {
        let bound = Expr::BoundOuterValue {
            value: SqliteValue::Text("5".into()),
            collation: BoundCollation::Named("NOCASE".to_owned()),
            affinity: Some(TypeAffinity::Text),
            span: Span::ZERO,
        };

        assert!(!is_simple_constant(&bound));
        assert!(!is_rowid_range_constant(&bound));
        assert!(!is_index_range_constant(&bound));
        assert!(is_simple_constant(&placeholder(1)));
        assert!(is_rowid_range_constant(&placeholder(1)));
        assert!(is_index_range_constant(&placeholder(1)));
        assert!(is_simple_constant(&Expr::Literal(
            Literal::Integer(5),
            Span::ZERO,
        )));

        let schema = test_schema_with_index();
        let table = &schema[0];
        let indexed_eq = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
            op: AstBinaryOp::Eq,
            right: Box::new(bound.clone()),
            span: Span::ZERO,
        };
        assert!(extract_column_eq_target(Some(&indexed_eq), table, None).is_none());
        assert!(
            extract_index_equality_prefix_exprs(&table.indexes[0], table, None, Some(&indexed_eq))
                .is_empty(),
        );

        let indexed_range = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
            op: AstBinaryOp::Gt,
            right: Box::new(bound.clone()),
            span: Span::ZERO,
        };
        assert!(extract_column_range_target(Some(&indexed_range), table, None).is_none());

        let rowid_eq = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
            op: AstBinaryOp::Eq,
            right: Box::new(bound.clone()),
            span: Span::ZERO,
        };
        assert!(extract_rowid_target_expr(Some(&rowid_eq), Some(table), None).is_none());
        let rowid_range = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
            op: AstBinaryOp::Gt,
            right: Box::new(bound.clone()),
            span: Span::ZERO,
        };
        assert!(extract_rowid_range_target(Some(&rowid_range), Some(table), None).is_none());

        let expression_schema = test_schema_with_expression_index();
        let expression_table = &expression_schema[0];
        let expression_eq = Expr::BinaryOp {
            left: Box::new(expr_sql("lower(name)")),
            op: AstBinaryOp::Eq,
            right: Box::new(bound.clone()),
            span: Span::ZERO,
        };
        assert!(
            extract_expression_index_equality_expr(
                Some(&expression_eq),
                &expression_table.indexes[0],
                expression_table,
                None,
            )
            .is_none(),
        );

        let expression_range = Expr::BinaryOp {
            left: Box::new(expr_sql("lower(name)")),
            op: AstBinaryOp::Lt,
            right: Box::new(bound.clone()),
            span: Span::ZERO,
        };
        assert!(
            extract_expression_index_range_target(
                Some(&expression_range),
                &expression_table.indexes[0],
                expression_table,
                None,
            )
            .is_none(),
        );

        let subquery_schema = test_schema_with_subquery_source();
        let inner_table = &subquery_schema[1];
        let correlated_rowid_eq = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::qualified("s", "rowid"), Span::ZERO)),
            op: AstBinaryOp::Eq,
            right: Box::new(bound.clone()),
            span: Span::ZERO,
        };
        assert!(extract_exists_rowid_probe(&correlated_rowid_eq, inner_table, Some("s")).is_none());

        let nested_bound_rowid_eq = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::qualified("s", "rowid"), Span::ZERO)),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::UnaryOp {
                op: fsqlite_ast::UnaryOp::Plus,
                expr: Box::new(bound),
                span: Span::ZERO,
            }),
            span: Span::ZERO,
        };
        assert!(
            extract_exists_rowid_probe(&nested_bound_rowid_eq, inner_table, Some("s")).is_none(),
        );
    }

    #[test]
    fn indexed_count_exists_rowid_probe_requires_numeric_outer_storage() {
        let stmt = agg_count_star_exists_rowid_probe();
        let mut schema = test_schema_with_index_and_subquery_source();
        let SelectCore::Select {
            where_clause: Some(where_clause),
            ..
        } = &stmt.body.select
        else {
            unreachable!("fixture must have a WHERE clause");
        };

        assert!(
            extract_count_indexed_exists_target(Some(where_clause), &schema[0], None, &schema)
                .is_some(),
            "numeric outer index remains on the rowid-probe fast path",
        );

        schema[0].columns[1].affinity = 'B';
        schema[0].columns[1].collation = Some("NOCASE".to_owned());
        assert!(
            extract_count_indexed_exists_target(Some(where_clause), &schema[0], None, &schema)
                .is_none(),
            "TEXT/NOCASE outer storage must not be probed with raw rowid keys",
        );
    }

    #[test]
    fn resolve_in_probe_source_rejects_schema_qualified_table_shorthand() {
        let set = InSet::Table(QualifiedName::qualified("main", "s"));
        let schema = test_schema_with_subquery_source();
        assert!(resolve_in_probe_source(&set, &schema).is_none());
    }

    #[test]
    fn test_codegen_select_where_in_table_supported_without_rewrite() {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
            set: InSet::Table(QualifiedName::bare("s")),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let open_reads = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::OpenRead)
            .count();
        assert_eq!(open_reads, 2, "outer + probe OpenRead expected");
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::Eq | Opcode::Found)),
            "expected IN membership probe"
        );
    }

    // === Test 10: INSERT RETURNING ===
    #[test]
    fn test_codegen_insert_returning() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![ResultColumn::Expr {
                expr: Expr::Column(ColumnRef::bare("rowid"), Span::ZERO),
                alias: None,
            }],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // With RETURNING, there should be a ResultRow after Insert.
        assert!(has_opcodes(
            &prog,
            &[Opcode::Insert, Opcode::ResultRow, Opcode::Close,]
        ));
    }

    #[test]
    fn test_codegen_insert_returning_expression_wrong_qualifier_errors() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![ResultColumn::Expr {
                expr: Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::qualified("u", "a"), Span::ZERO)),
                    op: AstBinaryOp::Add,
                    right: Box::new(Expr::Literal(Literal::Integer(1), Span::ZERO)),
                    span: Span::ZERO,
                },
                alias: None,
            }],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_insert(&mut b, &stmt, &schema, &ctx)
            .expect_err("RETURNING expression should reject wrong qualifier");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "u" && column == "u.a"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_insert_returning_respects_target_alias() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: Some("u".to_owned()),
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![ResultColumn::Expr {
                expr: Expr::Column(ColumnRef::qualified("u", "a"), Span::ZERO),
                alias: None,
            }],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();

        codegen_insert(&mut b, &stmt, &schema, &ctx)
            .expect("INSERT RETURNING should resolve the target alias");
    }

    // === Test 11: SELECT with LIMIT ===
    #[test]
    fn test_codegen_select_with_limit() {
        let stmt = star_select_with_limit("t", 10);
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Should contain Integer (for limit), DecrJumpZero (for countdown).
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Integer,
                Opcode::OpenRead,
                Opcode::Rewind,
                Opcode::Column,
                Opcode::ResultRow,
                Opcode::DecrJumpZero,
                Opcode::Next,
                Opcode::Close,
                Opcode::Halt,
            ]
        ));

        // DecrJumpZero p1 should be the limit register.
        let djz = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::DecrJumpZero)
            .expect("must have DecrJumpZero");
        assert!(djz.p1 >= 1, "limit register must be allocated");
    }

    // === Test 12: SELECT with LIMIT and OFFSET ===
    #[test]
    fn test_codegen_select_with_limit_offset() {
        let stmt = star_select_with_limit_offset("t", 5, 3);
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Should have both IfPos (offset skip) and DecrJumpZero (limit).
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Integer, // limit value
                Opcode::Integer, // offset value
                Opcode::OpenRead,
                Opcode::Rewind,
                Opcode::IfPos, // offset countdown
                Opcode::Column,
                Opcode::ResultRow,
                Opcode::DecrJumpZero, // limit countdown
                Opcode::Next,
                Opcode::Close,
                Opcode::Halt,
            ]
        ));

        // Verify IfPos p3 == 1 (decrement by 1).
        let ifpos = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::IfPos)
            .expect("must have IfPos");
        assert_eq!(ifpos.p3, 1, "IfPos should decrement offset by 1");
    }

    // === Test 13: SELECT without LIMIT has no DecrJumpZero ===
    #[test]
    fn test_codegen_select_no_limit_no_decr() {
        let stmt = star_select("t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Without LIMIT, there should be no DecrJumpZero.
        let djz_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::DecrJumpZero)
            .count();
        assert_eq!(djz_count, 0, "no DecrJumpZero without LIMIT");

        // And no IfPos either.
        let ifpos_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::IfPos)
            .count();
        assert_eq!(ifpos_count, 0, "no IfPos without OFFSET");
    }

    // === Test 14: LIMIT labels properly resolved ===
    #[test]
    fn test_codegen_select_limit_labels_resolved() {
        let stmt = star_select_with_limit_offset("t", 10, 5);
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // All jump targets should be valid addresses.
        for op in prog.ops() {
            if op.opcode.is_jump() {
                assert!(
                    op.p2 >= 0,
                    "unresolved jump at {:?}: p2 = {}",
                    op.opcode,
                    op.p2
                );
                assert!(
                    usize::try_from(op.p2).unwrap() <= prog.len(),
                    "jump target out of range at {:?}: p2 = {} (prog len = {})",
                    op.opcode,
                    op.p2,
                    prog.len()
                );
            }
        }
    }

    // ── ORDER BY test helpers ──

    fn star_select_order_by(table: &str, col: &str, desc: bool) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare(col), Span::ZERO),
                direction: if desc {
                    Some(SortDirection::Desc)
                } else {
                    None
                },
                nulls: None,
            }],
            limit: None,
        }
    }

    fn select_col_order_by(
        table: &str,
        select_col: &str,
        order_col: &str,
        desc: bool,
    ) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::bare(select_col), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare(order_col), Span::ZERO),
                direction: if desc {
                    Some(SortDirection::Desc)
                } else {
                    None
                },
                nulls: None,
            }],
            limit: None,
        }
    }

    fn star_select_order_by_with_limit(table: &str, col: &str, limit: i64) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare(col), Span::ZERO),
                direction: None,
                nulls: None,
            }],
            limit: Some(LimitClause {
                limit: Expr::Literal(Literal::Integer(limit), Span::ZERO),
                offset: None,
            }),
        }
    }

    fn star_select_order_by_expr(table: &str, expr: Expr) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr,
                direction: None,
                nulls: None,
            }],
            limit: None,
        }
    }

    // === Test 15: SELECT with ORDER BY ===
    #[test]
    fn test_codegen_select_order_by() {
        let stmt = star_select_order_by("t", "a", false);
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Two-pass pattern: SorterOpen, OpenRead, scan loop, SorterSort, output loop.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::SorterOpen,
                Opcode::OpenRead,
                Opcode::Rewind,
                Opcode::Column,
                Opcode::MakeRecord,
                Opcode::SorterInsert,
                Opcode::Next,
                Opcode::Close,
                Opcode::SorterSort,
                Opcode::SorterData,
                Opcode::Column,
                Opcode::ResultRow,
                Opcode::SorterNext,
                Opcode::Close,
                Opcode::Halt,
            ]
        ));

        // SorterOpen p2 should be 1 (one sort key column).
        let so = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::SorterOpen)
            .unwrap();
        assert_eq!(so.p2, 1, "SorterOpen should have 1 key column");
    }

    // === Test 16: SELECT ORDER BY DESC ===
    #[test]
    fn test_codegen_select_order_by_desc() {
        let stmt = star_select_order_by("t", "b", true);
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Should have SorterOpen with sort order in P4.
        let so = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::SorterOpen)
            .unwrap();
        assert_eq!(so.p2, 1, "SorterOpen should have 1 key column");
        // P4 should contain the '-' (DESC) sort order.
        assert!(
            matches!(&so.p4, P4::Str(s) if s == "-"),
            "SorterOpen P4 should be '-' for DESC, got {:?}",
            so.p4
        );
    }

    #[test]
    fn test_codegen_select_order_by_uses_index_without_sorter() {
        let stmt = star_select_order_by("t", "b", false);
        let schema = test_schema_with_index();
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // ORDER BY on indexed column should stream via index cursor.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::OpenRead, // table
                Opcode::OpenRead, // index
                Opcode::Rewind,
                Opcode::IdxRowid,
                Opcode::SeekRowid,
                Opcode::ResultRow,
                Opcode::Next,
                Opcode::Halt,
            ]
        ));
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")),
            "expected index cursor open for ORDER BY optimization"
        );

        let sorter_count = prog
            .ops()
            .iter()
            .filter(|op| {
                matches!(
                    op.opcode,
                    Opcode::SorterOpen
                        | Opcode::SorterInsert
                        | Opcode::SorterSort
                        | Opcode::SorterData
                        | Opcode::SorterNext
                )
            })
            .count();
        assert_eq!(
            sorter_count, 0,
            "index-assisted ORDER BY should bypass sorter"
        );
    }

    #[test]
    fn test_codegen_order_by_repeated_equality_prefix_uses_composite_range_seek() {
        let stmt = select_sql(
            "SELECT m.idx, COALESCE(LENGTH(CAST(m.content AS BLOB)), 0) \
             FROM messages AS m \
             WHERE m.conversation_id = ?1 AND m.idx > ?2 \
             ORDER BY m.conversation_id, m.idx \
             LIMIT ?3",
        );
        let schema = test_schema_with_composite_prefix_index();
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| {
                op.opcode == Opcode::OpenRead
                    && matches!(&op.p4, P4::Index(name) if name == "sqlite_autoindex_messages_1")
            }),
            "repeated fixed ORDER BY prefix should retain the composite index: {:?}",
            prog.ops()
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::SeekGE | Opcode::SeekGT)),
            "composite index plan should seek directly to the requested range: {:?}",
            prog.ops()
        );
        assert!(
            !prog.ops().iter().any(|op| {
                matches!(
                    op.opcode,
                    Opcode::SorterOpen
                        | Opcode::SorterInsert
                        | Opcode::SorterSort
                        | Opcode::SorterData
                        | Opcode::SorterNext
                )
            }),
            "repeated equality-constrained ORDER BY prefix must not force a temp sorter: {:?}",
            prog.ops()
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::DecrJumpZero),
            "parameterized LIMIT should stop the streaming index scan"
        );
    }

    #[test]
    fn test_codegen_order_by_repeated_equality_prefix_without_range_uses_bounded_index() {
        let stmt = select_sql(
            "SELECT m.idx FROM messages AS m \
             WHERE m.conversation_id = ?1 \
             ORDER BY m.conversation_id, m.idx \
             LIMIT ?2",
        );
        let schema = test_schema_with_composite_prefix_index();
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "fixed prefix should anchor the ordered index scan: {:?}",
            prog.ops()
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| { matches!(op.opcode, Opcode::Rewind | Opcode::SorterOpen) }),
            "fixed-prefix ORDER BY should neither rewind the full index nor sort: {:?}",
            prog.ops()
        );
    }

    #[test]
    fn test_codegen_order_by_fixed_prefix_direction_does_not_constrain_suffix() {
        let stmt = select_sql(
            "SELECT m.idx FROM messages AS m \
             WHERE m.conversation_id = ?1 \
             ORDER BY m.conversation_id DESC, m.idx ASC",
        );
        let schema = test_schema_with_composite_prefix_index();
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "direction on a fixed value must not reject the ascending suffix"
        );
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::SorterOpen),
            "fixed-prefix direction should be elided before direction matching"
        );
    }

    #[test]
    fn test_codegen_order_by_multiple_repeated_equality_prefixes_uses_index() {
        let stmt = select_sql(
            "SELECT e.sequence FROM events AS e \
             WHERE e.tenant_id = ?1 AND e.stream_id = ?2 \
             ORDER BY e.tenant_id, e.stream_id, e.sequence \
             LIMIT ?3",
        );
        let schema = test_schema_with_three_column_composite_index();
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let prefix_boundary = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::IdxGT)
            .expect("two-column equality prefix should bound the index walk");
        assert_eq!(prefix_boundary.p5, 2);
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::SorterOpen),
            "both fixed ORDER BY terms should be removed before matching sequence"
        );
    }

    #[test]
    fn test_codegen_order_by_repeated_prefix_desc_range_uses_reverse_seek() {
        let stmt = select_sql(
            "SELECT m.idx FROM messages AS m \
             WHERE m.conversation_id = ?1 AND m.idx < ?2 \
             ORDER BY m.conversation_id DESC, m.idx DESC \
             LIMIT ?3",
        );
        let schema = test_schema_with_composite_prefix_index();
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::SeekLE | Opcode::SeekLT)),
            "DESC suffix should use the dedicated reverse composite seek: {:?}",
            prog.ops()
        );
        assert!(prog.ops().iter().any(|op| op.opcode == Opcode::Prev));
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::SorterOpen),
            "fixed DESC prefix should not force a sorter"
        );
    }

    #[test]
    fn test_codegen_order_by_prefix_elision_requires_matching_collation() {
        let compatible = select_sql(
            "SELECT sequence FROM collated_events \
             WHERE tenant = ?1 \
             ORDER BY tenant, sequence",
        );
        let incompatible = select_sql(
            "SELECT sequence FROM collated_events \
             WHERE tenant = ?1 \
             ORDER BY tenant COLLATE BINARY, sequence",
        );
        let schema = test_schema_with_collated_composite_prefix_index();
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };

        let mut compatible_builder = ProgramBuilder::new();
        codegen_select(&mut compatible_builder, &compatible, &schema, &ctx).unwrap();
        let compatible_program = compatible_builder.finish().unwrap();
        assert!(
            !compatible_program
                .ops()
                .iter()
                .any(|op| op.opcode == Opcode::SorterOpen),
            "matching NOCASE semantics should permit prefix elision"
        );

        let mut incompatible_builder = ProgramBuilder::new();
        codegen_select(&mut incompatible_builder, &incompatible, &schema, &ctx).unwrap();
        let incompatible_program = incompatible_builder.finish().unwrap();
        assert!(
            incompatible_program
                .ops()
                .iter()
                .any(|op| op.opcode == Opcode::SorterOpen),
            "BINARY ORDER BY must not be treated as constant under NOCASE equality"
        );
    }

    #[test]
    fn test_resolve_order_by_prefix_does_not_borrow_equality_from_other_scope() {
        let stmt = select_sql(
            "SELECT m.idx FROM messages AS m \
             WHERE outer_scope.conversation_id = ?1 \
             ORDER BY m.idx",
        );
        let SelectCore::Select {
            columns,
            where_clause,
            ..
        } = &stmt.body.select
        else {
            unreachable!("test query should parse as a SELECT core");
        };
        let schema = test_schema_with_composite_prefix_index();

        assert!(
            resolve_order_by_index_plan(
                &schema[0],
                Some("m"),
                columns,
                where_clause.as_deref(),
                &stmt.order_by,
                Distinctness::All,
            )
            .is_none(),
            "a qualified equality from another scope must not pin this index prefix"
        );
    }

    #[test]
    fn test_codegen_select_order_by_desc_uses_index_reverse_scan_without_sorter() {
        let stmt = star_select_order_by("t", "b", true);
        let schema = test_schema_with_index();
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(has_opcodes(
            &prog,
            &[
                Opcode::OpenRead, // table
                Opcode::OpenRead, // index
                Opcode::Last,
                Opcode::IdxRowid,
                Opcode::SeekRowid,
                Opcode::ResultRow,
                Opcode::Prev,
                Opcode::Halt,
            ]
        ));
        assert!(
            !prog.ops().iter().any(|op| {
                matches!(
                    op.opcode,
                    Opcode::SorterOpen
                        | Opcode::SorterInsert
                        | Opcode::SorterSort
                        | Opcode::SorterData
                        | Opcode::SorterNext
                )
            }),
            "descending index-assisted ORDER BY should bypass sorter"
        );
    }

    #[test]
    fn test_resolve_sort_key_prefers_result_alias_named_rowid_over_visible_column() {
        let order_by_expr = Expr::Column(ColumnRef::bare("rowid"), Span::ZERO);
        let columns = vec![ResultColumn::Expr {
            expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
            alias: Some("rowid".to_owned()),
        }];
        let schema = schema_with_visible_rowid_column_and_a_indexes();

        assert!(matches!(
            resolve_sort_key(&order_by_expr, &schema[0], None, &columns),
            SortKeySource::Column(0)
        ));
    }

    #[test]
    fn test_codegen_select_order_by_alias_named_rowid_uses_sorter_not_hidden_rowid_scan() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                        alias: Some("rowid".to_owned()),
                    }],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare("rowid"), Span::ZERO),
                direction: None,
                nulls: None,
            }],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SorterOpen),
            "ORDER BY alias named rowid should sort by the output expression, not stream hidden rowid order"
        );
    }

    #[test]
    fn test_codegen_select_order_by_alias_named_rowid_prefers_alias_index() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                        alias: Some("rowid".to_owned()),
                    }],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare("rowid"), Span::ZERO),
                direction: None,
                nulls: None,
            }],
            limit: None,
        };
        let schema = schema_with_visible_rowid_column_and_a_indexes();
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_a")),
            "ORDER BY alias should use the aliased expression's index"
        );
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_rowid")),
            "visible rowid column index must not override SELECT-list alias precedence"
        );
        assert!(
            !prog.ops().iter().any(|op| {
                matches!(
                    op.opcode,
                    Opcode::SorterOpen
                        | Opcode::SorterInsert
                        | Opcode::SorterSort
                        | Opcode::SorterData
                        | Opcode::SorterNext
                )
            }),
            "aliased-column index ORDER BY should bypass the sorter"
        );
    }

    #[test]
    fn test_codegen_select_order_by_wrong_qualifier_errors() {
        let mut stmt = simple_select(&["a"], "t", None);
        stmt.order_by = vec![OrderingTerm {
            expr: Expr::Column(ColumnRef::qualified("u", "b"), Span::ZERO),
            direction: None,
            nulls: None,
        }];
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect_err("mismatched ORDER BY qualifier should be a semantic error");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "u" && column == "u.b"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_select_order_by_alias_hides_base_table_qualifier() {
        let mut stmt = simple_select(&["a"], "t", None);
        if let SelectCore::Select { from, .. } = &mut stmt.body.select {
            *from = Some(from_table_as("t", "x"));
        }
        stmt.order_by = vec![OrderingTerm {
            expr: Expr::Column(ColumnRef::qualified("t", "b"), Span::ZERO),
            direction: None,
            nulls: None,
        }];
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect_err("base-table qualifier should not resolve after FROM aliasing");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "t" && column == "t.b"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_select_covering_order_by_skips_table_lookup() {
        let stmt = select_col_order_by("t", "b", "b", false);
        let schema = test_schema_with_index();
        let ctx = CodegenContext {
            index_ordered_scan_reliable: true,
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let table_open_count = prog
            .ops()
            .iter()
            .filter(|op| {
                op.opcode == Opcode::OpenRead && matches!(&op.p4, P4::Table(name) if name == "t")
            })
            .count();
        assert_eq!(
            table_open_count, 0,
            "covering ORDER BY path should not open table cursor"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::OpenRead
                && matches!(&op.p4, P4::Index(name) if name == "idx_t_b")),
            "covering ORDER BY path should open index cursor"
        );
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::SeekRowid),
            "covering ORDER BY path should not perform table rowid lookups"
        );
        assert!(
            !prog.ops().iter().any(|op| {
                matches!(
                    op.opcode,
                    Opcode::SorterOpen
                        | Opcode::SorterInsert
                        | Opcode::SorterSort
                        | Opcode::SorterData
                        | Opcode::SorterNext
                )
            }),
            "covering ORDER BY path should bypass sorter"
        );
    }

    // === Test 17: SELECT ORDER BY + LIMIT ===
    #[test]
    fn test_codegen_select_order_by_with_limit() {
        let stmt = star_select_order_by_with_limit("t", "a", 5);
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Should have SorterSort + DecrJumpZero (LIMIT on sorted output).
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::SorterOpen,
                Opcode::SorterSort,
                Opcode::SorterData,
                Opcode::ResultRow,
                Opcode::DecrJumpZero,
                Opcode::SorterNext,
            ]
        ));

        // LIMIT is evaluated before opening or scanning the source table.
        let integers: Vec<_> = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Integer)
            .collect();
        assert!(
            integers.iter().any(|op| op.p1 == 5),
            "should have Integer with limit value 5"
        );

        let sorter_open = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::SorterOpen)
            .expect("ORDER BY + LIMIT should open a sorter");
        assert_eq!(
            sorter_open.p5, SORTER_OPEN_TOP_N_REGISTER,
            "simple ORDER BY + LIMIT should read its top-N bound from a register"
        );
        assert!(
            integers
                .iter()
                .any(|op| op.p1 == 5 && op.p2 == sorter_open.p3),
            "SorterOpen.p3 should name the register containing LIMIT 5"
        );
        let limit_index = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::Integer && op.p1 == 5)
            .expect("constant LIMIT should be emitted");
        let source_open_index = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::OpenRead)
            .expect("ordered SELECT should open its source");
        assert!(
            limit_index < source_open_index,
            "LIMIT evaluation must precede source-table I/O"
        );
    }

    #[test]
    fn test_codegen_ordered_top_n_preflights_before_independent_projection() {
        let stmt = select_sql("SELECT out(b) FROM t ORDER BY key(a) LIMIT ?1 OFFSET ?2");
        let schema = test_schema();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        let function_index = |name: &str| {
            ops.iter()
                .position(|op| {
                    op.opcode == Opcode::PureFunc
                        && matches!(&op.p4, P4::FuncName(actual) if actual == name)
                })
                .unwrap_or_else(|| {
                    assert!(test_failure(), "expected {name} function opcode");
                    usize::MAX
                })
        };
        let preflight_index = ops
            .iter()
            .position(|op| {
                op.opcode == Opcode::SorterCompare && op.p5 == SORTER_COMPARE_TOP_N_PREFLIGHT
            })
            .expect("dynamic top-N should emit candidate preflight");
        assert!(
            function_index("KEY") < preflight_index && preflight_index < function_index("OUT"),
            "candidate admission must occur after the ORDER key and before an independent projection"
        );

        let sorter_open = ops
            .iter()
            .find(|op| op.opcode == Opcode::SorterOpen)
            .expect("ordered SELECT should open a sorter");
        assert_eq!(sorter_open.p5, SORTER_OPEN_TOP_N_REGISTER);
        assert!(
            ops.iter()
                .any(|op| { op.opcode == Opcode::OffsetLimit && op.p3 == sorter_open.p3 }),
            "runtime LIMIT+OFFSET should supply the sorter bound"
        );
        let sorter_open_index = ops
            .iter()
            .position(|op| op.opcode == Opcode::SorterOpen)
            .expect("ordered SELECT should open a sorter");
        let second_must_be_int = ops
            .iter()
            .enumerate()
            .filter(|(_, op)| op.opcode == Opcode::MustBeInt)
            .nth(1)
            .map(|(index, _)| index)
            .expect("LIMIT and OFFSET should both be coerced");
        assert!(
            second_must_be_int < sorter_open_index,
            "LIMIT/OFFSET coercion must finish before sorter/source setup"
        );
    }

    #[test]
    fn test_codegen_ordered_raw_non_numbered_parameters_fail_closed() {
        let schema = test_schema();
        for sql in [
            "SELECT ? AS x FROM t ORDER BY x LIMIT ?",
            "SELECT :shared AS x FROM t ORDER BY x LIMIT :shared",
            "SELECT a FROM t WHERE a = ? ORDER BY a LIMIT ?",
            "SELECT a FROM t ORDER BY (? + a) LIMIT ?",
        ] {
            let stmt = select_sql(sql);
            let mut b = ProgramBuilder::new();
            let error = codegen_select(&mut b, &stmt, &schema, &CodegenContext::default())
                .expect_err("emission-reordered raw parameters should fail closed");
            assert!(
                matches!(
                    error,
                    CodegenError::Unsupported(ref message)
                        if message.contains("canonical numbered bind parameters")
                ),
                "unexpected raw ordered-parameter error for `{sql}`: {error:?}"
            );
        }

        let stmt = select_sql("SELECT ?1 AS x FROM t ORDER BY x LIMIT ?2 OFFSET ?3");
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default())
            .expect("canonical ?NNN slots remain stable despite LIMIT-first emission");
        let program = b.finish().unwrap();
        let variable_slots = program
            .ops()
            .iter()
            .filter_map(|op| (op.opcode == Opcode::Variable).then_some(op.p1))
            .collect::<Vec<_>>();
        assert_eq!(
            variable_slots,
            vec![2, 3, 1],
            "LIMIT/OFFSET may emit before projection, but explicit bind slots must remain textual"
        );
    }

    #[test]
    fn test_codegen_ordered_distinct_top_n_membership_precedes_admission() {
        let assert_program = |ops: &[VdbeOp], label: &str| {
            let Some(sorter_open) = ops.iter().find(|op| op.opcode == Opcode::SorterOpen) else {
                assert!(
                    test_failure(),
                    "[{label}] ordered DISTINCT should open a sorter"
                );
                return;
            };
            assert_eq!(
                sorter_open.p5, SORTER_OPEN_TOP_N_REGISTER,
                "[{label}] ordered DISTINCT should retain only LIMIT+OFFSET representatives"
            );

            let Some(preflight_index) = ops.iter().position(|op| {
                op.opcode == Opcode::SorterCompare && op.p5 == SORTER_COMPARE_TOP_N_PREFLIGHT
            }) else {
                assert!(
                    test_failure(),
                    "[{label}] ordered DISTINCT should preflight admission"
                );
                return;
            };
            let Some(found_index) = ops.iter().position(|op| op.opcode == Opcode::Found) else {
                assert!(test_failure(), "[{label}] DISTINCT should probe membership");
                return;
            };
            let Some(distinct_insert_index) =
                ops.iter().position(|op| op.opcode == Opcode::IdxInsert)
            else {
                assert!(
                    test_failure(),
                    "[{label}] DISTINCT should record first membership"
                );
                return;
            };
            assert!(
                found_index < distinct_insert_index && distinct_insert_index < preflight_index,
                "[{label}] every first DISTINCT representative must enter membership before \
                 bounded-sorter admission; rejected representatives must still suppress later duplicates"
            );

            let output_calls = ops
                .iter()
                .enumerate()
                .filter_map(|(index, op)| {
                    (op.opcode == Opcode::PureFunc
                        && matches!(&op.p4, P4::FuncName(name) if name == "OUT"))
                    .then_some(index)
                })
                .collect::<Vec<_>>();
            assert_eq!(
                output_calls.len(),
                1,
                "[{label}] function-bearing DISTINCT output should be evaluated once per source row"
            );
            assert!(
                output_calls[0] < found_index,
                "[{label}] pass-1 output must be evaluated before DISTINCT membership"
            );

            let Some(offset_index) = ops.iter().position(|op| op.opcode == Opcode::IfPos) else {
                assert!(
                    test_failure(),
                    "[{label}] OFFSET should skip sorted representatives"
                );
                return;
            };
            let Some(sorter_data_index) = ops.iter().position(|op| op.opcode == Opcode::SorterData)
            else {
                assert!(
                    test_failure(),
                    "[{label}] pass 2 should read retained sorter rows"
                );
                return;
            };
            assert!(
                output_calls[0] < offset_index && offset_index < sorter_data_index,
                "[{label}] OFFSET must skip representatives before reading stored output"
            );
            assert!(
                !ops.iter().any(|op| op.opcode == Opcode::SeekRowid),
                "[{label}] stored function output must not seek and reproject a source row"
            );
        };

        let schema = test_schema();
        let stmt = select_sql("SELECT DISTINCT out(b) AS x FROM t ORDER BY x LIMIT 1 OFFSET 1");
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
        let program = b.finish().unwrap();
        assert_program(program.ops(), "top-level");

        let complex_ops = in_subquery_program_ops(
            "SELECT a IN \
             (SELECT DISTINCT out(b) AS x FROM s ORDER BY x LIMIT 1 OFFSET 1) FROM t",
            &test_schema_with_subquery_source(),
        );
        assert_program(&complex_ops, "complex-in");
    }

    #[test]
    fn test_codegen_ordered_exact_output_reference_is_evaluated_once() {
        let schema = test_schema();
        for sql in [
            "SELECT out(b) AS x FROM t ORDER BY x LIMIT 1",
            "SELECT out(b) AS x FROM t ORDER BY x COLLATE BINARY LIMIT 1",
            "SELECT out(b) FROM t ORDER BY 1 LIMIT 1",
            "SELECT out(b) FROM t ORDER BY out(t.b) LIMIT 1",
        ] {
            let stmt = select_sql(sql);
            let mut b = ProgramBuilder::new();
            codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
            let prog = b.finish().unwrap();
            let output_calls = prog
                .ops()
                .iter()
                .filter(|op| {
                    op.opcode == Opcode::PureFunc
                        && matches!(&op.p4, P4::FuncName(name) if name == "OUT")
                })
                .count();
            assert_eq!(
                output_calls, 1,
                "an exact output alias/ordinal/expression should share one emitted value: `{sql}`"
            );
        }

        let stmt = select_sql("SELECT out(b) FROM t ORDER BY out(b) COLLATE BINARY LIMIT 1");
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
        let prog = b.finish().unwrap();
        let output_calls = prog
            .ops()
            .iter()
            .filter(|op| {
                op.opcode == Opcode::PureFunc
                    && matches!(&op.p4, P4::FuncName(name) if name == "OUT")
            })
            .count();
        assert_eq!(
            output_calls, 2,
            "a separately written COLLATE-wrapped expression remains a distinct evaluation"
        );
    }

    #[test]
    fn test_codegen_ordered_star_ordinal_inherits_output_collation() {
        let mut schema = test_schema();
        schema[0].columns[0].collation = Some("NOCASE".to_owned());
        let stmt = select_sql("SELECT * FROM t ORDER BY 1 LIMIT 1");
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
        let prog = b.finish().unwrap();
        let sorter_open = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::SorterOpen)
            .expect("star ordinal should use an ordered sorter");
        assert_eq!(
            sorter_open.p4,
            P4::Str("+|NOCASE".to_owned()),
            "ORDER BY 1 should inherit the first expanded star column's collation"
        );
    }

    #[test]
    fn test_codegen_ordered_ordinals_are_range_checked_after_star_expansion() {
        let schema = test_schema();
        for sql in [
            "SELECT a, b FROM t ORDER BY 0",
            "SELECT a, b FROM t ORDER BY -1",
            "SELECT a, b FROM t ORDER BY +3",
            "SELECT a FROM t ORDER BY 2 COLLATE BINARY",
        ] {
            let stmt = select_sql(sql);
            let mut b = ProgramBuilder::new();
            let error = codegen_select(&mut b, &stmt, &schema, &CodegenContext::default())
                .expect_err("out-of-range ORDER ordinal should fail");
            assert!(
                matches!(error, CodegenError::Unsupported(ref message) if message.contains("ORDER BY term")),
                "unexpected out-of-range ORDER ordinal error for `{sql}`: {error:?}"
            );
        }

        let stmt = select_sql("SELECT * FROM t ORDER BY 2");
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default())
            .expect("ORDER BY 2 should resolve to the second column expanded from star");
    }

    #[test]
    fn test_codegen_static_negative_limit_skips_top_n_preflight() {
        let schema = test_schema();
        let stmt = select_sql("SELECT out(b) FROM t ORDER BY a LIMIT -1");
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &CodegenContext::default()).unwrap();
        let prog = b.finish().unwrap();
        let sorter_open = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::SorterOpen)
            .expect("ordered SELECT should still use a full sorter");
        assert_eq!(
            sorter_open.p5, 0,
            "a static negative LIMIT means no bound and should not use runtime-bound setup"
        );
        assert!(
            !prog.ops().iter().any(|op| {
                op.opcode == Opcode::SorterCompare && op.p5 == SORTER_COMPARE_TOP_N_PREFLIGHT
            }),
            "a static negative LIMIT must not pay per-row preflight overhead"
        );

        let complex_ops = in_subquery_program_ops(
            "SELECT a IN (SELECT out(b) FROM s ORDER BY b LIMIT -1) FROM t",
            &test_schema_with_subquery_source(),
        );
        assert!(
            !complex_ops.iter().any(|op| {
                op.opcode == Opcode::SorterCompare && op.p5 == SORTER_COMPARE_TOP_N_PREFLIGHT
            }),
            "complex IN should also skip preflight for a static negative LIMIT"
        );
    }

    // === Test 17b: ORDER BY arithmetic expression ===
    #[test]
    fn test_codegen_select_order_by_arithmetic_expression() {
        let stmt = star_select_order_by_expr(
            "t",
            Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                op: AstBinaryOp::Add,
                right: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                span: Span::ZERO,
            },
        );
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(has_opcodes(
            &prog,
            &[
                Opcode::SorterOpen,
                Opcode::OpenRead,
                Opcode::Add,
                Opcode::SorterInsert,
                Opcode::SorterSort,
                Opcode::ResultRow,
            ]
        ));
    }

    // === Test 17c: ORDER BY scalar function expression ===
    #[test]
    fn test_codegen_select_order_by_function_expression() {
        let stmt = star_select_order_by_expr(
            "t",
            Expr::FunctionCall {
                name: "length".to_owned(),
                args: FunctionArgs::List(vec![Expr::Column(ColumnRef::bare("b"), Span::ZERO)]),
                distinct: false,
                order_by: vec![],
                filter: None,
                over: None,
                span: Span::ZERO,
            },
        );
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(has_opcodes(
            &prog,
            &[
                Opcode::SorterOpen,
                Opcode::OpenRead,
                Opcode::PureFunc,
                Opcode::SorterInsert,
                Opcode::SorterSort,
                Opcode::ResultRow,
            ]
        ));
    }

    #[test]
    fn test_codegen_select_where_literal_like_uses_const_fast_opcode() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table("t")),
                    where_clause: Some(Box::new(Expr::Like {
                        expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                        pattern: Box::new(Expr::Literal(
                            Literal::String("prefix%".to_owned()),
                            Span::ZERO,
                        )),
                        escape: None,
                        op: fsqlite_ast::LikeOp::Like,
                        not: false,
                        span: Span::ZERO,
                    })),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::LikeConstFast),
            "literal LIKE should use LikeConstFast opcode"
        );
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::PureFunc),
            "literal LIKE fast path should bypass generic PureFunc dispatch"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::LikeConstFast
                    && op.p4 == P4::Str("prefix".to_owned())),
            "prefix LIKE should hoist the trimmed literal into LikeConstFast"
        );
    }

    #[test]
    fn test_codegen_select_custom_like_context_disables_builtin_shortcuts() {
        let stmt = simple_select(
            &["a"],
            "t",
            Some(Box::new(Expr::Like {
                expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                pattern: Box::new(Expr::Literal(
                    Literal::String("123%".to_owned()),
                    Span::ZERO,
                )),
                escape: None,
                op: fsqlite_ast::LikeOp::Like,
                not: false,
                span: Span::ZERO,
            })),
        );
        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        with_connection_function_context(Vec::new(), false, true, || {
            codegen_select(&mut b, &stmt, &schema, &ctx)
        })
        .unwrap();
        let prog = b.finish().unwrap();
        let ops = prog.ops();

        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::LikeConstFast),
            "a replaced like() function must not be bypassed by LikeConstFast"
        );
        assert!(
            ops.iter().any(|op| {
                op.opcode == Opcode::PureFunc
                    && matches!(&op.p4, P4::FuncName(name) if name == "LIKE")
            }),
            "LIKE must dispatch through the function registry after replacement"
        );
        assert!(
            !ops.iter().any(|op| op.opcode == Opcode::SeekGE),
            "a built-in LIKE prefix range can exclude rows accepted by a replacement"
        );
        assert!(
            ops.iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "the replacement-aware lowering should retain the complete table candidate set"
        );
        assert!(
            use_builtin_like_glob_semantics(),
            "the connection function context must restore its prior state"
        );
    }

    #[test]
    fn scalar_override_declines_only_function_bearing_partial_index_heuristics() {
        fn fixture_where(sql: &str) -> Expr {
            let stmt = select_sql(sql);
            let SelectCore::Select {
                where_clause: Some(where_clause),
                ..
            } = stmt.body.select
            else {
                assert!(
                    test_failure(),
                    "partial-index fixture must have a WHERE clause"
                );
                return expr_sql("0");
            };
            *where_clause
        }

        let mut function_table = bd_2dgf5_table();
        function_table
            .indexes
            .first_mut()
            .expect("fixture must have an index")
            .where_clause = Some("abs(v) = 1".to_owned());
        let function_where = fixture_where("SELECT id FROM t WHERE k = 2 AND abs(v) = 1");
        let mut function_conjuncts = Vec::new();
        collect_conjunctive_terms(&function_where, &mut function_conjuncts);
        assert!(
            index_partial_predicate_is_covered_by_query_conjuncts(
                &function_table.indexes[0],
                &function_conjuncts,
                &function_table,
                None,
            ),
            "with built-in scalar semantics, the structurally identical function predicate \
             should prove partial-index coverage"
        );
        assert!(
            aggregate_index_prefix_literal_residual_target(
                Some(&function_where),
                &function_table,
                None,
                None,
            )
            .is_some(),
            "fixture must exercise the partial-index equality-prefix residual heuristic"
        );

        let mut plain_table = bd_2dgf5_table();
        plain_table
            .indexes
            .first_mut()
            .expect("fixture must have an index")
            .where_clause = Some("v = 'x'".to_owned());
        let plain_where = fixture_where("SELECT id FROM t WHERE k = 2 AND v = 'x'");
        let mut plain_conjuncts = Vec::new();
        collect_conjunctive_terms(&plain_where, &mut plain_conjuncts);

        with_connection_function_context(Vec::new(), true, false, || {
            assert!(
                !index_partial_predicate_is_covered_by_query_conjuncts(
                    &function_table.indexes[0],
                    &function_conjuncts,
                    &function_table,
                    None,
                ),
                "any scalar replacement must decline a function-bearing partial-index proof"
            );
            assert!(
                aggregate_index_prefix_literal_residual_target(
                    Some(&function_where),
                    &function_table,
                    None,
                    None,
                )
                .is_none(),
                "a scalar replacement must keep the function-bearing partial index \
                 out of the equality-prefix residual heuristic"
            );
            assert!(
                index_partial_predicate_is_covered_by_query_conjuncts(
                    &plain_table.indexes[0],
                    &plain_conjuncts,
                    &plain_table,
                    None,
                ),
                "an unrelated scalar replacement must not disable a function-free partial predicate"
            );
            assert!(
                aggregate_index_prefix_literal_residual_target(
                    Some(&plain_where),
                    &plain_table,
                    None,
                    None,
                )
                .is_some(),
                "the function-free partial index must remain eligible for the residual heuristic"
            );
        });
        assert!(
            use_builtin_scalar_function_semantics(),
            "the connection function context must restore scalar semantics state"
        );
    }

    // === Test 18: ORDER BY no sorter without ORDER BY ===
    #[test]
    fn test_codegen_select_no_order_by_no_sorter() {
        let stmt = star_select("t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Without ORDER BY, there should be no sorter opcodes.
        let sorter_count = prog
            .ops()
            .iter()
            .filter(|op| {
                matches!(
                    op.opcode,
                    Opcode::SorterOpen
                        | Opcode::SorterInsert
                        | Opcode::SorterSort
                        | Opcode::SorterData
                        | Opcode::SorterNext
                )
            })
            .count();
        assert_eq!(sorter_count, 0, "no sorter opcodes without ORDER BY");
    }

    // === Test 19: ORDER BY labels properly resolved ===
    #[test]
    fn test_codegen_select_order_by_labels_resolved() {
        let stmt = star_select_order_by("t", "a", false);
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // All jump targets should be valid addresses.
        for op in prog.ops() {
            if op.opcode.is_jump() {
                assert!(
                    op.p2 >= 0,
                    "unresolved jump at {:?}: p2 = {}",
                    op.opcode,
                    op.p2
                );
                assert!(
                    usize::try_from(op.p2).unwrap() <= prog.len(),
                    "jump target out of range at {:?}: p2 = {} (prog len = {})",
                    op.opcode,
                    op.p2,
                    prog.len()
                );
            }
        }

        // SorterNext p2 should point to SorterData (within bounds).
        let sn = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::SorterNext)
            .unwrap();
        let target_index = usize::try_from(sn.p2).unwrap();
        let target_op = &prog.ops()[target_index];
        assert_eq!(
            target_op.opcode,
            Opcode::SorterData,
            "SorterNext should jump back to SorterData"
        );
    }

    // === Test: SELECT ORDER BY expression (a + 1) ===
    #[test]
    fn test_codegen_select_order_by_expression() {
        // SELECT * FROM t ORDER BY a + 1
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Star],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr: Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                    op: fsqlite_ast::BinaryOp::Add,
                    right: Box::new(Expr::Literal(Literal::Integer(1), Span::ZERO)),
                    span: Span::ZERO,
                },
                direction: None,
                nulls: None,
            }],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Should use the sorter (two-pass pattern).
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::SorterOpen,
                Opcode::OpenRead,
                Opcode::Rewind,
                Opcode::SorterInsert,
                Opcode::Next,
                Opcode::SorterSort,
                Opcode::SorterData,
                Opcode::ResultRow,
                Opcode::SorterNext,
                Opcode::Halt,
            ]
        ));

        // The sort key is an expression, so we should see an Add opcode
        // in the first pass (before SorterInsert).
        let sorter_insert_idx = prog
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::SorterInsert)
            .unwrap();
        let has_add_before_sorter = prog.ops()[..sorter_insert_idx]
            .iter()
            .any(|op| op.opcode == Opcode::Add);
        assert!(
            has_add_before_sorter,
            "expression ORDER BY should emit Add before SorterInsert"
        );
    }

    // ── Aggregate test helpers ──

    /// Build `SELECT count(*) FROM table`.
    fn agg_count_star(table: &str) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    /// Build `SELECT count(*) FROM table WHERE rowid >= low AND rowid < high`.
    fn agg_count_star_rowid_range(table: &str, low: i64, high: i64) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table(table)),
                    where_clause: Some(Box::new(Expr::BinaryOp {
                        left: Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                            op: AstBinaryOp::Ge,
                            right: Box::new(Expr::Literal(Literal::Integer(low), Span::ZERO)),
                            span: Span::ZERO,
                        }),
                        op: AstBinaryOp::And,
                        right: Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                            op: AstBinaryOp::Lt,
                            right: Box::new(Expr::Literal(Literal::Integer(high), Span::ZERO)),
                            span: Span::ZERO,
                        }),
                        span: Span::ZERO,
                    })),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    fn agg_count_star_exists_rowid_probe() -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: Some(Box::new(Expr::Exists {
                        subquery: Box::new(SelectStatement {
                            with: None,
                            body: SelectBody {
                                select: SelectCore::Select {
                                    distinct: Distinctness::All,
                                    columns: vec![ResultColumn::Expr {
                                        expr: Expr::Literal(Literal::Integer(1), Span::ZERO),
                                        alias: None,
                                    }],
                                    from: Some(FromClause {
                                        source: TableOrSubquery::Table {
                                            name: QualifiedName::bare("s"),
                                            alias: Some("s".to_owned()),
                                            index_hint: None,
                                            time_travel: None,
                                        },
                                        joins: vec![],
                                    }),
                                    where_clause: Some(Box::new(Expr::BinaryOp {
                                        left: Box::new(Expr::BinaryOp {
                                            left: Box::new(Expr::Column(
                                                ColumnRef::qualified("s", "rowid"),
                                                Span::ZERO,
                                            )),
                                            op: AstBinaryOp::Eq,
                                            right: Box::new(Expr::Column(
                                                ColumnRef::qualified("t", "b"),
                                                Span::ZERO,
                                            )),
                                            span: Span::ZERO,
                                        }),
                                        op: AstBinaryOp::And,
                                        right: Box::new(Expr::BinaryOp {
                                            left: Box::new(Expr::Column(
                                                ColumnRef::qualified("s", "rowid"),
                                                Span::ZERO,
                                            )),
                                            op: AstBinaryOp::Le,
                                            right: Box::new(Expr::Literal(
                                                Literal::Integer(5),
                                                Span::ZERO,
                                            )),
                                            span: Span::ZERO,
                                        }),
                                        span: Span::ZERO,
                                    })),
                                    group_by: vec![],
                                    having: None,
                                    windows: vec![],
                                },
                                compounds: vec![],
                            },
                            order_by: vec![],
                            limit: None,
                        }),
                        not: false,
                        span: Span::ZERO,
                    })),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    /// Build `SELECT func(col) FROM table`.
    fn agg_func_col(func: &str, col: &str, table: &str) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: func.to_owned(),
                            args: FunctionArgs::List(vec![Expr::Column(
                                ColumnRef::bare(col),
                                Span::ZERO,
                            )]),
                            distinct: false,
                            order_by: Vec::new(),
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    /// Build `SELECT count(*), sum(col) FROM table`.
    fn agg_count_star_and_sum(col: &str, table: &str) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "count".to_owned(),
                                args: FunctionArgs::Star,
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "sum".to_owned(),
                                args: FunctionArgs::List(vec![Expr::Column(
                                    ColumnRef::bare(col),
                                    Span::ZERO,
                                )]),
                                distinct: false,
                                order_by: Vec::new(),
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                    ],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    /// Build `SELECT count(*) FROM table HAVING sum(col) > threshold`.
    fn agg_count_star_having_sum_gt(col: &str, threshold: i64, table: &str) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: Some(Box::new(Expr::BinaryOp {
                        left: Box::new(Expr::FunctionCall {
                            name: "sum".to_owned(),
                            args: FunctionArgs::List(vec![Expr::Column(
                                ColumnRef::bare(col),
                                Span::ZERO,
                            )]),
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        }),
                        op: AstBinaryOp::Gt,
                        right: Box::new(Expr::Literal(Literal::Integer(threshold), Span::ZERO)),
                        span: Span::ZERO,
                    })),
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    /// Build `SELECT count(*) FROM table HAVING count(*) > threshold`.
    fn agg_count_star_having_count_gt(threshold: i64, table: &str) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table(table)),
                    where_clause: None,
                    group_by: vec![],
                    having: Some(Box::new(Expr::BinaryOp {
                        left: Box::new(Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        }),
                        op: AstBinaryOp::Gt,
                        right: Box::new(Expr::Literal(Literal::Integer(threshold), Span::ZERO)),
                        span: Span::ZERO,
                    })),
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    // === Test 20: SELECT count(*) ===
    #[test]
    fn test_codegen_select_count_star() {
        let stmt = agg_count_star("t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // COUNT(*) now takes the direct Count fast path.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Init,
                Opcode::Transaction,
                Opcode::OpenRead,
                Opcode::Count,
                Opcode::ResultRow,
                Opcode::Close,
                Opcode::Halt,
            ]
        ));
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::AggStep | Opcode::AggFinal)),
            "COUNT(*) fast path should bypass aggregate opcodes"
        );

        // ResultRow should cover 1 column.
        let rr = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::ResultRow)
            .unwrap();
        assert_eq!(rr.p2, 1, "count(*) produces 1 result column");
    }

    #[test]
    fn test_codegen_select_count_star_rowid_range_uses_counter_loop() {
        let stmt = agg_count_star_rowid_range("t", 10, 20);
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::SeekGE | Opcode::SeekGT)),
            "rowid-bounded COUNT(*) should seek into range instead of rewinding from row 0"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::AddImm),
            "specialized COUNT(*) loop should increment a counter register directly"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::AggStep | Opcode::AggFinal)),
            "rowid-bounded COUNT(*) should bypass generic aggregate execution"
        );
    }

    #[test]
    fn test_codegen_exists_subquery_uses_rowid_probe_when_available() {
        let stmt = agg_count_star_exists_rowid_probe();
        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekRowid),
            "correlated EXISTS on inner rowid should probe directly with SeekRowid"
        );
        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();
        assert_eq!(
            rewind_count, 1,
            "only the outer scan should rewind when EXISTS lowers to a direct rowid probe"
        );
    }

    #[test]
    fn test_codegen_select_uncorrelated_exists_subquery_uses_once_cached_boolean() {
        let where_expr = Expr::Exists {
            subquery: Box::new(SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![ResultColumn::Expr {
                            expr: Expr::Literal(Literal::Integer(1), Span::ZERO),
                            alias: None,
                        }],
                        from: Some(FromClause {
                            source: TableOrSubquery::Table {
                                name: QualifiedName::bare("s"),
                                alias: Some("s".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            joins: vec![],
                        }),
                        where_clause: Some(Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(
                                ColumnRef::qualified("s", "b"),
                                Span::ZERO,
                            )),
                            op: AstBinaryOp::Le,
                            right: Box::new(Expr::Literal(Literal::Integer(5), Span::ZERO)),
                            span: Span::ZERO,
                        })),
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            }),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Once),
            "uncorrelated EXISTS subqueries should be evaluated once and cached"
        );
    }

    #[test]
    fn test_codegen_select_correlated_exists_subquery_does_not_use_once_materialization() {
        let where_expr = Expr::Exists {
            subquery: Box::new(SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![ResultColumn::Expr {
                            expr: Expr::Literal(Literal::Integer(1), Span::ZERO),
                            alias: None,
                        }],
                        from: Some(FromClause {
                            source: TableOrSubquery::Table {
                                name: QualifiedName::bare("s"),
                                alias: Some("s".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            joins: vec![],
                        }),
                        where_clause: Some(Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(
                                ColumnRef::qualified("s", "b"),
                                Span::ZERO,
                            )),
                            op: AstBinaryOp::Eq,
                            right: Box::new(Expr::Column(
                                ColumnRef::qualified("t", "a"),
                                Span::ZERO,
                            )),
                            span: Span::ZERO,
                        })),
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            }),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::Once),
            "correlated EXISTS subqueries must not be cached once because they depend on outer-row values"
        );
    }

    #[test]
    fn test_codegen_select_large_in_list_uses_once_materialized_autoindex() {
        let values = (1..=8)
            .map(|value| Expr::Literal(Literal::Integer(value), Span::ZERO))
            .collect();
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
            set: InSet::List(values),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Once),
            "large IN lists should materialize their membership set once per statement"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenAutoindex),
            "large IN lists should build an ephemeral autoindex"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::IdxInsert),
            "large IN lists should populate the ephemeral autoindex"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Found),
            "large IN lists should probe membership via Found"
        );
    }

    #[test]
    fn test_codegen_select_large_collated_in_list_materializes_autoindex_with_collation() {
        let values = (1..=8)
            .map(|value| Expr::Literal(Literal::String(format!("v{value}")), Span::ZERO))
            .collect();
        let where_expr = Expr::In {
            expr: Box::new(Expr::Collate {
                expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                collation: "NOCASE".to_owned(),
                span: Span::ZERO,
            }),
            set: InSet::List(values),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Once),
            "collated large IN lists should still materialize once per statement"
        );
        assert!(
            prog.ops().iter().any(|op| {
                op.opcode == Opcode::OpenAutoindex
                    && matches!(&op.p4, P4::Collation(name) if name == "NOCASE")
            }),
            "materialized collated IN lists must thread their collation into OpenAutoindex"
        );
    }

    #[test]
    fn test_codegen_select_uncorrelated_in_subquery_uses_once_materialized_autoindex() {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
            set: InSet::Subquery(Box::new(SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("s", "b"), Span::ZERO),
                            alias: None,
                        }],
                        from: Some(FromClause {
                            source: TableOrSubquery::Table {
                                name: QualifiedName::bare("s"),
                                alias: Some("s".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            joins: vec![],
                        }),
                        where_clause: Some(Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(
                                ColumnRef::qualified("s", "b"),
                                Span::ZERO,
                            )),
                            op: AstBinaryOp::Le,
                            right: Box::new(Expr::Literal(Literal::Integer(5), Span::ZERO)),
                            span: Span::ZERO,
                        })),
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            })),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Once),
            "uncorrelated IN subqueries should materialize once per statement"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenAutoindex),
            "uncorrelated IN subqueries should build an ephemeral autoindex"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::IdxInsert),
            "uncorrelated IN subqueries should populate the ephemeral autoindex"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Found),
            "uncorrelated IN subqueries should probe membership via Found"
        );
    }

    #[test]
    fn test_codegen_select_uncorrelated_collated_in_subquery_materializes_autoindex_with_collation()
    {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Collate {
                expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                collation: "NOCASE".to_owned(),
                span: Span::ZERO,
            }),
            set: InSet::Subquery(Box::new(SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("s", "b"), Span::ZERO),
                            alias: None,
                        }],
                        from: Some(FromClause {
                            source: TableOrSubquery::Table {
                                name: QualifiedName::bare("s"),
                                alias: Some("s".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            joins: vec![],
                        }),
                        where_clause: Some(Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(
                                ColumnRef::qualified("s", "b"),
                                Span::ZERO,
                            )),
                            op: AstBinaryOp::Le,
                            right: Box::new(Expr::Literal(Literal::Integer(5), Span::ZERO)),
                            span: Span::ZERO,
                        })),
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            })),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Once),
            "collated uncorrelated IN subqueries should still materialize once per statement"
        );
        assert!(
            prog.ops().iter().any(|op| {
                op.opcode == Opcode::OpenAutoindex
                    && matches!(&op.p4, P4::Collation(name) if name == "NOCASE")
            }),
            "materialized collated IN subqueries must thread their collation into OpenAutoindex"
        );
    }

    #[test]
    fn test_codegen_select_uncorrelated_in_subquery_with_overlapping_column_names_materializes_once()
     {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
            set: InSet::Subquery(Box::new(SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("b"), Span::ZERO),
                            alias: None,
                        }],
                        from: Some(from_table("s")),
                        where_clause: Some(Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                            op: AstBinaryOp::Le,
                            right: Box::new(Expr::Literal(Literal::Integer(5), Span::ZERO)),
                            span: Span::ZERO,
                        })),
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            })),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenAutoindex),
            "local subquery columns that overlap outer column names must still materialize once"
        );
    }

    #[test]
    fn test_codegen_select_correlated_in_subquery_does_not_use_once_materialization() {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
            set: InSet::Subquery(Box::new(SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("b"), Span::ZERO),
                            alias: None,
                        }],
                        from: Some(FromClause {
                            source: TableOrSubquery::Table {
                                name: QualifiedName::bare("s"),
                                alias: Some("s".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            joins: vec![],
                        }),
                        where_clause: Some(Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(
                                ColumnRef::qualified("s", "b"),
                                Span::ZERO,
                            )),
                            op: AstBinaryOp::Eq,
                            right: Box::new(Expr::Column(
                                ColumnRef::qualified("t", "a"),
                                Span::ZERO,
                            )),
                            span: Span::ZERO,
                        })),
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            })),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenAutoindex),
            "correlated IN subqueries must not materialize once because they depend on outer-row values"
        );
    }

    #[test]
    fn test_codegen_select_count_star_indexed_in_list_uses_index_probe_expansion() {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
            set: InSet::List(
                (1..=8)
                    .map(|value| Expr::Literal(Literal::Integer(value), Span::ZERO))
                    .collect(),
            ),
            not: false,
            span: Span::ZERO,
        };
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: Some(Box::new(where_expr)),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| matches!(&op.p4, P4::Index(name) if op.opcode == Opcode::OpenRead && name == "idx_t_b")),
            "count(*) with indexed IN-list should open the outer index"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenAutoindex),
            "count(*) with indexed IN-list should build a deduplicated probe set"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "count(*) with indexed IN-list should seek into the outer index per probe value"
        );
        assert!(
            !prog.ops().iter().any(|op| matches!(&op.p4, P4::Table(name) if op.opcode == Opcode::OpenRead && name == "t")),
            "count(*) with indexed IN-list should not fall back to opening the base table"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::AggStep | Opcode::AggFinal)),
            "count(*) with indexed IN-list should stay on the direct counter path"
        );
    }

    #[test]
    fn test_codegen_select_count_star_indexed_collated_in_list_threads_nocase() {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("name"), Span::ZERO)),
            set: InSet::List(
                [
                    "alpha", "ALPHA", "gamma", "delta", "epsilon", "zeta", "eta", "theta",
                ]
                .into_iter()
                .map(|value| Expr::Literal(Literal::String(value.to_owned()), Span::ZERO))
                .collect(),
            ),
            not: false,
            span: Span::ZERO,
        };
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: Some(Box::new(where_expr)),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_nocase_text_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| {
                op.opcode == Opcode::OpenAutoindex
                    && matches!(op.p4, P4::Collation(ref name) if name == "NOCASE")
            }),
            "collated COUNT(*) IN fast path must materialize the probe set with NOCASE semantics"
        );
        assert!(
            prog.ops().iter().any(|op| {
                op.opcode == Opcode::Ne
                    && matches!(op.p4, P4::Collation(ref name) if name == "NOCASE")
            }),
            "collated COUNT(*) IN fast path must compare probe keys against the outer index with NOCASE semantics"
        );
    }

    #[test]
    fn test_codegen_select_count_star_indexed_in_subquery_uses_index_probe_expansion() {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
            set: InSet::Subquery(Box::new(SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("b"), Span::ZERO),
                            alias: None,
                        }],
                        from: Some(from_table("s")),
                        where_clause: Some(Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                            op: AstBinaryOp::Le,
                            right: Box::new(Expr::Literal(Literal::Integer(5), Span::ZERO)),
                            span: Span::ZERO,
                        })),
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            })),
            not: false,
            span: Span::ZERO,
        };
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: Some(Box::new(where_expr)),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_index_and_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| matches!(&op.p4, P4::Index(name) if op.opcode == Opcode::OpenRead && name == "idx_t_b")),
            "count(*) with indexed IN-subquery should open the outer index"
        );
        assert!(
            prog.ops().iter().any(|op| matches!(&op.p4, P4::Table(name) if op.opcode == Opcode::OpenRead && name == "s")),
            "count(*) with indexed IN-subquery should still read the inner probe source once"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenAutoindex),
            "count(*) with indexed IN-subquery should materialize a deduplicated RHS probe set once"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "count(*) with indexed IN-subquery should seek into the outer index per probe value"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| op.opcode == Opcode::CountIndexEqRun),
            "non-rowid IN-subquery should stay on per-probe indexed seeks"
        );
        assert!(
            !prog.ops().iter().any(|op| matches!(&op.p4, P4::Table(name) if op.opcode == Opcode::OpenRead && name == "t")),
            "count(*) with indexed IN-subquery should avoid reopening the base table"
        );
    }

    /// bd-g5ys1: the non-aggregate indexed IN-subquery must drive the outer
    /// index with per-value seeks instead of full-scanning the table with a
    /// per-row membership probe.
    #[test]
    fn bd_g5ys1_nonaggregate_indexed_in_subquery_seeks_per_distinct_value() {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
            set: InSet::Subquery(Box::new(SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("b"), Span::ZERO),
                            alias: None,
                        }],
                        from: Some(from_table("s")),
                        where_clause: None,
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            })),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["b"], "t", Some(Box::new(where_expr)));

        let schema = test_schema_with_index_and_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| matches!(&op.p4, P4::Index(name) if op.opcode == Opcode::OpenRead && name == "idx_t_b")),
            "indexed IN-subquery should open the outer index"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenAutoindex),
            "indexed IN-subquery should materialize the RHS probe set once"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Found),
            "the probe-set build must dedup via Found so duplicate RHS values \
             cannot emit duplicate outer rows"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "indexed IN-subquery should seek into the outer index per probe value"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::IdxRowid)
                && prog.ops().iter().any(|op| op.opcode == Opcode::SeekRowid),
            "each index hit should look the row up in the base table"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::ResultRow),
            "matching rows should be emitted"
        );
        // The outer table is opened for row lookups (cursor 0) but never
        // scanned: every Rewind belongs to the probe/source cursors.
        assert!(
            prog.ops().iter().any(|op| matches!(&op.p4, P4::Table(name) if op.opcode == Opcode::OpenRead && name == "t")),
            "the base table stays open for SeekRowid lookups"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| op.opcode == Opcode::Rewind && op.p1 == 0),
            "the outer table must not be full-scanned, got: {:?}",
            prog.ops().iter().map(|op| op.opcode).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_codegen_select_count_star_indexed_in_rowid_subquery_uses_bounded_source_scan() {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
            set: InSet::Subquery(Box::new(SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("rowid"), Span::ZERO),
                            alias: None,
                        }],
                        from: Some(from_table("s")),
                        where_clause: Some(Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                            op: AstBinaryOp::Le,
                            right: Box::new(Expr::Literal(Literal::Integer(5), Span::ZERO)),
                            span: Span::ZERO,
                        })),
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            })),
            not: false,
            span: Span::ZERO,
        };
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: Some(Box::new(where_expr)),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_index_and_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops()
                .iter()
                .all(|op| op.opcode != Opcode::OpenAutoindex),
            "rowid-driven IN-subquery should scan the unique rowid probe source directly"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::CountIndexEqRun),
            "rowid-driven IN-subquery should consume the materialized RHS via duplicate-run counting"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::Ge | Opcode::Gt)),
            "rowid-driven IN-subquery should bound the inner probe-source rowid scan"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Rowid),
            "rowid-driven IN-subquery should read source rowids for bounded stop checks"
        );
        let rowid_reg = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Rowid)
            .expect("rowid-backed probe should read the source rowid")
            .p2;
        let count_eq_run = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::CountIndexEqRun)
            .expect("rowid-backed probe should count duplicate index-key runs");
        assert_eq!(
            count_eq_run.p3, rowid_reg,
            "CountIndexEqRun should consume the source rowid register directly"
        );
        assert!(
            prog.ops().iter().all(|op| op.opcode != Opcode::Copy),
            "rowid-backed indexed IN count should not copy the rowid into a separate probe register"
        );
    }

    #[test]
    fn test_extract_count_indexed_in_target_uses_direct_probe_source_for_bounded_ipk_subquery() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: Some(Box::new(Expr::In {
                        expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                        set: InSet::Subquery(Box::new(SelectStatement {
                            with: None,
                            body: SelectBody {
                                select: SelectCore::Select {
                                    distinct: Distinctness::All,
                                    columns: vec![ResultColumn::Expr {
                                        expr: Expr::Column(
                                            ColumnRef::qualified("s", "id"),
                                            Span::ZERO,
                                        ),
                                        alias: None,
                                    }],
                                    from: Some(FromClause {
                                        source: TableOrSubquery::Table {
                                            name: QualifiedName::bare("s"),
                                            alias: Some("s".to_owned()),
                                            index_hint: None,
                                            time_travel: None,
                                        },
                                        joins: vec![],
                                    }),
                                    where_clause: Some(Box::new(Expr::BinaryOp {
                                        left: Box::new(Expr::Column(
                                            ColumnRef::qualified("s", "id"),
                                            Span::ZERO,
                                        )),
                                        op: AstBinaryOp::Le,
                                        right: Box::new(Expr::Literal(
                                            Literal::Integer(5),
                                            Span::ZERO,
                                        )),
                                        span: Span::ZERO,
                                    })),
                                    group_by: vec![],
                                    having: None,
                                    windows: vec![],
                                },
                                compounds: vec![],
                            },
                            order_by: vec![],
                            limit: None,
                        })),
                        not: false,
                        span: Span::ZERO,
                    })),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = vec![
            TableSchema {
                name: "t".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("a", 'd', false),
                    ColumnInfo::basic("b", 'd', false),
                ],
                indexes: vec![IndexSchema {
                    name: "idx_t_b".to_owned(),
                    root_page: 4,
                    columns: vec!["b".to_owned()],
                    key_expressions: vec!["b".to_owned()],
                    key_sort_directions: vec![],
                    where_clause: None,
                    is_unique: false,
                    key_collations: vec![],
                    conflict_action: None,
                }],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "s".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'd', true),
                    ColumnInfo::basic("name", 'a', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ];

        let table = find_table(&schema, "t").expect("outer table should exist");
        let scan_ctx = ScanCtx {
            cursor: 0,
            table,
            table_alias: None,
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };
        let SelectCore::Select {
            where_clause: Some(where_clause),
            ..
        } = &stmt.body.select
        else {
            unreachable!("fixture should include a WHERE clause");
        };

        let extracted = extract_count_indexed_in_target(
            Some(where_clause),
            table,
            None,
            &schema,
            &scan_ctx,
            None,
        )
        .expect("indexed IN target should match");

        assert_eq!(extracted.0.name, "idx_t_b");
        match extracted.1 {
            CountIndexedInTarget::ProbeSource(probe_source) => {
                assert!(matches!(probe_source.value, InProbeValue::Rowid));
            }
            CountIndexedInTarget::MaterializedProbeSource(_) => {
                unreachable!(
                    "bounded IPK-projected IN target should lower to a direct rowid probe source"
                );
            }
            CountIndexedInTarget::List(_) => {
                unreachable!("IPK-projected IN target should lower to a rowid probe source");
            }
        }
    }

    #[test]
    fn test_extract_count_indexed_in_target_rejects_collation_mismatch() {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Collate {
                expr: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                collation: "NOCASE".to_owned(),
                span: Span::ZERO,
            }),
            set: InSet::List(
                [
                    "alpha", "ALPHA", "gamma", "delta", "epsilon", "zeta", "eta", "theta",
                ]
                .into_iter()
                .map(|value| Expr::Literal(Literal::String(value.to_owned()), Span::ZERO))
                .collect(),
            ),
            not: false,
            span: Span::ZERO,
        };

        let schema = test_schema_with_index();
        let table = find_table(&schema, "t").expect("table should exist");
        let scan_ctx = ScanCtx {
            cursor: 0,
            table,
            table_alias: None,
            schema: Some(&schema),
            register_base: None,
            secondaries: &[],
        };

        assert!(
            extract_count_indexed_in_target(
                Some(&where_expr),
                table,
                None,
                &schema,
                &scan_ctx,
                None,
            )
            .is_none(),
            "count(*) indexed-IN fast path must reject indexes whose collation does not match the probe semantics"
        );
    }

    #[test]
    fn test_codegen_select_count_star_exists_semijoin_uses_duplicate_run_count_opcode() {
        let stmt = agg_count_star_exists_rowid_probe();
        let schema = test_schema_with_index_and_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(
                |op| matches!(&op.p4, P4::Index(name) if op.opcode == Opcode::OpenRead && name == "idx_t_b")
            ),
            "count(*) EXISTS semijoin fast path should open the outer index"
        );
        assert!(
            prog.ops().iter().any(
                |op| matches!(&op.p4, P4::Table(name) if op.opcode == Opcode::OpenRead && name == "s")
            ),
            "count(*) EXISTS semijoin fast path should still read the inner probe source once"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::Ge | Opcode::Gt | Opcode::SeekGE)),
            "count(*) EXISTS semijoin fast path should keep the bounded source scan and indexed outer probe"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Rowid),
            "count(*) EXISTS semijoin fast path should read source rowids for bounded stop checks"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::CountIndexEqRun),
            "count(*) EXISTS semijoin fast path should fuse duplicate-run counting into a dedicated opcode"
        );
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::Eq),
            "count(*) EXISTS semijoin fast path should avoid interpreter-level duplicate-run equality loops"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenAutoindex),
            "count(*) EXISTS semijoin fast path should stay off temp materialization"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(&op.p4, P4::Table(name) if op.opcode == Opcode::OpenRead && name == "t")),
            "count(*) EXISTS semijoin fast path should avoid reopening the outer base table"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::AggStep | Opcode::AggFinal)),
            "count(*) EXISTS semijoin fast path should stay on the direct counter path"
        );
    }

    #[test]
    fn test_codegen_single_inner_join_uses_index_lookup_plan() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("c", "name"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("o", "amount"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("customers"),
                            alias: Some("c".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![fsqlite_ast::JoinClause {
                            join_type: fsqlite_ast::JoinType {
                                kind: fsqlite_ast::JoinKind::Inner,
                                natural: false,
                            },
                            table: TableOrSubquery::Table {
                                name: QualifiedName::bare("orders"),
                                alias: Some("o".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            constraint: Some(fsqlite_ast::JoinConstraint::On(Expr::BinaryOp {
                                left: Box::new(Expr::Column(
                                    ColumnRef::qualified("o", "customer_id"),
                                    Span::ZERO,
                                )),
                                op: AstBinaryOp::Eq,
                                right: Box::new(Expr::Column(
                                    ColumnRef::qualified("c", "id"),
                                    Span::ZERO,
                                )),
                                span: Span::ZERO,
                            })),
                        }],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_join_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert_eq!(
            rewind_count, 1,
            "lookup join should only rewind the outer table"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "lookup join should seek into the right-side index"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::IdxRowid),
            "lookup join should extract matching rowids from the right-side index"
        );
    }

    #[test]
    fn test_codegen_single_left_join_uses_index_lookup_plan() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("c", "name"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("o", "amount"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("customers"),
                            alias: Some("c".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![fsqlite_ast::JoinClause {
                            join_type: fsqlite_ast::JoinType {
                                kind: fsqlite_ast::JoinKind::Left,
                                natural: false,
                            },
                            table: TableOrSubquery::Table {
                                name: QualifiedName::bare("orders"),
                                alias: Some("o".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            constraint: Some(fsqlite_ast::JoinConstraint::On(Expr::BinaryOp {
                                left: Box::new(Expr::Column(
                                    ColumnRef::qualified("o", "customer_id"),
                                    Span::ZERO,
                                )),
                                op: AstBinaryOp::Eq,
                                right: Box::new(Expr::Column(
                                    ColumnRef::qualified("c", "id"),
                                    Span::ZERO,
                                )),
                                span: Span::ZERO,
                            })),
                        }],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_join_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert_eq!(
            rewind_count, 1,
            "lookup left join should only rewind the outer table"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "left join should seek into the right-side index"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::NullRow),
            "left join should still null-extend unmatched right rows"
        );
    }

    #[test]
    fn test_codegen_single_inner_join_uses_rowid_lookup_plan() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("o", "amount"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("c", "name"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("orders"),
                            alias: Some("o".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![fsqlite_ast::JoinClause {
                            join_type: fsqlite_ast::JoinType {
                                kind: fsqlite_ast::JoinKind::Inner,
                                natural: false,
                            },
                            table: TableOrSubquery::Table {
                                name: QualifiedName::bare("customers"),
                                alias: Some("c".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            constraint: Some(fsqlite_ast::JoinConstraint::On(Expr::BinaryOp {
                                left: Box::new(Expr::Column(
                                    ColumnRef::qualified("c", "id"),
                                    Span::ZERO,
                                )),
                                op: AstBinaryOp::Eq,
                                right: Box::new(Expr::Column(
                                    ColumnRef::qualified("o", "customer_id"),
                                    Span::ZERO,
                                )),
                                span: Span::ZERO,
                            })),
                        }],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_join_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert_eq!(
            rewind_count, 1,
            "rowid lookup join should only rewind the outer table"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekRowid),
            "join against an INTEGER PRIMARY KEY should seek by rowid"
        );
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "rowid lookup join should not use a secondary-index probe"
        );
    }

    /// Schema matching the bd_zjisk issue #62 bounded repro:
    /// messages (large fact) → conversations → agents (INNER) + workspaces (LEFT)
    /// Every foreign-key edge lands on an INTEGER PRIMARY KEY, so the
    /// multi-join lookup fast path should fire for all three joins.
    fn test_schema_issue_62_fts_rebuild() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "messages".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("conversation_id", 'D', false),
                    ColumnInfo::basic("content", 'B', false),
                    ColumnInfo::basic("created_at", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "conversations".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("agent_id", 'D', false),
                    ColumnInfo::basic("workspace_id", 'D', false),
                    ColumnInfo::basic("title", 'B', false),
                    ColumnInfo::basic("source_path", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "agents".to_owned(),
                root_page: 4,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("slug", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "workspaces".to_owned(),
                root_page: 5,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("path", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    /// Build the 4-table SELECT from the issue #62 repro:
    ///
    ///   SELECT m.id, c.title, a.slug, w.path
    ///     FROM messages m
    ///     JOIN conversations c ON m.conversation_id = c.id
    ///     JOIN agents a        ON c.agent_id = a.id
    ///     LEFT JOIN workspaces w ON c.workspace_id = w.id;
    fn issue_62_four_table_select() -> SelectStatement {
        let on_m_c = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("m", "conversation_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(ColumnRef::qualified("c", "id"), Span::ZERO)),
            span: Span::ZERO,
        };
        let on_c_a = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("c", "agent_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(ColumnRef::qualified("a", "id"), Span::ZERO)),
            span: Span::ZERO,
        };
        let on_c_w = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("c", "workspace_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(ColumnRef::qualified("w", "id"), Span::ZERO)),
            span: Span::ZERO,
        };
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("m", "id"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("c", "title"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("a", "slug"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("w", "path"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("messages"),
                            alias: Some("m".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("conversations"),
                                    alias: Some("c".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_m_c)),
                            },
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("agents"),
                                    alias: Some("a".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_c_a)),
                            },
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Left,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("workspaces"),
                                    alias: Some("w".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_c_w)),
                            },
                        ],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    /// The exact 4-table JOIN shape from bd_zjisk issue #62 must use the
    /// multi-join lookup fast path — not the nested full-scan path — so
    /// that execution scales linearly in the driver instead of blowing
    /// up as the Cartesian product of all four tables (the reported
    /// 81-minute vs 8-second gap).
    #[test]
    fn test_codegen_issue_62_four_table_join_uses_multi_lookup_path() {
        let stmt = issue_62_four_table_select();
        let schema = test_schema_issue_62_fts_rebuild();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();
        let seek_rowid_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::SeekRowid)
            .count();
        let null_row_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::NullRow)
            .count();

        assert_eq!(
            rewind_count, 1,
            "multi-join lookup fast path should only Rewind the driver \
             table once; nested full scans indicate a regression to the \
             Cartesian-product codegen path"
        );
        assert_eq!(
            seek_rowid_count, 3,
            "each of the three joins should resolve to a SeekRowid on \
             its respective dimension table (conversations, agents, \
             workspaces)"
        );
        assert!(
            null_row_count >= 1,
            "the trailing LEFT JOIN on workspaces must still emit a \
             NullRow stub for probe-misses so the outer row is \
             preserved with a NULL workspace"
        );
    }

    /// Sanity check: a 3-table INNER-JOIN chain whose middle step
    /// references the first (not the driver) must still resolve through
    /// the multi-join lookup fast path.
    #[test]
    fn test_codegen_three_table_inner_chain_uses_multi_lookup_path() {
        // messages → conversations (via m.conversation_id = c.id)
        //          → agents (via c.agent_id = a.id)  ← depends on conversations, not messages
        let stmt = {
            let on_m_c = Expr::BinaryOp {
                left: Box::new(Expr::Column(
                    ColumnRef::qualified("m", "conversation_id"),
                    Span::ZERO,
                )),
                op: AstBinaryOp::Eq,
                right: Box::new(Expr::Column(ColumnRef::qualified("c", "id"), Span::ZERO)),
                span: Span::ZERO,
            };
            let on_c_a = Expr::BinaryOp {
                left: Box::new(Expr::Column(
                    ColumnRef::qualified("c", "agent_id"),
                    Span::ZERO,
                )),
                op: AstBinaryOp::Eq,
                right: Box::new(Expr::Column(ColumnRef::qualified("a", "id"), Span::ZERO)),
                span: Span::ZERO,
            };
            SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![
                            ResultColumn::Expr {
                                expr: Expr::Column(ColumnRef::qualified("m", "id"), Span::ZERO),
                                alias: None,
                            },
                            ResultColumn::Expr {
                                expr: Expr::Column(ColumnRef::qualified("a", "slug"), Span::ZERO),
                                alias: None,
                            },
                        ],
                        from: Some(FromClause {
                            source: TableOrSubquery::Table {
                                name: QualifiedName::bare("messages"),
                                alias: Some("m".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            joins: vec![
                                fsqlite_ast::JoinClause {
                                    join_type: fsqlite_ast::JoinType {
                                        kind: fsqlite_ast::JoinKind::Inner,
                                        natural: false,
                                    },
                                    table: TableOrSubquery::Table {
                                        name: QualifiedName::bare("conversations"),
                                        alias: Some("c".to_owned()),
                                        index_hint: None,
                                        time_travel: None,
                                    },
                                    constraint: Some(fsqlite_ast::JoinConstraint::On(on_m_c)),
                                },
                                fsqlite_ast::JoinClause {
                                    join_type: fsqlite_ast::JoinType {
                                        kind: fsqlite_ast::JoinKind::Inner,
                                        natural: false,
                                    },
                                    table: TableOrSubquery::Table {
                                        name: QualifiedName::bare("agents"),
                                        alias: Some("a".to_owned()),
                                        index_hint: None,
                                        time_travel: None,
                                    },
                                    constraint: Some(fsqlite_ast::JoinConstraint::On(on_c_a)),
                                },
                            ],
                        }),
                        where_clause: None,
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            }
        };
        let schema = test_schema_issue_62_fts_rebuild();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();
        let seek_rowid_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::SeekRowid)
            .count();
        let null_row_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::NullRow)
            .count();

        assert_eq!(
            rewind_count, 1,
            "3-table INNER chain should only rewind the driver"
        );
        assert_eq!(
            seek_rowid_count, 2,
            "both right-side lookups should resolve to SeekRowid"
        );
        assert_eq!(
            null_row_count, 0,
            "pure INNER JOIN chain must not emit NullRow stubs"
        );
    }

    /// A non-terminal LEFT JOIN (LEFT followed by another join) must NOT
    /// take the multi-join lookup fast path, because the codegen below
    /// only knows how to emit a trailing null-row block for the *last*
    /// step.  Today the scan fallback (`codegen_join_select`) also
    /// refuses multi-table LEFT joins, so the expected outcome for this
    /// shape is `CodegenError::Unsupported` bubbled out of the
    /// VDBE-codegen layer and handled by the connection-level
    /// interpreter.  The important invariant we are asserting here is:
    /// we do NOT silently return a 1-Rewind fast-path plan (which would
    /// be incorrect because the middle LEFT miss would skip the
    /// trailing INNER step and produce wrong rows).
    #[test]
    fn test_codegen_non_terminal_left_join_does_not_take_fast_path() {
        // messages m
        //   INNER JOIN workspaces w ON m.conversation_id = w.id
        //   LEFT JOIN agents a ON m.conversation_id = a.id
        //   INNER JOIN conversations c ON m.conversation_id = c.id
        //
        // (the exact FK edges are contrived — we just want an INNER +
        // LEFT + INNER chain over the issue-62 schema that every step
        // could in principle resolve to a rowid lookup.)
        let on_m_w = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("m", "conversation_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(ColumnRef::qualified("w", "id"), Span::ZERO)),
            span: Span::ZERO,
        };
        let on_m_a = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("m", "conversation_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(ColumnRef::qualified("a", "id"), Span::ZERO)),
            span: Span::ZERO,
        };
        let on_m_c = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("m", "conversation_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(ColumnRef::qualified("c", "id"), Span::ZERO)),
            span: Span::ZERO,
        };
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::qualified("m", "id"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("messages"),
                            alias: Some("m".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("workspaces"),
                                    alias: Some("w".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_m_w)),
                            },
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Left,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("agents"),
                                    alias: Some("a".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_m_a)),
                            },
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("conversations"),
                                    alias: Some("c".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_m_c)),
                            },
                        ],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema_issue_62_fts_rebuild();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let result = codegen_select(&mut b, &stmt, &schema, &ctx);

        match result {
            Ok(()) => {
                // If codegen DOES succeed (e.g. because the scan
                // fallback ever learns multi-table LEFT), the crucial
                // invariant we care about is that the fast path was
                // not silently taken.  The fast path always emits
                // exactly one Rewind; more than one Rewind means we
                // landed on the nested-scan path, which is the only
                // correct shape for this chain today.
                let prog = b.finish().unwrap();
                let rewind_count = prog
                    .ops()
                    .iter()
                    .filter(|op| op.opcode == Opcode::Rewind)
                    .count();
                assert!(
                    rewind_count >= 2,
                    "non-terminal LEFT JOIN landed on the fast path \
                     (only {rewind_count} Rewinds) — the resolver \
                     should have rejected it"
                );
            }
            Err(CodegenError::Unsupported(_)) => {
                // Expected today: the scan fallback also refuses
                // multi-table LEFT, so the whole codegen layer bubbles
                // up Unsupported and the statement runs through the
                // connection-level interpreter.
            }
            Err(other) => {
                unreachable!(
                    "non-terminal LEFT JOIN must be rejected via \
                     Unsupported, got {other:?}"
                );
            }
        }
    }

    fn test_schema_multi_join_composite_unique_prefix_lookup() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "messages".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("conversation_id", 'D', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "conversations".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("tenant_id", 'D', false),
                    ColumnInfo::basic("title", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "agents".to_owned(),
                root_page: 4,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("tenant_id", 'D', false),
                    ColumnInfo::basic("slug", 'B', false),
                    ColumnInfo::basic("label", 'B', false),
                ],
                indexes: vec![IndexSchema {
                    name: "agents_tenant_slug_unique".to_owned(),
                    root_page: 5,
                    columns: vec!["tenant_id".to_owned(), "slug".to_owned()],
                    key_expressions: vec!["tenant_id".to_owned(), "slug".to_owned()],
                    key_sort_directions: vec![],
                    where_clause: None,
                    is_unique: true,
                    key_collations: vec![],
                    conflict_action: None,
                }],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn composite_unique_prefix_multi_join_stmt() -> SelectStatement {
        let on_m_c = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("m", "conversation_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(ColumnRef::qualified("c", "id"), Span::ZERO)),
            span: Span::ZERO,
        };
        let on_c_a = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("c", "tenant_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(
                ColumnRef::qualified("a", "tenant_id"),
                Span::ZERO,
            )),
            span: Span::ZERO,
        };
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("m", "id"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("a", "label"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("messages"),
                            alias: Some("m".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("conversations"),
                                    alias: Some("c".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_m_c)),
                            },
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("agents"),
                                    alias: Some("a".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_c_a)),
                            },
                        ],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    #[test]
    fn test_codegen_multi_join_rejects_composite_unique_prefix_lookup() {
        let stmt = composite_unique_prefix_multi_join_stmt();
        let schema = test_schema_multi_join_composite_unique_prefix_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert!(
            rewind_count >= 2,
            "joining on the leftmost column of UNIQUE(tenant_id, slug) is not a \
             single-row lookup; the multi-join fast path must be rejected"
        );
    }

    fn test_schema_multi_join_prefers_unique_single_column_lookup() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "messages".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("conversation_id", 'D', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "conversations".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("tenant_id", 'D', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "agents".to_owned(),
                root_page: 4,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("tenant_id", 'D', false),
                    ColumnInfo::basic("label", 'B', false),
                ],
                indexes: vec![
                    IndexSchema {
                        name: "agents_tenant_idx".to_owned(),
                        root_page: 5,
                        columns: vec!["tenant_id".to_owned()],
                        key_expressions: vec!["tenant_id".to_owned()],
                        key_sort_directions: vec![],
                        where_clause: None,
                        is_unique: false,
                        key_collations: vec![],
                        conflict_action: None,
                    },
                    IndexSchema {
                        name: "agents_tenant_unique".to_owned(),
                        root_page: 6,
                        columns: vec!["tenant_id".to_owned()],
                        key_expressions: vec!["tenant_id".to_owned()],
                        key_sort_directions: vec![],
                        where_clause: None,
                        is_unique: true,
                        key_collations: vec![],
                        conflict_action: None,
                    },
                ],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn test_schema_multi_join_prefers_ascending_unique_lookup() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "messages".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("conversation_id", 'D', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "conversations".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("tenant_id", 'D', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "agents".to_owned(),
                root_page: 4,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("tenant_id", 'D', false),
                    ColumnInfo::basic("label", 'B', false),
                ],
                indexes: vec![
                    IndexSchema {
                        name: "agents_tenant_unique_desc".to_owned(),
                        root_page: 5,
                        columns: vec!["tenant_id".to_owned()],
                        key_expressions: vec!["tenant_id".to_owned()],
                        key_sort_directions: vec![SortDirection::Desc],
                        where_clause: None,
                        is_unique: true,
                        key_collations: vec![],
                        conflict_action: None,
                    },
                    IndexSchema {
                        name: "agents_tenant_unique_asc".to_owned(),
                        root_page: 6,
                        columns: vec!["tenant_id".to_owned()],
                        key_expressions: vec!["tenant_id".to_owned()],
                        key_sort_directions: vec![],
                        where_clause: None,
                        is_unique: true,
                        key_collations: vec![],
                        conflict_action: None,
                    },
                ],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn unique_single_column_lookup_multi_join_stmt() -> SelectStatement {
        let on_m_c = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("m", "conversation_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(ColumnRef::qualified("c", "id"), Span::ZERO)),
            span: Span::ZERO,
        };
        let on_c_a = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("c", "tenant_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(
                ColumnRef::qualified("a", "tenant_id"),
                Span::ZERO,
            )),
            span: Span::ZERO,
        };
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("m", "id"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("a", "label"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("messages"),
                            alias: Some("m".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("conversations"),
                                    alias: Some("c".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_m_c)),
                            },
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("agents"),
                                    alias: Some("a".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_c_a)),
                            },
                        ],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    #[test]
    fn test_codegen_multi_join_uses_unique_lookup_even_if_nonunique_sibling_comes_first() {
        let stmt = unique_single_column_lookup_multi_join_stmt();
        let schema = test_schema_multi_join_prefers_unique_single_column_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert_eq!(
            rewind_count, 1,
            "a qualifying single-column UNIQUE lookup should keep the multi-join fast path enabled \
             even if a non-unique sibling index appears first"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "the multi-join fast path should still seek into the qualifying unique index"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::IdxRowid),
            "the multi-join fast path should fetch rowids from the qualifying unique index"
        );
    }

    #[test]
    fn test_codegen_multi_join_skips_descending_unique_lookup_sibling() {
        let stmt = unique_single_column_lookup_multi_join_stmt();
        let schema = test_schema_multi_join_prefers_ascending_unique_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(&op.p4, P4::Index(name) if name == "agents_tenant_unique_asc")),
            "multi-join lookup should skip descending unique siblings and open an ascending direct-lookup index"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(&op.p4, P4::Index(name) if name == "agents_tenant_unique_desc")),
            "multi-join lookup must not drive the fast path with a descending unique index"
        );
    }

    fn test_schema_multi_join_prefers_collation_matching_unique_lookup() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "messages".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("conversation_id", 'D', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "conversations".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("tenant_name", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "agents".to_owned(),
                root_page: 4,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo {
                        collation: Some("NOCASE".to_owned()),
                        ..ColumnInfo::basic("tenant_name", 'B', false)
                    },
                    ColumnInfo::basic("label", 'B', false),
                ],
                indexes: vec![
                    IndexSchema {
                        name: "agents_tenant_unique_binary".to_owned(),
                        root_page: 5,
                        columns: vec!["tenant_name".to_owned()],
                        key_expressions: vec!["tenant_name".to_owned()],
                        key_sort_directions: vec![],
                        where_clause: None,
                        is_unique: true,
                        key_collations: vec![],
                        conflict_action: None,
                    },
                    IndexSchema {
                        name: "agents_tenant_unique_nocase".to_owned(),
                        root_page: 6,
                        columns: vec!["tenant_name".to_owned()],
                        key_expressions: vec!["tenant_name".to_owned()],
                        key_sort_directions: vec![],
                        where_clause: None,
                        is_unique: true,
                        key_collations: vec![Some("NOCASE".to_owned())],
                        conflict_action: None,
                    },
                ],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn test_schema_single_join_prefers_collation_matching_lookup() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "customers".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("name", 'B', false),
                    ColumnInfo::basic("region", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "orders".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo {
                        collation: Some("NOCASE".to_owned()),
                        ..ColumnInfo::basic("region", 'B', false)
                    },
                    ColumnInfo::basic("amount", 'E', false),
                ],
                indexes: vec![
                    IndexSchema {
                        name: "idx_orders_region_binary".to_owned(),
                        root_page: 4,
                        columns: vec!["region".to_owned()],
                        key_expressions: vec!["region".to_owned()],
                        key_sort_directions: vec![],
                        where_clause: None,
                        is_unique: false,
                        key_collations: vec![],
                        conflict_action: None,
                    },
                    IndexSchema {
                        name: "idx_orders_region_nocase".to_owned(),
                        root_page: 5,
                        columns: vec!["region".to_owned()],
                        key_expressions: vec!["region".to_owned()],
                        key_sort_directions: vec![],
                        where_clause: None,
                        is_unique: false,
                        key_collations: vec![Some("NOCASE".to_owned())],
                        conflict_action: None,
                    },
                ],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn test_schema_single_join_rejects_composite_lookup_index() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "customers".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("name", 'B', false),
                    ColumnInfo::basic("region", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "orders".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("region", 'B', false),
                    ColumnInfo::basic("amount", 'E', false),
                ],
                indexes: vec![IndexSchema {
                    name: "idx_orders_region_amount".to_owned(),
                    root_page: 4,
                    columns: vec!["region".to_owned(), "amount".to_owned()],
                    key_expressions: vec!["region".to_owned(), "amount".to_owned()],
                    key_sort_directions: vec![],
                    where_clause: None,
                    is_unique: false,
                    key_collations: vec![],
                    conflict_action: None,
                }],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn test_schema_single_join_prefers_ascending_lookup_index() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "customers".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("name", 'B', false),
                    ColumnInfo::basic("region", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "orders".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("region", 'B', false),
                    ColumnInfo::basic("amount", 'E', false),
                ],
                indexes: vec![
                    IndexSchema {
                        name: "idx_orders_region_desc".to_owned(),
                        root_page: 4,
                        columns: vec!["region".to_owned()],
                        key_expressions: vec!["region".to_owned()],
                        key_sort_directions: vec![SortDirection::Desc],
                        where_clause: None,
                        is_unique: false,
                        key_collations: vec![],
                        conflict_action: None,
                    },
                    IndexSchema {
                        name: "idx_orders_region_asc".to_owned(),
                        root_page: 5,
                        columns: vec!["region".to_owned()],
                        key_expressions: vec!["region".to_owned()],
                        key_sort_directions: vec![],
                        where_clause: None,
                        is_unique: false,
                        key_collations: vec![],
                        conflict_action: None,
                    },
                ],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn collation_matching_single_join_lookup_stmt() -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("c", "name"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("o", "amount"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("customers"),
                            alias: Some("c".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![fsqlite_ast::JoinClause {
                            join_type: fsqlite_ast::JoinType {
                                kind: fsqlite_ast::JoinKind::Inner,
                                natural: false,
                            },
                            table: TableOrSubquery::Table {
                                name: QualifiedName::bare("orders"),
                                alias: Some("o".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            constraint: Some(fsqlite_ast::JoinConstraint::On(Expr::BinaryOp {
                                left: Box::new(Expr::Column(
                                    ColumnRef::qualified("c", "region"),
                                    Span::ZERO,
                                )),
                                op: AstBinaryOp::Eq,
                                right: Box::new(Expr::Column(
                                    ColumnRef::qualified("o", "region"),
                                    Span::ZERO,
                                )),
                                span: Span::ZERO,
                            })),
                        }],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    fn collation_matching_grouped_join_lookup_stmt() -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("c", "name"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "count".to_owned(),
                                args: FunctionArgs::Star,
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "sum".to_owned(),
                                args: FunctionArgs::List(vec![Expr::Column(
                                    ColumnRef::qualified("o", "amount"),
                                    Span::ZERO,
                                )]),
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("customers"),
                            alias: Some("c".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![fsqlite_ast::JoinClause {
                            join_type: fsqlite_ast::JoinType {
                                kind: fsqlite_ast::JoinKind::Inner,
                                natural: false,
                            },
                            table: TableOrSubquery::Table {
                                name: QualifiedName::bare("orders"),
                                alias: Some("o".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            constraint: Some(fsqlite_ast::JoinConstraint::On(Expr::BinaryOp {
                                left: Box::new(Expr::Column(
                                    ColumnRef::qualified("c", "region"),
                                    Span::ZERO,
                                )),
                                op: AstBinaryOp::Eq,
                                right: Box::new(Expr::Column(
                                    ColumnRef::qualified("o", "region"),
                                    Span::ZERO,
                                )),
                                span: Span::ZERO,
                            })),
                        }],
                    }),
                    where_clause: None,
                    group_by: vec![Expr::Column(ColumnRef::qualified("c", "name"), Span::ZERO)],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    fn collation_matching_unique_single_column_lookup_multi_join_stmt() -> SelectStatement {
        let on_m_c = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("m", "conversation_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(ColumnRef::qualified("c", "id"), Span::ZERO)),
            span: Span::ZERO,
        };
        let on_c_a = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("c", "tenant_name"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(
                ColumnRef::qualified("a", "tenant_name"),
                Span::ZERO,
            )),
            span: Span::ZERO,
        };
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("m", "id"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("a", "label"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("messages"),
                            alias: Some("m".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("conversations"),
                                    alias: Some("c".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_m_c)),
                            },
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("agents"),
                                    alias: Some("a".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_c_a)),
                            },
                        ],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    /// Oracle reconciliation (sqlite3 3.46.1): a comparison `A = B` takes its
    /// collation from the LEFT operand, so a declared-NOCASE column on the
    /// RIGHT of a join predicate does NOT drive NOCASE index selection —
    /// SQLite uses the left column's (BINARY) collation and rejects a NOCASE
    /// sibling index (verified via `EXPLAIN QUERY PLAN`). Commit 6133ccd4a
    /// correctly switched codegen to that left-operand rule; these fixtures put
    /// the NOCASE column on the right, so swap the ON operands to make the
    /// declared-NOCASE column the dominant (left) side while preserving the
    /// plain `Column = Column` join shape the grouped/join fast paths match.
    fn make_join_predicate_nocase_dominant(stmt: &mut SelectStatement, join_index: usize) {
        let SelectCore::Select {
            from: Some(from_clause),
            ..
        } = &mut stmt.body.select
        else {
            unreachable!("fixture should include a FROM clause");
        };
        let Some(fsqlite_ast::JoinConstraint::On(Expr::BinaryOp { left, right, .. })) =
            from_clause.joins[join_index].constraint.as_mut()
        else {
            unreachable!("fixture join should carry an ON equality");
        };
        std::mem::swap(left, right);
    }

    #[test]
    fn test_codegen_multi_join_prefers_collation_matching_unique_lookup() {
        let mut stmt = collation_matching_unique_single_column_lookup_multi_join_stmt();
        make_join_predicate_nocase_dominant(&mut stmt, 1);
        let schema = test_schema_multi_join_prefers_collation_matching_unique_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert_eq!(
            rewind_count, 1,
            "a matching-collation unique index should keep the multi-join fast path enabled even if a mismatched unique sibling appears first"
        );
        let lookup_cmp = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Ne)
            .expect("multi-join unique lookup should recheck the landed index key");
        assert_eq!(lookup_cmp.p4, P4::Collation("NOCASE".to_owned()));
    }

    fn test_schema_multi_join_prefers_nocase_unique_lookup() -> Vec<TableSchema> {
        vec![
            TableSchema {
                name: "messages".to_owned(),
                root_page: 2,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("conversation_id", 'D', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "conversations".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo::basic("tenant_name", 'B', false),
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
            TableSchema {
                name: "agents".to_owned(),
                root_page: 4,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo {
                        collation: Some("NOCASE".to_owned()),
                        ..ColumnInfo::basic("tenant_name", 'B', false)
                    },
                    ColumnInfo::basic("label", 'B', false),
                ],
                indexes: vec![
                    IndexSchema {
                        name: "agents_tenant_idx".to_owned(),
                        root_page: 5,
                        columns: vec!["tenant_name".to_owned()],
                        key_expressions: vec!["tenant_name".to_owned()],
                        key_sort_directions: vec![],
                        where_clause: None,
                        is_unique: false,
                        key_collations: vec![],
                        conflict_action: None,
                    },
                    IndexSchema {
                        name: "agents_tenant_unique_nocase".to_owned(),
                        root_page: 6,
                        columns: vec!["tenant_name".to_owned()],
                        key_expressions: vec!["tenant_name".to_owned()],
                        key_sort_directions: vec![],
                        where_clause: None,
                        is_unique: true,
                        key_collations: vec![Some("NOCASE".to_owned())],
                        conflict_action: None,
                    },
                ],
                strict: false,
                without_rowid: false,
                primary_key_constraints: Vec::new(),
                foreign_keys: Vec::new(),
                check_constraints: Vec::new(),
            },
        ]
    }

    fn nocase_unique_single_column_lookup_multi_join_stmt() -> SelectStatement {
        let on_m_c = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("m", "conversation_id"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(ColumnRef::qualified("c", "id"), Span::ZERO)),
            span: Span::ZERO,
        };
        let on_c_a = Expr::BinaryOp {
            left: Box::new(Expr::Column(
                ColumnRef::qualified("c", "tenant_name"),
                Span::ZERO,
            )),
            op: AstBinaryOp::Eq,
            right: Box::new(Expr::Column(
                ColumnRef::qualified("a", "tenant_name"),
                Span::ZERO,
            )),
            span: Span::ZERO,
        };
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("m", "id"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("a", "label"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("messages"),
                            alias: Some("m".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("conversations"),
                                    alias: Some("c".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_m_c)),
                            },
                            fsqlite_ast::JoinClause {
                                join_type: fsqlite_ast::JoinType {
                                    kind: fsqlite_ast::JoinKind::Inner,
                                    natural: false,
                                },
                                table: TableOrSubquery::Table {
                                    name: QualifiedName::bare("agents"),
                                    alias: Some("a".to_owned()),
                                    index_hint: None,
                                    time_travel: None,
                                },
                                constraint: Some(fsqlite_ast::JoinConstraint::On(on_c_a)),
                            },
                        ],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    #[test]
    fn test_codegen_multi_join_unique_lookup_threads_nocase_collation() {
        let mut stmt = nocase_unique_single_column_lookup_multi_join_stmt();
        make_join_predicate_nocase_dominant(&mut stmt, 1);
        let schema = test_schema_multi_join_prefers_nocase_unique_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();
        assert_eq!(
            rewind_count, 1,
            "the restored multi-join unique lookup fast path should stay enabled for NOCASE indexes"
        );

        let lookup_cmp = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Ne)
            .expect("multi-join unique lookup should recheck the landed index key");
        assert_eq!(lookup_cmp.p4, P4::Collation("NOCASE".to_owned()));
    }

    #[test]
    fn test_codegen_multi_join_rejects_unique_lookup_with_collation_mismatch() {
        let mut stmt = nocase_unique_single_column_lookup_multi_join_stmt();
        let SelectCore::Select {
            from: Some(from_clause),
            ..
        } = &mut stmt.body.select
        else {
            unreachable!("fixture should include a FROM clause");
        };
        let joins = &mut from_clause.joins;
        let Some(fsqlite_ast::JoinConstraint::On(Expr::BinaryOp { left, .. })) =
            joins[1].constraint.as_mut()
        else {
            unreachable!("fixture should include the second ON equality");
        };
        let original_left =
            std::mem::replace(left, Box::new(Expr::Literal(Literal::Null, Span::ZERO)));
        **left = Expr::Collate {
            expr: original_left,
            collation: "BINARY".to_owned(),
            span: Span::ZERO,
        };

        let schema = test_schema_multi_join_prefers_nocase_unique_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let result = codegen_select(&mut b, &stmt, &schema, &ctx);

        match result {
            Ok(()) => {
                let prog = b.finish().unwrap();
                let rewind_count = prog
                    .ops()
                    .iter()
                    .filter(|op| op.opcode == Opcode::Rewind)
                    .count();
                assert!(
                    rewind_count >= 2,
                    "a COLLATE BINARY join must not take the NOCASE unique-index fast path"
                );
                assert!(
                    !prog.ops().iter().any(|op| op.opcode == Opcode::IdxRowid),
                    "collation-mismatched joins should fall back to the scan path instead of using direct index lookups"
                );
            }
            Err(CodegenError::Unsupported(_)) => {
                // Also acceptable today: once the fast path is rejected, the
                // fallback JOIN codegen still refuses explicit COLLATE in the
                // ON clause and lets the connection-level interpreter handle it.
            }
            Err(other) => unreachable!(
                "collation-mismatched join should reject the unique-index fast path, got {other:?}"
            ),
        }
    }

    #[test]
    fn test_codegen_grouped_inner_join_uses_index_lookup_plan() {
        let stmt = grouped_join_count_sum_index_lookup_stmt();
        let schema = test_schema_with_join_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert_eq!(
            rewind_count, 1,
            "grouped lookup join should only rewind the outer table"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "grouped lookup join should seek into the right-side index"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::IdxRowid),
            "grouped lookup join should fetch rowids from the right-side index"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::SorterInsert),
            "grouped lookup join should still materialize rows for grouped aggregation"
        );
    }

    #[test]
    fn test_codegen_complex_select_real_path_evidence_stays_storage_only() {
        let cases = [
            (
                "grouped indexed lookup join",
                grouped_join_count_sum_index_lookup_stmt(),
                Opcode::SeekGE,
            ),
            (
                "grouped rowid lookup join",
                grouped_join_count_sum_rowid_lookup_stmt(),
                Opcode::SeekRowid,
            ),
        ];

        for (case_name, stmt, expected_probe) in cases {
            let schema = test_schema_with_join_lookup();
            let ctx = CodegenContext::default();
            let mut b = ProgramBuilder::new();
            codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
            let prog = b.finish().unwrap();

            assert!(
                !prog.requires_attached_memdb(),
                "{case_name} should stay on storage cursors for backend-identity replay evidence; got {:?}",
                opcode_sequence(&prog)
            );
            assert!(
                prog.ops().iter().any(|op| op.opcode == expected_probe),
                "{case_name} should retain its direct probe opcode"
            );
            assert!(
                prog.ops()
                    .iter()
                    .any(|op| op.opcode == Opcode::SorterInsert),
                "{case_name} should still use the sorter path for grouped aggregation"
            );
            assert!(
                !prog.ops().iter().any(|op| matches!(
                    op.opcode,
                    Opcode::OpenEphemeral
                        | Opcode::OpenAutoindex
                        | Opcode::OpenPseudo
                        | Opcode::OpenDup
                        | Opcode::ReopenIdx
                )),
                "{case_name} should not introduce cursor opcodes that force MemDatabase attachment"
            );
        }
    }

    #[test]
    fn test_codegen_single_join_prefers_collation_matching_lookup_index() {
        let mut stmt = collation_matching_single_join_lookup_stmt();
        make_join_predicate_nocase_dominant(&mut stmt, 0);
        let schema = test_schema_single_join_prefers_collation_matching_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert_eq!(
            rewind_count, 1,
            "single-join lookup should keep its fast path when a later sibling index matches the join collation"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(&op.p4, P4::Index(name) if name == "idx_orders_region_nocase")),
            "single-join lookup should open the collation-matching sibling index"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::Ne && op.p4 == P4::Collation("NOCASE".to_owned())),
            "single-join lookup should recheck landed keys with the join collation"
        );
    }

    #[test]
    fn test_codegen_single_join_rejects_composite_lookup_index() {
        let stmt = collation_matching_single_join_lookup_stmt();
        let schema = test_schema_single_join_rejects_composite_lookup_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert_eq!(
            rewind_count, 2,
            "single-join lookup fast path must reject composite indexes because it only emits a single-key seek record"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(&op.p4, P4::Index(name) if name == "idx_orders_region_amount")),
            "falling back to the generic nested-loop join must avoid opening the composite sibling index as a direct lookup cursor"
        );
    }

    #[test]
    fn test_codegen_single_join_skips_descending_lookup_sibling() {
        let stmt = collation_matching_single_join_lookup_stmt();
        let schema = test_schema_single_join_prefers_ascending_lookup_index();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(&op.p4, P4::Index(name) if name == "idx_orders_region_asc")),
            "single-join lookup should skip descending siblings and open an ascending direct-lookup index"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(&op.p4, P4::Index(name) if name == "idx_orders_region_desc")),
            "single-join lookup must not drive the fast path with a descending index"
        );
    }

    #[test]
    fn test_codegen_grouped_join_prefers_collation_matching_lookup_index() {
        let mut stmt = collation_matching_grouped_join_lookup_stmt();
        make_join_predicate_nocase_dominant(&mut stmt, 0);
        let schema = test_schema_single_join_prefers_collation_matching_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert_eq!(
            rewind_count, 1,
            "grouped lookup join should keep its fast path when a later sibling index matches the join collation"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(&op.p4, P4::Index(name) if name == "idx_orders_region_nocase")),
            "grouped lookup join should open the collation-matching sibling index"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::Ne && op.p4 == P4::Collation("NOCASE".to_owned())),
            "grouped lookup join should recheck landed keys with the join collation"
        );
    }

    #[test]
    fn test_codegen_grouped_inner_join_uses_rowid_lookup_plan() {
        let stmt = grouped_join_count_sum_rowid_lookup_stmt();
        let schema = test_schema_with_join_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();

        assert_eq!(
            rewind_count, 1,
            "grouped rowid lookup join should only rewind the outer table"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekRowid),
            "grouped rowid lookup join should seek the right table by rowid"
        );
        assert!(
            !prog.ops().iter().any(|op| op.opcode == Opcode::SeekGE),
            "grouped rowid lookup join should not use a secondary-index probe"
        );
    }

    #[test]
    fn test_extract_count_indexed_exists_target_matches_indexed_outer_column() {
        let stmt = agg_count_star_exists_rowid_probe();
        let schema = test_schema_with_index_and_subquery_source();
        let SelectCore::Select {
            from, where_clause, ..
        } = &stmt.body.select
        else {
            unreachable!("expected SELECT core");
        };
        let FromClause { source, .. } = from.as_ref().expect("outer FROM should exist");
        let TableOrSubquery::Table { alias, .. } = source else {
            unreachable!("expected plain outer table");
        };
        let table = find_table(&schema, "t").expect("outer table should exist");
        let Expr::Exists { subquery, .. } =
            where_clause.as_deref().expect("outer WHERE should exist")
        else {
            unreachable!("expected EXISTS predicate");
        };
        let SelectCore::Select {
            from: Some(sub_from),
            where_clause: Some(sub_where),
            ..
        } = &subquery.body.select
        else {
            unreachable!("expected simple subquery shape");
        };
        let TableOrSubquery::Table {
            name: sub_name,
            alias: sub_alias,
            ..
        } = &sub_from.source
        else {
            unreachable!("expected plain inner table");
        };
        let sub_table = find_table(&schema, &sub_name.name).expect("inner table should exist");
        let (probe_expr, residual_terms) =
            extract_exists_rowid_probe(sub_where, sub_table, sub_alias.as_deref())
                .expect("rowid probe should match");

        assert_eq!(
            column_name(probe_expr, table, alias.as_deref()).as_deref(),
            Some("b"),
            "outer probe should resolve to the indexed outer column"
        );
        assert_eq!(
            residual_terms.len(),
            1,
            "fixture should leave exactly one inner residual term"
        );
        assert!(
            table.index_for_column("b").is_some(),
            "outer fixture should expose an index on b"
        );

        let extracted = extract_count_indexed_exists_target(
            where_clause.as_deref(),
            table,
            alias.as_deref(),
            &schema,
        )
        .expect("indexed EXISTS target should match");

        assert_eq!(extracted.0.name, "idx_t_b");
        match extracted.1 {
            CountIndexedInTarget::ProbeSource(probe_source) => {
                assert!(matches!(probe_source.value, InProbeValue::Rowid));
            }
            CountIndexedInTarget::MaterializedProbeSource(_) => {
                unreachable!("EXISTS target should lower to a direct probe source");
            }
            CountIndexedInTarget::List(_) => {
                unreachable!("EXISTS target should lower to a probe source");
            }
        }
    }

    #[test]
    fn test_codegen_scalar_subquery_uses_rowid_probe_when_available() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Subquery(
                                Box::new(SelectStatement {
                                    with: None,
                                    body: SelectBody {
                                        select: SelectCore::Select {
                                            distinct: Distinctness::All,
                                            columns: vec![ResultColumn::Expr {
                                                expr: Expr::Column(
                                                    ColumnRef::qualified("s", "b"),
                                                    Span::ZERO,
                                                ),
                                                alias: None,
                                            }],
                                            from: Some(FromClause {
                                                source: TableOrSubquery::Table {
                                                    name: QualifiedName::bare("s"),
                                                    alias: Some("s".to_owned()),
                                                    index_hint: None,
                                                    time_travel: None,
                                                },
                                                joins: vec![],
                                            }),
                                            where_clause: Some(Box::new(Expr::BinaryOp {
                                                left: Box::new(Expr::Column(
                                                    ColumnRef::qualified("s", "rowid"),
                                                    Span::ZERO,
                                                )),
                                                op: AstBinaryOp::Eq,
                                                right: Box::new(Expr::Column(
                                                    ColumnRef::qualified("t", "a"),
                                                    Span::ZERO,
                                                )),
                                                span: Span::ZERO,
                                            })),
                                            group_by: vec![],
                                            having: None,
                                            windows: vec![],
                                        },
                                        compounds: vec![],
                                    },
                                    order_by: vec![],
                                    limit: None,
                                }),
                                Span::ZERO,
                            ),
                            alias: None,
                        },
                    ],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SeekRowid),
            "scalar subquery on inner rowid should probe directly with SeekRowid"
        );
        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();
        assert_eq!(
            rewind_count, 1,
            "only the outer scan should rewind when scalar subquery lowers to a direct rowid probe"
        );
        let open_read_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::OpenRead)
            .count();
        assert_eq!(
            open_read_count, 2,
            "scalar subquery should open the inner table once alongside the outer scan"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Once),
            "scalar subquery should hoist its inner cursor open behind Once"
        );
    }

    #[test]
    fn test_codegen_scalar_count_star_subquery_uses_count_opcode() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Subquery(Box::new(agg_count_star("s")), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Count),
            "scalar COUNT(*) subqueries should use the Count opcode directly"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::AggStep | Opcode::AggFinal)),
            "scalar COUNT(*) subqueries should bypass generic aggregate opcodes"
        );
        let rewind_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Rewind)
            .count();
        assert_eq!(
            rewind_count, 1,
            "the inner COUNT(*) subquery should not rewind/scan when Count is available"
        );
    }

    #[test]
    fn test_codegen_scalar_count_star_subquery_with_where_uses_counter_loop() {
        let count_subquery = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("s"),
                            alias: Some("s".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![],
                    }),
                    where_clause: Some(Box::new(Expr::BinaryOp {
                        left: Box::new(Expr::Column(ColumnRef::qualified("s", "b"), Span::ZERO)),
                        op: AstBinaryOp::Le,
                        right: Box::new(Expr::Literal(Literal::Integer(5), Span::ZERO)),
                        span: Span::ZERO,
                    })),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Subquery(Box::new(count_subquery), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::AddImm),
            "scalar COUNT(*) subqueries with WHERE should use a direct counter loop"
        );
        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::AggStep | Opcode::AggFinal)),
            "scalar COUNT(*) subqueries with WHERE should bypass generic aggregate opcodes"
        );
    }

    #[test]
    fn test_codegen_select_correlated_in_subquery_value_expr_does_not_use_once_materialization() {
        let where_expr = Expr::In {
            expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
            set: InSet::Subquery(Box::new(SelectStatement {
                with: None,
                body: SelectBody {
                    select: SelectCore::Select {
                        distinct: Distinctness::All,
                        columns: vec![ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::qualified("t", "a"), Span::ZERO),
                            alias: None,
                        }],
                        from: Some(from_table("s")),
                        where_clause: Some(Box::new(Expr::BinaryOp {
                            left: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                            op: AstBinaryOp::Le,
                            right: Box::new(Expr::Literal(Literal::Integer(5), Span::ZERO)),
                            span: Span::ZERO,
                        })),
                        group_by: vec![],
                        having: None,
                        windows: vec![],
                    },
                    compounds: vec![],
                },
                order_by: vec![],
                limit: None,
            })),
            not: false,
            span: Span::ZERO,
        };
        let stmt = simple_select(&["a"], "t", Some(Box::new(where_expr)));

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            !prog
                .ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenAutoindex),
            "IN subqueries whose selected probe values depend on outer-row values must not materialize once"
        );
    }

    #[test]
    fn test_in_probe_source_reference_detection_considers_secondary_outer_scan() {
        let schema = test_schema_with_subquery_source();
        let outer_table = &schema[0];
        let probe_table = &schema[1];
        let secondary_table = TableSchema {
            name: "u".to_owned(),
            root_page: 4,
            columns: vec![ColumnInfo::basic("b", 'd', false)],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        };
        let secondaries = [SecondaryScan {
            cursor: 1,
            table: &secondary_table,
            table_alias: Some("u"),
            register_base: None,
        }];
        let scan_ctx = ScanCtx {
            cursor: 0,
            table: outer_table,
            table_alias: Some("t"),
            schema: Some(&schema),
            register_base: None,
            secondaries: &secondaries,
        };
        let probe_source = InProbeSource {
            table: probe_table,
            table_alias: Some("s"),
            where_clause: Some(&Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::qualified("u", "b"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(Expr::Column(ColumnRef::qualified("s", "b"), Span::ZERO)),
                span: Span::ZERO,
            }),
            value: InProbeValue::FirstColumn,
        };

        assert!(
            in_probe_source_references_outer_scan(&probe_source, &scan_ctx),
            "secondary outer scan references must keep IN probe sources on the correlated path"
        );
    }

    // === Test 21: SELECT sum(col) ===
    #[test]
    fn test_codegen_select_sum_col() {
        let stmt = agg_func_col("sum", "a", "t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Should have Column (read arg) + AggStep in the loop.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::OpenRead,
                Opcode::Rewind,
                Opcode::Column,
                Opcode::AggStep,
                Opcode::Next,
                Opcode::AggFinal,
                Opcode::ResultRow,
            ]
        ));

        // AggStep p5 = 1 (one argument).
        let step = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::AggStep)
            .unwrap();
        assert_eq!(step.p5, 1, "sum(col) should have p5=1 (one arg)");

        // AggFinal P4 should be FuncName("SUM").
        let fin = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::AggFinal)
            .unwrap();
        assert!(
            matches!(&fin.p4, P4::FuncName(f) if f == "SUM"),
            "AggFinal P4 should be FuncName(SUM), got {:?}",
            fin.p4
        );
    }

    // === Test 22: SELECT count(*), sum(a) ===
    #[test]
    fn test_codegen_select_multiple_aggregates() {
        let stmt = agg_count_star_and_sum("a", "t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Count),
            "COUNT(*) in the COUNT+SUM fast path should use Count directly"
        );

        // COUNT(*) should bypass AggStep/AggFinal; SUM(a) still needs one.
        let step_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggStep)
            .count();
        assert_eq!(step_count, 1, "COUNT(*) + SUM(a) should only step SUM(a)");

        let final_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggFinal)
            .count();
        assert_eq!(
            final_count, 1,
            "COUNT(*) + SUM(a) should only finalize SUM(a)"
        );

        // ResultRow should cover 2 columns.
        let rr = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::ResultRow)
            .unwrap();
        assert_eq!(rr.p2, 2, "two aggregate columns");

        // The remaining aggregate opcodes should belong to SUM(a).
        let steps: Vec<_> = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggStep)
            .collect();
        assert!(matches!(&steps[0].p4, P4::FuncName(f) if f == "SUM"));
    }

    #[test]
    fn test_custom_aggregate_keys_preserve_max_arity_resolution() {
        let unary = FunctionArgs::List(vec![Expr::Literal(Literal::Integer(1), Span::ZERO)]);
        let binary = FunctionArgs::List(vec![
            Expr::Literal(Literal::Integer(1), Span::ZERO),
            Expr::Literal(Literal::Integer(2), Span::ZERO),
        ]);
        let ternary = FunctionArgs::List(vec![
            Expr::Literal(Literal::Integer(1), Span::ZERO),
            Expr::Literal(Literal::Integer(2), Span::ZERO),
            Expr::Literal(Literal::Integer(3), Span::ZERO),
        ]);

        assert!(is_aggregate_function_call("max", &unary));
        assert!(
            !is_aggregate_function_call("max", &binary),
            "the built-in two-argument max() form is scalar"
        );

        with_connection_function_context(
            vec![("max".to_owned(), FunctionArity::exact(1))],
            true,
            true,
            || {
                assert!(is_aggregate_function_call("max", &unary));
                assert!(
                    !is_aggregate_function_call("max", &binary),
                    "a custom max/1 must not change max/2"
                );
            },
        );
        with_connection_function_context(
            vec![("max".to_owned(), FunctionArity::variadic(0, None))],
            true,
            true,
            || {
                assert!(
                    is_aggregate_function_call("max", &unary),
                    "the exact built-in max/1 outranks the variadic registration but remains aggregate"
                );
                assert!(
                    is_aggregate_function_call("max", &binary),
                    "a variadic custom max replaces the scalar-shaped max/2 call"
                );
            },
        );
        with_connection_function_context(
            vec![("max".to_owned(), FunctionArity::variadic(2, Some(2)))],
            true,
            true,
            || {
                assert!(is_aggregate_function_call("max", &binary));
                assert!(
                    !is_aggregate_function_call("max", &ternary),
                    "a bounded variadic max/2 aggregate must not capture scalar max/3"
                );
            },
        );
        with_connection_function_context(
            vec![("max".to_owned(), FunctionArity::exact(2))],
            true,
            true,
            || {
                assert!(is_aggregate_function_call("max", &binary));
            },
        );
        with_connection_function_context(
            vec![("custom".to_owned(), FunctionArity::exact(1))],
            true,
            true,
            || {
                assert!(is_aggregate_function_call("custom", &unary));
                assert!(
                    !is_aggregate_function_call("custom", &binary),
                    "a fixed-arity custom aggregate must not capture a scalar overload"
                );
            },
        );
        with_connection_function_context(
            vec![("custom".to_owned(), FunctionArity::variadic(0, None))],
            true,
            true,
            || {
                assert!(is_aggregate_function_call("custom", &unary));
                assert!(is_aggregate_function_call("custom", &binary));
            },
        );

        assert!(
            !is_aggregate_function_call("max", &binary),
            "the codegen function context must restore its prior arity map"
        );
    }

    #[test]
    fn custom_builtin_aggregate_overrides_decline_algebraic_codegen_shortcuts() {
        let compile = |stmt: &SelectStatement,
                       schema: &[TableSchema],
                       custom_keys: Vec<(String, FunctionArity)>| {
            with_connection_function_context(custom_keys, true, true, || {
                let mut builder = ProgramBuilder::new();
                codegen_select(&mut builder, stmt, schema, &CodegenContext::default())
                    .expect("custom aggregate fixture should compile");
                builder
                    .finish()
                    .expect("custom aggregate program should finish")
                    .ops()
                    .to_vec()
            })
        };

        let count_ops = compile(
            &agg_count_star("t"),
            &test_schema(),
            vec![("count".to_owned(), FunctionArity::exact(0))],
        );
        assert!(
            !count_ops.iter().any(|op| op.opcode == Opcode::Count),
            "custom count/0 must not use the built-in Count opcode"
        );
        assert!(
            count_ops.iter().any(|op| {
                op.opcode == Opcode::AggStep
                    && matches!(&op.p4, P4::FuncName(name) if name == "COUNT")
            }),
            "custom count/0 must flow through generic AggStep"
        );

        let count_sum_ops = compile(
            &agg_count_star_and_sum("a", "t"),
            &test_schema(),
            vec![("sum".to_owned(), FunctionArity::exact(1))],
        );
        assert!(
            !count_sum_ops.iter().any(|op| op.opcode == Opcode::Count),
            "custom sum/1 must decline COUNT+SUM fusion because the fused path \
             assumes built-in SUM semantics"
        );
        assert_eq!(
            count_sum_ops
                .iter()
                .filter(|op| op.opcode == Opcode::AggStep)
                .count(),
            2,
            "declined COUNT+SUM fusion must step both aggregates generically"
        );

        let mut scalar_stmt = simple_select(&["a"], "t", None);
        let SelectCore::Select { columns, .. } = &mut scalar_stmt.body.select else {
            unreachable!("simple_select returns a SELECT core");
        };
        columns.push(ResultColumn::Expr {
            expr: Expr::Subquery(Box::new(agg_count_star("s")), Span::ZERO),
            alias: None,
        });
        let scalar_ops = compile(
            &scalar_stmt,
            &test_schema_with_subquery_source(),
            vec![("count".to_owned(), FunctionArity::exact(0))],
        );
        assert!(
            !scalar_ops.iter().any(|op| op.opcode == Opcode::Count),
            "custom count/0 inside a scalar subquery must not use Count"
        );
        assert!(
            scalar_ops.iter().any(|op| {
                op.opcode == Opcode::AggStep
                    && matches!(&op.p4, P4::FuncName(name) if name == "COUNT")
            }),
            "custom scalar-subquery count/0 must use generic aggregate lowering"
        );
    }

    #[test]
    fn custom_count_sum_overrides_decline_grouped_algebraic_plans() {
        let table = bd_2dgf5_table();
        let bucket_stmt = select_sql("SELECT id / 10, SUM(k) FROM t GROUP BY id / 10");
        let SelectCore::Select {
            columns, group_by, ..
        } = &bucket_stmt.body.select
        else {
            assert!(test_failure(), "bucket fixture must be a SELECT core");
            return;
        };
        assert!(
            simple_group_by_rowid_bucket_sum_plan(columns, &table, None, group_by).is_some(),
            "fixture must exercise the grouped rowid-bucket SUM shortcut"
        );
        with_connection_function_context(
            vec![("sum".to_owned(), FunctionArity::exact(1))],
            true,
            true,
            || {
                assert!(
                    simple_group_by_rowid_bucket_sum_plan(columns, &table, None, group_by)
                        .is_none(),
                    "custom sum/1 must decline grouped rowid-bucket SUM algebra"
                );
            },
        );

        let join_stmt = grouped_join_count_sum_index_lookup_stmt();
        let SelectCore::Select {
            from: Some(join_from),
            ..
        } = &join_stmt.body.select
        else {
            assert!(
                test_failure(),
                "grouped join fixture must have a FROM clause"
            );
            return;
        };
        let join_schema = test_schema_with_join_lookup();
        assert!(
            grouped_inner_join_count_sum_plan(&join_stmt, join_from, &join_schema)
                .expect("baseline grouped join plan")
                .is_some(),
            "fixture must exercise the grouped inner-join COUNT+SUM shortcut"
        );
        for custom_key in [
            ("count".to_owned(), FunctionArity::exact(0)),
            ("sum".to_owned(), FunctionArity::exact(1)),
        ] {
            with_connection_function_context(vec![custom_key], true, true, || {
                assert!(
                    grouped_inner_join_count_sum_plan(&join_stmt, join_from, &join_schema)
                        .expect("custom grouped join planning")
                        .is_none(),
                    "an exact custom COUNT/0 or SUM/1 must decline grouped join algebra"
                );
            });
        }
    }

    #[test]
    fn custom_minmax_and_count_distinct_overrides_decline_leaf_plans() {
        fn aggregate_fixture(sql: &str, table: &TableSchema) -> (SelectStatement, Vec<AggColumn>) {
            let stmt = select_sql(sql);
            let SelectCore::Select { columns, .. } = &stmt.body.select else {
                assert!(test_failure(), "aggregate fixture must be a SELECT core");
                return (stmt, Vec::new());
            };
            let aggregates =
                parse_aggregate_columns(columns, table).expect("aggregate fixture should parse");
            (stmt, aggregates)
        }

        fn fixture_where(stmt: &SelectStatement) -> Option<&Expr> {
            let SelectCore::Select { where_clause, .. } = &stmt.body.select else {
                return None;
            };
            where_clause.as_deref()
        }

        fn fixture_columns(stmt: &SelectStatement) -> &[ResultColumn] {
            let SelectCore::Select { columns, .. } = &stmt.body.select else {
                return &[];
            };
            columns
        }

        let table = bd_2dgf5_table();
        let (rowid_stmt, rowid_agg) = aggregate_fixture("SELECT MAX(id) FROM t", &table);
        let (index_stmt, index_agg) = aggregate_fixture("SELECT MAX(k) FROM t", &table);
        let (_pair_stmt, pair_agg) = aggregate_fixture("SELECT MIN(k), MAX(k) FROM t", &table);
        let (range_stmt, range_agg) =
            aggregate_fixture("SELECT MAX(k) FROM t WHERE k < 10", &table);
        let (rowid_range_stmt, rowid_range_agg) =
            aggregate_fixture("SELECT MAX(id) FROM t WHERE id < 10", &table);
        let (distinct_stmt, distinct_agg) =
            aggregate_fixture("SELECT COUNT(DISTINCT k) FROM t", &table);

        let prefix_schema = test_schema_with_composite_prefix_index();
        let prefix_table = &prefix_schema[0];
        let (prefix_stmt, prefix_agg) = aggregate_fixture(
            "SELECT MAX(idx) FROM messages WHERE conversation_id = 7",
            prefix_table,
        );

        assert!(
            minmax_rowid_seek_plan(&rowid_agg).is_some(),
            "fixture must exercise the rowid MIN/MAX leaf seek"
        );
        assert!(
            minmax_index_seek_plan(&index_agg, &table).is_some(),
            "fixture must exercise the secondary-index MIN/MAX leaf seek"
        );
        assert!(
            minmax_pair_seek_plan(&pair_agg, &table).is_some(),
            "fixture must exercise the paired MIN/MAX leaf seek"
        );
        assert!(
            minmax_range_seek_plan(&range_agg, &table, None, fixture_where(&range_stmt)).is_some(),
            "fixture must exercise the bounded secondary-index MIN/MAX leaf seek"
        );
        assert!(
            minmax_rowid_range_seek_plan(
                &rowid_range_agg,
                &table,
                None,
                fixture_where(&rowid_range_stmt),
            )
            .is_some(),
            "fixture must exercise the bounded rowid MIN/MAX leaf seek"
        );
        assert!(
            minmax_prefix_seek_plan(&prefix_agg, prefix_table, None, fixture_where(&prefix_stmt),)
                .is_some(),
            "fixture must exercise the composite-prefix MIN/MAX leaf seek"
        );
        assert!(
            count_distinct_index_walk_plan(&distinct_agg, fixture_columns(&distinct_stmt), &table,)
                .is_some(),
            "fixture must exercise the COUNT(DISTINCT) index walk"
        );

        with_connection_function_context(
            vec![("max".to_owned(), FunctionArity::exact(1))],
            true,
            true,
            || {
                assert!(
                    minmax_rowid_seek_plan(&rowid_agg).is_none(),
                    "custom max/1 must decline the rowid leaf seek"
                );
                assert!(
                    minmax_index_seek_plan(&index_agg, &table).is_none(),
                    "custom max/1 must decline the secondary-index leaf seek"
                );
                assert!(
                    minmax_pair_seek_plan(&pair_agg, &table).is_none(),
                    "custom max/1 must decline the MIN/MAX pair seek"
                );
                assert!(
                    minmax_range_seek_plan(&range_agg, &table, None, fixture_where(&range_stmt),)
                        .is_none(),
                    "custom max/1 must decline the bounded secondary-index leaf seek"
                );
                assert!(
                    minmax_rowid_range_seek_plan(
                        &rowid_range_agg,
                        &table,
                        None,
                        fixture_where(&rowid_range_stmt),
                    )
                    .is_none(),
                    "custom max/1 must decline the bounded rowid leaf seek"
                );
                assert!(
                    minmax_prefix_seek_plan(
                        &prefix_agg,
                        prefix_table,
                        None,
                        fixture_where(&prefix_stmt),
                    )
                    .is_none(),
                    "custom max/1 must decline the composite-prefix leaf seek"
                );
            },
        );

        with_connection_function_context(
            vec![("count".to_owned(), FunctionArity::exact(1))],
            true,
            true,
            || {
                assert!(
                    count_distinct_index_walk_plan(
                        &distinct_agg,
                        fixture_columns(&distinct_stmt),
                        &table,
                    )
                    .is_none(),
                    "custom count/1 must decline COUNT(DISTINCT) index-walk algebra"
                );
            },
        );

        // Keep the statements live through all borrowed WHERE checks above and
        // make the deliberately no-WHERE fixtures explicit.
        assert!(fixture_where(&rowid_stmt).is_none());
        assert!(fixture_where(&index_stmt).is_none());
    }

    // === Test 22b: HAVING-only aggregate is accumulated (bd-3ew8w) ===
    #[test]
    fn test_codegen_select_having_only_aggregate_is_accumulated() {
        let stmt = agg_count_star_having_sum_gt("a", 10, "t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // COUNT(*) in SELECT + SUM(a) in HAVING must both be stepped/finalized.
        let step_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggStep)
            .count();
        assert_eq!(step_count, 2, "HAVING-only SUM(a) must emit AggStep");

        let final_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggFinal)
            .count();
        assert_eq!(final_count, 2, "HAVING-only SUM(a) must emit AggFinal");

        assert!(
            prog.ops().iter().any(
                |op| matches!(&op.p4, P4::FuncName(f) if op.opcode == Opcode::AggStep && f == "SUM")
            ),
            "expected AggStep for SUM(a) referenced only by HAVING"
        );
        assert!(
            prog.ops().iter().any(
                |op| matches!(&op.p4, P4::FuncName(f) if op.opcode == Opcode::AggFinal && f == "SUM")
            ),
            "expected AggFinal for SUM(a) referenced only by HAVING"
        );

        assert!(
            has_opcodes(&prog, &[Opcode::IfNot, Opcode::ResultRow]),
            "HAVING clause should emit IfNot guard before ResultRow"
        );
        let rr = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::ResultRow)
            .unwrap();
        assert_eq!(rr.p2, 1, "query still returns one SELECT column");
    }

    // === Test 22c: HAVING aggregate deduplicates with SELECT aggregate ===
    #[test]
    fn test_codegen_select_having_aggregate_reuses_select_aggregate() {
        let stmt = agg_count_star_having_count_gt(1, "t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let step_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggStep)
            .count();
        assert_eq!(step_count, 1, "COUNT(*) should not be duplicated");

        let final_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggFinal)
            .count();
        assert_eq!(
            final_count, 1,
            "COUNT(*) finalization should not be duplicated"
        );
    }

    // === Test 23: Non-aggregate SELECT does not emit AggStep ===
    #[test]
    fn test_codegen_select_no_agg_no_aggstep() {
        let stmt = star_select("t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let agg_count = prog
            .ops()
            .iter()
            .filter(|op| {
                matches!(
                    op.opcode,
                    Opcode::AggStep | Opcode::AggFinal | Opcode::AggValue
                )
            })
            .count();
        assert_eq!(agg_count, 0, "no aggregate opcodes in non-aggregate SELECT");
    }

    // === Test 24: Aggregate labels properly resolved ===
    #[test]
    fn test_codegen_select_aggregate_labels_resolved() {
        let stmt = agg_count_star("t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        for op in prog.ops() {
            if op.opcode.is_jump() {
                assert!(
                    op.p2 >= 0,
                    "unresolved jump at {:?}: p2 = {}",
                    op.opcode,
                    op.p2
                );
                assert!(
                    usize::try_from(op.p2).unwrap() <= prog.len(),
                    "jump target out of range at {:?}: p2 = {} (prog len = {})",
                    op.opcode,
                    op.p2,
                    prog.len()
                );
            }
        }
    }

    #[test]
    fn test_codegen_select_aggregate_between_wrapper() -> Result<(), String> {
        let stmt = select_sql("SELECT SUM(a) BETWEEN 1 AND 10 FROM t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).map_err(|err| format!("{err:?}"))?;
        let prog = b.finish().map_err(|err| format!("{err:?}"))?;

        let agg_steps = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggStep)
            .count();
        if agg_steps != 1 {
            return Err(format!("expected one SUM AggStep, got {agg_steps}"));
        }

        let agg_finals = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggFinal)
            .count();
        if agg_finals != 1 {
            return Err(format!("expected one SUM AggFinal, got {agg_finals}"));
        }

        if !has_opcodes(
            &prog,
            &[
                Opcode::AggStep,
                Opcode::AggFinal,
                Opcode::Lt,
                Opcode::Gt,
                Opcode::ResultRow,
            ],
        ) {
            return Err(format!(
                "aggregate BETWEEN wrapper should emit finalized aggregate comparison, got {:?}",
                opcode_sequence(&prog)
            ));
        }

        Ok(())
    }

    // === Test 25: Bare column with aggregate (no GROUP BY) ===
    #[test]
    fn test_codegen_select_mixed_agg_bare_column() {
        // SELECT count(*), a FROM t — SQLite allows bare columns without GROUP BY.
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "count".to_owned(),
                                args: FunctionArgs::Star,
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                            alias: None,
                        },
                    ],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect("bare column with aggregate should succeed");
        let prog = b.finish().unwrap();

        // Should have exactly 1 AggStep (for count(*)) and 1 AggFinal.
        let step_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggStep)
            .count();
        assert_eq!(step_count, 1, "only count(*) should emit AggStep");

        let final_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggFinal)
            .count();
        assert_eq!(final_count, 1, "only count(*) should emit AggFinal");

        // ResultRow should cover 2 columns.
        let rr = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::ResultRow)
            .unwrap();
        assert_eq!(rr.p2, 2, "ResultRow should output 2 columns");
    }

    #[test]
    fn test_codegen_select_star_with_aggregate_expands_bare_columns() -> Result<(), String> {
        let stmt = select_sql("SELECT *, COUNT(*) FROM t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).map_err(|err| format!("{err:?}"))?;
        let prog = b.finish().map_err(|err| format!("{err:?}"))?;

        let agg_steps = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::AggStep)
            .count();
        if agg_steps != 1 {
            return Err(format!("expected one COUNT AggStep, got {agg_steps}"));
        }

        let column_reads = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Column)
            .count();
        if column_reads < 2 {
            return Err(format!(
                "expected star expansion to read both table columns, got {column_reads}"
            ));
        }

        let result_row = prog.ops().iter().find(|op| op.opcode == Opcode::ResultRow);
        if result_row.is_none_or(|op| op.p2 != 3) {
            return Err(format!(
                "expected ResultRow to expose two star columns plus COUNT, got {:?}",
                result_row.map(|op| op.p2)
            ));
        }

        Ok(())
    }

    // === Test 26: AVG aggregate ===
    #[test]
    fn test_codegen_select_avg() {
        let stmt = agg_func_col("avg", "a", "t");
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // AggStep P4 should be "AVG".
        let step = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::AggStep)
            .unwrap();
        assert!(
            matches!(&step.p4, P4::FuncName(f) if f == "AVG"),
            "AggStep P4 should be FuncName(AVG), got {:?}",
            step.p4
        );

        // AggFinal should also be "AVG".
        let fin = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::AggFinal)
            .unwrap();
        assert!(
            matches!(&fin.p4, P4::FuncName(f) if f == "AVG"),
            "AggFinal P4 should be FuncName(AVG), got {:?}",
            fin.p4
        );
    }

    // === Test: GROUP BY with HAVING clause ===
    #[test]
    fn test_codegen_select_group_by_having() {
        // SELECT a, count(*) FROM t GROUP BY a HAVING count(*) > 1
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "count".to_owned(),
                                args: FunctionArgs::Star,
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                    ],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![Expr::Column(ColumnRef::bare("a"), Span::ZERO)],
                    having: Some(Box::new(Expr::BinaryOp {
                        left: Box::new(Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        }),
                        op: AstBinaryOp::Gt,
                        right: Box::new(Expr::Literal(Literal::Integer(1), Span::ZERO)),
                        span: Span::ZERO,
                    })),
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Should produce GROUP BY with HAVING filter: SorterOpen, AggStep,
        // AggFinal, IfNot (HAVING check), ResultRow.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::SorterOpen,
                Opcode::AggStep,
                Opcode::AggFinal,
                Opcode::IfNot, // HAVING filter
                Opcode::ResultRow,
                Opcode::Halt,
            ]
        ));

        // There should be IfNot opcodes (HAVING filter) in the program.
        let if_not_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::IfNot)
            .count();
        assert!(
            if_not_count >= 1,
            "HAVING should generate at least one IfNot, got {if_not_count}"
        );
    }

    // === Test: GROUP BY with FILTER clause emits IfNot ===
    #[test]
    fn test_codegen_select_group_by_filter_emits_ifnot() {
        // SELECT a, count(*) FILTER (WHERE b > 0) FROM t GROUP BY a
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "count".to_owned(),
                                args: FunctionArgs::Star,
                                distinct: false,
                                order_by: vec![],
                                filter: Some(Box::new(Expr::BinaryOp {
                                    left: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                                    op: AstBinaryOp::Gt,
                                    right: Box::new(Expr::Literal(Literal::Integer(0), Span::ZERO)),
                                    span: Span::ZERO,
                                })),
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                    ],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![Expr::Column(ColumnRef::bare("a"), Span::ZERO)],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // There should be an IfNot opcode BEFORE AggStep (the FILTER check).
        let agg_step_positions: Vec<usize> = prog
            .ops()
            .iter()
            .enumerate()
            .filter(|(_, op)| op.opcode == Opcode::AggStep)
            .map(|(i, _)| i)
            .collect();

        // There should be at least one AggStep (in the sort iteration loop).
        assert!(
            !agg_step_positions.is_empty(),
            "GROUP BY FILTER should have AggStep"
        );

        // There should be IfNot before AggStep (FILTER check).
        let if_not_before_agg = prog.ops().iter().enumerate().any(|(i, op)| {
            op.opcode == Opcode::IfNot
                && agg_step_positions
                    .iter()
                    .any(|&as_pos| i < as_pos && as_pos - i <= 5)
        });
        assert!(
            if_not_before_agg,
            "GROUP BY FILTER should emit IfNot before AggStep"
        );
    }

    #[test]
    fn test_codegen_group_by_rowid_bucket_sum_skips_sorter() {
        let group_expr = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("id"), Span::ZERO)),
            op: AstBinaryOp::Divide,
            right: Box::new(Expr::Literal(Literal::Integer(10), Span::ZERO)),
            span: Span::ZERO,
        };
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: group_expr.clone(),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "sum".to_owned(),
                                args: FunctionArgs::List(vec![Expr::Column(
                                    ColumnRef::bare("value"),
                                    Span::ZERO,
                                )]),
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                    ],
                    from: Some(from_table("bench")),
                    where_clause: None,
                    group_by: vec![group_expr],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let schema = test_small_bench_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            !prog.ops().iter().any(|op| {
                matches!(
                    op.opcode,
                    Opcode::SorterOpen
                        | Opcode::SorterInsert
                        | Opcode::SorterSort
                        | Opcode::SorterData
                        | Opcode::SorterNext
                )
            }),
            "rowid-bucket SUM GROUP BY fast path should bypass the sorter"
        );
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::OpenRead,
                Opcode::Int64,
                Opcode::Rowid,
                Opcode::Divide,
                Opcode::AggStep,
                Opcode::AggFinal,
                Opcode::ResultRow,
                Opcode::Halt,
            ]
        ));
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.p4, P4::Int64(value) if value == 10)),
            "fast path should encode the bucket divisor literal"
        );
    }

    #[test]
    fn test_codegen_parsed_group_by_rowid_bucket_sum_skips_sorter() {
        let sql = "SELECT (id / 3), SUM(value) FROM bench GROUP BY (id / 3)";
        let Some((statement, tail)) = parse_first_statement_with_tail(sql).unwrap() else {
            unreachable!("expected parsed statement");
        };
        assert_eq!(
            tail,
            sql.len(),
            "parser should consume the whole SQL string"
        );
        let stmt = match statement {
            Statement::Select(stmt) => stmt,
            other => unreachable!("expected SELECT statement, got {other:?}"),
        };

        let schema = test_small_bench_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            !prog.ops().iter().any(|op| {
                matches!(
                    op.opcode,
                    Opcode::SorterOpen
                        | Opcode::SorterInsert
                        | Opcode::SorterSort
                        | Opcode::SorterData
                        | Opcode::SorterNext
                )
            }),
            "parsed rowid-bucket SUM GROUP BY should also bypass the sorter"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.p4, P4::Int64(value) if value == 3)),
            "parsed SQL fast path should encode the parsed divisor literal"
        );
    }

    #[test]
    fn test_execute_rowid_bucket_projection_keeps_integer_keys() {
        let group_expr = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("id"), Span::ZERO)),
            op: AstBinaryOp::Divide,
            right: Box::new(Expr::Literal(Literal::Integer(3), Span::ZERO)),
            span: Span::ZERO,
        };
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: group_expr,
                        alias: None,
                    }],
                    from: Some(from_table("bench")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let rows = execute_codegen_select_with_storage_cursor(
            &stmt,
            &test_small_bench_schema(),
            seed_small_bench_db(7),
        );

        assert_eq!(
            rows,
            vec![
                vec![SqliteValue::Integer(0)],
                vec![SqliteValue::Integer(0)],
                vec![SqliteValue::Integer(0)],
                vec![SqliteValue::Integer(1)],
                vec![SqliteValue::Integer(1)],
                vec![SqliteValue::Integer(1)],
                vec![SqliteValue::Integer(2)],
            ]
        );
    }

    #[test]
    fn test_execute_group_by_rowid_bucket_sum_storage_cursor_rows() {
        let group_expr = Expr::BinaryOp {
            left: Box::new(Expr::Column(ColumnRef::bare("id"), Span::ZERO)),
            op: AstBinaryOp::Divide,
            right: Box::new(Expr::Literal(Literal::Integer(3), Span::ZERO)),
            span: Span::ZERO,
        };
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![
                        ResultColumn::Expr {
                            expr: group_expr.clone(),
                            alias: None,
                        },
                        ResultColumn::Expr {
                            expr: Expr::FunctionCall {
                                name: "sum".to_owned(),
                                args: FunctionArgs::List(vec![Expr::Column(
                                    ColumnRef::bare("value"),
                                    Span::ZERO,
                                )]),
                                distinct: false,
                                order_by: vec![],
                                filter: None,
                                over: None,
                                span: Span::ZERO,
                            },
                            alias: None,
                        },
                    ],
                    from: Some(from_table("bench")),
                    where_clause: None,
                    group_by: vec![group_expr],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };

        let rows = execute_codegen_select_with_storage_cursor(
            &stmt,
            &test_small_bench_schema(),
            seed_small_bench_db(7),
        );

        assert_eq!(
            rows,
            vec![
                vec![SqliteValue::Integer(0), SqliteValue::Float(12.0)],
                vec![SqliteValue::Integer(1), SqliteValue::Float(39.0)],
                vec![SqliteValue::Integer(2), SqliteValue::Float(19.0)],
            ]
        );
    }

    // === Tests for bd-2vza: UPDATE/DELETE WHERE with qualified alias columns ===

    #[test]
    fn test_codegen_update_where_qualified_alias() {
        // UPDATE t AS u SET b = ?1 WHERE u.a = ?2
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: Some("u".to_owned()),
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::qualified("u", "a"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // The qualified alias "u.a" should resolve to Column opcode
        // for filter comparison (Ne), not silently skip filtering.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Rewind,
                Opcode::Column, // read u.a for WHERE comparison
                Opcode::Variable,
                Opcode::Ne, // filter non-matching rows
            ]
        ));
    }

    #[test]
    fn test_codegen_select_projection_expression_wrong_qualifier_errors() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::BinaryOp {
                            left: Box::new(Expr::Column(
                                ColumnRef::qualified("u", "a"),
                                Span::ZERO,
                            )),
                            op: AstBinaryOp::Add,
                            right: Box::new(Expr::Literal(Literal::Integer(1), Span::ZERO)),
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect_err("projection expression should reject wrong qualifier");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "u" && column == "u.a"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_update_where_wrong_qualifier_errors() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: Some("u".to_owned()),
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::qualified("t", "a"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_update(&mut b, &stmt, &schema, &ctx)
            .expect_err("base table qualifier should be hidden by UPDATE alias");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "t" && column == "t.a"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_update_set_unknown_column_errors() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: Expr::Column(ColumnRef::bare("missing"), Span::ZERO),
            }],
            from: None,
            where_clause: None,
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_update(&mut b, &stmt, &schema, &ctx)
            .expect_err("SET expression should reject unknown source column");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "t" && column == "missing"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_update_returning_qualified_alias() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: Some("u".to_owned()),
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::qualified("u", "a"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![ResultColumn::Expr {
                expr: Expr::Column(ColumnRef::qualified("u", "a"), Span::ZERO),
                alias: None,
            }],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
    }

    #[test]
    fn test_codegen_update_where_uses_resolved_collation_and_affinity() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("a".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("name"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema_with_nocase_text_column();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let filter_cmp = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Ne)
            .expect("scan-based WHERE should emit Ne");
        assert_eq!(filter_cmp.p4, P4::Collation("NOCASE".to_owned()));
        assert_eq!(filter_cmp.p5, 0x80 | u16::from(b'B'));
    }

    #[test]
    fn test_codegen_join_on_nocase_column_emits_collation() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::qualified("p", "probe"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("coll_probe"),
                            alias: Some("p".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![JoinClause {
                            join_type: JoinType {
                                natural: false,
                                kind: JoinKind::Inner,
                            },
                            table: TableOrSubquery::Table {
                                name: QualifiedName::bare("coll_words"),
                                alias: Some("w".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            constraint: Some(JoinConstraint::On(Expr::BinaryOp {
                                left: Box::new(Expr::Column(
                                    ColumnRef::qualified("w", "word"),
                                    Span::ZERO,
                                )),
                                op: AstBinaryOp::Eq,
                                right: Box::new(Expr::Column(
                                    ColumnRef::qualified("p", "probe"),
                                    Span::ZERO,
                                )),
                                span: Span::ZERO,
                            })),
                        }],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = vec![
            TableSchema {
                name: "coll_probe".to_owned(),
                root_page: 2,
                columns: vec![ColumnInfo::basic("probe", 'B', false)],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: vec![],
                foreign_keys: vec![],
                check_constraints: vec![],
            },
            TableSchema {
                name: "coll_words".to_owned(),
                root_page: 3,
                columns: vec![
                    ColumnInfo::basic("id", 'D', true),
                    ColumnInfo {
                        collation: Some("NOCASE".to_owned()),
                        ..ColumnInfo::basic("word", 'B', false)
                    },
                ],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: vec![],
                foreign_keys: vec![],
                check_constraints: vec![],
            },
        ];
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let join_cmp = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Eq && op.p5 == 0x20)
            .expect("JOIN ON equality should emit an Eq STOREP2 opcode");
        assert_eq!(join_cmp.p4, P4::Collation("NOCASE".to_owned()));
    }

    #[test]
    fn test_codegen_join_where_current_date_literal_emits_string() -> Result<(), String> {
        let stmt = select_sql(
            "SELECT c.name FROM customers c CROSS JOIN orders o WHERE CURRENT_DATE IS NOT NULL",
        );
        let schema = test_schema_with_join_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).map_err(|err| format!("{err:?}"))?;
        let prog = b.finish().map_err(|err| format!("{err:?}"))?;

        let has_current_date = prog.ops().iter().any(|op| {
            matches!(
                &op.p4,
                P4::Str(text)
                    if op.opcode == Opcode::String8
                        && text.len() == 10
                        && text.as_bytes().get(4) == Some(&b'-')
                        && text.as_bytes().get(7) == Some(&b'-')
            )
        });
        if !has_current_date {
            return Err(format!(
                "JOIN WHERE CURRENT_DATE should emit a date String8 literal, got {:?}",
                opcode_sequence(&prog)
            ));
        }

        Ok(())
    }

    #[test]
    fn test_codegen_join_where_divide_expression_emits_arithmetic() -> Result<(), String> {
        let stmt = select_sql(
            "SELECT c.name FROM customers c CROSS JOIN orders o WHERE (o.amount / 2) > 10",
        );
        let schema = test_schema_with_join_lookup();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).map_err(|err| format!("{err:?}"))?;
        let prog = b.finish().map_err(|err| format!("{err:?}"))?;

        if !has_opcodes(&prog, &[Opcode::Divide, Opcode::Gt, Opcode::IfNot]) {
            return Err(format!(
                "JOIN WHERE arithmetic expression should emit Divide before comparison, got {:?}",
                opcode_sequence(&prog)
            ));
        }

        Ok(())
    }

    fn ambiguous_join_on_stmt(column: &str) -> SelectStatement {
        SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::qualified("a", "x"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("a"),
                            alias: None,
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![JoinClause {
                            join_type: JoinType {
                                natural: false,
                                kind: JoinKind::Inner,
                            },
                            table: TableOrSubquery::Table {
                                name: QualifiedName::bare("b"),
                                alias: None,
                                index_hint: None,
                                time_travel: None,
                            },
                            constraint: Some(JoinConstraint::On(Expr::BinaryOp {
                                left: Box::new(Expr::Column(ColumnRef::bare(column), Span::ZERO)),
                                op: AstBinaryOp::Eq,
                                right: Box::new(Expr::Literal(Literal::Integer(1), Span::ZERO)),
                                span: Span::ZERO,
                            })),
                        }],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        }
    }

    #[test]
    fn test_codegen_join_on_unqualified_duplicate_column_is_ambiguous() {
        let schema = vec![
            TableSchema {
                name: "a".to_owned(),
                root_page: 2,
                columns: vec![ColumnInfo::basic("x", 'D', false)],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: vec![],
                foreign_keys: vec![],
                check_constraints: vec![],
            },
            TableSchema {
                name: "b".to_owned(),
                root_page: 3,
                columns: vec![ColumnInfo::basic("x", 'D', false)],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: vec![],
                foreign_keys: vec![],
                check_constraints: vec![],
            },
        ];
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &ambiguous_join_on_stmt("x"), &schema, &ctx)
            .expect_err("unqualified duplicate JOIN column should be ambiguous");
        assert!(
            matches!(err, CodegenError::AmbiguousColumn(ref name) if name == "x"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_join_on_unqualified_rowid_is_ambiguous() {
        let schema = vec![
            TableSchema {
                name: "a".to_owned(),
                root_page: 2,
                columns: vec![ColumnInfo::basic("x", 'D', false)],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: vec![],
                foreign_keys: vec![],
                check_constraints: vec![],
            },
            TableSchema {
                name: "b".to_owned(),
                root_page: 3,
                columns: vec![ColumnInfo::basic("y", 'D', false)],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: vec![],
                foreign_keys: vec![],
                check_constraints: vec![],
            },
        ];
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &ambiguous_join_on_stmt("rowid"), &schema, &ctx)
            .expect_err("unqualified JOIN rowid should be ambiguous");
        assert!(
            matches!(err, CodegenError::AmbiguousColumn(ref name) if name == "rowid"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_table_alias_hides_base_table_qualifier() {
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::qualified("t", "a"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(from_table_as("t", "u")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect_err("base table qualifier must not resolve after aliasing");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "t" && column == "t.a"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_join_alias_hides_base_table_qualifier() {
        let schema = vec![
            TableSchema {
                name: "t".to_owned(),
                root_page: 2,
                columns: vec![ColumnInfo::basic("a", 'D', false)],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: vec![],
                foreign_keys: vec![],
                check_constraints: vec![],
            },
            TableSchema {
                name: "s".to_owned(),
                root_page: 3,
                columns: vec![ColumnInfo::basic("a", 'D', false)],
                indexes: vec![],
                strict: false,
                without_rowid: false,
                primary_key_constraints: vec![],
                foreign_keys: vec![],
                check_constraints: vec![],
            },
        ];
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::qualified("u", "a"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("t"),
                            alias: Some("u".to_owned()),
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![JoinClause {
                            join_type: JoinType {
                                natural: false,
                                kind: JoinKind::Inner,
                            },
                            table: TableOrSubquery::Table {
                                name: QualifiedName::bare("s"),
                                alias: Some("v".to_owned()),
                                index_hint: None,
                                time_travel: None,
                            },
                            constraint: Some(JoinConstraint::On(Expr::BinaryOp {
                                left: Box::new(Expr::Column(
                                    ColumnRef::qualified("t", "a"),
                                    Span::ZERO,
                                )),
                                op: AstBinaryOp::Eq,
                                right: Box::new(Expr::Column(
                                    ColumnRef::qualified("v", "a"),
                                    Span::ZERO,
                                )),
                                span: Span::ZERO,
                            })),
                        }],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_select(&mut b, &stmt, &schema, &ctx)
            .expect_err("JOIN qualifier must use the table alias once present");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "t" && column == "t.a"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_delete_where_qualified_alias() {
        // DELETE FROM t AS u WHERE u.a = ?1
        let stmt = DeleteStatement {
            with: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: Some("u".to_owned()),
                index_hint: None,
                time_travel: None,
            },
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::qualified("u", "a"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(1)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_delete(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // The qualified alias "u.a" should resolve correctly (two-pass delete).
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Rewind,
                Opcode::Column, // read u.a for WHERE comparison
                Opcode::Variable,
                Opcode::Ne,    // filter non-matching rows
                Opcode::Rowid, // collect matching rowid
                Opcode::RowSetAdd,
                Opcode::RowSetRead, // pass 2: delete collected rows
                Opcode::SeekRowid,
                Opcode::Delete,
            ]
        ));
    }

    #[test]
    fn test_codegen_delete_where_wrong_qualifier_errors() {
        let stmt = DeleteStatement {
            with: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: Some("u".to_owned()),
                index_hint: None,
                time_travel: None,
            },
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::qualified("t", "a"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(1)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_delete(&mut b, &stmt, &schema, &ctx)
            .expect_err("base table qualifier should be hidden by DELETE alias");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "t" && column == "t.a"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_update_where_qualified_rowid_alias() {
        // UPDATE t AS u SET b = ?1 WHERE u.rowid = ?2
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: Some("u".to_owned()),
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::qualified("u", "rowid"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // The qualified alias "u.rowid" should resolve to the rowid fast path.
        assert!(has_opcodes(&prog, &[Opcode::Variable, Opcode::SeekRowid]));
    }

    #[test]
    fn test_codegen_update_from_generates_nested_loop() {
        // UPDATE t SET b = s.b FROM s WHERE t.a = s.b
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: Expr::Column(ColumnRef::qualified("s", "b"), Span::ZERO),
            }],
            from: Some(from_table("s")),
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::qualified("t", "a"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(Expr::Column(ColumnRef::qualified("s", "b"), Span::ZERO)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let opcodes = opcode_sequence(&prog);
        // Expect two Rewind opcodes (outer FROM, inner target).
        let rewind_count = opcodes.iter().filter(|&&o| o == Opcode::Rewind).count();
        assert_eq!(rewind_count, 2, "expected nested loop with 2 Rewind ops");
        // Expect two Next opcodes (inner and outer).
        let next_count = opcodes.iter().filter(|&&o| o == Opcode::Next).count();
        assert_eq!(next_count, 2, "expected nested loop with 2 Next ops");
        // Expect OpenWrite for target and OpenRead for FROM.
        assert!(
            opcodes.contains(&Opcode::OpenWrite),
            "expected OpenWrite for target table"
        );
        assert!(
            opcodes.contains(&Opcode::OpenRead),
            "expected OpenRead for FROM table"
        );
        // Expect Delete + Insert for the update-as-delete+insert pattern.
        assert!(
            opcodes.contains(&Opcode::Delete),
            "expected Delete for old row"
        );
        assert!(
            opcodes.contains(&Opcode::Insert),
            "expected Insert for updated row"
        );
    }

    #[test]
    fn test_codegen_update_from_unknown_set_column_errors() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: Expr::Column(ColumnRef::bare("missing"), Span::ZERO),
            }],
            from: Some(from_table("s")),
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::qualified("t", "a"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(Expr::Column(ColumnRef::qualified("s", "b"), Span::ZERO)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_update(&mut b, &stmt, &schema, &ctx)
            .expect_err("UPDATE FROM SET expression should reject unknown columns");
        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "t" && column == "missing"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_update_rejects_unmaterialized_order_by_limit() {
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                direction: Some(SortDirection::Desc),
                nulls: None,
            }],
            limit: Some(LimitClause {
                limit: Expr::Literal(Literal::Integer(1), Span::ZERO),
                offset: Some(Expr::Literal(Literal::Integer(1), Span::ZERO)),
            }),
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_update(&mut b, &stmt, &schema, &ctx).unwrap_err();
        assert!(
            matches!(&err, CodegenError::Unsupported(msg) if msg.contains("materialized")),
            "expected explicit unsupported error, got {err:?}"
        );
    }

    #[test]
    fn test_codegen_update_where_in_subquery_supported_without_rewrite() {
        // UPDATE t SET b = ?1 WHERE a IN (SELECT b FROM s)
        let subquery = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::bare("b"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(from_table("s")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::In {
                expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                set: InSet::Subquery(Box::new(subquery)),
                not: false,
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenRead && op.p2 == 3),
            "expected subquery probe OpenRead on root page 3"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::Eq | Opcode::Found)),
            "expected IN membership probe"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Insert),
            "expected update writeback Insert"
        );
    }

    #[test]
    fn test_codegen_update_set_subquery_anonymous_placeholder_offsets_where_and_returning() {
        // UPDATE t
        // SET b = a IN (SELECT b FROM s WHERE b = ?)
        // WHERE a = ?
        // RETURNING ?
        //
        // SQL placeholder order: SET-subquery first, WHERE second.
        // Bytecode emission order is WHERE first, then SET; codegen must offset
        // WHERE placeholder numbering so WHERE uses parameter 2.
        let set_subquery = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::bare("b"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(from_table("s")),
                    where_clause: Some(Box::new(Expr::BinaryOp {
                        left: Box::new(Expr::Column(ColumnRef::bare("b"), Span::ZERO)),
                        op: AstBinaryOp::Eq,
                        right: Box::new(Expr::Placeholder(PlaceholderType::Anonymous, Span::ZERO)),
                        span: Span::ZERO,
                    })),
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("b".to_owned()),
                value: Expr::In {
                    expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                    set: InSet::Subquery(Box::new(set_subquery)),
                    not: false,
                    span: Span::ZERO,
                },
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(Expr::Placeholder(PlaceholderType::Anonymous, Span::ZERO)),
                span: Span::ZERO,
            }),
            returning: vec![ResultColumn::Expr {
                expr: Expr::Placeholder(PlaceholderType::Anonymous, Span::ZERO),
                alias: None,
            }],
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let variable_params: Vec<i32> = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Variable)
            .map(|op| op.p1)
            .collect();
        assert_eq!(
            variable_params,
            vec![2, 1, 3],
            "placeholder numbering must follow SQL lexical order across WHERE (emitted first), SET, and RETURNING"
        );
    }

    #[test]
    fn test_codegen_delete_where_in_table_supported_without_rewrite() {
        // DELETE FROM t WHERE a IN s
        let stmt = DeleteStatement {
            with: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            where_clause: Some(Expr::In {
                expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                set: InSet::Table(QualifiedName::bare("s")),
                not: false,
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_delete(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::OpenRead && op.p2 == 3),
            "expected IN-table probe OpenRead on root page 3"
        );
        assert!(
            prog.ops()
                .iter()
                .any(|op| matches!(op.opcode, Opcode::Eq | Opcode::Found)),
            "expected IN membership probe"
        );
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Delete),
            "expected delete operation"
        );
    }

    #[test]
    fn test_codegen_delete_where_not_in_subquery_with_order_by_limit() {
        // DELETE FROM t WHERE
        //   a NOT IN (SELECT b FROM s ORDER BY b LIMIT ?1 OFFSET ?2)
        // Tests the complex IN subquery path with dynamic LIMIT/OFFSET.
        let subquery = SelectStatement {
            with: None,
            body: fsqlite_ast::SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::Column(ColumnRef::bare("b"), Span::ZERO),
                        alias: None,
                    }],
                    from: Some(fsqlite_ast::FromClause {
                        source: TableOrSubquery::Table {
                            name: QualifiedName::bare("s"),
                            alias: None,
                            index_hint: None,
                            time_travel: None,
                        },
                        joins: vec![],
                    }),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare("b"), Span::ZERO),
                direction: None,
                nulls: None,
            }],
            limit: Some(LimitClause {
                limit: Expr::Placeholder(fsqlite_ast::PlaceholderType::Numbered(1), Span::ZERO),
                offset: Some(Expr::Placeholder(
                    fsqlite_ast::PlaceholderType::Numbered(2),
                    Span::ZERO,
                )),
            }),
        };

        let stmt = DeleteStatement {
            with: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            where_clause: Some(Expr::In {
                expr: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                set: InSet::Subquery(Box::new(subquery)),
                not: true,
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };

        let schema = test_schema_with_subquery_source();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_delete(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Should have SorterOpen for materializing the subquery with ORDER BY.
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SorterOpen),
            "expected SorterOpen for ORDER BY subquery"
        );

        // Should have SorterSort to sort the materialized results.
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::SorterSort),
            "expected SorterSort opcode"
        );

        // Should have SorterInsert to populate the sorter.
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::SorterInsert),
            "expected SorterInsert opcode"
        );

        // Should have DecrJumpZero for LIMIT handling.
        assert!(
            prog.ops()
                .iter()
                .any(|op| op.opcode == Opcode::DecrJumpZero),
            "expected DecrJumpZero for LIMIT"
        );

        // Should have Delete opcode for the deletion.
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Delete),
            "expected Delete opcode"
        );

        let ops = prog.ops();
        let variable_slots: Vec<i32> = ops
            .iter()
            .filter(|op| op.opcode == Opcode::Variable)
            .map(|op| op.p1)
            .collect();
        assert_eq!(
            variable_slots,
            vec![1, 2],
            "LIMIT/OFFSET must retain their explicit bind slots"
        );
        let limit_variable = ops
            .iter()
            .position(|op| op.opcode == Opcode::Variable && op.p1 == 1)
            .expect("LIMIT ?1 should be emitted");
        let limit_coercion = ops
            .iter()
            .position(|op| op.opcode == Opcode::MustBeInt)
            .expect("dynamic LIMIT should be coerced");
        let zero_guard = ops
            .iter()
            .enumerate()
            .skip(limit_coercion + 1)
            .find_map(|(index, op)| (op.opcode == Opcode::IfNot).then_some(index))
            .expect("LIMIT zero should short-circuit the RHS build");
        let offset_variable = ops
            .iter()
            .position(|op| op.opcode == Opcode::Variable && op.p1 == 2)
            .expect("OFFSET ?2 should be emitted");
        assert!(
            limit_variable < limit_coercion
                && limit_coercion < zero_guard
                && zero_guard < offset_variable,
            "LIMIT must be validated and zero-guarded before OFFSET evaluation"
        );
        assert_eq!(
            ops.get(offset_variable + 1).map(|op| op.opcode),
            Some(Opcode::MustBeInt),
            "dynamic OFFSET should be losslessly coerced"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::IfPos),
            "OFFSET should emit a runtime skip counter"
        );
        assert!(
            ops.iter().any(|op| op.opcode == Opcode::Once)
                && ops.iter().any(|op| op.opcode == Opcode::OpenAutoindex)
                && ops.iter().any(|op| op.opcode == Opcode::IdxInsert)
                && ops.iter().any(|op| op.opcode == Opcode::Found),
            "complex RHS should build and probe one persistent membership set"
        );
    }

    #[test]
    fn test_codegen_delete_rejects_unmaterialized_order_by_limit() {
        let stmt = DeleteStatement {
            with: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(1)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![OrderingTerm {
                expr: Expr::Column(ColumnRef::bare("a"), Span::ZERO),
                direction: None,
                nulls: None,
            }],
            limit: Some(LimitClause {
                limit: Expr::Literal(Literal::Integer(2), Span::ZERO),
                offset: Some(Expr::Literal(Literal::Integer(1), Span::ZERO)),
            }),
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_delete(&mut b, &stmt, &schema, &ctx).unwrap_err();
        assert!(
            matches!(&err, CodegenError::Unsupported(msg) if msg.contains("materialized")),
            "expected explicit unsupported error, got {err:?}"
        );
    }

    #[test]
    fn test_codegen_delete_where_bare_rowid_eq() {
        // DELETE FROM t WHERE rowid = ?1
        // Ensures unqualified rowid in Eq fast-path emits Rowid opcode.
        let stmt = DeleteStatement {
            with: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(1)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_delete(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // Bare rowid in DELETE WHERE Eq should use the direct rowid probe path.
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Variable,
                Opcode::SeekRowid, // direct probe
                Opcode::RowSetAdd,
                Opcode::RowSetRead, // pass 2: delete collected rows
                Opcode::SeekRowid,
                Opcode::Delete,
            ]
        ));
    }

    #[test]
    fn test_codegen_delete_where_shadowed_rowid_eq_uses_visible_column_filter() {
        let stmt = DeleteStatement {
            with: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(ColumnRef::bare("rowid"), Span::ZERO)),
                op: AstBinaryOp::Eq,
                right: Box::new(placeholder(1)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = schema_with_visible_rowid_column();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_delete(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Rewind,
                Opcode::Column, // visible rowid column comparison
                Opcode::Variable,
                Opcode::Ne,
                Opcode::Rowid, // collect hidden rowid for deletion
                Opcode::RowSetAdd,
                Opcode::RowSetRead,
                Opcode::SeekRowid,
                Opcode::Delete,
            ]
        ));
    }

    // === Test: UPDATE SET with column self-reference (bd-2eau) ===

    #[test]
    fn test_codegen_update_set_column_self_ref() {
        // UPDATE t SET a = a + 1
        // The SET expression `a + 1` should generate a Column opcode to read
        // the current value of `a`, NOT a Null opcode.
        let stmt = UpdateStatement {
            with: None,
            or_conflict: None,
            table: QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![Assignment {
                target: AssignmentTarget::Column("a".to_owned()),
                value: Expr::BinaryOp {
                    left: Box::new(Expr::Column(ColumnRef::bare("a"), Span::ZERO)),
                    op: AstBinaryOp::Add,
                    right: Box::new(Expr::Literal(Literal::Integer(1), Span::ZERO)),
                    span: Span::ZERO,
                },
            }],
            from: None,
            where_clause: None,
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // The SET expression should emit Column (reading `a`) + Integer(1) + Add,
        // NOT Null. Count Column opcodes — there should be at least 3:
        // 2 from reading all columns, plus 1+ from evaluating `a` in the expression.
        let column_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Column)
            .count();
        assert!(
            column_count >= 3,
            "expected >= 3 Column ops (2 for reading all cols + 1 for SET expr), got {column_count}"
        );

        // There should be an Add opcode for `a + 1`.
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Add),
            "expected Add opcode for `a + 1` expression"
        );

        // There should be NO Null opcodes for column references.
        // (Null would only appear if the ScanCtx was missing.)
        let null_count = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Null)
            .count();
        assert_eq!(
            null_count, 0,
            "expected 0 Null opcodes (column refs should resolve), got {null_count}"
        );
    }

    // =================================================================
    // IPK codegen tests (bd-3l6e / PARITY-B5)
    // =================================================================

    /// INSERT VALUES with IPK column should emit IsNull+Copy routing, NOT
    /// unconditional NewRowid.
    #[test]
    fn test_codegen_insert_values_ipk_uses_copy_not_new_rowid() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        // Must contain IsNull (conditional branch) and Copy (value→rowid).
        assert!(
            ops.contains(&Opcode::IsNull),
            "IPK INSERT should emit IsNull to check for NULL IPK value"
        );
        assert!(
            ops.contains(&Opcode::Copy),
            "IPK INSERT should emit Copy to move IPK value to rowid register"
        );
        // The sequence must be: Variable (values) → IsNull → Copy → Goto
        //                       (or the NULL path: NewRowid → Copy)
        assert!(has_opcodes(
            &prog,
            &[
                Opcode::Init,
                Opcode::Transaction,
                Opcode::OpenWrite,
                Opcode::Variable,
                Opcode::Variable,
                Opcode::IsNull,
                Opcode::Copy,
                Opcode::MakeRecord,
                Opcode::Insert,
                Opcode::Close,
                Opcode::Halt,
            ]
        ));
    }

    #[test]
    fn test_codegen_insert_values_ipk_literals_preformat_record_blob() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![
                Expr::Literal(Literal::Integer(7), Span::ZERO),
                Expr::Literal(Literal::String("payload".to_owned()), Span::ZERO),
            ]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);
        let insert = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::Insert)
            .expect("IPK literal INSERT should emit Insert");

        assert!(ops.contains(&Opcode::IsNull));
        assert!(ops.contains(&Opcode::Copy));
        assert!(
            !ops.contains(&Opcode::Blob),
            "IPK preformatted record should be carried by Insert.p4, not a Blob register"
        );
        assert!(
            !ops.contains(&Opcode::MakeRecord),
            "IPK literal INSERT should still preformat the table record payload"
        );
        assert!(
            matches!(&insert.p4, P4::Blob(record) if !record.is_empty()),
            "IPK literal Insert should carry the preformatted payload in P4"
        );
    }

    #[test]
    fn test_codegen_insert_values_known_schema_uses_precomputed_header() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_and_strict_real_notnull();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let make_record = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::MakeRecord)
            .expect("expected MakeRecord for parameterized INSERT");
        assert!(
            matches!(&make_record.p4, P4::PrecomputedHeader(header)
                if header.template == vec![3, 0, 0]
                    && header.slots.len() == 2
                    && header.slots[0].kind == PrecomputedSerialTypeKind::NullPlaceholder
                    && header.slots[1].kind == PrecomputedSerialTypeKind::RealOrNull),
            "expected a precomputed header for IPK + STRICT REAL schema"
        );
    }

    #[test]
    fn test_codegen_upsert_update_known_schema_uses_precomputed_header() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![UpsertClause {
                target: None,
                action: UpsertAction::Update {
                    assignments: vec![Assignment {
                        target: AssignmentTarget::Column("score".to_owned()),
                        value: Expr::Column(ColumnRef::qualified("excluded", "score"), Span::ZERO),
                    }],
                    where_clause: None,
                },
            }],
            returning: vec![],
        };
        let schema = schema_with_ipk_and_strict_real_notnull();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let table_record_headers = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::MakeRecord)
            .filter(|op| {
                matches!(&op.p4, P4::PrecomputedHeader(header)
                    if header.template == vec![3, 0, 0]
                        && header.slots.len() == 2
                        && header.slots[0].kind == PrecomputedSerialTypeKind::NullPlaceholder
                        && header.slots[1].kind == PrecomputedSerialTypeKind::RealOrNull)
            })
            .count();

        assert_eq!(
            table_record_headers, 2,
            "UPSERT DO UPDATE should use precomputed headers for both conflict-update and insert table records"
        );
    }

    fn partial_unique_upsert_schema() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("id", 'D', true),
                ColumnInfo::basic("email", 'B', false),
                ColumnInfo::basic("active", 'D', false),
            ],
            indexes: vec![IndexSchema {
                name: "uq_active_email".to_owned(),
                root_page: 3,
                columns: vec!["email".to_owned()],
                key_expressions: Vec::new(),
                key_sort_directions: vec![SortDirection::Asc],
                where_clause: Some("active = 1".to_owned()),
                is_unique: true,
                key_collations: vec![None],
                conflict_action: None,
            }],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    fn partial_unique_upsert_statement(predicate: &str) -> InsertStatement {
        InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: Vec::new(),
            source: InsertSource::Values(vec![vec![
                placeholder(1),
                placeholder(2),
                placeholder(3),
            ]]),
            upsert: vec![UpsertClause {
                target: Some(UpsertTarget {
                    columns: vec![IndexedColumn {
                        expr: Expr::Column(ColumnRef::bare("email"), Span::ZERO),
                        collation: None,
                        direction: None,
                    }],
                    where_clause: Some(expr_sql(predicate)),
                }),
                action: UpsertAction::Update {
                    assignments: vec![Assignment {
                        target: AssignmentTarget::Column("id".to_owned()),
                        value: Expr::Column(ColumnRef::qualified("excluded", "id"), Span::ZERO),
                    }],
                    where_clause: None,
                },
            }],
            returning: Vec::new(),
        }
    }

    #[test]
    fn upsert_partial_unique_target_matches_predicate_and_guards_probe() {
        let schema = partial_unique_upsert_schema();
        let statement = partial_unique_upsert_statement("active = 1");
        let target = statement.upsert[0]
            .target
            .as_ref()
            .expect("test UPSERT should have a conflict target");
        assert_eq!(
            find_upsert_target_index(&schema[0], Some(target))
                .map(|(offset, index)| { (offset, index.name.as_str()) }),
            Some((0, "uq_active_email"))
        );

        let mut builder = ProgramBuilder::new();
        codegen_insert(
            &mut builder,
            &statement,
            &schema,
            &CodegenContext {
                rowid_alias_col_idx: Some(0),
                ..CodegenContext::default()
            },
        )
        .expect("matching partial UNIQUE target should compile");
        let program = builder.finish().expect("UPSERT program should finish");
        let predicate_guard = program
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::IfNot)
            .expect("partial UNIQUE probe should be guarded by its predicate");
        let conflict_probe = program
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::NoConflict && op.p1 == 1)
            .expect("matching partial UNIQUE index should supply the conflict probe");
        assert!(
            predicate_guard < conflict_probe,
            "the attempted row must satisfy the partial predicate before probing the index"
        );
        let old_row_delete = program
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::Delete && op.p5 == OPFLAG_ISUPDATE)
            .expect("UPSERT update must remove the conflict victim before reinsertion");
        let update_insert = program
            .ops()
            .iter()
            .position(|op| op.opcode == Opcode::Insert && op.p5 & OPFLAG_ISUPDATE != 0)
            .expect("UPSERT update must reinsert the rewritten row");
        assert!(
            conflict_probe < old_row_delete && old_row_delete < update_insert,
            "UPSERT must decide the conflict before deleting and reinserting its victim"
        );
    }

    #[test]
    fn upsert_partial_unique_target_rejects_mismatched_predicate() {
        let schema = partial_unique_upsert_schema();
        let statement = partial_unique_upsert_statement("active = 0");
        let mut builder = ProgramBuilder::new();
        let error = codegen_insert(
            &mut builder,
            &statement,
            &schema,
            &CodegenContext {
                rowid_alias_col_idx: Some(0),
                ..CodegenContext::default()
            },
        )
        .expect_err("mismatched partial-index predicate must not fall back to the rowid probe");
        assert!(
            matches!(error, CodegenError::Unsupported(ref message)
                if message.contains("does not match any PRIMARY KEY or UNIQUE constraint")),
            "unexpected unmatched-target error: {error:?}"
        );
    }

    #[test]
    fn test_codegen_upsert_update_respects_insert_target_alias() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: Some("u".to_owned()),
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![UpsertClause {
                target: None,
                action: UpsertAction::Update {
                    assignments: vec![Assignment {
                        target: AssignmentTarget::Column("score".to_owned()),
                        value: Expr::Column(ColumnRef::qualified("u", "score"), Span::ZERO),
                    }],
                    where_clause: None,
                },
            }],
            returning: vec![],
        };
        let schema = schema_with_ipk_and_strict_real_notnull();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            !opcode_sequence(&prog).contains(&Opcode::Null),
            "target alias in UPSERT DO UPDATE should resolve to the existing row, not emit NULL"
        );
    }

    #[test]
    fn test_codegen_upsert_update_column_list_assignment() -> Result<(), String> {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![UpsertClause {
                target: None,
                action: UpsertAction::Update {
                    assignments: vec![Assignment {
                        target: AssignmentTarget::ColumnList(vec!["a".to_owned(), "b".to_owned()]),
                        value: Expr::RowValue(
                            vec![
                                Expr::Column(ColumnRef::qualified("excluded", "a"), Span::ZERO),
                                Expr::Literal(Literal::String("updated".to_owned()), Span::ZERO),
                            ],
                            Span::ZERO,
                        ),
                    }],
                    where_clause: None,
                },
            }],
            returning: vec![],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).map_err(|err| format!("{err:?}"))?;
        let prog = b.finish().map_err(|err| format!("{err:?}"))?;

        if !has_opcodes(
            &prog,
            &[
                Opcode::Copy,
                Opcode::String8,
                Opcode::MakeRecord,
                Opcode::Insert,
            ],
        ) {
            return Err(format!(
                "UPSERT column-list assignment should copy excluded.a and emit literal b, got {:?}",
                opcode_sequence(&prog)
            ));
        }

        Ok(())
    }

    #[test]
    fn test_codegen_upsert_update_column_list_rejects_arity_mismatch() -> Result<(), String> {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![UpsertClause {
                target: None,
                action: UpsertAction::Update {
                    assignments: vec![Assignment {
                        target: AssignmentTarget::ColumnList(vec!["a".to_owned(), "b".to_owned()]),
                        value: Expr::RowValue(
                            vec![Expr::Column(
                                ColumnRef::qualified("excluded", "a"),
                                Span::ZERO,
                            )],
                            Span::ZERO,
                        ),
                    }],
                    where_clause: None,
                },
            }],
            returning: vec![],
        };
        let schema = test_schema();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();

        match codegen_insert(&mut b, &stmt, &schema, &ctx) {
            Err(CodegenError::Unsupported(msg)) if msg.contains("arity mismatch") => Ok(()),
            other => Err(format!("expected column-list arity error, got {other:?}")),
        }
    }

    #[test]
    fn test_codegen_upsert_between_does_not_inherit_excluded_column_collation() -> Result<(), String>
    {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec!["name".to_owned()],
            source: InsertSource::Values(vec![vec![placeholder(1)]]),
            upsert: vec![UpsertClause {
                target: None,
                action: UpsertAction::Update {
                    assignments: vec![Assignment {
                        target: AssignmentTarget::Column("name".to_owned()),
                        value: Expr::Between {
                            expr: Box::new(Expr::Column(
                                ColumnRef::qualified("excluded", "name"),
                                Span::ZERO,
                            )),
                            low: Box::new(Expr::Literal(
                                Literal::String("alpha".to_owned()),
                                Span::ZERO,
                            )),
                            high: Box::new(Expr::Literal(
                                Literal::String("omega".to_owned()),
                                Span::ZERO,
                            )),
                            not: false,
                            span: Span::ZERO,
                        },
                    }],
                    where_clause: None,
                },
            }],
            returning: vec![],
        };
        let schema = test_schema_with_nocase_text_column();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).map_err(|err| format!("{err:?}"))?;
        let prog = b.finish().map_err(|err| format!("{err:?}"))?;

        let lt_collations = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Lt)
            .map(|op| op.p4.clone())
            .collect::<Vec<_>>();
        let gt_collations = prog
            .ops()
            .iter()
            .filter(|op| op.opcode == Opcode::Gt)
            .map(|op| op.p4.clone())
            .collect::<Vec<_>>();
        if !matches!(lt_collations.as_slice(), [P4::None])
            || !matches!(gt_collations.as_slice(), [P4::None])
        {
            return Err(format!(
                "excluded.name incorrectly donated a declared collation: lt={lt_collations:?} gt={gt_collations:?}"
            ));
        }

        Ok(())
    }

    #[test]
    fn test_codegen_upsert_update_rejects_wrong_target_qualifier() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: Some("u".to_owned()),
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![UpsertClause {
                target: None,
                action: UpsertAction::Update {
                    assignments: vec![Assignment {
                        target: AssignmentTarget::Column("score".to_owned()),
                        value: Expr::Column(ColumnRef::qualified("t", "score"), Span::ZERO),
                    }],
                    where_clause: None,
                },
            }],
            returning: vec![],
        };
        let schema = schema_with_ipk_and_strict_real_notnull();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        let err = codegen_insert(&mut b, &stmt, &schema, &ctx)
            .expect_err("UPSERT target alias should hide the base table qualifier");

        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "t" && column == "t.score"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_upsert_update_unknown_assignment_target_errors() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![UpsertClause {
                target: None,
                action: UpsertAction::Update {
                    assignments: vec![Assignment {
                        target: AssignmentTarget::Column("missing".to_owned()),
                        value: Expr::Column(ColumnRef::qualified("excluded", "score"), Span::ZERO),
                    }],
                    where_clause: None,
                },
            }],
            returning: vec![],
        };
        let schema = schema_with_ipk_and_strict_real_notnull();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        let err = codegen_insert(&mut b, &stmt, &schema, &ctx)
            .expect_err("UPSERT DO UPDATE should reject unknown SET targets");

        assert!(
            matches!(err, CodegenError::ColumnNotFound { ref table, ref column } if table == "t" && column == "missing"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_insert_values_dynamic_text_schema_falls_back_to_affinity() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_and_strict_text();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let make_record = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::MakeRecord)
            .expect("expected MakeRecord for parameterized INSERT");
        assert!(
            matches!(&make_record.p4, P4::Affinity(aff) if aff == "XB"),
            "STRICT TEXT schema should stay on the generic affinity-driven MakeRecord path"
        );
    }

    /// INSERT VALUES without IPK should still use unconditional NewRowid.
    #[test]
    fn test_codegen_insert_values_no_ipk_uses_new_rowid() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema(); // no IPK
        let ctx = CodegenContext::default(); // rowid_alias_col_idx = None
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        assert!(
            ops.contains(&Opcode::NewRowid),
            "non-IPK INSERT should use NewRowid"
        );
        assert!(
            !ops.contains(&Opcode::IsNull),
            "non-IPK INSERT should NOT emit IsNull routing"
        );
    }

    #[test]
    fn test_codegen_insert_visible_rowid_column_does_not_use_explicit_rowid_path() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec!["rowid".to_owned(), "b".to_owned()],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_visible_rowid_column();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        assert!(
            ops.contains(&Opcode::NewRowid),
            "shadowed rowid column should still auto-generate the hidden rowid"
        );
        assert!(
            !ops.contains(&Opcode::IsNull),
            "visible rowid column must not be routed through the explicit hidden-rowid path"
        );
    }

    /// INSERT with explicit column list where IPK is in non-first position.
    #[test]
    fn test_codegen_insert_values_ipk_column_list_reorder() {
        // Table: (a INTEGER PRIMARY KEY, b TEXT)
        // INSERT INTO t(b, a) VALUES (?, ?)  →  IPK is at VALUES position 1
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec!["b".to_owned(), "a".to_owned()],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0), // IPK is column 0 in schema
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        // Should still emit IPK routing (IsNull + Copy) because 'a' is in
        // the column list at position 1.
        assert!(
            ops.contains(&Opcode::IsNull),
            "reordered column list with IPK should emit IsNull"
        );
    }

    #[test]
    fn test_codegen_insert_allows_duplicate_target_columns() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec!["b".to_owned(), "b".to_owned()],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
    }

    #[test]
    fn test_codegen_insert_allows_hidden_rowid_and_ipk_targets() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec!["rowid".to_owned(), "a".to_owned()],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
    }

    #[test]
    fn test_codegen_insert_hidden_rowid_after_ipk_uses_rowid_source() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec!["a".to_owned(), "rowid".to_owned()],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);
        assert!(
            ops.contains(&Opcode::Copy),
            "rowid/IPK mixed target list should still emit rowid routing"
        );
    }

    #[test]
    fn test_codegen_insert_values_rejects_explicit_column_arity_mismatch() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec!["b".to_owned()],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        let err = codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap_err();
        // a0e51891e switched explicit-column arity mismatch to stock's shorter
        // verbatim form ("<n> values for <m> columns") under SQLITE_ERROR.
        assert!(
            matches!(err, CodegenError::SqlError(ref message) if message.contains("2 values for 1 columns")),
            "unexpected error: {err:?}"
        );
    }

    /// INSERT with explicit column list that OMITS the IPK column.
    /// The reorder fills the IPK position with NULL, so IsNull routing is
    /// emitted but always takes the auto-generate path.
    #[test]
    fn test_codegen_insert_values_ipk_column_list_omitted() {
        // Table: (a INTEGER PRIMARY KEY, b TEXT)
        // INSERT INTO t(b) VALUES (?)  →  IPK omitted, reorder fills NULL
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec!["b".to_owned()],
            source: InsertSource::Values(vec![vec![placeholder(1)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        // Reorder fills IPK slot with NULL → IPK routing still emitted
        // (IsNull will always fire, triggering NewRowid).
        assert!(
            ops.contains(&Opcode::NewRowid),
            "omitted IPK should use NewRowid"
        );
        // The reordered row has 2 columns (full table width), not 1.
        let n_null = ops.iter().filter(|&&op| op == Opcode::Null).count();
        assert!(
            n_null >= 1,
            "reorder should emit Null for the omitted IPK column"
        );
    }

    /// Multi-row VALUES with IPK should emit IPK routing for each row.
    #[test]
    fn test_codegen_insert_values_ipk_multi_row() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![
                vec![placeholder(1), placeholder(2)],
                vec![placeholder(3), placeholder(4)],
                vec![placeholder(5), placeholder(6)],
            ]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = schema_with_ipk_alias();
        let ctx = CodegenContext {
            concurrent_mode: false,
            rowid_alias_col_idx: Some(0),
            ..CodegenContext::default()
        };
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        // Three rows → three IsNull opcodes (one per row).
        let is_null_count = ops.iter().filter(|&&op| op == Opcode::IsNull).count();
        assert_eq!(
            is_null_count, 3,
            "3-row INSERT with IPK should emit 3 IsNull opcodes, got {is_null_count}"
        );
    }

    #[test]
    fn test_codegen_insert_default_values_uses_expression_default() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::DefaultValues,
            upsert: vec![],
            returning: vec![],
        };
        let schema = vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("id", 'd', false),
                ColumnInfo {
                    name: "total".to_owned(),
                    affinity: 'd',
                    is_ipk: false,
                    type_name: None,
                    notnull: false,
                    unique: false,
                    default_value: Some("(40 + 2)".to_owned()),
                    strict_type: None,
                    generated_expr: None,
                    generated_stored: None,
                    collation: None,
                    conflict_action: None,
                },
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }];
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Add),
            "expression defaults should compile as expressions, not string literals"
        );
    }

    #[test]
    fn test_codegen_insert_default_values_rejects_unparseable_default() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::DefaultValues,
            upsert: vec![],
            returning: vec![],
        };
        let schema = vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![ColumnInfo {
                name: "broken".to_owned(),
                affinity: 'C',
                is_ipk: false,
                type_name: None,
                notnull: false,
                unique: false,
                default_value: Some("('unterminated".to_owned()),
                strict_type: None,
                generated_expr: None,
                generated_stored: None,
                collation: None,
                conflict_action: None,
            }],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }];
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap_err();
        assert!(
            matches!(err, CodegenError::Unsupported(ref msg) if msg.contains("failed to parse DEFAULT expression")),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn test_codegen_insert_default_values_rejects_non_self_contained_default() {
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::DefaultValues,
            upsert: vec![],
            returning: vec![],
        };
        let schema = vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'D', false),
                ColumnInfo {
                    name: "b".to_owned(),
                    affinity: 'D',
                    is_ipk: false,
                    type_name: None,
                    notnull: false,
                    unique: false,
                    default_value: Some("(a + 1)".to_owned()),
                    strict_type: None,
                    generated_expr: None,
                    generated_stored: None,
                    collation: None,
                    conflict_action: None,
                },
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }];
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        let err = codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap_err();
        assert!(
            matches!(err, CodegenError::Unsupported(ref msg) if msg.contains("is not self-contained")),
            "unexpected error: {err:?}"
        );
    }

    /// Schema: CREATE TABLE t (a INTEGER, b INTEGER, c GENERATED ALWAYS AS (a + b) STORED)
    fn test_schema_with_stored_generated() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', false),
                ColumnInfo::basic("b", 'd', false),
                ColumnInfo {
                    name: "c".to_owned(),
                    affinity: 'd',
                    is_ipk: false,
                    type_name: Some("INTEGER".to_owned()),
                    notnull: false,
                    unique: false,
                    default_value: None,
                    strict_type: None,
                    generated_expr: Some("a + b".to_owned()),
                    generated_stored: Some(true),
                    collation: None,
                    conflict_action: None,
                },
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    /// Schema: CREATE TABLE t (a INTEGER, b INTEGER, c GENERATED ALWAYS AS (a * 2) VIRTUAL)
    fn test_schema_with_virtual_generated() -> Vec<TableSchema> {
        vec![TableSchema {
            name: "t".to_owned(),
            root_page: 2,
            columns: vec![
                ColumnInfo::basic("a", 'd', false),
                ColumnInfo::basic("b", 'd', false),
                ColumnInfo {
                    name: "c".to_owned(),
                    affinity: 'd',
                    is_ipk: false,
                    type_name: Some("INTEGER".to_owned()),
                    notnull: false,
                    unique: false,
                    default_value: None,
                    strict_type: None,
                    generated_expr: Some("a * 2".to_owned()),
                    generated_stored: Some(false),
                    collation: None,
                    conflict_action: None,
                },
            ],
            indexes: vec![],
            strict: false,
            without_rowid: false,
            primary_key_constraints: Vec::new(),
            foreign_keys: Vec::new(),
            check_constraints: Vec::new(),
        }]
    }

    #[test]
    fn test_schema_evaluation_context_codegen_tags_function_owners() {
        fn emitted_function_contexts(mut builder: ProgramBuilder) -> Vec<SchemaEvaluationContext> {
            builder.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
            builder
                .finish()
                .expect("schema-expression program should build")
                .ops()
                .iter()
                .filter(|op| matches!(op.opcode, Opcode::Function | Opcode::PureFunc))
                .map(|op| {
                    SchemaEvaluationContext::from_function_p1(op.p1)
                        .expect("schema expression function must carry its owner context")
                })
                .collect()
        }

        let schema = test_schema();
        let table = &schema[0];
        let scan = ScanCtx {
            cursor: 0,
            table,
            table_alias: None,
            schema: None,
            register_base: None,
            secondaries: &[],
        };
        let index = IndexSchema {
            name: "idx_random".to_owned(),
            root_page: 3,
            columns: Vec::new(),
            key_expressions: vec!["random()".to_owned()],
            key_sort_directions: vec![],
            where_clause: Some("random() != 0".to_owned()),
            is_unique: false,
            key_collations: vec![],
            conflict_action: None,
        };
        let mut index_builder = ProgramBuilder::new();
        let skip = index_builder.emit_label();
        emit_index_predicate_guard(&mut index_builder, &index, &scan, skip);
        let index_key = index_builder.alloc_reg();
        emit_index_key_term(&mut index_builder, &index, 0, index_key, &scan);
        index_builder.resolve_label(skip);
        assert_eq!(
            emitted_function_contexts(index_builder),
            [
                SchemaEvaluationContext::Index,
                SchemaEvaluationContext::Index,
            ]
        );

        let mut stored_table = test_schema_with_stored_generated().remove(0);
        stored_table.columns[2].generated_expr = Some("random()".to_owned());
        let mut stored_builder = ProgramBuilder::new();
        let stored_row = stored_builder.alloc_regs(
            i32::try_from(stored_table.columns.len()).expect("test column count fits i32"),
        );
        emit_stored_generated_columns(&mut stored_builder, &stored_table, stored_row);
        assert_eq!(
            emitted_function_contexts(stored_builder),
            [SchemaEvaluationContext::GeneratedColumn]
        );

        let mut virtual_table = test_schema_with_virtual_generated().remove(0);
        virtual_table.columns[2].generated_expr = Some("random()".to_owned());
        let mut virtual_builder = ProgramBuilder::new();
        let virtual_value = virtual_builder.alloc_reg();
        emit_table_column_read(
            &mut virtual_builder,
            0,
            &virtual_table,
            None,
            None,
            2,
            virtual_value,
        );
        assert_eq!(
            emitted_function_contexts(virtual_builder),
            [SchemaEvaluationContext::GeneratedColumn]
        );

        let mut check_table = test_schema().remove(0);
        check_table.check_constraints = vec![CheckConstraint {
            expr: "random() != 0".to_owned(),
            owner_column: None,
            name: None,
        }];
        let mut check_builder = ProgramBuilder::new();
        let check_row = check_builder.alloc_regs(
            i32::try_from(check_table.columns.len()).expect("test column count fits i32"),
        );
        emit_check_constraints(&mut check_builder, &check_table, check_row, None);
        assert_eq!(
            emitted_function_contexts(check_builder),
            [SchemaEvaluationContext::CheckConstraint]
        );
    }

    #[test]
    fn test_codegen_insert_stored_generated_column_emits_copy_and_add() {
        // INSERT INTO t VALUES (?, ?, DEFAULT) — 3 columns, c is STORED generated
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![
                placeholder(1),
                placeholder(2),
                Expr::Literal(Literal::Null, Span::ZERO), // placeholder for generated col
            ]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema_with_stored_generated();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        // The generated column (c = a + b) should emit Copy opcodes to read
        // columns a and b from their registers, then Add to compute the result.
        assert!(
            ops.contains(&Opcode::Copy),
            "STORED generated column should emit Copy opcodes for column references"
        );
        assert!(
            ops.contains(&Opcode::Add),
            "STORED generated column 'a + b' should emit Add opcode"
        );
    }

    #[test]
    fn test_codegen_insert_virtual_generated_column_emits_null() {
        // INSERT INTO t VALUES (?, ?, DEFAULT) — c is VIRTUAL generated (not stored)
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::Values(vec![vec![
                placeholder(1),
                placeholder(2),
                Expr::Literal(Literal::Null, Span::ZERO),
            ]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema_with_virtual_generated();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        // VIRTUAL generated column should NOT emit Add (expression not evaluated
        // at insert time); it should just emit Null.
        assert!(
            !ops.contains(&Opcode::Multiply),
            "VIRTUAL generated column should not evaluate expression during INSERT"
        );
    }

    #[test]
    fn test_codegen_insert_default_values_stored_generated() {
        // INSERT INTO t DEFAULT VALUES — with a STORED generated column
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec![],
            source: InsertSource::DefaultValues,
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema_with_stored_generated();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        // Even with DEFAULT VALUES, stored generated columns should evaluate.
        assert!(
            ops.contains(&Opcode::Copy),
            "DEFAULT VALUES with STORED generated column should emit Copy for references"
        );
        assert!(
            ops.contains(&Opcode::Add),
            "DEFAULT VALUES with STORED generated column 'a + b' should emit Add"
        );
    }

    #[test]
    fn test_codegen_insert_stored_generated_with_explicit_columns() {
        // INSERT INTO t(a, b) VALUES (?, ?) — c is omitted (STORED generated)
        let stmt = InsertStatement {
            with: None,
            or_conflict: None,
            table: QualifiedName::bare("t"),
            alias: None,
            columns: vec!["a".to_owned(), "b".to_owned()],
            source: InsertSource::Values(vec![vec![placeholder(1), placeholder(2)]]),
            upsert: vec![],
            returning: vec![],
        };
        let schema = test_schema_with_stored_generated();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_insert(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        // With explicit column list omitting the generated column, it should
        // still evaluate the STORED expression.
        assert!(
            ops.contains(&Opcode::Add),
            "Explicit column list INSERT with STORED generated column should emit Add"
        );
    }

    #[test]
    fn test_codegen_update_stored_generated_column_recomputed() {
        // UPDATE t SET a = ? WHERE b = ?
        // STORED generated column c = a + b should be recomputed.
        let stmt = fsqlite_ast::UpdateStatement {
            with: None,
            or_conflict: None,
            table: fsqlite_ast::QualifiedTableRef {
                name: QualifiedName::bare("t"),
                alias: None,
                index_hint: None,
                time_travel: None,
            },
            assignments: vec![fsqlite_ast::Assignment {
                target: fsqlite_ast::AssignmentTarget::Column("a".to_owned()),
                value: placeholder(1),
            }],
            from: None,
            where_clause: Some(Expr::BinaryOp {
                left: Box::new(Expr::Column(
                    fsqlite_ast::ColumnRef::bare("b"),
                    Span::ZERO,
                )),
                op: fsqlite_ast::BinaryOp::Eq,
                right: Box::new(placeholder(2)),
                span: Span::ZERO,
            }),
            returning: vec![],
            order_by: vec![],
            limit: None,
        };
        let schema = test_schema_with_stored_generated();
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_update(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();
        let ops = opcode_sequence(&prog);

        // UPDATE should recompute STORED generated column.
        assert!(
            ops.contains(&Opcode::Add),
            "UPDATE should recompute STORED generated column 'a + b'"
        );
    }

    /// bd-wwqen.1: Verify cheapest-index COUNT optimization fires —
    /// when a table has a non-partial index, COUNT(*) opens the index
    /// root page instead of the table root page.
    #[test]
    fn test_count_star_opens_cheapest_index_not_table() {
        let schema = test_schema_with_index();
        // table root_page = 2, index root_page = 3
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        // The OpenRead should target the INDEX root page (3), not
        // the table root page (2).
        let open_read = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::OpenRead)
            .expect("COUNT(*) program must have OpenRead");
        assert_eq!(
            open_read.p2, 3,
            "bd-wwqen.1: COUNT(*) should open cheapest index (root=3), \
             not table (root=2); got root={}",
            open_read.p2
        );

        // The Count opcode must be present.
        assert!(
            prog.ops().iter().any(|op| op.opcode == Opcode::Count),
            "bd-wwqen.1: COUNT(*) program must contain Opcode::Count"
        );
    }

    /// bd-wwqen.1: COUNT(*) on a table with NO indexes falls back
    /// to the table root page.
    #[test]
    fn test_count_star_uses_table_when_no_index() {
        let schema = test_schema(); // no indexes
        let stmt = SelectStatement {
            with: None,
            body: SelectBody {
                select: SelectCore::Select {
                    distinct: Distinctness::All,
                    columns: vec![ResultColumn::Expr {
                        expr: Expr::FunctionCall {
                            name: "count".to_owned(),
                            args: FunctionArgs::Star,
                            distinct: false,
                            order_by: vec![],
                            filter: None,
                            over: None,
                            span: Span::ZERO,
                        },
                        alias: None,
                    }],
                    from: Some(from_table("t")),
                    where_clause: None,
                    group_by: vec![],
                    having: None,
                    windows: vec![],
                },
                compounds: vec![],
            },
            order_by: vec![],
            limit: None,
        };
        let ctx = CodegenContext::default();
        let mut b = ProgramBuilder::new();
        codegen_select(&mut b, &stmt, &schema, &ctx).unwrap();
        let prog = b.finish().unwrap();

        let open_read = prog
            .ops()
            .iter()
            .find(|op| op.opcode == Opcode::OpenRead)
            .expect("COUNT(*) program must have OpenRead");
        assert_eq!(
            open_read.p2, 2,
            "bd-wwqen.1: COUNT(*) with no indexes should open table (root=2), got root={}",
            open_read.p2
        );
    }
}