hakodb 0.18.0

Embedded & Cloud-native Document Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
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)
}

/// 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)>> {
        self.execute_with_cancel(storage_arc, indexes, plan, None)
    }

    /// [`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.
    pub(crate) fn execute_with_cancel(
        &self,
        storage_arc: Arc<RwLock<StorageEngine>>,
        indexes: &IndexManager,
        mut plan: QueryPlan,
        cancel: Option<&CancelToken>,
    ) -> Result<Vec<(String, HakoDoc)>> {
        let _inflight = InflightGuard::take();
        Self::check_cancel(cancel)?;
        // 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 self.execute_topn(storage_arc, &plan, keys_from_index, cancel);
        }

        // --- 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;
            let push_row = |id: String, bytes: &[u8], results: &mut Vec<(String, HakoDoc)>| {
                if plan.filters_satisfied_by_index {
                    if let Some(doc) = HakoDoc::decode(bytes) {
                        results.push((id, doc));
                    }
                } else if let Some(doc) = crate::query::executor::worker::unified_match_decode(&id, bytes, &optimized_plan) {
                    results.push((id, doc));
                }
            };

            for (id, ptr) in keys_from_index {
                Self::check_cancel(cancel)?;
                // 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, &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, &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;
                    if results.iter().any(|(_, doc)| doc_has_links(doc)) {
                        results.par_iter_mut().for_each(|(_, doc)| {
                            let _ = crate::query::executor::worker::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, 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),
                            _ => 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 self.execute_satisfied_parallel(
                storage_arc,
                indexes,
                plan,
                keys_from_index,
                cancel,
            );
        }

        // 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)
    }

    /// 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;
        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) = HakoDoc::decode(&bytes) 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)
    }

    /// 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.
    ///
    /// Requires index-satisfied filters AND ordering (raw cannot match or
    /// sort without decoding) — otherwise `QueryError`. Single-threaded by
    /// design: the work is Arc bumps + memcpys, 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();
        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)
    }

    /// 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)
    }

    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) ---
        // Conditions: Only 1 op, no OR groups, and simple Equality filters
        if ops.len() == 1 && plan.or_groups.is_empty() {
            let op = &ops[0];

            // 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 {
                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);
                            }
                        }
                    }
                }
            }
        }

        // --- 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;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            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 {
                    *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);
                }
            }
        }

        Ok(final_results)
    }

    #[allow(clippy::type_complexity)]
    pub fn execute_projected(
        &self,
        storage_arc: Arc<RwLock<StorageEngine>>,
        indexes: &IndexManager,
        plan: QueryPlan,
    ) -> Result<Vec<(String, Vec<(String, Value)>)>> {
        let _inflight = InflightGuard::take();
        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();

        // --- 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) = plan.covering_projection() {
            {
                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 {
                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 {
                // 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 {
            // 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); }

        Ok(final_results)
    }

    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) always brute-forces: ANN ranks
                // unfiltered, so post-filtering its top-ef could strand
                // matches it never surfaced. Ties break on doc id.
                use crate::index::vector::{decode_f32s, distance};
                use crate::query::filter::compare_values;
                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 };
                let ef = 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));
                let use_ann = extra.is_empty();
                let cand_ids: Option<Vec<String>> = indexes
                    .hnsw
                    .get(collection)
                    .and_then(|m| m.get(field))
                    .filter(|g| use_ann && g.complete() && !g.is_empty())
                    .map(|g| {
                        g.search(&qv, ef)
                            .into_iter()
                            .take(rescore_n)
                            .map(|(_, idx)| g.id_of(idx).to_string())
                            .collect()
                    });
                let pairs: Vec<(String, Pointer)> = match &cand_ids {
                    Some(ids) => 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(),
                    None => storage
                        .index
                        .iter()
                        .filter(|(_, p)| !matches!(p, Pointer::Deleted { .. }))
                        .map(|(k, p)| (k.clone(), p.clone()))
                        .collect(),
                };
                let mut scored: Vec<(f64, String, Pointer)> = Vec::new();
                for (key, ptr) in pairs {
                    // 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,
                    };
                    let mut pass = true;
                    for f in extra {
                        match doc.get(&f.field) {
                            Some(v) => {
                                if !compare_values(v, &f.op, &f.value) {
                                    pass = false;
                                    break;
                                }
                            }
                            // Missing field rejects (same rule as the
                            // unified-match slow path).
                            None => {
                                pass = false;
                                break;
                            }
                        }
                    }
                    if !pass {
                        continue;
                    }
                    // Missing / non-binary / dim-mismatched fields can't be
                    // ranked — skip (fail-closed, same rule as the planner).
                    // Blob-resident embeddings inflate here (durable: the
                    // indexer drains the flush queue before resolving, so
                    // by query time the bytes are on disk; a transient
                    // miss resolves Null and skips — rebuilds converge).
                    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()));
                }
                // 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(),
                ))
            }

        }
    }
}