Skip to main content

uqa_engine/search/
hybrid.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Hybrid text/vector query construction and execution.
8
9use super::{
10    storage_sql_error, Engine, HybridSearchParams, RobustHybridSearchParams, SQLError, ScoredEntry,
11};
12
13impl Engine {
14    /// Exact single-prior hybrid retrieval under cross-modal conditional
15    /// independence. Query-level Bayesian BM25 and query-pool-transformed KNN
16    /// emit signed prior-free evidence, the evidence logits add without
17    /// gating or confidence scaling, and the resolved corpus relevance prior
18    /// enters exactly once. Returns the top-`top_k` entries by descending
19    /// posterior score.
20    pub fn hybrid_search(&self, params: &HybridSearchParams) -> Result<Vec<ScoredEntry>, SQLError> {
21        self.with_direct_table_query(params.table, false, |engine, name, _| {
22            let signals = engine.build_hybrid_signals(
23                name,
24                params.text_field,
25                params.text_query,
26                params.vector_field,
27                &params.query_vector,
28                params.knn_pool,
29            )?;
30            let tree = uqa_operators::OperatorTree::BayesianEvidenceFusion {
31                signals,
32                base_rate: None,
33            };
34            let entries = crate::operator_tree_bridge::execute_scored_tree(
35                engine,
36                name,
37                params.table,
38                &[],
39                &tree,
40            )?;
41            Ok(uqa_scoring::rank_scored_entries_top_k(
42                entries,
43                params.top_k,
44            ))
45        })
46    }
47
48    /// Explicit robust positive-evidence hybrid ranking. This method applies
49    /// Softplus gating, confidence scaling, and adaptive query-pool weights;
50    /// its output is a bounded ranking heuristic rather than the exact
51    /// single-prior posterior returned by [`Self::hybrid_search`].
52    pub fn robust_hybrid_search(
53        &self,
54        params: &RobustHybridSearchParams,
55    ) -> Result<Vec<ScoredEntry>, SQLError> {
56        self.with_direct_table_query(params.table, false, |engine, name, _| {
57            let signals = engine.build_hybrid_signals(
58                name,
59                params.text_field,
60                params.text_query,
61                params.vector_field,
62                &params.query_vector,
63                params.knn_pool,
64            )?;
65            let tree = uqa_operators::OperatorTree::RobustPositiveEvidencePool {
66                signals,
67                alpha: params.alpha,
68                gating: uqa_operators::GatingSpec::Softplus,
69                weights: None,
70                logit_min: None,
71                logit_max: None,
72                adaptive_weights: true,
73            };
74            let entries = crate::operator_tree_bridge::execute_scored_tree(
75                engine,
76                name,
77                params.table,
78                &[],
79                &tree,
80            )?;
81            Ok(uqa_scoring::rank_scored_entries_top_k(
82                entries,
83                params.top_k,
84            ))
85        })
86    }
87
88    fn build_hybrid_signals(
89        &self,
90        table_name: &str,
91        text_field: &str,
92        text_query: &str,
93        vector_field: &str,
94        query_vector: &[f32],
95        knn_pool: usize,
96    ) -> Result<Vec<uqa_operators::OperatorTree>, SQLError> {
97        let Some(table) = self
98            .try_query_table(table_name)
99            .map_err(|error| storage_sql_error("resolve hybrid-search table", error))?
100        else {
101            return Err(SQLError::UnknownTable(table_name.to_string()));
102        };
103        self.validate_text_search_field(table_name, text_field)?;
104        let analyzer = table
105            .inverted_index
106            .read()
107            .search_analyzer_revision(text_field)
108            .map_err(|error| storage_sql_error("resolve hybrid analyzer revision", error))?;
109        let analyzed_terms = analyzer
110            .analyze_tokens(text_query)
111            .map_err(|error| storage_sql_error("analyze hybrid text query", error))?;
112        let mut signals = Vec::new();
113        if !analyzed_terms.tokens().is_empty() {
114            signals.push(uqa_operators::OperatorTree::Term {
115                query: text_query.to_string(),
116                field: Some(text_field.to_string()),
117                scoring: Some(uqa_operators::TextScoringMode::BayesianBM25),
118                top_k: None,
119            });
120        }
121
122        // The vector field is part of the hybrid API contract even when its
123        // candidate pool is empty. Always lower the leaf so EngineDriver
124        // validates field existence, index availability, dimensions, and
125        // finite query values instead of silently degrading to text-only.
126        signals.push(uqa_operators::OperatorTree::CalibratedVectorMatch {
127            query_vector: query_vector.to_vec(),
128            k: knn_pool,
129            field: vector_field.to_string(),
130            threshold: None,
131        });
132        Ok(signals)
133    }
134}