Skip to main content

allsource_core/infrastructure/search/
hybrid_search_engine.rs

1//! HybridSearchEngine - Combined semantic and keyword search orchestrator
2//!
3//! This module provides:
4//! - Unified search interface combining VectorSearchEngine (semantic) and KeywordSearchEngine (keyword)
5//! - Score combination and re-ranking using Reciprocal Rank Fusion (RRF)
6//! - Metadata filtering (event_type, entity_id, time range)
7//! - Configurable search modes (semantic-only, keyword-only, hybrid)
8
9use crate::error::Result;
10use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use std::{collections::HashMap, sync::Arc};
13use uuid::Uuid;
14
15use super::{
16    KeywordQuery, KeywordSearchEngine, KeywordSearchResult, SimilarityQuery, SimilarityResult,
17    VectorSearchEngine,
18};
19
20/// Configuration for the HybridSearchEngine
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct HybridSearchEngineConfig {
23    /// Weight for semantic search scores (0.0 to 1.0)
24    pub semantic_weight: f32,
25    /// Weight for keyword search scores (0.0 to 1.0)
26    pub keyword_weight: f32,
27    /// RRF constant k (typically 60)
28    pub rrf_k: f32,
29    /// Default number of results to return
30    pub default_limit: usize,
31    /// Minimum score threshold for final results (0.0 to 1.0)
32    pub min_score_threshold: f32,
33    /// Over-fetch multiplier for filtering (fetch N * multiplier before filtering)
34    pub over_fetch_multiplier: usize,
35}
36
37impl Default for HybridSearchEngineConfig {
38    fn default() -> Self {
39        Self {
40            semantic_weight: 0.5,
41            keyword_weight: 0.5,
42            rrf_k: 60.0,
43            default_limit: 10,
44            min_score_threshold: 0.0,
45            over_fetch_multiplier: 3,
46        }
47    }
48}
49
50/// Search mode for the hybrid search
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
52pub enum SearchMode {
53    /// Use only semantic (vector) search
54    SemanticOnly,
55    /// Use only keyword (BM25) search
56    KeywordOnly,
57    /// Combine both semantic and keyword search (default)
58    #[default]
59    Hybrid,
60}
61
62/// Metadata filters for search queries
63#[derive(Debug, Clone, Default, Serialize, Deserialize)]
64pub struct MetadataFilters {
65    /// Filter by event type (exact match)
66    pub event_type: Option<String>,
67    /// Filter by entity ID (exact match)
68    pub entity_id: Option<String>,
69    /// Filter by start time (events on or after this time)
70    pub time_from: Option<DateTime<Utc>>,
71    /// Filter by end time (events on or before this time)
72    pub time_to: Option<DateTime<Utc>>,
73}
74
75impl MetadataFilters {
76    pub fn new() -> Self {
77        Self::default()
78    }
79
80    pub fn with_event_type(mut self, event_type: impl Into<String>) -> Self {
81        self.event_type = Some(event_type.into());
82        self
83    }
84
85    pub fn with_entity_id(mut self, entity_id: impl Into<String>) -> Self {
86        self.entity_id = Some(entity_id.into());
87        self
88    }
89
90    pub fn with_time_range(mut self, from: DateTime<Utc>, to: DateTime<Utc>) -> Self {
91        self.time_from = Some(from);
92        self.time_to = Some(to);
93        self
94    }
95
96    pub fn with_time_from(mut self, from: DateTime<Utc>) -> Self {
97        self.time_from = Some(from);
98        self
99    }
100
101    pub fn with_time_to(mut self, to: DateTime<Utc>) -> Self {
102        self.time_to = Some(to);
103        self
104    }
105
106    /// Check if any filters are set
107    pub fn has_filters(&self) -> bool {
108        self.event_type.is_some()
109            || self.entity_id.is_some()
110            || self.time_from.is_some()
111            || self.time_to.is_some()
112    }
113}
114
115/// Unified search query combining all search options
116#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct SearchQuery {
118    /// The search query string (natural language or keywords)
119    pub query: String,
120    /// Maximum number of results to return
121    pub limit: usize,
122    /// Optional tenant filter for multi-tenancy
123    pub tenant_id: Option<String>,
124    /// Search mode (semantic, keyword, or hybrid)
125    pub mode: SearchMode,
126    /// Metadata filters
127    pub filters: MetadataFilters,
128    /// Minimum similarity threshold for semantic search (0.0 to 1.0)
129    pub min_similarity: Option<f32>,
130    /// Precomputed embedding of `query`; when absent the vector engine embeds it.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub query_embedding: Option<Vec<f32>>,
133    /// Per-query overrides of the configured fusion weights.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub semantic_weight: Option<f32>,
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub keyword_weight: Option<f32>,
138}
139
140impl SearchQuery {
141    pub fn new(query: impl Into<String>) -> Self {
142        Self {
143            query: query.into(),
144            limit: 10,
145            tenant_id: None,
146            mode: SearchMode::Hybrid,
147            filters: MetadataFilters::default(),
148            min_similarity: None,
149            query_embedding: None,
150            semantic_weight: None,
151            keyword_weight: None,
152        }
153    }
154
155    pub fn with_query_embedding(mut self, embedding: Vec<f32>) -> Self {
156        self.query_embedding = Some(embedding);
157        self
158    }
159
160    pub fn with_weights(mut self, semantic: Option<f32>, keyword: Option<f32>) -> Self {
161        self.semantic_weight = semantic;
162        self.keyword_weight = keyword;
163        self
164    }
165
166    pub fn with_limit(mut self, limit: usize) -> Self {
167        self.limit = limit;
168        self
169    }
170
171    pub fn with_tenant(mut self, tenant_id: impl Into<String>) -> Self {
172        self.tenant_id = Some(tenant_id.into());
173        self
174    }
175
176    pub fn with_mode(mut self, mode: SearchMode) -> Self {
177        self.mode = mode;
178        self
179    }
180
181    pub fn with_filters(mut self, filters: MetadataFilters) -> Self {
182        self.filters = filters;
183        self
184    }
185
186    pub fn with_event_type(mut self, event_type: impl Into<String>) -> Self {
187        self.filters.event_type = Some(event_type.into());
188        self
189    }
190
191    pub fn with_entity_id(mut self, entity_id: impl Into<String>) -> Self {
192        self.filters.entity_id = Some(entity_id.into());
193        self
194    }
195
196    pub fn with_time_range(mut self, from: DateTime<Utc>, to: DateTime<Utc>) -> Self {
197        self.filters.time_from = Some(from);
198        self.filters.time_to = Some(to);
199        self
200    }
201
202    pub fn with_min_similarity(mut self, threshold: f32) -> Self {
203        self.min_similarity = Some(threshold);
204        self
205    }
206
207    /// Create a semantic-only search query
208    pub fn semantic(query: impl Into<String>) -> Self {
209        Self::new(query).with_mode(SearchMode::SemanticOnly)
210    }
211
212    /// Create a keyword-only search query
213    pub fn keyword(query: impl Into<String>) -> Self {
214        Self::new(query).with_mode(SearchMode::KeywordOnly)
215    }
216}
217
218/// Result of a hybrid search
219#[derive(Debug, Clone, Serialize, Deserialize)]
220pub struct HybridSearchResult {
221    /// Event ID of the matching event
222    pub event_id: Uuid,
223    /// Combined score (0.0 to 1.0)
224    pub score: f32,
225    /// Individual semantic similarity score (if available)
226    pub semantic_score: Option<f32>,
227    /// Individual keyword relevance score (if available)
228    pub keyword_score: Option<f32>,
229    /// Event type (from keyword search if available)
230    pub event_type: Option<String>,
231    /// Entity ID (from keyword search if available)
232    pub entity_id: Option<String>,
233    /// Source text snippet (from vector search if available)
234    pub source_text: Option<String>,
235}
236
237/// Event metadata for filtering (stored alongside indexed data)
238#[derive(Debug, Clone, Default)]
239pub struct EventMetadata {
240    pub event_type: Option<String>,
241    pub entity_id: Option<String>,
242    pub timestamp: Option<DateTime<Utc>>,
243}
244
245/// An event plus its precomputed embedding, for [`HybridSearchEngine::index_embedded`].
246#[derive(Debug, Clone)]
247pub struct EmbeddedEvent {
248    pub event_id: Uuid,
249    pub tenant_id: String,
250    pub event_type: String,
251    pub entity_id: Option<String>,
252    pub payload: serde_json::Value,
253    pub timestamp: DateTime<Utc>,
254    pub embedding: Option<Vec<f32>>,
255}
256
257/// HybridSearchEngine - Orchestrates semantic and keyword search
258///
259/// Features:
260/// - Combines VectorSearchEngine (semantic) and KeywordSearchEngine (keyword)
261/// - Score fusion using Reciprocal Rank Fusion (RRF)
262/// - Metadata filtering for event_type, entity_id, and time range
263/// - Configurable search modes and weights
264pub struct HybridSearchEngine {
265    config: HybridSearchEngineConfig,
266    vector_engine: Arc<VectorSearchEngine>,
267    keyword_engine: Arc<KeywordSearchEngine>,
268    /// Event metadata cache for filtering
269    metadata_cache: parking_lot::RwLock<HashMap<Uuid, EventMetadata>>,
270    /// Statistics
271    stats: parking_lot::RwLock<EngineStats>,
272}
273
274#[derive(Debug, Default, Clone)]
275struct EngineStats {
276    total_searches: u64,
277    semantic_searches: u64,
278    keyword_searches: u64,
279    hybrid_searches: u64,
280}
281
282impl HybridSearchEngine {
283    /// Create a new HybridSearchEngine with existing engines
284    pub fn new(
285        vector_engine: Arc<VectorSearchEngine>,
286        keyword_engine: Arc<KeywordSearchEngine>,
287    ) -> Self {
288        Self::with_config(
289            vector_engine,
290            keyword_engine,
291            HybridSearchEngineConfig::default(),
292        )
293    }
294
295    /// Create a new HybridSearchEngine with custom configuration
296    pub fn with_config(
297        vector_engine: Arc<VectorSearchEngine>,
298        keyword_engine: Arc<KeywordSearchEngine>,
299        config: HybridSearchEngineConfig,
300    ) -> Self {
301        Self {
302            config,
303            vector_engine,
304            keyword_engine,
305            metadata_cache: parking_lot::RwLock::new(HashMap::new()),
306            stats: parking_lot::RwLock::new(EngineStats::default()),
307        }
308    }
309
310    /// Get the engine configuration
311    pub fn config(&self) -> &HybridSearchEngineConfig {
312        &self.config
313    }
314
315    /// Store metadata for an event (for post-search filtering)
316    pub fn store_metadata(&self, event_id: Uuid, metadata: EventMetadata) {
317        let mut cache = self.metadata_cache.write();
318        cache.insert(event_id, metadata);
319    }
320
321    /// Index an event in both engines
322    ///
323    /// This is a convenience method that indexes the event in both
324    /// the vector and keyword engines, and stores metadata for filtering.
325    #[cfg(any(feature = "vector-search", feature = "keyword-search"))]
326    pub async fn index_event(
327        &self,
328        event_id: Uuid,
329        tenant_id: &str,
330        event_type: &str,
331        entity_id: Option<&str>,
332        payload: &serde_json::Value,
333        timestamp: DateTime<Utc>,
334    ) -> Result<()> {
335        // Store metadata for filtering
336        self.store_metadata(
337            event_id,
338            EventMetadata {
339                event_type: Some(event_type.to_string()),
340                entity_id: entity_id.map(std::string::ToString::to_string),
341                timestamp: Some(timestamp),
342            },
343        );
344
345        // Index in keyword engine
346        #[cfg(feature = "keyword-search")]
347        self.keyword_engine
348            .index_event(event_id, tenant_id, event_type, entity_id, payload)?;
349
350        // Index in vector engine (requires embedding generation)
351        #[cfg(feature = "vector-search")]
352        {
353            let embedding = self.vector_engine.embed_event(payload)?;
354            let source_text = extract_source_text(payload);
355            self.vector_engine
356                .index_event(event_id, tenant_id, embedding, source_text)
357                .await?;
358        }
359
360        Ok(())
361    }
362
363    /// Stub for when features are not enabled
364    #[cfg(not(any(feature = "vector-search", feature = "keyword-search")))]
365    pub fn index_event<'a>(
366        &'a self,
367        event_id: Uuid,
368        _tenant_id: &str,
369        event_type: &str,
370        entity_id: Option<&str>,
371        _payload: &serde_json::Value,
372        timestamp: DateTime<Utc>,
373    ) -> impl std::future::Future<Output = Result<()>> + 'a {
374        let metadata = EventMetadata {
375            event_type: Some(event_type.to_string()),
376            entity_id: entity_id.map(str::to_string),
377            timestamp: Some(timestamp),
378        };
379        futures::future::lazy(move |_| {
380            self.store_metadata(event_id, metadata);
381            Ok(())
382        })
383    }
384
385    /// Index events whose embeddings the caller already computed, then commit.
386    ///
387    /// An event without an embedding is still keyword-searchable.
388    pub fn index_embedded(&self, events: Vec<EmbeddedEvent>) -> Result<()> {
389        let mut vectors = Vec::with_capacity(events.len());
390        for event in events {
391            self.keyword_engine.index_event(
392                event.event_id,
393                &event.tenant_id,
394                &event.event_type,
395                event.entity_id.as_deref(),
396                &event.payload,
397            )?;
398            if let Some(embedding) = event.embedding {
399                vectors.push(super::IndexedVector {
400                    event_id: event.event_id,
401                    tenant_id: event.tenant_id,
402                    embedding,
403                    source_text: extract_source_text(&event.payload),
404                });
405            }
406            self.store_metadata(
407                event.event_id,
408                EventMetadata {
409                    event_type: Some(event.event_type),
410                    entity_id: event.entity_id,
411                    timestamp: Some(event.timestamp),
412                },
413            );
414        }
415        self.vector_engine.index_batch(vectors)?;
416        self.commit()
417    }
418
419    /// Commit changes to both engines
420    #[cfg(feature = "keyword-search")]
421    pub fn commit(&self) -> Result<()> {
422        self.keyword_engine.commit()
423    }
424
425    #[cfg(not(feature = "keyword-search"))]
426    pub fn commit(&self) -> Result<()> {
427        Ok(())
428    }
429
430    /// Perform a search using the configured mode
431    ///
432    /// This is the main entry point for searching. It:
433    /// 1. Runs semantic search (if natural language query and mode allows)
434    /// 2. Runs keyword search (if keywords present and mode allows)
435    /// 3. Combines and re-ranks scores using RRF
436    /// 4. Applies metadata filters
437    /// 5. Returns top-k results
438    pub fn search(&self, query: &SearchQuery) -> Result<Vec<HybridSearchResult>> {
439        // Update stats
440        {
441            let mut stats = self.stats.write();
442            stats.total_searches += 1;
443            match query.mode {
444                SearchMode::SemanticOnly => stats.semantic_searches += 1,
445                SearchMode::KeywordOnly => stats.keyword_searches += 1,
446                SearchMode::Hybrid => stats.hybrid_searches += 1,
447            }
448        }
449
450        // Calculate how many results to fetch (over-fetch for filtering)
451        let fetch_limit = if query.filters.has_filters() {
452            query.limit * self.config.over_fetch_multiplier
453        } else {
454            query.limit
455        };
456
457        match query.mode {
458            SearchMode::SemanticOnly => self.search_semantic_only(query, fetch_limit),
459            SearchMode::KeywordOnly => self.search_keyword_only(query, fetch_limit),
460            SearchMode::Hybrid => self.search_hybrid(query, fetch_limit),
461        }
462    }
463
464    /// Search using only semantic (vector) search
465    fn search_semantic_only(
466        &self,
467        query: &SearchQuery,
468        fetch_limit: usize,
469    ) -> Result<Vec<HybridSearchResult>> {
470        let semantic_results = self.run_semantic_search(query, fetch_limit)?;
471
472        let mut results: Vec<HybridSearchResult> = semantic_results
473            .into_iter()
474            .map(|r| HybridSearchResult {
475                event_id: r.event_id,
476                score: r.score,
477                semantic_score: Some(r.score),
478                keyword_score: None,
479                event_type: self.get_cached_event_type(r.event_id),
480                entity_id: self.get_cached_entity_id(r.event_id),
481                source_text: r.source_text,
482            })
483            .collect();
484
485        // Apply metadata filters
486        self.apply_filters(&mut results, &query.filters);
487
488        // Apply minimum score threshold
489        results.retain(|r| r.score >= self.config.min_score_threshold);
490
491        // Truncate to requested limit
492        results.truncate(query.limit);
493
494        Ok(results)
495    }
496
497    /// Search using only keyword (BM25) search
498    fn search_keyword_only(
499        &self,
500        query: &SearchQuery,
501        fetch_limit: usize,
502    ) -> Result<Vec<HybridSearchResult>> {
503        let keyword_results = self.run_keyword_search(query, fetch_limit)?;
504
505        // Normalize keyword scores to 0-1 range
506        let max_score = keyword_results
507            .iter()
508            .map(|r| r.score)
509            .fold(0.0_f32, f32::max);
510
511        let mut results: Vec<HybridSearchResult> = keyword_results
512            .into_iter()
513            .map(|r| {
514                let normalized_score = if max_score > 0.0 {
515                    r.score / max_score
516                } else {
517                    0.0
518                };
519                HybridSearchResult {
520                    event_id: r.event_id,
521                    score: normalized_score,
522                    semantic_score: None,
523                    keyword_score: Some(r.score),
524                    event_type: Some(r.event_type),
525                    entity_id: r.entity_id,
526                    source_text: None,
527                }
528            })
529            .collect();
530
531        // Apply metadata filters
532        self.apply_filters(&mut results, &query.filters);
533
534        // Apply minimum score threshold
535        results.retain(|r| r.score >= self.config.min_score_threshold);
536
537        // Truncate to requested limit
538        results.truncate(query.limit);
539
540        Ok(results)
541    }
542
543    /// Search using hybrid (combined) search with RRF score fusion
544    fn search_hybrid(
545        &self,
546        query: &SearchQuery,
547        fetch_limit: usize,
548    ) -> Result<Vec<HybridSearchResult>> {
549        // Run both searches
550        let semantic_results = self.run_semantic_search(query, fetch_limit)?;
551        let keyword_results = self.run_keyword_search(query, fetch_limit)?;
552
553        let semantic_weight = query.semantic_weight.unwrap_or(self.config.semantic_weight);
554        let keyword_weight = query.keyword_weight.unwrap_or(self.config.keyword_weight);
555
556        // Build score maps with ranks
557        let mut combined_scores: HashMap<Uuid, HybridSearchResult> = HashMap::new();
558
559        // Process semantic results
560        for (rank, result) in semantic_results.into_iter().enumerate() {
561            let rrf_score = 1.0 / (self.config.rrf_k + rank as f32 + 1.0);
562            let weighted_score = rrf_score * semantic_weight;
563
564            combined_scores.insert(
565                result.event_id,
566                HybridSearchResult {
567                    event_id: result.event_id,
568                    score: weighted_score,
569                    semantic_score: Some(result.score),
570                    keyword_score: None,
571                    event_type: self.get_cached_event_type(result.event_id),
572                    entity_id: self.get_cached_entity_id(result.event_id),
573                    source_text: result.source_text,
574                },
575            );
576        }
577
578        // Process keyword results and combine with semantic
579        for (rank, result) in keyword_results.into_iter().enumerate() {
580            let rrf_score = 1.0 / (self.config.rrf_k + rank as f32 + 1.0);
581            let weighted_score = rrf_score * keyword_weight;
582
583            if let Some(existing) = combined_scores.get_mut(&result.event_id) {
584                // Combine scores
585                existing.score += weighted_score;
586                existing.keyword_score = Some(result.score);
587                // Prefer keyword engine's event_type and entity_id as they're stored
588                existing.event_type = Some(result.event_type);
589                existing.entity_id = result.entity_id;
590            } else {
591                combined_scores.insert(
592                    result.event_id,
593                    HybridSearchResult {
594                        event_id: result.event_id,
595                        score: weighted_score,
596                        semantic_score: None,
597                        keyword_score: Some(result.score),
598                        event_type: Some(result.event_type),
599                        entity_id: result.entity_id,
600                        source_text: None,
601                    },
602                );
603            }
604        }
605
606        // Convert to sorted vector
607        let mut results: Vec<HybridSearchResult> = combined_scores.into_values().collect();
608        results.sort_by(|a, b| {
609            b.score
610                .partial_cmp(&a.score)
611                .unwrap_or(std::cmp::Ordering::Equal)
612        });
613
614        // Apply metadata filters
615        self.apply_filters(&mut results, &query.filters);
616
617        // Apply minimum score threshold
618        results.retain(|r| r.score >= self.config.min_score_threshold);
619
620        // Truncate to requested limit
621        results.truncate(query.limit);
622
623        Ok(results)
624    }
625
626    /// Run semantic search
627    fn run_semantic_search(
628        &self,
629        query: &SearchQuery,
630        limit: usize,
631    ) -> Result<Vec<SimilarityResult>> {
632        let query_embedding = match &query.query_embedding {
633            Some(embedding) => embedding.clone(),
634            None => self.vector_engine.embed_text(&query.query)?,
635        };
636
637        let similarity_query = SimilarityQuery::new(query_embedding, limit)
638            .with_min_similarity(query.min_similarity.unwrap_or(0.0));
639
640        let similarity_query = if let Some(ref tenant_id) = query.tenant_id {
641            similarity_query.with_tenant(tenant_id.clone())
642        } else {
643            similarity_query
644        };
645
646        self.vector_engine.search_similar(&similarity_query)
647    }
648
649    /// Run keyword search
650    fn run_keyword_search(
651        &self,
652        query: &SearchQuery,
653        limit: usize,
654    ) -> Result<Vec<KeywordSearchResult>> {
655        let keyword_query = KeywordQuery::new(&query.query).with_limit(limit);
656
657        let keyword_query = if let Some(ref tenant_id) = query.tenant_id {
658            keyword_query.with_tenant(tenant_id)
659        } else {
660            keyword_query
661        };
662
663        self.keyword_engine.search_keywords(&keyword_query)
664    }
665
666    /// Apply metadata filters to results
667    fn apply_filters(&self, results: &mut Vec<HybridSearchResult>, filters: &MetadataFilters) {
668        if !filters.has_filters() {
669            return;
670        }
671
672        let metadata_cache = self.metadata_cache.read();
673
674        results.retain(|result| {
675            // Get cached metadata
676            let cached = metadata_cache.get(&result.event_id);
677
678            // Filter by event_type
679            if let Some(ref filter_type) = filters.event_type {
680                let event_type = result
681                    .event_type
682                    .as_ref()
683                    .or_else(|| cached.and_then(|m| m.event_type.as_ref()));
684                match event_type {
685                    Some(t) if t == filter_type => {}
686                    _ => return false,
687                }
688            }
689
690            // Filter by entity_id
691            if let Some(ref filter_entity) = filters.entity_id {
692                let entity_id = result
693                    .entity_id
694                    .as_ref()
695                    .or_else(|| cached.and_then(|m| m.entity_id.as_ref()));
696                match entity_id {
697                    Some(e) if e == filter_entity => {}
698                    _ => return false,
699                }
700            }
701
702            // Filter by time range
703            if filters.time_from.is_some() || filters.time_to.is_some() {
704                if let Some(timestamp) = cached.and_then(|m| m.timestamp) {
705                    if let Some(from) = filters.time_from
706                        && timestamp < from
707                    {
708                        return false;
709                    }
710                    if let Some(to) = filters.time_to
711                        && timestamp > to
712                    {
713                        return false;
714                    }
715                } else {
716                    // No timestamp available, exclude if time filter is required
717                    return false;
718                }
719            }
720
721            true
722        });
723    }
724
725    /// Get cached event type for an event
726    fn get_cached_event_type(&self, event_id: Uuid) -> Option<String> {
727        self.metadata_cache
728            .read()
729            .get(&event_id)
730            .and_then(|m| m.event_type.clone())
731    }
732
733    /// Get cached entity ID for an event
734    fn get_cached_entity_id(&self, event_id: Uuid) -> Option<String> {
735        self.metadata_cache
736            .read()
737            .get(&event_id)
738            .and_then(|m| m.entity_id.clone())
739    }
740
741    /// Get engine statistics
742    pub fn stats(&self) -> (u64, u64, u64, u64) {
743        let stats = self.stats.read();
744        (
745            stats.total_searches,
746            stats.semantic_searches,
747            stats.keyword_searches,
748            stats.hybrid_searches,
749        )
750    }
751
752    /// Health check for both engines
753    pub fn health_check(&self) -> Result<()> {
754        self.vector_engine.health_check()?;
755        self.keyword_engine.health_check()?;
756        Ok(())
757    }
758
759    /// Get the number of events in the metadata cache
760    pub fn cached_metadata_count(&self) -> usize {
761        self.metadata_cache.read().len()
762    }
763
764    /// Clear the metadata cache
765    pub fn clear_metadata_cache(&self) {
766        self.metadata_cache.write().clear();
767    }
768}
769
770/// Extract source text from a payload for the vector search engine
771fn extract_source_text(payload: &serde_json::Value) -> Option<String> {
772    let priority_fields = [
773        "content",
774        "text",
775        "body",
776        "message",
777        "description",
778        "title",
779        "name",
780    ];
781
782    if let serde_json::Value::Object(map) = payload {
783        for field in priority_fields {
784            if let Some(serde_json::Value::String(s)) = map.get(field)
785                && !s.is_empty()
786            {
787                return Some(s.clone());
788            }
789        }
790    }
791
792    // Fallback: convert entire payload to string
793    Some(payload.to_string())
794}
795
796#[cfg(all(test, not(any(feature = "vector-search", feature = "keyword-search"))))]
797mod deferred_tests;
798
799#[cfg(test)]
800mod tests {
801    use super::*;
802
803    fn create_test_config() -> HybridSearchEngineConfig {
804        HybridSearchEngineConfig {
805            semantic_weight: 0.5,
806            keyword_weight: 0.5,
807            rrf_k: 60.0,
808            default_limit: 10,
809            min_score_threshold: 0.0,
810            over_fetch_multiplier: 3,
811        }
812    }
813
814    #[test]
815    fn test_config_default() {
816        let config = HybridSearchEngineConfig::default();
817        assert_eq!(config.semantic_weight, 0.5);
818        assert_eq!(config.keyword_weight, 0.5);
819        assert_eq!(config.rrf_k, 60.0);
820        assert_eq!(config.default_limit, 10);
821    }
822
823    #[test]
824    fn test_search_query_builder() {
825        let query = SearchQuery::new("test query")
826            .with_limit(20)
827            .with_tenant("tenant-1")
828            .with_mode(SearchMode::Hybrid)
829            .with_event_type("UserCreated")
830            .with_entity_id("user-123")
831            .with_min_similarity(0.7);
832
833        assert_eq!(query.query, "test query");
834        assert_eq!(query.limit, 20);
835        assert_eq!(query.tenant_id, Some("tenant-1".to_string()));
836        assert_eq!(query.mode, SearchMode::Hybrid);
837        assert_eq!(query.filters.event_type, Some("UserCreated".to_string()));
838        assert_eq!(query.filters.entity_id, Some("user-123".to_string()));
839        assert_eq!(query.min_similarity, Some(0.7));
840    }
841
842    #[test]
843    fn test_search_query_semantic_constructor() {
844        let query = SearchQuery::semantic("natural language query");
845        assert_eq!(query.mode, SearchMode::SemanticOnly);
846    }
847
848    #[test]
849    fn test_search_query_keyword_constructor() {
850        let query = SearchQuery::keyword("keyword search");
851        assert_eq!(query.mode, SearchMode::KeywordOnly);
852    }
853
854    #[test]
855    fn test_metadata_filters_builder() {
856        let now = Utc::now();
857        let past = now - chrono::Duration::hours(1);
858
859        let filters = MetadataFilters::new()
860            .with_event_type("OrderPlaced")
861            .with_entity_id("order-456")
862            .with_time_range(past, now);
863
864        assert_eq!(filters.event_type, Some("OrderPlaced".to_string()));
865        assert_eq!(filters.entity_id, Some("order-456".to_string()));
866        assert!(filters.time_from.is_some());
867        assert!(filters.time_to.is_some());
868        assert!(filters.has_filters());
869    }
870
871    #[test]
872    fn test_metadata_filters_has_filters() {
873        let empty = MetadataFilters::new();
874        assert!(!empty.has_filters());
875
876        let with_type = MetadataFilters::new().with_event_type("Test");
877        assert!(with_type.has_filters());
878
879        let with_entity = MetadataFilters::new().with_entity_id("e1");
880        assert!(with_entity.has_filters());
881
882        let with_time = MetadataFilters::new().with_time_from(Utc::now());
883        assert!(with_time.has_filters());
884    }
885
886    #[test]
887    fn test_search_mode_default() {
888        let mode: SearchMode = Default::default();
889        assert_eq!(mode, SearchMode::Hybrid);
890    }
891
892    #[test]
893    fn test_hybrid_search_result_structure() {
894        let result = HybridSearchResult {
895            event_id: Uuid::new_v4(),
896            score: 0.85,
897            semantic_score: Some(0.9),
898            keyword_score: Some(0.8),
899            event_type: Some("UserCreated".to_string()),
900            entity_id: Some("user-123".to_string()),
901            source_text: Some("Test content".to_string()),
902        };
903
904        assert!(result.score > 0.0);
905        assert!(result.semantic_score.is_some());
906        assert!(result.keyword_score.is_some());
907    }
908
909    #[test]
910    fn test_event_metadata_default() {
911        let metadata = EventMetadata::default();
912        assert!(metadata.event_type.is_none());
913        assert!(metadata.entity_id.is_none());
914        assert!(metadata.timestamp.is_none());
915    }
916
917    #[test]
918    fn test_rrf_score_calculation() {
919        // Verify RRF formula: 1 / (k + rank + 1)
920        let k = 60.0_f32;
921
922        // Rank 0 (first result)
923        let score_rank_0 = 1.0 / (k + 0.0 + 1.0);
924        assert!((score_rank_0 - 0.01639344).abs() < 0.0001);
925
926        // Rank 1 (second result)
927        let score_rank_1 = 1.0 / (k + 1.0 + 1.0);
928        assert!((score_rank_1 - 0.01612903).abs() < 0.0001);
929
930        // Verify rank 0 > rank 1
931        assert!(score_rank_0 > score_rank_1);
932    }
933
934    #[test]
935    fn test_config_weights_validation() {
936        let config = create_test_config();
937
938        // Weights should sum to 1.0 for balanced hybrid search
939        assert!((config.semantic_weight + config.keyword_weight - 1.0).abs() < f32::EPSILON);
940    }
941
942    #[test]
943    fn test_search_query_with_time_range() {
944        let now = Utc::now();
945        let past = now - chrono::Duration::days(7);
946
947        let query = SearchQuery::new("test").with_time_range(past, now);
948
949        assert_eq!(query.filters.time_from, Some(past));
950        assert_eq!(query.filters.time_to, Some(now));
951    }
952
953    #[test]
954    fn test_search_query_serialization() {
955        let query = SearchQuery::new("test query")
956            .with_limit(5)
957            .with_tenant("tenant-1")
958            .with_mode(SearchMode::Hybrid);
959
960        // Should serialize without error
961        let json = serde_json::to_string(&query);
962        assert!(json.is_ok());
963
964        // Should deserialize without error
965        let deserialized: std::result::Result<SearchQuery, _> =
966            serde_json::from_str(&json.unwrap());
967        assert!(deserialized.is_ok());
968
969        let deserialized = deserialized.unwrap();
970        assert_eq!(deserialized.query, "test query");
971        assert_eq!(deserialized.limit, 5);
972    }
973
974    #[test]
975    fn test_hybrid_search_result_serialization() {
976        let result = HybridSearchResult {
977            event_id: Uuid::new_v4(),
978            score: 0.85,
979            semantic_score: Some(0.9),
980            keyword_score: Some(0.8),
981            event_type: Some("Test".to_string()),
982            entity_id: None,
983            source_text: None,
984        };
985
986        let json = serde_json::to_string(&result);
987        assert!(json.is_ok());
988    }
989}
990
991/// Integration tests that require both search features enabled
992#[cfg(test)]
993#[cfg(all(feature = "vector-search", feature = "keyword-search"))]
994mod integration_tests {
995    use super::*;
996    use crate::infrastructure::search::{KeywordSearchEngineConfig, VectorSearchEngineConfig};
997
998    // VectorSearchEngine::with_config eagerly calls TextEmbedding::try_new, which
999    // retrieves the ONNX model. cargo runs these tests in parallel, so on a cold
1000    // cache three concurrent retrievals race and one loses with
1001    // "Failed to retrieve model.onnx" — reproducibly the third test. Serialize
1002    // construction so the first call populates the cache and the rest read it.
1003    static MODEL_INIT: std::sync::Mutex<()> = std::sync::Mutex::new(());
1004
1005    fn create_test_engines() -> (Arc<VectorSearchEngine>, Arc<KeywordSearchEngine>) {
1006        let vector_engine = {
1007            // A poisoned lock only means another test panicked; the cache is still
1008            // usable, so recover rather than cascading the failure.
1009            let _guard = MODEL_INIT
1010                .lock()
1011                .unwrap_or_else(std::sync::PoisonError::into_inner);
1012
1013            Arc::new(
1014                VectorSearchEngine::with_config(VectorSearchEngineConfig {
1015                    default_similarity_threshold: 0.0,
1016                    ..Default::default()
1017                })
1018                .unwrap(),
1019            )
1020        };
1021
1022        let keyword_engine = Arc::new(
1023            KeywordSearchEngine::with_config(KeywordSearchEngineConfig {
1024                auto_commit: true,
1025                ..Default::default()
1026            })
1027            .unwrap(),
1028        );
1029
1030        (vector_engine, keyword_engine)
1031    }
1032
1033    #[tokio::test]
1034    async fn test_hybrid_search_integration() {
1035        let (vector_engine, keyword_engine) = create_test_engines();
1036        let hybrid_engine = HybridSearchEngine::new(vector_engine, keyword_engine);
1037
1038        let id1 = Uuid::new_v4();
1039        let id2 = Uuid::new_v4();
1040
1041        // Index events
1042        hybrid_engine
1043            .index_event(
1044                id1,
1045                "tenant-1",
1046                "UserCreated",
1047                Some("user-123"),
1048                &serde_json::json!({"name": "Alice", "email": "alice@example.com"}),
1049                Utc::now(),
1050            )
1051            .await
1052            .unwrap();
1053
1054        hybrid_engine
1055            .index_event(
1056                id2,
1057                "tenant-1",
1058                "OrderPlaced",
1059                Some("order-456"),
1060                &serde_json::json!({"product": "Widget", "quantity": 5}),
1061                Utc::now(),
1062            )
1063            .await
1064            .unwrap();
1065
1066        // Hybrid search
1067        let query = SearchQuery::new("Alice user").with_tenant("tenant-1");
1068        let results = hybrid_engine.search(&query).unwrap();
1069
1070        assert!(!results.is_empty());
1071        // Alice result should be first
1072        assert_eq!(results[0].event_id, id1);
1073    }
1074
1075    #[tokio::test]
1076    async fn test_search_with_event_type_filter() {
1077        let (vector_engine, keyword_engine) = create_test_engines();
1078        let hybrid_engine = HybridSearchEngine::new(vector_engine, keyword_engine);
1079
1080        let id1 = Uuid::new_v4();
1081        let id2 = Uuid::new_v4();
1082
1083        hybrid_engine
1084            .index_event(
1085                id1,
1086                "tenant-1",
1087                "UserCreated",
1088                None,
1089                &serde_json::json!({"data": "test user"}),
1090                Utc::now(),
1091            )
1092            .await
1093            .unwrap();
1094
1095        hybrid_engine
1096            .index_event(
1097                id2,
1098                "tenant-1",
1099                "OrderPlaced",
1100                None,
1101                &serde_json::json!({"data": "test order"}),
1102                Utc::now(),
1103            )
1104            .await
1105            .unwrap();
1106
1107        // Search with event_type filter
1108        let query = SearchQuery::new("test")
1109            .with_tenant("tenant-1")
1110            .with_event_type("UserCreated");
1111        let results = hybrid_engine.search(&query).unwrap();
1112
1113        assert_eq!(results.len(), 1);
1114        assert_eq!(results[0].event_type, Some("UserCreated".to_string()));
1115    }
1116
1117    #[tokio::test]
1118    async fn test_search_with_time_range_filter() {
1119        let (vector_engine, keyword_engine) = create_test_engines();
1120        let hybrid_engine = HybridSearchEngine::new(vector_engine, keyword_engine);
1121
1122        let now = Utc::now();
1123        let past = now - chrono::Duration::hours(2);
1124        let recent = now - chrono::Duration::minutes(30);
1125
1126        let id1 = Uuid::new_v4();
1127        let id2 = Uuid::new_v4();
1128
1129        // Old event
1130        hybrid_engine
1131            .index_event(
1132                id1,
1133                "tenant-1",
1134                "Event",
1135                None,
1136                &serde_json::json!({"data": "old event"}),
1137                past,
1138            )
1139            .await
1140            .unwrap();
1141
1142        // Recent event
1143        hybrid_engine
1144            .index_event(
1145                id2,
1146                "tenant-1",
1147                "Event",
1148                None,
1149                &serde_json::json!({"data": "recent event"}),
1150                recent,
1151            )
1152            .await
1153            .unwrap();
1154
1155        // Search for events in the last hour
1156        let one_hour_ago = now - chrono::Duration::hours(1);
1157        let query = SearchQuery::new("event")
1158            .with_tenant("tenant-1")
1159            .with_time_range(one_hour_ago, now);
1160        let results = hybrid_engine.search(&query).unwrap();
1161
1162        assert_eq!(results.len(), 1);
1163        assert_eq!(results[0].event_id, id2);
1164    }
1165
1166    #[test]
1167    fn test_health_check() {
1168        let (vector_engine, keyword_engine) = create_test_engines();
1169        let hybrid_engine = HybridSearchEngine::new(vector_engine, keyword_engine);
1170        assert!(hybrid_engine.health_check().is_ok());
1171    }
1172
1173    #[test]
1174    fn test_stats() {
1175        let (vector_engine, keyword_engine) = create_test_engines();
1176        let hybrid_engine = HybridSearchEngine::new(vector_engine, keyword_engine);
1177
1178        let (total, semantic, keyword, hybrid) = hybrid_engine.stats();
1179        assert_eq!(total, 0);
1180        assert_eq!(semantic, 0);
1181        assert_eq!(keyword, 0);
1182        assert_eq!(hybrid, 0);
1183    }
1184}