sochdb-query 2.0.2

SochDB query engine (sync-first execution and vector query planning)
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// SochDB - LLM-Optimized Embedded Database
// Copyright (C) 2026 Sushanth Reddy Vanagala (https://github.com/sushanthpy)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Hybrid Retrieval Pipeline (Task 3)
//!
//! This module implements a unified hybrid query planner combining:
//! - Vector similarity search (ANN)
//! - Lexical search (BM25)
//! - Metadata filtering (PRE-FILTER ONLY)
//! - Score fusion (RRF)
//! - Cross-encoder reranking
//!
//! ## CRITICAL INVARIANT: No Post-Filtering
//!
//! This module enforces a hard security invariant:
//! 
//! > **All filtering MUST occur during candidate generation, never after.**
//!
//! The `ExecutionStep::PostFilter` variant has been intentionally removed.
//! This guarantees:
//! 1. **Security by construction**: No leakage of filtered documents
//! 2. **No wasted compute**: We never score disallowed documents
//! 3. **Monotone property**: `result-set ⊆ allowed-set` (verifiable)
//!
//! ## Correct Pattern
//!
//! ```text
//! FilterIR + AuthScope → AllowedSet (computed once)
//!//! vector_search(query, AllowedSet) → filtered candidates
//! bm25_search(query, AllowedSet)   → filtered candidates
//!//! fusion(filtered_v, filtered_b)   → already correct!
//!//! rerank, limit                    → final results
//! ```
//!
//! ## Anti-Pattern (What We Prevent)
//!
//! ```text
//! BAD: vector_search() → candidates → filter → too few/leaky
//!      bm25_search()   → candidates → filter → inconsistent
//!      fusion()        → filter at end → SECURITY RISK!
//! ```
//!
//! ## Execution Plan
//!
//! ```text
//! HybridQuery
//!//!//! ┌─────────────────────────────────────────┐
//! │              ExecutionPlan              │
//! │  ┌─────────┐ ┌─────────┐ ┌──────────┐  │
//! │  │ Vector  │ │  BM25   │ │  Filter  │  │
//! │  │ Search  │ │ Search  │ │ (PRE-ONLY)│  │
//! │  └────┬────┘ └────┬────┘ └────┬─────┘  │
//! │       │           │           │        │
//! │       └─────┬─────┘           │        │
//! │             ▼                 │        │
//! │       ┌─────────┐             │        │
//! │       │  Fusion │◄────────────┘        │
//! │       │  (RRF)  │                      │
//! │       └────┬────┘                      │
//! │            ▼                           │
//! │       ┌─────────┐                      │
//! │       │ Rerank  │                      │
//! │       └────┬────┘                      │
//! │            ▼                           │
//! │       ┌─────────┐                      │
//! │       │  Limit  │                      │
//! │       └─────────┘                      │
//! └─────────────────────────────────────────┘
//! ```
//!
//! ## Scoring
//!
//! RRF fusion: `score(d) = Σ w_i / (k + rank_i(d))`
//! where k is typically 60 (robust default)

use std::collections::{HashMap, HashSet};
use std::cmp::Ordering;
use std::sync::Arc;

use crate::context_query::VectorIndex;
use crate::soch_ql::SochValue;

// ============================================================================
// Hybrid Query Builder
// ============================================================================

/// Builder for hybrid retrieval queries
#[derive(Debug, Clone)]
pub struct HybridQuery {
    /// Collection to search
    pub collection: String,
    
    /// Vector search component
    pub vector: Option<VectorQueryComponent>,
    
    /// Lexical (BM25) search component
    pub lexical: Option<LexicalQueryComponent>,
    
    /// Metadata filters
    pub filters: Vec<MetadataFilter>,
    
    /// Fusion configuration
    pub fusion: FusionConfig,
    
    /// Reranking configuration
    pub rerank: Option<RerankConfig>,
    
    /// Result limit
    pub limit: usize,
    
    /// Minimum score threshold
    pub min_score: Option<f32>,
}

impl HybridQuery {
    /// Create a new hybrid query builder
    pub fn new(collection: &str) -> Self {
        Self {
            collection: collection.to_string(),
            vector: None,
            lexical: None,
            filters: Vec::new(),
            fusion: FusionConfig::default(),
            rerank: None,
            limit: 10,
            min_score: None,
        }
    }
    
    /// Add vector search component
    pub fn with_vector(mut self, embedding: Vec<f32>, weight: f32) -> Self {
        self.vector = Some(VectorQueryComponent {
            embedding,
            weight,
            ef_search: 100,
        });
        self
    }
    
    /// Add vector search from text (requires embedding provider)
    pub fn with_vector_text(mut self, text: String, weight: f32) -> Self {
        self.vector = Some(VectorQueryComponent {
            embedding: Vec::new(), // Will be resolved at execution time
            weight,
            ef_search: 100,
        });
        // Store text for later resolution
        self.lexical = self.lexical.or(Some(LexicalQueryComponent {
            query: text,
            weight: 0.0, // Text stored but not used for lexical
            fields: vec!["content".to_string()],
        }));
        self
    }
    
    /// Add lexical (BM25) search component
    pub fn with_lexical(mut self, query: &str, weight: f32) -> Self {
        self.lexical = Some(LexicalQueryComponent {
            query: query.to_string(),
            weight,
            fields: vec!["content".to_string()],
        });
        self
    }
    
    /// Add lexical search with specific fields
    pub fn with_lexical_fields(mut self, query: &str, weight: f32, fields: Vec<String>) -> Self {
        self.lexical = Some(LexicalQueryComponent {
            query: query.to_string(),
            weight,
            fields,
        });
        self
    }
    
    /// Add metadata filter
    pub fn filter(mut self, field: &str, op: FilterOp, value: SochValue) -> Self {
        self.filters.push(MetadataFilter {
            field: field.to_string(),
            op,
            value,
        });
        self
    }
    
    /// Add equality filter
    pub fn filter_eq(self, field: &str, value: impl Into<SochValue>) -> Self {
        self.filter(field, FilterOp::Eq, value.into())
    }
    
    /// Add range filter
    pub fn filter_range(mut self, field: &str, min: Option<SochValue>, max: Option<SochValue>) -> Self {
        if let Some(min_val) = min {
            self.filters.push(MetadataFilter {
                field: field.to_string(),
                op: FilterOp::Gte,
                value: min_val,
            });
        }
        if let Some(max_val) = max {
            self.filters.push(MetadataFilter {
                field: field.to_string(),
                op: FilterOp::Lte,
                value: max_val,
            });
        }
        self
    }
    
    /// Set fusion method
    pub fn with_fusion(mut self, method: FusionMethod) -> Self {
        self.fusion.method = method;
        self
    }
    
    /// Set RRF k parameter
    pub fn with_rrf_k(mut self, k: f32) -> Self {
        self.fusion.rrf_k = k;
        self
    }
    
    /// Enable reranking
    pub fn with_rerank(mut self, model: &str, top_n: usize) -> Self {
        self.rerank = Some(RerankConfig {
            model: model.to_string(),
            top_n,
            batch_size: 32,
        });
        self
    }
    
    /// Set result limit
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }
    
    /// Set minimum score threshold
    pub fn min_score(mut self, score: f32) -> Self {
        self.min_score = Some(score);
        self
    }
}

/// Vector search component
#[derive(Debug, Clone)]
pub struct VectorQueryComponent {
    /// Query embedding
    pub embedding: Vec<f32>,
    /// Weight for fusion
    pub weight: f32,
    /// HNSW ef_search parameter
    pub ef_search: usize,
}

/// Lexical search component
#[derive(Debug, Clone)]
pub struct LexicalQueryComponent {
    /// Query text
    pub query: String,
    /// Weight for fusion
    pub weight: f32,
    /// Fields to search
    pub fields: Vec<String>,
}

/// Metadata filter
#[derive(Debug, Clone)]
pub struct MetadataFilter {
    /// Field name
    pub field: String,
    /// Comparison operator
    pub op: FilterOp,
    /// Value to compare
    pub value: SochValue,
}

/// Filter comparison operators
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterOp {
    /// Equal
    Eq,
    /// Not equal
    Ne,
    /// Greater than
    Gt,
    /// Greater than or equal
    Gte,
    /// Less than
    Lt,
    /// Less than or equal
    Lte,
    /// Contains (for arrays/strings)
    Contains,
    /// In set
    In,
}

/// Fusion configuration
#[derive(Debug, Clone)]
pub struct FusionConfig {
    /// Fusion method
    pub method: FusionMethod,
    /// RRF k parameter (default: 60)
    pub rrf_k: f32,
    /// Normalize scores before fusion
    pub normalize: bool,
}

impl Default for FusionConfig {
    fn default() -> Self {
        Self {
            method: FusionMethod::Rrf,
            rrf_k: 60.0,
            normalize: true,
        }
    }
}

/// Score fusion methods
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FusionMethod {
    /// Reciprocal Rank Fusion
    Rrf,
    /// Weighted sum of normalized scores
    WeightedSum,
    /// Max score from any source
    Max,
    /// Relative score fusion
    Rsf,
}

/// Reranking configuration
#[derive(Debug, Clone)]
pub struct RerankConfig {
    /// Reranker model
    pub model: String,
    /// Number of top candidates to rerank
    pub top_n: usize,
    /// Batch size for reranking
    pub batch_size: usize,
}

// ============================================================================
// Execution Plan
// ============================================================================

/// Execution plan for hybrid query
#[derive(Debug, Clone)]
pub struct HybridExecutionPlan {
    /// Query being executed
    pub query: HybridQuery,
    
    /// Execution steps
    pub steps: Vec<ExecutionStep>,
    
    /// Estimated cost
    pub estimated_cost: f64,
}

/// Individual execution step
#[derive(Debug, Clone)]
pub enum ExecutionStep {
    /// Vector similarity search
    VectorSearch {
        collection: String,
        ef_search: usize,
        weight: f32,
    },
    
    /// Lexical (BM25) search
    LexicalSearch {
        collection: String,
        query: String,
        fields: Vec<String>,
        weight: f32,
    },
    
    /// Pre-filter (before retrieval) - REQUIRED for security
    /// 
    /// This is the ONLY allowed filter step. Filters are always applied
    /// during candidate generation via AllowedSet, never after.
    PreFilter {
        filters: Vec<MetadataFilter>,
    },
    
    // NOTE: PostFilter has been REMOVED by design.
    // The "no post-filtering" invariant is a hard security requirement.
    // All filtering must happen via PreFilter -> AllowedSet -> candidate generation.
    // See unified_fusion.rs for the correct pattern.
    
    /// Score fusion
    Fusion {
        method: FusionMethod,
        rrf_k: f32,
    },
    
    /// Reranking (does NOT filter, only re-orders)
    Rerank {
        model: String,
        top_n: usize,
    },
    
    /// Limit results (applied AFTER all filtering is complete)
    Limit {
        count: usize,
        min_score: Option<f32>,
    },
    
    /// Redaction transform (post-retrieval modification, NOT filtering)
    /// 
    /// Unlike filtering (which removes candidates), redaction transforms
    /// the content of already-allowed documents. This preserves the
    /// invariant: result-set ⊆ allowed-set.
    Redact {
        /// Fields to redact
        fields: Vec<String>,
        /// Redaction method
        method: RedactionMethod,
    },
}

/// Redaction methods for post-retrieval content transformation
#[derive(Debug, Clone)]
pub enum RedactionMethod {
    /// Replace with a fixed string
    Replace(String),
    /// Mask with asterisks
    Mask,
    /// Remove the field entirely
    Remove,
    /// Hash the value
    Hash,
}

// ============================================================================
// Hybrid Query Executor
// ============================================================================

/// Executor for hybrid queries
pub struct HybridQueryExecutor<V: VectorIndex> {
    /// Vector index
    vector_index: Arc<V>,
    
    /// Lexical index (BM25)
    lexical_index: Arc<LexicalIndex>,
}

impl<V: VectorIndex> HybridQueryExecutor<V> {
    /// Create a new executor
    pub fn new(vector_index: Arc<V>, lexical_index: Arc<LexicalIndex>) -> Self {
        Self {
            vector_index,
            lexical_index,
        }
    }
    
    /// Execute a hybrid query
    pub fn execute(&self, query: &HybridQuery) -> Result<HybridQueryResult, HybridQueryError> {
        let mut candidates: HashMap<String, CandidateDoc> = HashMap::new();
        
        // Over-fetch factor for fusion
        let overfetch = (query.limit * 3).max(100);
        
        // Execute vector search
        if let Some(vector) = &query.vector {
            if !vector.embedding.is_empty() {
                let results = self.vector_index
                    .search_by_embedding(&query.collection, &vector.embedding, overfetch, None)
                    .map_err(HybridQueryError::VectorSearchError)?;
                
                for (rank, result) in results.iter().enumerate() {
                    let entry = candidates.entry(result.id.clone()).or_insert_with(|| {
                        CandidateDoc {
                            id: result.id.clone(),
                            content: result.content.clone(),
                            metadata: result.metadata.clone(),
                            vector_rank: None,
                            vector_score: None,
                            lexical_rank: None,
                            lexical_score: None,
                            fused_score: 0.0,
                        }
                    });
                    entry.vector_rank = Some(rank);
                    entry.vector_score = Some(result.score);
                }
            }
        }
        
        // Execute lexical search
        if let Some(lexical) = &query.lexical {
            if lexical.weight > 0.0 {
                let results = self.lexical_index.search(
                    &query.collection,
                    &lexical.query,
                    &lexical.fields,
                    overfetch,
                )?;
                
                for (rank, result) in results.iter().enumerate() {
                    let entry = candidates.entry(result.id.clone()).or_insert_with(|| {
                        CandidateDoc {
                            id: result.id.clone(),
                            content: result.content.clone(),
                            metadata: HashMap::new(),
                            vector_rank: None,
                            vector_score: None,
                            lexical_rank: None,
                            lexical_score: None,
                            fused_score: 0.0,
                        }
                    });
                    entry.lexical_rank = Some(rank);
                    entry.lexical_score = Some(result.score);
                }
            }
        }
        
        // Apply filters
        let filtered: Vec<CandidateDoc> = candidates
            .into_values()
            .filter(|doc| self.matches_filters(doc, &query.filters))
            .collect();
        
        // Fuse scores
        let mut fused = self.fuse_scores(filtered, query)?;
        
        // Sort by fused score (descending)
        fused.sort_by(|a, b| b.fused_score.partial_cmp(&a.fused_score).unwrap_or(Ordering::Equal));
        
        // Apply reranking (stub - would call reranker model)
        if let Some(rerank) = &query.rerank {
            fused = self.rerank(&fused, &query.lexical.as_ref().map(|l| l.query.clone()).unwrap_or_default(), rerank)?;
        }
        
        // Apply min_score filter
        if let Some(min) = query.min_score {
            fused.retain(|doc| doc.fused_score >= min);
        }
        
        // Limit results
        fused.truncate(query.limit);
        
        // Convert to results
        let results: Vec<HybridSearchResult> = fused
            .into_iter()
            .map(|doc| HybridSearchResult {
                id: doc.id,
                score: doc.fused_score,
                content: doc.content,
                metadata: doc.metadata,
                vector_score: doc.vector_score,
                lexical_score: doc.lexical_score,
            })
            .collect();
        
        Ok(HybridQueryResult {
            results,
            query: query.clone(),
            stats: HybridQueryStats {
                vector_candidates: 0, // Would be populated in real impl
                lexical_candidates: 0,
                filtered_candidates: 0,
                fusion_time_us: 0,
                rerank_time_us: 0,
            },
        })
    }
    
    /// Check if document matches all filters
    fn matches_filters(&self, doc: &CandidateDoc, filters: &[MetadataFilter]) -> bool {
        for filter in filters {
            if let Some(value) = doc.metadata.get(&filter.field) {
                if !self.match_filter(value, &filter.op, &filter.value) {
                    return false;
                }
            } else {
                // Field not present - filter fails
                return false;
            }
        }
        true
    }
    
    /// Match a single filter
    fn match_filter(&self, doc_value: &SochValue, op: &FilterOp, filter_value: &SochValue) -> bool {
        match op {
            FilterOp::Eq => doc_value == filter_value,
            FilterOp::Ne => doc_value != filter_value,
            FilterOp::Gt => self.compare_values(doc_value, filter_value) == Some(Ordering::Greater),
            FilterOp::Gte => matches!(self.compare_values(doc_value, filter_value), Some(Ordering::Greater | Ordering::Equal)),
            FilterOp::Lt => self.compare_values(doc_value, filter_value) == Some(Ordering::Less),
            FilterOp::Lte => matches!(self.compare_values(doc_value, filter_value), Some(Ordering::Less | Ordering::Equal)),
            FilterOp::Contains => self.value_contains(doc_value, filter_value),
            FilterOp::In => self.value_in_set(doc_value, filter_value),
        }
    }
    
    /// Compare two SochValues
    fn compare_values(&self, a: &SochValue, b: &SochValue) -> Option<Ordering> {
        match (a, b) {
            (SochValue::Int(a), SochValue::Int(b)) => Some(a.cmp(b)),
            (SochValue::UInt(a), SochValue::UInt(b)) => Some(a.cmp(b)),
            (SochValue::Float(a), SochValue::Float(b)) => a.partial_cmp(b),
            (SochValue::Text(a), SochValue::Text(b)) => Some(a.cmp(b)),
            _ => None,
        }
    }
    
    /// Check if value contains another
    fn value_contains(&self, doc_value: &SochValue, search_value: &SochValue) -> bool {
        match (doc_value, search_value) {
            (SochValue::Text(text), SochValue::Text(search)) => text.contains(search.as_str()),
            (SochValue::Array(arr), _) => arr.contains(search_value),
            _ => false,
        }
    }
    
    /// Check if value is in set
    fn value_in_set(&self, doc_value: &SochValue, set_value: &SochValue) -> bool {
        if let SochValue::Array(arr) = set_value {
            arr.contains(doc_value)
        } else {
            false
        }
    }
    
    /// Fuse scores from multiple sources
    fn fuse_scores(
        &self,
        candidates: Vec<CandidateDoc>,
        query: &HybridQuery,
    ) -> Result<Vec<CandidateDoc>, HybridQueryError> {
        let vector_weight = query.vector.as_ref().map(|v| v.weight).unwrap_or(0.0);
        let lexical_weight = query.lexical.as_ref().map(|l| l.weight).unwrap_or(0.0);
        
        let mut fused = candidates;
        
        match query.fusion.method {
            FusionMethod::Rrf => {
                // Reciprocal Rank Fusion
                // score(d) = Σ w_i / (k + rank_i(d))
                for doc in &mut fused {
                    let mut score = 0.0;
                    
                    if let Some(rank) = doc.vector_rank {
                        score += vector_weight / (query.fusion.rrf_k + rank as f32);
                    }
                    
                    if let Some(rank) = doc.lexical_rank {
                        score += lexical_weight / (query.fusion.rrf_k + rank as f32);
                    }
                    
                    doc.fused_score = score;
                }
            }
            
            FusionMethod::WeightedSum => {
                // Weighted sum of normalized scores
                for doc in &mut fused {
                    let mut score = 0.0;
                    
                    if let Some(s) = doc.vector_score {
                        score += vector_weight * s;
                    }
                    
                    if let Some(s) = doc.lexical_score {
                        score += lexical_weight * s;
                    }
                    
                    doc.fused_score = score;
                }
            }
            
            FusionMethod::Max => {
                // Maximum score from any source
                for doc in &mut fused {
                    let v_score = doc.vector_score.map(|s| vector_weight * s).unwrap_or(0.0);
                    let l_score = doc.lexical_score.map(|s| lexical_weight * s).unwrap_or(0.0);
                    doc.fused_score = v_score.max(l_score);
                }
            }
            
            FusionMethod::Rsf => {
                // Relative Score Fusion (simplified)
                for doc in &mut fused {
                    let mut score = 0.0;
                    let mut count = 0;
                    
                    if let Some(s) = doc.vector_score {
                        score += s;
                        count += 1;
                    }
                    
                    if let Some(s) = doc.lexical_score {
                        score += s;
                        count += 1;
                    }
                    
                    doc.fused_score = if count > 0 { score / count as f32 } else { 0.0 };
                }
            }
        }
        
        Ok(fused)
    }
    
    /// Rerank candidates using cross-encoder (stub)
    fn rerank(
        &self,
        candidates: &[CandidateDoc],
        query: &str,
        config: &RerankConfig,
    ) -> Result<Vec<CandidateDoc>, HybridQueryError> {
        // Take top_n candidates for reranking
        let to_rerank: Vec<_> = candidates.iter().take(config.top_n).cloned().collect();
        
        // Stub: In production, would call cross-encoder model
        // For now, just apply a small boost based on query term overlap
        let mut reranked = to_rerank;
        let query_terms: HashSet<&str> = query.split_whitespace().collect();
        
        for doc in &mut reranked {
            let content_terms: HashSet<&str> = doc.content.split_whitespace().collect();
            let overlap = query_terms.intersection(&content_terms).count();
            
            // Small boost for term overlap
            doc.fused_score += (overlap as f32) * 0.01;
        }
        
        // Add remaining candidates unchanged
        reranked.extend(candidates.iter().skip(config.top_n).cloned());
        
        Ok(reranked)
    }
}

/// Internal candidate document during processing
#[derive(Debug, Clone)]
struct CandidateDoc {
    id: String,
    content: String,
    metadata: HashMap<String, SochValue>,
    vector_rank: Option<usize>,
    vector_score: Option<f32>,
    lexical_rank: Option<usize>,
    lexical_score: Option<f32>,
    fused_score: f32,
}

// ============================================================================
// Lexical Index (BM25)
// ============================================================================

/// Simple lexical (BM25) index
pub struct LexicalIndex {
    /// Collections: name -> inverted index
    collections: std::sync::RwLock<HashMap<String, InvertedIndex>>,
}

/// Inverted index for a collection
struct InvertedIndex {
    /// Term -> posting list (doc_id, term_freq)
    postings: HashMap<String, Vec<(String, u32)>>,
    
    /// Document lengths
    doc_lengths: HashMap<String, u32>,
    
    /// Document contents
    documents: HashMap<String, String>,
    
    /// Average document length
    avg_doc_len: f32,
    
    /// BM25 parameters
    k1: f32,
    b: f32,
}

/// Lexical search result
#[derive(Debug, Clone)]
pub struct LexicalSearchResult {
    pub id: String,
    pub score: f32,
    pub content: String,
}

impl LexicalIndex {
    /// Create a new lexical index
    pub fn new() -> Self {
        Self {
            collections: std::sync::RwLock::new(HashMap::new()),
        }
    }
    
    /// Create collection
    pub fn create_collection(&self, name: &str) {
        let mut collections = self.collections.write().unwrap();
        collections.insert(name.to_string(), InvertedIndex {
            postings: HashMap::new(),
            doc_lengths: HashMap::new(),
            documents: HashMap::new(),
            avg_doc_len: 0.0,
            k1: 1.2,
            b: 0.75,
        });
    }
    
    /// Index a document
    pub fn index_document(&self, collection: &str, id: &str, content: &str) -> Result<(), HybridQueryError> {
        let mut collections = self.collections.write().unwrap();
        let index = collections.get_mut(collection)
            .ok_or_else(|| HybridQueryError::CollectionNotFound(collection.to_string()))?;
        
        // Tokenize
        let tokens: Vec<String> = content
            .split_whitespace()
            .map(|t| t.to_lowercase())
            .collect();
        
        let doc_len = tokens.len() as u32;
        
        // Update document length
        index.doc_lengths.insert(id.to_string(), doc_len);
        index.documents.insert(id.to_string(), content.to_string());
        
        // Update average doc length
        let total_len: u32 = index.doc_lengths.values().sum();
        index.avg_doc_len = total_len as f32 / index.doc_lengths.len() as f32;
        
        // Count term frequencies
        let mut term_freqs: HashMap<String, u32> = HashMap::new();
        for token in &tokens {
            *term_freqs.entry(token.clone()).or_insert(0) += 1;
        }
        
        // Update postings
        for (term, freq) in term_freqs {
            index.postings
                .entry(term)
                .or_insert_with(Vec::new)
                .push((id.to_string(), freq));
        }
        
        Ok(())
    }
    
    /// Search using BM25
    pub fn search(
        &self,
        collection: &str,
        query: &str,
        _fields: &[String],
        limit: usize,
    ) -> Result<Vec<LexicalSearchResult>, HybridQueryError> {
        let collections = self.collections.read().unwrap();
        let index = collections.get(collection)
            .ok_or_else(|| HybridQueryError::CollectionNotFound(collection.to_string()))?;
        
        // Tokenize query
        let query_terms: Vec<String> = query
            .split_whitespace()
            .map(|t| t.to_lowercase())
            .collect();
        
        let n = index.doc_lengths.len() as f32;
        let mut scores: HashMap<String, f32> = HashMap::new();
        
        // Calculate BM25 scores
        for term in &query_terms {
            if let Some(postings) = index.postings.get(term) {
                let df = postings.len() as f32;
                let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
                
                for (doc_id, tf) in postings {
                    let doc_len = *index.doc_lengths.get(doc_id).unwrap_or(&1) as f32;
                    let tf = *tf as f32;
                    
                    // BM25 formula
                    let score = idf * (tf * (index.k1 + 1.0)) / 
                        (tf + index.k1 * (1.0 - index.b + index.b * doc_len / index.avg_doc_len));
                    
                    *scores.entry(doc_id.clone()).or_insert(0.0) += score;
                }
            }
        }
        
        // Sort by score
        let mut results: Vec<_> = scores.into_iter().collect();
        results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(Ordering::Equal));
        
        // Convert to results
        let results: Vec<LexicalSearchResult> = results
            .into_iter()
            .take(limit)
            .map(|(id, score)| {
                let content = index.documents.get(&id).cloned().unwrap_or_default();
                LexicalSearchResult { id, score, content }
            })
            .collect();
        
        Ok(results)
    }
}

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

// ============================================================================
// Results
// ============================================================================

/// Hybrid search result
#[derive(Debug, Clone)]
pub struct HybridSearchResult {
    /// Document ID
    pub id: String,
    /// Fused score
    pub score: f32,
    /// Document content
    pub content: String,
    /// Document metadata
    pub metadata: HashMap<String, SochValue>,
    /// Score from vector search (if any)
    pub vector_score: Option<f32>,
    /// Score from lexical search (if any)
    pub lexical_score: Option<f32>,
}

/// Result of hybrid query execution
#[derive(Debug, Clone)]
pub struct HybridQueryResult {
    /// Search results
    pub results: Vec<HybridSearchResult>,
    /// Original query
    pub query: HybridQuery,
    /// Execution statistics
    pub stats: HybridQueryStats,
}

/// Execution statistics
#[derive(Debug, Clone, Default)]
pub struct HybridQueryStats {
    /// Candidates from vector search
    pub vector_candidates: usize,
    /// Candidates from lexical search
    pub lexical_candidates: usize,
    /// Candidates after filtering
    pub filtered_candidates: usize,
    /// Fusion time in microseconds
    pub fusion_time_us: u64,
    /// Rerank time in microseconds
    pub rerank_time_us: u64,
}

/// Hybrid query error
#[derive(Debug, Clone)]
pub enum HybridQueryError {
    /// Collection not found
    CollectionNotFound(String),
    /// Vector search error
    VectorSearchError(String),
    /// Lexical search error
    LexicalSearchError(String),
    /// Filter error
    FilterError(String),
    /// Rerank error
    RerankError(String),
}

impl std::fmt::Display for HybridQueryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CollectionNotFound(name) => write!(f, "Collection not found: {}", name),
            Self::VectorSearchError(msg) => write!(f, "Vector search error: {}", msg),
            Self::LexicalSearchError(msg) => write!(f, "Lexical search error: {}", msg),
            Self::FilterError(msg) => write!(f, "Filter error: {}", msg),
            Self::RerankError(msg) => write!(f, "Rerank error: {}", msg),
        }
    }
}

impl std::error::Error for HybridQueryError {}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_hybrid_query_builder() {
        let query = HybridQuery::new("documents")
            .with_vector(vec![0.1, 0.2, 0.3], 0.7)
            .with_lexical("search query", 0.3)
            .filter_eq("category", SochValue::Text("tech".to_string()))
            .with_fusion(FusionMethod::Rrf)
            .with_rerank("cross-encoder", 20)
            .limit(10);
        
        assert_eq!(query.collection, "documents");
        assert!(query.vector.is_some());
        assert!(query.lexical.is_some());
        assert_eq!(query.filters.len(), 1);
        assert_eq!(query.limit, 10);
    }
    
    #[test]
    fn test_lexical_index_bm25() {
        let index = LexicalIndex::new();
        index.create_collection("test");
        
        index.index_document("test", "doc1", "the quick brown fox").unwrap();
        index.index_document("test", "doc2", "the lazy dog sleeps").unwrap();
        index.index_document("test", "doc3", "quick fox jumps over the lazy dog").unwrap();
        
        let results = index.search("test", "quick fox", &[], 10).unwrap();
        
        assert!(!results.is_empty());
        // doc1 and doc3 should both appear in results (they both have "quick" and/or "fox")
        let ids: Vec<&str> = results.iter().map(|r| r.id.as_str()).collect();
        assert!(ids.contains(&"doc1") || ids.contains(&"doc3"));
        // doc2 should not appear (no "quick" or "fox")
        assert!(!ids.contains(&"doc2"));
    }
    
    #[test]
    fn test_rrf_fusion() {
        // RRF formula: score = Σ w / (k + rank)
        let k = 60.0;
        
        // Doc appears at rank 0 in vector, rank 5 in lexical
        let vector_weight = 0.7;
        let lexical_weight = 0.3;
        
        let score = vector_weight / (k + 0.0) + lexical_weight / (k + 5.0);
        
        // Should be approximately 0.0116 + 0.0046 = 0.0162
        assert!(score > 0.01 && score < 0.02);
    }
    
    #[test]
    fn test_filter_matching() {
        let filters = vec![
            MetadataFilter {
                field: "status".to_string(),
                op: FilterOp::Eq,
                value: SochValue::Text("active".to_string()),
            },
            MetadataFilter {
                field: "count".to_string(),
                op: FilterOp::Gte,
                value: SochValue::Int(10),
            },
        ];
        
        let mut metadata = HashMap::new();
        metadata.insert("status".to_string(), SochValue::Text("active".to_string()));
        metadata.insert("count".to_string(), SochValue::Int(15));
        
        // Create a mock candidate
        let doc = CandidateDoc {
            id: "test".to_string(),
            content: "test content".to_string(),
            metadata,
            vector_rank: None,
            vector_score: None,
            lexical_rank: None,
            lexical_score: None,
            fused_score: 0.0,
        };
        
        // Would pass filters
        assert!(doc.metadata.get("status") == Some(&SochValue::Text("active".to_string())));
        if let Some(SochValue::Int(count)) = doc.metadata.get("count") {
            assert!(*count >= 10);
        }
    }
}