Skip to main content

post_cortex_embeddings/embeddings/
engine.rs

1// Copyright (c) 2025 Julius ML
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12
13//! `LocalEmbeddingEngine` — the public entry point.
14//!
15//! Selects a backend based on [`EmbeddingConfig::model_type`] and wraps the BERT
16//! path with concurrency control, timeouts, and adaptive batch sizing. The static
17//! path is dispatched directly.
18
19use anyhow::Result;
20use dashmap::DashMap;
21use std::sync::Arc;
22use std::sync::atomic::{AtomicUsize, Ordering};
23use std::time::Duration;
24use tokio::time::timeout;
25use tracing::{debug, error, info, warn};
26
27use super::backend::EmbeddingBackend;
28#[cfg(feature = "bert")]
29use super::backends::BertBackend;
30#[cfg(feature = "model2vec")]
31use super::backends::Model2VecBackend;
32use super::backends::StaticHashBackend;
33use super::concurrency::ConcurrencyController;
34use super::config::{EmbeddingConfig, EmbeddingModelType};
35use super::pool::MemoryPool;
36
37/// Local embedding engine.
38pub struct LocalEmbeddingEngine {
39    backend: Arc<dyn EmbeddingBackend>,
40    config: EmbeddingConfig,
41    /// Current batch size (atomic — adapts based on runtime performance).
42    current_batch_size: AtomicUsize,
43    /// Performance metric per observed batch size — drives adaptive batching.
44    batch_performance_cache: Arc<DashMap<usize, f64>>,
45    /// Concurrency gate for the BERT path.
46    concurrency_controller: Arc<ConcurrencyController>,
47}
48
49impl LocalEmbeddingEngine {
50    /// Create a new embedding engine with the given configuration.
51    pub async fn new(config: EmbeddingConfig) -> Result<Self> {
52        info!(
53            "Initializing embedding engine with model: {:?}",
54            config.model_type
55        );
56
57        let dimension = config.model_type.embedding_dimension();
58        let backend: Arc<dyn EmbeddingBackend> = if config.model_type.is_model2vec() {
59            #[cfg(feature = "model2vec")]
60            {
61                Arc::new(Model2VecBackend::load(config.model_type).await?)
62            }
63            #[cfg(not(feature = "model2vec"))]
64            {
65                return Err(anyhow::anyhow!(
66                    "Model type {:?} requires the `model2vec` feature, which is disabled. \
67                     Rebuild post-cortex-embeddings with `--features model2vec` or pick a \
68                     different EmbeddingModelType.",
69                    config.model_type
70                ));
71            }
72        } else if config.model_type.is_bert_based() {
73            #[cfg(feature = "bert")]
74            {
75                Arc::new(BertBackend::load(config.model_type).await?)
76            }
77            #[cfg(not(feature = "bert"))]
78            {
79                return Err(anyhow::anyhow!(
80                    "Model type {:?} requires the `bert` feature, which is disabled. \
81                     Rebuild post-cortex-embeddings with `--features bert` or pick a \
82                     different EmbeddingModelType.",
83                    config.model_type
84                ));
85            }
86        } else {
87            let pool = Arc::new(MemoryPool::new(config.memory_pool_size, dimension));
88            Arc::new(StaticHashBackend::new(dimension, pool))
89        };
90
91        let concurrency_controller =
92            Arc::new(ConcurrencyController::new(config.max_concurrent_ops));
93
94        Ok(Self {
95            backend,
96            current_batch_size: AtomicUsize::new(config.max_batch_size),
97            batch_performance_cache: Arc::new(DashMap::new()),
98            concurrency_controller,
99            config,
100        })
101    }
102
103    /// Get current batch size.
104    pub fn current_batch_size(&self) -> usize {
105        self.current_batch_size.load(Ordering::Relaxed)
106    }
107
108    /// Get embedding dimension.
109    pub fn embedding_dimension(&self) -> usize {
110        self.backend.embedding_dimension()
111    }
112
113    /// Check if the active backend is BERT-based.
114    pub fn is_bert_based(&self) -> bool {
115        self.backend.is_bert_based()
116    }
117
118    /// Encode a single text into an embedding.
119    pub async fn encode_text(&self, text: &str) -> Result<Vec<f32>> {
120        let embeddings = self.encode_batch(vec![text.to_string()]).await?;
121        embeddings
122            .into_iter()
123            .next()
124            .ok_or_else(|| anyhow::anyhow!("No embeddings generated"))
125    }
126
127    /// Encode a batch of texts into embeddings.
128    pub async fn encode_batch(&self, texts: Vec<String>) -> Result<Vec<Vec<f32>>> {
129        if texts.is_empty() {
130            return Ok(Vec::new());
131        }
132
133        // Non-BERT path: dispatch directly — no concurrency gating
134        // required because both Model2Vec and the hash fallback are
135        // ms-cheap. The hash fallback is the only case that does *not*
136        // produce real semantic embeddings, so the warning is scoped to
137        // that variant; Model2Vec is a legitimate static-embedding
138        // backend and silently uses the same direct path.
139        if !self.backend.is_bert_based() {
140            if matches!(self.config.model_type, EmbeddingModelType::StaticSimilarityMRL) {
141                warn!(
142                    "Using StaticHashBackend for model_type {:?} — semantic search will NOT \
143                     work correctly! Pick PotionMultilingual (default) or a BERT variant.",
144                    self.config.model_type
145                );
146            }
147            return self.backend.process_batch(texts).await;
148        }
149
150        info!(
151            "Using BERT embeddings for model_type: {:?}, encoding {} texts",
152            self.config.model_type,
153            texts.len()
154        );
155
156        let total_start_time = std::time::Instant::now();
157        let result = self.encode_batch_with_controls(texts.clone()).await;
158
159        let total_time = total_start_time.elapsed();
160        debug!("Encoded {} texts in {:?}", texts.len(), total_time);
161
162        result
163    }
164
165    /// BERT path with concurrency, timeout, and adaptive batching.
166    async fn encode_batch_with_controls(&self, texts: Vec<String>) -> Result<Vec<Vec<f32>>> {
167        let _permit = match self.concurrency_controller.try_acquire() {
168            Some(permit) => permit,
169            None => self.concurrency_controller.acquire().await?,
170        };
171
172        let batch_size = if self.config.adaptive_batching {
173            self.get_adaptive_batch_size(texts.len()).await
174        } else {
175            self.current_batch_size()
176        };
177
178        let mut all_embeddings = Vec::new();
179
180        for chunk in texts.chunks(batch_size) {
181            let start_time = std::time::Instant::now();
182
183            let batch_result = timeout(
184                Duration::from_secs(self.config.operation_timeout_secs),
185                self.backend.process_batch(chunk.to_vec()),
186            )
187            .await;
188
189            match batch_result {
190                Ok(Ok(batch_embeddings)) => {
191                    all_embeddings.extend(batch_embeddings);
192                    let time_ms = start_time.elapsed().as_millis() as f64;
193                    self.update_batch_performance(chunk.len(), time_ms, 1.0);
194                }
195                Ok(Err(e)) => {
196                    error!("Batch processing failed: {}", e);
197                    self.update_batch_performance(
198                        chunk.len(),
199                        start_time.elapsed().as_millis() as f64,
200                        0.0,
201                    );
202                    return Err(e);
203                }
204                Err(_) => {
205                    error!("Batch processing timed out");
206                    return Err(anyhow::anyhow!(
207                        "Batch processing timed out after {} seconds",
208                        self.config.operation_timeout_secs
209                    ));
210                }
211            }
212        }
213
214        Ok(all_embeddings)
215    }
216
217    /// Get adaptive batch size based on recent performance history.
218    async fn get_adaptive_batch_size(&self, text_count: usize) -> usize {
219        let base_size = self.current_batch_size();
220
221        if text_count <= base_size {
222            return text_count;
223        }
224
225        let recent_performance: Vec<f64> = self
226            .batch_performance_cache
227            .iter()
228            .take(10)
229            .map(|entry| *entry.value())
230            .collect();
231
232        let avg_performance = if recent_performance.is_empty() {
233            0.8 // Default success rate
234        } else {
235            recent_performance.iter().sum::<f64>() / recent_performance.len() as f64
236        };
237
238        if avg_performance > 0.9 {
239            (base_size as f64 * 1.2) as usize
240        } else if avg_performance < 0.7 {
241            (base_size as f64 * 0.8) as usize
242        } else {
243            base_size
244        }
245    }
246
247    /// Update batch performance stats (atomic CAS loop on current_batch_size).
248    fn update_batch_performance(&self, batch_size: usize, time_ms: f64, success_rate: f64) {
249        let metric = success_rate / (time_ms / batch_size as f64);
250        self.batch_performance_cache.insert(batch_size, metric);
251
252        loop {
253            let current = self.current_batch_size.load(Ordering::Acquire);
254
255            let new_size = if success_rate > 0.9 && time_ms < 1000.0 {
256                (current as f64 * 1.1) as usize
257            } else if success_rate < 0.7 || time_ms > 2000.0 {
258                (current as f64 * 0.9) as usize
259            } else {
260                return; // No change needed
261            };
262
263            let clamped = new_size.clamp(8, 256);
264
265            match self.current_batch_size.compare_exchange_weak(
266                current,
267                clamped,
268                Ordering::AcqRel,
269                Ordering::Relaxed,
270            ) {
271                Ok(_) => return,
272                Err(_) => {
273                    std::hint::spin_loop();
274                    continue;
275                }
276            }
277        }
278    }
279
280    /// Get current concurrency load.
281    pub fn current_concurrency_load(&self) -> usize {
282        self.concurrency_controller.current_load()
283    }
284
285    /// Get concurrency stats: `(current_load, max_capacity)`.
286    pub fn get_concurrency_stats(&self) -> (usize, usize) {
287        (
288            self.concurrency_controller.current_load(),
289            self.concurrency_controller.max_capacity(),
290        )
291    }
292}