hakodb 0.23.6

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
use super::filter::{Filter, Operator};
use super::plan::{QueryPlan, ScanType};
use super::query::Query;
use crate::document::value::Value;
use crate::index::composite::definition::SortDirection;
use crate::index::composite::range_builder::build_cursor_range;
use crate::index::composite::range_builder::{
    build_prefix_key, build_prefix_open_end, build_value_key, key_with_upper_sentinel,
};
use crate::index::manager::IndexManager;
use std::ops::Bound; // Required for range definitions

pub struct QueryPlanner;

use crate::index::composite::definition::CompositeIndexDefinition;

impl QueryPlanner {
    /// Filtered (partial) composite-index consistency gate (hakodb#71):
    /// a probe over a filtered index's tree answers ONLY docs matching
    /// the tree's predicate, so the planner may ride it only when the
    /// query implies that predicate — otherwise results would silently
    /// miss non-tree docs. Conservative: every And-group condition must
    /// be pinned by the query's AND conjunction with the exact same
    /// Eq/In-single value; Or-filters and range/other ops are unprovable
    /// (fail-closed → full-scan lanes instead). Runs at plan build only
    /// (plan-cache TTL amortizes it); with ≤8 conditions it is a couple
    /// of nanoseconds — a memo map would cost more than the check.
    fn composite_def_usable(def: &CompositeIndexDefinition, query: &Query) -> bool {
        use crate::query::filter::FilterLogic;
        let Some(group) = &def.filter else { return true };
        if group.logic != FilterLogic::And {
            return false;
        }
        group.filters.iter().all(|cond| {
            query.filters.iter().any(|f| f.field == cond.field && match (&f.op, &cond.op) {
                (Operator::Eq, Operator::Eq) => f.value == cond.value,
                (Operator::In, Operator::Eq) => matches!(
                    &f.value,
                    Value::Array(a) if a.len() == 1 && a[0] == cond.value
                ),
                _ => false,
            })
        })
    }

    pub fn plan(
        query: &Query,        indexes: &IndexManager,
        collection_rows: usize,
        worker_count: usize,
        index_ready: bool,
        vector_ready: bool,
    ) -> QueryPlan {
        if !index_ready {
            // Vector lanes survive pending writer ops: the executor
            // live-filters handles (delete invisibility), so tree lag
            // only lowers recall — never serves ghost rows. FullCollection
            // cannot score Near at all and would serve empty results
            // (vector_hnsw delete_stays_invisible). Still gated on
            // backfill (partial initial build = genuinely bad ANN).
            if vector_ready {
                if let Some(plan) = Self::try_plan_vector(query, indexes) {
                    return plan;
                }
            }
            // The `id`-order SortedKeys slice is index-INDEPENDENT (natural
            // storage key order), so keep it alive even in the not-ready
            // window — otherwise cursor pagination falls back to
            // FullCollection, which ignores cursor bounds (repeated rows,
            // oplog_fuzz page-walk). Everything index-backed stays behind
            // the gate (hakodb#71 BUG-2).
            if let Some(scan) = Self::id_order_sortedkeys(query) {
                return Self::make_plan(query, scan, query.limit, true, true);
            }
            return Self::make_plan(query, ScanType::FullCollection, None, false, false);
        }

        let work_per_thread = collection_rows / worker_count.max(1);
        let use_index_heuristic = work_per_thread > 50;

        // 1. PRIORITY 1: Full-Text Search
        // SAFEGUARD: Skip FTS for 'id' and '_time' as they are never tokenized as text.
        for filter in &query.filters {
            if matches!(filter.op, Operator::Match | Operator::MatchPrefix) && filter.field != "_time" {
                if let Value::String(q_text) = &filter.value {
                    if indexes.fts.get(&query.collection).is_some_and(|m| m.contains_key(&filter.field)) {
                        return Self::make_plan(
                            query,
                            ScanType::InvertedIndex {
                                field: filter.field.clone(),
                                query: q_text.clone(),
                                prefix: filter.op == Operator::MatchPrefix,
                            },
                            query.limit,
                            false,
                            false,
                        );
                    }
                }
            }
        }

        // 1b. PRIORITY 1b: Vector KNN (exact, P0).
        // Gate: exactly one Near filter, no OR groups, Binary LE-f32
        // value, registered def with matching dim. Anything else falls
        // through — Near is fail-closed in compare_values, so unsupported
        // shapes return empty, never unranked rows.
        if let Some(plan) = Self::try_plan_vector(query, indexes) {
            return plan;
        }

        // 1c. PRIORITY 1c: Graph traversal (issue #53, Phase A).
        // Gate: exactly one Traverse filter, no OR groups, anchor
        // collection in the field, Map value (id/dir/edge?/depth), sane
        // depth, tracked start when incoming. Anything else falls through
        // — Traverse is fail-closed in compare_values, so unsupported
        // shapes return empty, never unranked rows. Combined Near+Traverse
        // is unsupported (first marker wins, the other fail-closes).
        let trav_count = query.filters.iter().filter(|f| matches!(f.op, Operator::Traverse)).count();
        if trav_count == 1 && query.or_groups.is_empty() {
            if let Some(tf) = query.filters.iter().find(|f| matches!(f.op, Operator::Traverse)) {
                if !tf.field.is_empty() {
                    if let Value::Map(pairs) = &tf.value {
                        let str_of = |k: &str| {
                            pairs.iter().find(|(kk, _)| kk.as_ref() == k).and_then(|(_, v)| {
                                if let Value::String(s) = v { Some(s.clone()) } else { None }
                            })
                        };
                        let int_of = |k: &str| {
                            pairs.iter().find(|(kk, _)| kk.as_ref() == k).and_then(|(_, v)| {
                                if let Value::Int(i) = v { Some(*i) } else { None }
                            })
                        };
                        if let (Some(start_id), Some(depth)) = (str_of("id"), int_of("depth")) {
                            let dir = int_of("dir").unwrap_or(0);
                            let edge = str_of("edge");
                            if depth >= 1 && depth <= crate::index::traverse::MAX_TRAVERSE_DEPTH as i64 {
                                if let Ok(direction) = crate::index::traverse::TraverseDir::from_u32(dir as u32) {
                                    // Phase B keys (optional, backward compatible).
                                    let via = str_of("via");
                                    let weight = str_of("weight");
                                    let incoming_ok = !direction.uses_incoming()
                                        || indexes.traverse.is_tracked(&tf.field)
                                        || via.as_deref().is_some_and(|e| {
                                            indexes.secondary.get(e).is_some_and(|m| {
                                                m.contains_key("_from") && m.contains_key("_to")
                                            })
                                        });
                                    if incoming_ok {
                                        let extra: Vec<Filter> = query
                                            .filters
                                            .iter()
                                            .filter(|f| !matches!(f.op, Operator::Traverse))
                                            .cloned()
                                            .collect();
                                        let limit = query.limit.unwrap_or(100);
                                        let spec = crate::index::traverse::TraverseSpec {
                                            direction,
                                            edge_field: edge,
                                            max_depth: depth as usize,
                                            limit,
                                            via_edge: via,
                                            weight_field: weight,
                                            node_match: None,
                                            edge_type: None,
                                            edge_match: None,
                                            include_path: false,
                                            include_via: false,
                                        };
                                        let mut plan = Self::make_plan(
                                            query,
                                            ScanType::Traverse {
                                                start_col: tf.field.clone(),
                                                start_id,
                                                spec: Box::new(spec),
                                                extra,
                                            },
                                            query.limit.map(|l| l + query.offset.unwrap_or(0)),
                                            false,
                                            true,
                                        );
                                        plan.filters.retain(|f| !matches!(f.op, Operator::Traverse));
                                        return plan;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // 2. PRIORITY 2: Composite Index (Now correctly handles id/_time via updated IndexManager)
        //
        // ponytail: unordered single-Eq lookups are cheaper via the simple
        // secondary index (exact-key BTreeMap get + early break at the scan
        // limit) than a composite prefix walk (prefix-range build + FULL
        // materialization of every matching tuple key before truncation).
        // So yield to P6 whenever it would accept this filter. The conditions
        // below mirror P6's acceptance exactly — Eq op, secondary present,
        // no numeric-string ambiguity, size heuristic on — so we can never
        // fall through to a full scan by yielding.
        // Multi-filter and ordered queries keep the composite: conjunction
        // narrowing and pre-sorted output are worth more than the cheaper
        // point lookup there.
        let yield_to_secondary = query.order_by.is_empty()
            && query.or_groups.is_empty()
            && query.filters.len() == 1
            && use_index_heuristic
            && matches!(query.filters[0].op, Operator::Eq)
            && indexes.secondary.get(&query.collection)
                .is_some_and(|m| m.contains_key(&query.filters[0].field))
            && !matches!(&query.filters[0].value, Value::String(s) if s.parse::<i64>().is_ok());
        if !yield_to_secondary {
        if let Some((eq_scan, satisfied, filters_done)) = Self::try_plan_composite_eq(query, indexes) {
            // ponytail: include offset like every P3/P6 path does — bare
            // `limit` under-collected when offset > 0 (scan grabs `limit`,
            // executor then skips `offset`).
            let safe_limit = if satisfied {
                query.limit.map(|l| l + query.offset.unwrap_or(0))
            } else { None };
            return Self::make_plan(
                query, 
                eq_scan, 
                safe_limit, 
                satisfied, 
                filters_done
            );
        }
        }

        // #250 follow-up: composite prefix equality + order/range. When a
        // composite index starts with an equality-filtered field and the next
        // field is the ORDER BY field, it satisfies both filter and order and
        // must win over P3's "order index only" choice. This is the exact
        // shape of `tenant = ? AND score >= ? ORDER BY score`.
        if use_index_heuristic && query.or_groups.is_empty() {
            if let Some((range_scan, order_ok)) = Self::try_composite_prefix_order(query, indexes) {
                let safe_limit = if order_ok {
                    query.limit.map(|l| l + query.offset.unwrap_or(0))
                } else { None };
                let filters_done = Self::composite_scan_filters_satisfied(query, &range_scan, indexes);
                return Self::make_plan(query, range_scan, safe_limit, order_ok, filters_done);
            }
        }

        // 3. PRIORITY 3: Range / Cursor / Pure Pagination Detection
        if let Some(first_order) = query.order_by.first() {
            // PONYTAIL: special-case the `id` field. When the user orders by
            // `id` with no filters, the storage sorted_keys vec is already
            // sorted by id. We can slice it directly (O(log N + limit))
            // instead of walking any index — including for cursor queries
            // (`start_at`/`start_after` resolve to a binary search + slice
            // in the executor). hk_engine_create_index("id") registers `id`
            // as a composite index with one field, so this short-circuit has
            // to live BEFORE the composite-index loop below or it never
            // fires. Only shapes we can't express here (end bounds) fall
            // through to the composite path below.
            if first_order.field == "id"
                && query.end_at.is_none() && query.end_before.is_none()
                && query.filters.is_empty() && query.or_groups.is_empty()
                && query.order_by.len() == 1
            {
                if let Some(scan) = Self::id_order_sortedkeys(query) {
                    return Self::make_plan(
                        query,
                        scan,
                        query.limit,
                        true,
                        true,
                    );
                }
                // Unsupported anchor shape: fall through to the composite
                // loop below (end bounds / exotic values).
            }
            // #250 follow-up: cost-based choice — when a single equality
            // filter has a secondary index and ORDER BY is on another field,
            // ride the (small) filter posting and let the executor TopN-sort
            // the final page. This beats scanning the whole ORDER BY index
            // and verifying the filter afterwards.
            if query.limit.is_some()
                && query.or_groups.is_empty() && query.elem_match.is_empty()
                && query.filters.len() == 1
                && query.start_at.is_none() && query.start_after.is_none()
                && query.end_at.is_none() && query.end_before.is_none()
            {
                let f = &query.filters[0];
                if f.op == Operator::Eq && f.field != first_order.field && f.field != "id" {
                    let ambiguous = matches!(&f.value, Value::String(s) if s.parse::<i64>().is_ok() || s.parse::<f64>().is_ok());
                    if !ambiguous {
                        if let Some(sec_map) = indexes.secondary.get(&query.collection) {
                            if let Some(sec) = sec_map.get(&f.field) {
                                let val_bytes = crate::index::index_key::encode_scalar(&f.value);
                                let posting = sec.get_map().get(&val_bytes).map(|s| s.len()).unwrap_or(0);
                                if posting > 0 {
                                    return Self::make_plan(
                                        query,
                                        ScanType::SecondaryIndex { field: f.field.clone(), value: val_bytes },
                                        None, // no scan truncation: executor TOPN needs the full page
                                        false, // order satisfied by TopN sort, not the scan
                                        true,  // Eq filter pinned by the index key
                                    );
                                }
                            }
                        }
                    }
                }
            }

            // Check Composite Indices for both Cursors AND pure OrderBy Pagination
            for idx in indexes.indexes_for_collection(&query.collection) {
                if !Self::composite_def_usable(&idx.definition, query) {
                    continue;
                }
                if !idx.definition.fields.is_empty() && idx.definition.fields[0].field == first_order.field {
                    let mut matches_all = true;
                    let mut reverse_scan = false;
                    for (i, q_order) in query.order_by.iter().enumerate() {
                        if let Some(idx_f) = idx.definition.fields.get(i) {
                            if idx_f.field != q_order.field { matches_all = false; break; }
                            if i == 0 && (idx_f.direction == SortDirection::Asc) != q_order.ascending {
                                reverse_scan = true;
                            }
                            if (idx_f.direction == SortDirection::Asc) != (q_order.ascending != reverse_scan) {
                                matches_all = false; break;
                            }
                        } else { matches_all = false; break; }
                    }

                    if matches_all {
                        let start = match (&query.start_at, &query.start_after) {
                            (Some(v), _) => Bound::Included(build_cursor_range(&idx.definition, v, false)),
                            (_, Some(v)) => Bound::Excluded(build_cursor_range(&idx.definition, v, false)),
                            _ => Bound::Unbounded,
                        };
                        let end = match (&query.end_at, &query.end_before) {
                            (Some(v), _) => Bound::Included(build_cursor_range(&idx.definition, v, false)),
                            (_, Some(v)) => Bound::Excluded(build_cursor_range(&idx.definition, v, false)),
                            _ => Bound::Unbounded,
                        };

                        let filters_empty = query.filters.is_empty() && query.or_groups.is_empty();
                        let safe_limit = if filters_empty {
                            query.limit.map(|l| l + query.offset.unwrap_or(0))
                        } else { None };

                        return Self::make_plan(
                            query, 
                            ScanType::CompositeIndexRange { index_id: idx.definition.id, ranges: vec![(start, end)], reverse: reverse_scan }, 
                            safe_limit, 
                            true, // order_satisfied
                            filters_empty
                        );
                    }
                }
            }

            // Secondary Index Range Fallback
            if let Some(sec_map) = indexes.secondary.get(&query.collection) {
                if sec_map.contains_key(&first_order.field) {
                    // #250 follow-up: derive index bounds from filter
                    // ranges on the order field (e.g. `score BETWEEN a AND b
                    // ORDER BY score`). Existing cursor bounds still win if
                    // present (they are explicit user pagination).
                    let (filter_start, filter_end) = Self::secondary_filter_bounds(query, &first_order.field);
                    let start = match (&query.start_at, &query.start_after) {
                        (Some(v), _) if !v.is_empty() => Bound::Included(crate::index::index_key::encode_scalar(&v[0])),
                        (_, Some(v)) if !v.is_empty() => Bound::Excluded(crate::index::index_key::encode_scalar(&v[0])),
                        _ => filter_start,
                    };
                    let end = match (&query.end_at, &query.end_before) {
                        (Some(v), _) if !v.is_empty() => Bound::Included(crate::index::index_key::encode_scalar(&v[0])),
                        (_, Some(v)) if !v.is_empty() => Bound::Excluded(crate::index::index_key::encode_scalar(&v[0])),
                        _ => filter_end,
                    };

                    let order_satisfied = query.order_by.len() == 1;
                    let mut filters_empty = query.filters.is_empty() && query.or_groups.is_empty();
                    // A single range filter fully expressed as index bounds
                    // is satisfied by the scan (same encoded-key domain).
                    if !filters_empty && order_satisfied && query.or_groups.is_empty()
                        && query.elem_match.is_empty()
                        && query.filters.iter().all(|f| f.field == first_order.field
                            && matches!(f.op, Operator::Gt | Operator::Gte | Operator::Lt | Operator::Lte))
                    {
                        filters_empty = true;
                    }
                    let safe_limit = if order_satisfied && filters_empty {
                        query.limit.map(|l| l + query.offset.unwrap_or(0))
                    } else { None };

                    return Self::make_plan(
                        query,
                        ScanType::SecondaryIndexRange { field: first_order.field.clone(), start, end, reverse: !first_order.ascending },
                        safe_limit,
                        order_satisfied,
                        filters_empty
                    );
                }
            }
        }

        // 4. PRIORITY 4: Composite Range (e.g. WHERE price > 100)
        // ponytail: also gated on !yield_to_secondary — P4 accepts all-Eq
        // filters too, and would otherwise recapture the queries we just
        // yielded with a WORSE plan (full prefix materialization, no limit
        // pushdown, per-doc filter re-verify). P6 takes them instead.
        if use_index_heuristic && !yield_to_secondary {
            if let Some(range_scan) = Self::try_plan_composite_range(query, indexes) {
                let filters_done =
                    Self::composite_scan_filters_satisfied(query, &range_scan, indexes);
                return Self::make_plan(
                    query,
                    range_scan,
                    None,
                    false,
                    filters_done
                );
            }
        }

        // 5. PRIORITY 5: Union/OR/IN Logic
        if !query.or_groups.is_empty() || query.filters.iter().any(|f| matches!(f.op, Operator::In)) {
            if let Some(union_scan) = Self::try_plan_union(query, indexes) {
                return Self::make_plan(
                    query,
                    union_scan,
                    None,
                    false,
                    false
                );
            }
        }

        // 6. PRIORITY 6: Simple Secondary Index (Equality)
        // ponytail: probe posting sizes, ride the smallest. The old code
        // took the FIRST Eq filter's posting, so filter ORDER decided cost
        // (30x measured hot-first vs rare-first on 20k rows, 634ms vs
        // 21ms). One BTree get per candidate is O(log n); ties keep the
        // first filter (same plan as before). Single-Eq is unchanged.
        // No sweep fallback: measured index wins even at 90% selectivity
        // unbounded (454ms vs 802ms) — the premise in #22 was wrong.
        if use_index_heuristic {
            // (posting_len, filter_idx, encoded value) — index, not &Filter,
            // so the build below stays a plain move.
            let mut best: Option<(usize, usize, Vec<u8>)> = None;
            for (fi, filter) in query.filters.iter().enumerate() {
                if matches!(filter.op, Operator::Eq) {
                    if let Some(sec_map) = indexes.secondary.get(&query.collection) {
                        if let Some(sec) = sec_map.get(&filter.field) {
                            // Ambiguous-class values (numeric strings AND
                            // bare Int/Float: the stored side may encode
                            // the number differently) take the alternatives
                            // union instead of one exact bucket — the DHP
                            // `passw` hole was a single-key trust here.
                            // Union scans verify downstream; the single-key
                            // path below keeps its trust (same-type keys
                            // are exact by tag).
                            let ambiguous = match &filter.value {
                                Value::String(s) => {
                                    s.parse::<i64>().is_ok() || s.parse::<f64>().is_ok()
                                }
                                Value::Int(_) | Value::Float(_) => true,
                                _ => false,
                            };
                            if ambiguous {
                                if let Some(scan) = Self::get_single_filter_scan(
                                    &query.collection,
                                    &filter.field,
                                    &filter.value,
                                    indexes,
                                    query,
                                ) {
                                    // Union (or composite-first single):
                                    // verify downstream, no limit pushdown
                                    // (verification may drop rows).
                                    return Self::make_plan(
                                        query, scan, None, false, false,
                                    );
                                }
                                continue;
                            }
                            let val_bytes = crate::index::index_key::encode_scalar(&filter.value);
                            let len = sec.get_map().get(&val_bytes).map(|s| s.len()).unwrap_or(0);
                            if best.as_ref().is_none_or(|(l, _, _)| len < *l) {
                                best = Some((len, fi, val_bytes));
                            }
                        }
                    }
                }
            }
            if let Some((_, fi, val_bytes)) = best {
                let filter = &query.filters[fi];
                                // CRITICAL FIX: Mark filters satisfied if this is the ONLY filter
                                let filters_satisfied = query.filters.len() == 1 && query.or_groups.is_empty();
                                // ponytail: no limit pushdown under ORDER BY — the
                                // point scan is NOT in sort order, so truncating
                                // before the executor sort returns the wrong
                                // TOP-N (same trap as the FullCollection
                                // fallback below). Unordered keeps the pushdown.
                                let safe_limit = if filters_satisfied && query.order_by.is_empty() { 
                                    query.limit.map(|l| l + query.offset.unwrap_or(0)) 
                                } else { None };

                                return Self::make_plan(
                                    query, 
                                    ScanType::SecondaryIndex { field: filter.field.clone(), value: val_bytes }, 
                                    safe_limit, 
                                    false, 
                                    filters_satisfied
                                );
            }
        }

        // 7. DEFAULT FALLBACK: Full Collection Scan
        // This is the "Safety Net". If no index was found for 'id:eq',
        // it lands here and the Worker checks the storage keys manually.
        // ponytail: push limit+offset into the scan ONLY when no filters
        // need matching AND no ORDER BY is requested — unordered scans can
        // satisfy TOP-N from ANY rows, but pre-truncating before filter
        // matching returns wrong (usually empty) results, and pre-truncating
        // before the executor's in-memory sort returns the wrong TOP-N.
        // Unfiltered+unordered keeps the pushdown; everything else scans
        // fully and truncates downstream (inherent to unindexed match/sort).
        let no_filters = query.filters.is_empty() && query.or_groups.is_empty();
        let fc_limit = if no_filters && query.order_by.is_empty() {
            query.limit.map(|l| l + query.offset.unwrap_or(0))
        } else {
            None
        };
        Self::make_plan(query, ScanType::FullCollection, fc_limit, false, no_filters)
    }

    /// Helper to build the plan object.
    /// Now takes 'order_satisfied' as an argument.
    fn make_plan(
        query: &Query,
        scan: ScanType,
        scan_limit: Option<usize>,
        order_satisfied: bool,
        filters_satisfied: bool,
    ) -> QueryPlan {
        // If there's no specific sort requested, then the index's natural order is acceptable
        let actual_order_satisfied = query.order_by.is_empty() || order_satisfied;
        // Cursor bounds ride into bounded index scans (SortedKeys, ranges);
        // anything else leaves them to post-filtering (see has_cursor_bounds).
        let has_cursor_bounds = [&query.start_at, &query.start_after, &query.end_at, &query.end_before]
            .iter()
            .any(|b| matches!(b, Some(v) if !v.is_empty()));

        // hakodb#71 F3: elemMatch clauses are matcher passes — every
        // candidate row must be decoded and element-checked, so no scan
        // lane may claim it covered the filters when clauses exist.
        let filters_satisfied = filters_satisfied && query.elem_match.is_empty();

        QueryPlan {
            collection: query.collection.clone(),
            scan,
            filters: query.filters.clone(),
            or_groups: query.or_groups.clone(),
            elem_match: query.elem_match.clone(),
            order_by: query.order_by.clone(),
            limit: query.limit,
            scan_limit,
            offset: query.offset,
            projection: query.projection.clone(),
            order_by_satisfied: actual_order_satisfied,
            filters_satisfied_by_index: filters_satisfied,
            defer_blobs: query.defer_blobs,
            raw: query.raw,
            has_cursor_bounds,
        }
    }

    /// Cursor anchor for `order by id`: the anchor value is a doc id, which
    /// is exactly what `sorted_keys` holds. Returns None for non-id-like
    /// values so the caller falls through to the composite-index path.
    fn anchor_id(v: &Value) -> Option<String> {
        match v {
            Value::String(s) => Some(s.clone()),
            Value::Int(i) => Some(i.to_string()),
            _ => None,
        }
    }

    /// Vector KNN planning: exactly one Near filter, no Or groups, Binary
    /// LE-f32 value, registered def with matching dim. The arm verifies
    /// everything itself (Near scoring + remaining Eq filters), so the
    /// returned plan strips Near: downstream re-verify (incl. projected
    /// path) sees only boolean filters.
    fn try_plan_vector(query: &Query, indexes: &IndexManager) -> Option<QueryPlan> {
        let near_count = query.filters.iter().filter(|f| matches!(f.op, Operator::Near)).count();
        if near_count != 1 || !query.or_groups.is_empty() {
            return None;
        }
        let nf = query.filters.iter().find(|f| matches!(f.op, Operator::Near))?;
        let Value::Binary(qb) = &nf.value else { return None };
        let def = indexes.vector.get(&query.collection).and_then(|m| m.get(&nf.field))?;
        if qb.len() % 4 != 0 || qb.len() / 4 != def.dim as usize {
            return None;
        }
        let extra: Vec<Filter> = query
            .filters
            .iter()
            .filter(|f| !matches!(f.op, Operator::Near))
            .cloned()
            .collect();
        let mut plan = Self::make_plan(
            query,
            ScanType::VectorKnn {
                field: nf.field.clone(),
                query: qb.clone(),
                metric: def.metric,
                extra,
            },
            query.limit.map(|l| l + query.offset.unwrap_or(0)),
            false,
            true,
        );
        plan.filters.retain(|f| !matches!(f.op, Operator::Near));
        Some(plan)
    }

    /// The index-free `id`-order paging shape (planner P3 short-circuit):    /// order by `id` only, no filters/Or groups/end bounds, anchor
    /// resolvable to a string. Returns the SortedKeys scan or None —
    /// callers must not treat None as an error, just continue planning.
    fn id_order_sortedkeys(query: &Query) -> Option<ScanType> {
        let first_order = query.order_by.first()?;
        if first_order.field != "id"
            || query.end_at.is_some()
            || query.end_before.is_some()
            || !query.filters.is_empty()
            || !query.or_groups.is_empty()
            || query.order_by.len() != 1
        {
            return None;
        }
        let (start_key, start_exclusive) = match (&query.start_at, &query.start_after) {
            (Some(v), _) if !v.is_empty() => (Some(Self::anchor_id(&v[0])?), false),
            (_, Some(v)) if !v.is_empty() => (Some(Self::anchor_id(&v[0])?), true),
            _ => (None, false),
        };
        Some(ScanType::SortedKeys { start_key, start_exclusive, reverse: !first_order.ascending })
    }

    fn try_plan_union(query: &Query, indexes: &IndexManager) -> Option<ScanType> {
        let mut scans = Vec::new();
        for filter in &query.filters {
            if matches!(filter.op, Operator::In) {
                if let Value::Array(vals) = &filter.value {
                    for v in vals {
                        // This ensures each item in the IN array checks for
                        // Composite Indexes first, then Secondary Indexes.
                        let scan = Self::get_single_filter_scan(
                            &query.collection,
                            &filter.field,
                            v,
                            indexes,
                            query,
                        )?;
                        scans.push(scan);
                    }
                    return Some(ScanType::UnionIndex { scans });
                }
            }
        }
        if !query.or_groups.is_empty() {
            for group in &query.or_groups {
                if group.len() == 1 {
                    let f = &group[0];
                    scans.push(Self::get_single_filter_scan(
                        &query.collection,
                        &f.field,
                        &f.value,
                        indexes,
                        query
                    )?);
                } else {
                    // Complex OR groups (multiple filters in one OR) still fallback to Full Scan
                    return None;
                }
            }
            return Some(ScanType::UnionIndex { scans });
        }

        None
    }

    /// Cross-type Eq alternatives (mirrors compare_values numeric arms):
    /// the stored side may carry the number as a String (legacy imports,
    /// CSV seeds) or float, so an exact-key index probe must try every
    /// encoding the semantic compare would accept. Original first; order
    /// otherwise irrelevant (union dedups nothing — keys are type-tagged,
    /// so alternatives never collide).
    fn numeric_alternatives(val: &Value) -> Vec<Value> {
        let mut out = vec![val.clone()];
        match val {
            Value::String(s) => {
                if let Ok(i) = s.parse::<i64>() {
                    out.push(Value::Int(i));
                }
                if let Ok(f) = s.parse::<f64>() {
                    if f.is_finite() {
                        out.push(Value::Float(f));
                    }
                }
            }
            Value::Int(i) => {
                out.push(Value::String(i.to_string()));
                // Lossless only: past 2^53 the float can't name this int.
                let f = *i as f64;
                if f as i64 == *i {
                    out.push(Value::Float(f));
                }
            }
            Value::Float(f) => {
                // String form is best-effort (float textual forms are
                // unbounded: "4.75" vs "4.750" vs "4.75e0" all parse equal
                // but key differently — a miss here falls through to the
                // executor's empty-index sweep fallback, still correct).
                out.push(Value::String(f.to_string()));
                if f.is_finite() {
                    // Integral floats name an int ("4" for 4.0 — matches a
                    // stored String("4") via parse, and stored Int(4) via
                    // total_cmp). Non-integral floats have no int form.
                    if f.fract() == 0.0
                        && *f >= i64::MIN as f64
                        && *f <= i64::MAX as f64
                    {
                        out.push(Value::Int(*f as i64));
                    }
                }
            }
            _ => {}
        }
        out
    }

    fn get_single_filter_scan(
        col: &str,
        field: &str,
        val: &Value,
        indexes: &IndexManager,
        _query: &Query,
    ) -> Option<ScanType> {
        // Cross-type alternatives (Int/String/Float closure — see
        // numeric_alternatives): the stored side may encode the number
        // differently than the filter does.
        let alternatives = Self::numeric_alternatives(val);

        let mut sub_scans = Vec::new();
        for alt_val in &alternatives {
            let mut found_for_this_type = false;
            // Look for Composite Index first
            for idx in indexes.indexes_for_collection(col) {
                if !Self::composite_def_usable(&idx.definition, _query) {
                    continue;
                }
                if idx.definition.fields.first().is_some_and(|f| f.field == field) {
                    sub_scans.push(ScanType::CompositeIndex {
                        index_id: idx.definition.id,
                        fields: vec![field.to_string()],
                        values: vec![alt_val.clone()],
                        reverse: false,
                    });
                    found_for_this_type = true;
                    break; // Found an index for this specific alternative
                }
            }
            
            // If no composite scan was added for this alternative, check Secondary Index
            if !found_for_this_type { // Logic: if we didn't just add a composite scan
                if let Some(sec_map) = indexes.secondary.get(col) {
                    if sec_map.contains_key(field) {
                        sub_scans.push(ScanType::SecondaryIndex {
                            field: field.to_string(),
                            value: crate::index::index_key::encode_scalar(alt_val),
                        });
                    }
                }
            }
        }

        // Return a Union if multiple types are valid, a Single scan if only one, or None
        if sub_scans.is_empty() {
            None
        } else if sub_scans.len() == 1 {
            sub_scans.pop()
        } else {
            // This is the magic: It will check the index for String AND Int versions
            Some(ScanType::UnionIndex { scans: sub_scans })
        }
    }


    /// #250: encoded index bounds implied by equality/range filters on a
    /// single field. Used to push `score >= a AND score <= b` into the
    /// secondary index range instead of scanning every key.
    fn secondary_filter_bounds(
        query: &Query,
        field: &str,
    ) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
        let mut start = Bound::Unbounded;
        let mut end = Bound::Unbounded;
        for f in &query.filters {
            if f.field != field || query.or_groups.iter().any(|g| g.iter().any(|x| x.field == field)) {
                continue;
            }
            let key = crate::index::index_key::encode_scalar(&f.value);
            match f.op {
                Operator::Eq => {
                    start = Bound::Included(key.clone());
                    end = Bound::Included(key);
                }
                Operator::Gt => start = Bound::Excluded(key),
                Operator::Gte => start = Bound::Included(key),
                Operator::Lt => end = Bound::Excluded(key),
                Operator::Lte => end = Bound::Included(key),
                _ => {}
            }
        }
        (start, end)
    }

    /// #250: composite `(eq_prefix..., order_field)` with a single range
    /// filter on the order field. Returns (scan, order_satisfied).
    fn try_composite_prefix_order(
        query: &Query,
        indexes: &IndexManager,
    ) -> Option<(ScanType, bool)> {
        let first_order = query.order_by.first()?;
        if query.filters.len() < 2 || !query.or_groups.is_empty() { return None; }
        for idx in indexes.indexes_for_collection(&query.collection) {
            if !Self::composite_def_usable(&idx.definition, query) { continue; }
            let fields = &idx.definition.fields;
            if fields.len() < 2 { continue; }
            // Every field before the order field must have an Eq filter.
            let order_pos = fields.iter().position(|f| f.field == first_order.field)?;
            if order_pos == 0 || order_pos + 1 > fields.len() { continue; }
            let mut eq_prefix = Vec::new();
            let mut ok = true;
            for f in &fields[..order_pos] {
                match query.filters.iter().find(|qf| qf.field == f.field) {
                    Some(qf) if qf.op == Operator::Eq => eq_prefix.push(qf.value.clone()),
                    _ => { ok = false; break; }
                }
            }
            if !ok { continue; }
            // The order field must carry exactly one range/Eq filter so the
            // index range pins it; otherwise fall through to the old path.
            let of = query.filters.iter().find(|qf| qf.field == first_order.field)?;
            if !matches!(of.op, Operator::Eq | Operator::Gt | Operator::Gte | Operator::Lt | Operator::Lte) { continue; }
            // Direction: composite range scans ascending; matching ascending
            // order is satisfied, descending would need a reverse scan (not
            // yet supported for composite ranges) so leave order unsatisfied.
            let order_ok = first_order.ascending && idx.definition.fields[order_pos].direction == SortDirection::Asc;
            let mut range_query = query.clone();
            // Reuse P4's range construction on a query limited to the eq + range filters.
            range_query.filters = query.filters.iter()
                .filter(|f| fields.iter().any(|idx_f| idx_f.field == f.field))
                .cloned().collect();
            if let Some(scan) = Self::try_plan_composite_range(&range_query, indexes) {
                return Some((scan, order_ok));
            }
        }
        None
    }

    /// True when a composite range scan pins every predicate of the original
    /// query: all filters are point/range ops on index fields, no OR,
    /// elemMatch, or cursor bounds are left for the executor to verify.
    fn composite_scan_filters_satisfied(
        query: &Query,
        scan: &ScanType,
        indexes: &IndexManager,
    ) -> bool {
        if !query.or_groups.is_empty()
            || !query.elem_match.is_empty()
            || query.start_at.is_some()
            || query.start_after.is_some()
            || query.end_at.is_some()
            || query.end_before.is_some()
            || query.filters.is_empty()
        {
            return false;
        }
        let ScanType::CompositeIndexRange { index_id, .. } = scan else {
            return false;
        };
        let Some(idx) = indexes.composite.get(*index_id) else {
            return false;
        };
        query.filters.iter().all(|f| {
            let indexed = idx.definition.fields.iter().any(|idx_f| idx_f.field == f.field);
            indexed
                && (matches!(
                    f.op,
                    Operator::Eq
                        | Operator::Gt
                        | Operator::Gte
                        | Operator::Lt
                        | Operator::Lte
                        | Operator::Ne
                ) || matches!(&f.value, Value::Array(a) if a.len() == 1))
        })
    }

    fn try_plan_composite_range(query: &Query, indexes: &IndexManager) -> Option<ScanType> {

        let is_point_lookup = |f: &crate::query::filter::Filter| {
            matches!(f.op, Operator::Eq) ||
            (matches!(f.op, Operator::In) && matches!(&f.value, Value::Array(a) if a.len() == 1))
        };
        let is_range = |f: &crate::query::filter::Filter| {
            matches!(f.op, Operator::Gt | Operator::Gte | Operator::Lt | Operator::Lte | Operator::Ne)
        };

        if query.filters.is_empty()
            || query.filters.iter().filter(|f| is_range(f)).count() > 1
            || !query.filters.iter().all(|f| is_point_lookup(f) || is_range(f))
        {
            return None;
        }

        for idx in indexes.indexes_for_collection(&query.collection) {
            if !Self::composite_def_usable(&idx.definition, query) {
                continue;
            }
            let mut eq_prefix = Vec::new();
            let mut range_filter = None;
            let mut supported = true;

            let mut matched_fields = Vec::new();
            let mut matched_values = Vec::new();

            for idx_field in &idx.definition.fields {
                if let Some(filter) = query.filters.iter().find(|f| f.field == idx_field.field) {
                    matched_fields.push(idx_field.field.clone());
                    
                    // Extract value: if array of 1, take the first element
                    let v = match &filter.value {
                        Value::Array(a) if a.len() == 1 => a[0].clone(),
                        other => other.clone(),
                    };
                    matched_values.push(v);
                } else { break; }
            }

            for field in &idx.definition.fields {
                if let Some(filter) = query.filters.iter().find(|f| f.field == field.field) {
                    match filter.op {
                        Operator::Eq => eq_prefix.push(filter.value.clone()),
                        Operator::Gt
                        | Operator::Gte
                        | Operator::Lt
                        | Operator::Lte
                        | Operator::Ne => {
                            range_filter = Some((filter.op, filter.value.clone()));
                            break;
                        }
                        _ => {
                            supported = false;
                            break;
                        }
                    }
                } else {
                    break;
                }
            }

            if !supported || (eq_prefix.is_empty() && range_filter.is_none()) {
                continue;
            }

            let eq_prefix_key = build_prefix_key(&idx.definition, &eq_prefix);
            let eq_prefix_end = build_prefix_open_end(&eq_prefix_key);

            let ranges = match range_filter {
                None => vec![(
                    Bound::Included(eq_prefix_key),
                    Bound::Included(eq_prefix_end),
                )],
                Some((op, value)) => {
                    let value_key = build_value_key(&idx.definition, &eq_prefix, &value)?;
                    let value_key_end = key_with_upper_sentinel(&value_key);
                    match op {
                        Operator::Gt => vec![(
                            Bound::Excluded(value_key_end),
                            Bound::Included(eq_prefix_end),
                        )],
                        Operator::Gte => {
                            vec![(Bound::Included(value_key), Bound::Included(eq_prefix_end))]
                        }
                        Operator::Lt => {
                            vec![(Bound::Included(eq_prefix_key), Bound::Excluded(value_key))]
                        }
                        Operator::Lte => vec![(
                            Bound::Included(eq_prefix_key),
                            Bound::Included(value_key_end),
                        )],
                        Operator::Ne => vec![
                            (
                                Bound::Included(eq_prefix_key),
                                Bound::Excluded(value_key.clone()),
                            ),
                            (
                                Bound::Excluded(value_key_end),
                                Bound::Included(eq_prefix_end),
                            ),
                        ],
                        _ => return None,
                    }
                }
            };

            return Some(ScanType::CompositeIndexRange {
                index_id: idx.definition.id,
                ranges,
                reverse: false
            });
        }

        None
    }

    fn try_plan_composite_eq(query: &Query, indexes: &IndexManager) -> Option<(ScanType, bool, bool)> {
        let is_point_lookup = |f: &crate::query::filter::Filter| {
            matches!(f.op, Operator::Eq) || 
            (matches!(f.op, Operator::In) && matches!(&f.value, Value::Array(a) if a.len() == 1))
        };

        // We only use this optimization if ALL filters are Equality/Point-lookups
        if query.filters.is_empty() || !query.filters.iter().all(is_point_lookup) {
            return None;
        }

        // 1. Probing: alternate types for the FIRST filter field (shared
        // numeric closure — the stored side may encode the number
        // differently than the filter does).
        let first_filter = &query.filters[0];
        let alternatives = Self::numeric_alternatives(&first_filter.value);

        let mut sub_scans = Vec::new();

        // 2. Try to find a matching index for each alternative type
        for alt_val in alternatives {
            for idx in indexes.indexes_for_collection(&query.collection) {
                if !Self::composite_def_usable(&idx.definition, query) {
                    continue;
                }
                let mut matched_fields = Vec::new();
                let mut matched_values = Vec::new();

                // Match query filters to index prefix
                for idx_field in &idx.definition.fields {
                    let val_opt = if matched_fields.is_empty() {
                        if idx_field.field == first_filter.field { Some(&alt_val) } else { None }
                    } else {
                        query.filters.iter().find(|f| f.field == idx_field.field).map(|f| &f.value)
                    };

                    if let Some(v) = val_opt {
                        matched_fields.push(idx_field.field.clone());
                        matched_values.push(match v {
                            Value::Array(a) if a.len() == 1 => a[0].clone(),
                            other => other.clone(),
                        });
                    } else { break; }
                }

                // If this index covers ALL our filters
                if matched_fields.len() == query.filters.len() {
                    // ponytail: no ORDER BY means any subset is correctly
                    // ordered, so limit pushdown is safe — treat as
                    // satisfied. (make_plan already does this for the plan
                    // flag; the raw bool here gates safe_limit below.)
                    let mut order_satisfied = query.order_by.is_empty();
                    let mut reverse_scan = false;

                    // 3. Sorting Logic: Does the index cover the ORDER BY clause?
                    if !query.order_by.is_empty() {
                        let start_idx = matched_fields.len();
                        let mut matches_all_sorts = true;
                        
                        for (i, q_order) in query.order_by.iter().enumerate() {
                            if let Some(idx_f) = idx.definition.fields.get(start_idx + i) {
                                if idx_f.field != q_order.field {
                                    matches_all_sorts = false;
                                    break;
                                }
                                // Logic: If the first sort field direction is different from index, 
                                // we scan the B-Tree backwards (reverse_scan).
                                if i == 0 && (idx_f.direction == SortDirection::Asc) != q_order.ascending {
                                    reverse_scan = true;
                                }
                                // Subsequent fields must follow the same flip
                                if (idx_f.direction == SortDirection::Asc) != (q_order.ascending != reverse_scan) {
                                    matches_all_sorts = false;
                                    break;
                                }
                            } else {
                                matches_all_sorts = false;
                                break;
                            }
                        }
                        order_satisfied = matches_all_sorts;
                    }

                    sub_scans.push((
                        ScanType::CompositeIndex { 
                            index_id: idx.definition.id,
                            fields: matched_fields, 
                            values: matched_values, 
                            reverse: reverse_scan 
                        },
                        order_satisfied
                    ));
                    break; // Found the best index for this specific alternative
                }
            }
        }

        if sub_scans.is_empty() {
            None
        } else if sub_scans.len() == 1 {
            let (scan, ordered) = sub_scans.pop().unwrap();
            // Some((scan, ordered, true))
            let has_in_filter = query.filters.iter().any(|f| f.op == Operator::In);
            let filters_done = query.or_groups.is_empty() && !has_in_filter;
            
            Some((scan, ordered, filters_done))
        } else {
            // We hit multiple types (String and Int). 
            // We MUST sort in RAM because Union merges different ranges.
            let scans = sub_scans.into_iter().map(|(s, _)| s).collect();
            Some((ScanType::UnionIndex { scans }, false, false))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::index::composite::definition::{CompositeIndexDefinition, SortDirection};

    fn bench_manager() -> IndexManager {
        let mut m = IndexManager::default();
        m.create_secondary_index("bench", "tenant");
        m.create_index(
            CompositeIndexDefinition::new("bench").with_fields(vec![
                ("tenant".to_string(), SortDirection::Asc),
                ("score".to_string(), SortDirection::Desc),
            ]),
        );
        m
    }

    #[test]
    fn unordered_single_eq_yields_to_secondary() {
        // No ORDER BY + single Eq + secondary present => P6 SecondaryIndex
        // (exact-key get), NOT a composite prefix walk. Also pins the
        // limit+offset pushdown P6 applies.
        let m = bench_manager();
        let q = Query::new("bench")
            .where_eq("tenant", Value::String("tenant-2".into()))
            .limit(20);
        let plan = QueryPlanner::plan(&q, &m, 1000, 8, true, true);
        assert!(
            matches!(plan.scan, ScanType::SecondaryIndex { .. }),
            "unordered point lookup should use secondary, got {:?}",
            plan.scan
        );
        assert_eq!(plan.scan_limit, Some(20));
        assert!(plan.filters_satisfied_by_index);
    }

    #[test]
    fn ordered_single_eq_keeps_composite() {
        // ORDER BY score => composite (tenant, score) keeps the query so
        // rows come back pre-sorted; the yield must not fire.
        let m = bench_manager();
        let q = Query::new("bench")
            .where_eq("tenant", Value::String("tenant-2".into()))
            .order_by("score", false)
            .limit(20);
        let plan = QueryPlanner::plan(&q, &m, 1000, 8, true, true);
        assert!(
            matches!(plan.scan, ScanType::CompositeIndex { .. }),
            "ordered query should keep composite, got {:?}",
            plan.scan
        );
        assert_eq!(plan.scan_limit, Some(20));
    }

    #[test]
    fn ordered_eq_no_limit_pushdown() {
        // Single Eq on a secondary-only field + ORDER BY on another field:
        // Int filters route to the alternatives union (cross-type safety —
        // the stored side may encode the number differently), which
        // verifies downstream, so pushing limit would truncate before the
        // executor sort AND verification (wrong TOP-N). scan_limit None.
        let mut m = IndexManager::default();
        m.create_secondary_index("bench", "age");
        let q = Query::new("bench")
            .where_eq("age", Value::Int(30))
            .order_by("score", false)
            .limit(20);
        let plan = QueryPlanner::plan(&q, &m, 1000, 8, true, true);
        assert!(
            matches!(plan.scan, ScanType::UnionIndex { .. }),
            "ambiguous Int should take the alternatives union, got {:?}",
            plan.scan
        );
        assert_eq!(plan.scan_limit, None);
        // Same shape unordered: union too (verify downstream), no pushdown.
        let q2 = Query::new("bench").where_eq("age", Value::Int(30)).limit(20);
        let plan2 = QueryPlanner::plan(&q2, &m, 1000, 8, true, true);
        assert!(
            matches!(plan2.scan, ScanType::UnionIndex { .. }),
            "unordered ambiguous Int also unions, got {:?}",
            plan2.scan
        );
        assert_eq!(plan2.scan_limit, None);
        // Non-numeric strings keep the single-key trust + pushdown.
        let q3 = Query::new("bench")
            .where_eq("tenant", Value::String("x".into()))
            .limit(20);
        let m2 = bench_manager();
        let plan3 = QueryPlanner::plan(&q3, &m2, 1000, 8, true, true);
        assert!(
            matches!(plan3.scan, ScanType::SecondaryIndex { .. }),
            "plain strings keep single-key trust, got {:?}",
            plan3.scan
        );
    }

    #[test]
    fn fallback_order_no_limit_pushdown() {
        // No indexes at all: unordered keeps TOP-N pushdown, ordered does
        // not (full scan + executor sort, then truncate).
        let m = IndexManager::default();
        let q = Query::new("plain").order_by("age", false).limit(100);
        let plan = QueryPlanner::plan(&q, &m, 1000, 8, true, true);
        assert!(matches!(plan.scan, ScanType::FullCollection));
        assert_eq!(plan.scan_limit, None);
        let q2 = Query::new("plain").limit(100);
        let plan2 = QueryPlanner::plan(&q2, &m, 1000, 8, true, true);
        assert!(matches!(plan2.scan, ScanType::FullCollection));
        assert_eq!(plan2.scan_limit, Some(100));
    }
}