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
use hashbrown::HashMap;
use rayon::prelude::*;
use std::collections::BinaryHeap;
use std::sync::{Arc, RwLock};
use std::thread;
use crate::cancel::CancelToken;
use crate::document::hako_doc::{BorrowedValue, DocView, HakoDoc, HakoDocView};
use crate::document::value::Value;
use crate::error::Result;
use crate::index::manager::IndexManager;
use crate::query::order::OrderBy;
use crate::query::plan::ScanType;
use crate::query::query::AggregateOp;
use crate::storage::engine::{Pointer, StorageEngine};
use super::super::plan::QueryPlan;
// use super::result_stream::QueryResults;
use super::scheduler::shard_tasks;
use super::task::QueryTask;
use super::worker::{matches_filters_view, run_task, run_task_projected};
/// TopN lane firings since process start: operational visibility and test
/// engagement proof (the parity suite asserts this moves). One Relaxed
/// increment per TopN query — negligible next to a scan.
static TOPN_RUNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
/// How many queries took the TopN lane (see `execute_topn`).
pub fn topn_runs() -> usize {
TOPN_RUNS.load(std::sync::atomic::Ordering::Relaxed)
}
/// Zero-copy rows (#142 Q3 + M1): only cache-hit rows from the executor's
/// fast path are `Shared` (the entire source of the win — no deep clone per
/// row); every freshly decoded row stays `Owned`, so the topN, parallel and
/// worker lanes churn zero `Arc`s (the bisect showed Arc churn alone costs
/// `Bulk_del(all)` −27%). `into_doc` restores the old owned semantics for
/// `Hako::query`; `into_arc` hands FFI handles a shared `Arc` for free.
pub(crate) enum RowRef {
Owned(HakoDoc),
Shared(std::sync::Arc<HakoDoc>),
}
impl RowRef {
fn doc(&self) -> &HakoDoc {
match self {
RowRef::Owned(d) => d,
RowRef::Shared(a) => a,
}
}
pub(crate) fn into_doc(self) -> HakoDoc {
match self {
RowRef::Owned(d) => d,
// ponytail: refcount 1 frees without a clone; more holders
// deep-clone (same cost the pre-Q3 hit path always paid).
RowRef::Shared(a) => std::sync::Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone()),
}
}
pub(crate) fn into_arc(self) -> std::sync::Arc<HakoDoc> {
match self {
RowRef::Owned(d) => std::sync::Arc::new(d),
RowRef::Shared(a) => a,
}
}
}
/// Queries currently executing (any execute_* entry point). The
/// maintenance tick sheds non-durability work while this is non-zero —
/// queries never queue behind compaction/snapshot I/O. Best-effort
/// signal (walk/aggregation paths also count via the same guard).
static QUERIES_INFLIGHT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
/// Current in-flight query count (see above).
pub fn queries_inflight() -> usize {
QUERIES_INFLIGHT.load(std::sync::atomic::Ordering::Relaxed)
}
/// RAII bump for the in-flight counter — covers every return path.
struct InflightGuard;
impl InflightGuard {
fn take() -> Self {
QUERIES_INFLIGHT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Self
}
}
impl Drop for InflightGuard {
fn drop(&mut self) {
QUERIES_INFLIGHT.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
}
use crate::index::index_key::decode_scalar_as_f64;
pub struct ParallelQueryExecutor {
workers: usize,
}
/// One ORDER BY slot, resolved per direction at compare time.
/// `Field(None)` = missing (sorts below every value — same as the full
/// sort's `Option` compare).
#[derive(Debug, Clone, PartialEq, Eq)]
enum TopKey {
Id,
Time(i64),
Field(Option<Value>),
}
/// Heap candidate: owned sort keys + scan position + identity. The pointer
/// is re-read at fetch (never compared).
struct TopEntry {
keys: Vec<TopKey>,
seq: usize,
id: String,
ptr: Pointer,
}
/// Heap item borrows the order spec (directions live in the plan).
struct TopItem<'a> {
entry: TopEntry,
orders: &'a [OrderBy],
}
impl<'a> PartialEq for TopItem<'a> {
fn eq(&self, other: &Self) -> bool {
cmp_top(&self.entry, &other.entry, self.orders) == std::cmp::Ordering::Equal
}
}
impl<'a> Eq for TopItem<'a> {}
impl<'a> PartialOrd for TopItem<'a> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<'a> Ord for TopItem<'a> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
cmp_top(&self.entry, &other.entry, self.orders)
}
}
/// The phase-6 comparator, factored for the heap: per-slot direction, then
/// scan-seq (a stable sort over scan order is exactly (keys…, input-seq),
/// so this reproduces the legacy page bit-for-bit, ties included).
fn cmp_top(a: &TopEntry, b: &TopEntry, orders: &[OrderBy]) -> std::cmp::Ordering {
use std::cmp::Ordering;
for (o, (ka, kb)) in orders.iter().zip(a.keys.iter().zip(b.keys.iter())) {
let cmp = match (o.field.as_str(), ka, kb) {
("id", _, _) => a.id.cmp(&b.id),
("_time", TopKey::Time(x), TopKey::Time(y)) => x.cmp(y),
(_, TopKey::Field(x), TopKey::Field(y)) => x.cmp(y),
// Unreachable: keys are built from this same spec. Equal keeps
// the heap total without inventing order.
_ => Ordering::Equal,
};
if cmp != Ordering::Equal {
return if o.ascending { cmp } else { cmp.reverse() };
}
}
a.seq.cmp(&b.seq)
}
/// Pull one ORDER BY slot per doc from the view: header time, id compare
/// needs nothing, fields decode a single value (never the whole doc).
fn top_keys(view: &HakoDocView, orders: &[OrderBy]) -> Vec<TopKey> {
orders
.iter()
.map(|o| match o.field.as_str() {
"id" => TopKey::Id,
"_time" => TopKey::Time(view._time),
// Dotted ORDER BY (hakodb#71 F2): nested walk off the raw
// view, Map-only descent, fail-closed absent.
f if f.contains('.') => TopKey::Field(view.get_path(f)),
f => TopKey::Field(
view.iter()
.find(|(k, _, _)| *k == f)
.and_then(|(_, tag, data)| {
crate::document::hako_doc::decode_value(tag, data)
}),
),
})
.collect()
}
impl ParallelQueryExecutor {
/// True when an empty exact-key index result may hide cross-type
/// matches: an Eq filter whose value has a numeric twin (bare Int /
/// Float, or a string that parses as one). Mirrors the planner's
/// ambiguous class — the sweep fallback only fires for these, and
/// only on empty, so same-type point lookups never pay it.
fn index_may_hide_xtype(plan: &QueryPlan) -> bool {
if !matches!(
plan.scan,
ScanType::SecondaryIndex { .. }
| ScanType::CompositeIndex { .. }
| ScanType::CompositeIndexRange { .. }
| ScanType::UnionIndex { .. }
) {
return false;
}
if !plan.or_groups.is_empty() {
return false;
}
use crate::query::filter::Operator;
plan.filters.iter().any(|f| {
matches!(f.op, Operator::Eq)
&& match &f.value {
Value::Int(_) | Value::Float(_) => true,
Value::String(s) => s.parse::<i64>().is_ok() || s.parse::<f64>().is_ok(),
_ => false,
}
})
}
/// Shared fast-lane gate for the raw/walk entry points: they never decode
/// to match or sort, so unsatisfied filters/ordering are a loud error,
/// not a silent sweep. One message (keeps the `"index-satisfied"`
/// contract asserted by `cursor_parity`, one literal in rodata).
#[inline]
fn check_index_satisfied(plan: &QueryPlan) -> Result<()> {
use crate::error::HakoError;
// hakodb#71 F3: elemMatch clauses are decode-time passes — raw
// bytes carry no element verdict, so refuse loudly instead of
// silently returning every row.
if !plan.elem_match.is_empty() {
return Err(HakoError::QueryError(
"query requires index-satisfied filters (decode to match)".into(),
));
}
if (!plan.filters.is_empty() || !plan.or_groups.is_empty())
&& !plan.filters_satisfied_by_index
{
return Err(HakoError::QueryError(
"query requires index-satisfied filters (decode to match)".into(),
));
}
if !plan.order_by_satisfied && !plan.order_by.is_empty() {
return Err(HakoError::QueryError(
"query requires index-satisfied ordering (decode to sort)".into(),
));
}
Ok(())
}
pub fn new(workers: usize) -> Self {
Self {
workers: workers.max(1),
}
}
fn check_cancel(cancel: Option<&CancelToken>) -> Result<()> {
match cancel {
Some(token) => token.check(),
None => Ok(()),
}
}
pub fn execute(
&self,
storage_arc: Arc<RwLock<StorageEngine>>,
indexes: &IndexManager,
plan: QueryPlan,
) -> Result<Vec<(String, HakoDoc)>> {
Ok(self
.execute_with_cancel(storage_arc, indexes, plan, None, None)?
.into_iter()
.map(|(id, row)| (id, row.into_doc()))
.collect())
}
/// [`Self::execute`] with cooperative cancellation. The optional token
/// is checked at scan-row and fetch checkpoints; a cancelled scan
/// returns `HakoError::Cancelled` without running the write side.
/// `row_cache` opts index-satisfied page queries into the engine's
/// query row cache (`Some(self)` from `Hako::query_with_cancel`); the
/// probe contract is the point read's — version read, then exact match.
pub(crate) fn execute_with_cancel(
&self,
storage_arc: Arc<RwLock<StorageEngine>>,
indexes: &IndexManager,
mut plan: QueryPlan,
cancel: Option<&CancelToken>,
row_cache: Option<&crate::engine::engine::Hako>,
) -> Result<Vec<(String, RowRef)>> {
let _inflight = InflightGuard::take();
Self::check_cancel(cancel)?;
// Fused residual-filter page path.
//
// Eligible only when the scan is the whole ordered stream (no page was
// pushed into it), the predicates are not already index-satisfied, and
// every predicate has a canonical byte key. Then one walk suffices:
// test bytes, count matches, apply offset, decode the page winners.
// Everything else falls through to the unchanged pipeline below.
if !plan.raw && Self::residual_filter_eligible(&plan) {
if let Some(page) =
self.execute_scan_filter_decode(storage_arc.clone(), indexes, &plan, cancel)?
{
return Ok(page);
}
}
// 1. PHASE 1: INDEX SCAN
// Fetch physical pointers from the RAM Index
let mut keys_from_index = {
// ponytail: lock-wait sample — query scans blocked here are
// queued behind the writer (same mixed r/w signal as get).
let t_lock = std::time::Instant::now();
let storage = storage_arc.read().unwrap();
crate::engine::engine::LOCK_STATS.read_wait_ns.fetch_add(t_lock.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
crate::engine::engine::LOCK_STATS.read_acqs.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.execute_single_scan(
&storage,
indexes,
&plan.scan,
&plan.collection,
plan.scan_limit,
plan.offset,
)?
};
if keys_from_index.is_empty() && Self::index_may_hide_xtype(&plan) {
// Exact-key index buckets miss cross-type values (stored Int
// vs String filter) while the semantic compare would hit —
// the DHP `passw` hole. The planner routes ambiguous values
// to unions, but float textual forms, stale entries, or a
// planner miss can still land here empty. Redo as a full
// sweep WITH verification (flip the trust flag: the sweep
// must re-check, the index proved nothing). Only the
// ambiguous class pays this, and only when empty — same-type
// misses keep index speed. No limit pushdown on the redo
// (verification may drop rows); downstream truncates.
let storage = storage_arc.read().unwrap();
keys_from_index = self.execute_single_scan(
&storage,
indexes,
&ScanType::FullCollection,
&plan.collection,
None,
plan.offset,
)?;
plan.scan = ScanType::FullCollection;
plan.filters_satisfied_by_index = false;
}
Self::check_cancel(cancel)?;
if keys_from_index.is_empty() {
return Ok(Vec::new());
}
// 2. PHASE 2: Limit / Offset
// ponytail: v0.7.2 hard-coded this to 0 which silently dropped the
// user's offset for FullCollection and every other scan that didn't
// apply it internally. SortedKeys above already applied offset via
// sorted_key_range, so its skip path is a no-op (`0`).
let offset_to_apply_later = match plan.scan {
ScanType::SortedKeys { .. } => 0,
_ => plan.offset.unwrap_or(0),
};
let doc_count = keys_from_index.len();
// --- TOPN FAST LANE: unsatisfied ORDER BY + LIMIT, no cursor bounds.
// Full scans used to decode every doc + full sort + truncate (~10ms
// per 2000 docs). The heap keeps limit+offset candidates by sort
// keys pulled from views (no full decode); only the final page
// decodes. Cursor shapes keep the legacy path (bounds need the
// contract predicate; the gateway post-filters them anyway).
// Guard: limit >= scanned rows means no eviction is possible — the
// heap would be pure overhead, so those keep the legacy full sort
// (deep offsets with small limits still qualify: skipping is cheap,
// decoding the skipped prefix is not).
let topn = !plan.order_by.is_empty()
&& !plan.order_by_satisfied
&& !plan.has_cursor_bounds
&& matches!(plan.limit, Some(l) if l < keys_from_index.len());
if topn {
return Ok(self
.execute_topn(storage_arc, &plan, keys_from_index, cancel)?
.into_iter()
.map(|(id, doc)| (id, RowRef::Owned(doc)))
.collect());
}
// --- EARLY TERMINATION (issue #22): unordered (or order-satisfied)
// scans with bounded need stop at the page. Output-identical to
// full scan + truncate (scan-order prefix); cursor-bounded shapes
// keep the legacy full path (post-filters could drop rows).
let early_need: Option<usize> = match (
plan.limit,
plan.order_by.is_empty() || plan.order_by_satisfied,
plan.has_cursor_bounds,
) {
(Some(l), true, false) => Some(l + plan.offset.unwrap_or(0)),
_ => None,
};
// --- THE FAST PATH: satisfied scans skip the heavy machinery ---
// Bypasses physical sorting, String re-clones, rayon dispatch, and
// HashMap recreation overhead. Small queries always qualify
// (<= 250 rows); satisfied scans up to the sequential cap decode in
// scan order (that IS the result); bigger satisfied scans go
// parallel below. Unordered/unfiltered shapes keep the general path.
// ponytail: 2000 rows x ~1us decode ~= 2ms — past that, rayon earns
// its dispatch. Typical pages (<= 1000) stay sequential.
const SATISFIED_SEQUENTIAL_CAP: usize = 2000;
if doc_count <= 250
|| ((plan.order_by_satisfied && plan.filters_satisfied_by_index)
&& doc_count <= SATISFIED_SEQUENTIAL_CAP)
{
let storage_guard = storage_arc.read().unwrap();
let blob_manager = storage_guard.blob_manager.as_ref();
let optimized_plan = crate::query::executor::worker::prepare_optimized_plan(&plan);
let mut results = Vec::with_capacity(doc_count);
// ponytail: shared decode helper for both byte sources below.
// Decodes skeletons ONLY — blob inflation happens once below,
// concurrently across all rows (positional blob reads are
// thread-safe). With plan.defer_blobs the placeholders are
// returned as-is; resolve later per doc if needed.
let defer = plan.defer_blobs;
// Row cache (Q1, #142): small index-satisfied pages of full
// (non-projected, non-deferred) documents ride the point-read
// contract. Hit replaces the byte fetch + decode with one deep
// clone; a miss populates while the page budget lasts and only
// for link-free rows (the par-inflate pass below must see the
// same skeleton the cache would serve). Big scans keep the
// cache off — residency effects on Scan_fwd(all) measured in
// the study — and matcher/filtered rows never qualify.
let hako = row_cache.filter(|_| {
doc_count <= 250
&& plan.filters_satisfied_by_index
&& !defer
&& plan.projection.is_empty()
});
let collection = plan.collection.as_str();
// Populate budget: the page the query returns (limit+offset), at
// most 250. Unbounded small scans use the scan itself.
let cache_budget = std::cell::Cell::new(early_need.unwrap_or(250).min(250));
let proj_prefixes = crate::document::value::projection_prefixes(&plan.projection);
let push_row =
|id: String,
bytes: &[u8],
populate: Option<(&crate::engine::engine::Hako, u64)>,
results: &mut Vec<(String, RowRef)>| {
if !plan.projection.is_empty() {
// issue #234: selective decode; row cache is gated off for projections.
if let Some(doc) = crate::query::executor::worker::unified_match_projected_doc(&id, bytes, &optimized_plan, &proj_prefixes) {
results.push((id, RowRef::Owned(doc)));
}
} else if plan.filters_satisfied_by_index {
if let Some(doc) = HakoDoc::decode(bytes) {
if let Some((hk, ver)) = populate {
if !crate::query::executor::worker::doc_has_links(&doc) {
hk.row_cache_insert(collection, &id, ver, &doc);
}
}
results.push((id, RowRef::Owned(doc)));
}
} else if let Some(doc) = crate::query::executor::worker::unified_match_decode(&id, bytes, &optimized_plan) {
results.push((id, RowRef::Owned(doc)));
}
};
for (id, ptr) in keys_from_index {
Self::check_cancel(cancel)?;
// Row-cache probe first: a hit linearizes at the version
// check (same as get_arc) and skips the storage read and
// the decode entirely — the shared Arc leaves the cache
// untouched (zero-copy row, Q3). A miss remembers the
// version so the decode below can populate under it.
let mut populate = None;
if let Some(hk) = hako {
if let Some(ver) = hk.current_version(&id) {
if let Some(cached) = hk.probe_row_cache(collection, &id, ver) {
results.push((id, RowRef::Shared(cached)));
continue;
}
if cache_budget.get() > 0 {
cache_budget.set(cache_budget.get() - 1);
populate = Some((hk, ver));
}
}
}
// ponytail: Inlined bytes are Arc-shared — decode borrows the
// shared buffer instead of cloning ~1KB per row. The owned Arc
// keeps the buffer alive, so no guard lifetime is involved.
match ptr {
Pointer::Inlined(shared) => push_row(id, &shared, populate, &mut results),
other => {
// ponytail: shared read (see Inlined arm above).
if let Ok(Some(bytes)) = storage_guard.read_pointer_shared(&other) {
push_row(id, &bytes, populate, &mut results);
}
}
}
// Early termination: the page is full (see above for why
// the prefix is output-identical).
if let Some(need) = early_need {
if results.len() >= need {
break;
}
}
}
Self::check_cancel(cancel)?;
// ponytail: parallel blob inflation. Skeletons are all decoded
// above; resolve every BlobLink concurrently (positional preads
// are thread-safe, no shared state). Sequential 20x50KB disk
// reads serialize on I/O latency; concurrent reads queue in the
// OS. Link-free results (the common small-doc case) skip the
// pass via one branchy scan — no rayon dispatch, no per-doc
// overhead, same speed as before.
if !defer {
if let Some(bm) = blob_manager {
use rayon::prelude::*;
use crate::query::executor::worker::{doc_has_links, inflate_blobs};
// Shared rows are link-free by the populate gate; only
// owned rows can carry links (and they mutate in place —
// no Arc::make_mut, no COW copy).
if results.iter().any(|(_, row)| matches!(row, RowRef::Owned(d) if doc_has_links(d))) {
results.par_iter_mut().for_each(|(_, row)| {
if let RowRef::Owned(doc) = row {
let _ = inflate_blobs(doc, bm);
}
});
}
}
}
// 6. PHASE 6: FINAL SORTING & SLICING
Self::check_cancel(cancel)?;
if !plan.order_by_satisfied && !plan.order_by.is_empty() {
results.sort_by(|(id_a, row_a), (id_b, row_b)| {
let (doc_a, doc_b) = (row_a.doc(), row_b.doc());
for order in &plan.order_by {
let cmp = match order.field.as_str() {
"id" => id_a.cmp(id_b),
"_time" => doc_a._time.cmp(&doc_b._time),
_ => doc_a.get_path(&order.field).cmp(&doc_b.get_path(&order.field)),
};
if cmp != std::cmp::Ordering::Equal {
return if order.ascending { cmp } else { cmp.reverse() };
}
}
std::cmp::Ordering::Equal
});
}
if offset_to_apply_later > 0 {
results = results.into_iter().skip(offset_to_apply_later).collect();
}
if let Some(limit) = plan.limit {
results.truncate(limit);
}
return Ok(results);
}
// Large satisfied scans (> SEQUENTIAL cap below): same skip-the-
// machinery deal, but decode in parallel. Staged as (id, shared
// bytes) under one guard, then order-preserving par-decode — no
// String re-clones, no restore-order map. Without this, big
// satisfied scans would fall into phases 3-6 and regress vs the
// old rayon path they used to take.
if plan.order_by_satisfied && plan.filters_satisfied_by_index {
return Ok(self
.execute_satisfied_parallel(
storage_arc,
indexes,
plan,
keys_from_index,
cancel,
)?
.into_iter()
.map(|(id, doc)| (id, RowRef::Owned(doc)))
.collect());
}
// 3. PHASE 3: PHYSICAL SORT (The "Sweep" optimization)
// Record logical position to restore order later
let mut work_items: Vec<(usize, String, Pointer)> = keys_from_index
.into_iter()
.enumerate()
.map(|(i, (k, v))| (i, k, v))
.collect();
// Sort by file offset to ensure sequential disk reads (minimizes seek time)
work_items.sort_by_key(|(_, _, ptr)| match ptr {
Pointer::Segment { offset, .. } => *offset,
Pointer::Blob { offset, .. } => *offset,
Pointer::Inlined(_) | Pointer::BlobPending(_) | Pointer::BlobPendingData { .. } => 0,
_ => 0,
});
let mut docs_to_fetch: Vec<(String, Pointer)> = work_items
.iter()
.map(|(_, k, p)| (k.clone(), p.clone()))
.collect();
// Early-termination probe (issue #22): unordered (or order-
// satisfied), bounded need, no cursor bounds → scan the first
// PROBE_ROWS sequentially. A full page here skips the parallel
// machinery below entirely; otherwise the remainder proceeds
// normally and merges in scan order. Output-identical either
// way (scan-order prefix); bounded regret when sparse (one
// sequential probe window, then full parallelism as today).
const PROBE_ROWS: usize = 2000;
Self::check_cancel(cancel)?;
let mut probe_results: Vec<(String, HakoDoc)> = Vec::new();
if let Some(need) = early_need {
if need < docs_to_fetch.len() {
let probe_len = PROBE_ROWS.min(docs_to_fetch.len());
let probe_rows: Vec<(String, Pointer)> =
docs_to_fetch.drain(..probe_len).collect();
probe_results = run_task(QueryTask {
docs: probe_rows,
plan: plan.clone(),
storage: Some(storage_arc.clone()),
});
}
}
// 4. PHASE 4: ADAPTIVE WORKER DISPATCH
Self::check_cancel(cancel)?;
// Probe already full: drop the remainder, the page is complete.
if let Some(need) = early_need {
if probe_results.len() >= need {
docs_to_fetch.clear();
}
}
let doc_count = docs_to_fetch.len();
// Decide how many workers to use based on result set density
// Threshold: 1 worker per 150 documents, capped by global config.
let target_workers = match doc_count {
0..=150 => 1, // Small set: Stay on current thread (Fairness to Get)
151..=500 => 2, // Medium: Parallelize across 2 cores
_ => self.workers, // Large: Full system power
}
.min(self.workers)
.max(1);
let tasks = shard_tasks(
docs_to_fetch,
target_workers,
plan.clone(),
Some(storage_arc.clone()),
);
let processed_docs: Vec<(String, HakoDoc)> = if target_workers == 1 {
// SHORT-CIRCUIT: Avoid Rayon task-scheduling overhead for small results.
// This ensures a query for 50 docs is as fast as 50 individual Get calls.
let mut out = Vec::new();
for task in tasks {
Self::check_cancel(cancel)?;
out.extend(run_task(task));
}
out
} else {
// PARALLEL PATH: Use full CPU power for heavy workloads
let out = tasks
.into_par_iter()
.flat_map(run_task)
.collect();
Self::check_cancel(cancel)?;
out
};
// 5. PHASE 5: LOGICAL ORDER RESTORATION
// ponytail: single-worker output is already in work_items order
// (tasks stay ordered, flat_map preserves) — the HashMap round-trip
// below (2 hashes/row) only exists for parallel completion order.
let mut results: Vec<(String, HakoDoc)> = if target_workers == 1 {
processed_docs
} else {
let mut processed_map: HashMap<String, HakoDoc> = processed_docs.into_iter().collect();
let mut ordered_results = Vec::with_capacity(doc_count);
for (original_pos, key, _) in work_items {
if let Some(doc) = processed_map.remove(&key) {
ordered_results.push((original_pos, key, doc));
}
}
// Restore the order provided by the index (or original insertion order)
ordered_results.sort_by_key(|(pos, _, _)| *pos);
ordered_results
.into_iter()
.map(|(_, k, d)| (k, d))
.collect()
};
// Probe prefix first (scan order), parallel remainder after —
// together exactly the scan-order sequence truncation expects.
if !probe_results.is_empty() {
let mut combined = std::mem::take(&mut probe_results);
combined.extend(results);
results = combined;
}
// 6. PHASE 6: FINAL SORTING & SLICING
Self::check_cancel(cancel)?;
// Manual sort if the Index couldn't satisfy the order_by clause
if !plan.order_by_satisfied && !plan.order_by.is_empty() {
results.sort_by(|(id_a, doc_a), (id_b, doc_b)| {
for order in &plan.order_by {
let cmp = match order.field.as_str() {
"id" => id_a.cmp(id_b),
"_time" => doc_a._time.cmp(&doc_b._time),
_ => {
// Dotted ORDER BY (hakodb#71 F2) rides the fetch
// hook; single segments behave like `get`.
let av = doc_a.get_path(&order.field);
let bv = doc_b.get_path(&order.field);
av.cmp(&bv)
}
};
if cmp != std::cmp::Ordering::Equal {
return if order.ascending { cmp } else { cmp.reverse() };
}
}
std::cmp::Ordering::Equal
});
}
// Apply final Offset/Limit for non-indexed queries
if offset_to_apply_later > 0 {
results = results.into_iter().skip(offset_to_apply_later).collect();
}
if let Some(limit) = plan.limit {
results.truncate(limit);
}
Ok(results
.into_iter()
.map(|(id, doc)| (id, RowRef::Owned(doc)))
.collect())
}
/// TopN heap for unsatisfied ORDER BY + LIMIT (see the hook in
/// [`Self::execute`]). Scan order in, globally-correct top page out:
///
/// - Key-only scan: sort keys come from [`HakoDocView`] (header `_time`,
/// id compare, single-field view pull) — never a full decode, except
/// the final page. Filter matching is view-based too, or skipped when
/// the scan already constrained to matches (same trust as the fast path).
/// - Exact parity with the legacy full stable sort: the heap orders by
/// (keys…, scan-seq), and a stable sort is exactly (keys…, input-seq).
/// Same scan order in → identical page out, ties included.
/// - Corrupt rows (view ok, full decode fails) drop at fetch like the
/// legacy paths drop undecodables; offset applies over successes.
/// Storage writes validated docs, so this is bitrot-only territory.
fn execute_topn(
&self,
storage_arc: Arc<RwLock<StorageEngine>>,
plan: &QueryPlan,
keys: Vec<(String, Pointer)>,
cancel: Option<&CancelToken>,
) -> Result<Vec<(String, HakoDoc)>> {
let limit = plan.limit.unwrap_or(usize::MAX);
let offset = plan.offset.unwrap_or(0);
let k = limit.saturating_add(offset);
TOPN_RUNS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if k == 0 {
return Ok(Vec::new());
}
let orders = &plan.order_by;
let need_match = !plan.filters.is_empty() || !plan.or_groups.is_empty();
let trust_scan = plan.filters_satisfied_by_index;
let storage = storage_arc.read().unwrap();
// Max-heap of the K best so far: peek is the worst kept; a better
// arrival evicts it. (NOT Reverse: that would peak the best and
// freeze the heap on the first K scanned.)
let mut heap: BinaryHeap<TopItem> = BinaryHeap::new();
for (seq, (id, ptr)) in keys.iter().enumerate() {
Self::check_cancel(cancel)?;
let Some(shared) = storage.read_pointer_shared(ptr)? else {
continue;
};
let bytes: &[u8] = &shared;
let Some(view) = HakoDocView::new(bytes) else {
continue;
};
if need_match && !trust_scan && !matches_filters_view(id, bytes, plan) {
continue;
}
let entry = TopEntry {
keys: top_keys(&view, orders),
seq,
id: id.clone(),
ptr: ptr.clone(),
};
let item = TopItem { entry, orders };
if heap.len() < k {
heap.push(item);
} else if let Some(worst) = heap.peek() {
if item < *worst {
heap.pop();
heap.push(item);
}
}
}
// Best-first, then offset over successes + take limit (mirrors the
// legacy slice order: offset first, then limit).
let mut entries: Vec<TopEntry> =
heap.into_iter().map(|item| item.entry).collect();
entries.sort_by(|a, b| cmp_top(a, b, orders));
let blob_manager = storage.blob_manager.as_ref();
Self::check_cancel(cancel)?;
let mut out = Vec::new();
let mut skipped = 0usize;
let proj_prefixes = crate::document::value::projection_prefixes(&plan.projection);
for e in entries {
// ponytail: decode lazily in order; corrupt rows drop and the
// page backfills from the heap remainder (same rows the legacy
// full-decode-then-sort would have kept). Shared read: decode
// borrows, no per-row clone.
let bytes = match storage.read_pointer_shared(&e.ptr)? {
Some(b) => b,
None => continue,
};
let Some(doc) = (if plan.projection.is_empty() {
HakoDoc::decode(&bytes)
} else {
crate::query::executor::worker::unified_match_projected_doc(&e.id, &bytes, plan, &proj_prefixes)
}) else {
continue;
};
if skipped < offset {
skipped += 1;
continue;
}
if out.len() >= limit {
break;
}
out.push((e.id, doc));
}
// Blob inflation for the final page only (mirrors the fast path).
if !plan.defer_blobs {
if let Some(bm) = blob_manager {
use crate::query::executor::worker::{doc_has_links, inflate_blobs};
if out.iter().any(|(_, doc)| doc_has_links(doc)) {
out.par_iter_mut().for_each(|(_, doc)| {
let _ = inflate_blobs(doc, bm);
});
}
}
}
Ok(out)
}
/// Decode only the page winners.
///
/// The caller has already established: bounded page, no pushed scan page
/// (`scan_limit == None`), not index-satisfied, scan order == output order,
/// no cursor bounds, no projection and no OR/elemMatch matcher passes.
///
/// This lane walks the scan in order, tests the predicates on borrowed
/// bytes against keys compiled once per call and calls `HakoDoc::decode`
/// only for rows that pass the predicate; `offset` is counted over those
/// decoded matches, and `limit` bounds the page. The old pipeline decoded
/// every candidate before testing it, rejected or not; the returned row
/// set and order are identical.
///
/// Returns `None` if the keys cannot cover the whole conjunct list (the
/// generic matcher keeps the row) so the caller falls back to the legacy
/// pipeline with unchanged semantics.
pub(crate) fn execute_scan_filter_decode(
&self,
storage_arc: Arc<RwLock<StorageEngine>>,
indexes: &IndexManager,
plan: &QueryPlan,
cancel: Option<&CancelToken>,
) -> Result<Option<Vec<(String, RowRef)>>> {
let Some(limit) = plan.limit else { return Ok(None) };
if !Self::residual_filter_eligible(plan) {
return Ok(None);
}
let offset = plan.offset.unwrap_or(0);
if limit == 0 {
return Ok(Some(Vec::new()));
}
// The comparison values are query constants. Encode them once for this
// page; the gate is the same `Eq` + byte-safe rule the per-row fast lane
// applies, so an ineligible predicate declines here instead of taking a
// different semantic path.
let Some(keys) = crate::query::match_key::MatchKeys::compile_fast_eq(&plan.filters) else {
return Ok(None);
};
Self::check_cancel(cancel)?;
let optimized_plan = crate::query::executor::worker::prepare_optimized_plan(plan);
let defer = plan.defer_blobs;
let storage = storage_arc.read().unwrap();
let blob_manager = storage.blob_manager.as_ref();
// The scan source cannot page early (the caller excluded `scan_limit`),
// so this is the only page cut: over matches, in scan order. Walking the
// source directly means the rejected prefix is never materialised as
// `(String, Pointer)` pairs.
let mut out: Vec<(String, RowRef)> = Vec::with_capacity(limit.min(256));
let mut matched = 0usize;
self.visit_scan_rows(
&storage,
indexes,
&plan.scan,
&plan.collection,
&mut |id, ptr| {
Self::check_cancel(cancel)?;
// Match the historical fused-lane skip contract: a read
// failure or missing pointer drops the row, never shortens
// the page with an error.
let Some(shared) = storage.read_pointer_shared(ptr).ok().flatten() else {
return Ok(true);
};
let bytes: &[u8] = &shared;
if !crate::query::executor::worker::matches_filters_view_cached(
id,
bytes,
&optimized_plan,
&keys,
) {
return Ok(true);
}
// Decode before the offset count so a corrupt row keeps the legacy
// backfill behaviour: it is dropped everywhere, never counted as a
// page winner, and never shortens the page.
let Some(doc) = HakoDoc::decode(bytes) else {
return Ok(true);
};
matched += 1;
if matched <= offset {
return Ok(true);
}
out.push((id.to_string(), RowRef::Owned(doc)));
Ok(out.len() < limit)
},
)?;
if !defer {
if let Some(bm) = blob_manager {
use rayon::prelude::*;
use crate::query::executor::worker::{doc_has_links, inflate_blobs};
if out
.iter()
.any(|(_, row)| matches!(row, RowRef::Owned(d) if doc_has_links(d)))
{
out.par_iter_mut().for_each(|(_, row)| {
if let RowRef::Owned(doc) = row {
let _ = inflate_blobs(doc, bm);
}
});
}
}
}
Ok(Some(out))
}
/// Raw scan: phase-1 index walk with byte materialization — no decode,
/// no filter re-verify, no blob inflation, no rayon. `Inlined` docs
/// share the RAM buffer (Arc bump, zero copies); segment/blob pointers
/// do one positional read each. Returns storage-encoded bytes: opaque
/// and version-scoped — decode with `HakoDoc::decode`, do not
/// persist or compare across versions.
///
/// Historical raw scans require index-satisfied filters AND ordering
/// (raw cannot match or sort without decoding) — otherwise `QueryError`.
/// The residual-filter extension below is the one exception: when the
/// whole ordered stream is available and every predicate is a byte-safe
/// `Eq`, the borrowed encoding can decide the match, so the page is
/// emitted without materialising a document. Single-threaded by design:
/// the work is Arc bumps + memcmps, rayon dispatch would only add
/// overhead. Scan order is preserved (no re-sort).
pub fn execute_raw(
&self,
storage_arc: Arc<RwLock<StorageEngine>>,
indexes: &IndexManager,
plan: QueryPlan,
) -> Result<Vec<(String, Arc<Vec<u8>>)>> {
let _inflight = InflightGuard::take();
// Residual byte egress: the decoded fused lane established that a
// byte-safe predicate can be decided on the borrowed encoding. This
// arm does the same, but stops at the encoded bytes: no owned document
// is built for either a rejected candidate or a page winner. It only
// engages when the whole ordered stream is available (no pushed scan
// page) and scan order is output order, so row order/offset/limit are
// unchanged. Everything else keeps the historical raw contract below.
if Self::raw_residual_eligible(&plan) {
if plan.limit == Some(0) {
return Ok(Vec::new());
}
let Some(keys) = crate::query::match_key::MatchKeys::compile_fast_eq(&plan.filters)
else {
return Err(crate::error::HakoError::QueryError(
"query requires index-satisfied filters (decode to match)".into(),
));
};
let optimized = crate::query::executor::worker::prepare_optimized_plan(&plan);
let offset = plan.offset.unwrap_or(0);
let limit = plan.limit;
let storage = storage_arc.read().unwrap();
let mut out: Vec<(String, Arc<Vec<u8>>)> =
Vec::with_capacity(limit.unwrap_or(0).min(256));
let mut matched = 0usize;
self.visit_scan_rows(
&storage,
indexes,
&plan.scan,
&plan.collection,
&mut |id, ptr| {
let Some(bytes) = storage.read_pointer_shared(ptr).ok().flatten() else {
return Ok(true);
};
if !crate::query::executor::worker::matches_filters_view_cached(
id,
&bytes,
&optimized,
&keys,
) {
return Ok(true);
}
matched += 1;
if matched <= offset {
return Ok(true);
}
out.push((id.to_string(), bytes));
Ok(limit.map(|l| out.len() < l).unwrap_or(true))
},
)?;
return Ok(out);
}
Self::check_index_satisfied(&plan)?;
let storage = storage_arc.read().unwrap();
let found = self.execute_single_scan(
&storage,
indexes,
&plan.scan,
&plan.collection,
plan.scan_limit,
plan.offset,
)?;
let mut out = Vec::with_capacity(found.len());
for (id, ptr) in found {
// ponytail: shared read — Inlined hands back the live Arc, no
// per-row copy; Deleted defensively skipped (phase 1 already
// filters it).
if let Some(bytes) = storage.read_pointer_shared(&ptr)? {
out.push((id, bytes));
}
}
// Phase-6-style truncation for scans that didn't pre-apply it
// (mirrors `execute`: SortedKeys pre-applied offset via the range).
let skip = match plan.scan {
ScanType::SortedKeys { .. } => 0,
_ => plan.offset.unwrap_or(0),
};
if skip > 0 {
out = out.into_iter().skip(skip).collect();
}
if let Some(limit) = plan.limit {
out.truncate(limit);
}
Ok(out)
}
/// True when [`Self::execute_raw`] may satisfy residual filters on the
/// borrowed encoding instead of refusing: whole ordered stream, byte-safe
/// `Eq` predicates, and a scan kind the lazy walker can drive. Mirrors the
/// decoded fused-page gate; the two lanes must accept the same shapes.
fn raw_residual_eligible(plan: &QueryPlan) -> bool {
Self::residual_filter_eligible(plan)
}
/// The shape gate shared by the decoded fused page and the residual raw
/// egress. Both must admit exactly the same plans: then a row that JSON
/// emits is a row `query()` would have decoded, in the same order.
fn residual_filter_eligible(plan: &QueryPlan) -> bool {
plan.scan_limit.is_none()
&& !plan.filters.is_empty()
&& plan.projection.is_empty()
&& !plan.filters_satisfied_by_index
&& plan.or_groups.is_empty()
&& plan.elem_match.is_empty()
&& !plan.has_cursor_bounds
&& (plan.order_by.is_empty() || plan.order_by_satisfied)
// SortedKeys applies offset inside the scan (raw rows); the fused
// lanes apply it over matches. Keep the legacy contract there.
&& !(matches!(plan.scan, ScanType::SortedKeys { .. })
&& plan.offset.unwrap_or(0) > 0)
&& crate::query::match_key::can_preverify(&plan.filters)
&& Self::residual_scan_supported(&plan.scan)
}
/// Scan kinds the borrow-scoped fused walk can drive. The legacy
/// materialising pipeline remains the fallback for every other kind
/// (union, FTS, vector, traverse, cursor): semantics are unchanged.
fn residual_scan_supported(scan: &ScanType) -> bool {
matches!(
scan,
ScanType::FullCollection
| ScanType::SortedKeys { .. }
| ScanType::SecondaryIndex { .. }
| ScanType::SecondaryIndexRange { .. }
| ScanType::CompositeIndex { .. }
| ScanType::CompositeIndexRange { .. }
)
}
/// Borrow-scoped walk over the scan sources the fused residual lane can
/// drive. No `Vec<(String, Pointer)>` is built: each row is presented to
/// `visit` in exactly the order [`Self::execute_single_scan`] would have
/// returned it, and `Ok(false)` stops the walk immediately.
fn visit_scan_rows<F>(
&self,
storage: &StorageEngine,
indexes: &IndexManager,
scan: &ScanType,
collection: &str,
visit: &mut F,
) -> Result<bool>
where
F: FnMut(&str, &Pointer) -> Result<bool>,
{
match scan {
ScanType::FullCollection => {
for (key, ptr) in storage.index.iter() {
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
if !visit(key.as_str(), ptr)? {
return Ok(false);
}
}
Ok(true)
}
ScanType::SortedKeys { start_key, start_exclusive, reverse } => {
let (start, end) = Self::sorted_walk_bounds(
storage,
start_key.as_deref(),
*start_exclusive,
None,
None,
*reverse,
);
if *reverse {
for key in storage.sorted_keys[start..end].iter().rev() {
let Some(ptr) = storage.index.get(key) else { continue };
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
if !visit(key.as_str(), ptr)? {
return Ok(false);
}
}
} else {
for key in &storage.sorted_keys[start..end] {
let Some(ptr) = storage.index.get(key) else { continue };
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
if !visit(key.as_str(), ptr)? {
return Ok(false);
}
}
}
Ok(true)
}
ScanType::SecondaryIndex { field, value } => {
if let Some(sec_map) = indexes.secondary.get(collection) {
if let Some(index) = sec_map.get(field) {
if let Some(doc_ids) = index.get_map().get(value) {
for doc_id in doc_ids {
let key = Self::make_key(collection, doc_id);
let Some(ptr) = storage.index.get(&key) else { continue };
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
if !visit(key.as_str(), ptr)? {
return Ok(false);
}
}
}
}
}
Ok(true)
}
ScanType::SecondaryIndexRange { field, start, end, reverse } => {
if let Some(sec_map) = indexes.secondary.get(collection) {
if let Some(index) = sec_map.get(field) {
let range_iter = index.get_map().range((start.clone(), end.clone()));
if *reverse {
for (_, ids) in range_iter.rev() {
for doc_id in ids.iter().rev() {
let Some(ptr) = storage.index.get(doc_id.as_ref()) else {
continue;
};
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
if !visit(doc_id.as_ref(), ptr)? {
return Ok(false);
}
}
}
} else {
for (_, ids) in range_iter {
for doc_id in ids {
let Some(ptr) = storage.index.get(doc_id.as_ref()) else {
continue;
};
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
if !visit(doc_id.as_ref(), ptr)? {
return Ok(false);
}
}
}
}
}
}
Ok(true)
}
ScanType::CompositeIndex { index_id, values, reverse, .. } => {
if let Some(idx) = indexes.composite.get(*index_id) {
let range = crate::index::composite::range_builder::build_prefix_range(
&idx.definition,
values,
);
let iter = idx.tree.range((
std::ops::Bound::Included(range.start),
std::ops::Bound::Included(range.end),
));
if *reverse {
for (_, doc_id) in iter.rev() {
let Some(ptr) = storage.index.get(doc_id.as_ref()) else {
continue;
};
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
if !visit(doc_id.as_ref(), ptr)? {
return Ok(false);
}
}
} else {
for (_, doc_id) in iter {
let Some(ptr) = storage.index.get(doc_id.as_ref()) else {
continue;
};
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
if !visit(doc_id.as_ref(), ptr)? {
return Ok(false);
}
}
}
}
Ok(true)
}
ScanType::CompositeIndexRange { index_id, ranges, reverse } => {
if let Some(idx) = indexes.composite.get(*index_id) {
for (start_bound, end_bound) in ranges {
let iter = idx.tree.range((start_bound.clone(), end_bound.clone()));
if *reverse {
for (_, doc_id) in iter.rev() {
let Some(ptr) = storage.index.get(doc_id.as_ref()) else {
continue;
};
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
if !visit(doc_id.as_ref(), ptr)? {
return Ok(false);
}
}
} else {
for (_, doc_id) in iter {
let Some(ptr) = storage.index.get(doc_id.as_ref()) else {
continue;
};
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
if !visit(doc_id.as_ref(), ptr)? {
return Ok(false);
}
}
}
}
}
Ok(true)
}
_ => Ok(false),
}
}
/// Zero-alloc scan walk: the engine lends each row (`&str` id borrowed
/// from the sorted key vec, bytes borrowed from the resident Arc or a
/// single reused scratch buffer) and the caller decides per row.
/// Returning `false` stops early. Returns rows visited.
///
/// Currently covers the SortedKeys fast path (order-by-id / no-order
/// scans — the hot shape); anything else is `QueryError`, extend
/// arm-by-arm on demand. Same index-satisfied requirements as raw.
///
/// CONTRACT: the storage read lock is held for the whole walk, so the
/// callback MUST NOT re-enter the engine (a waiting writer + second
/// read-lock attempt deadlocks, same as nested MDBX txns). Keep it
/// short: count, hash, copy, compare — not queries.
pub fn execute_walk<F>(
&self,
storage_arc: Arc<RwLock<StorageEngine>>,
indexes: &IndexManager,
plan: QueryPlan,
callback: &mut F,
) -> Result<usize>
where
F: FnMut(&str, &[u8]) -> bool,
{
let _inflight = InflightGuard::take();
Self::check_index_satisfied(&plan)?;
// ponytail: reserved for the non-SortedKeys arms when the walk
// grows beyond order-by-id (underscore until then, not dead).
let _ = indexes;
let (reverse, start_key, start_exclusive) = match &plan.scan {
ScanType::SortedKeys { start_key, start_exclusive, reverse } => {
(*reverse, start_key.clone(), *start_exclusive)
}
_ => {
return Err(crate::error::HakoError::QueryError(
"walk supports SortedKeys scans only (order by id)".into(),
))
}
};
// The guard lives to the end of the function — every borrow below
// (keys, resident Arcs) is covered by it. ponytail: one reused
// scratch buffer for the rare owned reads (segment/blob pointers)
// instead of a Vec per row.
let storage = storage_arc.read().unwrap();
if storage.sorted_keys.is_empty() {
return Ok(0);
}
let (start, end) = Self::sorted_walk_bounds(
&storage,
start_key.as_deref(),
start_exclusive,
plan.offset,
plan.limit,
reverse,
);
let limit = plan.limit.unwrap_or(usize::MAX);
let mut scratch = Vec::new();
Self::drive_sorted_keys(&storage, start, end, reverse, limit, &mut |key, ptr| {
match ptr {
Pointer::Inlined(shared) => Ok(callback(key, shared)),
other => match storage.read_pointer_internal(other, true)? {
Some(bytes) => {
scratch.clear();
scratch.extend_from_slice(&bytes);
Ok(callback(key, &scratch))
}
None => Ok(true),
},
}
})
}
/// View walk: like [`Self::execute_walk`] but lends each row as a
/// `DocView` (lazy per-field reads) instead of raw bytes. Same guards,
/// same driver. Construction validates the framing header; per-field
/// access is bounds-checked and `to_owned_doc` decodes strictly, so
/// corrupt rows surface as empty pulls, never panics.
pub fn execute_walk_view<F>(
&self,
storage_arc: Arc<RwLock<StorageEngine>>,
indexes: &IndexManager,
plan: QueryPlan,
callback: &mut F,
) -> Result<usize>
where
F: FnMut(&str, &DocView) -> bool,
{
let _inflight = InflightGuard::take();
Self::check_index_satisfied(&plan)?;
let _ = indexes;
let (reverse, start_key, start_exclusive) = match &plan.scan {
ScanType::SortedKeys { start_key, start_exclusive, reverse } => {
(*reverse, start_key.clone(), *start_exclusive)
}
_ => {
return Err(crate::error::HakoError::QueryError(
"view walk supports SortedKeys scans only (order by id)".into(),
))
}
};
let storage = storage_arc.read().unwrap();
if storage.sorted_keys.is_empty() {
return Ok(0);
}
let (start, end) = Self::sorted_walk_bounds(
&storage,
start_key.as_deref(),
start_exclusive,
plan.offset,
plan.limit,
reverse,
);
let limit = plan.limit.unwrap_or(usize::MAX);
Self::drive_sorted_keys(&storage, start, end, reverse, limit, &mut |key, ptr| {
let shared = match ptr {
Pointer::Inlined(shared) => Arc::clone(shared),
Pointer::BlobPendingData { data, .. } => Arc::clone(data),
Pointer::BlobPending(doc) => Arc::new(doc.encode()),
Pointer::Deleted { .. } => return Ok(true),
other => match storage.read_pointer_internal(other, true)? {
Some(bytes) => Arc::new(bytes),
None => return Ok(true),
},
};
match DocView::new(shared) {
Some(view) => Ok(callback(key, &view)),
None => Ok(true),
}
})
}
#[inline]
fn make_key(_collection: &str, doc_id: &str) -> String {
doc_id.to_string()
}
/// Bounds for a SortedKeys walk in either direction: binary-search the
/// optional anchor, apply offset from the top, take limit downward.
/// Returns an empty range (never None-shaped) when there is nothing.
fn sorted_walk_bounds(
storage: &StorageEngine,
start_key: Option<&str>,
start_exclusive: bool,
offset: Option<usize>,
limit: Option<usize>,
reverse: bool,
) -> (usize, usize) {
if reverse {
storage
.sorted_key_range_reverse(start_key, start_exclusive, offset, limit)
.unwrap_or((0, 0))
} else {
storage
.sorted_key_range(start_key, start_exclusive, offset, limit)
.unwrap_or((0, 0))
}
}
/// Drives a SortedKeys slice in either direction, invoking `f` per live
/// (non-deleted, indexed) row. `f` returns false to stop early. Returns
/// rows PRESENTED to `f`. Shared by the byte walk and the view walk —
/// one loop to maintain instead of per-arm duplicates.
fn drive_sorted_keys<F>(
storage: &StorageEngine,
start: usize,
end: usize,
reverse: bool,
limit: usize,
f: &mut F,
) -> Result<usize>
where
F: FnMut(&str, &Pointer) -> Result<bool>,
{
let mut visited = 0usize;
if reverse {
for key in storage.sorted_keys[start..end].iter().rev() {
if visited >= limit {
break;
}
let Some(ptr) = storage.index.get(key) else { continue };
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
visited += 1;
if !f(key.as_str(), ptr)? {
return Ok(visited);
}
}
} else {
for key in &storage.sorted_keys[start..end] {
if visited >= limit {
break;
}
let Some(ptr) = storage.index.get(key) else { continue };
if matches!(ptr, Pointer::Deleted { .. }) {
continue;
}
visited += 1;
if !f(key.as_str(), ptr)? {
return Ok(visited);
}
}
}
Ok(visited)
}
/// Parallel twin of the satisfied fast path above, for scans past the
/// sequential cap. Stage 1 resolves pointers to shared bytes under one
/// guard (Arc bumps, zero copies for inlined); stage 2 is an
/// order-preserving parallel decode; stage 3 reuses the standard blob
/// inflation + truncation tail. Filters are index-satisfied by the
/// caller gate, so no per-row re-verify.
fn execute_satisfied_parallel(
&self,
storage_arc: Arc<RwLock<StorageEngine>>,
_indexes: &IndexManager,
plan: QueryPlan,
keys_from_index: Vec<(String, Pointer)>,
cancel: Option<&CancelToken>,
) -> Result<Vec<(String, HakoDoc)>> {
use crate::query::executor::worker::{doc_has_links, inflate_blobs};
let (staged, blob_manager) = {
let storage = storage_arc.read().unwrap();
let mut v = Vec::with_capacity(keys_from_index.len());
for (id, ptr) in keys_from_index {
Self::check_cancel(cancel)?;
if let Some(bytes) = storage.read_pointer_shared(&ptr)? {
v.push((id, bytes));
}
}
(v, storage.blob_manager.clone())
};
// Early termination for satisfied scans (issue #22): every staged
// row matches by construction, so truncating pointers pre-decode
// is output-identical. Unordered-or-satisfied only, no cursors
// (same rule as the sequential lane).
let early_all_match = (plan.order_by.is_empty() || plan.order_by_satisfied)
&& !plan.has_cursor_bounds;
let mut staged = staged;
if early_all_match {
if let Some(l) = plan.limit {
let need = l + plan.offset.unwrap_or(0);
if staged.len() > need {
staged.truncate(need);
}
}
}
Self::check_cancel(cancel)?;
let mut results: Vec<(String, HakoDoc)> = staged
.into_par_iter()
.filter_map(|(id, bytes)| HakoDoc::decode(&bytes).map(|doc| (id, doc)))
.collect();
Self::check_cancel(cancel)?;
if !plan.defer_blobs {
if let Some(bm) = blob_manager.as_ref() {
if results.iter().any(|(_, doc)| doc_has_links(doc)) {
results.par_iter_mut().for_each(|(_, doc)| {
let _ = inflate_blobs(doc, bm);
});
}
}
}
let offset_to_apply_later = match plan.scan {
ScanType::SortedKeys { .. } => 0,
_ => plan.offset.unwrap_or(0),
};
if offset_to_apply_later > 0 {
results = results.into_iter().skip(offset_to_apply_later).collect();
}
if let Some(limit) = plan.limit {
results.truncate(limit);
}
Ok(results)
}
/// Candidate ids for an aggregation whose equality predicates are exactly
/// the leading fields of a composite index and every aggregate target is
/// one of the remaining fields. Returns `None` for every other shape so
/// the historical secondary-index and scan paths stay authoritative.
fn composite_covering_aggregation_ids(
indexes: &IndexManager,
plan: &QueryPlan,
targets: &[&str],
) -> Option<Vec<std::sync::Arc<str>>> {
if plan.filters.is_empty()
|| plan.has_cursor_bounds
|| !plan.or_groups.is_empty()
|| !plan.elem_match.is_empty()
|| !plan.projection.is_empty()
{
return None;
}
let mut values: HashMap<&str, crate::document::value::Value> = HashMap::new();
for filter in &plan.filters {
if filter.op != crate::query::filter::Operator::Eq {
return None;
}
values.insert(filter.field.as_str(), filter.value.clone());
}
let prefix_len = values.len();
for idx in indexes.indexes_for_collection(&plan.collection) {
if idx.definition.fields.len() <= prefix_len {
continue;
}
let fields: Vec<&str> = idx
.definition
.fields
.iter()
.map(|f| f.field.as_str())
.collect();
if !fields[..prefix_len]
.iter()
.all(|f| values.contains_key(*f))
{
continue;
}
if !targets
.iter()
.all(|target| fields[prefix_len..].contains(target))
{
continue;
}
let prefix_values: Vec<crate::document::value::Value> = fields[..prefix_len]
.iter()
.map(|f| values.get(*f).expect("checked above").clone())
.collect();
let range =
crate::index::composite::range_builder::build_prefix_range(&idx.definition, &prefix_values);
let ids = idx
.tree
.range((
std::ops::Bound::Included(range.start),
std::ops::Bound::Included(range.end),
))
.map(|(_, doc_id)| doc_id.clone())
.collect();
return Some(ids);
}
None
}
pub fn execute_aggregation(
&self,
storage_arc: Arc<RwLock<StorageEngine>>,
indexes: &IndexManager,
plan: QueryPlan,
ops: &[AggregateOp],
) -> Result<HashMap<String, f64>> {
let _inflight = InflightGuard::take();
// --- 1. UNIFIED FAST PATH (Index-Only Aggregation) ---
// No OR groups and simple Equality filters. A composite range can
// cover several operations at once; the per-op secondary paths below
// remain single-operation only.
if plan.or_groups.is_empty() {
// Determine if the operation is eligible for RAM-only execution
let mut filter_ids: Option<hashbrown::HashSet<std::sync::Arc<str>>> = None;
let mut can_use_fast_path = true;
// Step A: Attempt to resolve matching Document IDs using RAM indexes
for filter in &plan.filters {
if filter.op == crate::query::filter::Operator::Eq {
let val_bytes = crate::index::index_key::encode_scalar(&filter.value);
if let Some(ids) =
indexes.lookup_secondary(&plan.collection, &filter.field, &val_bytes)
{
let id_set: hashbrown::HashSet<_> = ids.into_iter().collect();
if let Some(ref mut existing_set) = filter_ids {
existing_set.retain(|id| id_set.contains(id));
} else {
filter_ids = Some(id_set);
}
} else {
can_use_fast_path = false;
break;
}
} else {
can_use_fast_path = false;
break;
}
}
if can_use_fast_path {
// Composite covering lane: an Eq prefix plus every aggregate
// field lives in one index, so one bounded walk covers all
// operations and no document is materialised.
let targets: Vec<&str> = ops
.iter()
.filter_map(|op| match op {
AggregateOp::Sum(field)
| AggregateOp::Avg(field)
| AggregateOp::Min(field)
| AggregateOp::Max(field) => Some(field.as_str()),
AggregateOp::Count => None,
})
.collect();
if !targets.is_empty() {
if let Some(ids) =
Self::composite_covering_aggregation_ids(indexes, &plan, &targets)
{
let storage = storage_arc.read().unwrap();
let mut res: HashMap<String, f64> = HashMap::new();
for id in ids {
let Some(ptr) = storage.index.get(id.as_ref()) else { continue };
let Some(bytes) = storage.read_pointer_shared(ptr).ok().flatten()
else { continue };
let Some(view) = HakoDocView::new(&bytes) else { continue };
for op in ops {
match op {
AggregateOp::Count => {
*res.entry("count".to_string()).or_insert(0.0) += 1.0;
}
AggregateOp::Sum(target)
| AggregateOp::Avg(target)
| AggregateOp::Min(target)
| AggregateOp::Max(target) => {
let Some((_, tag, data)) =
view.iter().find(|(key, _, _)| *key == target)
else { continue };
let Some(num) = BorrowedValue { tag, data }.as_f64()
else { continue };
match op {
AggregateOp::Sum(_) => {
*res.entry(format!("sum_{target}")).or_insert(0.0)
+= num;
}
AggregateOp::Avg(_) => {
*res.entry(format!("avg_tmp_{target}")).or_insert(0.0)
+= num;
*res.entry(format!("avg_cnt_{target}")).or_insert(0.0)
+= 1.0;
}
AggregateOp::Min(_) => {
let entry = res
.entry(format!("min_{target}"))
.or_insert(num);
*entry = entry.min(num);
}
AggregateOp::Max(_) => {
let entry = res
.entry(format!("max_{target}"))
.or_insert(num);
*entry = entry.max(num);
}
AggregateOp::Count => unreachable!(),
}
}
}
}
}
for target in &targets {
let tmp_key = format!("avg_tmp_{target}");
if let Some(sum) = res.remove(&tmp_key) {
let count = res
.remove(&format!("avg_cnt_{target}"))
.unwrap_or(0.0);
if count > 0.0 {
res.insert(format!("avg_{target}"), sum / count);
}
}
}
return Ok(res);
}
}
if ops.len() == 1 {
let op = &ops[0];
match op {
// CASE 1: COUNT
AggregateOp::Count => {
let count = if plan.filters.is_empty() {
// Instant O(1) count from storage metadata if no filters
let storage = storage_arc.read().unwrap();
storage.count_prefix("")
} else {
// O(Index) count from intersection results
filter_ids.map(|ids| ids.len()).unwrap_or(0)
};
let mut res = HashMap::new();
res.insert("count".to_string(), count as f64);
return Ok(res);
}
// CASE 2: SUM / AVG
AggregateOp::Sum(target_field) | AggregateOp::Avg(target_field) => {
if let Some(sec_map) = indexes.secondary.get(&plan.collection) {
if let Some(index) = sec_map.get(target_field) {
let mut total_sum = 0.0;
let mut total_count = 0.0;
let is_avg = matches!(op, AggregateOp::Avg(_));
for (val_bytes, doc_ids) in index.get_map() {
if let Some(val) = decode_scalar_as_f64(val_bytes) {
let match_count = if let Some(ref allowed_ids) = filter_ids
{
doc_ids
.iter()
.filter(|id| allowed_ids.contains(*id))
.count()
} else {
doc_ids.len()
};
total_sum += val * (match_count as f64);
total_count += match_count as f64;
}
}
let mut res = HashMap::new();
if is_avg {
res.insert(
format!("avg_{}", target_field),
if total_count > 0.0 {
total_sum / total_count
} else {
0.0
},
);
} else {
res.insert(format!("sum_{}", target_field), total_sum);
}
return Ok(res);
}
}
}
// CASE 3: MIN / MAX
AggregateOp::Min(target_field) | AggregateOp::Max(target_field) => {
if let Some(sec_map) = indexes.secondary.get(&plan.collection) {
if let Some(index) = sec_map.get(target_field) {
let is_min = matches!(op, AggregateOp::Min(_));
let mut best: Option<f64> = None;
for (val_bytes, doc_ids) in index.get_map() {
let match_count = if let Some(ref allowed_ids) = filter_ids {
doc_ids
.iter()
.filter(|id| allowed_ids.contains(*id))
.count()
} else {
doc_ids.len()
};
if match_count == 0 {
continue;
}
if let Some(val) = decode_scalar_as_f64(val_bytes) {
best = Some(match best {
Some(b) if is_min => b.min(val),
Some(b) => b.max(val),
None => val,
});
}
}
let mut res = HashMap::new();
if let Some(v) = best {
let key = if is_min { "min" } else { "max" };
res.insert(format!("{}_{}", key, target_field), v);
}
return Ok(res);
}
}
}
}
}
}
}
// --- 2. SLOW PATH (Physical Disk Sweep) ---
// Fallback for complex queries, multiple ops, or range filters
let docs: Vec<(String, Pointer)> = {
let storage = storage_arc.read().unwrap();
self.execute_single_scan(
&storage,
indexes,
&plan.scan,
&plan.collection,
plan.scan_limit,
None,
)?
};
let doc_count = docs.len();
let mut final_results: HashMap<String, f64> = HashMap::new();
let process_task = |task: QueryTask, thread_ops: Vec<AggregateOp>| -> HashMap<String, f64> {
let mut partial_results = HashMap::new();
let storage_engine = task.storage.as_ref().unwrap().read().unwrap();
for (id, pointer) in task.docs {
// ponytail: shared read — view matching borrows, no clone.
if let Ok(Some(bytes)) = storage_engine.read_pointer_shared(&pointer) {
// Check if the document matches the WHERE filters first
if matches_filters_view(&id, &bytes, &task.plan) {
if let Some(view) = HakoDocView::new(&bytes) {
for op in &thread_ops {
match op {
AggregateOp::Count => {
*partial_results.entry("count".to_string()).or_insert(0.0) += 1.0;
}
AggregateOp::Sum(field) | AggregateOp::Avg(field) => {
// IMPROVEMENT: Instead of failing if index is missing,
// we scan the document view for the field.
if let Some((_, tag, data)) = view.iter().find(|(k, _, _)| k == field) {
let borrowed = BorrowedValue { tag, data };
if let Some(num) = borrowed.as_f64() {
let key = if matches!(op, AggregateOp::Sum(_)) {
format!("sum_{}", field)
} else {
format!("avg_tmp_{}", field)
};
*partial_results.entry(key).or_insert(0.0) += num;
if matches!(op, AggregateOp::Avg(_)) {
*partial_results.entry(format!("avg_cnt_{}", field)).or_insert(0.0) += 1.0;
}
}
}
}
AggregateOp::Min(field) | AggregateOp::Max(field) => {
if let Some((_, tag, data)) = view.iter().find(|(k, _, _)| k == field) {
let borrowed = BorrowedValue { tag, data };
if let Some(num) = borrowed.as_f64() {
let is_min = matches!(op, AggregateOp::Min(_));
let key = if is_min {
format!("min_{}", field)
} else {
format!("max_{}", field)
};
let entry = partial_results.entry(key).or_insert(num);
if is_min {
*entry = entry.min(num);
} else {
*entry = entry.max(num);
}
}
}
}
}
}
}
}
}
}
partial_results
};
// --- 3. PARALLEL EXECUTION ---
if doc_count < 1000 || self.workers <= 1 {
let task = QueryTask {
docs,
plan: plan.clone(),
storage: Some(storage_arc.clone()),
};
final_results = process_task(task, ops.to_vec());
} else {
let optimal_workers = self.workers.min((doc_count / 500).max(1));
let tasks = shard_tasks(
docs,
optimal_workers,
plan.clone(),
Some(storage_arc.clone()),
);
let (tx, rx) = std::sync::mpsc::channel();
for task in tasks {
let thread_tx = tx.clone();
let thread_ops = ops.to_vec();
thread::spawn(move || {
let _ = thread_tx.send(process_task(task, thread_ops));
});
}
drop(tx);
while let Ok(partial) = rx.recv() {
for (k, v) in partial {
// min/max are foldable idempotent, not additive.
if k.starts_with("min_") {
let e = final_results.entry(k).or_insert(v);
*e = e.min(v);
} else if k.starts_with("max_") {
let e = final_results.entry(k).or_insert(v);
*e = e.max(v);
} else {
*final_results.entry(k).or_insert(0.0) += v;
}
}
}
}
// [4. Final Processing for Averages]
let keys: Vec<String> = final_results.keys().cloned().collect();
for k in keys {
if let Some(field) = k.strip_prefix("avg_tmp_") {
let sum = final_results.remove(&k).unwrap_or(0.0);
let count = final_results
.remove(&format!("avg_cnt_{}", field))
.unwrap_or(1.0);
final_results.insert(
format!("avg_{}", field),
if count > 0.0 { sum / count } else { 0.0 },
);
}
}
// Ensure default keys exist for requested operations
for op in ops {
match op {
AggregateOp::Count => {
final_results.entry("count".to_string()).or_insert(0.0);
}
AggregateOp::Sum(field) => {
final_results.entry(format!("sum_{}", field)).or_insert(0.0);
}
AggregateOp::Avg(field) => {
final_results.entry(format!("avg_{}", field)).or_insert(0.0);
}
// min/max over an empty set has no value: the key stays absent.
AggregateOp::Min(_) | AggregateOp::Max(_) => {}
}
}
Ok(final_results)
}
#[allow(clippy::type_complexity)]
/// True when a projected page can use the residual byte filter: the scan
/// is the whole ordered stream, predicates are byte-safe Eq, and scan
/// order is output order. Projection is allowed here; only the page
/// winners are decoded into projected fields.
fn projected_residual_eligible(plan: &QueryPlan) -> bool {
plan.scan_limit.is_none()
&& !plan.filters.is_empty()
&& !plan.filters_satisfied_by_index
&& plan.or_groups.is_empty()
&& plan.elem_match.is_empty()
&& !plan.has_cursor_bounds
&& (plan.order_by.is_empty() || plan.order_by_satisfied)
&& !(matches!(plan.scan, ScanType::SortedKeys { .. }) && plan.offset.unwrap_or(0) > 0)
&& crate::query::match_key::can_preverify(&plan.filters)
&& Self::residual_scan_supported(&plan.scan)
}
#[allow(clippy::type_complexity)]
pub fn execute_projected(
&self,
storage_arc: Arc<RwLock<StorageEngine>>,
indexes: &IndexManager,
mut plan: QueryPlan,
cancel: Option<&CancelToken>,
) -> Result<Vec<(String, Vec<(String, Value)>)>> {
let _inflight = InflightGuard::take();
Self::check_cancel(cancel)?;
// issue #237: ORDER BY fields must be decoded even when they are
// outside the caller projection, otherwise the post-scan sort below
// compares missing values. Keep the original list to prune them at
// the end. _time is a header pseudo-field emitted by the decoder.
let original_projection = plan.projection.clone();
for order in &plan.order_by {
let field = order.field.as_str();
if !plan.projection.iter().any(|p| p == field) {
plan.projection.push(field.to_string());
}
}
// Residual byte filter for projected pages: reject candidates on
// borrowed bytes, count offset/limit over survivors, and decode only
// the winners' projection fields. Unsupported shapes fall through.
if Self::projected_residual_eligible(&plan) {
if let Some(keys) = crate::query::match_key::MatchKeys::compile_fast_eq(&plan.filters) {
let optimized = crate::query::executor::worker::prepare_optimized_plan(&plan);
let offset = plan.offset.unwrap_or(0);
let limit = plan.limit;
let storage = storage_arc.read().unwrap();
let mut winners: Vec<(String, Arc<Vec<u8>>)> =
Vec::with_capacity(limit.unwrap_or(0).min(256));
let mut matched = 0usize;
self.visit_scan_rows(
&storage,
indexes,
&plan.scan,
&plan.collection,
&mut |id, ptr| {
Self::check_cancel(cancel)?;
let Some(bytes) = storage.read_pointer_shared(ptr).ok().flatten() else {
return Ok(true);
};
if !crate::query::executor::worker::matches_filters_view_cached(
id, &bytes, &optimized, &keys,
) {
return Ok(true);
}
matched += 1;
if matched <= offset {
return Ok(true);
}
winners.push((id.to_string(), bytes));
Ok(limit.map(|l| winners.len() < l).unwrap_or(true))
},
)?;
let prefixes = crate::document::value::projection_prefixes(&original_projection);
let blob_manager = storage.blob_manager.as_ref();
let mut projected = Vec::with_capacity(winners.len());
for (id, bytes) in winners {
let Some(mut fields) = crate::query::executor::worker::unified_match_projected(
&id, &bytes, &optimized,
) else { continue };
if !plan.defer_blobs {
if let Some(bm) = blob_manager {
for (_, value) in fields.iter_mut() {
if let Value::BlobLink { offset, len } = *value {
*value = crate::query::executor::worker::resolve_single_blob_in_worker(
bm, offset, len,
);
}
}
}
}
fields.retain(|(key, _)| prefixes.contains(&key.as_str()));
projected.push((id, fields));
}
return Ok(projected);
}
}
let docs: Vec<(String, Pointer)> = {
// Explicitly set the type
let storage = storage_arc.read().unwrap();
self.execute_single_scan(
&storage,
indexes,
&plan.scan,
&plan.collection,
plan.scan_limit,
plan.offset,
)?
};
let mut results: Vec<(String, Vec<(String, Value)>)> = Vec::new();
// let doc_count = docs.len();
// if doc_count < 1000 || self.workers <= 1 {
// let task = QueryTask {
// docs,
// plan: plan.clone(),
// storage: Some(storage_arc.clone()),
// };
// results = run_task_projected(task);
// } else {
// let optimal_workers = self.workers.min((doc_count / 500).max(1));
// let tasks = shard_tasks(
// docs,
// optimal_workers,
// plan.clone(),
// Some(storage_arc.clone()),
// );
// let mut handles = Vec::new();
// for task in tasks {
// handles.push(thread::spawn(move || run_task_projected(task)));
// }
// for handle in handles {
// results.extend(handle.join().unwrap_or_default());
// }
// }
// Apply Offset/Limit to Index results early if satisfied
let mut docs_to_process = docs;
let mut offset_to_apply_later = plan.offset.unwrap_or(0);
if plan.order_by_satisfied && offset_to_apply_later > 0 {
let skip = offset_to_apply_later.min(docs_to_process.len());
docs_to_process.drain(0..skip);
offset_to_apply_later = 0;
}
if plan.order_by_satisfied && plan.filters_satisfied_by_index {
if let Some(limit) = plan.limit { docs_to_process.truncate(limit); }
}
let doc_count = docs_to_process.len();
let prefixes = crate::document::value::projection_prefixes(&original_projection);
let covering = plan.covering_projection();
// TOPN parity: when ORDER BY is not served by the scan and the page
// is much smaller than the candidate set, reuse execute_topn — it
// decodes only the final page. Skip when a covering index exists:
// an index-only read is cheaper than any heap, and we must not lose
// the F6 zero-decode lane (issue #237 follow-up).
let topn = !plan.order_by.is_empty()
&& !plan.order_by_satisfied
&& !plan.has_cursor_bounds
&& covering.is_none()
&& matches!(plan.limit, Some(l) if l < doc_count);
if topn {
let rows = self.execute_topn(storage_arc, &plan, docs_to_process, None)?;
return Ok(rows.into_iter().map(|(id, doc)| {
let time = doc._time;
let mut fields: Vec<(String, Value)> = doc.fields.into_iter()
.filter(|(key, _)| prefixes.contains(&key.as_ref()))
.map(|(key, value)| (key.to_string(), value))
.collect();
if original_projection.iter().any(|p| p == "_time") {
fields.push(("_time".to_string(), Value::Int(time)));
}
(id, fields)
}).collect());
}
// --- INDEX-ONLY (covering) PATH: hakodb#71 F6 -------------------
// Filters, order and projection are all covered by the composite
// point scan, so every field value is already in the plan: no
// document is read or decoded. Rows still come from the scan
// (liveness/tombstones included).
if let Some(mut template) = covering {
{
let storage_guard = storage_arc.read().unwrap();
if let Some(ref manager) = storage_guard.blob_manager {
for (_, val) in template.iter_mut() {
if let Value::BlobLink { offset, len } = *val {
*val = crate::query::executor::worker::resolve_single_blob_in_worker(manager, offset, len);
}
}
}
}
for (id, _pointer) in docs_to_process {
Self::check_cancel(cancel)?;
results.push((id, template.clone()));
}
} else if doc_count <= 250 {
// --- FAST PATH ---
let storage_guard = storage_arc.read().unwrap();
let blob_manager = storage_guard.blob_manager.clone();
let optimized_plan = crate::query::executor::worker::prepare_optimized_plan(&plan);
for (id, pointer) in docs_to_process {
Self::check_cancel(cancel)?;
// ponytail: shared read — projected match borrows, no clone.
if let Ok(Some(bytes)) = storage_guard.read_pointer_shared(&pointer) {
if let Some(mut fields) = crate::query::executor::worker::unified_match_projected(&id, &bytes, &optimized_plan) {
if let Some(ref manager) = blob_manager {
for (_, val) in fields.iter_mut() {
if let Value::BlobLink { offset, len } = *val {
*val = crate::query::executor::worker::resolve_single_blob_in_worker(manager, offset, len);
}
}
}
results.push((id, fields));
}
}
}
} else {
Self::check_cancel(cancel)?;
// SLOW PATH (Rayon Tasks)
let optimal_workers = self.workers.min((doc_count / 500).max(1));
let tasks = shard_tasks(docs_to_process, optimal_workers, plan.clone(), Some(storage_arc.clone()));
let mut handles = Vec::new();
for task in tasks { handles.push(thread::spawn(move || run_task_projected(task))); }
for handle in handles { results.extend(handle.join().unwrap_or_default()); }
}
if !plan.order_by_satisfied && !plan.order_by.is_empty() {
results.sort_by(|(id_a, fields_a), (id_b, fields_b)| {
for order in &plan.order_by {
let cmp = match order.field.as_str() {
"id" => id_a.cmp(id_b),
"_time" => { /* handle time if projected */ id_a.cmp(id_b) } // Placeholder
_ => {
let av = fields_a.iter().find(|(k, _)| k == &order.field).map(|(_, v)| v);
let bv = fields_b.iter().find(|(k, _)| k == &order.field).map(|(_, v)| v);
av.cmp(&bv)
}
};
if cmp != std::cmp::Ordering::Equal {
return if order.ascending { cmp } else { cmp.reverse() };
}
}
std::cmp::Ordering::Equal
});
}
// let mut final_results = if let Some(offset) = plan.offset {
// results.into_iter().skip(offset).collect()
// } else {
// results
// };
// if let Some(limit) = plan.limit {
// final_results.truncate(limit);
// }
let mut final_results = if offset_to_apply_later > 0 {
results.into_iter().skip(offset_to_apply_later).collect()
} else { results };
if let Some(limit) = plan.limit { final_results.truncate(limit); }
if !original_projection.is_empty() {
for (_, fields) in final_results.iter_mut() {
fields.retain(|(key, _)| prefixes.contains(&key.as_str()));
}
}
Ok(final_results)
}
/// VectorKnn batch scorer (#156 Phase D): decode each candidate doc,
/// apply `extra` filters (missing field rejects — unified-match rule),
/// decode the doc vector, exact `distance()`. Rows already scored are
/// skipped via `seen` (one shared set across widening stages + the
/// fallback, so every id decodes/filters exactly once). Returns how
/// many rows were added.
/// Shared `extra`-filter check (#192): every filter must pass on the
/// decoded doc; a missing field rejects (unified-match rule). Used by
/// the scoring path and the filtered-traversal admission predicate.
#[allow(clippy::too_many_arguments)] // private; the param set is the scoring context
fn score_vector_batch(
storage: &StorageEngine,
pairs: &[(String, Pointer)],
field: &str,
qv: &[f32],
metric: crate::index::vector::Metric,
extra: &[crate::query::filter::Filter],
seen: &mut std::collections::HashSet<String>,
scored: &mut Vec<(f64, String, Pointer)>,
) -> usize {
use crate::index::vector::{decode_f32s, distance};
let mut added = 0usize;
for (key, ptr) in pairs {
// G3 (#168): cross-stage dedup rides only the hybrid path —
// widening + fallback stages exist only when `extra` filters
// are present, so an unfiltered single-stage call would clone
// + hash every candidate key for a set that is never read
// again (measured −12% on the degenerate Vec lane; −31% on
// 1000-doc rejects).
if !extra.is_empty() && !seen.insert(key.clone()) {
continue;
}
// ponytail: shared read — scoring decodes from the live Arc,
// no per-row clone (same rule as every other scan arm now).
let bytes = match storage.read_pointer_shared(ptr) {
Ok(Some(b)) => b,
_ => continue,
};
let doc = match HakoDoc::decode(&bytes) {
Some(d) => d,
None => continue,
};
if !crate::query::filter::extras_match(&doc, extra) {
continue;
}
// Missing / non-binary / dim-mismatched fields can't be
// ranked — skip (fail-closed, same rule as the planner).
// Blob-resident embeddings resolve single (durable: the
// indexer drains the flush queue before queries read).
let dv = match doc.get(field) {
Some(Value::Binary(b)) => decode_f32s(b).unwrap_or_default(),
Some(Value::BlobLink { offset, len }) => {
match storage.blob_manager.as_deref() {
Some(bm) => match crate::query::executor::worker::resolve_single_blob_in_worker(bm, *offset, *len) {
Value::Binary(b) => decode_f32s(&b).unwrap_or_default(),
_ => continue,
},
None => continue,
}
}
_ => continue,
};
if dv.len() != qv.len() {
continue;
}
scored.push((distance(metric, qv, &dv), key.clone(), ptr.clone()));
added += 1;
}
added
}
/// ANN-candidate id list → live (id, pointer) pairs: deleted or
/// vanished candidates drop (same liveness rule as every scan arm).
fn knn_pairs_from_ids(storage: &StorageEngine, ids: &[String]) -> Vec<(String, Pointer)> {
ids.iter()
.filter_map(|id| {
storage.index.get(id.as_str()).and_then(|ptr| {
if matches!(ptr, Pointer::Deleted { .. }) {
None
} else {
Some((id.clone(), ptr.clone()))
}
})
})
.collect()
}
/// Every live key — the exact fallback candidate set.
fn knn_pairs_brute(storage: &StorageEngine) -> Vec<(String, Pointer)> {
storage
.index
.iter()
.filter(|(_, p)| !matches!(p, Pointer::Deleted { .. }))
.map(|(k, p)| (k.clone(), p.clone()))
.collect()
}
fn execute_single_scan(
&self,
storage: &StorageEngine,
indexes: &IndexManager,
scan: &ScanType,
collection: &str,
limit: Option<usize>,
offset: Option<usize>,
) -> Result<Vec<(String, Pointer)>> {
// Change from Vec<u8> to Pointer
let max_ids = limit.unwrap_or(usize::MAX);
match scan {
ScanType::FullCollection => {
Ok(storage
.index
.iter()
// FIX: Added check to skip Pointer::Deleted
.filter(|(_, p)| !matches!(p, Pointer::Deleted { .. }))
.take(max_ids)
.map(|(k, p)| (k.clone(), p.clone()))
.collect())
}
// Direct slice over sorted_keys. Used by the planner for queries
// that order by `id` (or no order at all) and have no usable
// filter index — turns offset-of-N from O(N) into O(log N + limit).
ScanType::SortedKeys { start_key, start_exclusive, reverse } => {
let total = storage.sorted_keys.len();
if total == 0 {
return Ok(Vec::new());
}
// Descending, optional upper cursor bound (planner
// guarantee): binary-search the anchor, walk backward —
// O(log N + limit), no sort pass needed.
if *reverse {
let (start, end) = match storage.sorted_key_range_reverse(
start_key.as_deref(),
*start_exclusive,
offset,
limit,
) {
Some(r) => r,
None => return Ok(Vec::new()),
};
let mut out = Vec::with_capacity(end.saturating_sub(start));
for key in storage.sorted_keys[start..end].iter().rev() {
if let Some(ptr) = storage.index.get(key) {
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((key.clone(), ptr.clone()));
if out.len() >= max_ids { break; }
}
}
}
return Ok(out);
}
// Ascending, optional cursor bound: binary search + slice.
let (start_pos, end_pos) = match storage.sorted_key_range(
start_key.as_deref(),
*start_exclusive,
offset,
limit,
) {
Some(r) => r,
None => return Ok(Vec::new()),
};
let mut out = Vec::with_capacity(end_pos.saturating_sub(start_pos));
for key in &storage.sorted_keys[start_pos..end_pos] {
if let Some(ptr) = storage.index.get(key) {
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((key.clone(), ptr.clone()));
if out.len() >= max_ids { break; }
}
}
}
Ok(out)
}
ScanType::SecondaryIndex { field, value } => {
// let mut out = Vec::new();
// if let Some(sec_map) = indexes.secondary.get(collection) {
// if let Some(index) = sec_map.get(field) {
// for doc_id in index.range_scan(value, value).iter() {
// let key = Self::make_key(collection, doc_id);
// if let Some(ptr) = storage.index.get(&key) {
// // FIX: Ensure we don't return a deleted pointer found in secondary index
// if !matches!(ptr, Pointer::Deleted { .. }) {
// out.push((key, ptr.clone()));
// if out.len() >= max_ids {
// break;
// }
// }
// }
// }
// }
// }
// Ok(out)
let mut out = Vec::new();
if let Some(sec_map) = indexes.secondary.get(collection) {
if let Some(index) = sec_map.get(field) {
// CRITICAL FIX: Direct `get()` on the BTreeMap prevents array allocation
if let Some(doc_ids) = index.get_map().get(value) {
for doc_id in doc_ids {
let key = Self::make_key(collection, doc_id);
if let Some(ptr) = storage.index.get(&key) {
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((key, ptr.clone()));
if out.len() >= max_ids {
break;
}
}
}
}
}
}
}
Ok(out)
}
ScanType::CompositeIndex {
index_id,
fields: _,
values,
reverse,
} => {
let mut out = Vec::new();
if let Some(idx) = indexes.composite.get(*index_id) {
let range = crate::index::composite::range_builder::build_prefix_range(&idx.definition, values);
// ponytail: bounded walk — the old code materialized the
// ENTIRE prefix (e.g. 666 keys for a hot value) and only
// then truncated via max_ids below.
let doc_ids = idx.range_scan_limit(&range.start, &range.end, max_ids, *reverse);
// ponytail: range_scan_limit already yields rows in scan
// order (ascending, or descending when reverse), so no
// re-reversal — the old code rev'd because it always
// materialized ascending first.
for doc_id in doc_ids.iter() {
if let Some(ptr) = storage.index.get(doc_id.as_ref()) {
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((doc_id.to_string(), ptr.clone()));
}
}
if out.len() >= max_ids { break; }
}
}
Ok(out)
}
ScanType::CompositeIndexRange { index_id, ranges, reverse } => {
let mut out = Vec::new();
if let Some(idx) = indexes.composite.get(*index_id) {
for (start_bound, end_bound) in ranges {
let iter = idx.tree.range((start_bound.clone(), end_bound.clone()));
if *reverse {
for (_, doc_id) in iter.rev() {
if let Some(ptr) = storage.index.get(doc_id.as_ref()) {
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((doc_id.to_string(), ptr.clone()));
}
}
if out.len() >= max_ids { break; }
}
} else {
for (_, doc_id) in iter {
if let Some(ptr) = storage.index.get(doc_id.as_ref()) {
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((doc_id.to_string(), ptr.clone()));
}
}
if out.len() >= max_ids { break; }
}
}
if out.len() >= max_ids { break; }
}
}
Ok(out)
}
// ScanType::SecondaryIndexRange { field, start, end, reverse } => {
// let mut out = Vec::new();
// if let Some(sec_map) = indexes.secondary.get(collection) {
// if let Some(index) = sec_map.get(field) {
// let range_iter = index.get_map().range((start.clone(), end.clone()));
// // CRITICAL FIX: Iterate lazily
// if *reverse {
// for (_, ids) in range_iter.rev() {
// for doc_id in ids {
// if let Some(ptr) = storage.index.get(doc_id) {
// if !matches!(ptr, Pointer::Deleted { .. }) {
// out.push((doc_id.clone(), ptr.clone()));
// if out.len() >= max_ids { break; }
// }
// }
// }
// if out.len() >= max_ids { break; }
// }
// } else {
// for (_, ids) in range_iter {
// for doc_id in ids {
// if let Some(ptr) = storage.index.get(doc_id) {
// if !matches!(ptr, Pointer::Deleted { .. }) {
// out.push((doc_id.clone(), ptr.clone()));
// if out.len() >= max_ids { break; }
// }
// }
// }
// if out.len() >= max_ids { break; }
// }
// }
// }
// }
// Ok(out)
// }
ScanType::SecondaryIndexRange { field, start, end, reverse } => {
let mut out = Vec::new();
if let Some(sec_map) = indexes.secondary.get(collection) {
if let Some(index) = sec_map.get(field) {
let range_iter = index.get_map().range((start.clone(), end.clone()));
if *reverse {
for (_, ids) in range_iter.rev() {
for doc_id in ids.iter().rev() {
if let Some(ptr) = storage.index.get(doc_id.as_ref()) {
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((doc_id.to_string(), ptr.clone()));
if out.len() >= max_ids { break; }
}
}
}
if out.len() >= max_ids { break; }
}
} else {
for (_, ids) in range_iter {
for doc_id in ids {
if let Some(ptr) = storage.index.get(doc_id.as_ref()) {
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((doc_id.to_string(), ptr.clone()));
if out.len() >= max_ids { break; }
}
}
}
if out.len() >= max_ids { break; }
}
}
}
}
Ok(out)
}
ScanType::CursorIndex { index_id, start, end, reverse } => {
let mut out = Vec::new();
if let Some(idx) = indexes.composite.get(*index_id) {
let iter = idx.tree.range((start.clone(), end.clone()));
// CRITICAL FIX: Iterate lazily to prevent massive memory allocation
if *reverse {
for (_, doc_id) in iter.rev() {
if let Some(ptr) = storage.index.get(doc_id.as_ref()) {
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((doc_id.to_string(), ptr.clone()));
if out.len() >= max_ids { break; }
}
}
}
} else {
for (_, doc_id) in iter {
if let Some(ptr) = storage.index.get(doc_id.as_ref()) {
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((doc_id.to_string(), ptr.clone()));
if out.len() >= max_ids { break; }
}
}
}
}
}
Ok(out)
}
ScanType::VectorKnn { field, query, metric, extra } => {
// Two-stage rescore: the search's int8 distances prune to
// rescore_n, then exact rescore orders THOSE. ANN can only
// drop rows, never invent them — recall is gated by the
// duel harness (must hold 0.99). rescore_n always covers
// max_ids (deep pages can't under-fill) and never exceeds
// ef (never rescore more than surfaced). Fallback (no
// complete graph): every live key, exact by construction.
// Hybrid (extra filters): 2-stage (#156 Phase D) — ANN
// over-fetches (×1/×4/×16, widening only on under-fill);
// an exact full-scan fallback can only ADD rows, so the
// served set is never worse than the old brute force.
// Ties break on doc id.
use crate::index::vector::decode_f32s;
let qv = decode_f32s(query).unwrap_or_default();
// ef sizing (P3): int8 graph distances are approximate, so
// over-fetch generously. High dims compound routing error
// per hop (duel: recall 0.62 at D=384/ef128), so the floor
// steps 128→256 at D≥128.
let floor = if qv.len() >= 128 { 256 } else { 128 };
// #141-1: a per-def ef_search override rides the index
// definition (persisted, syncs); None keeps the derived
// formula (max_ids×8, clamped 128/256..20000).
let ef = indexes
.vector
.get(collection)
.and_then(|m| m.get(field))
.and_then(|d| d.ef_search)
.unwrap_or_else(|| max_ids.saturating_mul(8).clamp(floor, 20_000));
let need = max_ids.min(ef);
let rescore_n = need.max((need.saturating_mul(4).max(32)).min(ef));
// ANN gate (#156 Phase D): a complete graph serves both
// unfiltered queries (proven single-stage path, shape
// unchanged) AND filtered ones. #141 rule intact: ANN may
// only drop rows — the exact rescore orders THOSE, and
// the under-fill fallback can only add rows.
let graph = indexes
.hnsw
.get(collection)
.and_then(|m| m.get(field))
.filter(|g| g.complete() && !g.is_empty());
// Filtered traversal (#192): with extra filters, admission
// is gated INSIDE the walk (only matching nodes enter the
// beam/results), so `ef` isn't wasted on doomed candidates
// and selective queries fill without the widening ladder.
// The predicate decodes each newly visited node once
// (cached); the scoring pass re-checks cheaply (same rule,
// same tie-breaks — results identical to post-filter).
let mut allow_cache: std::collections::HashMap<String, bool> =
std::collections::HashMap::new();
let mut allow = |idx: usize| -> bool {
let id = match graph.as_ref() {
Some(g) => g.id_of(idx),
None => return false,
};
*allow_cache
.entry(id.to_string())
.or_insert_with(|| {
let key = Self::make_key(collection, id);
match storage.index.get(&key) {
Some(ptr) if !matches!(ptr, Pointer::Deleted { .. }) => {
match storage.read_pointer_shared(ptr) {
Ok(Some(b)) => HakoDoc::decode(&b)
.map(|d| crate::query::filter::extras_match(&d, extra))
.unwrap_or(false),
_ => false,
}
}
_ => false,
}
})
};
let cand_ids: Option<Vec<String>> = match graph.as_ref() {
Some(g) if extra.is_empty() => Some(
g.search(&qv, ef)
.into_iter()
.take(rescore_n)
.map(|(_, idx)| g.id_of(idx).to_string())
.collect(),
),
Some(g) => Some(
g.search_filtered(&qv, ef, &mut allow)
.into_iter()
.take(ef)
.map(|(_, idx)| g.id_of(idx).to_string())
.collect(),
),
None => None,
};
let pairs: Vec<(String, Pointer)> = match &cand_ids {
Some(ids) => Self::knn_pairs_from_ids(storage, ids),
None => Self::knn_pairs_brute(storage),
};
let mut scored: Vec<(f64, String, Pointer)> = Vec::new();
// One shared `seen` across stages: widened re-searches
// re-surface earlier ids and the fallback must not
// re-score them either — each id decodes/filters once.
let mut seen: std::collections::HashSet<String> =
std::collections::HashSet::new();
Self::score_vector_batch(storage, &pairs, field, &qv, *metric, extra, &mut seen, &mut scored);
// Stage continuation (filtered only): widen ×4/×16 while
// under-filled; ef ≥ graph size or a filled window stops
// it; then one exact full scan if still short — union
// (ANN ∪ brute) with exact rescore = the same top-k the
// brute force alone would produce.
if !extra.is_empty() {
if let Some(g) = graph.as_ref() {
for over in [4usize, 16] {
let stag = ef.saturating_mul(over).min(g.len());
if stag <= ef || scored.len() >= max_ids {
break;
}
// Widening rides the same filtered walk (#192):
// a bigger beam still admits matches only.
let ids: Vec<String> = g
.search_filtered(&qv, stag, &mut allow)
.into_iter()
.take(stag)
.map(|(_, idx)| g.id_of(idx).to_string())
.collect();
let pairs = Self::knn_pairs_from_ids(storage, &ids);
Self::score_vector_batch(storage, &pairs, field, &qv, *metric, extra, &mut seen, &mut scored);
if scored.len() >= max_ids || stag == g.len() {
break;
}
}
if scored.len() < max_ids {
let pairs = Self::knn_pairs_brute(storage);
Self::score_vector_batch(storage, &pairs, field, &qv, *metric, extra, &mut seen, &mut scored);
}
}
}
// NaN-free by construction (zero-norm guards in vector.rs),
// so total_cmp is a true order here.
scored.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
Ok(scored
.into_iter()
.take(max_ids)
.map(|(_, k, p)| (k, p))
.collect())
}
ScanType::InvertedIndex { field, query, prefix } => {
let mut out = Vec::new();
if let Some(fts_map) = indexes.fts.get(collection) {
if let Some(index) = fts_map.get(field) {
let doc_ids = if *prefix {
index.search_prefix(query)
} else {
index.search(query)
};
if let Some(doc_ids) = doc_ids {
for doc_id in doc_ids.iter().take(max_ids) {
let key = Self::make_key(collection, doc_id);
if let Some(ptr) = storage.index.get(&key) {
// out.push((key, ptr.clone()));
if !matches!(ptr, Pointer::Deleted { .. }) {
out.push((key, ptr.clone()));
if out.len() >= max_ids {
break;
}
}
}
}
}
}
}
Ok(out)
}
ScanType::UnionIndex { scans } => {
let mut unique_results = HashMap::new();
for sub_scan in scans {
// Recursively execute sub-scans (Eq lookups for each item in the "IN" array)
let results = self.execute_single_scan(storage, indexes, sub_scan, collection, None, None)?;
for (id, ptr) in results {
unique_results.insert(id, ptr);
}
}
let mut out: Vec<_> = unique_results.into_iter().collect();
// Re-apply limits after union
if let Some(l) = limit { out.truncate(l); }
Ok(out)
}
// Graph BFS crosses collections — the single-shard scan
// paths (projected/raw/walk) cannot run it. Loud error, never
// silent empty: traverse over `query()` (issue #53).
ScanType::Traverse { .. } => {
Err(crate::error::HakoError::Corrupt(
"traverse scans need the decoded query path (use query(), not raw/projected/walk)".into(),
))
}
}
}
}