laurus 0.4.1

Unified search library for lexical, vector, and semantic retrieval
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
//! Matcher implementations for query execution.

use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::fmt::Debug;

use crate::error::Result;
use crate::lexical::reader::PostingIterator;

/// Trait for document matchers.
pub trait Matcher: Send + Debug {
    /// Get the current document ID.
    fn doc_id(&self) -> u64;

    /// Move to the next matching document.
    fn next(&mut self) -> Result<bool>;

    /// Skip to the first document >= target.
    fn skip_to(&mut self, target: u64) -> Result<bool>;

    /// Get the cost of iterating through this matcher.
    fn cost(&self) -> u64;

    /// Check if this matcher is exhausted.
    fn is_exhausted(&self) -> bool;

    /// Get the term frequency for the current document.
    fn term_freq(&self) -> u64 {
        1 // Default implementation for matchers that don't track term frequency
    }
}

/// A matcher that matches no documents.
#[derive(Debug)]
pub struct EmptyMatcher {
    exhausted: bool,
}

impl EmptyMatcher {
    /// Create a new empty matcher.
    pub fn new() -> Self {
        EmptyMatcher { exhausted: true }
    }
}

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

impl Matcher for EmptyMatcher {
    fn doc_id(&self) -> u64 {
        u64::MAX
    }

    fn next(&mut self) -> Result<bool> {
        Ok(false)
    }

    fn skip_to(&mut self, _target: u64) -> Result<bool> {
        Ok(false)
    }

    fn cost(&self) -> u64 {
        0
    }

    fn is_exhausted(&self) -> bool {
        self.exhausted
    }
}

/// A matcher that matches all documents.
#[derive(Debug)]
pub struct AllMatcher {
    current_doc: u64,
    max_doc: u64,
}

impl AllMatcher {
    /// Create a new all matcher.
    pub fn new(max_doc: u64) -> Self {
        AllMatcher {
            current_doc: 0,
            max_doc,
        }
    }
}

impl Matcher for AllMatcher {
    fn doc_id(&self) -> u64 {
        if self.current_doc >= self.max_doc {
            u64::MAX
        } else {
            self.current_doc
        }
    }

    fn next(&mut self) -> Result<bool> {
        if self.current_doc >= self.max_doc {
            Ok(false)
        } else {
            self.current_doc += 1;
            Ok(self.current_doc < self.max_doc)
        }
    }

    fn skip_to(&mut self, target: u64) -> Result<bool> {
        if target >= self.max_doc {
            self.current_doc = self.max_doc;
            Ok(false)
        } else {
            self.current_doc = target;
            Ok(true)
        }
    }

    fn cost(&self) -> u64 {
        self.max_doc
    }

    fn is_exhausted(&self) -> bool {
        self.current_doc >= self.max_doc
    }
}

/// A matcher based on a posting iterator.
#[derive(Debug)]
pub struct PostingMatcher {
    posting_iter: Box<dyn PostingIterator>,
    exhausted: bool,
    cost: u64,
}

impl PostingMatcher {
    /// Create a new posting matcher.
    pub fn new(mut posting_iter: Box<dyn PostingIterator>) -> Self {
        let cost = posting_iter.cost();

        // Position the iterator at the first document
        let exhausted = !posting_iter.next().unwrap_or(false);

        PostingMatcher {
            posting_iter,
            exhausted,
            cost,
        }
    }

    /// Create an exhausted posting matcher.
    pub fn exhausted() -> Self {
        // Create a dummy iterator that's already exhausted
        let postings = vec![];
        let posting_iter = Box::new(
            crate::lexical::index::inverted::reader::InvertedIndexPostingIterator::new(postings),
        );
        PostingMatcher {
            posting_iter,
            exhausted: true,
            cost: 0,
        }
    }
}

impl Matcher for PostingMatcher {
    fn doc_id(&self) -> u64 {
        if self.exhausted {
            u64::MAX
        } else {
            self.posting_iter.doc_id()
        }
    }

    fn next(&mut self) -> Result<bool> {
        if self.exhausted {
            Ok(false)
        } else {
            let has_next = self.posting_iter.next()?;
            if !has_next {
                self.exhausted = true;
            }
            Ok(has_next)
        }
    }

    fn skip_to(&mut self, target: u64) -> Result<bool> {
        if self.exhausted {
            Ok(false)
        } else {
            let result = self.posting_iter.skip_to(target)?;
            if !result {
                self.exhausted = true;
            }
            Ok(result)
        }
    }

    fn cost(&self) -> u64 {
        self.cost
    }

    fn is_exhausted(&self) -> bool {
        self.exhausted
    }

    fn term_freq(&self) -> u64 {
        if self.exhausted {
            0
        } else {
            self.posting_iter.term_freq()
        }
    }
}

/// A helper struct for tracking matchers in the disjunction heap.
#[derive(Debug)]
struct MatcherEntry {
    matcher: Box<dyn Matcher>,
}

impl PartialEq for MatcherEntry {
    fn eq(&self, other: &Self) -> bool {
        self.matcher.doc_id() == other.matcher.doc_id()
    }
}

impl Eq for MatcherEntry {}

impl PartialOrd for MatcherEntry {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for MatcherEntry {
    fn cmp(&self, other: &Self) -> Ordering {
        // Min-heap: lower doc IDs come first
        other.matcher.doc_id().cmp(&self.matcher.doc_id())
    }
}

/// A matcher that implements disjunction (OR) of multiple matchers.
#[derive(Debug)]
pub struct DisjunctionMatcher {
    /// Min-heap of active matchers, ordered by current doc_id.
    heap: BinaryHeap<MatcherEntry>,
    /// Current document ID.
    current_doc: u64,
    /// Whether this matcher is exhausted.
    exhausted: bool,
    /// Total cost estimate.
    cost: u64,
    /// Reusable buffer for matchers to reinsert during advance operations.
    reinsert_buffer: Vec<MatcherEntry>,
}

impl DisjunctionMatcher {
    /// Create a new disjunction matcher from multiple matchers.
    pub fn new(mut matchers: Vec<Box<dyn Matcher>>) -> Self {
        let mut heap = BinaryHeap::new();
        let mut cost = 0;

        // Initialize heap with all non-empty matchers
        for matcher in matchers.drain(..) {
            if !matcher.is_exhausted() {
                cost += matcher.cost();
                heap.push(MatcherEntry { matcher });
            }
        }

        let current_doc = heap
            .peek()
            .map(|entry| entry.matcher.doc_id())
            .unwrap_or(u64::MAX);
        let exhausted = heap.is_empty();

        DisjunctionMatcher {
            heap,
            current_doc,
            exhausted,
            cost,
            reinsert_buffer: Vec::new(),
        }
    }

    /// Create an empty disjunction matcher.
    pub fn empty() -> Self {
        DisjunctionMatcher {
            heap: BinaryHeap::new(),
            current_doc: u64::MAX,
            exhausted: true,
            cost: 0,
            reinsert_buffer: Vec::new(),
        }
    }

    /// Advance to the next document, skipping duplicates.
    fn advance_to_next_doc(&mut self) -> Result<()> {
        if self.exhausted {
            return Ok(());
        }

        let current_doc = self.current_doc;

        // Reuse buffer to avoid allocation on every call.
        self.reinsert_buffer.clear();

        // Advance all matchers that are at the current document
        while let Some(entry) = self.heap.peek() {
            if entry.matcher.doc_id() == current_doc {
                let mut entry = self.heap.pop().unwrap();
                if entry.matcher.next()? && !entry.matcher.is_exhausted() {
                    self.reinsert_buffer.push(entry);
                }
            } else {
                break;
            }
        }

        // Reinsert advanced matchers
        while let Some(entry) = self.reinsert_buffer.pop() {
            self.heap.push(entry);
        }

        // Update current document
        if let Some(entry) = self.heap.peek() {
            self.current_doc = entry.matcher.doc_id();
        } else {
            self.current_doc = u64::MAX;
            self.exhausted = true;
        }

        Ok(())
    }
}

impl Matcher for DisjunctionMatcher {
    fn doc_id(&self) -> u64 {
        self.current_doc
    }

    fn next(&mut self) -> Result<bool> {
        if self.exhausted {
            return Ok(false);
        }

        self.advance_to_next_doc()?;
        Ok(!self.exhausted)
    }

    fn skip_to(&mut self, target: u64) -> Result<bool> {
        if self.exhausted || target <= self.current_doc {
            return Ok(!self.exhausted);
        }

        // Reuse buffer to avoid allocation on every call.
        self.reinsert_buffer.clear();

        // Skip all matchers to target or beyond
        while let Some(mut entry) = self.heap.pop() {
            if entry.matcher.skip_to(target)? && !entry.matcher.is_exhausted() {
                self.reinsert_buffer.push(entry);
            }
        }

        // Reinsert matchers that successfully skipped
        while let Some(entry) = self.reinsert_buffer.pop() {
            self.heap.push(entry);
        }

        // Update current document
        if let Some(entry) = self.heap.peek() {
            self.current_doc = entry.matcher.doc_id();
            self.exhausted = false;
        } else {
            self.current_doc = u64::MAX;
            self.exhausted = true;
        }

        Ok(!self.exhausted)
    }

    fn cost(&self) -> u64 {
        self.cost
    }

    fn term_freq(&self) -> u64 {
        let mut total_freq = 0;
        for entry in self.heap.iter() {
            if entry.matcher.doc_id() == self.current_doc {
                total_freq += entry.matcher.term_freq();
            }
        }
        total_freq
    }

    fn is_exhausted(&self) -> bool {
        self.exhausted
    }
}

/// A matcher that implements conjunction (AND) of multiple matchers.
#[derive(Debug)]
pub struct ConjunctionMatcher {
    /// The matchers that must all match.
    matchers: Vec<Box<dyn Matcher>>,
    /// Current document ID.
    current_doc: u64,
    /// Whether this matcher is exhausted.
    exhausted: bool,
    /// Total cost estimate.
    cost: u64,
}

impl ConjunctionMatcher {
    /// Create a new conjunction matcher from multiple matchers.
    pub fn new(matchers: Vec<Box<dyn Matcher>>) -> Self {
        if matchers.is_empty() {
            return ConjunctionMatcher {
                matchers: vec![],
                current_doc: u64::MAX,
                exhausted: true,
                cost: 0,
            };
        }

        let cost = matchers.iter().map(|m| m.cost()).sum();
        let mut matcher = ConjunctionMatcher {
            matchers,
            current_doc: 0,
            exhausted: false,
            cost,
        };

        // Advance to the first matching document
        if let Ok(found) = matcher.advance_to_alignment() {
            if !found {
                matcher.exhausted = true;
                matcher.current_doc = u64::MAX;
            }
        } else {
            matcher.exhausted = true;
            matcher.current_doc = u64::MAX;
        }

        matcher
    }

    /// Advance all matchers to be aligned on the same document.
    fn advance_to_alignment(&mut self) -> Result<bool> {
        if self.matchers.is_empty() || self.exhausted {
            return Ok(false);
        }

        loop {
            // Find the maximum doc ID among all matchers
            let mut max_doc = 0;
            for matcher in &self.matchers {
                let doc_id = matcher.doc_id();
                if doc_id == u64::MAX {
                    self.exhausted = true;
                    return Ok(false);
                }
                if doc_id > max_doc {
                    max_doc = doc_id;
                }
            }

            // Try to advance all matchers to max_doc
            let mut all_aligned = true;
            for matcher in &mut self.matchers {
                let doc_id = matcher.doc_id();
                if doc_id < max_doc {
                    if !matcher.skip_to(max_doc)? {
                        self.exhausted = true;
                        return Ok(false);
                    }
                    if matcher.doc_id() != max_doc {
                        all_aligned = false;
                    }
                }
            }

            if all_aligned {
                self.current_doc = max_doc;
                return Ok(true);
            }
        }
    }
}

impl Matcher for ConjunctionMatcher {
    fn doc_id(&self) -> u64 {
        if self.exhausted {
            u64::MAX
        } else {
            self.current_doc
        }
    }

    fn next(&mut self) -> Result<bool> {
        if self.exhausted || self.matchers.is_empty() {
            return Ok(false);
        }

        // Advance the first matcher
        if !self.matchers[0].next()? {
            self.exhausted = true;
            self.current_doc = u64::MAX;
            return Ok(false);
        }

        // Realign all matchers
        self.advance_to_alignment()
    }

    fn skip_to(&mut self, target: u64) -> Result<bool> {
        if self.exhausted || target <= self.current_doc {
            return Ok(!self.exhausted && self.current_doc >= target);
        }

        // Skip the first matcher to target
        if !self.matchers[0].skip_to(target)? {
            self.exhausted = true;
            self.current_doc = u64::MAX;
            return Ok(false);
        }

        // Realign all matchers
        self.advance_to_alignment()
    }

    fn cost(&self) -> u64 {
        self.cost
    }

    fn is_exhausted(&self) -> bool {
        self.exhausted
    }
}

/// A matcher that excludes documents matched by negative matchers.
#[derive(Debug)]
pub struct ConjunctionNotMatcher {
    /// The positive matcher (documents must match this).
    positive: Box<dyn Matcher>,
    /// The negative matchers (documents must NOT match any of these).
    negatives: Vec<Box<dyn Matcher>>,
    /// Current document ID.
    current_doc: u64,
    /// Whether this matcher is exhausted.
    exhausted: bool,
    /// Total cost estimate.
    cost: u64,
}

impl ConjunctionNotMatcher {
    /// Create a new conjunction-not matcher.
    pub fn new(positive: Box<dyn Matcher>, negatives: Vec<Box<dyn Matcher>>) -> Self {
        let cost = positive.cost();
        let mut matcher = ConjunctionNotMatcher {
            positive,
            negatives,
            current_doc: 0,
            exhausted: false,
            cost,
        };

        // Advance to the first valid document
        if let Ok(found) = matcher.advance_to_next_valid() {
            if !found {
                matcher.exhausted = true;
                matcher.current_doc = u64::MAX;
            }
        } else {
            matcher.exhausted = true;
            matcher.current_doc = u64::MAX;
        }

        matcher
    }

    /// Check if the current document in positive matcher is excluded by any negative matcher.
    fn is_excluded(&mut self, doc_id: u64) -> Result<bool> {
        for negative in &mut self.negatives {
            // Skip negative matcher to the document
            if negative.doc_id() < doc_id {
                negative.skip_to(doc_id)?;
            }
            // If negative matcher is at the same document, it's excluded
            if negative.doc_id() == doc_id {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Advance to the next valid document (not excluded by negatives).
    fn advance_to_next_valid(&mut self) -> Result<bool> {
        loop {
            if self.positive.is_exhausted() {
                self.exhausted = true;
                self.current_doc = u64::MAX;
                return Ok(false);
            }

            let doc_id = self.positive.doc_id();
            if doc_id == u64::MAX {
                self.exhausted = true;
                self.current_doc = u64::MAX;
                return Ok(false);
            }

            if !self.is_excluded(doc_id)? {
                self.current_doc = doc_id;
                return Ok(true);
            }

            // Current document is excluded, move to next
            if !self.positive.next()? {
                self.exhausted = true;
                self.current_doc = u64::MAX;
                return Ok(false);
            }
        }
    }
}

impl Matcher for ConjunctionNotMatcher {
    fn doc_id(&self) -> u64 {
        if self.exhausted {
            u64::MAX
        } else {
            self.current_doc
        }
    }

    fn next(&mut self) -> Result<bool> {
        if self.exhausted {
            return Ok(false);
        }

        // Advance positive matcher
        if !self.positive.next()? {
            self.exhausted = true;
            self.current_doc = u64::MAX;
            return Ok(false);
        }

        // Find next valid document
        self.advance_to_next_valid()
    }

    fn skip_to(&mut self, target: u64) -> Result<bool> {
        if self.exhausted || target <= self.current_doc {
            return Ok(!self.exhausted && self.current_doc >= target);
        }

        // Skip positive matcher to target
        if !self.positive.skip_to(target)? {
            self.exhausted = true;
            self.current_doc = u64::MAX;
            return Ok(false);
        }

        // Find next valid document
        self.advance_to_next_valid()
    }

    fn cost(&self) -> u64 {
        self.cost
    }

    fn term_freq(&self) -> u64 {
        self.positive.term_freq()
    }

    fn is_exhausted(&self) -> bool {
        self.exhausted
    }
}

/// A matcher that matches all documents except those matched by the negative matcher.
#[derive(Debug)]
pub struct NotMatcher {
    /// The matcher for documents to exclude.
    negative: Box<dyn Matcher>,
    /// Maximum document ID.
    max_doc: u64,
    /// Current document ID.
    current_doc: u64,
    /// Whether this matcher is exhausted.
    exhausted: bool,
}

impl NotMatcher {
    /// Create a new NOT matcher.
    pub fn new(negative: Box<dyn Matcher>, max_doc: u64) -> Self {
        let mut matcher = NotMatcher {
            negative,
            max_doc,
            current_doc: 0,
            exhausted: false,
        };

        // Advance to the first valid document
        if let Ok(found) = matcher.advance_to_next_valid() {
            if !found {
                matcher.exhausted = true;
            }
        } else {
            matcher.exhausted = true;
        }

        matcher
    }

    /// Advance to the next document not matched by the negative matcher.
    fn advance_to_next_valid(&mut self) -> Result<bool> {
        while self.current_doc < self.max_doc {
            let neg_doc = self.negative.doc_id();

            if neg_doc > self.current_doc || neg_doc == u64::MAX {
                // Negative matcher is ahead or exhausted, current doc is valid
                return Ok(true);
            } else if neg_doc == self.current_doc {
                // Current doc is excluded, move to next
                self.current_doc += 1;
                // Also advance negative matcher if needed
                if self.negative.doc_id() < self.current_doc && !self.negative.is_exhausted() {
                    self.negative.skip_to(self.current_doc)?;
                }
            } else {
                // Negative matcher is behind, skip it forward
                self.negative.skip_to(self.current_doc)?;
            }
        }

        self.current_doc = u64::MAX;
        self.exhausted = true;
        Ok(false)
    }
}

impl Matcher for NotMatcher {
    fn doc_id(&self) -> u64 {
        if self.exhausted || self.current_doc >= self.max_doc {
            u64::MAX
        } else {
            self.current_doc
        }
    }

    fn next(&mut self) -> Result<bool> {
        if self.exhausted || self.current_doc >= self.max_doc {
            return Ok(false);
        }

        self.current_doc += 1;
        self.advance_to_next_valid()
    }

    fn skip_to(&mut self, target: u64) -> Result<bool> {
        if self.exhausted || target <= self.current_doc {
            return Ok(!self.exhausted && self.current_doc < self.max_doc);
        }

        if target >= self.max_doc {
            self.current_doc = self.max_doc;
            self.exhausted = true;
            return Ok(false);
        }

        self.current_doc = target;
        self.advance_to_next_valid()
    }

    fn cost(&self) -> u64 {
        self.max_doc
    }

    fn is_exhausted(&self) -> bool {
        self.exhausted || self.current_doc >= self.max_doc
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_matcher() {
        let mut matcher = EmptyMatcher::new();

        assert_eq!(matcher.doc_id(), u64::MAX);
        assert!(matcher.is_exhausted());
        assert_eq!(matcher.cost(), 0);
        assert!(!matcher.next().unwrap());
        assert!(!matcher.skip_to(5).unwrap());
    }

    #[test]
    fn test_all_matcher() {
        let mut matcher = AllMatcher::new(5);

        assert_eq!(matcher.doc_id(), 0);
        assert!(!matcher.is_exhausted());
        assert_eq!(matcher.cost(), 5);

        // Test iteration
        assert!(matcher.next().unwrap());
        assert_eq!(matcher.doc_id(), 1);

        assert!(matcher.next().unwrap());
        assert_eq!(matcher.doc_id(), 2);

        // Test skip_to
        assert!(matcher.skip_to(4).unwrap());
        assert_eq!(matcher.doc_id(), 4);

        assert!(!matcher.skip_to(10).unwrap());
        assert_eq!(matcher.doc_id(), u64::MAX);
        assert!(matcher.is_exhausted());
    }

    #[test]
    fn test_posting_matcher() {
        let postings = vec![
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 0,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 1,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 2,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 3,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 4,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
        ];
        let posting_iter = Box::new(
            crate::lexical::index::inverted::reader::InvertedIndexPostingIterator::new(postings),
        );
        let mut matcher = PostingMatcher::new(posting_iter);

        assert_eq!(matcher.doc_id(), 0);
        assert!(!matcher.is_exhausted());
        assert_eq!(matcher.cost(), 5);

        // Test iteration
        for i in 1..5 {
            assert!(matcher.next().unwrap());
            assert_eq!(matcher.doc_id(), i);
        }

        assert!(!matcher.next().unwrap());
        assert!(matcher.is_exhausted());
    }

    #[test]
    fn test_exhausted_posting_matcher() {
        let matcher = PostingMatcher::exhausted();

        assert_eq!(matcher.doc_id(), u64::MAX);
        assert!(matcher.is_exhausted());
        assert_eq!(matcher.cost(), 0);
    }

    #[test]
    fn test_conjunction_matcher() {
        // Create two posting matchers with overlapping documents
        let postings1 = vec![
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 0,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 2,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 4,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 6,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 8,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
        ];
        let matcher1 = Box::new(PostingMatcher::new(Box::new(
            crate::lexical::index::inverted::reader::InvertedIndexPostingIterator::new(postings1),
        )));

        let postings2 = vec![
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 1,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 2,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 3,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 4,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 5,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 6,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
        ];
        let matcher2 = Box::new(PostingMatcher::new(Box::new(
            crate::lexical::index::inverted::reader::InvertedIndexPostingIterator::new(postings2),
        )));

        let mut conjunction = ConjunctionMatcher::new(vec![matcher1, matcher2]);

        // Should match documents 2, 4, 6 (intersection)
        assert_eq!(conjunction.doc_id(), 2);
        assert!(!conjunction.is_exhausted());

        assert!(conjunction.next().unwrap());
        assert_eq!(conjunction.doc_id(), 4);

        assert!(conjunction.next().unwrap());
        assert_eq!(conjunction.doc_id(), 6);

        assert!(!conjunction.next().unwrap());
        assert!(conjunction.is_exhausted());
    }

    #[test]
    fn test_conjunction_not_matcher() {
        // Positive matcher: documents 0, 1, 2, 3, 4, 5
        let postings_pos = vec![
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 0,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 1,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 2,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 3,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 4,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 5,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
        ];
        let positive = Box::new(PostingMatcher::new(Box::new(
            crate::lexical::index::inverted::reader::InvertedIndexPostingIterator::new(
                postings_pos,
            ),
        )));

        // Negative matcher: documents 1, 3, 5
        let postings_neg = vec![
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 1,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 3,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 5,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
        ];
        let negative = Box::new(PostingMatcher::new(Box::new(
            crate::lexical::index::inverted::reader::InvertedIndexPostingIterator::new(
                postings_neg,
            ),
        )));

        let mut conj_not = ConjunctionNotMatcher::new(positive, vec![negative]);

        // Should match documents 0, 2, 4 (positive minus negative)
        assert_eq!(conj_not.doc_id(), 0);
        assert!(!conj_not.is_exhausted());

        assert!(conj_not.next().unwrap());
        assert_eq!(conj_not.doc_id(), 2);

        assert!(conj_not.next().unwrap());
        assert_eq!(conj_not.doc_id(), 4);

        assert!(!conj_not.next().unwrap());
        assert!(conj_not.is_exhausted());
    }

    #[test]
    fn test_not_matcher() {
        // Negative matcher: documents 1, 3, 5
        let postings_neg = vec![
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 1,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 3,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 5,
                frequency: 1,
                positions: Some(vec![]),
                weight: 1.0,
            },
        ];
        let negative = Box::new(PostingMatcher::new(Box::new(
            crate::lexical::index::inverted::reader::InvertedIndexPostingIterator::new(
                postings_neg,
            ),
        )));

        let mut not_matcher = NotMatcher::new(negative, 7);

        // Should match documents 0, 2, 4, 6 (all except 1, 3, 5)
        assert_eq!(not_matcher.doc_id(), 0);
        assert!(!not_matcher.is_exhausted());

        assert!(not_matcher.next().unwrap());
        assert_eq!(not_matcher.doc_id(), 2);

        assert!(not_matcher.next().unwrap());
        assert_eq!(not_matcher.doc_id(), 4);

        assert!(not_matcher.next().unwrap());
        assert_eq!(not_matcher.doc_id(), 6);

        assert!(!not_matcher.next().unwrap());
        assert!(not_matcher.is_exhausted());
    }

    #[test]
    fn test_conjunction_matcher_empty() {
        let conjunction = ConjunctionMatcher::new(vec![]);
        assert_eq!(conjunction.doc_id(), u64::MAX);
        assert!(conjunction.is_exhausted());
    }

    #[test]
    fn test_conjunction_matcher_no_overlap() {
        // Create two posting matchers with no overlapping documents
        let postings1 = vec![
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 0,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 2,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 4,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
        ];
        let matcher1 = Box::new(PostingMatcher::new(Box::new(
            crate::lexical::index::inverted::reader::InvertedIndexPostingIterator::new(postings1),
        )));

        let postings2 = vec![
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 1,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 3,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
            crate::lexical::index::inverted::core::posting::Posting {
                doc_id: 5,
                frequency: 1_u32,
                positions: Some(vec![]),
                weight: 1.0,
            },
        ];
        let matcher2 = Box::new(PostingMatcher::new(Box::new(
            crate::lexical::index::inverted::reader::InvertedIndexPostingIterator::new(postings2),
        )));

        let conjunction = ConjunctionMatcher::new(vec![matcher1, matcher2]);

        // Should have no matches
        assert_eq!(conjunction.doc_id(), u64::MAX);
        assert!(conjunction.is_exhausted());
    }
}

/// A matcher that works with pre-computed document IDs.
/// This is used for BKD Tree results where document IDs are already filtered.
#[derive(Debug)]
pub struct PreComputedMatcher {
    /// Pre-sorted document IDs that match the query.
    doc_ids: Vec<u64>,
    /// Current position in the doc_ids vector.
    current_index: usize,
    /// Whether this matcher is exhausted.
    exhausted: bool,
}

impl PreComputedMatcher {
    /// Create a new pre-computed matcher with sorted document IDs.
    pub fn new(mut doc_ids: Vec<u64>) -> Self {
        doc_ids.sort_unstable();
        doc_ids.dedup();

        let exhausted = doc_ids.is_empty();

        PreComputedMatcher {
            doc_ids,
            current_index: 0,
            exhausted,
        }
    }

    /// Create an empty pre-computed matcher.
    pub fn empty() -> Self {
        PreComputedMatcher {
            doc_ids: Vec::new(),
            current_index: 0,
            exhausted: true,
        }
    }
}

impl Matcher for PreComputedMatcher {
    fn doc_id(&self) -> u64 {
        if self.exhausted || self.current_index >= self.doc_ids.len() {
            u64::MAX
        } else {
            self.doc_ids[self.current_index]
        }
    }

    fn next(&mut self) -> Result<bool> {
        if self.exhausted {
            return Ok(false);
        }

        self.current_index += 1;
        if self.current_index >= self.doc_ids.len() {
            self.exhausted = true;
            Ok(false)
        } else {
            Ok(true)
        }
    }

    fn skip_to(&mut self, target: u64) -> Result<bool> {
        if self.exhausted {
            return Ok(false);
        }

        // Binary search for the first doc_id >= target
        let mut left = self.current_index;
        let mut right = self.doc_ids.len();

        while left < right {
            let mid = left + (right - left) / 2;
            if self.doc_ids[mid] >= target {
                right = mid;
            } else {
                left = mid + 1;
            }
        }

        self.current_index = left;
        if self.current_index >= self.doc_ids.len() {
            self.exhausted = true;
            Ok(false)
        } else {
            Ok(true)
        }
    }

    fn cost(&self) -> u64 {
        self.doc_ids.len() as u64
    }

    fn is_exhausted(&self) -> bool {
        self.exhausted
    }
}