apexbase 1.24.0

High-performance HTAP embedded database with Rust core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
"""
ApexBase Performance Benchmark: ApexBase vs SQLite vs DuckDB

Measures OLAP and OLTP operations across all three engines on the same
dataset. Default fair rankings use normal engine APIs and comparable
materialization semantics; tunable or opt-in paths are shown in metric labels.
Results are printed as formatted tables and optionally saved to JSON.

Usage:
    python benchmarks/bench_vs_sqlite_duckdb.py [--rows N] [--warmup N] [--iterations N] [--output FILE]
"""

import argparse
import csv as csv_mod
import gc
import json
import math
import os
import platform
import random
import shutil
import sqlite3
import statistics
import string
import sys
import tempfile
import time
import uuid
from contextlib import contextmanager
from pathlib import Path

import numpy as np

# ---------------------------------------------------------------------------
# Optional imports
# ---------------------------------------------------------------------------
duckdb = None
ApexClient = None
pd = None
pa = None
HAS_DUCKDB = False
HAS_APEXBASE = False
HAS_PANDAS = False
HAS_PYARROW = False
_OPTIONAL_IMPORTS_READY = False


def ensure_optional_imports():
    """Load benchmark-only dependencies lazily so profile tests stay cheap."""
    global duckdb, ApexClient, pd, pa
    global HAS_DUCKDB, HAS_APEXBASE, HAS_PANDAS, HAS_PYARROW
    global _OPTIONAL_IMPORTS_READY

    if _OPTIONAL_IMPORTS_READY:
        return

    try:
        import duckdb as _duckdb
        duckdb = _duckdb
        HAS_DUCKDB = True
    except ImportError:
        duckdb = None
        HAS_DUCKDB = False

    try:
        from apexbase import ApexClient as _ApexClient
        ApexClient = _ApexClient
        HAS_APEXBASE = True
    except ImportError:
        ApexClient = None
        HAS_APEXBASE = False

    try:
        import pandas as _pd
        pd = _pd
        HAS_PANDAS = True
    except ImportError:
        pd = None
        HAS_PANDAS = False

    try:
        import pyarrow as _pa
        pa = _pa
        HAS_PYARROW = True
    except ImportError:
        pa = None
        HAS_PYARROW = False

    _OPTIONAL_IMPORTS_READY = True

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

CITIES = ["Beijing", "Shanghai", "Guangzhou", "Shenzhen", "Hangzhou",
          "Nanjing", "Chengdu", "Wuhan", "Xian", "Qingdao"]
CATEGORIES = ["Electronics", "Clothing", "Food", "Sports", "Books",
              "Home", "Auto", "Health", "Travel", "Gaming"]
TXN_BACKLOG_ROWS = 1500
TXN_BACKLOG_MISSING_NAME = "__txn_backlog_missing__"
MICROBENCH_TARGET_SAMPLE_NS = 2_000_000
MICROBENCH_MAX_REPEATS = 4096
MICROBENCH_CALIBRATION_TRIALS = 5
VECTOR_DIM_DEFAULT = 128
VECTOR_K_DEFAULT = 10
VECTOR_BATCH_QUERY_COUNT = 10
VECTOR_ROWS_DEFAULT = 1_000_000
VECTOR_HEAD_TO_HEAD_METRICS = [
    ("TopK L2", "l2"),
    ("TopK Cosine", "cosine"),
    ("TopK Dot", "dot"),
]
VECTOR_BATCH_METRICS = [
    ("Batch TopK L2 (10 queries)", "l2"),
    ("Batch TopK Cosine (10 queries)", "cosine"),
    ("Batch TopK Dot (10 queries)", "dot"),
]
VECTOR_APEX_ONLY_METRICS = [
    ("TopK L2 squared", "l2_squared"),
    ("TopK L1", "l1"),
    ("TopK Linf", "linf"),
]
VECTOR_APEX_METRIC_MAP = {
    "l2": "l2",
    "cosine": "cosine_distance",
    "dot": "dot",
    "l2_squared": "l2_squared",
    "l1": "l1",
    "linf": "linf",
}
VECTOR_DUCKDB_FUNCTIONS = {
    "l2": "array_distance",
    "cosine": "array_cosine_distance",
    "dot": "array_negative_inner_product",
}
VECTOR_SQLITE_NOTE = (
    "Stock SQLite in this harness has no native vector distance/top-k, "
    "so ranked vector comparisons are ApexBase vs DuckDB only."
)
PROFILE_PUBLIC = "public"
PROFILE_EXTENDED = "extended"
PROFILE_CHOICES = (PROFILE_PUBLIC, PROFILE_EXTENDED)
PUBLIC_VECTOR_HEAD_TO_HEAD_METRICS = VECTOR_HEAD_TO_HEAD_METRICS
PUBLIC_VECTOR_BATCH_METRICS = VECTOR_BATCH_METRICS
PUBLIC_VECTOR_APEX_ONLY_METRICS = []
OLTP_ONE_ROW_DICT = {
    "name": "oltp_one",
    "age": 31,
    "score": 77.0,
    "city": "Beijing",
    "category": "Books",
}
OLTP_ONE_ROW_TUPLE = ("oltp_one", 31, 77.0, "Beijing", "Books")


def generate_data(n: int):
    """Generate test data as columnar dict."""
    rng = random.Random(42)
    names = [f"user_{i}" for i in range(n)]
    ages = [rng.randint(18, 80) for _ in range(n)]
    scores = [round(rng.uniform(0, 100), 2) for _ in range(n)]
    cities = [rng.choice(CITIES) for _ in range(n)]
    categories = [rng.choice(CATEGORIES) for _ in range(n)]
    return {
        "name": names,
        "age": ages,
        "score": scores,
        "city": cities,
        "category": categories,
    }


def generate_benchmark_files(tmpdir, data):
    """Generate CSV, Parquet, and NDJSON test files from benchmark data."""
    ensure_optional_imports()
    csv_path = os.path.join(tmpdir, "bench_data.csv")
    parquet_path = os.path.join(tmpdir, "bench_data.parquet")
    json_path = os.path.join(tmpdir, "bench_data.jsonl")
    n = len(data["name"])
    columns = ["name", "age", "score", "city", "category"]

    with open(csv_path, "w", newline="") as f:
        writer = csv_mod.writer(f)
        writer.writerow(columns)
        for i in range(n):
            writer.writerow([data[col][i] for col in columns])

    if HAS_PANDAS:
        df = pd.DataFrame(data)
        df.to_parquet(parquet_path, index=False)
    elif HAS_PYARROW:
        import pyarrow.parquet as pq
        table = pa.table(data)
        pq.write_table(table, parquet_path)

    with open(json_path, "w") as f:
        for i in range(n):
            row = {col: data[col][i] for col in columns}
            json.dump(row, f)
            f.write("\n")

    return csv_path, parquet_path, json_path


def build_shared_inputs(n: int):
    """Build deterministic shared benchmark inputs used by all engines."""
    if n <= 0:
        return {"point_lookup_id": 0, "retrieve_many_ids": []}

    rng = random.Random(20260416)
    point_lookup_id = min(5000, n)
    sample_size = min(100, n)
    retrieve_many_ids = rng.sample(range(1, n + 1), sample_size)
    return {
        "point_lookup_id": point_lookup_id,
        "retrieve_many_ids": retrieve_many_ids,
    }


def generate_vector_data(n: int, dim: int, seed: int = 42):
    """Generate deterministic vector benchmark data."""
    rng = np.random.default_rng(seed)
    vecs = rng.random((n, dim), dtype=np.float32)
    query = rng.random(dim, dtype=np.float32)
    batch_queries = rng.random((VECTOR_BATCH_QUERY_COUNT, dim), dtype=np.float32)
    return vecs, query, batch_queries


def rows_to_dicts(columns, rows):
    """Materialize rows into a consistent Python representation."""
    if not rows:
        return []
    if not columns:
        return list(rows)
    return [dict(zip(columns, row)) for row in rows]


def default_vector_rows(base_rows: int) -> int:
    """Default vector benchmark rows: run the separate vector module at 1M rows."""
    return max(max(1, base_rows), VECTOR_ROWS_DEFAULT)


def normalize_profile(profile: str) -> str:
    return profile if profile in PROFILE_CHOICES else PROFILE_PUBLIC


def vector_metric_sets(profile: str = PROFILE_EXTENDED):
    if normalize_profile(profile) == PROFILE_PUBLIC:
        return (
            PUBLIC_VECTOR_HEAD_TO_HEAD_METRICS,
            PUBLIC_VECTOR_BATCH_METRICS,
            PUBLIC_VECTOR_APEX_ONLY_METRICS,
        )
    return (
        VECTOR_HEAD_TO_HEAD_METRICS,
        VECTOR_BATCH_METRICS,
        VECTOR_APEX_ONLY_METRICS,
    )


def vector_metric_count(profile: str = PROFILE_EXTENDED):
    head_metrics, batch_metrics, apex_only_metrics = vector_metric_sets(profile)
    return (
        len(head_metrics)
        + len(batch_metrics)
        + len(apex_only_metrics)
    )


def display_only_specs(labels):
    """Build print_benchmark_section-compatible specs for precomputed rows."""
    return [(label, "", False, False, False, None) for label in labels]


def vector_query_sql_literal(query: np.ndarray) -> str:
    values = np.asarray(query, dtype=np.float32).reshape(-1)
    return ",".join(f"{float(v):.6f}" for v in values)


def build_duckdb_vector_sql(query: np.ndarray, k: int, metric: str) -> str:
    func = VECTOR_DUCKDB_FUNCTIONS.get(metric)
    if func is None:
        raise ValueError(f"DuckDB vector SQL does not support metric '{metric}'")

    dim = int(np.asarray(query).size)
    q_cast = f"[{vector_query_sql_literal(query)}]::FLOAT[{dim}]"
    return f"SELECT id, {func}(vec, {q_cast}) AS dist FROM vecs ORDER BY dist LIMIT {k}"


def materialize_apex_vector_result(result_view):
    ensure_optional_imports()
    if HAS_PYARROW:
        return result_view.to_arrow()
    return result_view.to_dict()


def materialize_duckdb_vector_result(cursor):
    ensure_optional_imports()
    if HAS_PYARROW:
        return cursor.fetch_arrow_table()
    return cursor.fetchall()


def setup_apex_vector_bench(base_tmpdir: str, vecs: np.ndarray):
    ensure_optional_imports()
    vector_dir = os.path.join(base_tmpdir, "vector_apex")
    client = ApexClient(vector_dir, drop_if_exists=True)
    client.create_table("vecs")
    client.use_table("vecs")

    batch_size = 10_000
    for start in range(0, len(vecs), batch_size):
        end = min(start + batch_size, len(vecs))
        rows = [{"id": i, "vec": vecs[i]} for i in range(start, end)]
        client.store(rows)
    client.flush()
    return client


def setup_duckdb_vector_bench(vecs: np.ndarray):
    ensure_optional_imports()
    con = duckdb.connect(":memory:")
    dim = vecs.shape[1]
    ids = np.arange(len(vecs), dtype=np.int32)
    df = pd.DataFrame({"id": ids, "vec": list(vecs)})
    con.register("_vecs_src", df)
    con.execute(f"CREATE TABLE vecs AS SELECT id, vec::FLOAT[{dim}] AS vec FROM _vecs_src")
    try:
        con.unregister("_vecs_src")
    except Exception:
        con.execute("DROP VIEW IF EXISTS _vecs_src")
    return con


def bench_apex_vector_query(client, query: np.ndarray, k: int, metric: str):
    return materialize_apex_vector_result(
        client.topk_distance("vec", query, k=k, metric=VECTOR_APEX_METRIC_MAP[metric])
    )


def bench_duckdb_vector_query(connection, query: np.ndarray, k: int, metric: str):
    return materialize_duckdb_vector_result(
        connection.execute(build_duckdb_vector_sql(query, k, metric))
    )


def bench_apex_batch_vector_query(client, queries: np.ndarray, k: int, metric: str):
    return client.batch_topk_distance("vec", queries, k=k, metric=VECTOR_APEX_METRIC_MAP[metric])


def bench_duckdb_batch_vector_query(connection, queries: np.ndarray, k: int, metric: str):
    last = None
    for query in queries:
        last = materialize_duckdb_vector_result(
            connection.execute(build_duckdb_vector_sql(query, k, metric))
        )
    return last


@contextmanager
def timer():
    """Context manager that yields a dict; sets 'elapsed_ms' on exit."""
    result = {}
    gc.collect()
    t0 = time.perf_counter()
    yield result
    result["elapsed_ms"] = (time.perf_counter() - t0) * 1000


def fmt_ms(ms):
    if ms < 0.01:
        return f"{ms * 1000:.2f}us"
    if ms < 1:
        return f"{ms:.3f}ms"
    if ms < 1000:
        return f"{ms:.2f}ms"
    return f"{ms / 1000:.2f}s"


def run_bench(fn, warmup=2, iterations=5):
    """Run fn() with warmup, return average ms."""
    for _ in range(warmup):
        fn()
    times = []
    for _ in range(iterations):
        with timer() as t:
            fn()
        times.append(t["elapsed_ms"])
    return sum(times) / len(times)


def run_bench_cold(setup_fn, bench_fn, warmup=2, iterations=5):
    """Cold-start benchmark: re-run setup_fn() before EVERY iteration.
    Measures true from-scratch query latency (no warm caches)."""
    for _ in range(warmup):
        setup_fn()
        bench_fn()
    times = []
    for _ in range(iterations):
        setup_fn()   # cold restart — invalidates all in-process caches
        gc.collect()
        with timer() as t:
            bench_fn()
        times.append(t["elapsed_ms"])
    return sum(times) / len(times)


def run_bench_cold_nogc(setup_fn, bench_fn, warmup=2, iterations=5):
    """Cold-start benchmark WITHOUT gc.collect() before timing.
    Measures file-open + query latency without CPU-cache eviction noise."""
    for _ in range(warmup):
        setup_fn()
        bench_fn()
    times = []
    for _ in range(iterations):
        setup_fn()
        t0 = time.perf_counter()
        bench_fn()
        times.append((time.perf_counter() - t0) * 1000)
    return sum(times) / len(times)


def run_bench_nogc(fn, warmup=2, iterations=5):
    """Warm benchmark WITHOUT gc.collect() before timing."""
    for _ in range(warmup):
        fn()
    times = []
    for _ in range(iterations):
        t0 = time.perf_counter()
        fn()
        times.append((time.perf_counter() - t0) * 1000)
    return sum(times) / len(times)


def run_bench_nogc_median(fn, warmup=2, iterations=5):
    """Warm microbenchmark WITHOUT gc.collect(); returns median per-call latency.

    Ultra-fast Python call paths are vulnerable to timer granularity and
    scheduler jitter when measuring a single invocation per sample. Calibrate a
    symmetric repeat count for all engines, time a short batch, then divide by
    the repeat count so the reported number still reflects one logical call.
    """
    call = fn
    repeats = 1

    # Prime/cache the path and pick a batch size that lifts each timed sample
    # well above timer noise while preserving per-call semantics.
    best_single_ns = None
    for _ in range(MICROBENCH_CALIBRATION_TRIALS):
        t0 = time.perf_counter_ns()
        call()
        elapsed_ns = time.perf_counter_ns() - t0
        if best_single_ns is None or elapsed_ns < best_single_ns:
            best_single_ns = elapsed_ns

    if best_single_ns is not None and best_single_ns > 0:
        while (best_single_ns * repeats < MICROBENCH_TARGET_SAMPLE_NS
               and repeats < MICROBENCH_MAX_REPEATS):
            repeats *= 2

    for _ in range(warmup):
        for _ in range(repeats):
            call()
    times = []
    for _ in range(iterations):
        t0 = time.perf_counter_ns()
        for _ in range(repeats):
            call()
        times.append((time.perf_counter_ns() - t0) / (1_000_000 * repeats))
    return statistics.median(times)


def run_bench_gc_median(fn, warmup=2, iterations=5):
    """Run fn() with explicit gc before each timed iteration and return median ms."""
    for _ in range(warmup):
        fn()
    times = []
    for _ in range(iterations):
        gc.collect()
        t0 = time.perf_counter()
        fn()
        times.append((time.perf_counter() - t0) * 1000)
    return statistics.median(times)


def run_bench_with_setup(setup_fn, bench_fn, warmup=2, iterations=5):
    """Per-iteration setup WITHOUT cold-start (no DB reopen). Times only bench_fn."""
    for _ in range(warmup):
        setup_fn()
        bench_fn()
    times = []
    for _ in range(iterations):
        setup_fn()
        t0 = time.perf_counter()
        bench_fn()
        times.append((time.perf_counter() - t0) * 1000)
    return sum(times) / len(times)


def measure_rss_mb():
    """Return current process RSS in MB (requires psutil)."""
    try:
        import psutil
        return psutil.Process().memory_info().rss / (1024 * 1024)
    except Exception:
        return None


# ---------------------------------------------------------------------------
# SQLite benchmark
# ---------------------------------------------------------------------------

class SQLiteBench:
    def __init__(self, tmpdir, data):
        self.db_path = os.path.join(tmpdir, "bench.db")
        self.data = data
        self.n = len(data["name"])
        self.conn = None
        self.shared_inputs = build_shared_inputs(self.n)
        self._txn_counter = 0
        self._txn_backlog_ready = False

    def _connect(self):
        self.conn = sqlite3.connect(self.db_path)
        self.conn.execute("PRAGMA journal_mode=WAL")
        self.conn.execute("PRAGMA synchronous=OFF")

    def _query_all(self, sql, params=()):
        cur = self.conn.execute(sql, params)
        return rows_to_dicts([d[0] for d in (cur.description or [])], cur.fetchall())

    def _scalar(self, sql, params=()):
        return self.conn.execute(sql, params).fetchone()[0]

    def _query_pandas(self, sql):
        ensure_optional_imports()
        if HAS_PANDAS:
            return pd.read_sql(sql, self.conn)
        return self._query_all(sql)

    def execute_materialized_query(self, sql):
        return self._query_all(sql)

    def setup(self):
        if self.conn:
            self.conn.close()
        if os.path.exists(self.db_path):
            os.remove(self.db_path)
        self._connect()
        self.conn.execute("""
            CREATE TABLE bench (
                _id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT,
                age INTEGER,
                score REAL,
                city TEXT,
                category TEXT
            )
        """)
        self._txn_counter = 0
        self._txn_backlog_ready = False

    def cold_start_setup(self):
        if self.conn:
            self.conn.close()
        self._connect()

    def bench_insert(self):
        rows = list(zip(
            self.data["name"], self.data["age"], self.data["score"],
            self.data["city"], self.data["category"]
        ))
        self.conn.executemany(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            rows,
        )
        self.conn.commit()

    def bench_count(self):
        return self._scalar("SELECT COUNT(*) FROM bench")

    def bench_select_limit(self, limit=100):
        return self._query_all(f"SELECT * FROM bench LIMIT {limit}")

    def bench_select_limit_10k(self):
        return self._query_all("SELECT * FROM bench LIMIT 10000")

    def bench_projected_full_scan(self):
        return self._query_all("SELECT name, age, city FROM bench")

    def bench_filtered_limit_100(self):
        return self._query_all("SELECT * FROM bench WHERE age > 30 LIMIT 100")

    def bench_limit_offset_100(self):
        return self._query_all("SELECT * FROM bench LIMIT 100 OFFSET 10000")

    def bench_filter_string(self):
        return self._query_all(
            "SELECT * FROM bench WHERE name = 'user_5000'"
        )

    def bench_filter_range(self):
        return self._query_all(
            "SELECT * FROM bench WHERE age BETWEEN 25 AND 35"
        )

    def bench_group_by(self):
        return self._query_all(
            "SELECT city, COUNT(*), AVG(score) FROM bench GROUP BY city"
        )

    def bench_group_by_category(self):
        return self._query_all(
            "SELECT category, COUNT(*), AVG(score) FROM bench GROUP BY category"
        )

    def bench_group_by_order_count(self):
        return self._query_all(
            "SELECT city, COUNT(*) AS cnt FROM bench GROUP BY city ORDER BY cnt DESC LIMIT 5"
        )

    def bench_group_by_category_order_count(self):
        return self._query_all(
            "SELECT category, COUNT(*) AS cnt FROM bench GROUP BY category ORDER BY cnt DESC LIMIT 5"
        )

    def bench_group_by_having(self):
        return self._query_all(
            "SELECT city, COUNT(*) as cnt, AVG(score) FROM bench GROUP BY city HAVING cnt > 1000"
        )

    def bench_group_by_category_having(self):
        return self._query_all(
            "SELECT category, COUNT(*) as cnt, AVG(score) FROM bench GROUP BY category HAVING cnt > 1000"
        )

    def setup_view_bench(self):
        self.conn.execute("DROP VIEW IF EXISTS bench_view")
        self.conn.execute(
            "CREATE VIEW bench_view AS "
            "SELECT city, COUNT(*) AS cnt, AVG(score) AS avg_score "
            "FROM bench GROUP BY city"
        )
        self.conn.commit()

    def bench_view_select(self):
        return self._query_all(
            "SELECT city, cnt FROM bench_view WHERE cnt > 0 ORDER BY cnt DESC LIMIT 5"
        )

    def bench_order_limit(self):
        return self._query_all(
            "SELECT * FROM bench ORDER BY score DESC LIMIT 100"
        )

    def bench_order_limit_asc(self):
        return self._query_all(
            "SELECT * FROM bench ORDER BY score ASC LIMIT 100"
        )

    def bench_aggregation(self):
        return self._query_all(
            "SELECT COUNT(*), AVG(age), SUM(score), MIN(age), MAX(age) FROM bench"
        )

    def bench_filtered_aggregation(self):
        return self._query_all(
            "SELECT COUNT(*), AVG(score), MAX(score) FROM bench WHERE category = 'Electronics'"
        )

    def bench_filtered_aggregation_city(self):
        return self._query_all(
            "SELECT COUNT(*), AVG(score), MAX(score) FROM bench WHERE city = 'Beijing'"
        )

    def bench_count_where_category(self):
        return self._scalar(
            "SELECT COUNT(*) FROM bench WHERE category = 'Electronics'"
        )

    def bench_complex(self):
        return self._query_all(
            "SELECT city, AVG(score) as avg_s FROM bench WHERE age BETWEEN 25 AND 50 GROUP BY city ORDER BY avg_s DESC LIMIT 5"
        )

    def bench_point_lookup(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        return self._query_all(
            "SELECT * FROM bench WHERE _id = ?",
            (point_lookup_id,),
        )

    def bench_oltp_projected_point_lookup(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        return self._query_all(
            "SELECT name, age, score FROM bench WHERE _id = ?",
            (point_lookup_id,),
        )

    def bench_oltp_count_rows(self):
        return self._scalar("SELECT COUNT(*) FROM bench")

    def bench_oltp_direct_point_lookup(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        return self._query_all("SELECT * FROM bench WHERE _id = ?", (point_lookup_id,))

    def bench_oltp_missing_point_lookup(self):
        missing_id = self.n + 100_000_000
        return self._query_all("SELECT * FROM bench WHERE _id = ?", (missing_id,))

    def bench_retrieve_many(self):
        ids = self.shared_inputs["retrieve_many_ids"]
        placeholders = ",".join(["?"] * len(ids))
        return self._query_all(
            f"SELECT * FROM bench WHERE _id IN ({placeholders})",
            ids,
        )

    def bench_oltp_projected_retrieve_10(self):
        ids = self.shared_inputs["retrieve_many_ids"][:10]
        placeholders = ",".join(["?"] * len(ids))
        return self._query_all(
            f"SELECT name, age, score FROM bench WHERE _id IN ({placeholders})",
            ids,
        )

    def bench_oltp_projected_retrieve_100(self):
        ids = self.shared_inputs["retrieve_many_ids"]
        placeholders = ",".join(["?"] * len(ids))
        return self._query_all(
            f"SELECT name, age, score FROM bench WHERE _id IN ({placeholders})",
            ids,
        )

    def bench_oltp_projected_limit_100(self):
        return self._query_all("SELECT name, age, city FROM bench LIMIT 100")

    def bench_oltp_projected_string_eq(self):
        return self._query_all("SELECT age, score, city FROM bench WHERE name = 'user_5000'")

    def bench_oltp_city_limit_10(self):
        return self._query_all(
            "SELECT name, age FROM bench WHERE city = 'Beijing' LIMIT 100"
        )

    def bench_oltp_insert_one(self):
        self.conn.execute(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            OLTP_ONE_ROW_TUPLE,
        )
        self.conn.commit()

    def bench_oltp_insert_10_rows(self):
        rows = [
            (f"oltp_10_{self._txn_counter}_{i}", 30 + i, 70.0 + i, CITIES[i % len(CITIES)], CATEGORIES[i % len(CATEGORIES)])
            for i in range(10)
        ]
        self._txn_counter += 10
        self.conn.executemany(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            rows,
        )
        self.conn.commit()

    def bench_oltp_insert_read_own_row(self):
        cur = self.conn.execute(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            ("oltp_insert_read", 32, 78.0, "Shanghai", "Books"),
        )
        self.conn.commit()
        return self._query_all("SELECT * FROM bench WHERE _id = ?", (cur.lastrowid,))

    def bench_oltp_insert_count_visible(self):
        self.conn.execute(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            ("oltp_insert_count", 33, 79.0, "Guangzhou", "Books"),
        )
        self.conn.commit()
        return self._scalar("SELECT COUNT(*) FROM bench")

    def bench_oltp_update_by_id(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        self.conn.execute("UPDATE bench SET score = 77.0 WHERE _id = ?", (point_lookup_id,))
        self.conn.commit()

    def bench_oltp_update_missing_id(self):
        missing_id = self.n + 100_000_000
        self.conn.execute("UPDATE bench SET score = 77.0 WHERE _id = ?", (missing_id,))
        self.conn.commit()

    def bench_oltp_update_read_by_id(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        self.conn.execute("UPDATE bench SET score = 77.0 WHERE _id = ?", (point_lookup_id,))
        self.conn.commit()
        return self._query_all("SELECT score FROM bench WHERE _id = ?", (point_lookup_id,))

    def bench_oltp_replace_by_id(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        self.conn.execute(
            "UPDATE bench SET name = ?, age = ?, score = ?, city = ?, category = ? WHERE _id = ?",
            ("user_5000", 31, 77.0, "Beijing", "Books", point_lookup_id),
        )
        self.conn.commit()

    def bench_oltp_insert_delete_by_id(self):
        cur = self.conn.execute(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            ("oltp_insert_delete", 34, 80.0, "Shenzhen", "Books"),
        )
        self.conn.commit()
        self.conn.execute("DELETE FROM bench WHERE _id = ?", (cur.lastrowid,))
        self.conn.commit()

    def bench_oltp_delete_missing_id(self):
        missing_id = self.n + 100_000_000
        self.conn.execute("DELETE FROM bench WHERE _id = ?", (missing_id,))
        self.conn.commit()

    def _next_txn_prefix(self, count=1):
        start = self._txn_counter
        self._txn_counter += count
        return f"txn_sqlite_{start}"

    def _txn_rows(self, prefix, count):
        return [
            (f"{prefix}_{i}", 30 + (i % 25), 70.0 + (i % 17), CITIES[i % len(CITIES)], CATEGORIES[i % len(CATEGORIES)])
            for i in range(count)
        ]

    def bench_txn_empty_commit(self):
        self.conn.execute("BEGIN")
        self.conn.execute("COMMIT")

    def bench_txn_empty_rollback(self):
        self.conn.execute("BEGIN")
        self.conn.execute("ROLLBACK")

    def bench_txn_read_count_commit(self):
        self.conn.execute("BEGIN")
        result = self._scalar("SELECT COUNT(*) FROM bench")
        self.conn.execute("COMMIT")
        return result

    def bench_txn_insert_one_commit(self):
        row = self._txn_rows(self._next_txn_prefix(), 1)[0]
        self.conn.execute("BEGIN")
        self.conn.execute(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            row,
        )
        self.conn.execute("COMMIT")

    def bench_txn_insert_10_commit(self):
        rows = self._txn_rows(self._next_txn_prefix(10), 10)
        self.conn.execute("BEGIN")
        for row in rows:
            self.conn.execute(
                "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
                row,
            )
        self.conn.execute("COMMIT")

    def bench_txn_multi_insert_10_commit(self):
        rows = self._txn_rows(self._next_txn_prefix(10), 10)
        placeholders = ",".join(["(?,?,?,?,?)"] * len(rows))
        params = [value for row in rows for value in row]
        self.conn.execute("BEGIN")
        self.conn.execute(
            f"INSERT INTO bench (name, age, score, city, category) VALUES {placeholders}",
            params,
        )
        self.conn.execute("COMMIT")

    def bench_txn_insert_100_commit(self):
        rows = self._txn_rows(self._next_txn_prefix(100), 100)
        self.conn.execute("BEGIN")
        for row in rows:
            self.conn.execute(
                "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
                row,
            )
        self.conn.execute("COMMIT")

    def bench_txn_multi_insert_100_commit(self):
        rows = self._txn_rows(self._next_txn_prefix(100), 100)
        placeholders = ",".join(["(?,?,?,?,?)"] * len(rows))
        params = [value for row in rows for value in row]
        self.conn.execute("BEGIN")
        self.conn.execute(
            f"INSERT INTO bench (name, age, score, city, category) VALUES {placeholders}",
            params,
        )
        self.conn.execute("COMMIT")

    def bench_txn_insert_10_rollback(self):
        rows = self._txn_rows(self._next_txn_prefix(10), 10)
        self.conn.execute("BEGIN")
        for row in rows:
            self.conn.execute(
                "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
                row,
            )
        self.conn.execute("ROLLBACK")

    def bench_txn_update_by_id_commit(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        self.conn.execute("BEGIN")
        self.conn.execute("UPDATE bench SET score = 77.0 WHERE _id = ?", (point_lookup_id,))
        self.conn.execute("COMMIT")

    def bench_txn_insert_read_own_commit(self):
        row = self._txn_rows(self._next_txn_prefix(), 1)[0]
        self.conn.execute("BEGIN")
        cur = self.conn.execute(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            row,
        )
        result = self._query_all("SELECT * FROM bench WHERE _id = ?", (cur.lastrowid,))
        self.conn.execute("COMMIT")
        return result

    def setup_txn_backlog_1500(self):
        if self._txn_backlog_ready:
            return
        for _ in range(TXN_BACKLOG_ROWS):
            row = self._txn_rows(self._next_txn_prefix(), 1)[0]
            self.conn.execute("BEGIN")
            self.conn.execute(
                "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
                row,
            )
            self.conn.execute("COMMIT")
        self._txn_backlog_ready = True

    def bench_txn_backlog_string_miss_commit(self):
        self.conn.execute("BEGIN")
        result = self._query_all(
            "SELECT * FROM bench WHERE name = ?",
            (TXN_BACKLOG_MISSING_NAME,),
        )
        self.conn.execute("COMMIT")
        return result

    def bench_txn_backlog_count_commit(self):
        self.conn.execute("BEGIN")
        result = self._scalar("SELECT COUNT(*) FROM bench")
        self.conn.execute("COMMIT")
        return result

    def bench_txn_backlog_insert_read_own_by_name_commit(self):
        row = self._txn_rows(self._next_txn_prefix(), 1)[0]
        self.conn.execute("BEGIN")
        self.conn.execute(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            row,
        )
        result = self._query_all("SELECT * FROM bench WHERE name = ?", (row[0],))
        self.conn.execute("COMMIT")
        return result

    def bench_insert_1k(self):
        rows = [(f"new_{i}", 25, 50.0, "Beijing", "Books") for i in range(1000)]
        self.conn.executemany(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            rows,
        )
        self.conn.commit()

    def bench_full_scan_pandas(self):
        return self._query_pandas("SELECT * FROM bench")

    def bench_group_by_2cols(self):
        return self._query_all(
            "SELECT city, category, COUNT(*), AVG(score) FROM bench GROUP BY city, category"
        )

    def bench_filter_like(self):
        return self._query_all(
            "SELECT * FROM bench WHERE name LIKE 'user_1%'"
        )

    def bench_filter_multi_cond(self):
        return self._query_all(
            "SELECT * FROM bench WHERE age > 30 AND score > 50.0"
        )

    def bench_order_by_multi(self):
        return self._query_all(
            "SELECT * FROM bench ORDER BY city ASC, score DESC LIMIT 100"
        )

    def bench_count_distinct(self):
        return self._scalar(
            "SELECT COUNT(DISTINCT city) FROM bench"
        )

    def bench_count_distinct_category(self):
        return self._scalar(
            "SELECT COUNT(DISTINCT category) FROM bench"
        )

    def bench_filter_in(self):
        return self._query_all(
            "SELECT * FROM bench WHERE city IN ('Beijing', 'Shanghai', 'Guangzhou')"
        )

    def bench_filter_numeric_in(self):
        return self._query_all(
            "SELECT * FROM bench WHERE age IN (20, 25, 30, 35, 40, 45, 50, 55, 60)"
        )

    def bench_filter_or_cross_col(self):
        return self._query_all(
            "SELECT * FROM bench WHERE age = 25 OR city = 'Beijing'"
        )

    def bench_filter_numeric_or(self):
        return self._query_all(
            "SELECT * FROM bench WHERE age = 20 OR age = 30 OR age = 40 OR age = 50"
        )

    def bench_update_1k(self):
        self.conn.execute("UPDATE bench SET score = 50.0 WHERE age = 25")
        self.conn.commit()

    def bench_delete_1k(self):
        rows = [(f"del_{i}", 99, 99.0, "Beijing", "Books") for i in range(1000)]
        self.conn.executemany(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            rows,
        )
        self.conn.commit()
        self.conn.execute("DELETE FROM bench WHERE age = 99")
        self.conn.commit()

    def bench_delete_1k_setup(self):
        rows = [(f"del_{i}", 99, 99.0, "Beijing", "Books") for i in range(1000)]
        self.conn.executemany(
            "INSERT INTO bench (name, age, score, city, category) VALUES (?,?,?,?,?)",
            rows,
        )
        self.conn.commit()

    def bench_delete_1k_only(self):
        self.conn.execute("DELETE FROM bench WHERE age = 99")
        self.conn.commit()

    def bench_window_row_number(self):
        return self._query_all(
            "SELECT name, city, score, "
            "ROW_NUMBER() OVER (PARTITION BY city ORDER BY score DESC) as rn "
            "FROM bench LIMIT 1000"
        )

    def bench_fts_build(self):
        try:
            self.conn.execute("DROP TABLE IF EXISTS bench_fts")
            self.conn.execute("""
                CREATE VIRTUAL TABLE bench_fts
                USING fts5(name, city, category, content='bench', content_rowid='_id')
            """)
            self.conn.execute("INSERT INTO bench_fts(bench_fts) VALUES('rebuild')")
            self.conn.commit()
            self._fts_ready = True
        except Exception:
            self._fts_ready = False

    def bench_fts_search(self):
        if not getattr(self, '_fts_ready', False):
            return None
        return [
            row[0] for row in self.conn.execute(
            "SELECT rowid FROM bench_fts WHERE bench_fts MATCH 'Electronics'"
        ).fetchall()
        ]

    def close(self):
        if self.conn:
            self.conn.close()


# ---------------------------------------------------------------------------
# DuckDB benchmark
# ---------------------------------------------------------------------------

class DuckDBBench:
    def __init__(self, tmpdir, data, csv_path=None, parquet_path=None, json_path=None):
        self.db_path = os.path.join(tmpdir, "bench.duckdb")
        self.data = data
        self.n = len(data["name"])
        self.conn = None
        self.csv_path = csv_path
        self.parquet_path = parquet_path
        self.json_path = json_path
        self.shared_inputs = build_shared_inputs(self.n)
        self._next_rowid = 0
        self._txn_counter = 0
        self._txn_backlog_ready = False

    def _connect(self):
        ensure_optional_imports()
        self.conn = duckdb.connect(self.db_path)

    def _query_all(self, sql, params=()):
        cur = self.conn.execute(sql, params)
        return rows_to_dicts([d[0] for d in (cur.description or [])], cur.fetchall())

    def _scalar(self, sql, params=()):
        return self.conn.execute(sql, params).fetchone()[0]

    def _query_pandas(self, sql):
        ensure_optional_imports()
        if HAS_PANDAS:
            return self.conn.execute(sql).df()
        return self._query_all(sql)

    def execute_materialized_query(self, sql):
        return self._query_all(sql)

    def setup(self):
        if self.conn:
            self.conn.close()
        if os.path.exists(self.db_path):
            os.remove(self.db_path)
        self._connect()
        self.conn.execute("""
            CREATE TABLE bench (
                name VARCHAR,
                age INTEGER,
                score DOUBLE,
                city VARCHAR,
                category VARCHAR
            )
        """)
        self._txn_counter = 0
        self._txn_backlog_ready = False
        self._temp_csv_name = None
        self._temp_json_name = None

    def cold_start_setup(self):
        if self.conn:
            self.conn.close()
        self._connect()

    def bench_insert(self):
        # Use executemany for reliable cross-version compatibility
        rows = list(zip(
            self.data["name"], self.data["age"], self.data["score"],
            self.data["city"], self.data["category"]
        ))
        self.conn.executemany(
            "INSERT INTO bench VALUES (?,?,?,?,?)", rows
        )
        self._next_rowid = self.n

    def bench_count(self):
        return self._scalar("SELECT COUNT(*) FROM bench")

    def bench_select_limit(self, limit=100):
        return self._query_all(f"SELECT * FROM bench LIMIT {limit}")

    def bench_select_limit_10k(self):
        return self._query_all("SELECT * FROM bench LIMIT 10000")

    def bench_projected_full_scan(self):
        return self._query_all("SELECT name, age, city FROM bench")

    def bench_filtered_limit_100(self):
        return self._query_all("SELECT * FROM bench WHERE age > 30 LIMIT 100")

    def bench_limit_offset_100(self):
        return self._query_all("SELECT * FROM bench LIMIT 100 OFFSET 10000")

    def bench_filter_string(self):
        return self._query_all(
            "SELECT * FROM bench WHERE name = 'user_5000'"
        )

    def bench_filter_range(self):
        return self._query_all(
            "SELECT * FROM bench WHERE age BETWEEN 25 AND 35"
        )

    def bench_group_by(self):
        return self._query_all(
            "SELECT city, COUNT(*), AVG(score) FROM bench GROUP BY city"
        )

    def bench_group_by_category(self):
        return self._query_all(
            "SELECT category, COUNT(*), AVG(score) FROM bench GROUP BY category"
        )

    def bench_group_by_order_count(self):
        return self._query_all(
            "SELECT city, COUNT(*) AS cnt FROM bench GROUP BY city ORDER BY cnt DESC LIMIT 5"
        )

    def bench_group_by_category_order_count(self):
        return self._query_all(
            "SELECT category, COUNT(*) AS cnt FROM bench GROUP BY category ORDER BY cnt DESC LIMIT 5"
        )

    def bench_group_by_having(self):
        return self._query_all(
            "SELECT city, COUNT(*) as cnt, AVG(score) FROM bench GROUP BY city HAVING cnt > 1000"
        )

    def bench_group_by_category_having(self):
        return self._query_all(
            "SELECT category, COUNT(*) as cnt, AVG(score) FROM bench GROUP BY category HAVING cnt > 1000"
        )

    def setup_view_bench(self):
        self.conn.execute("DROP VIEW IF EXISTS bench_view")
        self.conn.execute(
            "CREATE VIEW bench_view AS "
            "SELECT city, COUNT(*) AS cnt, AVG(score) AS avg_score "
            "FROM bench GROUP BY city"
        )

    def bench_view_select(self):
        return self._query_all(
            "SELECT city, cnt FROM bench_view WHERE cnt > 0 ORDER BY cnt DESC LIMIT 5"
        )

    def bench_order_limit(self):
        return self._query_all(
            "SELECT * FROM bench ORDER BY score DESC LIMIT 100"
        )

    def bench_order_limit_asc(self):
        return self._query_all(
            "SELECT * FROM bench ORDER BY score ASC LIMIT 100"
        )

    def bench_aggregation(self):
        return self._query_all(
            "SELECT COUNT(*), AVG(age), SUM(score), MIN(age), MAX(age) FROM bench"
        )

    def bench_filtered_aggregation(self):
        return self._query_all(
            "SELECT COUNT(*), AVG(score), MAX(score) FROM bench WHERE category = 'Electronics'"
        )

    def bench_filtered_aggregation_city(self):
        return self._query_all(
            "SELECT COUNT(*), AVG(score), MAX(score) FROM bench WHERE city = 'Beijing'"
        )

    def bench_count_where_category(self):
        return self._scalar(
            "SELECT COUNT(*) FROM bench WHERE category = 'Electronics'"
        )

    def bench_complex(self):
        return self._query_all(
            "SELECT city, AVG(score) as avg_s FROM bench WHERE age BETWEEN 25 AND 50 GROUP BY city ORDER BY avg_s DESC LIMIT 5"
        )

    def bench_point_lookup(self):
        rowid = self.shared_inputs["point_lookup_id"] - 1
        return self._query_all(
            "SELECT rowid + 1 AS _id, * FROM bench WHERE rowid = ?",
            (rowid,),
        )

    def bench_oltp_projected_point_lookup(self):
        rowid = self.shared_inputs["point_lookup_id"] - 1
        return self._query_all(
            "SELECT name, age, score FROM bench WHERE rowid = ?",
            (rowid,),
        )

    def bench_oltp_count_rows(self):
        return self._scalar("SELECT COUNT(*) FROM bench")

    def bench_oltp_direct_point_lookup(self):
        rowid = self.shared_inputs["point_lookup_id"] - 1
        return self._query_all(
            "SELECT rowid + 1 AS _id, * FROM bench WHERE rowid = ?",
            (rowid,),
        )

    def bench_oltp_missing_point_lookup(self):
        missing_rowid = self.n + 100_000_000
        return self._query_all(
            "SELECT rowid + 1 AS _id, * FROM bench WHERE rowid = ?",
            (missing_rowid,),
        )

    def bench_retrieve_many(self):
        ids = self.shared_inputs["retrieve_many_ids"]
        rowids = [id_ - 1 for id_ in ids]
        placeholders = ",".join(["?"] * len(rowids))
        return self._query_all(
            f"SELECT rowid + 1 AS _id, * FROM bench WHERE rowid IN ({placeholders})",
            rowids,
        )

    def bench_oltp_projected_retrieve_10(self):
        ids = self.shared_inputs["retrieve_many_ids"][:10]
        rowids = [id_ - 1 for id_ in ids]
        placeholders = ",".join(["?"] * len(rowids))
        return self._query_all(
            f"SELECT name, age, score FROM bench WHERE rowid IN ({placeholders})",
            rowids,
        )

    def bench_oltp_projected_retrieve_100(self):
        ids = self.shared_inputs["retrieve_many_ids"]
        rowids = [id_ - 1 for id_ in ids]
        placeholders = ",".join(["?"] * len(rowids))
        return self._query_all(
            f"SELECT name, age, score FROM bench WHERE rowid IN ({placeholders})",
            rowids,
        )

    def bench_oltp_projected_limit_100(self):
        return self._query_all("SELECT name, age, city FROM bench LIMIT 100")

    def bench_oltp_projected_string_eq(self):
        return self._query_all("SELECT age, score, city FROM bench WHERE name = 'user_5000'")

    def bench_oltp_city_limit_10(self):
        return self._query_all(
            "SELECT name, age FROM bench WHERE city = 'Beijing' LIMIT 100"
        )

    def bench_oltp_insert_one(self):
        self.conn.execute(
            "INSERT INTO bench VALUES (?,?,?,?,?)",
            OLTP_ONE_ROW_TUPLE,
        )
        self._next_rowid += 1

    def bench_oltp_insert_10_rows(self):
        rows = [
            (f"oltp_10_{self._txn_counter}_{i}", 30 + i, 70.0 + i, CITIES[i % len(CITIES)], CATEGORIES[i % len(CATEGORIES)])
            for i in range(10)
        ]
        self._txn_counter += 10
        self.conn.executemany("INSERT INTO bench VALUES (?,?,?,?,?)", rows)
        self._next_rowid += 10

    def bench_oltp_insert_read_own_row(self):
        rowid = self._next_rowid
        self.conn.execute(
            "INSERT INTO bench VALUES (?,?,?,?,?)",
            ("oltp_insert_read", 32, 78.0, "Shanghai", "Books"),
        )
        self._next_rowid += 1
        return self._query_all(
            "SELECT rowid + 1 AS _id, * FROM bench WHERE rowid = ?",
            (rowid,),
        )

    def bench_oltp_insert_count_visible(self):
        self.conn.execute(
            "INSERT INTO bench VALUES (?,?,?,?,?)",
            ("oltp_insert_count", 33, 79.0, "Guangzhou", "Books"),
        )
        self._next_rowid += 1
        return self._scalar("SELECT COUNT(*) FROM bench")

    def bench_oltp_update_by_id(self):
        rowid = self.shared_inputs["point_lookup_id"] - 1
        self.conn.execute("UPDATE bench SET score = 77.0 WHERE rowid = ?", (rowid,))

    def bench_oltp_update_missing_id(self):
        missing_rowid = self.n + 100_000_000
        self.conn.execute("UPDATE bench SET score = 77.0 WHERE rowid = ?", (missing_rowid,))

    def bench_oltp_update_read_by_id(self):
        rowid = self.shared_inputs["point_lookup_id"] - 1
        self.conn.execute("UPDATE bench SET score = 77.0 WHERE rowid = ?", (rowid,))
        return self._query_all("SELECT score FROM bench WHERE rowid = ?", (rowid,))

    def bench_oltp_replace_by_id(self):
        rowid = self.shared_inputs["point_lookup_id"] - 1
        self.conn.execute(
            "UPDATE bench SET name = ?, age = ?, score = ?, city = ?, category = ? WHERE rowid = ?",
            ("user_5000", 31, 77.0, "Beijing", "Books", rowid),
        )

    def bench_oltp_insert_delete_by_id(self):
        rowid = self._next_rowid
        self.conn.execute(
            "INSERT INTO bench VALUES (?,?,?,?,?)",
            ("oltp_insert_delete", 34, 80.0, "Shenzhen", "Books"),
        )
        self._next_rowid += 1
        self.conn.execute("DELETE FROM bench WHERE rowid = ?", (rowid,))

    def bench_oltp_delete_missing_id(self):
        missing_rowid = self.n + 100_000_000
        self.conn.execute("DELETE FROM bench WHERE rowid = ?", (missing_rowid,))

    def _next_txn_prefix(self, count=1):
        start = self._txn_counter
        self._txn_counter += count
        return f"txn_duckdb_{start}"

    def _txn_rows(self, prefix, count):
        return [
            (f"{prefix}_{i}", 30 + (i % 25), 70.0 + (i % 17), CITIES[i % len(CITIES)], CATEGORIES[i % len(CATEGORIES)])
            for i in range(count)
        ]

    def bench_txn_empty_commit(self):
        self.conn.execute("BEGIN TRANSACTION")
        self.conn.execute("COMMIT")

    def bench_txn_empty_rollback(self):
        self.conn.execute("BEGIN TRANSACTION")
        self.conn.execute("ROLLBACK")

    def bench_txn_read_count_commit(self):
        self.conn.execute("BEGIN TRANSACTION")
        result = self._scalar("SELECT COUNT(*) FROM bench")
        self.conn.execute("COMMIT")
        return result

    def bench_txn_insert_one_commit(self):
        row = self._txn_rows(self._next_txn_prefix(), 1)[0]
        self.conn.execute("BEGIN TRANSACTION")
        self.conn.execute("INSERT INTO bench VALUES (?,?,?,?,?)", row)
        self.conn.execute("COMMIT")
        self._next_rowid += 1

    def bench_txn_insert_10_commit(self):
        rows = self._txn_rows(self._next_txn_prefix(10), 10)
        self.conn.execute("BEGIN TRANSACTION")
        for row in rows:
            self.conn.execute("INSERT INTO bench VALUES (?,?,?,?,?)", row)
        self.conn.execute("COMMIT")
        self._next_rowid += 10

    def bench_txn_multi_insert_10_commit(self):
        rows = self._txn_rows(self._next_txn_prefix(10), 10)
        placeholders = ",".join(["(?,?,?,?,?)"] * len(rows))
        params = [value for row in rows for value in row]
        self.conn.execute("BEGIN TRANSACTION")
        self.conn.execute(f"INSERT INTO bench VALUES {placeholders}", params)
        self.conn.execute("COMMIT")
        self._next_rowid += 10

    def bench_txn_insert_100_commit(self):
        rows = self._txn_rows(self._next_txn_prefix(100), 100)
        self.conn.execute("BEGIN TRANSACTION")
        for row in rows:
            self.conn.execute("INSERT INTO bench VALUES (?,?,?,?,?)", row)
        self.conn.execute("COMMIT")
        self._next_rowid += 100

    def bench_txn_multi_insert_100_commit(self):
        rows = self._txn_rows(self._next_txn_prefix(100), 100)
        placeholders = ",".join(["(?,?,?,?,?)"] * len(rows))
        params = [value for row in rows for value in row]
        self.conn.execute("BEGIN TRANSACTION")
        self.conn.execute(f"INSERT INTO bench VALUES {placeholders}", params)
        self.conn.execute("COMMIT")
        self._next_rowid += 100

    def bench_txn_insert_10_rollback(self):
        rows = self._txn_rows(self._next_txn_prefix(10), 10)
        self.conn.execute("BEGIN TRANSACTION")
        for row in rows:
            self.conn.execute("INSERT INTO bench VALUES (?,?,?,?,?)", row)
        self.conn.execute("ROLLBACK")

    def bench_txn_update_by_id_commit(self):
        rowid = self.shared_inputs["point_lookup_id"] - 1
        self.conn.execute("BEGIN TRANSACTION")
        self.conn.execute("UPDATE bench SET score = 77.0 WHERE rowid = ?", (rowid,))
        self.conn.execute("COMMIT")

    def bench_txn_insert_read_own_commit(self):
        row = self._txn_rows(self._next_txn_prefix(), 1)[0]
        rowid = self._next_rowid
        self.conn.execute("BEGIN TRANSACTION")
        self.conn.execute("INSERT INTO bench VALUES (?,?,?,?,?)", row)
        result = self._query_all("SELECT rowid + 1 AS _id, * FROM bench WHERE rowid = ?", (rowid,))
        self.conn.execute("COMMIT")
        self._next_rowid += 1
        return result

    def setup_txn_backlog_1500(self):
        if self._txn_backlog_ready:
            return
        for _ in range(TXN_BACKLOG_ROWS):
            row = self._txn_rows(self._next_txn_prefix(), 1)[0]
            self.conn.execute("BEGIN TRANSACTION")
            self.conn.execute("INSERT INTO bench VALUES (?,?,?,?,?)", row)
            self.conn.execute("COMMIT")
            self._next_rowid += 1
        self._txn_backlog_ready = True

    def bench_txn_backlog_string_miss_commit(self):
        self.conn.execute("BEGIN TRANSACTION")
        result = self._query_all(
            "SELECT rowid + 1 AS _id, * FROM bench WHERE name = ?",
            (TXN_BACKLOG_MISSING_NAME,),
        )
        self.conn.execute("COMMIT")
        return result

    def bench_txn_backlog_count_commit(self):
        self.conn.execute("BEGIN TRANSACTION")
        result = self._scalar("SELECT COUNT(*) FROM bench")
        self.conn.execute("COMMIT")
        return result

    def bench_txn_backlog_insert_read_own_by_name_commit(self):
        row = self._txn_rows(self._next_txn_prefix(), 1)[0]
        self.conn.execute("BEGIN TRANSACTION")
        self.conn.execute("INSERT INTO bench VALUES (?,?,?,?,?)", row)
        result = self._query_all(
            "SELECT rowid + 1 AS _id, * FROM bench WHERE name = ?",
            (row[0],),
        )
        self.conn.execute("COMMIT")
        self._next_rowid += 1
        return result

    def bench_insert_1k(self):
        # Use executemany for reliable cross-version compatibility
        rows = [(f"new_{i}", 25, 50.0, "Beijing", "Books") for i in range(1000)]
        self.conn.executemany("INSERT INTO bench VALUES (?,?,?,?,?)", rows)
        self._next_rowid += 1000

    def bench_full_scan_pandas(self):
        return self._query_pandas("SELECT rowid + 1 AS _id, * FROM bench")

    def bench_group_by_2cols(self):
        return self._query_all(
            "SELECT city, category, COUNT(*), AVG(score) FROM bench GROUP BY city, category"
        )

    def bench_filter_like(self):
        return self._query_all(
            "SELECT * FROM bench WHERE name LIKE 'user_1%'"
        )

    def bench_filter_multi_cond(self):
        return self._query_all(
            "SELECT * FROM bench WHERE age > 30 AND score > 50.0"
        )

    def bench_order_by_multi(self):
        return self._query_all(
            "SELECT * FROM bench ORDER BY city ASC, score DESC LIMIT 100"
        )

    def bench_count_distinct(self):
        return self._scalar(
            "SELECT COUNT(DISTINCT city) FROM bench"
        )

    def bench_count_distinct_category(self):
        return self._scalar(
            "SELECT COUNT(DISTINCT category) FROM bench"
        )

    def bench_filter_in(self):
        return self._query_all(
            "SELECT * FROM bench WHERE city IN ('Beijing', 'Shanghai', 'Guangzhou')"
        )

    def bench_filter_numeric_in(self):
        return self._query_all(
            "SELECT * FROM bench WHERE age IN (20, 25, 30, 35, 40, 45, 50, 55, 60)"
        )

    def bench_filter_or_cross_col(self):
        return self._query_all(
            "SELECT * FROM bench WHERE age = 25 OR city = 'Beijing'"
        )

    def bench_filter_numeric_or(self):
        return self._query_all(
            "SELECT * FROM bench WHERE age = 20 OR age = 30 OR age = 40 OR age = 50"
        )

    def bench_update_1k(self):
        self.conn.execute("UPDATE bench SET score = 50.0 WHERE age = 25")

    def bench_delete_1k(self):
        rows = [(f"del_{i}", 99, 99.0, "Beijing", "Books") for i in range(1000)]
        self.conn.executemany("INSERT INTO bench VALUES (?,?,?,?,?)", rows)
        self._next_rowid += 1000
        self.conn.execute("DELETE FROM bench WHERE age = 99")

    def bench_delete_1k_setup(self):
        rows = [(f"del_{i}", 99, 99.0, "Beijing", "Books") for i in range(1000)]
        self.conn.executemany("INSERT INTO bench VALUES (?,?,?,?,?)", rows)
        self._next_rowid += 1000

    def bench_delete_1k_only(self):
        self.conn.execute("DELETE FROM bench WHERE age = 99")

    def bench_window_row_number(self):
        return self._query_all(
            "SELECT name, city, score, "
            "ROW_NUMBER() OVER (PARTITION BY city ORDER BY score DESC) as rn "
            "FROM bench LIMIT 1000"
        )

    def bench_fts_build(self):
        try:
            self.conn.execute("INSTALL fts")
            self.conn.execute("LOAD fts")
            self.conn.execute(
                "PRAGMA create_fts_index('bench', 'rowid', 'name', 'city', 'category')"
            )
            self._fts_ready = True
        except Exception:
            self._fts_ready = False

    def bench_fts_search(self):
        if not getattr(self, '_fts_ready', False):
            return None
        try:
            return [
                row["_id"] for row in self._query_all(
                "SELECT rowid + 1 AS _id FROM bench "
                "WHERE fts_main_bench.match_bm25(rowid, 'Electronics') IS NOT NULL"
            )
            ]
        except Exception:
            return None

    def bench_csv_read_count(self):
        return self._scalar(f"SELECT COUNT(*) FROM read_csv_auto('{self.csv_path}')")

    def bench_csv_read_filter_group(self):
        return self._query_all(
            f"SELECT city, COUNT(*) FROM read_csv_auto('{self.csv_path}') WHERE age > 30 GROUP BY city"
        )

    def bench_csv_read_limit_1k(self):
        return self._query_all(f"SELECT * FROM read_csv_auto('{self.csv_path}') LIMIT 1000")

    def bench_json_read_count(self):
        return self._scalar(f"SELECT COUNT(*) FROM read_json_auto('{self.json_path}')")

    def bench_temp_csv_create_query(self):
        if self._temp_csv_name is None:
            self._temp_csv_name = f"bench_csv_temp_{uuid.uuid4().hex[:8]}"
            self.conn.execute(f"CREATE TABLE {self._temp_csv_name} AS SELECT * FROM read_csv_auto('{self.csv_path}')")
        return self._scalar(f"SELECT AVG(score) FROM {self._temp_csv_name} WHERE age > 30")

    def bench_csv_read_order_limit(self):
        return self._query_all(
            f"SELECT * FROM read_csv_auto('{self.csv_path}') ORDER BY score DESC LIMIT 100"
        )

    def bench_json_read_filter(self):
        return self._scalar(
            f"SELECT COUNT(*) FROM read_json_auto('{self.json_path}') WHERE age > 30"
        )

    def bench_json_read_order_limit(self):
        return self._query_all(
            f"SELECT * FROM read_json_auto('{self.json_path}') ORDER BY score DESC LIMIT 100"
        )

    def bench_json_read_group_category(self):
        return self._query_all(
            f"SELECT category, COUNT(*) FROM read_json_auto('{self.json_path}') GROUP BY category"
        )

    def close(self):
        if self.conn:
            self.conn.close()


# ---------------------------------------------------------------------------
# ApexBase benchmark
# ---------------------------------------------------------------------------

class ApexBaseBench:
    def __init__(self, tmpdir, data, low_memory=False, csv_path=None, parquet_path=None, json_path=None):
        self.db_dir = os.path.join(tmpdir, "apex_bench")
        self.data = data
        self.n = len(data["name"])
        self.client = None
        self.low_memory = low_memory
        self.csv_path = csv_path
        self.parquet_path = parquet_path
        self.json_path = json_path
        self.shared_inputs = build_shared_inputs(self.n)
        self._next_id = 1
        self._txn_counter = 0
        self._txn_backlog_ready = False

    def _query_all(self, sql):
        return self.client.execute(sql, show_internal_id=True).to_dict()

    def _scalar(self, sql):
        return self.client.execute(sql).scalar()

    def _query_pandas(self, sql):
        ensure_optional_imports()
        result = self.client.execute(sql, show_internal_id=True)
        if HAS_PANDAS:
            return result.to_pandas()
        return result.to_dict()

    def execute_materialized_query(self, sql):
        return self.client.execute(sql, show_internal_id=True).to_dict()

    def setup(self):
        ensure_optional_imports()
        if self.client:
            try:
                self.client.close()
            except Exception:
                pass
            self.client = None
        if os.path.exists(self.db_dir):
            shutil.rmtree(self.db_dir)
        self.client = ApexClient(self.db_dir, drop_if_exists=True)
        self.client.create_table('default')
        self._next_id = 1
        self._txn_counter = 0
        self._txn_backlog_ready = False
        self._temp_csv_name = None
        self._temp_json_name = None

    def cold_start_setup(self):
        """Close and reopen client — clears all Python/Rust-side caches (arrow_batch_cache etc.)."""
        ensure_optional_imports()
        if self.client:
            self.client.close()
        self.client = ApexClient(self.db_dir)
        self.client.use_table('default')

    def bench_insert(self):
        self.client.store(self.data)
        self._next_id = self.n + 1

    def bench_count(self):
        return self._scalar("SELECT COUNT(*) FROM default")

    def bench_select_limit(self, limit=100):
        return self._query_all(f"SELECT * FROM default LIMIT {limit}")

    def bench_select_limit_10k(self):
        return self._query_all("SELECT * FROM default LIMIT 10000")

    def bench_projected_full_scan(self):
        return self._query_all("SELECT name, age, city FROM default")

    def bench_filtered_limit_100(self):
        return self._query_all("SELECT * FROM default WHERE age > 30 LIMIT 100")

    def bench_limit_offset_100(self):
        return self._query_all("SELECT * FROM default LIMIT 100 OFFSET 10000")

    def bench_filter_string(self):
        return self._query_all(
            "SELECT * FROM default WHERE name = 'user_5000'"
        )

    def bench_filter_range(self):
        return self._query_all(
            "SELECT * FROM default WHERE age BETWEEN 25 AND 35"
        )

    def bench_group_by(self):
        return self._query_all(
            "SELECT city, COUNT(*), AVG(score) FROM default GROUP BY city"
        )

    def bench_group_by_category(self):
        return self._query_all(
            "SELECT category, COUNT(*), AVG(score) FROM default GROUP BY category"
        )

    def bench_group_by_order_count(self):
        return self._query_all(
            "SELECT city, COUNT(*) AS cnt FROM default GROUP BY city ORDER BY cnt DESC LIMIT 5"
        )

    def bench_group_by_category_order_count(self):
        return self._query_all(
            "SELECT category, COUNT(*) AS cnt FROM default GROUP BY category ORDER BY cnt DESC LIMIT 5"
        )

    def bench_group_by_having(self):
        return self._query_all(
            "SELECT city, COUNT(*) as cnt, AVG(score) FROM default GROUP BY city HAVING cnt > 1000"
        )

    def bench_group_by_category_having(self):
        return self._query_all(
            "SELECT category, COUNT(*) as cnt, AVG(score) FROM default GROUP BY category HAVING cnt > 1000"
        )

    def setup_view_bench(self):
        try:
            self.client.execute("DROP VIEW bench_view")
        except Exception:
            pass
        self.client.execute(
            "CREATE VIEW bench_view AS "
            "SELECT city, COUNT(*) AS cnt, AVG(score) AS avg_score "
            "FROM default GROUP BY city"
        )

    def bench_view_select(self):
        return self._query_all(
            "SELECT city, cnt FROM bench_view WHERE cnt > 0 ORDER BY cnt DESC LIMIT 5"
        )

    def bench_order_limit(self):
        return self._query_all(
            "SELECT * FROM default ORDER BY score DESC LIMIT 100"
        )

    def bench_order_limit_asc(self):
        return self._query_all(
            "SELECT * FROM default ORDER BY score ASC LIMIT 100"
        )

    def bench_aggregation(self):
        return self._query_all(
            "SELECT COUNT(*), AVG(age), SUM(score), MIN(age), MAX(age) FROM default"
        )

    def bench_filtered_aggregation(self):
        return self._query_all(
            "SELECT COUNT(*), AVG(score), MAX(score) FROM default WHERE category = 'Electronics'"
        )

    def bench_filtered_aggregation_city(self):
        return self._query_all(
            "SELECT COUNT(*), AVG(score), MAX(score) FROM default WHERE city = 'Beijing'"
        )

    def bench_count_where_category(self):
        return self._scalar(
            "SELECT COUNT(*) FROM default WHERE category = 'Electronics'"
        )

    def bench_complex(self):
        return self._query_all(
            "SELECT city, AVG(score) as avg_s FROM default WHERE age BETWEEN 25 AND 50 GROUP BY city ORDER BY avg_s DESC LIMIT 5"
        )

    def bench_point_lookup(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        return self._query_all(
            f"SELECT * FROM default WHERE _id = {point_lookup_id}"
        )

    def bench_oltp_projected_point_lookup(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        return self.client.execute(
            f"SELECT name, age, score FROM default WHERE _id = {point_lookup_id}"
        ).to_dict()

    def bench_oltp_count_rows(self):
        return self.client.count_rows()

    def bench_oltp_direct_point_lookup(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        return self.client.retrieve(point_lookup_id)

    def bench_oltp_missing_point_lookup(self):
        missing_id = self.n + 100_000_000
        return self.client.retrieve(missing_id)

    def bench_retrieve_many(self):
        ids = self.shared_inputs["retrieve_many_ids"]
        id_list = ",".join(str(id_) for id_ in ids)
        return self._query_all(
            f"SELECT * FROM default WHERE _id IN ({id_list})"
        )

    def bench_oltp_projected_retrieve_10(self):
        ids = self.shared_inputs["retrieve_many_ids"][:10]
        id_list = ",".join(str(id_) for id_ in ids)
        return self.client.execute(
            f"SELECT name, age, score FROM default WHERE _id IN ({id_list})"
        ).to_dict()

    def bench_oltp_projected_retrieve_100(self):
        ids = self.shared_inputs["retrieve_many_ids"]
        id_list = ",".join(str(id_) for id_ in ids)
        return self.client.execute(
            f"SELECT name, age, score FROM default WHERE _id IN ({id_list})"
        ).to_dict()

    def bench_oltp_projected_limit_100(self):
        return self.client.execute("SELECT name, age, city FROM default LIMIT 100").to_dict()

    def bench_oltp_projected_string_eq(self):
        return self.client.execute("SELECT age, score, city FROM default WHERE name = 'user_5000'").to_dict()

    def bench_oltp_city_limit_10(self):
        return self.client.execute(
            "SELECT name, age FROM default WHERE city = 'Beijing' LIMIT 100"
        ).to_dict()

    def bench_oltp_insert_one(self):
        self.client.store(OLTP_ONE_ROW_DICT)
        self._next_id += 1

    def bench_oltp_insert_10_rows(self):
        data = {
            "name": [f"oltp_10_{self._txn_counter}_{i}" for i in range(10)],
            "age": [30 + i for i in range(10)],
            "score": [70.0 + i for i in range(10)],
            "city": [CITIES[i % len(CITIES)] for i in range(10)],
            "category": [CATEGORIES[i % len(CATEGORIES)] for i in range(10)],
        }
        self._txn_counter += 10
        self.client.store(data)
        self._next_id += 10

    def bench_oltp_insert_one_durable(self):
        self.client.store_durable_one(OLTP_ONE_ROW_DICT)
        self._next_id += 1

    def bench_oltp_insert_read_own_row(self):
        row_id = self._next_id
        self.client.store({
            "name": "oltp_insert_read",
            "age": 32,
            "score": 78.0,
            "city": "Shanghai",
            "category": "Books",
        })
        self._next_id += 1
        return self.client.retrieve(row_id)

    def bench_oltp_insert_count_visible(self):
        self.client.store({
            "name": "oltp_insert_count",
            "age": 33,
            "score": 79.0,
            "city": "Guangzhou",
            "category": "Books",
        })
        self._next_id += 1
        return self.client.count_rows()

    def bench_oltp_update_by_id(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        return self.client.execute(
            f"UPDATE default SET score = 77.0 WHERE _id = {point_lookup_id}"
        )

    def bench_oltp_update_missing_id(self):
        missing_id = self.n + 100_000_000
        return self.client.execute(
            f"UPDATE default SET score = 77.0 WHERE _id = {missing_id}"
        )

    def bench_oltp_update_read_by_id(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        self.client.execute(
            f"UPDATE default SET score = 77.0 WHERE _id = {point_lookup_id}"
        )
        return self.client.execute(
            f"SELECT score FROM default WHERE _id = {point_lookup_id}"
        ).to_dict()

    def bench_oltp_replace_by_id(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        return self.client.replace(point_lookup_id, {
            "name": "user_5000",
            "age": 31,
            "score": 77.0,
            "city": "Beijing",
            "category": "Books",
        })

    def bench_oltp_insert_delete_by_id(self):
        row_id = self._next_id
        self.client.store({
            "name": "oltp_insert_delete",
            "age": 34,
            "score": 80.0,
            "city": "Shenzhen",
            "category": "Books",
        })
        self._next_id += 1
        return self.client.delete(id=row_id)

    def bench_oltp_delete_missing_id(self):
        missing_id = self.n + 100_000_000
        return self.client.delete(id=missing_id)

    def _next_txn_prefix(self, count=1):
        start = self._txn_counter
        self._txn_counter += count
        return f"txn_apex_{start}"

    def _txn_rows_sql(self, prefix, count):
        return [
            f"('{prefix}_{i}', {30 + (i % 25)}, {70.0 + (i % 17):.1f}, "
            f"'{CITIES[i % len(CITIES)]}', '{CATEGORIES[i % len(CATEGORIES)]}')"
            for i in range(count)
        ]

    def bench_txn_empty_commit(self):
        self.client.execute("BEGIN")
        self.client.execute("COMMIT")

    def bench_txn_empty_rollback(self):
        self.client.execute("BEGIN")
        self.client.execute("ROLLBACK")

    def bench_txn_read_count_commit(self):
        self.client.execute("BEGIN")
        result = self.client.execute("SELECT COUNT(*) FROM default").scalar()
        self.client.execute("COMMIT")
        return result

    def bench_txn_insert_one_commit(self):
        values = self._txn_rows_sql(self._next_txn_prefix(), 1)[0]
        self.client.execute("BEGIN")
        self.client.execute(f"INSERT INTO default (name, age, score, city, category) VALUES {values}")
        self.client.execute("COMMIT")
        self._next_id += 1

    def bench_txn_insert_10_commit(self):
        rows = self._txn_rows_sql(self._next_txn_prefix(10), 10)
        self.client.execute("BEGIN")
        for values in rows:
            self.client.execute(f"INSERT INTO default (name, age, score, city, category) VALUES {values}")
        self.client.execute("COMMIT")
        self._next_id += 10

    def bench_txn_multi_insert_10_commit(self):
        rows = self._txn_rows_sql(self._next_txn_prefix(10), 10)
        self.client.execute("BEGIN")
        self.client.execute(
            "INSERT INTO default (name, age, score, city, category) VALUES "
            + ", ".join(rows)
        )
        self.client.execute("COMMIT")
        self._next_id += 10

    def bench_txn_insert_100_commit(self):
        rows = self._txn_rows_sql(self._next_txn_prefix(100), 100)
        self.client.execute("BEGIN")
        for values in rows:
            self.client.execute(f"INSERT INTO default (name, age, score, city, category) VALUES {values}")
        self.client.execute("COMMIT")
        self._next_id += 100

    def bench_txn_multi_insert_100_commit(self):
        rows = self._txn_rows_sql(self._next_txn_prefix(100), 100)
        self.client.execute("BEGIN")
        self.client.execute(
            "INSERT INTO default (name, age, score, city, category) VALUES "
            + ", ".join(rows)
        )
        self.client.execute("COMMIT")
        self._next_id += 100

    def bench_txn_insert_10_rollback(self):
        rows = self._txn_rows_sql(self._next_txn_prefix(10), 10)
        self.client.execute("BEGIN")
        for values in rows:
            self.client.execute(f"INSERT INTO default (name, age, score, city, category) VALUES {values}")
        self.client.execute("ROLLBACK")

    def bench_txn_update_by_id_commit(self):
        point_lookup_id = self.shared_inputs["point_lookup_id"]
        self.client.execute("BEGIN")
        self.client.execute(f"UPDATE default SET score = 77.0 WHERE _id = {point_lookup_id}")
        self.client.execute("COMMIT")

    def bench_txn_insert_read_own_commit(self):
        prefix = self._next_txn_prefix()
        values = self._txn_rows_sql(prefix, 1)[0]
        self.client.execute("BEGIN")
        self.client.execute(f"INSERT INTO default (name, age, score, city, category) VALUES {values}")
        result = self.client.execute(
            f"SELECT * FROM default WHERE name = '{prefix}_0'",
            show_internal_id=True,
        ).to_dict()
        self.client.execute("COMMIT")
        self._next_id += 1
        return result

    def setup_txn_backlog_1500(self):
        if self._txn_backlog_ready:
            return
        for _ in range(TXN_BACKLOG_ROWS):
            values = self._txn_rows_sql(self._next_txn_prefix(), 1)[0]
            self.client.execute("BEGIN")
            self.client.execute(f"INSERT INTO default (name, age, score, city, category) VALUES {values}")
            self.client.execute("COMMIT")
            self._next_id += 1
        self._txn_backlog_ready = True

    def bench_txn_backlog_string_miss_commit(self):
        self.client.execute("BEGIN")
        result = self.client.execute(
            f"SELECT * FROM default WHERE name = '{TXN_BACKLOG_MISSING_NAME}'",
            show_internal_id=True,
        ).to_dict()
        self.client.execute("COMMIT")
        return result

    def bench_txn_backlog_count_commit(self):
        self.client.execute("BEGIN")
        result = self.client.execute("SELECT COUNT(*) FROM default").scalar()
        self.client.execute("COMMIT")
        return result

    def bench_txn_backlog_insert_read_own_by_name_commit(self):
        prefix = self._next_txn_prefix()
        values = self._txn_rows_sql(prefix, 1)[0]
        self.client.execute("BEGIN")
        self.client.execute(f"INSERT INTO default (name, age, score, city, category) VALUES {values}")
        result = self.client.execute(
            f"SELECT * FROM default WHERE name = '{prefix}_0'",
            show_internal_id=True,
        ).to_dict()
        self.client.execute("COMMIT")
        self._next_id += 1
        return result

    def bench_insert_1k(self):
        data_1k = {
            "name": [f"new_{i}" for i in range(1000)],
            "age": [25] * 1000,
            "score": [50.0] * 1000,
            "city": ["Beijing"] * 1000,
            "category": ["Books"] * 1000,
        }
        self.client.store(data_1k)
        self._next_id += 1000

    def bench_full_scan_pandas(self):
        return self._query_pandas("SELECT * FROM default")

    def bench_group_by_2cols(self):
        return self._query_all(
            "SELECT city, category, COUNT(*), AVG(score) FROM default GROUP BY city, category"
        )

    def bench_filter_like(self):
        return self._query_all(
            "SELECT * FROM default WHERE name LIKE 'user_1%'"
        )

    def bench_filter_multi_cond(self):
        return self._query_all(
            "SELECT * FROM default WHERE age > 30 AND score > 50.0"
        )

    def bench_order_by_multi(self):
        return self._query_all(
            "SELECT * FROM default ORDER BY city ASC, score DESC LIMIT 100"
        )

    def bench_count_distinct(self):
        return self._scalar(
            "SELECT COUNT(DISTINCT city) FROM default"
        )

    def bench_count_distinct_category(self):
        return self._scalar(
            "SELECT COUNT(DISTINCT category) FROM default"
        )

    def bench_filter_in(self):
        return self._query_all(
            "SELECT * FROM default WHERE city IN ('Beijing', 'Shanghai', 'Guangzhou')"
        )

    def bench_filter_numeric_in(self):
        return self._query_all(
            "SELECT * FROM default WHERE age IN (20, 25, 30, 35, 40, 45, 50, 55, 60)"
        )

    def bench_filter_or_cross_col(self):
        return self._query_all(
            "SELECT * FROM default WHERE age = 25 OR city = 'Beijing'"
        )

    def bench_filter_numeric_or(self):
        return self._query_all(
            "SELECT * FROM default WHERE age = 20 OR age = 30 OR age = 40 OR age = 50"
        )

    def bench_update_1k(self):
        return self.client.execute(
            "UPDATE default SET score = 50.0 WHERE age = 25"
        )

    def bench_delete_1k(self):
        data = {
            "name": [f"del_{i}" for i in range(1000)],
            "age": [99] * 1000,
            "score": [99.0] * 1000,
            "city": ["Beijing"] * 1000,
            "category": ["Books"] * 1000,
        }
        self.client.store(data)
        self._next_id += 1000
        self.client.execute("DELETE FROM default WHERE age = 99")

    def bench_delete_1k_setup(self):
        data = {
            "name": [f"del_{i}" for i in range(1000)],
            "age": [99] * 1000,
            "score": [99.0] * 1000,
            "city": ["Beijing"] * 1000,
            "category": ["Books"] * 1000,
        }
        self.client.store(data)
        self._next_id += 1000

    def bench_delete_1k_only(self):
        self.client.execute("DELETE FROM default WHERE age = 99")

    def bench_window_row_number(self):
        return self._query_all(
            "SELECT name, city, score, "
            "ROW_NUMBER() OVER (PARTITION BY city ORDER BY score DESC) as rn "
            "FROM default LIMIT 1000"
        )

    def bench_fts_build(self):
        try:
            # Close + reopen to clear the executor STORAGE_CACHE before backfill,
            # ensuring CREATE FTS INDEX reads fresh row data from disk.
            self.client.close()
            self.client = ApexClient(self.db_dir)
            self.client.use_table('default')
            self.client.execute(
                "CREATE FTS INDEX ON default (name, city, category)"
            )
            self.client._fts_tables['default'] = {
                'enabled': True,
                'index_fields': ['name', 'city', 'category'],
                'config': {'lazy_load': False, 'cache_size': 10000},
            }
            self._fts_ready = True
        except Exception:
            self._fts_ready = False

    def bench_fts_search(self):
        if not getattr(self, '_fts_ready', False):
            return None
        return self.client.search_text('Electronics').tolist()

    def bench_copy_to_csv(self):
        path = os.path.join(self.db_dir, "bench_export.csv")
        try:
            os.remove(path)
        except FileNotFoundError:
            pass
        return self.client.execute(f"COPY default TO '{path}'").scalar()

    def bench_copy_to_json(self):
        path = os.path.join(self.db_dir, "bench_export.jsonl")
        try:
            os.remove(path)
        except FileNotFoundError:
            pass
        return self.client.execute(f"COPY default TO '{path}'").scalar()

    def bench_csv_read_count(self):
        return self._scalar(f"SELECT COUNT(*) FROM read_csv('{self.csv_path}')")

    def bench_csv_read_filter_group(self):
        return self._query_all(
            f"SELECT city, COUNT(*) FROM read_csv('{self.csv_path}') WHERE age > 30 GROUP BY city"
        )

    def bench_csv_read_limit_1k(self):
        return self._query_all(f"SELECT * FROM read_csv('{self.csv_path}') LIMIT 1000")

    def bench_json_read_count(self):
        return self._scalar(f"SELECT COUNT(*) FROM read_json('{self.json_path}')")

    def bench_temp_csv_create_query(self):
        if self._temp_csv_name is None:
            self._temp_csv_name = f"bench_csv_temp_{uuid.uuid4().hex[:8]}"
            self.client.register_temp_table(self._temp_csv_name, self.csv_path)
        return self._scalar(f"SELECT AVG(score) FROM {self._temp_csv_name} WHERE age > 30")

    def bench_csv_read_order_limit(self):
        return self._query_all(
            f"SELECT * FROM read_csv('{self.csv_path}') ORDER BY score DESC LIMIT 100"
        )

    def bench_json_read_filter(self):
        return self._scalar(
            f"SELECT COUNT(*) FROM read_json('{self.json_path}') WHERE age > 30"
        )

    def bench_json_read_order_limit(self):
        return self._query_all(
            f"SELECT * FROM read_json('{self.json_path}') ORDER BY score DESC LIMIT 100"
        )

    def bench_json_read_group_category(self):
        return self._query_all(
            f"SELECT category, COUNT(*) FROM read_json('{self.json_path}') GROUP BY category"
        )

    def close(self):
        if self.client:
            self.client.close()


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

# (display_name, method_name, is_write, is_cold, is_warm_nogc, setup_method)
# is_cold=True      -> cold_start_setup() per iter (reopen connection/client), no gc
# is_warm_nogc=True -> warm cached backend, no gc
# setup_method      -> if not None, call bench.{setup_method}() before each timed iter
BENCHMARKS = [
    ("Bulk Insert (N rows; default fair)", "bench_insert",         True,  False, False, None),
    ("COUNT(*)",                         "bench_count",            False, False, False, None),
    ("SELECT * LIMIT 100 (cold reopen)", "bench_select_limit",     False, True,  False, None),
    ("SELECT * LIMIT 100 (warm cache)",  "bench_select_limit",     False, False, True,  None),
    ("SELECT * LIMIT 10K (cold reopen)", "bench_select_limit_10k", False, True,  False, None),
    ("SELECT * LIMIT 10K (warm cache)",  "bench_select_limit_10k", False, False, True,  None),
    ("Projection full scan (3 cols)",    "bench_projected_full_scan", False, False, False, None),
    ("Filtered LIMIT 100 (age>30)",      "bench_filtered_limit_100", False, False, True,  None),
    ("LIMIT 100 OFFSET 10K",             "bench_limit_offset_100", False, False, True,  None),
    ("Filter (name = 'user_5000')",      "bench_filter_string",    False, False, False, None),
    ("Filter (age BETWEEN 25 AND 35)",   "bench_filter_range",     False, False, False, None),
    ("GROUP BY city (10 groups)",        "bench_group_by",         False, False, False, None),
    ("GROUP BY category (10 groups)",    "bench_group_by_category", False, False, False, None),
    ("GROUP BY city ORDER BY count",     "bench_group_by_order_count", False, False, False, None),
    ("GROUP BY category ORDER BY count", "bench_group_by_category_order_count", False, False, False, None),
    ("GROUP BY + HAVING",                "bench_group_by_having",  False, False, False, None),
    ("GROUP BY category + HAVING",       "bench_group_by_category_having", False, False, False, None),
    ("Persistent VIEW select",           "bench_view_select",      False, False, False, "setup_view_bench"),
    ("ORDER BY score LIMIT 100",         "bench_order_limit",      False, False, False, None),
    ("ORDER BY score ASC LIMIT 100",     "bench_order_limit_asc",  False, False, False, None),
    ("Aggregation (5 funcs)",            "bench_aggregation",      False, False, False, None),
    ("Filtered aggregation (category)",  "bench_filtered_aggregation", False, False, False, None),
    ("Filtered aggregation (city)",      "bench_filtered_aggregation_city", False, False, False, None),
    ("COUNT WHERE category",             "bench_count_where_category", False, False, False, None),
    ("Complex (Filter+Group+Order)",     "bench_complex",          False, False, False, None),
    ("Point Lookup (SQL by ID)",         "bench_point_lookup",     False, False, False, None),
    ("Retrieve Many (SQL, 100 IDs)",     "bench_retrieve_many",    False, False, False, None),
    # --- New cases ---
    ("SELECT * -> pandas (full scan)",   "bench_full_scan_pandas", False, False, False, None),
    ("GROUP BY city,category (100 grp)","bench_group_by_2cols",   False, False, False, None),
    ("LIKE filter (name LIKE user_1%)",  "bench_filter_like",      False, False, False, None),
    ("Multi-cond (age>30 AND score>50)", "bench_filter_multi_cond",False, False, False, None),
    ("ORDER BY city,score DESC LIMIT100","bench_order_by_multi",   False, False, False, None),
    ("COUNT(DISTINCT city)",             "bench_count_distinct",   False, False, False, None),
    ("COUNT(DISTINCT category)",         "bench_count_distinct_category", False, False, False, None),
    ("IN filter (city IN 3 cities)",     "bench_filter_in",        False, False, False, None),
    ("Numeric IN (age IN 9 values)",      "bench_filter_numeric_in",False, False, False, None),
    ("OR cross-col (age=25 OR city=BJ)",  "bench_filter_or_cross_col",False,False,False, None),
    ("Numeric OR (age=20|30|40|50)",      "bench_filter_numeric_or",False, False, False, None),
    # --- Window ---
    ("Window ROW_NUMBER PARTITION BY city",  "bench_window_row_number", False, False, False, None),
    # --- File reading / temp table benchmarks ---
    ("CSV Read + COUNT(*)",               "bench_csv_read_count",        False, False, False, None),
    ("CSV Read + Filter + GROUP BY",      "bench_csv_read_filter_group", False, False, False, None),
    ("CSV Read + Full Scan LIMIT 1000",   "bench_csv_read_limit_1k",     False, False, False, None),
    ("JSON Read + COUNT(*)",              "bench_json_read_count",       False, False, False, None),
    ("JSON Read + Filter",                "bench_json_read_filter",      False, False, False, None),
    ("JSON Read + GROUP BY category",     "bench_json_read_group_category", False, False, False, None),
    ("Temp Table (CSV) Query (filter+agg)","bench_temp_csv_create_query", False, False, True,  None),
    ("JSON Read + ORDER BY LIMIT 100",    "bench_json_read_order_limit", False, False, False, None),
    ("CSV Read + ORDER BY LIMIT 100",     "bench_csv_read_order_limit",  False, False, False, None),
    # --- OLTP read microbenchmarks run after analytical/file scans but before
    # mutation-heavy DML so latency is measured on a clean loaded table.
    ("COUNT(*) (direct API)",            "bench_oltp_count_rows",  False, False, True,  None),
    ("Point lookup (projected SQL)",     "bench_oltp_projected_point_lookup", False, False, True, None),
    ("Point lookup (direct full row)",   "bench_oltp_direct_point_lookup", False, False, True, None),
    ("Missing ID lookup",                "bench_oltp_missing_point_lookup", False, False, True, None),
    ("Retrieve 10 IDs (projected SQL)",  "bench_oltp_projected_retrieve_10", False, False, True, None),
    ("Retrieve 100 IDs (projected SQL)", "bench_oltp_projected_retrieve_100", False, False, True, None),
    ("SELECT 3 cols LIMIT 100",          "bench_oltp_projected_limit_100", False, False, True, None),
    ("String equality (projected)",      "bench_oltp_projected_string_eq", False, False, True, None),
    ("City filter LIMIT 100",            "bench_oltp_city_limit_10", False, False, True, None),
    # --- Bulk DML and FTS build run last so mutation-heavy paths do not
    # perturb read-only OLAP/OLTP latency metrics.
    ("Insert 1K rows (default fair)",    "bench_insert_1k",        False, False, False, None),
    ("UPDATE rows (age=25; idempotent)", "bench_update_1k",        False, False, False, None),
    ("Store+DELETE 1K (combined)",       "bench_delete_1k",        False, False, False, None),
    ("DELETE 1K (pure delete; setup rows)", "bench_delete_1k_only", False, False, False, "bench_delete_1k_setup"),
    ("Insert 1 row (default fair)",      "bench_oltp_insert_one", False, False, True, None),
    ("Insert+Read own row",              "bench_oltp_insert_read_own_row", False, False, True, None),
    ("Insert+COUNT visible",             "bench_oltp_insert_count_visible", False, False, True, None),
    ("UPDATE by ID",                     "bench_oltp_update_by_id", False, False, True, None),
    ("UPDATE missing ID",                "bench_oltp_update_missing_id", False, False, True, None),
    ("UPDATE+Read by ID",                "bench_oltp_update_read_by_id", False, False, True, None),
    ("Replace row by ID",                "bench_oltp_replace_by_id", False, False, True, None),
    ("Insert+DELETE by ID",              "bench_oltp_insert_delete_by_id", False, False, True, None),
    ("DELETE missing ID",                "bench_oltp_delete_missing_id", False, False, True, None),
    ("FTS Index Build (name,city,category)", "bench_fts_build",         True,  False, False, None),
    ("FTS Search ('Electronics')",           "bench_fts_search",        False, False, False, None),
]

OLAP_BENCHMARK_NAMES = [
    "COUNT(*)",
    "SELECT * LIMIT 100 (cold reopen)",
    "SELECT * LIMIT 100 (warm cache)",
    "SELECT * LIMIT 10K (cold reopen)",
    "SELECT * LIMIT 10K (warm cache)",
    "Projection full scan (3 cols)",
    "Filtered LIMIT 100 (age>30)",
    "LIMIT 100 OFFSET 10K",
    "Filter (name = 'user_5000')",
    "Filter (age BETWEEN 25 AND 35)",
    "GROUP BY city (10 groups)",
    "GROUP BY category (10 groups)",
    "GROUP BY city ORDER BY count",
    "GROUP BY category ORDER BY count",
    "GROUP BY + HAVING",
    "GROUP BY category + HAVING",
    "Persistent VIEW select",
    "ORDER BY score LIMIT 100",
    "ORDER BY score ASC LIMIT 100",
    "Aggregation (5 funcs)",
    "Filtered aggregation (category)",
    "Filtered aggregation (city)",
    "COUNT WHERE category",
    "Complex (Filter+Group+Order)",
    "SELECT * -> pandas (full scan)",
    "GROUP BY city,category (100 grp)",
    "LIKE filter (name LIKE user_1%)",
    "Multi-cond (age>30 AND score>50)",
    "ORDER BY city,score DESC LIMIT100",
    "COUNT(DISTINCT city)",
    "COUNT(DISTINCT category)",
    "IN filter (city IN 3 cities)",
    "Numeric IN (age IN 9 values)",
    "OR cross-col (age=25 OR city=BJ)",
    "Numeric OR (age=20|30|40|50)",
    "Window ROW_NUMBER PARTITION BY city",
    "CSV Read + COUNT(*)",
    "CSV Read + Filter + GROUP BY",
    "CSV Read + Full Scan LIMIT 1000",
    "JSON Read + COUNT(*)",
    "JSON Read + Filter",
    "JSON Read + GROUP BY category",
    "Temp Table (CSV) Query (filter+agg)",
    "JSON Read + ORDER BY LIMIT 100",
    "CSV Read + ORDER BY LIMIT 100",
]

# The public scoreboard now includes every cross-engine OLAP metric that this
# harness can run with comparable setup and materialized result semantics.
PUBLIC_OLAP_BENCHMARK_NAMES = list(OLAP_BENCHMARK_NAMES)

OLTP_FAIR_BENCHMARK_NAMES = [
    "Bulk Insert (N rows; default fair)",
    "Point Lookup (SQL by ID)",
    "Retrieve Many (SQL, 100 IDs)",
    "COUNT(*) (direct API)",
    "Point lookup (projected SQL)",
    "Point lookup (direct full row)",
    "Missing ID lookup",
    "Retrieve 10 IDs (projected SQL)",
    "Retrieve 100 IDs (projected SQL)",
    "SELECT 3 cols LIMIT 100",
    "String equality (projected)",
    "City filter LIMIT 100",
    "Insert 1 row (default fair)",
    "Insert+Read own row",
    "Insert+COUNT visible",
    "UPDATE by ID",
    "UPDATE missing ID",
    "UPDATE+Read by ID",
    "Replace row by ID",
    "Insert+DELETE by ID",
    "DELETE missing ID",
    "Insert 1K rows (default fair)",
    "UPDATE rows (age=25; idempotent)",
    "Store+DELETE 1K (combined)",
    "DELETE 1K (pure delete; setup rows)",
    "FTS Index Build (name,city,category)",
    "FTS Search ('Electronics')",
]

FILE_BACKED_METHODS = {
    "bench_csv_read_count",
    "bench_csv_read_filter_group",
    "bench_csv_read_limit_1k",
    "bench_json_read_count",
    "bench_json_read_filter",
    "bench_json_read_group_category",
    "bench_temp_csv_create_query",
    "bench_json_read_order_limit",
    "bench_csv_read_order_limit",
}

FAIR_WORKLOAD_GROUPS = [
    (
        "Load & Index",
        [
            "Bulk Insert (N rows; default fair)",
            "FTS Index Build (name,city,category)",
        ],
    ),
    (
        "Point & Limited Reads",
        [
            "COUNT(*)",
            "SELECT * LIMIT 100 (cold reopen)",
            "SELECT * LIMIT 100 (warm cache)",
            "SELECT * LIMIT 10K (cold reopen)",
            "SELECT * LIMIT 10K (warm cache)",
            "Filtered LIMIT 100 (age>30)",
            "LIMIT 100 OFFSET 10K",
            "Point Lookup (SQL by ID)",
            "Retrieve Many (SQL, 100 IDs)",
            "COUNT(*) (direct API)",
            "Point lookup (projected SQL)",
            "Point lookup (direct full row)",
            "Missing ID lookup",
            "Retrieve 10 IDs (projected SQL)",
            "Retrieve 100 IDs (projected SQL)",
            "SELECT 3 cols LIMIT 100",
            "City filter LIMIT 100",
        ],
    ),
    (
        "Filtering",
        [
            "Filter (name = 'user_5000')",
            "Filter (age BETWEEN 25 AND 35)",
            "LIKE filter (name LIKE user_1%)",
            "Multi-cond (age>30 AND score>50)",
            "IN filter (city IN 3 cities)",
            "Numeric IN (age IN 9 values)",
            "OR cross-col (age=25 OR city=BJ)",
            "Numeric OR (age=20|30|40|50)",
            "String equality (projected)",
            "COUNT WHERE category",
        ],
    ),
    (
        "Aggregation",
        [
            "GROUP BY city (10 groups)",
            "GROUP BY category (10 groups)",
            "GROUP BY city ORDER BY count",
            "GROUP BY category ORDER BY count",
            "GROUP BY + HAVING",
            "GROUP BY category + HAVING",
            "Aggregation (5 funcs)",
            "Filtered aggregation (category)",
            "Filtered aggregation (city)",
            "Complex (Filter+Group+Order)",
            "GROUP BY city,category (100 grp)",
            "COUNT(DISTINCT city)",
            "COUNT(DISTINCT category)",
        ],
    ),
    (
        "Ordering, Window, View",
        [
            "Persistent VIEW select",
            "ORDER BY score LIMIT 100",
            "ORDER BY score ASC LIMIT 100",
            "ORDER BY city,score DESC LIMIT100",
            "Window ROW_NUMBER PARTITION BY city",
        ],
    ),
    (
        "Full Materialization",
        [
            "Projection full scan (3 cols)",
            "SELECT * -> pandas (full scan)",
        ],
    ),
    (
        "File Scan",
        [
            "CSV Read + COUNT(*)",
            "CSV Read + Filter + GROUP BY",
            "CSV Read + Full Scan LIMIT 1000",
            "JSON Read + COUNT(*)",
            "JSON Read + Filter",
            "JSON Read + GROUP BY category",
            "Temp Table (CSV) Query (filter+agg)",
            "JSON Read + ORDER BY LIMIT 100",
            "CSV Read + ORDER BY LIMIT 100",
        ],
    ),
    (
        "DML",
        [
            "Insert 1K rows (default fair)",
            "Insert 1 row (default fair)",
            "Insert+Read own row",
            "Insert+COUNT visible",
            "UPDATE by ID",
            "UPDATE missing ID",
            "UPDATE+Read by ID",
            "Replace row by ID",
            "Insert+DELETE by ID",
            "DELETE missing ID",
            "UPDATE rows (age=25; idempotent)",
            "Store+DELETE 1K (combined)",
            "DELETE 1K (pure delete; setup rows)",
        ],
    ),
    (
        "Search",
        [
            "FTS Search ('Electronics')",
        ],
    ),
]

_BENCHMARK_BY_NAME = {spec[0]: spec for spec in BENCHMARKS}
OLAP_BENCHMARK_SECTIONS = [
    (
        "OLAP Fair Metrics",
        "Analytical scans, filters, grouping, ordering, windows, and full-result materialization.",
        [_BENCHMARK_BY_NAME[name] for name in OLAP_BENCHMARK_NAMES],
    ),
]

OLTP_BENCHMARK_SECTIONS = [
    (
        "OLTP Fair Metrics",
        "Load, indexing/search, point reads, small writes, updates, and deletes on the loaded table.",
        [_BENCHMARK_BY_NAME[name] for name in OLTP_FAIR_BENCHMARK_NAMES],
    ),
]


def olap_benchmark_names_for_profile(profile: str):
    if normalize_profile(profile) == PROFILE_PUBLIC:
        return PUBLIC_OLAP_BENCHMARK_NAMES
    return OLAP_BENCHMARK_NAMES


def benchmark_sections_for_profile(profile: str):
    olap_names = olap_benchmark_names_for_profile(profile)
    olap_sections = [
        (
            "OLAP Fair Metrics",
            "Analytical scans, filters, grouping, ordering, windows, and full-result materialization.",
            [_BENCHMARK_BY_NAME[name] for name in olap_names],
        ),
    ]
    oltp_sections = list(OLTP_BENCHMARK_SECTIONS)
    return olap_sections, oltp_sections


def benchmark_specs_for_profile(profile: str):
    olap_sections, oltp_sections = benchmark_sections_for_profile(profile)
    selected = {spec[0] for _, _, specs in (olap_sections + oltp_sections) for spec in specs}
    return [spec for spec in BENCHMARKS if spec[0] in selected]


def selected_benchmarks_need_files(benchmark_specs):
    return any(spec[1] in FILE_BACKED_METHODS for spec in benchmark_specs)


def profile_runs_extended_sections(profile: str) -> bool:
    return normalize_profile(profile) == PROFILE_EXTENDED


OLTP_DEFAULT_BENCHMARKS = [
    ("COUNT(*) (direct API)", "bench_oltp_count_rows"),
    ("Point lookup (projected SQL)", "bench_oltp_projected_point_lookup"),
    ("Point lookup (direct full row)", "bench_oltp_direct_point_lookup"),
    ("Missing ID lookup", "bench_oltp_missing_point_lookup"),
    ("Retrieve 10 IDs (projected SQL)", "bench_oltp_projected_retrieve_10"),
    ("Retrieve 100 IDs (projected SQL)", "bench_oltp_projected_retrieve_100"),
    ("SELECT 3 cols LIMIT 100", "bench_oltp_projected_limit_100"),
    ("String equality (projected)", "bench_oltp_projected_string_eq"),
    ("City filter LIMIT 100", "bench_oltp_city_limit_10"),
    ("Insert 1 row (default fair)", "bench_oltp_insert_one"),
    ("Insert+Read own row", "bench_oltp_insert_read_own_row"),
    ("Insert+COUNT visible", "bench_oltp_insert_count_visible"),
    ("UPDATE by ID", "bench_oltp_update_by_id"),
    ("UPDATE missing ID", "bench_oltp_update_missing_id"),
    ("UPDATE+Read by ID", "bench_oltp_update_read_by_id"),
    ("Replace row by ID", "bench_oltp_replace_by_id"),
    ("Insert+DELETE by ID", "bench_oltp_insert_delete_by_id"),
    ("DELETE missing ID", "bench_oltp_delete_missing_id"),
]

MICRO_MEDIAN_BENCHMARK_METHODS = {
    method_name for _, method_name in OLTP_DEFAULT_BENCHMARKS
}
MICRO_MEDIAN_BENCHMARK_METHODS.add("bench_temp_csv_create_query")

OLTP_APEX_DIAGNOSTIC_BENCHMARKS = [
    ("Insert 10 rows (small-batch API diagnostic)", "bench_oltp_insert_10_rows"),
    ("COPY TO CSV (Apex-only export)", "bench_copy_to_csv"),
    ("COPY TO JSONL (Apex-only export)", "bench_copy_to_json"),
]

OLTP_DURABLE_WRITE_BENCHMARKS = [
    ("Insert 1 row (durable fair)", "bench_oltp_insert_one_durable"),
    ("UPDATE by ID (durable fair)", "bench_oltp_update_by_id"),
]

TXN_FAIR_BENCHMARKS = [
    ("TXN empty (BEGIN+COMMIT; durable sync)", "bench_txn_empty_commit"),
    ("TXN read COUNT(*) (COMMIT; durable sync)", "bench_txn_read_count_commit"),
    (
        "TXN backlog string miss (COMMIT; 1500 preseed; durable sync)",
        "bench_txn_backlog_string_miss_commit",
        "setup_txn_backlog_1500",
    ),
    (
        "TXN backlog COUNT(*) (COMMIT; 1500 preseed; durable sync)",
        "bench_txn_backlog_count_commit",
        "setup_txn_backlog_1500",
    ),
    (
        "TXN backlog INSERT+read-own-name (COMMIT; 1500 preseed; durable sync)",
        "bench_txn_backlog_insert_read_own_by_name_commit",
        "setup_txn_backlog_1500",
    ),
]

TXN_APEX_DIAGNOSTIC_BENCHMARKS = [
    ("TXN empty (BEGIN+ROLLBACK)", "bench_txn_empty_rollback"),
    ("TXN INSERT 1 (COMMIT; .delta diagnostic)", "bench_txn_insert_one_commit"),
    ("TXN INSERT 10 stmts (COMMIT; .delta diagnostic)", "bench_txn_insert_10_commit"),
    ("TXN multi-row INSERT 10 (COMMIT; .delta diagnostic)", "bench_txn_multi_insert_10_commit"),
    ("TXN INSERT 100 stmts (COMMIT; .delta diagnostic)", "bench_txn_insert_100_commit"),
    ("TXN multi-row INSERT 100 (COMMIT; .delta diagnostic)", "bench_txn_multi_insert_100_commit"),
    ("TXN INSERT 10 (ROLLBACK; diagnostic)", "bench_txn_insert_10_rollback"),
    ("TXN UPDATE by ID (COMMIT; .delta diagnostic)", "bench_txn_update_by_id_commit"),
    ("TXN INSERT+read-own-row (COMMIT; .delta diagnostic)", "bench_txn_insert_read_own_commit"),
]


def result_shape(value):
    """Return a compact shape string for materialized benchmark results."""
    if value is None:
        return "0x0"
    if hasattr(value, "num_rows") and hasattr(value, "num_columns"):
        return f"{value.num_rows}x{value.num_columns}"
    if hasattr(value, "shape"):
        shape = tuple(value.shape)
        if len(shape) >= 2:
            return f"{shape[0]}x{shape[1]}"
        if len(shape) == 1:
            return f"{shape[0]}x1"
    if isinstance(value, list):
        return f"{len(value)}x{len(value[0]) if value else 0}"
    return type(value).__name__


def run_bench_with_result(fn, warmup=2, iterations=5):
    """Run fn() and return (average_ms, last_result)."""
    last = None
    for _ in range(warmup):
        last = fn()
    times = []
    for _ in range(iterations):
        with timer() as t:
            last = fn()
        times.append(t["elapsed_ms"])
    return sum(times) / len(times), last


def materialization_speedup_label(dict_ms, arrow_ms):
    if dict_ms is None or arrow_ms is None or arrow_ms <= 0:
        return "N/A"
    ratio = dict_ms / arrow_ms
    if ratio >= 1:
        return f"{ratio:.1f}x faster"
    return f"{1 / ratio:.1f}x slower"


def apex_ratio_label(apex_ms, others):
    if apex_ms is None or not others:
        return None
    best_other = min(others)
    ratio = apex_ms / best_other if best_other > 0 else float("inf")
    if abs(ratio - 1.0) < 1e-9:
        return "~1.0x (tied)"
    if ratio < 1:
        return f"{ratio:.2f}x (faster)"
    return f"{ratio:.1f}x (slower)"


def summarize_apex_section(benchmark_specs, results):
    wins = 0
    ties = 0
    total = 0
    for bench_name, _, _, _, _, _ in benchmark_specs:
        vals = results.get(bench_name, {})
        apex_ms = vals.get("ApexBase")
        if apex_ms is None:
            continue
        others = [v for k, v in vals.items() if k != "ApexBase" and v is not None]
        if not others:
            continue
        total += 1
        best_other = min(others)
        ratio = apex_ms / best_other if best_other > 0 else float("inf")
        if abs(ratio - 1.0) < 1e-9:
            ties += 1
        elif ratio < 1:
            wins += 1
    return {
        "wins": wins,
        "ties": ties,
        "slower": total - wins - ties,
        "total": total,
    }


def geometric_mean_ms(values):
    positives = [v for v in values if v is not None and v > 0]
    if not positives:
        return None
    return math.exp(sum(math.log(v) for v in positives) / len(positives))


def summarize_workload_group(group_name, metric_names, results, eng_names):
    rows = []
    for metric_name in metric_names:
        metric_values = results.get(metric_name, {})
        apex_ms = metric_values.get("ApexBase")
        other_values = [
            metric_values.get(eng_name)
            for eng_name in eng_names
            if eng_name != "ApexBase"
        ]
        if apex_ms is not None and any(value is not None for value in other_values):
            rows.append((metric_name, {
                eng_name: metric_values.get(eng_name)
                for eng_name in eng_names
            }))

    totals = {}
    geomeans = {}
    for eng_name in eng_names:
        values = [values.get(eng_name) for _, values in rows]
        available = [value for value in values if value is not None]
        totals[eng_name] = sum(available) if available and len(available) == len(rows) else None
        geomeans[eng_name] = geometric_mean_ms(values)

    apex_total = totals.get("ApexBase")
    other_totals = [v for k, v in totals.items() if k != "ApexBase" and v is not None]
    ratio_label = apex_ratio_label(apex_total, other_totals) if apex_total is not None else None

    wins = ties = 0
    for _, values in rows:
        apex_ms = values.get("ApexBase")
        others = [v for k, v in values.items() if k != "ApexBase" and v is not None]
        if apex_ms is None or not others:
            continue
        best_other = min(others)
        ratio = apex_ms / best_other if best_other > 0 else float("inf")
        if abs(ratio - 1.0) < 1e-9:
            ties += 1
        elif ratio < 1:
            wins += 1

    return {
        "workload": group_name,
        "metric_count": len(rows),
        "metrics": [metric_name for metric_name, _ in rows],
        "total_ms": totals,
        "geomean_ms": geomeans,
        "apex_vs_best_total": ratio_label,
        "apex_wins": wins,
        "apex_ties": ties,
        "apex_slower": len(rows) - wins - ties,
    }


def build_fair_workload_scoreboard(results, eng_names, selected_benchmarks):
    selected_names = {spec[0] for spec in selected_benchmarks}
    grouped_names = set()
    scoreboard = []
    for group_name, metric_names in FAIR_WORKLOAD_GROUPS:
        names = [name for name in metric_names if name in selected_names]
        if not names:
            continue
        grouped_names.update(names)
        summary = summarize_workload_group(group_name, names, results, eng_names)
        if summary["metric_count"] > 0:
            scoreboard.append(summary)

    uncategorized = [
        spec[0] for spec in selected_benchmarks
        if spec[0] not in grouped_names
    ]
    if uncategorized:
        summary = summarize_workload_group("Other", uncategorized, results, eng_names)
        if summary["metric_count"] > 0:
            scoreboard.append(summary)
    return scoreboard


def print_fair_workload_scoreboard(results, eng_names, selected_benchmarks, col_width):
    scoreboard = build_fair_workload_scoreboard(results, eng_names, selected_benchmarks)
    if not scoreboard:
        return []

    print("\n--- Fair Workload Scoreboard (Aggregated) ---")
    print("  Lower total is better. A row can compare ApexBase with any available peer; missing peers show N/A.")
    name_width = max(24, *(len(row["workload"]) for row in scoreboard))
    header = f"{'Workload':<{name_width}} | {'Metrics':>7}"
    for eng_name in eng_names:
        header += f" | {eng_name + ' total':>{col_width}}"
    if "ApexBase" in eng_names and len(eng_names) >= 2:
        header += f" | {'Apex/Best':>{col_width}} | {'Apex wins':>{10}}"
    print(header)
    print("-" * len(header))

    json_rows = []
    for summary in scoreboard:
        row = f"{summary['workload']:<{name_width}} | {summary['metric_count']:>7}"
        for eng_name in eng_names:
            total_ms = summary["total_ms"].get(eng_name)
            row += f" | {fmt_ms(total_ms) if total_ms is not None else 'N/A':>{col_width}}"
        if "ApexBase" in eng_names and len(eng_names) >= 2:
            ratio = summary.get("apex_vs_best_total") or "N/A"
            row += f" | {ratio:>{col_width}} | {summary['apex_wins']:>3}/{summary['metric_count']:<6}"
        print(row)
        json_rows.append({
            "workload": summary["workload"],
            "metric_count": summary["metric_count"],
            "metrics": summary["metrics"],
            "total_ms": {
                k: round(v, 3) if v is not None else None
                for k, v in summary["total_ms"].items()
            },
            "geomean_ms": {
                k: round(v, 6) if v is not None else None
                for k, v in summary["geomean_ms"].items()
            },
            "apex_vs_best_total": summary["apex_vs_best_total"],
            "apex_wins": summary["apex_wins"],
            "apex_ties": summary["apex_ties"],
            "apex_slower": summary["apex_slower"],
        })
    return json_rows


def print_benchmark_section(title, description, benchmark_specs, results, eng_names, col_width):
    print(f"\n--- {title} ---")
    print(f"  {description}")
    name_width = max(42, *(len(spec[0]) for spec in benchmark_specs))
    header = f"{'Metric':<{name_width}}"
    for name in eng_names:
        header += f" | {name:>{col_width}}"
    if len(eng_names) >= 2:
        header += f" | {'Ratio (Apex/Best)':>{col_width}}"
    print(header)
    print("-" * len(header))

    json_rows = []
    for bench_name, method_name, is_insert, is_cold, is_warm_nogc, setup_method in benchmark_specs:
        row = f"{bench_name:<{name_width}}"
        values = {}
        for eng_name in eng_names:
            ms = results.get(bench_name, {}).get(eng_name)
            if ms is not None:
                row += f" | {fmt_ms(ms):>{col_width}}"
                values[eng_name] = ms
            else:
                row += f" | {'N/A':>{col_width}}"

        if len(eng_names) >= 2 and "ApexBase" in values:
            others = [v for k, v in values.items() if k != "ApexBase"]
            label = apex_ratio_label(values["ApexBase"], others)
            if label:
                row += f" | {label:>{col_width}}"

        print(row)
        json_rows.append({
            "category": title,
            "query": bench_name,
            **{k: round(v, 3) for k, v in values.items()},
        })

    if "ApexBase" in eng_names:
        stats = summarize_apex_section(benchmark_specs, results)
        print(
            f"Section Summary: ApexBase wins {stats['wins']}/{stats['total']}, "
            f"ties {stats['ties']}/{stats['total']}, slower {stats['slower']}/{stats['total']}"
        )

    return json_rows


def module_metric_counts(profile: str = PROFILE_PUBLIC):
    olap_sections, oltp_sections = benchmark_sections_for_profile(profile)
    olap_count = sum(len(specs) for _, _, specs in olap_sections)
    oltp_count = sum(len(specs) for _, _, specs in oltp_sections)
    if profile_runs_extended_sections(profile):
        olap_count += len(apex_materialization_queries({"point_lookup_id": 1})) + 2
        oltp_count += (
            len(OLTP_APEX_DIAGNOSTIC_BENCHMARKS)
            + len(OLTP_DURABLE_WRITE_BENCHMARKS)
            + len(TXN_FAIR_BENCHMARKS)
            + len(TXN_APEX_DIAGNOSTIC_BENCHMARKS)
            + 2
        )
    vector_count = vector_metric_count(profile)
    return olap_count, oltp_count, vector_count


def print_module_header(title, metric_count):
    print("\n" + "=" * 80)
    print(f" {title} Module ({metric_count} named metrics)")
    print("=" * 80)


def reload_loaded_state(engines):
    """Recreate each engine on a fresh loaded table before a new microbench section."""
    ensure_optional_imports()
    for _, bench in engines:
        bench.setup()
        bench.bench_insert()
        if HAS_APEXBASE and isinstance(bench, ApexBaseBench):
            try:
                bench.client.flush()
            except Exception:
                pass


def wrap_durable_bench_fn(eng_name, bench, fn):
    """Apply comparable post-write persistence for commit-timed microbenchmarks."""
    if eng_name == "ApexBase":
        def durable_fn(fn=fn, bench=bench):
            result = fn()
            bench.client.flush()
            return result
        return durable_fn
    if eng_name == "SQLite":
        def durable_fn(fn=fn, bench=bench):
            result = fn()
            bench.conn.execute("PRAGMA wal_checkpoint(FULL)")
            return result
        return durable_fn
    if eng_name == "DuckDB":
        def durable_fn(fn=fn, bench=bench):
            result = fn()
            bench.conn.execute("CHECKPOINT")
            return result
        return durable_fn
    return fn


def apex_materialization_queries(shared_inputs):
    point_id = shared_inputs.get("point_lookup_id", 1)
    return [
        ("Point Lookup", f"SELECT * FROM default WHERE _id = {point_id}"),
        ("SELECT * LIMIT 10K", "SELECT * FROM default LIMIT 10000"),
        ("IN filter (city IN 3)", "SELECT * FROM default WHERE city IN ('Beijing', 'Shanghai', 'Guangzhou')"),
        ("Multi-cond filter", "SELECT * FROM default WHERE age > 30 AND score > 50.0"),
        ("GROUP BY city", "SELECT city, COUNT(*), AVG(score) FROM default GROUP BY city"),
        ("Full scan", "SELECT * FROM default"),
    ]


def run_apex_materialization_benchmarks(tmpdir, data, shared_inputs, warmup, iterations, low_memory=False):
    """Compare ApexBase result APIs without mixing them into cross-engine rankings."""
    ensure_optional_imports()
    if not HAS_APEXBASE:
        return []

    methods = [
        ("to_dict", lambda rv: rv.to_dict()),
        ("to_arrow", lambda rv: rv.to_arrow() if HAS_PYARROW else None),
        ("to_pandas", lambda rv: rv.to_pandas() if HAS_PANDAS else None),
    ]
    rows = []
    mat_tmpdir = tempfile.mkdtemp(prefix="apexbase_materialize_", dir=tmpdir)
    apex_bench = ApexBaseBench(mat_tmpdir, data, low_memory=low_memory)

    print("\n--- OLAP ApexBase Materialization APIs (Apex-only; not ranked) ---")
    try:
        apex_bench.setup()
        apex_bench.shared_inputs = shared_inputs
        apex_bench.bench_insert()

        print("  Uses a fresh ApexBase copy of the same generated data; previous DML benchmarks do not affect row counts.")
        print("  This isolates Python result conversion cost and is not compared against SQLite/DuckDB rows.")
        header = (
            f"  {'Metric':<24} | {'to_dict':>12} | {'to_arrow':>12} | "
            f"{'to_pandas':>12} | {'Arrow vs dict':>14} | {'Shape':>12}"
        )
        print(header)
        print("  " + "-" * (len(header) - 2))

        for label, sql in apex_materialization_queries(shared_inputs):
            method_ms = {}
            method_shapes = {}
            for method_name, materialize in methods:
                if method_name == "to_arrow" and not HAS_PYARROW:
                    method_ms[method_name] = None
                    continue
                if method_name == "to_pandas" and not HAS_PANDAS:
                    method_ms[method_name] = None
                    continue

                def fn(sql=sql, materialize=materialize):
                    rv = apex_bench.client.execute(sql, show_internal_id=True)
                    return materialize(rv)

                ms, last = run_bench_with_result(fn, warmup=warmup, iterations=iterations)
                method_ms[method_name] = ms
                method_shapes[method_name] = result_shape(last)

            shape = (
                method_shapes.get("to_arrow")
                or method_shapes.get("to_pandas")
                or method_shapes.get("to_dict")
                or "N/A"
            )
            speedup = materialization_speedup_label(method_ms.get("to_dict"), method_ms.get("to_arrow"))
            row = (
                f"  {label:<24} | "
                f"{fmt_ms(method_ms['to_dict']) if method_ms.get('to_dict') is not None else 'N/A':>12} | "
                f"{fmt_ms(method_ms['to_arrow']) if method_ms.get('to_arrow') is not None else 'N/A':>12} | "
                f"{fmt_ms(method_ms['to_pandas']) if method_ms.get('to_pandas') is not None else 'N/A':>12} | "
                f"{speedup:>14} | {shape:>12}"
            )
            print(row)
            rows.append({
                "query": label,
                "sql": sql,
                "shape": shape,
                "to_dict_ms": round(method_ms["to_dict"], 3) if method_ms.get("to_dict") is not None else None,
                "to_arrow_ms": round(method_ms["to_arrow"], 3) if method_ms.get("to_arrow") is not None else None,
                "to_pandas_ms": round(method_ms["to_pandas"], 3) if method_ms.get("to_pandas") is not None else None,
                "arrow_vs_dict": speedup,
            })
    finally:
        try:
            apex_bench.close()
        except Exception:
            pass
        try:
            shutil.rmtree(mat_tmpdir)
        except Exception:
            pass

    return rows


def run_oltp_benchmarks(engines, warmup, iterations):
    """Run short OLTP-style microbenchmarks on a fresh loaded copy of each engine."""
    ensure_optional_imports()
    if not engines:
        return []

    reload_loaded_state(engines)

    print("\n--- OLTP Default Fair Microbenchmarks ---")
    print("  Rehydrates a fresh loaded table for this section; metric labels include native/default visibility and setup options.")
    print("  Reports median hot-path latency to reduce scheduler noise in microsecond-scale timings.")

    for _, bench in engines:
        if isinstance(bench, ApexBaseBench) and getattr(bench, "_fts_ready", False):
            try:
                bench.client.disable_fts("default")
            except Exception:
                pass

    eng_names = [name for name, _ in engines]
    col_width = 16
    name_width = max(34, *(len(name) for name, _ in OLTP_DEFAULT_BENCHMARKS))
    header = f"  {'Metric':<{name_width}}"
    for name in eng_names:
        header += f" | {name:>{col_width}}"
    if len(eng_names) >= 2:
        header += f" | {'Ratio (Apex/Best)':>{col_width}}"
    print(header)
    print("  " + "-" * (len(header) - 2))

    rows = []
    for bench_name, method_name in OLTP_DEFAULT_BENCHMARKS:
        values = {}
        row = f"  {bench_name:<{name_width}}"
        for eng_name, bench in engines:
            fn = getattr(bench, method_name, None)
            if fn is None:
                row += f" | {'N/A':>{col_width}}"
                continue
            try:
                ms = run_bench_nogc_median(fn, warmup=warmup, iterations=iterations)
                values[eng_name] = ms
                row += f" | {fmt_ms(ms):>{col_width}}"
            except Exception:
                row += f" | {'N/A':>{col_width}}"

        if len(eng_names) >= 2 and "ApexBase" in values:
            others = {k: v for k, v in values.items() if k != "ApexBase"}
            if others:
                label = apex_ratio_label(values["ApexBase"], others.values())
                row += f" | {label:>{col_width}}"
        print(row)
        rows.append({
            "operation": bench_name,
            **{k: round(v, 3) for k, v in values.items()},
        })
    return rows


def run_oltp_durable_benchmarks(engines, warmup, iterations):
    """Run OLTP write microbenchmarks with explicit durable persistence per operation."""
    ensure_optional_imports()
    if not engines:
        return []

    reload_loaded_state(engines)

    print("\n--- OLTP Durable Fair Microbenchmarks ---")
    print("  Rehydrates a fresh loaded table, then forces comparable persistence per timed write.")
    print("  Reports median hot-path latency to reduce scheduler noise in microsecond-scale timings.")

    # Keep SQLite in durable mode only for this section.
    for eng_name, bench in engines:
        if eng_name == "SQLite":
            try:
                bench.conn.execute("PRAGMA synchronous=FULL")
            except Exception:
                pass

    eng_names = [name for name, _ in engines]
    col_width = 16
    name_width = max(34, *(len(name) for name, _ in OLTP_DURABLE_WRITE_BENCHMARKS))
    header = f"  {'Metric':<{name_width}}"
    for name in eng_names:
        header += f" | {name:>{col_width}}"
    if len(eng_names) >= 2:
        header += f" | {'Ratio (Apex/Best)':>{col_width}}"
    print(header)
    print("  " + "-" * (len(header) - 2))

    rows = []
    try:
        for bench_name, method_name in OLTP_DURABLE_WRITE_BENCHMARKS:
            values = {}
            row = f"  {bench_name:<{name_width}}"
            for eng_name, bench in engines:
                fn = getattr(bench, method_name, None)
                if fn is None and method_name == "bench_oltp_insert_one_durable":
                    fn = getattr(bench, "bench_oltp_insert_one", None)
                if fn is None:
                    row += f" | {'N/A':>{col_width}}"
                    continue

                try:
                    if eng_name == "ApexBase" and method_name == "bench_oltp_insert_one_durable":
                        durable_fn = fn
                    else:
                        durable_fn = wrap_durable_bench_fn(eng_name, bench, fn)
                    ms = run_bench_nogc_median(durable_fn, warmup=warmup, iterations=iterations)
                    values[eng_name] = ms
                    row += f" | {fmt_ms(ms):>{col_width}}"
                except Exception:
                    row += f" | {'N/A':>{col_width}}"

            if len(eng_names) >= 2 and "ApexBase" in values:
                others = {k: v for k, v in values.items() if k != "ApexBase"}
                if others:
                    label = apex_ratio_label(values["ApexBase"], others.values())
                    row += f" | {label:>{col_width}}"
            print(row)
            rows.append({
                "operation": bench_name,
                **{k: round(v, 3) for k, v in values.items()},
            })
    finally:
        for eng_name, bench in engines:
            if eng_name == "SQLite":
                try:
                    bench.conn.execute("PRAGMA synchronous=OFF")
                except Exception:
                    pass

    return rows


def run_txn_benchmarks(engines, warmup, iterations):
    """Run fair cross-engine transaction microbenchmarks with durable sync on COMMIT."""
    ensure_optional_imports()
    if not engines:
        return []

    reload_loaded_state(engines)

    print("\n--- OLTP Transaction Fair Microbenchmarks ---")
    print("  Rehydrates a fresh loaded table, then applies comparable durable sync after each committed transaction.")
    print("  Reports median hot-path latency to reduce scheduler noise in microsecond-scale timings.")

    for eng_name, bench in engines:
        if eng_name == "SQLite":
            try:
                bench.conn.execute("PRAGMA synchronous=FULL")
            except Exception:
                pass

    eng_names = [name for name, _ in engines]
    col_width = 16
    name_width = max(38, *(len(spec[0]) for spec in TXN_FAIR_BENCHMARKS))
    header = f"  {'Metric':<{name_width}}"
    for name in eng_names:
        header += f" | {name:>{col_width}}"
    if len(eng_names) >= 2:
        header += f" | {'Ratio (Apex/Best)':>{col_width}}"
    print(header)
    print("  " + "-" * (len(header) - 2))

    rows = []
    try:
        for spec in TXN_FAIR_BENCHMARKS:
            bench_name, method_name = spec[:2]
            setup_method = spec[2] if len(spec) > 2 else None
            values = {}
            row = f"  {bench_name:<{name_width}}"
            for eng_name, bench in engines:
                if setup_method is not None:
                    setup_fn = getattr(bench, setup_method, None)
                    if setup_fn is not None:
                        setup_fn()
                fn = getattr(bench, method_name, None)
                if fn is None:
                    row += f" | {'N/A':>{col_width}}"
                    continue
                try:
                    ms = run_bench_nogc_median(
                        wrap_durable_bench_fn(eng_name, bench, fn),
                        warmup=warmup,
                        iterations=iterations,
                    )
                    values[eng_name] = ms
                    row += f" | {fmt_ms(ms):>{col_width}}"
                except Exception:
                    row += f" | {'N/A':>{col_width}}"

            if len(eng_names) >= 2 and "ApexBase" in values:
                others = {k: v for k, v in values.items() if k != "ApexBase"}
                if others:
                    label = apex_ratio_label(values["ApexBase"], others.values())
                    row += f" | {label:>{col_width}}"
            print(row)
            rows.append({
                "operation": bench_name,
                **{k: round(v, 3) for k, v in values.items()},
            })
    finally:
        for eng_name, bench in engines:
            if eng_name == "SQLite":
                try:
                    bench.conn.execute("PRAGMA synchronous=OFF")
                except Exception:
                    pass
    return rows


def run_apex_oltp_diagnostics(tmpdir, data, warmup, iterations):
    """Show Apex-only tiny-write diagnostics outside cross-engine fair rankings."""
    ensure_optional_imports()
    if not HAS_APEXBASE or not OLTP_APEX_DIAGNOSTIC_BENCHMARKS:
        return []

    print("\n--- OLTP ApexBase Small-Batch Diagnostics (Apex-only; not ranked) ---")
    print("  Uses a fresh loaded ApexBase copy; tiny Python API batching effects are tracked separately from fair cross-engine rankings.")

    col_width = 16
    name_width = max(42, *(len(name) for name, _ in OLTP_APEX_DIAGNOSTIC_BENCHMARKS))
    header = f"  {'Metric':<{name_width}} | {'ApexBase':>{col_width}}"
    print(header)
    print("  " + "-" * (len(header) - 2))

    rows = []
    for bench_name, method_name in OLTP_APEX_DIAGNOSTIC_BENCHMARKS:
        diag_tmpdir = tempfile.mkdtemp(prefix="apexbase_oltp_diag_", dir=tmpdir)
        bench = ApexBaseBench(diag_tmpdir, data)
        try:
            bench.setup()
            bench.bench_insert()
            fn = getattr(bench, method_name)
            ms = run_bench_nogc_median(fn, warmup=warmup, iterations=iterations)
            print(f"  {bench_name:<{name_width}} | {fmt_ms(ms):>{col_width}}")
            rows.append({
                "operation": bench_name,
                "ApexBase": round(ms, 3),
            })
        finally:
            try:
                bench.close()
            except Exception:
                pass
            try:
                shutil.rmtree(diag_tmpdir)
            except Exception:
                pass

    return rows


def run_apex_txn_diagnostics(tmpdir, data, warmup, iterations):
    """Show Apex-only .delta transaction-path diagnostics outside fair rankings."""
    ensure_optional_imports()
    if not HAS_APEXBASE or not TXN_APEX_DIAGNOSTIC_BENCHMARKS:
        return []

    print("\n--- OLTP ApexBase Transaction Diagnostics (Apex-only; not ranked) ---")
    print("  Preserves ApexBase .delta commit semantics and reports transaction-control diagnostics without cross-engine ranking.")

    col_width = 16
    name_width = max(52, *(len(spec[0]) for spec in TXN_APEX_DIAGNOSTIC_BENCHMARKS))
    header = f"  {'Metric':<{name_width}} | {'ApexBase':>{col_width}}"
    print(header)
    print("  " + "-" * (len(header) - 2))

    rows = []
    diag_tmpdir = tempfile.mkdtemp(prefix="apexbase_txn_diag_", dir=tmpdir)
    bench = ApexBaseBench(diag_tmpdir, data)
    try:
        for spec in TXN_APEX_DIAGNOSTIC_BENCHMARKS:
            bench_name, method_name = spec[:2]
            setup_method = spec[2] if len(spec) > 2 else None
            bench.setup()
            bench.bench_insert()
            if setup_method is not None:
                getattr(bench, setup_method)()
            fn = getattr(bench, method_name)
            ms = run_bench_nogc_median(fn, warmup=warmup, iterations=iterations)
            print(f"  {bench_name:<{name_width}} | {fmt_ms(ms):>{col_width}}")
            rows.append({
                "operation": bench_name,
                "ApexBase": round(ms, 3),
            })
    finally:
        try:
            bench.close()
        except Exception:
            pass
        try:
            shutil.rmtree(diag_tmpdir)
        except Exception:
            pass

    return rows


def run_apex_buffered_oltp_benchmarks(tmpdir, oltp_results, warmup, iterations):
    """Show ApexBase's explicit client-local buffered write mode.

    This is intentionally separate from the default cross-engine OLTP table:
    buffered rows are accumulated in the ApexClient process and become visible
    after flush/end/close, so the durability/visibility contract is different
    from per-call SQLite INSERT+commit.
    """
    ensure_optional_imports()
    if not HAS_APEXBASE or not hasattr(ApexClient, "begin_buffered_writes"):
        return []

    baselines = {}
    for row in oltp_results or []:
        if row.get("operation") == "Insert 1 row (default fair)":
            baselines = row
            break

    print("\n--- OLTP ApexBase Buffered Writes (Apex-only; not ranked) ---")
    print("  Opt-in client-local write buffer; visibility/durability option is included in the metric label.")

    col_width = 16
    header = f"  {'Metric':<42} | {'ApexBase Buffered':>{col_width}}"
    for name in ("SQLite", "DuckDB"):
        if name in baselines:
            header += f" | {name:>{col_width}}"
    if baselines:
        header += f" | {'Ratio (Apex/Best)':>{col_width}}"
    print(header)
    print("  " + "-" * (len(header) - 2))

    rows = []
    buf_tmpdir = tempfile.mkdtemp(prefix="apexbase_buffered_oltp_", dir=tmpdir)
    client = ApexClient(buf_tmpdir, drop_if_exists=True)
    try:
        client.create_table("default")
        client.store({
            "name": ["seed"],
            "age": [1],
            "score": [1.0],
            "city": ["Beijing"],
            "category": ["Books"],
        })
        client.begin_buffered_writes()

        def buffered_insert_one():
            client.store({
                "name": "oltp_buffered_one",
                "age": 31,
                "score": 77.0,
                "city": "Beijing",
                "category": "Books",
            })

        ms = run_bench_nogc_median(buffered_insert_one, warmup=warmup, iterations=iterations)
        flushed = client.flush_buffered_writes()

        row_text = f"  {'Buffered Insert 1 row (flush after timing)':<42} | {fmt_ms(ms):>{col_width}}"
        others = []
        for name in ("SQLite", "DuckDB"):
            other_ms = baselines.get(name)
            if other_ms is not None:
                row_text += f" | {fmt_ms(other_ms):>{col_width}}"
                others.append(other_ms)
        if others:
            label = apex_ratio_label(ms, others)
            row_text += f" | {label:>{col_width}}"
        print(row_text)

        rows.append({
            "operation": "Buffered Insert 1 row (flush after timing)",
            "ApexBase Buffered": round(ms, 6),
            "flushed_rows_after_timing": flushed,
        })
    finally:
        try:
            client.end_buffered_writes(flush=True)
        except Exception:
            pass
        try:
            client.close()
        except Exception:
            pass
        try:
            shutil.rmtree(buf_tmpdir)
        except Exception:
            pass

    return rows


def run_apex_memtable_oltp_benchmarks(tmpdir, oltp_results, warmup, iterations):
    """Show ApexBase's default fast storage-level memtable write path in isolation.

    This path keeps writes inside the storage engine and makes them immediately
    readable by the same storage instance, then persists them on flush/close or
    auto-flush. Separate processes see the rows only after persistence, so this
    stays outside committed-write OLTP rankings unless the benchmark flushes
    each timed write.
    """
    ensure_optional_imports()
    if not HAS_APEXBASE:
        return []

    baselines = {}
    for row in oltp_results or []:
        if row.get("operation") == "Insert 1 row (default fair)":
            baselines = row
            break

    print("\n--- OLTP ApexBase Memtable Writes (Apex-only; not ranked) ---")
    print("  Same-storage reads see rows immediately; cross-process visibility follows flush/close/auto-flush.")

    col_width = 16
    header = f"  {'Metric':<42} | {'ApexBase Memtable':>{col_width}}"
    for name in ("SQLite", "DuckDB"):
        if name in baselines:
            header += f" | {name:>{col_width}}"
    if baselines:
        header += f" | {'Ratio (Apex/Best)':>{col_width}}"
    print(header)
    print("  " + "-" * (len(header) - 2))

    rows = []
    mem_tmpdir = tempfile.mkdtemp(prefix="apexbase_memtable_oltp_", dir=tmpdir)
    old_disable_env = os.environ.get("APEXBASE_DISABLE_MEMTABLE_SINGLE_WRITE")
    os.environ.pop("APEXBASE_DISABLE_MEMTABLE_SINGLE_WRITE", None)
    client = ApexClient(mem_tmpdir, drop_if_exists=True)
    try:
        client.create_table("default")
        client.store({
            "name": ["seed"],
            "age": [1],
            "score": [1.0],
            "city": ["Beijing"],
            "category": ["Books"],
        })

        def memtable_insert_one():
            client.store({
                "name": "oltp_memtable_one",
                "age": 31,
                "score": 77.0,
                "city": "Beijing",
                "category": "Books",
            })

        ms = run_bench_nogc_median(memtable_insert_one, warmup=warmup, iterations=iterations)
        client.flush()

        row_text = f"  {'Memtable Insert 1 row (same-client visible)':<42} | {fmt_ms(ms):>{col_width}}"
        others = []
        for name in ("SQLite", "DuckDB"):
            other_ms = baselines.get(name)
            if other_ms is not None:
                row_text += f" | {fmt_ms(other_ms):>{col_width}}"
                others.append(other_ms)
        if others:
            label = apex_ratio_label(ms, others)
            row_text += f" | {label:>{col_width}}"
        print(row_text)

        rows.append({
            "operation": "Memtable Insert 1 row (same-client visible)",
            "ApexBase Memtable": round(ms, 6),
        })
    finally:
        try:
            client.close()
        except Exception:
            pass
        if old_disable_env is None:
            os.environ.pop("APEXBASE_DISABLE_MEMTABLE_SINGLE_WRITE", None)
        else:
            os.environ["APEXBASE_DISABLE_MEMTABLE_SINGLE_WRITE"] = old_disable_env
        try:
            shutil.rmtree(mem_tmpdir)
        except Exception:
            pass

    return rows


def run_vector_similarity_benchmarks(tmpdir, rows, dim, k, warmup, iterations, profile=PROFILE_PUBLIC):
    """Benchmark vector similarity against DuckDB on a separate vector dataset."""
    ensure_optional_imports()
    head_metrics, batch_metrics, apex_only_metrics = vector_metric_sets(profile)
    config = {
        "rows": rows,
        "dim": dim,
        "k": k,
        "batch_queries": VECTOR_BATCH_QUERY_COUNT,
        "sqlite_note": VECTOR_SQLITE_NOTE,
        "profile": normalize_profile(profile),
    }

    reason = None
    if not HAS_APEXBASE:
        reason = "ApexBase is unavailable in this environment."
    elif not HAS_DUCKDB:
        reason = "DuckDB is unavailable in this environment."
    elif not HAS_PANDAS:
        reason = "pandas is required to bulk-load the DuckDB vector table."
    elif rows <= 0 or dim <= 0 or k <= 0:
        reason = "rows, dim, and k must all be positive."

    print_module_header("Vector Similarity", vector_metric_count(profile))
    print(f"  Dedicated vector dataset: {rows:,} rows x {dim} dims; TopK k={k}; batch queries={VECTOR_BATCH_QUERY_COUNT}.")
    print(f"  {VECTOR_SQLITE_NOTE}")

    if reason is not None:
        print(f"  Skipped: {reason}")
        return {
            "config": config,
            "skipped": True,
            "skip_reason": reason,
            "head_to_head": [],
            "batch": [],
            "apex_only": [],
            "summary": {"wins": 0, "ties": 0, "slower": 0, "total": 0},
        }

    print("Generating vector dataset...", end=" ", flush=True)
    vecs, query, batch_queries = generate_vector_data(rows, dim)
    print("done.")

    vector_tmpdir = tempfile.mkdtemp(prefix="apexbase_vector_", dir=tmpdir)
    apex_client = None
    duck_con = None
    try:
        print("Setting up vector engines...", end=" ", flush=True)
        apex_client = setup_apex_vector_bench(vector_tmpdir, vecs)
        duck_con = setup_duckdb_vector_bench(vecs)
        print("done.")

        head_results = {}
        head_rows = []
        for label, metric in head_metrics:
            head_results[label] = {
                "ApexBase": run_bench_gc_median(
                    lambda client=apex_client, q=query, metric=metric: bench_apex_vector_query(client, q, k, metric),
                    warmup=warmup,
                    iterations=iterations,
                ),
                "DuckDB": run_bench_gc_median(
                    lambda con=duck_con, q=query, metric=metric: bench_duckdb_vector_query(con, q, k, metric),
                    warmup=warmup,
                    iterations=iterations,
                ),
            }

        if head_metrics:
            head_rows = print_benchmark_section(
                "Vector Head-to-Head (single query)",
                "Single-query TopK similarity on the same vector table; results materialized via Arrow when available.",
                display_only_specs([label for label, _ in head_metrics]),
                head_results,
                ["ApexBase", "DuckDB"],
                16,
            )

        batch_results = {}
        batch_rows = []
        for label, metric in batch_metrics:
            batch_results[label] = {
                "ApexBase": run_bench_gc_median(
                    lambda client=apex_client, queries=batch_queries, metric=metric: bench_apex_batch_vector_query(client, queries, k, metric),
                    warmup=warmup,
                    iterations=iterations,
                ),
                "DuckDB": run_bench_gc_median(
                    lambda con=duck_con, queries=batch_queries, metric=metric: bench_duckdb_batch_vector_query(con, queries, k, metric),
                    warmup=warmup,
                    iterations=iterations,
                ),
            }

        if batch_metrics:
            batch_rows = print_benchmark_section(
                "Vector Head-to-Head (batch queries)",
                "Ten-query TopK workload: ApexBase batch_topk_distance() vs repeated DuckDB single-query SQL on the same batch.",
                display_only_specs([label for label, _ in batch_metrics]),
                batch_results,
                ["ApexBase", "DuckDB"],
                16,
            )

        apex_only_rows = []
        if apex_only_metrics:
            print("\n--- Vector Apex-only Metrics ---")
            print("  Metrics without a native DuckDB equivalent in this harness.")
            col_width = 16
            name_width = max(32, *(len(label) for label, _ in apex_only_metrics))
            header = f"{'Metric':<{name_width}} | {'ApexBase':>{col_width}}"
            print(header)
            print("-" * len(header))

            for label, metric in apex_only_metrics:
                ms = run_bench_gc_median(
                    lambda client=apex_client, q=query, metric=metric: bench_apex_vector_query(client, q, k, metric),
                    warmup=warmup,
                    iterations=iterations,
                )
                print(f"{label:<{name_width}} | {fmt_ms(ms):>{col_width}}")
                apex_only_rows.append({
                    "category": "Vector Apex-only Metrics",
                    "query": label,
                    "ApexBase": round(ms, 3),
                })

        combined_results = {}
        combined_results.update(head_results)
        combined_results.update(batch_results)
        combined_specs = display_only_specs(list(head_results) + list(batch_results))
        summary = summarize_apex_section(combined_specs, combined_results)
        print(
            f"Vector Competitive Summary: ApexBase wins {summary['wins']}/{summary['total']}, "
            f"ties {summary['ties']}/{summary['total']}, slower {summary['slower']}/{summary['total']}"
        )

        return {
            "config": config,
            "skipped": False,
            "skip_reason": None,
            "head_to_head": head_rows,
            "batch": batch_rows,
            "apex_only": apex_only_rows,
            "summary": summary,
        }
    finally:
        if apex_client is not None:
            try:
                apex_client.close()
            except Exception:
                pass
        if duck_con is not None:
            try:
                duck_con.close()
            except Exception:
                pass
        try:
            shutil.rmtree(vector_tmpdir)
        except Exception:
            pass


def get_system_info():
    ensure_optional_imports()
    info = {
        "platform": platform.platform(),
        "machine": platform.machine(),
        "processor": platform.processor(),
        "python": platform.python_version(),
    }
    try:
        import psutil
        info["cpu_count"] = psutil.cpu_count(logical=True)
        info["memory_gb"] = round(psutil.virtual_memory().total / (1024**3), 1)
    except ImportError:
        info["cpu_count"] = os.cpu_count()
        info["memory_gb"] = "N/A"

    if HAS_APEXBASE:
        try:
            from apexbase._core import __version__
            info["apexbase"] = __version__
        except Exception:
            info["apexbase"] = "unknown"
    if HAS_DUCKDB:
        info["duckdb"] = duckdb.__version__
    info["sqlite"] = sqlite3.sqlite_version
    if HAS_PYARROW:
        info["pyarrow"] = pa.__version__
    return info


def main(argv=None, default_profile=PROFILE_PUBLIC):
    parser = argparse.ArgumentParser(description="ApexBase vs SQLite vs DuckDB benchmark")
    parser.add_argument("--rows", type=int, default=1_000_000, help="Number of rows (default: 1M)")
    parser.add_argument("--warmup", type=int, default=2, help="Warmup iterations (default: 2)")
    parser.add_argument("--iterations", type=int, default=5, help="Timed iterations (default: 5)")
    parser.add_argument("--output", type=str, default=None, help="JSON output file")
    parser.add_argument("--profile", choices=PROFILE_CHOICES, default=default_profile,
                        help="Benchmark profile: public README scoreboard or extended diagnostics")
    parser.add_argument("--full", action="store_true",
                        help="Alias for --profile extended")
    parser.add_argument("--memory", action="store_true", help="Track RSS memory delta per query")
    parser.add_argument("--low-memory", action="store_true",
                        help="Disable ApexBase arrow_batch_cache (simulate low-memory mode like SQLite/DuckDB)")
    parser.add_argument("--skip-vector", action="store_true", help="Skip the vector similarity benchmark module")
    parser.add_argument("--vector-rows", type=int, default=None,
                        help="Rows for vector similarity module (default: min(rows, 200000))")
    parser.add_argument("--vector-dim", type=int, default=VECTOR_DIM_DEFAULT,
                        help=f"Vector dimensions for similarity module (default: {VECTOR_DIM_DEFAULT})")
    parser.add_argument("--vector-k", type=int, default=VECTOR_K_DEFAULT,
                        help=f"TopK value for vector similarity module (default: {VECTOR_K_DEFAULT})")
    args = parser.parse_args(argv)
    profile = PROFILE_EXTENDED if args.full else normalize_profile(args.profile)
    ensure_optional_imports()

    N = args.rows
    WARMUP = args.warmup
    ITERS = args.iterations
    VECTOR_ROWS = args.vector_rows if args.vector_rows is not None else default_vector_rows(N)
    VECTOR_DIM = args.vector_dim
    VECTOR_K = args.vector_k
    selected_benchmarks = benchmark_specs_for_profile(profile)

    print("=" * 80)
    print(f" ApexBase vs SQLite vs DuckDB — Performance Benchmark")
    print("=" * 80)

    sys_info = get_system_info()
    print(f"\nSystem: {sys_info['platform']} ({sys_info['machine']})")
    print(f"CPU: {sys_info.get('processor', 'N/A')} ({sys_info['cpu_count']} cores)")
    print(f"Memory: {sys_info['memory_gb']} GB")
    print(f"Python: {sys_info['python']}")
    if "apexbase" in sys_info:
        print(f"ApexBase: v{sys_info['apexbase']}")
    print(f"SQLite: v{sys_info['sqlite']}")
    if HAS_DUCKDB:
        print(f"DuckDB: v{sys_info['duckdb']}")
    if HAS_PYARROW:
        print(f"PyArrow: v{sys_info['pyarrow']}")
    olap_metric_count, oltp_metric_count, vector_metric_total = module_metric_counts(profile)
    print(f"\nDataset: {N:,} rows × 5 columns (name, age, score, city, category)")
    print(f"Warmup: {WARMUP} iterations, Timed: {ITERS} iterations (average)")
    print(f"Profile: {profile} ({'fair workload scoreboard' if profile == PROFILE_PUBLIC else 'full diagnostics'})")
    print("Fairness mode: default rankings use normal engine APIs, shared input data, and comparable materialized results.")
    print(
        f"Layout: OLAP, OLTP, and Vector Similarity modules; "
        f"{olap_metric_count + oltp_metric_count + vector_metric_total} named metrics configured "
        f"({olap_metric_count} OLAP, {oltp_metric_count} OLTP, {vector_metric_total} vector)."
    )
    print("Tunable/fairness options are shown in metric names using parentheses.")
    if args.skip_vector:
        print("Vector module: skipped by --skip-vector")
    else:
        print(
            f"Vector dataset: {VECTOR_ROWS:,} rows x {VECTOR_DIM} dims (separate module), "
            f"TopK={VECTOR_K}, batch queries={VECTOR_BATCH_QUERY_COUNT}"
        )
        print(
            "Vector results are reported separately and do not change the "
            f"{len(selected_benchmarks)}-metric tabular fair scoreboard."
        )
    if args.low_memory:
        print("Mode: LOW-MEMORY (ApexBase-only cache stress mode; not a cross-engine apples-to-apples setting)")
    print()

    # Generate data
    print("Generating test data...", end=" ", flush=True)
    data = generate_data(N)
    print("done.")

    tmpdir = tempfile.mkdtemp(prefix="apexbase_bench_")

    csv_path = parquet_path = json_path = None
    if selected_benchmarks_need_files(selected_benchmarks) or profile_runs_extended_sections(profile):
        print("Generating benchmark files (CSV/Parquet/JSON)...", end=" ", flush=True)
        csv_path, parquet_path, json_path = generate_benchmark_files(tmpdir, data)
        print("done.")
    else:
        print("Benchmark files: skipped; no selected fair metric needs external files.")
    results = {}
    shared_inputs = build_shared_inputs(N)

    engines = []
    if HAS_APEXBASE:
        engines.append(("ApexBase", ApexBaseBench(tmpdir, data, low_memory=args.low_memory, csv_path=csv_path, parquet_path=parquet_path, json_path=json_path)))
    engines.append(("SQLite", SQLiteBench(tmpdir, data)))
    if HAS_DUCKDB:
        engines.append(("DuckDB", DuckDBBench(tmpdir, data, csv_path=csv_path, parquet_path=parquet_path, json_path=json_path)))

    if not engines:
        print("ERROR: No database engines available!")
        return

    # Setup all engines
    for name, bench in engines:
        bench.shared_inputs = shared_inputs
        bench.setup()

    mem_results = {}  # bench_name -> {eng_name: rss_delta_mb}

    # Run benchmarks
    for bench_name, method_name, is_insert, is_cold, is_warm_nogc, setup_method in selected_benchmarks:
        results[bench_name] = {}
        mem_results.setdefault(bench_name, {})
        for eng_name, bench in engines:
            fn = getattr(bench, method_name, None)
            if fn is None:
                results[bench_name][eng_name] = None
                continue

            if is_insert:
                rss_before = measure_rss_mb()
                with timer() as t:
                    fn()
                ms = t["elapsed_ms"]
                rss_after = measure_rss_mb()
                results[bench_name][eng_name] = ms
                if rss_before and rss_after:
                    mem_results[bench_name][eng_name] = rss_after - rss_before
            elif is_cold:
                # Cold-start (no gc): reopen DB before each iteration
                cold_setup_fn = getattr(bench, "cold_start_setup", None)
                if cold_setup_fn is None:
                    # Engine has no cold_start_setup — run warm no-gc
                    ms = run_bench_nogc(fn, warmup=WARMUP, iterations=ITERS)
                else:
                    rss_before = measure_rss_mb()
                    ms = run_bench_cold_nogc(cold_setup_fn, fn, warmup=WARMUP, iterations=ITERS)
                    rss_after = measure_rss_mb()
                    if rss_before and rss_after:
                        mem_results[bench_name][eng_name] = rss_after - rss_before
                results[bench_name][eng_name] = ms
            elif is_warm_nogc:
                # Warm cached backend, no gc
                rss_before = measure_rss_mb()
                if method_name in MICRO_MEDIAN_BENCHMARK_METHODS:
                    ms = run_bench_nogc_median(fn, warmup=WARMUP, iterations=ITERS)
                else:
                    ms = run_bench_nogc(fn, warmup=WARMUP, iterations=ITERS)
                rss_after = measure_rss_mb()
                results[bench_name][eng_name] = ms
                if rss_before and rss_after:
                    mem_results[bench_name][eng_name] = rss_after - rss_before
            elif setup_method is not None:
                # Per-iteration setup (e.g. pre-insert rows before timing delete)
                per_setup_fn = getattr(bench, setup_method, None)
                if per_setup_fn is None:
                    results[bench_name][eng_name] = None
                    continue
                rss_before = measure_rss_mb()
                ms = run_bench_with_setup(per_setup_fn, fn, warmup=WARMUP, iterations=ITERS)
                rss_after = measure_rss_mb()
                results[bench_name][eng_name] = ms
                if rss_before and rss_after:
                    mem_results[bench_name][eng_name] = rss_after - rss_before
            else:
                rss_before = measure_rss_mb()
                # low_memory mode: disable arrow_batch_cache for ApexBase by reopening each iter
                cold_setup_fn = getattr(bench, "cold_start_setup", None)
                use_cold = (HAS_APEXBASE and isinstance(bench, ApexBaseBench)
                            and bench.low_memory and cold_setup_fn is not None)
                if use_cold:
                    ms = run_bench_cold_nogc(cold_setup_fn, fn, warmup=WARMUP, iterations=ITERS)
                else:
                    ms = run_bench(fn, warmup=WARMUP, iterations=ITERS)
                rss_after = measure_rss_mb()
                results[bench_name][eng_name] = ms
                if rss_before and rss_after:
                    mem_results[bench_name][eng_name] = rss_after - rss_before

            if HAS_APEXBASE and isinstance(bench, ApexBaseBench):
                try:
                    bench.client.flush()
                except Exception:
                    pass

    # Print results tables by the two top-level modules requested by the benchmark.
    eng_names = [name for name, _ in engines]
    col_width = 16

    json_results = []
    olap_sections, oltp_sections = benchmark_sections_for_profile(profile)
    benchmark_sections = olap_sections + oltp_sections
    grouped_names = {spec[0] for _, _, specs in benchmark_sections for spec in specs}
    ungrouped_specs = [spec for spec in selected_benchmarks if spec[0] not in grouped_names]
    if ungrouped_specs:
        oltp_sections.append((
            "OLTP Other Fair Metrics",
            "Metrics not yet classified into a narrower OLTP table.",
            ungrouped_specs,
        ))
        benchmark_sections = olap_sections + oltp_sections

    print_module_header("OLAP", olap_metric_count)
    for section_title, section_description, benchmark_specs in olap_sections:
        json_results.extend(print_benchmark_section(
            section_title,
            section_description,
            benchmark_specs,
            results,
            eng_names,
            col_width,
        ))

    print()

    if profile_runs_extended_sections(profile):
        materialization_results = run_apex_materialization_benchmarks(
            tmpdir,
            data,
            shared_inputs,
            warmup=WARMUP,
            iterations=ITERS,
            low_memory=args.low_memory,
        )
    else:
        materialization_results = []

    # ========================================================================
    # OLAP Throughput Tests (Single & Concurrent)
    # ========================================================================
    from concurrent.futures import ThreadPoolExecutor
    import threading

    # Q/s test queries - mixed short + analytical reads on the same loaded table
    QPS_QUERIES_APEX = [
        "SELECT COUNT(*) FROM default",
        "SELECT city, COUNT(*) FROM default GROUP BY city",
        "SELECT category, AVG(score) FROM default GROUP BY category",
        "SELECT * FROM default WHERE age > 30 LIMIT 100",
    ]
    
    QPS_QUERIES_SQLITE = [
        "SELECT COUNT(*) FROM bench",
        "SELECT city, COUNT(*) FROM bench GROUP BY city",
        "SELECT category, AVG(score) FROM bench GROUP BY category",
        "SELECT * FROM bench WHERE age > 30 LIMIT 100",
    ]
    
    QPS_QUERIES_DUCKDB = [
        "SELECT COUNT(*) FROM bench",
        "SELECT city, COUNT(*) FROM bench GROUP BY city",
        "SELECT category, AVG(score) FROM bench GROUP BY category",
        "SELECT rowid + 1 AS _id, * FROM bench WHERE age > 30 LIMIT 100",
    ]

    def run_qps_benchmark(tmpdir, data, n_threads=4, min_duration=1.0, min_iterations=50,
                           existing_engines=None):
        """Measure OLAP/read Q/s for single-threaded and concurrent scenarios.
        
        Args:
            min_duration: Minimum test duration in seconds for accurate timing
            min_iterations: Minimum number of query batches to run
            existing_engines: dict of {name: bench} to reuse, avoids re-inserting data
        """
        results = {}
        print("\n--- OLAP Throughput (mixed read profile) ---")
        print("  Metric options: COUNT + two GROUP BY scans + filtered LIMIT 100; materialized Python rows.")

        # Reuse existing engines (data already inserted) to avoid re-inserting 1M rows
        qps_engines = []
        if existing_engines is not None:
            if HAS_APEXBASE and "ApexBase" in existing_engines:
                qps_engines.append(("ApexBase", existing_engines["ApexBase"], QPS_QUERIES_APEX))
            if "SQLite" in existing_engines:
                qps_engines.append(("SQLite", existing_engines["SQLite"], QPS_QUERIES_SQLITE))
            if HAS_DUCKDB and "DuckDB" in existing_engines:
                qps_engines.append(("DuckDB", existing_engines["DuckDB"], QPS_QUERIES_DUCKDB))
        else:
            # Fallback: create fresh engines (slow path)
            if HAS_APEXBASE:
                qps_engines.append(("ApexBase", ApexBaseBench(tmpdir, data), QPS_QUERIES_APEX))
            qps_engines.append(("SQLite", SQLiteBench(tmpdir, data), QPS_QUERIES_SQLITE))
            if HAS_DUCKDB:
                qps_engines.append(("DuckDB", DuckDBBench(tmpdir, data), QPS_QUERIES_DUCKDB))
            for name, bench, _ in qps_engines:
                bench.setup()
                if hasattr(bench, 'bench_insert'):
                    bench.bench_insert()

        # Pre-warm all engines - run each query once to ensure caching is comparable
        for name, bench, queries in qps_engines:
            try:
                for q in queries:
                    _ = bench.execute_materialized_query(q)
            except Exception:
                pass

        # 1. Single-threaded Q/s
        print("\n--- OLAP Q/s (single thread) ---")
        iterations = min_iterations  # fallback default
        single_iterations = {}
        for name, bench, queries in qps_engines:
            try:
                exec_fn = lambda q, b=bench: b.execute_materialized_query(q)

                # Run sequential queries with proper timing
                gc.collect()
                
                # First, determine appropriate number of iterations based on time
                # Run a small batch first to estimate time per query
                batch_size = len(queries)
                trial_iterations = 5
                
                t0 = time.perf_counter()
                for _ in range(trial_iterations):
                    for q in queries:
                        exec_fn(q)
                trial_time = time.perf_counter() - t0
                
                # Calculate iterations needed for min_duration seconds
                # At least min_iterations batches, but also enough to run for min_duration
                time_per_batch = trial_time / trial_iterations
                iterations = max(min_iterations, int(min_duration / time_per_batch))
                single_iterations[name] = iterations
                
                # Run the actual benchmark
                t0 = time.perf_counter()
                for _ in range(iterations):
                    for q in queries:
                        exec_fn(q)
                elapsed = time.perf_counter() - t0

                total_queries = iterations * len(queries)
                qps = total_queries / elapsed if elapsed > 0 else 0
                results[f'{name}_single'] = qps
                print(f"  {name}: {qps:.1f} Q/s ({total_queries} queries in {elapsed:.3f}s)")
            except Exception as e:
                print(f"  {name}: Error - {e}")

        # 2. Concurrent Q/s (multiple threads) — reuse qps_engines, no re-insert
        print(f"\n--- OLAP Q/s (threads={n_threads}) ---")

        for name, bench, queries in qps_engines:
            try:
                # For each thread, we need a separate connection for SQLite/DuckDB
                # ApexBase handles concurrency internally
                if hasattr(bench, 'client'):
                    # ApexBase: shared client
                    # Reuse the per-engine calibration from the single-threaded test.
                    conc_iterations = max(min_iterations, single_iterations.get(name, min_iterations))
                    def concurrent_worker_apex(its=conc_iterations):
                        for _ in range(its):
                            for q in queries:
                                bench.execute_materialized_query(q)
                    
                    gc.collect()
                    t0 = time.perf_counter()
                    with ThreadPoolExecutor(max_workers=n_threads) as executor:
                        list(executor.map(lambda _: concurrent_worker_apex(), range(n_threads)))
                    elapsed = time.perf_counter() - t0
                    total_queries = n_threads * conc_iterations * len(queries)
                    qps = total_queries / elapsed if elapsed > 0.001 else 0
                    
                elif hasattr(bench, 'conn'):
                    # SQLite/DuckDB: create connection per thread
                    db_path = bench.db_path
                    is_duckdb = 'duckdb' in str(type(bench.conn)).lower()

                    conc_iterations = max(min_iterations, single_iterations.get(name, min_iterations))
                    def concurrent_worker_sql(db_path, is_duckdb, queries, its=conc_iterations):
                        # Each thread creates its own connection
                        try:
                            if is_duckdb:
                                import duckdb
                                conn = duckdb.connect(db_path)
                            else:
                                import sqlite3
                                conn = sqlite3.connect(db_path, timeout=30)
                            for _ in range(its):
                                for q in queries:
                                    cur = conn.execute(q)
                                    _ = rows_to_dicts([d[0] for d in (cur.description or [])], cur.fetchall())
                            conn.close()
                        except Exception:
                            pass
                    
                    gc.collect()
                    t0 = time.perf_counter()
                    with ThreadPoolExecutor(max_workers=n_threads) as executor:
                        list(executor.map(
                            lambda _: concurrent_worker_sql(db_path, is_duckdb, queries),
                            range(n_threads)
                        ))
                    elapsed = time.perf_counter() - t0
                    total_queries = n_threads * conc_iterations * len(queries)
                    qps = total_queries / elapsed if elapsed > 0.001 else 0
                else:
                    qps = 0
                    total_queries = 0
                    elapsed = 0

                results[f'{name}_concurrent_{n_threads}'] = qps
                if elapsed > 0.001:
                    print(f"  {name}: {qps:.1f} Q/s ({total_queries} queries in {elapsed:.3f}s)")
                else:
                    print(f"  {name}: Error - test time too short ({elapsed:.6f}s)")
            except Exception as e:
                print(f"  {name}: Error - {e}")

        # Print Q/s Summary
        print("\n--- OLAP Q/s Summary ---")
        apex_single = results.get("ApexBase_single", 0)
        sqlite_single = results.get("SQLite_single", 0)
        duckdb_single = results.get("DuckDB_single", 0)
        apex_concurrent = results.get("ApexBase_concurrent_4", 0)
        sqlite_concurrent = results.get("SQLite_concurrent_4", 0)
        duckdb_concurrent = results.get("DuckDB_concurrent_4", 0)
        print(f"  ApexBase (single-threaded): {apex_single:.1f} Q/s")
        print(f"  SQLite (single-threaded): {sqlite_single:.1f} Q/s")
        print(f"  DuckDB (single-threaded): {duckdb_single:.1f} Q/s")
        print(f"  ApexBase (4-thread concurrent): {apex_concurrent:.1f} Q/s")
        print(f"  SQLite (4-thread concurrent): {sqlite_concurrent:.1f} Q/s")
        print(f"  DuckDB (4-thread concurrent): {duckdb_concurrent:.1f} Q/s")

        return results

    if profile_runs_extended_sections(profile):
        existing_engines = {name: bench for name, bench in engines}
        qps_results = run_qps_benchmark(
            tmpdir,
            data,
            n_threads=4,
            min_duration=2.0,
            min_iterations=50,
            existing_engines=existing_engines,
        )
    else:
        qps_results = {}

    print_module_header("OLTP", oltp_metric_count)
    for section_title, section_description, benchmark_specs in oltp_sections:
        json_results.extend(print_benchmark_section(
            section_title,
            section_description,
            benchmark_specs,
            results,
            eng_names,
            col_width,
        ))

    if args.memory:
        print()
        print("Memory delta per fair metric by module (RSS change, MB):")
        name_width = max(42, *(len(spec[0]) for _, _, specs in benchmark_sections for spec in specs))
        mem_header = f"    {'Metric':<{name_width}}"
        for name in eng_names:
            mem_header += f" | {name:>{col_width}}"
        print(mem_header)
        print("    " + "-" * (len(mem_header) - 4))
        for section_title, _, benchmark_specs in benchmark_sections:
            print(f"  {section_title}:")
            for bench_name, _, _, _, _, _ in benchmark_specs:
                row = f"    {bench_name:<{name_width}}"
                for eng_name in eng_names:
                    delta = mem_results.get(bench_name, {}).get(eng_name)
                    if delta is not None:
                        row += f" | {delta:>+{col_width}.1f}"
                    else:
                        row += f" | {'N/A':>{col_width}}"
                print(row)

    fair_workload_scoreboard = print_fair_workload_scoreboard(
        results,
        eng_names,
        selected_benchmarks,
        col_width,
    )

    if "ApexBase" in [n for n, _ in engines]:
        stats = summarize_apex_section(selected_benchmarks, results)
        print(
            f"\nTabular Fair Detail Summary: ApexBase wins {stats['wins']}/{stats['total']}, "
            f"ties {stats['ties']}/{stats['total']}, slower {stats['slower']}/{stats['total']}"
        )

    if args.skip_vector:
        vector_results = {
            "config": {
                "profile": profile,
                "rows": VECTOR_ROWS,
                "dim": VECTOR_DIM,
                "k": VECTOR_K,
                "batch_queries": VECTOR_BATCH_QUERY_COUNT,
                "sqlite_note": VECTOR_SQLITE_NOTE,
            },
            "skipped": True,
            "skip_reason": "Skipped by --skip-vector",
            "head_to_head": [],
            "batch": [],
            "apex_only": [],
            "summary": {"wins": 0, "ties": 0, "slower": 0, "total": 0},
        }
    else:
        vector_results = run_vector_similarity_benchmarks(
            tmpdir,
            rows=VECTOR_ROWS,
            dim=VECTOR_DIM,
            k=VECTOR_K,
            warmup=WARMUP,
            iterations=ITERS,
            profile=profile,
        )

    if profile_runs_extended_sections(profile):
        oltp_results = run_oltp_benchmarks(
            engines,
            warmup=WARMUP,
            iterations=ITERS,
        )
        apex_oltp_diagnostics = run_apex_oltp_diagnostics(
            tmpdir,
            data,
            warmup=WARMUP,
            iterations=ITERS,
        )
        durable_oltp_results = run_oltp_durable_benchmarks(
            engines,
            warmup=WARMUP,
            iterations=ITERS,
        )
        txn_results = run_txn_benchmarks(
            engines,
            warmup=WARMUP,
            iterations=ITERS,
        )
        apex_txn_diagnostics = run_apex_txn_diagnostics(
            tmpdir,
            data,
            warmup=WARMUP,
            iterations=ITERS,
        )
        buffered_oltp_results = run_apex_buffered_oltp_benchmarks(
            tmpdir,
            oltp_results,
            warmup=WARMUP,
            iterations=ITERS,
        )
        memtable_oltp_results = run_apex_memtable_oltp_benchmarks(
            tmpdir,
            oltp_results,
            warmup=WARMUP,
            iterations=ITERS,
        )
    else:
        oltp_results = []
        apex_oltp_diagnostics = []
        durable_oltp_results = []
        txn_results = []
        apex_txn_diagnostics = []
        buffered_oltp_results = []
        memtable_oltp_results = []

    # Cleanup (after Q/s tests, engines are still open)
    for name, bench in engines:
        bench.close()

    # Save JSON if requested
    if args.output:
        output = {
            "system": sys_info,
            "config": {
                "profile": profile,
                "rows": N,
                "warmup": WARMUP,
                "iterations": ITERS,
                "vector_rows": VECTOR_ROWS,
                "vector_dim": VECTOR_DIM,
                "vector_k": VECTOR_K,
                "skip_vector": args.skip_vector,
            },
            "results": json_results,
            "fair_workload_scoreboard": fair_workload_scoreboard,
            "vector_similarity": vector_results,
            "apexbase_materialization": materialization_results,
            "qps": qps_results,
            "oltp_microbenchmarks": oltp_results,
            "apexbase_oltp_diagnostics": apex_oltp_diagnostics,
            "oltp_durable_microbenchmarks": durable_oltp_results,
            "transaction_microbenchmarks": txn_results,
            "apexbase_transaction_diagnostics": apex_txn_diagnostics,
            "apexbase_buffered_oltp": buffered_oltp_results,
            "apexbase_memtable_oltp": memtable_oltp_results,
        }
        with open(args.output, "w") as f:
            json.dump(output, f, indent=2)
        print(f"Results saved to {args.output}")

    # Cleanup tmpdir
    try:
        shutil.rmtree(tmpdir)
    except Exception:
        pass


if __name__ == "__main__":
    main()