radixdb-executor 1.1.0

SQL binding, planning, and execution engine for RadixDB
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
// Copyright 2026 RadixDB Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Expression Virtual Machine
//
// The VM executes compiled Programs against row data.
// Design goals:
// - Zero allocation in hot path
// - Linear instruction dispatch
// - Reusable across rows (clear() between uses)
// - No recursion

use std::borrow::Cow;
use std::sync::Arc;

use smallvec::SmallVec;

use super::execution_context::ExecuteContext;
use super::ops::{CompiledPattern, Op};
use super::program::Program;
use radixdb_core::SmartString;
use radixdb_core::{DataType, Error, Result, Value, NULL_VALUE};

/// Stack value that can be borrowed (from row/constants) or owned (from operations)
type StackValue<'a> = Cow<'a, Value>;

/// Stack capacity for inline storage (avoids heap allocation for simple expressions)
/// Most expressions need 4-8 stack slots, so 8 covers the common case.
const STACK_INLINE_CAPACITY: usize = 16;

/// Arithmetic operation type (used for safe wrapping operations)
#[derive(Clone, Copy)]
#[allow(dead_code)]
enum ArithmeticOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
}

/// Expression Virtual Machine
///
/// Executes compiled Programs against row data.
/// The VM is reusable - call execute() with different contexts.
/// Capacity for reusable args buffer (most functions have <= 4 args)
const ARGS_BUFFER_CAPACITY: usize = 8;

/// Parsed interval value: either a fixed-length duration or a calendar-relative month count.
/// Months/years require calendar-aware arithmetic (leap years, variable month lengths).
enum IntervalValue {
    Duration(chrono::Duration),
    Months(i64),
}

pub struct ExprVM {
    /// Evaluation stack (reused between executions)
    /// Uses SmallVec to avoid heap allocation for simple expressions (stack depth <= 16)
    stack: SmallVec<[Value; STACK_INLINE_CAPACITY]>,

    /// Reusable buffer for function arguments (avoids allocation per call)
    /// Uses SmallVec to avoid heap allocation for functions with <= 8 args
    args_buffer: SmallVec<[Value; ARGS_BUFFER_CAPACITY]>,

    /// Cache for dynamic LIKE patterns (avoids recompilation per row)
    /// Stores (pattern_string, case_insensitive, escape_char, compiled_pattern)
    cached_like: Option<(SmartString, bool, Option<char>, CompiledPattern)>,

    /// Cache for dynamic GLOB patterns (separate from LIKE to avoid cross-contamination)
    /// Stores (pattern_string, compiled_pattern)
    cached_glob: Option<(SmartString, CompiledPattern)>,

    /// Cache for dynamic REGEXP patterns (avoids recompilation per row)
    /// Stores (pattern_string, compiled_regex)
    cached_regexp: Option<(SmartString, regex::Regex)>,
}

impl ExprVM {
    /// Create a new VM with default stack capacity
    /// Uses inline storage for up to 16 stack values and 8 args (no heap allocation)
    pub fn new() -> Self {
        Self {
            stack: SmallVec::new(),
            args_buffer: SmallVec::new(),
            cached_like: None,
            cached_glob: None,
            cached_regexp: None,
        }
    }

    /// Create a VM with specific stack capacity
    /// If capacity > 16, will spill to heap when needed
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            stack: SmallVec::with_capacity(capacity),
            args_buffer: SmallVec::new(),
            cached_like: None,
            cached_glob: None,
            cached_regexp: None,
        }
    }

    /// Execute a program and return the result
    #[inline]
    pub fn execute(&mut self, program: &Program, ctx: &ExecuteContext) -> Result<Value> {
        // Ensure stack has enough capacity
        if self.stack.capacity() < program.max_stack_depth() {
            self.stack
                .reserve(program.max_stack_depth() - self.stack.capacity());
        }
        self.stack.clear();

        let ops = program.ops();
        if ops.is_empty() {
            return Ok(Value::null_unknown());
        }

        let mut pc: usize = 0;

        // Main execution loop
        loop {
            if pc >= ops.len() {
                break;
            }

            match &ops[pc] {
                // =============================================================
                // LOAD OPERATIONS
                // =============================================================
                Op::LoadColumn(idx) => {
                    let idx = *idx as usize;
                    let value = ctx
                        .row
                        .get(idx)
                        .cloned()
                        .unwrap_or_else(Value::null_unknown);
                    self.stack.push(value);
                    pc += 1;
                }

                Op::LoadColumn2(idx) => {
                    let idx = *idx as usize;
                    let value = ctx
                        .row2
                        .and_then(|r| r.get(idx).cloned())
                        .unwrap_or_else(Value::null_unknown);
                    self.stack.push(value);
                    pc += 1;
                }

                Op::LoadOuterColumn(name) => {
                    let value = ctx
                        .outer_row
                        .and_then(|r| r.get(name.as_ref()).cloned())
                        .unwrap_or_else(Value::null_unknown);
                    self.stack.push(value);
                    pc += 1;
                }

                Op::LoadConst(value) => {
                    self.stack.push(value.clone());
                    pc += 1;
                }

                Op::LoadParam(idx) => {
                    let idx = *idx as usize;
                    let value = ctx
                        .params
                        .get(idx)
                        .cloned()
                        .unwrap_or_else(Value::null_unknown);
                    self.stack.push(value);
                    pc += 1;
                }

                Op::LoadNamedParam(name) => {
                    let value = ctx
                        .named_params
                        .and_then(|p| p.get(name.as_ref()).cloned())
                        .or_else(|| {
                            // DEFAULT evaluation and catalog recovery compile
                            // scalar expressions without a full statement
                            // context. CURRENT_TIMESTAMP must remain a valid
                            // system value there instead of degrading to NULL;
                            // ordinary statement execution supplies one stable
                            // value through named_params.
                            (name.as_ref() == "CURRENT_STATEMENT_TIMESTAMP").then(|| {
                                Value::timestamp(
                                    radixdb_core::time_compat::system_time_now().into(),
                                )
                            })
                        })
                        .unwrap_or_else(Value::null_unknown);
                    self.stack.push(value);
                    pc += 1;
                }

                Op::LoadNull(dt) => {
                    self.stack.push(Value::Null(*dt));
                    pc += 1;
                }

                Op::LoadAggregateResult(idx) => {
                    // Aggregate results are stored in the row at specific indices
                    let idx = *idx as usize;
                    let value = ctx
                        .row
                        .get(idx)
                        .cloned()
                        .unwrap_or_else(Value::null_unknown);
                    self.stack.push(value);
                    pc += 1;
                }

                Op::LoadTransactionId => {
                    // Load current transaction ID, or NULL if not in a transaction
                    let value = match ctx.transaction_id {
                        Some(txn_id) => Value::Integer(i64::try_from(txn_id).map_err(|_| {
                            radixdb_core::Error::invalid_argument(
                                "transaction ID exceeds the SQL INTEGER domain",
                            )
                        })?),
                        None => Value::null_unknown(),
                    };
                    self.stack.push(value);
                    pc += 1;
                }

                // =============================================================
                // COMPARISON OPERATIONS
                // =============================================================
                Op::Eq => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::sql_equality_result(ctx, &a, &b, false)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Ne => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::sql_equality_result(ctx, &a, &b, true)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Lt => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::sql_order_result(ctx, &a, &b, |ordering| {
                        ordering == std::cmp::Ordering::Less
                    })?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Le => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::sql_order_result(ctx, &a, &b, |ordering| {
                        ordering != std::cmp::Ordering::Greater
                    })?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Gt => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::sql_order_result(ctx, &a, &b, |ordering| {
                        ordering == std::cmp::Ordering::Greater
                    })?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Ge => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::sql_order_result(ctx, &a, &b, |ordering| {
                        ordering != std::cmp::Ordering::Less
                    })?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::IsNull => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    self.stack.push(Value::Boolean(v.is_null()));
                    pc += 1;
                }

                Op::IsNotNull => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    self.stack.push(Value::Boolean(!v.is_null()));
                    pc += 1;
                }

                Op::IsDistinctFrom => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    // NULL IS DISTINCT FROM NULL = FALSE
                    // NULL IS DISTINCT FROM non-NULL = TRUE
                    // non-NULL IS DISTINCT FROM NULL = TRUE
                    // Otherwise use regular comparison
                    let result = match (a.is_null(), b.is_null()) {
                        (true, true) => false,
                        (true, false) | (false, true) => true,
                        (false, false) => !Self::sql_values_equal(ctx, &a, &b)?,
                    };
                    self.stack.push(Value::Boolean(result));
                    pc += 1;
                }

                Op::IsNotDistinctFrom => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (a.is_null(), b.is_null()) {
                        (true, true) => true,
                        (true, false) | (false, true) => false,
                        (false, false) => Self::sql_values_equal(ctx, &a, &b)?,
                    };
                    self.stack.push(Value::Boolean(result));
                    pc += 1;
                }

                // =============================================================
                // FUSED COMPARISON OPERATIONS
                // Single instruction for column vs constant (avoids push/pop)
                // =============================================================
                Op::EqColumnConst(idx, val) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    let result = Self::sql_equality_result(ctx, col_val, val, false)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::NeColumnConst(idx, val) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    let result = Self::sql_equality_result(ctx, col_val, val, true)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::LtColumnConst(idx, val) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    let result = Self::sql_order_result(ctx, col_val, val, |ordering| {
                        ordering == std::cmp::Ordering::Less
                    })?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::LeColumnConst(idx, val) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    let result = Self::sql_order_result(ctx, col_val, val, |ordering| {
                        ordering != std::cmp::Ordering::Greater
                    })?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::GtColumnConst(idx, val) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    let result = Self::sql_order_result(ctx, col_val, val, |ordering| {
                        ordering == std::cmp::Ordering::Greater
                    })?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::GeColumnConst(idx, val) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    let result = Self::sql_order_result(ctx, col_val, val, |ordering| {
                        ordering != std::cmp::Ordering::Less
                    })?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::IsNullColumn(idx) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    self.stack.push(Value::Boolean(col_val.is_null()));
                    pc += 1;
                }

                Op::IsNotNullColumn(idx) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    self.stack.push(Value::Boolean(!col_val.is_null()));
                    pc += 1;
                }

                Op::LikeColumn(idx, pattern, case_insensitive) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    let result = match col_val {
                        Value::Text(s) => Value::Boolean(pattern.matches(s, *case_insensitive)),
                        Value::Null(_) => Value::Null(DataType::Boolean),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::InSetColumn(idx, set, has_null) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    let result = if col_val.is_null() {
                        Value::Null(DataType::Boolean)
                    } else if Self::sql_set_contains(ctx, set, col_val)? {
                        Value::Boolean(true)
                    } else if *has_null {
                        Value::Null(DataType::Boolean)
                    } else {
                        Value::Boolean(false)
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::BetweenColumnConst(idx, low, high) => {
                    let col_val = ctx
                        .row
                        .get(*idx as usize)
                        .unwrap_or(&Value::Null(DataType::Null));
                    let result = Self::sql_between_result(ctx, col_val, low, high, false)?;
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // LOGICAL OPERATIONS
                // =============================================================
                Op::And(jump_target) => {
                    // Short-circuit AND: if top is false, jump
                    let top = self.stack.last().unwrap_or(&Value::Null(DataType::Boolean));
                    match top {
                        Value::Boolean(false) => {
                            // Result is false, jump to target
                            pc = *jump_target as usize;
                        }
                        Value::Null(_) => {
                            // Need to evaluate right side to check for false
                            pc += 1;
                        }
                        _ => {
                            // True or truthy, continue to evaluate right side
                            pc += 1;
                        }
                    }
                }

                Op::Or(jump_target) => {
                    // Short-circuit OR: if top is true, jump
                    let top = self.stack.last().unwrap_or(&Value::Null(DataType::Boolean));
                    match top {
                        Value::Boolean(true) => {
                            // Result is true, jump to target
                            pc = *jump_target as usize;
                        }
                        Value::Null(_) => {
                            // Need to evaluate right side to check for true
                            pc += 1;
                        }
                        _ => {
                            // False or falsy, continue to evaluate right side
                            pc += 1;
                        }
                    }
                }

                Op::AndFinalize => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (Self::to_tribool(&a), Self::to_tribool(&b)) {
                        (Some(false), _) | (_, Some(false)) => Value::Boolean(false),
                        (Some(true), Some(true)) => Value::Boolean(true),
                        _ => Value::Null(DataType::Boolean),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::OrFinalize => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (Self::to_tribool(&a), Self::to_tribool(&b)) {
                        (Some(true), _) | (_, Some(true)) => Value::Boolean(true),
                        (Some(false), Some(false)) => Value::Boolean(false),
                        _ => Value::Null(DataType::Boolean),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Not => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match Self::to_tribool(&v) {
                        Some(b) => Value::Boolean(!b),
                        None => Value::Null(DataType::Boolean),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Xor => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (Self::to_tribool(&a), Self::to_tribool(&b)) {
                        (Some(a), Some(b)) => Value::Boolean(a ^ b),
                        _ => Value::Null(DataType::Boolean),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // ARITHMETIC OPERATIONS
                // =============================================================
                Op::Add => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    // Handle timestamp + interval or timestamp + integer (days)
                    let result = match (&a, &b) {
                        (Value::Timestamp(t), Value::Integer(days)) => {
                            Self::timestamp_add_days(*t, *days)?
                        }
                        (Value::Integer(days), Value::Timestamp(t)) => {
                            Self::timestamp_add_days(*t, *days)?
                        }
                        (Value::Extension(_), Value::Integer(days))
                            if a.as_date_days().is_some() =>
                        {
                            Self::date_add_days(a.as_date_days().expect("date was checked"), *days)?
                        }
                        (Value::Integer(days), Value::Extension(_))
                            if b.as_date_days().is_some() =>
                        {
                            Self::date_add_days(b.as_date_days().expect("date was checked"), *days)?
                        }
                        (Value::Timestamp(_), Value::Text(_)) => {
                            // Parse interval string - pass references directly to avoid clone
                            self.timestamp_add_interval(&a, &b, true)?
                        }
                        _ => Self::arithmetic_op(&a, &b, ArithmeticOp::Add, |x, y| x + y)?,
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Sub => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    // Handle timestamp - interval, timestamp - integer (days), or timestamp - timestamp
                    let result = match (&a, &b) {
                        (Value::Timestamp(t1), Value::Timestamp(t2)) => {
                            // Return interval text
                            let duration = t1.signed_duration_since(*t2);
                            Value::Text(SmartString::from_string(
                                self.format_duration_as_interval(duration),
                            ))
                        }
                        (Value::Timestamp(t), Value::Integer(days)) => Self::timestamp_add_days(
                            *t,
                            days.checked_neg().ok_or_else(|| {
                                Error::Type("timestamp interval overflow".to_string())
                            })?,
                        )?,
                        (Value::Extension(_), Value::Integer(days))
                            if a.as_date_days().is_some() =>
                        {
                            Self::date_add_days(
                                a.as_date_days().expect("date was checked"),
                                days.checked_neg().ok_or_else(|| {
                                    Error::Type("DATE arithmetic overflow".to_string())
                                })?,
                            )?
                        }
                        (Value::Extension(_), Value::Extension(_))
                            if a.as_date_days().is_some() && b.as_date_days().is_some() =>
                        {
                            Value::Integer(
                                i64::from(a.as_date_days().expect("date was checked"))
                                    - i64::from(b.as_date_days().expect("date was checked")),
                            )
                        }
                        (Value::Timestamp(_), Value::Text(_)) => {
                            // Parse interval string - pass references directly to avoid clone
                            self.timestamp_add_interval(&a, &b, false)?
                        }
                        _ => Self::arithmetic_op(&a, &b, ArithmeticOp::Sub, |x, y| x - y)?,
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Mul => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::arithmetic_op(&a, &b, ArithmeticOp::Mul, |x, y| x * y)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Div => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::div_op(&a, &b)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Mod => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::mod_op(&a, &b)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Neg => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match v {
                        Value::Integer(i) => match i.checked_neg() {
                            Some(neg) => Value::Integer(neg),
                            None => Value::Null(DataType::Integer), // i64::MIN overflow
                        },
                        Value::Float(f) => Value::Float(-f),
                        Value::Null(dt) => Value::Null(dt),
                        _ => Value::Null(DataType::Null),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // BITWISE OPERATIONS (inlined for performance)
                // =============================================================
                Op::BitAnd => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&a, &b) {
                        (Value::Integer(x), Value::Integer(y)) => Value::Integer(x & y),
                        _ if a.is_null() || b.is_null() => Value::Null(DataType::Integer),
                        _ => Value::Null(DataType::Null),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::BitOr => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&a, &b) {
                        (Value::Integer(x), Value::Integer(y)) => Value::Integer(x | y),
                        _ if a.is_null() || b.is_null() => Value::Null(DataType::Integer),
                        _ => Value::Null(DataType::Null),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::BitXor => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&a, &b) {
                        (Value::Integer(x), Value::Integer(y)) => Value::Integer(x ^ y),
                        _ if a.is_null() || b.is_null() => Value::Null(DataType::Integer),
                        _ => Value::Null(DataType::Null),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::BitNot => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match v {
                        Value::Integer(i) => Value::Integer(!i),
                        Value::Null(dt) => Value::Null(dt),
                        _ => Value::Null(DataType::Null),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Shl => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&a, &b) {
                        (Value::Integer(x), Value::Integer(y)) => {
                            Value::Integer(x.wrapping_shl(*y as u32))
                        }
                        _ if a.is_null() || b.is_null() => Value::Null(DataType::Integer),
                        _ => Value::Null(DataType::Null),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Shr => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&a, &b) {
                        (Value::Integer(x), Value::Integer(y)) => {
                            Value::Integer(x.wrapping_shr(*y as u32))
                        }
                        _ if a.is_null() || b.is_null() => Value::Null(DataType::Integer),
                        _ => Value::Null(DataType::Null),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // STRING OPERATIONS
                // =============================================================
                Op::Concat => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = if a.is_null() || b.is_null() {
                        Value::Null(DataType::Text)
                    } else {
                        // Fast path: both are Text
                        match (&a, &b) {
                            (Value::Text(a_str), Value::Text(b_str)) => {
                                // Use optimized concat - handles inline and heap efficiently
                                Value::Text(SmartString::concat(a_str, b_str))
                            }
                            (Value::Text(a_str), _) => {
                                // a is Text, b needs conversion - use Arc to avoid shrink_to_fit
                                use std::fmt::Write;
                                let mut s = String::with_capacity(a_str.len() + 32);
                                s.push_str(a_str);
                                let _ = write!(s, "{}", b);
                                Value::Text(SmartString::from_string_shared(s))
                            }
                            (_, Value::Text(b_str)) => {
                                // a needs conversion, b is Text - use Arc to avoid shrink_to_fit
                                use std::fmt::Write;
                                let mut s = String::with_capacity(32 + b_str.len());
                                let _ = write!(s, "{}", a);
                                s.push_str(b_str);
                                Value::Text(SmartString::from_string_shared(s))
                            }
                            _ => {
                                // Both need conversion - use Arc to avoid shrink_to_fit
                                use std::fmt::Write;
                                let mut s = String::with_capacity(64);
                                let _ = write!(s, "{}{}", a, b);
                                Value::Text(SmartString::from_string_shared(s))
                            }
                        }
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::ConcatN(n) => {
                    let n = *n as usize;
                    let start = self.stack.len().saturating_sub(n);

                    // Single pass: check for NULL and calculate total length
                    let mut total_len = 0usize;
                    let mut has_null = false;
                    let mut all_text = true;

                    for v in &self.stack[start..] {
                        match v {
                            Value::Null(_) => {
                                has_null = true;
                                break;
                            }
                            Value::Text(s) => total_len += s.len(),
                            _ => {
                                all_text = false;
                                total_len += 32;
                            }
                        }
                    }

                    if has_null {
                        self.stack.truncate(start);
                        self.stack.push(Value::Null(DataType::Text));
                        pc += 1;
                        continue;
                    }

                    // Build result - optimize for inline vs heap
                    let result = if all_text && total_len <= 15 {
                        // Fast path: build directly into inline SmartString (no heap allocation)
                        let mut data = [0u8; 15];
                        let mut pos = 0;
                        for v in self.stack.drain(start..) {
                            if let Value::Text(text) = v {
                                let bytes = text.as_bytes();
                                data[pos..pos + bytes.len()].copy_from_slice(bytes);
                                pos += bytes.len();
                            }
                        }
                        let text = std::str::from_utf8(&data[..total_len])
                            .expect("concatenated Text values remain valid UTF-8");
                        SmartString::new(text)
                    } else if all_text {
                        // Heap path: exact capacity, into_boxed_str is O(1) when len == capacity
                        let mut s = String::with_capacity(total_len);
                        for v in self.stack.drain(start..) {
                            if let Value::Text(text) = v {
                                s.push_str(&text);
                            }
                        }
                        // len == capacity, so into_boxed_str is O(1)
                        SmartString::from_string(s)
                    } else {
                        // Mixed types: capacity is estimate, use Arc to avoid shrink_to_fit
                        let mut s = String::with_capacity(total_len);
                        for v in self.stack.drain(start..) {
                            match v {
                                Value::Text(text) => s.push_str(&text),
                                _ => {
                                    use std::fmt::Write;
                                    let _ = write!(s, "{}", v);
                                }
                            }
                        }
                        SmartString::from_string_shared(s)
                    };
                    self.stack.push(Value::Text(result));
                    pc += 1;
                }

                Op::Like(pattern, case_insensitive) => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match &v {
                        Value::Text(s) => Value::Boolean(pattern.matches(s, *case_insensitive)),
                        Value::Null(_) => Value::Null(DataType::Boolean),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Glob(pattern) => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match &v {
                        Value::Text(s) => Value::Boolean(pattern.matches(s, false)),
                        Value::Null(_) => Value::Null(DataType::Boolean),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Regexp(regex) => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match &v {
                        Value::Text(s) => Value::Boolean(regex.is_match(s)),
                        Value::Null(_) => Value::Null(DataType::Boolean),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::LikeEscape(pattern, case_insensitive, _escape) => {
                    // ESCAPE is already incorporated into the compiled pattern
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match &v {
                        Value::Text(s) => Value::Boolean(pattern.matches(s, *case_insensitive)),
                        Value::Null(_) => Value::Null(DataType::Boolean),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::LikeDynamic(case_insensitive) => {
                    let pattern_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let text_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let ci = *case_insensitive;
                    let result = match (&text_val, &pattern_val) {
                        (Value::Text(text), Value::Text(pat)) => {
                            // Cache compiled pattern: parameters are constant per query,
                            // so recompiling every row is wasteful
                            let need_compile = match &self.cached_like {
                                Some((cached_pat, cached_ci, cached_esc, _)) => {
                                    cached_pat.as_str() != pat.as_str()
                                        || *cached_ci != ci
                                        || cached_esc.is_some()
                                }
                                None => true,
                            };
                            if need_compile {
                                let compiled = CompiledPattern::compile(pat, ci)?;
                                self.cached_like = Some((pat.clone(), ci, None, compiled));
                            }
                            let (_, _, _, ref compiled) = self.cached_like.as_ref().unwrap();
                            Value::Boolean(compiled.matches(text, ci))
                        }
                        (Value::Null(_), _) | (_, Value::Null(_)) => Value::Null(DataType::Boolean),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::LikeDynamicEscape(case_insensitive, escape_char) => {
                    let pattern_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let text_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&text_val, &pattern_val) {
                        (Value::Text(text), Value::Text(pat)) => {
                            let ci = *case_insensitive;
                            let esc = *escape_char;
                            let need_compile = match &self.cached_like {
                                Some((cached_pat, cached_ci, cached_esc, _)) => {
                                    cached_pat.as_str() != pat.as_str()
                                        || *cached_ci != ci
                                        || *cached_esc != Some(esc)
                                }
                                None => true,
                            };
                            if need_compile {
                                // Pre-process the escape character in the pattern at runtime,
                                // converting e.g. !% -> \% so CompiledPattern treats it as literal
                                let processed = process_like_escape_runtime(pat, esc);
                                let compiled = CompiledPattern::compile(&processed, ci)?;
                                self.cached_like = Some((pat.clone(), ci, Some(esc), compiled));
                            }
                            let (_, _, _, ref compiled) = self.cached_like.as_ref().unwrap();
                            Value::Boolean(compiled.matches(text, ci))
                        }
                        (Value::Null(_), _) | (_, Value::Null(_)) => Value::Null(DataType::Boolean),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::GlobDynamic => {
                    let pattern_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let text_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&text_val, &pattern_val) {
                        (Value::Text(text), Value::Text(pat)) => {
                            let need_compile = match &self.cached_glob {
                                Some((cached_pat, _)) => cached_pat.as_str() != pat.as_str(),
                                None => true,
                            };
                            if need_compile {
                                let compiled = CompiledPattern::compile_glob(pat)?;
                                self.cached_glob = Some((pat.clone(), compiled));
                            }
                            let (_, ref compiled) = self.cached_glob.as_ref().unwrap();
                            Value::Boolean(compiled.matches(text, false))
                        }
                        (Value::Null(_), _) | (_, Value::Null(_)) => Value::Null(DataType::Boolean),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::RegexpDynamic => {
                    let pattern_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let text_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&text_val, &pattern_val) {
                        (Value::Text(text), Value::Text(pat)) => {
                            let need_compile = match &self.cached_regexp {
                                Some((cached_pat, _)) => cached_pat.as_str() != pat.as_str(),
                                None => true,
                            };
                            if need_compile {
                                match regex::Regex::new(pat) {
                                    Ok(re) => {
                                        self.cached_regexp = Some((pat.clone(), re));
                                    }
                                    Err(e) => {
                                        self.cached_regexp = None;
                                        // Return error for invalid regex, matching literal
                                        // REGEXP behavior where bad patterns fail at compile time
                                        return Err(radixdb_core::Error::invalid_argument(
                                            format!("Invalid regular expression '{}': {}", pat, e),
                                        ));
                                    }
                                }
                            }
                            let (_, ref re) = self.cached_regexp.as_ref().unwrap();
                            Value::Boolean(re.is_match(text))
                        }
                        (Value::Null(_), _) | (_, Value::Null(_)) => Value::Null(DataType::Boolean),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // JSON OPERATIONS
                // =============================================================
                Op::JsonAccess => {
                    let key = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let json_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = self.json_access(&json_val, &key, false);
                    self.stack.push(result);
                    pc += 1;
                }

                Op::JsonAccessText => {
                    let key = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let json_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = self.json_access(&json_val, &key, true);
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // TIMESTAMP OPERATIONS
                // =============================================================
                Op::TimestampAddInterval => {
                    let interval = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let ts = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = self.timestamp_add_interval(&ts, &interval, true)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::TimestampSubInterval => {
                    let interval = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let ts = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = self.timestamp_add_interval(&ts, &interval, false)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::TimestampDiff => {
                    let ts2 = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let ts1 = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&ts1, &ts2) {
                        (Value::Timestamp(t1), Value::Timestamp(t2)) => {
                            let duration = t1.signed_duration_since(*t2);
                            Value::Text(SmartString::from_string(
                                self.format_duration_as_interval(duration),
                            ))
                        }
                        _ if ts1.is_null() || ts2.is_null() => Value::Null(DataType::Text),
                        _ => Value::Null(DataType::Text),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::TimestampAddDays => {
                    let days = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let ts = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&ts, &days) {
                        (Value::Timestamp(t), Value::Integer(d)) => {
                            Value::Timestamp(*t + chrono::Duration::days(*d))
                        }
                        (Value::Extension(_), Value::Integer(d)) if ts.as_date_days().is_some() => {
                            Self::date_add_days(ts.as_date_days().expect("date was checked"), *d)?
                        }
                        _ if ts.is_null() || days.is_null() => Value::Null(DataType::Timestamp),
                        _ => Value::Null(DataType::Timestamp),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::TimestampSubDays => {
                    let days = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let ts = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match (&ts, &days) {
                        (Value::Timestamp(t), Value::Integer(d)) => {
                            Value::Timestamp(*t - chrono::Duration::days(*d))
                        }
                        (Value::Extension(_), Value::Integer(d)) if ts.as_date_days().is_some() => {
                            Self::date_add_days(
                                ts.as_date_days().expect("date was checked"),
                                d.checked_neg().ok_or_else(|| {
                                    Error::Type("DATE arithmetic overflow".to_string())
                                })?,
                            )?
                        }
                        _ if ts.is_null() || days.is_null() => Value::Null(DataType::Timestamp),
                        _ => Value::Null(DataType::Timestamp),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // SET OPERATIONS
                // =============================================================
                Op::InSet(set, has_null) => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = if v.is_null() {
                        Value::Null(DataType::Boolean)
                    } else if Self::sql_set_contains(ctx, set, &v)? {
                        Value::Boolean(true)
                    } else if *has_null {
                        Value::Null(DataType::Boolean)
                    } else {
                        Value::Boolean(false)
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::NotInSet(set, has_null) => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = if v.is_null() {
                        Value::Null(DataType::Boolean)
                    } else if Self::sql_set_contains(ctx, set, &v)? {
                        Value::Boolean(false)
                    } else if *has_null {
                        Value::Null(DataType::Boolean)
                    } else {
                        Value::Boolean(true)
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Between => {
                    let high = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let low = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::sql_between_result(ctx, &val, &low, &high, false)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::NotBetween => {
                    let high = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let low = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = Self::sql_between_result(ctx, &val, &low, &high, true)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::InTupleSet {
                    tuple_size,
                    values,
                    negated,
                } => {
                    let tuple_size = *tuple_size as usize;
                    let start = self.stack.len().saturating_sub(tuple_size);

                    // Reuse args_buffer to avoid allocation
                    self.args_buffer.clear();
                    self.args_buffer.extend(self.stack.drain(start..));

                    // Check if any values are NULL
                    let has_null_in_tuple = self.args_buffer.iter().any(|v| v.is_null());

                    if has_null_in_tuple {
                        // NULL in tuple -> result is NULL
                        self.stack.push(Value::Null(DataType::Boolean));
                    } else {
                        // Check membership
                        let mut found = false;
                        for tuple in values.iter() {
                            if tuple.len() != self.args_buffer.len() {
                                continue;
                            }
                            let mut equal = true;
                            for (left, right) in tuple.iter().zip(self.args_buffer.iter()) {
                                if !Self::sql_values_equal(ctx, left, right)? {
                                    equal = false;
                                    break;
                                }
                            }
                            if equal {
                                found = true;
                                break;
                            }
                        }

                        let result = if *negated { !found } else { found };
                        self.stack.push(Value::Boolean(result));
                    }
                    pc += 1;
                }

                // =============================================================
                // BOOLEAN CHECKS
                // =============================================================
                Op::IsTrue => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match v {
                        Value::Boolean(b) => Value::Boolean(b),
                        Value::Null(_) => Value::Boolean(false),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::IsNotTrue => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match v {
                        Value::Boolean(b) => Value::Boolean(!b),
                        Value::Null(_) => Value::Boolean(true),
                        _ => Value::Boolean(true),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::IsFalse => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match v {
                        Value::Boolean(b) => Value::Boolean(!b),
                        Value::Null(_) => Value::Boolean(false),
                        _ => Value::Boolean(false),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::IsNotFalse => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match v {
                        Value::Boolean(b) => Value::Boolean(b),
                        Value::Null(_) => Value::Boolean(true),
                        _ => Value::Boolean(true),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // FUNCTION CALLS
                // =============================================================
                Op::CallScalar { func, arg_count } => {
                    let arg_count = *arg_count as usize;
                    let start = self.stack.len().saturating_sub(arg_count);

                    // Reuse args_buffer to avoid allocation
                    self.args_buffer.clear();
                    self.args_buffer.extend(self.stack.drain(start..));

                    func.info().signature.validate_values(&self.args_buffer)?;
                    let result = crate::context::with_current_query_cancellation(|cancellation| {
                        func.evaluate_with_cancellation(&self.args_buffer, cancellation)
                    })?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::CallStored { name, arg_count } => {
                    let arg_count = *arg_count as usize;
                    let start = self.stack.len().saturating_sub(arg_count);
                    self.args_buffer.clear();
                    self.args_buffer.extend(self.stack.drain(start..));
                    let invoker = ctx.stored_function_invoker.ok_or_else(|| {
                        Error::invalid_argument(format!(
                            "stored function {name} is unavailable in this execution context"
                        ))
                    })?;
                    let result = Arc::clone(invoker).invoke(name, &self.args_buffer)?;
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Coalesce(n) => {
                    let n = *n as usize;
                    let start = self.stack.len().saturating_sub(n);

                    // Find first non-null using slice iteration (no intermediate buffer)
                    let result_idx = self.stack[start..]
                        .iter()
                        .position(|v| !v.is_null())
                        .map(|i| start + i);

                    let result = if let Some(idx) = result_idx {
                        // Swap the result to end, pop it, then truncate the rest
                        let last = self.stack.len() - 1;
                        self.stack.swap(idx, last);
                        let result = self.stack.pop().unwrap_or_else(Value::null_unknown);
                        self.stack.truncate(start);
                        result
                    } else {
                        self.stack.truncate(start);
                        Value::null_unknown()
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::NullIf => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = if Self::sql_values_equal(ctx, &a, &b)? {
                        Value::null_unknown()
                    } else {
                        a
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Greatest(n) => {
                    let n = *n as usize;
                    let start = self.stack.len().saturating_sub(n);

                    // Find max using slice iteration (no intermediate buffer)
                    let mut max_idx: Option<usize> = None;
                    for (i, v) in self.stack[start..].iter().enumerate() {
                        if !v.is_null() {
                            match max_idx {
                                None => max_idx = Some(start + i),
                                Some(mi) => {
                                    if matches!(
                                        Self::sql_ordering(ctx, v, &self.stack[mi])?,
                                        Some(std::cmp::Ordering::Greater)
                                    ) {
                                        max_idx = Some(start + i);
                                    }
                                }
                            }
                        }
                    }

                    let result = if let Some(idx) = max_idx {
                        // Swap the result to end, pop it, then truncate the rest
                        let last = self.stack.len() - 1;
                        self.stack.swap(idx, last);
                        let result = self.stack.pop().unwrap_or_else(Value::null_unknown);
                        self.stack.truncate(start);
                        result
                    } else {
                        self.stack.truncate(start);
                        Value::null_unknown()
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::Least(n) => {
                    let n = *n as usize;
                    let start = self.stack.len().saturating_sub(n);

                    // Find min using slice iteration (no intermediate buffer)
                    let mut min_idx: Option<usize> = None;
                    for (i, v) in self.stack[start..].iter().enumerate() {
                        if !v.is_null() {
                            match min_idx {
                                None => min_idx = Some(start + i),
                                Some(mi) => {
                                    if matches!(
                                        Self::sql_ordering(ctx, v, &self.stack[mi])?,
                                        Some(std::cmp::Ordering::Less)
                                    ) {
                                        min_idx = Some(start + i);
                                    }
                                }
                            }
                        }
                    }

                    let result = if let Some(idx) = min_idx {
                        // Swap the result to end, pop it, then truncate the rest
                        let last = self.stack.len() - 1;
                        self.stack.swap(idx, last);
                        let result = self.stack.pop().unwrap_or_else(Value::null_unknown);
                        self.stack.truncate(start);
                        result
                    } else {
                        self.stack.truncate(start);
                        Value::null_unknown()
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // NATIVE SCALAR FUNCTIONS (direct function pointer call)
                // In-place mutation - no pop/push overhead
                // =============================================================
                Op::NativeFn1(func) => {
                    if let Some(v) = self.stack.last_mut() {
                        func(v);
                    }
                    pc += 1;
                }

                // =============================================================
                // TYPE OPERATIONS
                // =============================================================
                Op::Cast(target_type) => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = if v.as_external().is_some() {
                        let invoker = ctx.stored_function_invoker.ok_or_else(|| {
                            Error::invalid_argument(
                                "external type output is unavailable in this execution context",
                            )
                        })?;
                        invoker.external_output(&v, *target_type)?
                    } else {
                        v.try_coerce_to_type(*target_type)?
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                Op::CastExternal(type_name) => {
                    let value = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let invoker = ctx.stored_function_invoker.ok_or_else(|| {
                        Error::invalid_argument(
                            "external type input is unavailable in this execution context",
                        )
                    })?;
                    self.stack.push(invoker.external_input(type_name, &value)?);
                    pc += 1;
                }

                Op::TruncateToDate => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = match &v {
                        Value::Timestamp(t) => {
                            use chrono::{Datelike, TimeZone, Utc};
                            let truncated = Utc
                                .with_ymd_and_hms(t.year(), t.month(), t.day(), 0, 0, 0)
                                .single()
                                .unwrap_or(*t);
                            Value::Timestamp(truncated)
                        }
                        Value::Text(s) => match radixdb_core::parse_timestamp(s) {
                            Ok(t) => {
                                use chrono::{Datelike, TimeZone, Utc};
                                let truncated = Utc
                                    .with_ymd_and_hms(t.year(), t.month(), t.day(), 0, 0, 0)
                                    .single()
                                    .unwrap_or(t);
                                Value::Timestamp(truncated)
                            }
                            Err(_) => Value::Null(DataType::Timestamp),
                        },
                        Value::Integer(i) => {
                            use chrono::{Datelike, TimeZone, Utc};
                            match Utc.timestamp_opt(*i, 0) {
                                chrono::LocalResult::Single(t) => {
                                    let truncated = Utc
                                        .with_ymd_and_hms(t.year(), t.month(), t.day(), 0, 0, 0)
                                        .single()
                                        .unwrap_or(t);
                                    Value::Timestamp(truncated)
                                }
                                _ => Value::Null(DataType::Timestamp),
                            }
                        }
                        Value::Null(_) => Value::Null(DataType::Timestamp),
                        _ => Value::Null(DataType::Timestamp),
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // CASE EXPRESSION
                // =============================================================
                Op::CaseStart => {
                    // Marker only, no operation
                    pc += 1;
                }

                Op::CaseWhen(next_branch) => {
                    let cond = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    if !Self::to_bool(&cond) {
                        pc = *next_branch as usize;
                    } else {
                        pc += 1;
                    }
                }

                Op::CaseThen(end_pos) => {
                    // Result is on stack, jump to end
                    pc = *end_pos as usize;
                }

                Op::CaseElse => {
                    // Marker only
                    pc += 1;
                }

                Op::CaseEnd => {
                    // Marker only
                    pc += 1;
                }

                Op::CaseCompare => {
                    let when_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let case_val = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let result = if !case_val.is_null() && !when_val.is_null() {
                        Value::Boolean(case_val == when_val)
                    } else {
                        Value::Boolean(false)
                    };
                    self.stack.push(result);
                    pc += 1;
                }

                // =============================================================
                // CONTROL FLOW
                // =============================================================
                Op::Jump(target) => {
                    pc = *target as usize;
                }

                Op::JumpIfTrue(target) => {
                    let top = self.stack.last().unwrap_or(&Value::Null(DataType::Boolean));
                    if Self::to_bool(top) {
                        pc = *target as usize;
                    } else {
                        pc += 1;
                    }
                }

                Op::JumpIfFalse(target) => {
                    let top = self.stack.last().unwrap_or(&Value::Null(DataType::Boolean));
                    if !Self::to_bool(top) {
                        pc = *target as usize;
                    } else {
                        pc += 1;
                    }
                }

                Op::JumpIfNull(target) => {
                    let top = self.stack.last().unwrap_or(&Value::Null(DataType::Boolean));
                    if top.is_null() {
                        pc = *target as usize;
                    } else {
                        pc += 1;
                    }
                }

                Op::JumpIfNotNull(target) => {
                    let top = self.stack.last().unwrap_or(&Value::Null(DataType::Boolean));
                    if !top.is_null() {
                        pc = *target as usize;
                    } else {
                        pc += 1;
                    }
                }

                Op::PopJumpIfTrue(target) => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    if Self::to_bool(&v) {
                        pc = *target as usize;
                    } else {
                        pc += 1;
                    }
                }

                Op::PopJumpIfFalse(target) => {
                    let v = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    if !Self::to_bool(&v) {
                        pc = *target as usize;
                    } else {
                        pc += 1;
                    }
                }

                Op::Dup => {
                    if let Some(v) = self.stack.last().cloned() {
                        self.stack.push(v);
                    }
                    pc += 1;
                }

                Op::Pop => {
                    // Use truncate instead of pop to drop in-place without copying value out
                    let new_len = self.stack.len().saturating_sub(1);
                    self.stack.truncate(new_len);
                    pc += 1;
                }

                Op::Swap => {
                    let len = self.stack.len();
                    if len >= 2 {
                        self.stack.swap(len - 1, len - 2);
                    }
                    pc += 1;
                }

                // =============================================================
                // SPECIAL
                // =============================================================
                Op::Nop => {
                    pc += 1;
                }

                Op::Return => {
                    break;
                }

                Op::ReturnTrue => {
                    self.stack.clear();
                    self.stack.push(Value::Boolean(true));
                    break;
                }

                Op::ReturnFalse => {
                    self.stack.clear();
                    self.stack.push(Value::Boolean(false));
                    break;
                }

                Op::ReturnNull(dt) => {
                    self.stack.clear();
                    self.stack.push(Value::Null(*dt));
                    break;
                }

                // =============================================================
                // VECTOR DISTANCE OPERATIONS
                // =============================================================
                Op::VectorDistanceL2 => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let mut buf_a = Vec::new();
                    let mut buf_b = Vec::new();
                    if a.is_null() || b.is_null() {
                        self.stack.push(Value::null_unknown());
                    } else {
                        match (
                            extract_vector_bytes(&a, &mut buf_a),
                            extract_vector_bytes(&b, &mut buf_b),
                        ) {
                            (Some(ba), Some(bb)) => {
                                self.stack.push(Value::Float(
                                    radixdb_functions::scalar::vector::l2_distance_bytes(ba, bb)?,
                                ));
                            }
                            _ => {
                                return Err(Error::Type(
                                    "vector distance requires two valid VECTOR values".to_string(),
                                ));
                            }
                        }
                    }
                    pc += 1;
                }

                Op::VectorDistanceCosine => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let mut buf_a = Vec::new();
                    let mut buf_b = Vec::new();
                    if a.is_null() || b.is_null() {
                        self.stack.push(Value::null_unknown());
                    } else {
                        match (
                            extract_vector_bytes(&a, &mut buf_a),
                            extract_vector_bytes(&b, &mut buf_b),
                        ) {
                            (Some(ba), Some(bb)) => {
                                self.stack.push(Value::Float(
                                    radixdb_functions::scalar::vector::cosine_distance_bytes(
                                        ba, bb,
                                    )?,
                                ));
                            }
                            _ => {
                                return Err(Error::Type(
                                    "vector distance requires two valid VECTOR values".to_string(),
                                ));
                            }
                        }
                    }
                    pc += 1;
                }

                Op::VectorDistanceIP => {
                    let b = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let a = self.stack.pop().unwrap_or_else(Value::null_unknown);
                    let mut buf_a = Vec::new();
                    let mut buf_b = Vec::new();
                    if a.is_null() || b.is_null() {
                        self.stack.push(Value::null_unknown());
                    } else {
                        match (
                            extract_vector_bytes(&a, &mut buf_a),
                            extract_vector_bytes(&b, &mut buf_b),
                        ) {
                            (Some(ba), Some(bb)) => {
                                self.stack.push(Value::Float(
                                    radixdb_functions::scalar::vector::ip_distance_bytes(ba, bb)?,
                                ));
                            }
                            _ => {
                                return Err(Error::Type(
                                    "vector distance requires two valid VECTOR values".to_string(),
                                ));
                            }
                        }
                    }
                    pc += 1;
                }
            }
        }

        // Return top of stack or NULL
        Ok(self.stack.pop().unwrap_or_else(Value::null_unknown))
    }

    /// Execute a program using borrowed values where possible (Cow-based stack)
    ///
    /// This version avoids cloning values from the row when possible.
    /// Values are only cloned when they need to be modified or passed to functions.
    #[inline]
    pub fn execute_cow<'a>(
        &mut self,
        program: &'a Program,
        ctx: &'a ExecuteContext<'a>,
    ) -> Result<Value> {
        // Choose the interpreter before executing any observable instruction.
        // Restarting after a partial Cow prefix would duplicate scalar calls.
        if !program.ops().iter().all(Self::cow_supports_op) {
            return self.execute(program, ctx);
        }

        // Local stack with borrowed values - lifetime tied to this execution
        let mut stack: SmallVec<[StackValue<'a>; STACK_INLINE_CAPACITY]> = SmallVec::new();

        let ops = program.ops();
        if ops.is_empty() {
            return Ok(NULL_VALUE.clone());
        }

        let mut pc: usize = 0;

        loop {
            if pc >= ops.len() {
                break;
            }

            match &ops[pc] {
                // LOAD OPERATIONS - borrow instead of clone
                Op::LoadColumn(idx) => {
                    let idx = *idx as usize;
                    let value = ctx
                        .row
                        .get(idx)
                        .map(Cow::Borrowed)
                        .unwrap_or_else(|| Cow::Borrowed(&NULL_VALUE));
                    stack.push(value);
                    pc += 1;
                }

                Op::LoadColumn2(idx) => {
                    let idx = *idx as usize;
                    let value = ctx
                        .row2
                        .and_then(|r| r.get(idx))
                        .map(Cow::Borrowed)
                        .unwrap_or_else(|| Cow::Borrowed(&NULL_VALUE));
                    stack.push(value);
                    pc += 1;
                }

                Op::LoadConst(value) => {
                    stack.push(Cow::Borrowed(value));
                    pc += 1;
                }

                Op::LoadParam(idx) => {
                    let idx = *idx as usize;
                    let value = ctx
                        .params
                        .get(idx)
                        .map(Cow::Borrowed)
                        .unwrap_or_else(|| Cow::Borrowed(&NULL_VALUE));
                    stack.push(value);
                    pc += 1;
                }

                Op::LoadNull(dt) => {
                    stack.push(Cow::Owned(Value::Null(*dt)));
                    pc += 1;
                }

                Op::LoadAggregateResult(idx) => {
                    let idx = *idx as usize;
                    let value = ctx
                        .row
                        .get(idx)
                        .map(Cow::Borrowed)
                        .unwrap_or_else(|| Cow::Borrowed(&NULL_VALUE));
                    stack.push(value);
                    pc += 1;
                }

                // COMPARISON OPERATIONS - work with references
                Op::Eq => {
                    let b = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let a = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = Self::sql_equality_result(ctx, a.as_ref(), b.as_ref(), false)?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::Ne => {
                    let b = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let a = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = Self::sql_equality_result(ctx, a.as_ref(), b.as_ref(), true)?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::Lt => {
                    let b = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let a = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = Self::sql_order_result(ctx, a.as_ref(), b.as_ref(), |ordering| {
                        ordering == std::cmp::Ordering::Less
                    })?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::Le => {
                    let b = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let a = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = Self::sql_order_result(ctx, a.as_ref(), b.as_ref(), |ordering| {
                        ordering != std::cmp::Ordering::Greater
                    })?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::Gt => {
                    let b = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let a = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = Self::sql_order_result(ctx, a.as_ref(), b.as_ref(), |ordering| {
                        ordering == std::cmp::Ordering::Greater
                    })?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::Ge => {
                    let b = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let a = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = Self::sql_order_result(ctx, a.as_ref(), b.as_ref(), |ordering| {
                        ordering != std::cmp::Ordering::Less
                    })?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::IsNull => {
                    let v = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    stack.push(Cow::Owned(Value::Boolean(v.is_null())));
                    pc += 1;
                }

                Op::IsNotNull => {
                    let v = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    stack.push(Cow::Owned(Value::Boolean(!v.is_null())));
                    pc += 1;
                }

                // LOGICAL OPERATIONS
                Op::And(jump_target) => {
                    let top = stack.last().map(|v| &**v).unwrap_or(&NULL_VALUE);
                    match top {
                        Value::Boolean(false) => pc = *jump_target as usize,
                        Value::Null(_) => pc += 1,
                        _ => pc += 1,
                    }
                }

                Op::Or(jump_target) => {
                    let top = stack.last().map(|v| &**v).unwrap_or(&NULL_VALUE);
                    match top {
                        Value::Boolean(true) => pc = *jump_target as usize,
                        Value::Null(_) => pc += 1,
                        _ => pc += 1,
                    }
                }

                Op::AndFinalize => {
                    let b = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let a = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = match (Self::to_tribool(&a), Self::to_tribool(&b)) {
                        (Some(false), _) | (_, Some(false)) => Value::Boolean(false),
                        (Some(true), Some(true)) => Value::Boolean(true),
                        _ => Value::Null(DataType::Boolean),
                    };
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::OrFinalize => {
                    let b = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let a = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = match (Self::to_tribool(&a), Self::to_tribool(&b)) {
                        (Some(true), _) | (_, Some(true)) => Value::Boolean(true),
                        (Some(false), Some(false)) => Value::Boolean(false),
                        _ => Value::Null(DataType::Boolean),
                    };
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::Not => {
                    let v = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = match Self::to_tribool(&v) {
                        Some(b) => Value::Boolean(!b),
                        None => Value::Null(DataType::Boolean),
                    };
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                // FUNCTION CALLS - need to convert to owned
                Op::CallScalar { func, arg_count } => {
                    let arg_count = *arg_count as usize;
                    let start = stack.len().saturating_sub(arg_count);

                    // Convert Cow values to owned for function call
                    self.args_buffer.clear();
                    for cow_val in stack.drain(start..) {
                        self.args_buffer.push(cow_val.into_owned());
                    }

                    func.info().signature.validate_values(&self.args_buffer)?;
                    let result = crate::context::with_current_query_cancellation(|cancellation| {
                        func.evaluate_with_cancellation(&self.args_buffer, cancellation)
                    })?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::CallStored { name, arg_count } => {
                    let arg_count = *arg_count as usize;
                    let start = stack.len().saturating_sub(arg_count);
                    self.args_buffer.clear();
                    for value in stack.drain(start..) {
                        self.args_buffer.push(value.into_owned());
                    }
                    let invoker = ctx.stored_function_invoker.ok_or_else(|| {
                        Error::invalid_argument(format!(
                            "stored function {name} is unavailable in this execution context"
                        ))
                    })?;
                    let result = Arc::clone(invoker).invoke(name, &self.args_buffer)?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                // FUSED OPERATIONS (already optimized, no stack involvement)
                Op::GtColumnConst(idx, val) => {
                    let col_val = ctx.row.get(*idx as usize).unwrap_or(&NULL_VALUE);
                    let result = Self::sql_order_result(ctx, col_val, val, |ordering| {
                        ordering == std::cmp::Ordering::Greater
                    })?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::LtColumnConst(idx, val) => {
                    let col_val = ctx.row.get(*idx as usize).unwrap_or(&NULL_VALUE);
                    let result = Self::sql_order_result(ctx, col_val, val, |ordering| {
                        ordering == std::cmp::Ordering::Less
                    })?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::EqColumnConst(idx, val) => {
                    let col_val = ctx.row.get(*idx as usize).unwrap_or(&NULL_VALUE);
                    let result = Self::sql_equality_result(ctx, col_val, val, false)?;
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                // COALESCE - return first non-null value
                Op::Coalesce(n) => {
                    let n = *n as usize;
                    let start = stack.len().saturating_sub(n);

                    // Find first non-null value index
                    let result_idx = stack[start..]
                        .iter()
                        .position(|v| !v.is_null())
                        .map(|i| start + i);

                    let result = if let Some(idx) = result_idx {
                        // Move the result out, swap to end, pop, then truncate
                        let last = stack.len() - 1;
                        stack.swap(idx, last);
                        // pop() should always succeed since we found an index
                        stack.pop().expect("stack underflow in COALESCE")
                    } else {
                        Cow::Borrowed(&NULL_VALUE)
                    };
                    stack.truncate(start);
                    stack.push(result);
                    pc += 1;
                }

                // NULLIF - return NULL if both args are equal
                Op::NullIf => {
                    let b = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let a = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = if Self::sql_values_equal(ctx, a.as_ref(), b.as_ref())? {
                        Cow::Borrowed(&NULL_VALUE)
                    } else {
                        a
                    };
                    stack.push(result);
                    pc += 1;
                }

                // GREATEST - return maximum non-null value
                Op::Greatest(n) => {
                    let n = *n as usize;
                    let start = stack.len().saturating_sub(n);

                    // Find max value index
                    let mut max_idx: Option<usize> = None;
                    for (i, v) in stack[start..].iter().enumerate() {
                        if !v.is_null() {
                            match max_idx {
                                None => max_idx = Some(start + i),
                                Some(mi) => {
                                    if matches!(
                                        Self::sql_ordering(ctx, v.as_ref(), stack[mi].as_ref())?,
                                        Some(std::cmp::Ordering::Greater)
                                    ) {
                                        max_idx = Some(start + i);
                                    }
                                }
                            }
                        }
                    }

                    let result = if let Some(idx) = max_idx {
                        let last = stack.len() - 1;
                        stack.swap(idx, last);
                        stack.pop().expect("stack underflow in GREATEST")
                    } else {
                        Cow::Borrowed(&NULL_VALUE)
                    };
                    stack.truncate(start);
                    stack.push(result);
                    pc += 1;
                }

                // LEAST - return minimum non-null value
                Op::Least(n) => {
                    let n = *n as usize;
                    let start = stack.len().saturating_sub(n);

                    // Find min value index
                    let mut min_idx: Option<usize> = None;
                    for (i, v) in stack[start..].iter().enumerate() {
                        if !v.is_null() {
                            match min_idx {
                                None => min_idx = Some(start + i),
                                Some(mi) => {
                                    if matches!(
                                        Self::sql_ordering(ctx, v.as_ref(), stack[mi].as_ref())?,
                                        Some(std::cmp::Ordering::Less)
                                    ) {
                                        min_idx = Some(start + i);
                                    }
                                }
                            }
                        }
                    }

                    let result = if let Some(idx) = min_idx {
                        let last = stack.len() - 1;
                        stack.swap(idx, last);
                        stack.pop().expect("stack underflow in LEAST")
                    } else {
                        Cow::Borrowed(&NULL_VALUE)
                    };
                    stack.truncate(start);
                    stack.push(result);
                    pc += 1;
                }

                // JUMP/CONTROL FLOW for short-circuit evaluation (used by COALESCE)
                Op::JumpIfNotNull(target) => {
                    if let Some(top) = stack.last() {
                        if !top.is_null() {
                            pc = *target as usize;
                            continue;
                        }
                    }
                    pc += 1;
                }

                Op::Pop => {
                    // Use truncate instead of pop to drop in-place without copying value out
                    let new_len = stack.len().saturating_sub(1);
                    stack.truncate(new_len);
                    pc += 1;
                }

                Op::Jump(target) => {
                    pc = *target as usize;
                }

                Op::JumpIfTrue(target) => {
                    if let Some(top) = stack.last() {
                        if Self::to_bool(top) {
                            pc = *target as usize;
                            continue;
                        }
                    }
                    pc += 1;
                }

                Op::JumpIfFalse(target) => {
                    if let Some(top) = stack.last() {
                        if !Self::to_bool(top) {
                            pc = *target as usize;
                            continue;
                        }
                    } else {
                        // Empty stack → treat as NULL → falsy → jump
                        pc = *target as usize;
                        continue;
                    }
                    pc += 1;
                }

                Op::JumpIfNull(target) => {
                    if let Some(top) = stack.last() {
                        if top.is_null() {
                            pc = *target as usize;
                            continue;
                        }
                    }
                    pc += 1;
                }

                Op::PopJumpIfFalse(target) => {
                    let v = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    if !Self::to_bool(&v) {
                        pc = *target as usize;
                    } else {
                        pc += 1;
                    }
                }

                Op::PopJumpIfTrue(target) => {
                    let v = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    if Self::to_bool(&v) {
                        pc = *target as usize;
                    } else {
                        pc += 1;
                    }
                }

                Op::Nop => {
                    pc += 1;
                }

                // STRING CONCATENATION
                Op::Concat => {
                    let b = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let a = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = if a.is_null() || b.is_null() {
                        Value::Null(DataType::Text)
                    } else {
                        // Fast path: both are Text
                        match (&*a, &*b) {
                            (Value::Text(a_str), Value::Text(b_str)) => {
                                // Use optimized concat - handles inline and heap efficiently
                                Value::Text(SmartString::concat(a_str, b_str))
                            }
                            (Value::Text(a_str), _) => {
                                // Use Arc to avoid shrink_to_fit
                                use std::fmt::Write;
                                let mut s = String::with_capacity(a_str.len() + 32);
                                s.push_str(a_str);
                                let _ = write!(s, "{}", *b);
                                Value::Text(SmartString::from_string_shared(s))
                            }
                            (_, Value::Text(b_str)) => {
                                // Use Arc to avoid shrink_to_fit
                                use std::fmt::Write;
                                let mut s = String::with_capacity(32 + b_str.len());
                                let _ = write!(s, "{}", *a);
                                s.push_str(b_str);
                                Value::Text(SmartString::from_string_shared(s))
                            }
                            _ => {
                                // Use Arc to avoid shrink_to_fit
                                use std::fmt::Write;
                                let mut s = String::with_capacity(64);
                                let _ = write!(s, "{}{}", *a, *b);
                                Value::Text(SmartString::from_string_shared(s))
                            }
                        }
                    };
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                // Multi-value string concatenation (optimized for chained ||)
                Op::ConcatN(n) => {
                    let n = *n as usize;
                    let start = stack.len().saturating_sub(n);

                    // Single pass: check for NULL and calculate total length
                    let mut total_len = 0usize;
                    let mut has_null = false;
                    let mut all_text = true;

                    for v in &stack[start..] {
                        match &**v {
                            Value::Null(_) => {
                                has_null = true;
                                break;
                            }
                            Value::Text(s) => total_len += s.len(),
                            _ => {
                                all_text = false;
                                total_len += 32;
                            }
                        }
                    }

                    if has_null {
                        stack.truncate(start);
                        stack.push(Cow::Owned(Value::Null(DataType::Text)));
                        pc += 1;
                        continue;
                    }

                    // Build result - optimize for inline vs heap
                    let result = if all_text && total_len <= 15 {
                        // Fast path: build directly into inline SmartString (no heap allocation)
                        let mut data = [0u8; 15];
                        let mut pos = 0;
                        for v in stack.drain(start..) {
                            if let Value::Text(text) = &*v {
                                let bytes = text.as_bytes();
                                data[pos..pos + bytes.len()].copy_from_slice(bytes);
                                pos += bytes.len();
                            }
                        }
                        let text = std::str::from_utf8(&data[..total_len])
                            .expect("concatenated Text values remain valid UTF-8");
                        SmartString::new(text)
                    } else if all_text {
                        // Heap path: exact capacity, into_boxed_str is O(1) when len == capacity
                        let mut s = String::with_capacity(total_len);
                        for v in stack.drain(start..) {
                            if let Value::Text(text) = &*v {
                                s.push_str(text);
                            }
                        }
                        // len == capacity, so into_boxed_str is O(1)
                        SmartString::from_string(s)
                    } else {
                        // Mixed types: capacity is estimate, use Arc to avoid shrink_to_fit
                        let mut s = String::with_capacity(total_len);
                        for v in stack.drain(start..) {
                            match &*v {
                                Value::Text(text) => s.push_str(text),
                                other => {
                                    use std::fmt::Write;
                                    let _ = write!(s, "{}", other);
                                }
                            }
                        }
                        SmartString::from_string_shared(s)
                    };
                    stack.push(Cow::Owned(Value::Text(result)));
                    pc += 1;
                }

                // CASE expression operations
                Op::CaseStart => {
                    // Marker only, no operation
                    pc += 1;
                }

                Op::CaseWhen(next_branch) => {
                    let cond = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    if !Self::to_bool(&cond) {
                        pc = *next_branch as usize;
                    } else {
                        pc += 1;
                    }
                }

                Op::CaseThen(end_pos) => {
                    // Result is on stack, jump to end
                    pc = *end_pos as usize;
                }

                Op::CaseElse => {
                    // Marker only
                    pc += 1;
                }

                Op::CaseEnd => {
                    // Marker only
                    pc += 1;
                }

                Op::CaseCompare => {
                    let when_val = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let case_val = stack.pop().unwrap_or(Cow::Borrowed(&NULL_VALUE));
                    let result = if !case_val.is_null() && !when_val.is_null() {
                        Value::Boolean(*case_val == *when_val)
                    } else {
                        Value::Boolean(false)
                    };
                    stack.push(Cow::Owned(result));
                    pc += 1;
                }

                Op::Return => break,
                Op::ReturnTrue => {
                    return Ok(Value::Boolean(true));
                }
                Op::ReturnFalse => {
                    return Ok(Value::Boolean(false));
                }
                Op::ReturnNull(dt) => {
                    return Ok(Value::Null(*dt));
                }

                // For any unhandled operation, fall back to the regular execute
                _ => {
                    return Err(radixdb_core::Error::internal(
                        "Cow VM support classification drifted from dispatch",
                    ));
                }
            }
        }

        // Return top of stack or NULL
        Ok(stack
            .pop()
            .map(Cow::into_owned)
            .unwrap_or_else(Value::null_unknown))
    }

    #[inline]
    fn cow_supports_op(op: &Op) -> bool {
        matches!(
            op,
            Op::LoadColumn(_)
                | Op::LoadColumn2(_)
                | Op::LoadConst(_)
                | Op::LoadParam(_)
                | Op::LoadNull(_)
                | Op::LoadAggregateResult(_)
                | Op::Eq
                | Op::Ne
                | Op::Lt
                | Op::Le
                | Op::Gt
                | Op::Ge
                | Op::IsNull
                | Op::IsNotNull
                | Op::And(_)
                | Op::Or(_)
                | Op::AndFinalize
                | Op::OrFinalize
                | Op::Not
                | Op::CallScalar { .. }
                | Op::CallStored { .. }
                | Op::GtColumnConst(_, _)
                | Op::LtColumnConst(_, _)
                | Op::EqColumnConst(_, _)
                | Op::Coalesce(_)
                | Op::NullIf
                | Op::Greatest(_)
                | Op::Least(_)
                | Op::JumpIfNotNull(_)
                | Op::Pop
                | Op::Jump(_)
                | Op::JumpIfTrue(_)
                | Op::JumpIfFalse(_)
                | Op::JumpIfNull(_)
                | Op::PopJumpIfFalse(_)
                | Op::PopJumpIfTrue(_)
                | Op::Nop
                | Op::Concat
                | Op::ConcatN(_)
                | Op::CaseStart
                | Op::CaseWhen(_)
                | Op::CaseThen(_)
                | Op::CaseElse
                | Op::CaseEnd
                | Op::CaseCompare
                | Op::Return
                | Op::ReturnTrue
                | Op::ReturnFalse
                | Op::ReturnNull(_)
        )
    }

    /// Execute and return boolean result (for WHERE clauses)
    ///
    /// This method is optimized for common filter patterns, avoiding
    /// the full VM loop overhead for simple comparisons.
    #[inline]
    pub fn execute_bool(&mut self, program: &Program, ctx: &ExecuteContext) -> Result<bool> {
        self.execute_bool_checked(program, ctx)
    }

    /// Like execute_bool but returns errors instead of swallowing them.
    ///
    /// Used by RowFilter::matches_checked to propagate VM errors (e.g. invalid
    /// REGEXP patterns) through the query result iterator.
    #[inline]
    pub fn execute_bool_checked(
        &mut self,
        program: &Program,
        ctx: &ExecuteContext,
    ) -> radixdb_core::Result<bool> {
        let ops = program.ops();

        // Fast path: Single comparison + Return (most common filter)
        if ops.len() == 2 && matches!(&ops[1], Op::Return) && Self::is_fast_bool_op(&ops[0]) {
            return Self::eval_single_op_bool(&ops[0], ctx);
        }

        // Fast path: Two comparisons with AND/OR
        if ops.len() == 5 {
            if Self::is_fast_bool_op(&ops[0])
                && Self::is_fast_bool_op(&ops[2])
                && matches!(
                    (&ops[1], &ops[3], &ops[4]),
                    (Op::And(_), Op::AndFinalize, Op::Return)
                )
            {
                let a = Self::eval_single_op_tribool(&ops[0], ctx)?;
                if a == Some(false) {
                    return Ok(false);
                }
                let b = Self::eval_single_op_tribool(&ops[2], ctx)?;
                return Ok(a == Some(true) && b == Some(true));
            }
            if Self::is_fast_bool_op(&ops[0])
                && Self::is_fast_bool_op(&ops[2])
                && matches!(
                    (&ops[1], &ops[3], &ops[4]),
                    (Op::Or(_), Op::OrFinalize, Op::Return)
                )
            {
                let a = Self::eval_single_op_tribool(&ops[0], ctx)?;
                if a == Some(true) {
                    return Ok(true);
                }
                let b = Self::eval_single_op_tribool(&ops[2], ctx)?;
                return Ok(a == Some(true) || b == Some(true));
            }
        }

        // General path: full VM execution
        match self.execute_cow(program, ctx) {
            Ok(Value::Boolean(b)) => Ok(b),
            Ok(Value::Integer(i)) => Ok(i != 0),
            Ok(Value::Null(_)) => Ok(false),
            Ok(value) => Err(Error::Type(format!(
                "predicate expression produced {}, expected BOOLEAN, INTEGER, or NULL",
                value.data_type()
            ))),
            Err(e) => Err(e),
        }
    }

    #[inline]
    fn is_fast_bool_op(op: &Op) -> bool {
        matches!(
            op,
            Op::GtColumnConst(_, _)
                | Op::LtColumnConst(_, _)
                | Op::GeColumnConst(_, _)
                | Op::LeColumnConst(_, _)
                | Op::EqColumnConst(_, _)
                | Op::NeColumnConst(_, _)
                | Op::IsNullColumn(_)
                | Op::IsNotNullColumn(_)
                | Op::BetweenColumnConst(_, _, _)
                | Op::InSetColumn(_, _, _)
                | Op::LoadConst(Value::Boolean(_) | Value::Integer(_) | Value::Null(_))
                | Op::LikeColumn(_, _, _)
        )
    }

    /// Evaluate a single comparison op and return bool (for fast path)
    #[inline]
    fn eval_single_op_bool(op: &Op, ctx: &ExecuteContext) -> Result<bool> {
        Ok(match op {
            Op::GtColumnConst(idx, threshold) => match ctx.row.get(*idx as usize) {
                Some(value) => Self::sql_order_tribool(ctx, value, threshold, |ordering| {
                    ordering == std::cmp::Ordering::Greater
                })?
                .unwrap_or(false),
                None => false,
            },
            Op::LtColumnConst(idx, threshold) => match ctx.row.get(*idx as usize) {
                Some(value) => Self::sql_order_tribool(ctx, value, threshold, |ordering| {
                    ordering == std::cmp::Ordering::Less
                })?
                .unwrap_or(false),
                None => false,
            },
            Op::GeColumnConst(idx, threshold) => match ctx.row.get(*idx as usize) {
                Some(value) => Self::sql_order_tribool(ctx, value, threshold, |ordering| {
                    ordering != std::cmp::Ordering::Less
                })?
                .unwrap_or(false),
                None => false,
            },
            Op::LeColumnConst(idx, threshold) => match ctx.row.get(*idx as usize) {
                Some(value) => Self::sql_order_tribool(ctx, value, threshold, |ordering| {
                    ordering != std::cmp::Ordering::Greater
                })?
                .unwrap_or(false),
                None => false,
            },
            Op::EqColumnConst(idx, value) => match ctx.row.get(*idx as usize) {
                Some(column) => {
                    Self::sql_equality_tribool(ctx, column, value, false)?.unwrap_or(false)
                }
                None => false,
            },
            Op::NeColumnConst(idx, value) => match ctx.row.get(*idx as usize) {
                Some(column) => {
                    Self::sql_equality_tribool(ctx, column, value, true)?.unwrap_or(false)
                }
                None => false,
            },
            Op::IsNullColumn(idx) => ctx.row.get(*idx as usize).is_some_and(|v| v.is_null()),
            Op::IsNotNullColumn(idx) => ctx.row.get(*idx as usize).is_some_and(|v| !v.is_null()),
            Op::BetweenColumnConst(idx, low, high) => match ctx.row.get(*idx as usize) {
                Some(col_val) => {
                    Self::sql_between_tribool(ctx, col_val, low, high)?.unwrap_or(false)
                }
                _ => false,
            },
            Op::InSetColumn(idx, set, has_null) => {
                match ctx.row.get(*idx as usize) {
                    Some(v) if v.is_null() => false, // NULL IN set -> NULL -> false in bool context
                    Some(v) => {
                        let mut found = false;
                        for candidate in set.iter() {
                            if Self::sql_values_equal(ctx, v, candidate)? {
                                found = true;
                                break;
                            }
                        }
                        let _ = has_null;
                        found
                    }
                    None => false,
                }
            }
            // Handle LIKE pattern matching (e.g., fruit LIKE 'a%')
            Op::LikeColumn(idx, pattern, case_insensitive) => {
                match ctx.row.get(*idx as usize) {
                    Some(Value::Text(s)) => pattern.matches(s, *case_insensitive),
                    _ => false, // NULL or non-text -> false
                }
            }
            // For other ops, fall back to tribool and convert
            _ => Self::eval_single_op_tribool(op, ctx)? == Some(true),
        })
    }

    /// Evaluate a single comparison op and return Option<bool> (tribool)
    /// None = NULL, Some(true) = true, Some(false) = false
    #[inline]
    fn eval_single_op_tribool(op: &Op, ctx: &ExecuteContext) -> Result<Option<bool>> {
        Ok(match op {
            Op::GtColumnConst(idx, threshold) => match ctx.row.get(*idx as usize) {
                Some(value) => Self::sql_order_tribool(ctx, value, threshold, |ordering| {
                    ordering == std::cmp::Ordering::Greater
                })?,
                None => None,
            },
            Op::LtColumnConst(idx, threshold) => match ctx.row.get(*idx as usize) {
                Some(value) => Self::sql_order_tribool(ctx, value, threshold, |ordering| {
                    ordering == std::cmp::Ordering::Less
                })?,
                None => None,
            },
            Op::GeColumnConst(idx, threshold) => match ctx.row.get(*idx as usize) {
                Some(value) => Self::sql_order_tribool(ctx, value, threshold, |ordering| {
                    ordering != std::cmp::Ordering::Less
                })?,
                None => None,
            },
            Op::LeColumnConst(idx, threshold) => match ctx.row.get(*idx as usize) {
                Some(value) => Self::sql_order_tribool(ctx, value, threshold, |ordering| {
                    ordering != std::cmp::Ordering::Greater
                })?,
                None => None,
            },
            Op::EqColumnConst(idx, value) => match ctx.row.get(*idx as usize) {
                Some(column) => Self::sql_equality_tribool(ctx, column, value, false)?,
                None => None,
            },
            Op::NeColumnConst(idx, value) => match ctx.row.get(*idx as usize) {
                Some(column) => Self::sql_equality_tribool(ctx, column, value, true)?,
                None => None,
            },
            Op::IsNullColumn(idx) => Some(ctx.row.get(*idx as usize).is_some_and(|v| v.is_null())),
            Op::IsNotNullColumn(idx) => {
                Some(ctx.row.get(*idx as usize).is_some_and(|v| !v.is_null()))
            }
            Op::BetweenColumnConst(idx, low, high) => match ctx.row.get(*idx as usize) {
                Some(col_val) => Self::sql_between_tribool(ctx, col_val, low, high)?,
                None => None,
            },
            Op::InSetColumn(idx, set, has_null) => {
                match ctx.row.get(*idx as usize) {
                    Some(v) if v.is_null() => None, // NULL IN set -> NULL
                    Some(v) => {
                        let mut found = false;
                        for candidate in set.iter() {
                            if Self::sql_values_equal(ctx, v, candidate)? {
                                found = true;
                                break;
                            }
                        }
                        if found {
                            Some(true)
                        } else if *has_null {
                            None
                        } else {
                            Some(false)
                        }
                    }
                    None => None,
                }
            }
            // Handle boolean constants (from processed subqueries like NOT EXISTS)
            Op::LoadConst(Value::Boolean(b)) => Some(*b),
            Op::LoadConst(Value::Integer(i)) => Some(*i != 0),
            Op::LoadConst(Value::Null(_)) => None,
            // Handle LIKE pattern matching (e.g., fruit LIKE 'a%')
            Op::LikeColumn(idx, pattern, case_insensitive) => match ctx.row.get(*idx as usize) {
                Some(Value::Text(s)) => Some(pattern.matches(s, *case_insensitive)),
                Some(Value::Null(_)) | None => None,
                _ => Some(false),
            },
            // For other comparisons, return None to fall back to full VM
            _ => None,
        })
    }

    // =========================================================================
    // HELPER METHODS
    // =========================================================================

    #[inline]
    fn to_bool(v: &Value) -> bool {
        match v {
            Value::Boolean(b) => *b,
            Value::Integer(i) => *i != 0,
            Value::Null(_) => false,
            _ => true, // Non-null values are truthy
        }
    }

    #[inline]
    fn to_tribool(v: &Value) -> Option<bool> {
        match v {
            Value::Boolean(b) => Some(*b),
            Value::Integer(i) => Some(*i != 0),
            Value::Null(_) => None,
            _ => Some(true),
        }
    }

    /// SQL equality uses plugin-owned semantics for external types. Structural
    /// `Value::Eq` is never a fallback for an external payload.
    #[inline]
    fn sql_values_equal(ctx: &ExecuteContext<'_>, a: &Value, b: &Value) -> Result<bool> {
        if a.is_external() || b.is_external() {
            let invoker = ctx.stored_function_invoker.ok_or_else(|| {
                Error::NotSupported(
                    "external equality is unavailable in this execution context".to_owned(),
                )
            })?;
            return invoker.external_equal(a, b);
        }
        match a
            .compare(b)
            .ok()
            .or_else(|| Self::sql_literal_ordering(a, b))
        {
            Some(std::cmp::Ordering::Equal) => Ok(true),
            Some(_) => Ok(false),
            None => Ok(a == b),
        }
    }

    #[inline]
    fn sql_set_contains(
        ctx: &ExecuteContext<'_>,
        set: &radixdb_core::ValueSet,
        value: &Value,
    ) -> Result<bool> {
        if !value.is_external() {
            return Ok(set.contains(value));
        }
        for candidate in set.iter() {
            if Self::sql_values_equal(ctx, value, candidate)? {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Canonical SQL comparison result shared by the stack, fused and
    /// bool/tribool execution paths. NULL remains UNKNOWN; non-NULL numeric
    /// values use `Value::compare`, which does not round an i64 through f64.
    #[inline]
    fn sql_ordering(
        ctx: &ExecuteContext<'_>,
        a: &Value,
        b: &Value,
    ) -> Result<Option<std::cmp::Ordering>> {
        if a.is_null() || b.is_null() {
            return Ok(None);
        }
        if a.is_external() || b.is_external() {
            let invoker = ctx.stored_function_invoker.ok_or_else(|| {
                Error::NotSupported(
                    "external ordering is unavailable in this execution context".to_owned(),
                )
            })?;
            return invoker.external_compare(a, b).map(Some);
        }
        Ok(a.compare(b)
            .ok()
            .or_else(|| Self::sql_literal_ordering(a, b)))
    }

    /// SQL literals may be compared with typed UUID/TIMESTAMP values before a
    /// schema-aware pushdown can bind them (TVFs and post-join residuals are
    /// the two important cases). Keep those explicit admissions here instead
    /// of making structural `Value` identity perform general string coercion.
    #[inline]
    fn sql_literal_ordering(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
        match (a, b) {
            (Value::Extension(_), Value::Text(text)) => a
                .as_uuid_bytes()
                .zip(radixdb_core::value::parse_uuid_str(text))
                .map(|(left, right)| left.cmp(&right)),
            (Value::Text(text), Value::Extension(_)) => radixdb_core::value::parse_uuid_str(text)
                .zip(b.as_uuid_bytes())
                .map(|(left, right)| left.cmp(&right)),
            (Value::Timestamp(left), Value::Text(text)) => {
                radixdb_core::value::parse_timestamp(text)
                    .ok()
                    .map(|right| left.cmp(&right))
            }
            (Value::Text(text), Value::Timestamp(right)) => {
                radixdb_core::value::parse_timestamp(text)
                    .ok()
                    .map(|left| left.cmp(right))
            }
            _ => None,
        }
    }

    #[inline]
    fn sql_equality_result(
        ctx: &ExecuteContext<'_>,
        a: &Value,
        b: &Value,
        negated: bool,
    ) -> Result<Value> {
        if a.is_null() || b.is_null() {
            Ok(Value::Null(DataType::Boolean))
        } else {
            Ok(Value::Boolean(
                Self::sql_values_equal(ctx, a, b)? != negated,
            ))
        }
    }

    #[inline]
    fn sql_order_result(
        ctx: &ExecuteContext<'_>,
        a: &Value,
        b: &Value,
        predicate: impl FnOnce(std::cmp::Ordering) -> bool,
    ) -> Result<Value> {
        match Self::sql_ordering(ctx, a, b)? {
            Some(ordering) => Ok(Value::Boolean(predicate(ordering))),
            None => Ok(Value::Null(DataType::Boolean)),
        }
    }

    #[inline]
    fn sql_order_tribool(
        ctx: &ExecuteContext<'_>,
        a: &Value,
        b: &Value,
        predicate: impl FnOnce(std::cmp::Ordering) -> bool,
    ) -> Result<Option<bool>> {
        Ok(Self::sql_ordering(ctx, a, b)?.map(predicate))
    }

    #[inline]
    fn sql_equality_tribool(
        ctx: &ExecuteContext<'_>,
        a: &Value,
        b: &Value,
        negated: bool,
    ) -> Result<Option<bool>> {
        if a.is_null() || b.is_null() {
            Ok(None)
        } else {
            Ok(Some(Self::sql_values_equal(ctx, a, b)? != negated))
        }
    }

    #[inline]
    fn sql_between_result(
        ctx: &ExecuteContext<'_>,
        value: &Value,
        low: &Value,
        high: &Value,
        negated: bool,
    ) -> Result<Value> {
        let Some(ge_low) = Self::sql_order_tribool(ctx, value, low, |ordering| {
            ordering != std::cmp::Ordering::Less
        })?
        else {
            return Ok(Value::Null(DataType::Boolean));
        };
        let Some(le_high) = Self::sql_order_tribool(ctx, value, high, |ordering| {
            ordering != std::cmp::Ordering::Greater
        })?
        else {
            return Ok(Value::Null(DataType::Boolean));
        };
        Ok(Value::Boolean((ge_low && le_high) != negated))
    }

    #[inline]
    fn sql_between_tribool(
        ctx: &ExecuteContext<'_>,
        value: &Value,
        low: &Value,
        high: &Value,
    ) -> Result<Option<bool>> {
        let Some(ge_low) = Self::sql_order_tribool(ctx, value, low, |ordering| {
            ordering != std::cmp::Ordering::Less
        })?
        else {
            return Ok(None);
        };
        let Some(le_high) = Self::sql_order_tribool(ctx, value, high, |ordering| {
            ordering != std::cmp::Ordering::Greater
        })?
        else {
            return Ok(None);
        };
        Ok(Some(ge_low && le_high))
    }

    #[inline]
    fn date_add_days(days_since_epoch: i32, delta_days: i64) -> Result<Value> {
        let result = i64::from(days_since_epoch)
            .checked_add(delta_days)
            .and_then(|days| i32::try_from(days).ok())
            .ok_or_else(|| Error::Type("DATE arithmetic overflow".to_string()))?;
        Ok(Value::date(result))
    }

    #[inline]
    fn arithmetic_op<FF>(a: &Value, b: &Value, int_op: ArithmeticOp, float_op: FF) -> Result<Value>
    where
        FF: Fn(f64, f64) -> f64,
    {
        match (a, b) {
            (Value::Integer(x), Value::Integer(y)) => {
                // Use checked operations to detect overflow and return an error
                let result = match int_op {
                    ArithmeticOp::Add => x.checked_add(*y),
                    ArithmeticOp::Sub => x.checked_sub(*y),
                    ArithmeticOp::Mul => x.checked_mul(*y),
                    ArithmeticOp::Div => {
                        if *y == 0 {
                            return Ok(Value::Null(DataType::Integer));
                        }
                        x.checked_div(*y)
                    }
                    ArithmeticOp::Mod => {
                        if *y == 0 {
                            return Ok(Value::Null(DataType::Integer));
                        }
                        x.checked_rem(*y)
                    }
                };
                match result {
                    Some(r) => Ok(Value::Integer(r)),
                    None => Err(radixdb_core::Error::Type(format!(
                        "Integer overflow in arithmetic operation: {} and {}",
                        x, y
                    ))),
                }
            }
            (Value::Float(x), Value::Float(y)) => Ok(Value::Float(float_op(*x, *y))),
            (Value::Integer(x), Value::Float(y)) => Ok(Value::Float(float_op(*x as f64, *y))),
            (Value::Float(x), Value::Integer(y)) => Ok(Value::Float(float_op(*x, *y as f64))),
            _ if a.is_null() || b.is_null() => Ok(Value::Null(DataType::Float)),
            _ => Ok(Value::Null(DataType::Null)),
        }
    }

    #[inline]
    fn div_op(a: &Value, b: &Value) -> radixdb_core::Result<Value> {
        match (a, b) {
            (Value::Integer(x), Value::Integer(y)) if *y != 0 => x
                .checked_div(*y)
                .map(Value::Integer)
                .ok_or_else(|| radixdb_core::Error::Type("integer division overflow".to_string())),
            (Value::Float(x), Value::Float(y)) if *y != 0.0 => Ok(Value::Float(x / y)),
            (Value::Integer(x), Value::Float(y)) if *y != 0.0 => Ok(Value::Float(*x as f64 / y)),
            (Value::Float(x), Value::Integer(y)) if *y != 0 => Ok(Value::Float(x / *y as f64)),
            _ if a.is_null() || b.is_null() => Ok(Value::Null(DataType::Float)),
            _ => Ok(Value::Null(DataType::Null)),
        }
    }

    #[inline]
    fn mod_op(a: &Value, b: &Value) -> radixdb_core::Result<Value> {
        match (a, b) {
            (Value::Integer(x), Value::Integer(y)) if *y != 0 => x
                .checked_rem(*y)
                .map(Value::Integer)
                .ok_or_else(|| radixdb_core::Error::Type("integer remainder overflow".to_string())),
            (Value::Float(x), Value::Float(y)) if *y != 0.0 => Ok(Value::Float(x % y)),
            (Value::Integer(x), Value::Float(y)) if *y != 0.0 => Ok(Value::Float(*x as f64 % y)),
            (Value::Float(x), Value::Integer(y)) if *y != 0 => Ok(Value::Float(x % *y as f64)),
            _ if a.is_null() || b.is_null() => Ok(Value::Null(DataType::Float)),
            _ => Ok(Value::Null(DataType::Null)),
        }
    }

    /// JSON access helper
    /// If as_text is true, returns TEXT; otherwise returns JSON
    fn json_access(&self, json_val: &Value, key: &Value, as_text: bool) -> Value {
        use serde_json;

        // Get the JSON string
        let json_str = match json_val {
            Value::Extension(data) if data.first() == Some(&(DataType::Json as u8)) => {
                std::str::from_utf8(&data[1..]).unwrap_or("")
            }
            Value::Text(s) => s.as_ref(),
            Value::Null(_) => {
                return Value::Null(if as_text {
                    DataType::Text
                } else {
                    DataType::Json
                })
            }
            _ => {
                return Value::Null(if as_text {
                    DataType::Text
                } else {
                    DataType::Json
                })
            }
        };

        // Parse the JSON
        let parsed: serde_json::Value = match serde_json::from_str(json_str) {
            Ok(v) => v,
            Err(_) => {
                return Value::Null(if as_text {
                    DataType::Text
                } else {
                    DataType::Json
                })
            }
        };

        // Access by key or index
        let result = match key {
            Value::Text(k) => parsed.get(k.as_str()),
            Value::Integer(i) => {
                if *i >= 0 {
                    parsed.get(*i as usize)
                } else {
                    None
                }
            }
            _ => None,
        };

        match result {
            Some(v) => {
                if as_text {
                    // ->> returns text
                    match v {
                        serde_json::Value::String(s) => Value::Text(SmartString::new(s)),
                        serde_json::Value::Null => Value::Null(DataType::Text),
                        other => Value::Text(SmartString::from_string(other.to_string())),
                    }
                } else {
                    // -> returns JSON
                    Value::json(v.to_string())
                }
            }
            None => Value::Null(if as_text {
                DataType::Text
            } else {
                DataType::Json
            }),
        }
    }

    /// Add or subtract interval from timestamp
    fn timestamp_add_days(timestamp: chrono::DateTime<chrono::Utc>, days: i64) -> Result<Value> {
        let duration = chrono::Duration::try_days(days)
            .ok_or_else(|| Error::Type("timestamp day interval overflow".to_string()))?;
        timestamp
            .checked_add_signed(duration)
            .map(Value::Timestamp)
            .ok_or_else(|| Error::Type("timestamp result is out of range".to_string()))
    }

    fn timestamp_add_interval(&self, ts: &Value, interval: &Value, add: bool) -> Result<Value> {
        let timestamp = match ts {
            Value::Timestamp(t) => *t,
            Value::Null(_) => return Ok(Value::Null(DataType::Timestamp)),
            _ => return Ok(Value::Null(DataType::Timestamp)),
        };

        let interval_str = match interval {
            Value::Text(s) => s.as_ref(),
            Value::Null(_) => return Ok(Value::Null(DataType::Timestamp)),
            _ => return Ok(Value::Null(DataType::Timestamp)),
        };

        // Parse interval string
        // Formats: "1 day", "2 hours", "30 minutes", "1 year", "1 month", etc.
        match self.parse_interval(interval_str)? {
            IntervalValue::Duration(duration) => {
                let duration = if add {
                    duration
                } else {
                    duration
                        .checked_mul(-1)
                        .ok_or_else(|| Error::Type("fixed interval overflow".to_string()))?
                };
                timestamp
                    .checked_add_signed(duration)
                    .map(Value::Timestamp)
                    .ok_or_else(|| Error::Type("timestamp result is out of range".to_string()))
            }
            IntervalValue::Months(months) => {
                let months = if add {
                    months
                } else {
                    months
                        .checked_neg()
                        .ok_or_else(|| Error::Type("calendar interval overflow".to_string()))?
                };
                Self::calendar_add_months(timestamp, months)
                    .map(Value::Timestamp)
                    .ok_or_else(|| Error::Type("timestamp result is out of range".to_string()))
            }
        }
    }

    /// Calendar-aware month addition preserving time-of-day and nanoseconds.
    fn calendar_add_months(
        ts: chrono::DateTime<chrono::Utc>,
        months: i64,
    ) -> Option<chrono::DateTime<chrono::Utc>> {
        use chrono::{Datelike, NaiveDate, Timelike};

        let total_months = (ts.year() as i64)
            .checked_mul(12)?
            .checked_add(i64::from(ts.month()) - 1)?
            .checked_add(months)?;
        let new_year_i64 = total_months.div_euclid(12);
        let new_month = (total_months.rem_euclid(12) + 1) as u32;

        let new_year = i32::try_from(new_year_i64).ok()?;
        if !(1..=9999).contains(&new_year) {
            return None;
        }

        // Clamp day to valid range for the new month
        let max_day = match new_month {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            4 | 6 | 9 | 11 => 30,
            2 => {
                if (new_year % 4 == 0 && new_year % 100 != 0) || (new_year % 400 == 0) {
                    29
                } else {
                    28
                }
            }
            _ => 30,
        };
        let day = ts.day().min(max_day);

        // Rebuild date preserving original time including nanoseconds
        let date = NaiveDate::from_ymd_opt(new_year, new_month, day)?;
        let time = ts.time();
        let naive = date.and_hms_nano_opt(
            time.hour(),
            time.minute(),
            time.second(),
            ts.timestamp_subsec_nanos(),
        )?;
        Some(chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
            naive,
            chrono::Utc,
        ))
    }

    /// Parsed interval: either a fixed duration or a calendar-relative month count.
    fn parse_interval(&self, s: &str) -> Result<IntervalValue> {
        let s = s.trim();
        let parts: Vec<&str> = s.split_whitespace().collect();

        if parts.len() < 2 {
            // Try parsing as just a number (days)
            if let Ok(n) = s.parse::<i64>() {
                return chrono::Duration::try_days(n)
                    .map(IntervalValue::Duration)
                    .ok_or_else(|| Error::Type("interval is out of range".to_string()));
            }
            return Err(Error::Type(format!("invalid interval: {s}")));
        }

        let value: i64 = parts[0]
            .parse()
            .map_err(|_| Error::Type(format!("invalid interval: {s}")))?;
        let unit = parts[1];

        // Case-insensitive unit matching without allocation
        // Handle both singular and plural forms
        if unit.eq_ignore_ascii_case("year") || unit.eq_ignore_ascii_case("years") {
            value
                .checked_mul(12)
                .map(IntervalValue::Months)
                .ok_or_else(|| Error::Type("calendar interval overflow".to_string()))
        } else if unit.eq_ignore_ascii_case("month") || unit.eq_ignore_ascii_case("months") {
            Ok(IntervalValue::Months(value))
        } else if unit.eq_ignore_ascii_case("week") || unit.eq_ignore_ascii_case("weeks") {
            chrono::Duration::try_weeks(value)
                .map(IntervalValue::Duration)
                .ok_or_else(|| Error::Type("interval is out of range".to_string()))
        } else if unit.eq_ignore_ascii_case("day") || unit.eq_ignore_ascii_case("days") {
            chrono::Duration::try_days(value)
                .map(IntervalValue::Duration)
                .ok_or_else(|| Error::Type("interval is out of range".to_string()))
        } else if unit.eq_ignore_ascii_case("hour") || unit.eq_ignore_ascii_case("hours") {
            chrono::Duration::try_hours(value)
                .map(IntervalValue::Duration)
                .ok_or_else(|| Error::Type("interval is out of range".to_string()))
        } else if unit.eq_ignore_ascii_case("minute")
            || unit.eq_ignore_ascii_case("minutes")
            || unit.eq_ignore_ascii_case("min")
        {
            chrono::Duration::try_minutes(value)
                .map(IntervalValue::Duration)
                .ok_or_else(|| Error::Type("interval is out of range".to_string()))
        } else if unit.eq_ignore_ascii_case("second")
            || unit.eq_ignore_ascii_case("seconds")
            || unit.eq_ignore_ascii_case("sec")
        {
            chrono::Duration::try_seconds(value)
                .map(IntervalValue::Duration)
                .ok_or_else(|| Error::Type("interval is out of range".to_string()))
        } else if unit.eq_ignore_ascii_case("millisecond")
            || unit.eq_ignore_ascii_case("milliseconds")
            || unit.eq_ignore_ascii_case("ms")
        {
            Ok(IntervalValue::Duration(chrono::Duration::milliseconds(
                value,
            )))
        } else if unit.eq_ignore_ascii_case("microsecond")
            || unit.eq_ignore_ascii_case("microseconds")
            || unit.eq_ignore_ascii_case("us")
        {
            Ok(IntervalValue::Duration(chrono::Duration::microseconds(
                value,
            )))
        } else {
            Err(Error::Type(format!("invalid interval unit: {unit}")))
        }
    }

    /// Format chrono Duration as interval string
    fn format_duration_as_interval(&self, duration: chrono::TimeDelta) -> String {
        let total_seconds = duration.num_seconds();
        let abs_seconds = total_seconds.abs();

        let days = abs_seconds / 86400;
        let hours = (abs_seconds % 86400) / 3600;
        let minutes = (abs_seconds % 3600) / 60;
        let seconds = abs_seconds % 60;

        let sign = if total_seconds < 0 { "-" } else { "" };

        if days > 0 {
            format!(
                "{}{} days {:02}:{:02}:{:02}",
                sign, days, hours, minutes, seconds
            )
        } else {
            format!("{}{:02}:{:02}:{:02}", sign, hours, minutes, seconds)
        }
    }
}

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

/// Extract raw LE f32 bytes from a vector Value, zero-copy for Extension.
/// Process a LIKE pattern with a custom escape character at runtime.
///
/// Converts escaped wildcards (e.g. `!%` with escape `!`) into the
/// default `\%` escape form that `CompiledPattern::compile` understands.
fn process_like_escape_runtime(pattern: &str, escape: char) -> String {
    let mut result = String::with_capacity(pattern.len());
    let mut chars = pattern.chars().peekable();

    while let Some(c) = chars.next() {
        if c == escape {
            if let Some(&next) = chars.peek() {
                if next == '%' || next == '_' || next == escape {
                    // Convert to default escape form: \% or \_ or \\
                    result.push('\\');
                    result.push(chars.next().unwrap());
                } else {
                    result.push(c);
                }
            } else {
                result.push(c);
            }
        } else {
            result.push(c);
        }
    }

    result
}

/// For Text values, parses and writes into `buf` as fallback.
#[inline]
fn extract_vector_bytes<'a>(v: &'a Value, buf: &'a mut Vec<u8>) -> Option<&'a [u8]> {
    match v {
        Value::Extension(data) if data.first() == Some(&(DataType::Vector as u8)) => {
            Some(&data[1..])
        }
        Value::Text(s) => {
            let floats = radixdb_core::value::parse_vector_str(s.as_ref())?;
            buf.clear();
            buf.reserve(floats.len() * 4);
            for f in &floats {
                buf.extend_from_slice(&f.to_le_bytes());
            }
            Some(buf.as_slice())
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests;