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