Skip to main content

lean_ctx/core/embeddings/
mod.rs

1//! Embedding engine for semantic code search.
2//!
3//! Provides dense vector embeddings for code chunks using a local ONNX model.
4//! Supports multiple models via `EmbeddingModel` registry — selected via
5//! `LEAN_CTX_EMBEDDING_MODEL` env var (default: all-MiniLM-L6-v2).
6//!
7//! Feature-gated under `embeddings` — falls back gracefully to BM25-only
8//! search when the feature or model is not available.
9//!
10//! Architecture:
11//!   Tokenizer → ONNX Model (ort) → Mean Pooling → L2 Normalize → `Vec<f32>`
12//!   Tokenizer → static token table (model2vec, pure Rust) → weighted mean → L2
13//!
14//! A static model (`potion-code-16m`) never initialises ONNX Runtime, so it
15//! works where `libonnxruntime` is missing.
16
17pub mod download;
18#[cfg(all(test, feature = "embeddings"))]
19mod eval;
20pub mod model_registry;
21pub mod pooling;
22#[cfg(feature = "embeddings")]
23mod static_model;
24pub mod tokenizer;
25
26use std::path::{Path, PathBuf};
27
28#[cfg(feature = "embeddings")]
29use model_registry::VocabSource;
30use model_registry::{EmbeddingModel, ModelConfig};
31use tokenizer::TokenizedInput;
32#[cfg(feature = "embeddings")]
33use tokenizer::WordPieceTokenizer;
34
35// `embed_batch` parallelises tokenization in every build (rayon is a core, non
36// optional dependency), so this import must not be feature-gated — otherwise the
37// no-embeddings build (e.g. FreeBSD, #586) loses `par_iter`.
38use rayon::prelude::*;
39#[cfg(feature = "embeddings")]
40use std::sync::Mutex;
41
42pub struct EmbeddingEngine {
43    tokenizer: TokenizerKind,
44    dimensions: usize,
45    max_seq_len: usize,
46    model_id: EmbeddingModel,
47    model_config: ModelConfig,
48    /// Exactly one of the two backends is present.
49    #[cfg(feature = "embeddings")]
50    backend: Backend,
51}
52
53#[cfg(feature = "embeddings")]
54enum Backend {
55    Onnx(OnnxSession),
56    Static(static_model::StaticModel),
57}
58
59#[cfg(feature = "embeddings")]
60struct OnnxSession {
61    session: Mutex<ort::session::Session>,
62    graph_inputs: GraphInputs,
63    output_name: String,
64}
65
66/// Abstraction over different tokenizer backends.
67/// Built only by the ORT loader: empty without `embeddings`.
68enum TokenizerKind {
69    #[cfg(feature = "embeddings")]
70    WordPiece(WordPieceTokenizer),
71    #[cfg(feature = "embeddings")]
72    HfTokenizer(tokenizer::HfTokenizerWrapper),
73}
74
75/// The two ONNX graph topologies we can drive (GL #452).
76///
77/// Transformers take `[1, seq]` id/mask tensors and emit per-token hidden
78/// states `[1, seq, dim]` that we mean-pool. model2vec exports are
79/// EmbeddingBag graphs: flat `input_ids: [n_tokens]` plus `offsets: [batch]`,
80/// already pooled to `[batch, dim]` — ~500x faster, no attention pass.
81#[cfg(feature = "embeddings")]
82enum GraphInputs {
83    Transformer {
84        input_ids: String,
85        attention_mask: String,
86        token_type_ids: Option<String>,
87    },
88    EmbeddingBag {
89        input_ids: String,
90        offsets: String,
91    },
92}
93
94/// Classify the graph topology from its input names (pure, unit-testable).
95/// The model2vec signature is exactly two inputs whose second is `offsets`;
96/// everything else is treated as a transformer.
97#[cfg(feature = "embeddings")]
98fn is_embedding_bag_signature(input_names: &[String]) -> bool {
99    input_names.len() == 2 && input_names[1] == "offsets"
100}
101
102impl EmbeddingEngine {
103    /// Load embedding model and vocabulary from a directory.
104    /// Downloads model automatically from HuggingFace if not present.
105    #[cfg(feature = "embeddings")]
106    pub fn load(model_dir: &Path) -> anyhow::Result<Self> {
107        let selected = model_registry::resolve_model();
108        Self::load_model(model_dir, selected)
109    }
110
111    /// Load a specific embedding model from a directory.
112    #[cfg(feature = "embeddings")]
113    pub fn load_model(base_dir: &Path, model_id: EmbeddingModel) -> anyhow::Result<Self> {
114        let config = model_id.config();
115        let model_dir = base_dir.join(model_id.storage_dir_name());
116
117        download::ensure_model(&model_dir, &config)?;
118
119        if config.format == model_registry::ModelFormat::StaticSafetensors {
120            return Self::load_static(&model_dir, model_id, config);
121        }
122
123        let tokenizer = load_tokenizer(&model_dir, &config)?;
124        let model_path = model_dir.join("model.onnx");
125
126        // Deterministic mode (#895): single CPU thread + no GPU EP makes the
127        // model's output bit-identical across machines (reproducible embeddings),
128        // at the cost of throughput. Off by default — the normal path keeps the
129        // multi-threaded, GPU-capable providers. Extractive ranking stays
130        // deterministic regardless via score quantization; this is extra hardening.
131        let deterministic = deterministic_inference();
132        let eps = if deterministic {
133            vec![ort::ep::CPU::default().build()]
134        } else {
135            crate::core::ort_execution_providers::execution_providers()
136        };
137        // Surface a loud, actionable warning when the user expected the GPU but
138        // the CUDA runtime is unusable, so it doesn't silently crawl on CPU.
139        if !deterministic
140            && let Some(msg) = crate::core::ort_execution_providers::gpu_fallback_warning()
141        {
142            tracing::warn!("{msg}");
143        }
144        let num_cpus = if deterministic {
145            1
146        } else {
147            std::thread::available_parallelism().map_or(4, |n| n.get().max(1))
148        };
149        tracing::info!(
150            model = %config.name,
151            model_path = %model_path.display(),
152            deterministic,
153            num_cpus,
154            execution_providers = eps.len(),
155            "Loading ONNX embedding model"
156        );
157        crate::core::ort_environment::ensure_ort_env(&eps)?;
158        tracing::debug!("ONNX Runtime environment ready; creating embedding session builder");
159        let mut session = ort::session::Session::builder()
160            .map_err(|e| anyhow::anyhow!("ORT builder: {e}"))?
161            .with_intra_threads(num_cpus)
162            .map_err(|e| anyhow::anyhow!("ORT intra threads: {e}"))?
163            .with_optimization_level(ort::session::builder::GraphOptimizationLevel::All)
164            .map_err(|e| anyhow::anyhow!("ORT optimization: {e}"))?
165            .commit_from_file(&model_path)
166            .map_err(|e| anyhow::anyhow!("ORT load model: {e}"))?;
167        tracing::debug!("ONNX embedding session loaded; inspecting graph signature");
168
169        let input_names: Vec<String> = session
170            .inputs()
171            .iter()
172            .map(|i| i.name().to_string())
173            .collect();
174
175        if input_names.len() < 2 {
176            anyhow::bail!(
177                "Expected model with at least 2 inputs (input_ids, attention_mask), got {}",
178                input_names.len()
179            );
180        }
181
182        // Topology detection (GL #452): model2vec EmbeddingBag graphs expose
183        // exactly (input_ids, offsets) — structurally incompatible with the
184        // transformer path, so they get their own input adapter.
185        let graph_inputs = if is_embedding_bag_signature(&input_names) {
186            GraphInputs::EmbeddingBag {
187                input_ids: input_names[0].clone(),
188                offsets: input_names[1].clone(),
189            }
190        } else {
191            let token_type_ids = if config.needs_token_type_ids {
192                if input_names.len() < 3 {
193                    anyhow::bail!(
194                        "Model {} requires token_type_ids but only has {} inputs",
195                        config.name,
196                        input_names.len()
197                    );
198                }
199                Some(input_names[2].clone())
200            } else if input_names.len() >= 3 {
201                Some(input_names[2].clone())
202            } else {
203                None
204            };
205            GraphInputs::Transformer {
206                input_ids: input_names[0].clone(),
207                attention_mask: input_names[1].clone(),
208                token_type_ids,
209            }
210        };
211
212        let output_name = session
213            .outputs()
214            .first()
215            .map(|o| o.name().to_string())
216            .ok_or_else(|| anyhow::anyhow!("Model has no named outputs"))?;
217
218        let dimensions = detect_dimensions(
219            &mut session,
220            &tokenizer,
221            &graph_inputs,
222            &output_name,
223            config.max_seq_len,
224        )
225        .unwrap_or(config.dimensions);
226        tracing::debug!(dimensions, "ONNX embedding dimensions resolved");
227
228        tracing::info!(
229            "Embedding engine loaded: model={}, {}d, max_seq_len={}, topology={}",
230            config.name,
231            dimensions,
232            config.max_seq_len,
233            match graph_inputs {
234                GraphInputs::Transformer { .. } => "transformer",
235                GraphInputs::EmbeddingBag { .. } => "embedding-bag (model2vec)",
236            },
237        );
238
239        Ok(Self {
240            tokenizer,
241            dimensions,
242            max_seq_len: config.max_seq_len,
243            model_id,
244            model_config: config,
245            backend: Backend::Onnx(OnnxSession {
246                session: Mutex::new(session),
247                graph_inputs,
248                output_name,
249            }),
250        })
251    }
252
253    /// A model2vec table: the tokenizer and the weights, nothing else — ONNX
254    /// Runtime is never initialised on this path.
255    #[cfg(feature = "embeddings")]
256    fn load_static(
257        model_dir: &Path,
258        model_id: EmbeddingModel,
259        config: ModelConfig,
260    ) -> anyhow::Result<Self> {
261        let tokenizer = tokenizer::HfTokenizerWrapper::from_file_static(
262            &model_dir.join(config.vocab_file.filename()),
263        )?;
264        let model = static_model::StaticModel::load(&model_dir.join(config.local_model_file()))?;
265        if model.vocab_size() != tokenizer.vocab_size() {
266            anyhow::bail!(
267                "{}: tokenizer has {} tokens but the weights cover {}",
268                config.name,
269                tokenizer.vocab_size(),
270                model.vocab_size()
271            );
272        }
273        tracing::info!(
274            "Embedding engine loaded: model={}, {}d, static (model2vec, no ONNX Runtime)",
275            config.name,
276            model.dimensions()
277        );
278        Ok(Self {
279            tokenizer: TokenizerKind::HfTokenizer(tokenizer),
280            dimensions: model.dimensions(),
281            max_seq_len: config.max_seq_len,
282            model_id,
283            model_config: config,
284            backend: Backend::Static(model),
285        })
286    }
287
288    /// The static backend, when this engine runs a model2vec table.
289    #[cfg(feature = "embeddings")]
290    fn static_model(&self) -> Option<&static_model::StaticModel> {
291        match &self.backend {
292            Backend::Static(model) => Some(model),
293            Backend::Onnx(_) => None,
294        }
295    }
296
297    #[cfg(feature = "embeddings")]
298    fn onnx(&self) -> anyhow::Result<&OnnxSession> {
299        match &self.backend {
300            Backend::Onnx(onnx) => Ok(onnx),
301            Backend::Static(_) => anyhow::bail!("static embedding model has no ONNX session"),
302        }
303    }
304
305    #[cfg(not(feature = "embeddings"))]
306    pub fn load(_model_dir: &Path) -> anyhow::Result<Self> {
307        anyhow::bail!("Embeddings feature not enabled. Compile with --features embeddings")
308    }
309
310    /// Load from default model directory (~/.lean-ctx/models/).
311    pub fn load_default() -> anyhow::Result<Self> {
312        Self::load(&Self::model_directory())
313    }
314
315    /// Generate an embedding vector for a single text (document/code).
316    pub fn embed(&self, text: &str) -> anyhow::Result<Vec<f32>> {
317        let prefixed;
318        let input_text = if let Some(prefix) = &self.model_config.document_prefix {
319            prefixed = format!("{prefix}{text}");
320            &prefixed
321        } else {
322            text
323        };
324        #[cfg(feature = "embeddings")]
325        if let Some(model) = self.static_model() {
326            return Ok(model.embed_ids(&self.plain_ids(input_text)));
327        }
328        let input = tokenize(&self.tokenizer, input_text, self.max_seq_len);
329        self.run_inference(&input)
330    }
331
332    /// Token ids for a static model: no sentence markers, no `[UNK]`.
333    #[cfg(feature = "embeddings")]
334    fn plain_ids(&self, text: &str) -> Vec<i32> {
335        match &self.tokenizer {
336            TokenizerKind::WordPiece(wp) => wp.encode_plain(text, self.max_seq_len),
337            TokenizerKind::HfTokenizer(hf) => hf.encode_plain(text, self.max_seq_len),
338        }
339    }
340
341    /// Generate an embedding vector for a query string.
342    /// Applies query-specific prefix if the model requires one.
343    pub fn embed_query(&self, query: &str) -> anyhow::Result<Vec<f32>> {
344        let prefixed;
345        let input_text = if let Some(prefix) = &self.model_config.query_prefix {
346            prefixed = format!("{prefix}{query}");
347            &prefixed
348        } else {
349            query
350        };
351        #[cfg(feature = "embeddings")]
352        if let Some(model) = self.static_model() {
353            return Ok(model.embed_ids(&self.plain_ids(input_text)));
354        }
355        let input = tokenize(&self.tokenizer, input_text, self.max_seq_len);
356        self.run_inference(&input)
357    }
358
359    /// Generate embedding vectors for multiple texts using true batched ONNX
360    /// inference. Sends a single `[batch, max_seq_len]` tensor through the model
361    /// instead of `batch` separate calls — up to 50× faster on CPU for typical
362    /// batch sizes (64–128) by leveraging matrix-matrix instead of matrix-vector
363    /// operations inside the transformer.
364    pub fn embed_batch(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {
365        if texts.is_empty() {
366            return Ok(Vec::new());
367        }
368
369        // A static model is a table lookup per token: embed in parallel, in
370        // slices small enough that cancellation is honoured promptly.
371        #[cfg(feature = "embeddings")]
372        if let Some(model) = self.static_model() {
373            let mut results = Vec::with_capacity(texts.len());
374            for slice in texts.chunks(4096) {
375                if crate::core::interrupt::is_cancelled()
376                    || crate::core::memory_guard::abort_requested()
377                {
378                    anyhow::bail!(
379                        "embedding cancelled after {}/{} chunks",
380                        results.len(),
381                        texts.len()
382                    );
383                }
384                results.extend(
385                    slice
386                        .par_iter()
387                        .map(|text| model.embed_ids(&self.plain_ids(text)))
388                        .collect::<Vec<_>>(),
389                );
390            }
391            return Ok(results);
392        }
393
394        // Process in mini-batches to cap peak memory. Prefixing and tokenization
395        // deliberately happen inside the loop: retaining those buffers for the
396        // entire corpus used to defeat the mini-batch cap under large indexes.
397        // Override the upper bound via LEAN_CTX_EMBEDDING_BATCH_SIZE.
398        let configured_batch_size: usize = std::env::var("LEAN_CTX_EMBEDDING_BATCH_SIZE")
399            .ok()
400            .and_then(|v| v.parse().ok())
401            .filter(|&v| v >= 1)
402            .unwrap_or_else(|| {
403                #[cfg(feature = "embeddings")]
404                if crate::core::ort_execution_providers::gpu_active() {
405                    return 256;
406                }
407                64
408            });
409        // Approximate tokenizer tensors plus transformer activations per input.
410        // Saturating arithmetic keeps hostile custom-model dimensions harmless.
411        let estimated_bytes_per_text = self
412            .max_seq_len
413            .saturating_mul(self.dimensions.max(1))
414            .saturating_mul(std::mem::size_of::<f32>())
415            .saturating_mul(8) as u64;
416        let batch_size = crate::core::memory_guard::adaptive_batch_size(
417            1,
418            configured_batch_size,
419            estimated_bytes_per_text.max(1),
420        );
421
422        let total = texts.len();
423        let total_batches = total.div_ceil(batch_size);
424        let mut results = Vec::with_capacity(total);
425        let start = std::time::Instant::now();
426
427        for (batch_idx, text_chunk) in texts.chunks(batch_size).enumerate() {
428            // Cooperative cancellation checkpoint before any per-batch allocation
429            // and between FFI calls. A hard pressure sample therefore prevents the
430            // next prefix/tokenizer spike and cleanly drops prior batch buffers.
431            if crate::core::interrupt::is_cancelled()
432                || crate::core::memory_guard::abort_requested()
433            {
434                anyhow::bail!(
435                    "embedding cancelled after {done}/{total_batches} batches ({embedded}/{total} chunks)",
436                    done = batch_idx,
437                    embedded = results.len(),
438                );
439            }
440
441            let prefixed: Vec<String> = text_chunk
442                .iter()
443                .map(|text| {
444                    if let Some(prefix) = &self.model_config.document_prefix {
445                        format!("{prefix}{text}")
446                    } else {
447                        (*text).to_owned()
448                    }
449                })
450                .collect();
451            let tokenized: Vec<TokenizedInput> = prefixed
452                .par_iter()
453                .map(|text| tokenize(&self.tokenizer, text, self.max_seq_len))
454                .collect();
455
456            let batch_start = std::time::Instant::now();
457            let batch_out = self.run_inference_batch(&tokenized)?;
458            results.extend(batch_out);
459            tracing::info!(
460                batch = batch_idx + 1,
461                total_batches,
462                embedded = results.len(),
463                total,
464                batch_ms = batch_start.elapsed().as_millis(),
465                elapsed_ms = start.elapsed().as_millis(),
466                "embedding progress"
467            );
468        }
469        Ok(results)
470    }
471
472    pub fn dimensions(&self) -> usize {
473        self.dimensions
474    }
475
476    pub fn model_id(&self) -> &EmbeddingModel {
477        &self.model_id
478    }
479
480    pub fn model_name(&self) -> &str {
481        &self.model_config.name
482    }
483
484    /// Resolve the model directory (respects LEAN_CTX_MODELS_DIR env).
485    pub fn model_directory() -> PathBuf {
486        if let Ok(dir) = std::env::var("LEAN_CTX_MODELS_DIR") {
487            return PathBuf::from(dir);
488        }
489        if let Ok(d) = crate::core::paths::cache_dir() {
490            return d.join("models");
491        }
492        PathBuf::from("models")
493    }
494
495    /// Check if the model files are present and loadable.
496    pub fn is_available() -> bool {
497        let base_dir = Self::model_directory();
498        let selected = model_registry::resolve_model();
499        let config = selected.config();
500        let model_dir = base_dir.join(selected.storage_dir_name());
501        model_dir.join(config.local_model_file()).exists()
502            && model_dir.join(config.vocab_file.filename()).exists()
503    }
504
505    /// Ensure the selected model's files exist on disk, downloading them from
506    /// HuggingFace if absent. Pure network/file IO — this never initializes the
507    /// ONNX Runtime, so a failed bootstrap costs nothing in ORT teardown (the
508    /// caller only loads ORT via [`shared_engine`] once the files are present).
509    /// After `Ok`, [`is_available`](Self::is_available) is guaranteed true; on a
510    /// warm cache it short-circuits without touching the network.
511    ///
512    /// The explicit index-build path uses this to cold-start a fresh machine.
513    /// `is_available()` alone is only a file check, so the build path must call
514    /// this to actually trigger the download instead of bailing (#545).
515    pub fn ensure_downloaded() -> anyhow::Result<()> {
516        let base_dir = Self::model_directory();
517        let selected = model_registry::resolve_model();
518        let config = selected.config();
519        let model_dir = base_dir.join(selected.storage_dir_name());
520        download::ensure_model(&model_dir, &config)?;
521        Ok(())
522    }
523
524    #[cfg(feature = "embeddings")]
525    fn run_inference(&self, input: &TokenizedInput) -> anyhow::Result<Vec<f32>> {
526        let onnx = self.onnx()?;
527        let seq_len = input.input_ids.len();
528
529        let mut embedding = match &onnx.graph_inputs {
530            GraphInputs::Transformer {
531                input_ids,
532                attention_mask,
533                token_type_ids,
534            } => {
535                let ids_vec: Vec<i64> = input.input_ids.iter().map(|&x| x as i64).collect();
536                let mask_vec: Vec<i64> = input.attention_mask.iter().map(|&x| x as i64).collect();
537                let ids_array = ndarray::Array2::from_shape_vec((1, seq_len), ids_vec)?;
538                let mask_array = ndarray::Array2::from_shape_vec((1, seq_len), mask_vec)?;
539                let ids_tensor = ort::value::Tensor::from_array(ids_array)?;
540                let mask_tensor = ort::value::Tensor::from_array(mask_array)?;
541
542                let hidden = if let Some(type_id) = token_type_ids {
543                    let type_vec: Vec<i64> =
544                        input.token_type_ids.iter().map(|&x| x as i64).collect();
545                    let type_array = ndarray::Array2::from_shape_vec((1, seq_len), type_vec)?;
546                    let type_tensor = ort::value::Tensor::from_array(type_array)?;
547                    let mut _guard = onnx
548                        .session
549                        .lock()
550                        .unwrap_or_else(std::sync::PoisonError::into_inner);
551                    let outputs = _guard.run(ort::inputs![
552                        input_ids.as_str() => ids_tensor,
553                        attention_mask.as_str() => mask_tensor,
554                        type_id.as_str() => type_tensor,
555                    ])?;
556                    let (_, data) =
557                        outputs[onnx.output_name.as_str()].try_extract_tensor::<f32>()?;
558                    data.to_vec()
559                } else {
560                    let mut _guard = onnx
561                        .session
562                        .lock()
563                        .unwrap_or_else(std::sync::PoisonError::into_inner);
564                    let outputs = _guard.run(ort::inputs![
565                        input_ids.as_str() => ids_tensor,
566                        attention_mask.as_str() => mask_tensor,
567                    ])?;
568                    let (_, data) =
569                        outputs[onnx.output_name.as_str()].try_extract_tensor::<f32>()?;
570                    data.to_vec()
571                };
572                pooling::mean_pool(&hidden, &input.attention_mask, seq_len, self.dimensions)
573            }
574            GraphInputs::EmbeddingBag { input_ids, offsets } => {
575                if seq_len == 0 {
576                    return Ok(vec![0.0; self.dimensions]);
577                }
578                let ids_vec: Vec<i64> = input.input_ids.iter().map(|&x| x as i64).collect();
579                let ids_array = ndarray::Array1::from_shape_vec(seq_len, ids_vec)?;
580                let offsets_array = ndarray::Array1::from_shape_vec(1, vec![0i64])?;
581                let ids_tensor = ort::value::Tensor::from_array(ids_array)?;
582                let offsets_tensor = ort::value::Tensor::from_array(offsets_array)?;
583                let mut _guard = onnx
584                    .session
585                    .lock()
586                    .unwrap_or_else(std::sync::PoisonError::into_inner);
587                let outputs = _guard.run(ort::inputs![
588                    input_ids.as_str() => ids_tensor,
589                    offsets.as_str() => offsets_tensor,
590                ])?;
591                let (_, data) = outputs[onnx.output_name.as_str()].try_extract_tensor::<f32>()?;
592                data.to_vec()
593            }
594        };
595
596        pooling::normalize_l2(&mut embedding);
597        Ok(embedding)
598    }
599
600    /// Run batched inference over multiple tokenized inputs.
601    ///
602    /// For the Transformer topology: pads all inputs to `max_seq_len` of the
603    /// batch, creates a `[batch, max_seq_len]` tensor, runs ONNX once, then
604    /// mean-pools and L2-normalizes each sequence individually.
605    ///
606    /// For the EmbeddingBag topology: concatenates tokens with per-row offsets,
607    /// runs ONNX once, and L2-normalizes each output row.
608    #[cfg(feature = "embeddings")]
609    fn run_inference_batch(&self, inputs: &[TokenizedInput]) -> anyhow::Result<Vec<Vec<f32>>> {
610        if inputs.is_empty() {
611            return Ok(Vec::new());
612        }
613        let onnx = self.onnx()?;
614
615        match &onnx.graph_inputs {
616            GraphInputs::Transformer {
617                input_ids: input_id,
618                attention_mask: mask_id,
619                token_type_ids,
620            } => {
621                let batch = inputs.len();
622                let max_len = inputs.iter().map(|i| i.input_ids.len()).max().unwrap_or(0);
623
624                let mut ids_data: Vec<i64> = Vec::with_capacity(batch * max_len);
625                let mut mask_data: Vec<i64> = Vec::with_capacity(batch * max_len);
626                let mut type_data: Vec<i64> = Vec::with_capacity(batch * max_len);
627                let mut per_seq_masks: Vec<&[i32]> = Vec::with_capacity(batch);
628
629                for inp in inputs {
630                    let seq_len = inp.input_ids.len();
631                    ids_data.extend(inp.input_ids.iter().map(|&x| x as i64));
632                    ids_data.resize(ids_data.len() + (max_len - seq_len), 0);
633
634                    mask_data.extend(inp.attention_mask.iter().map(|&x| x as i64));
635                    mask_data.resize(mask_data.len() + (max_len - seq_len), 0);
636
637                    type_data.extend(inp.token_type_ids.iter().map(|&x| x as i64));
638                    type_data.resize(type_data.len() + (max_len - seq_len), 0);
639
640                    per_seq_masks.push(inp.attention_mask.as_slice());
641                }
642
643                let ids_array = ndarray::Array2::from_shape_vec((batch, max_len), ids_data)?;
644                let mask_array = ndarray::Array2::from_shape_vec((batch, max_len), mask_data)?;
645                let ids_tensor = ort::value::Tensor::from_array(ids_array)?;
646                let mask_tensor = ort::value::Tensor::from_array(mask_array)?;
647
648                let hidden = if let Some(type_id) = token_type_ids {
649                    let type_array = ndarray::Array2::from_shape_vec((batch, max_len), type_data)?;
650                    let type_tensor = ort::value::Tensor::from_array(type_array)?;
651                    let mut _guard = onnx
652                        .session
653                        .lock()
654                        .unwrap_or_else(std::sync::PoisonError::into_inner);
655                    let outputs = _guard.run(ort::inputs![
656                        input_id.as_str() => ids_tensor,
657                        mask_id.as_str() => mask_tensor,
658                        type_id.as_str() => type_tensor,
659                    ])?;
660                    let (_, data) =
661                        outputs[onnx.output_name.as_str()].try_extract_tensor::<f32>()?;
662                    data.to_vec()
663                } else {
664                    let mut _guard = onnx
665                        .session
666                        .lock()
667                        .unwrap_or_else(std::sync::PoisonError::into_inner);
668                    let outputs = _guard.run(ort::inputs![
669                        input_id.as_str() => ids_tensor,
670                        mask_id.as_str() => mask_tensor,
671                    ])?;
672                    let (_, data) =
673                        outputs[onnx.output_name.as_str()].try_extract_tensor::<f32>()?;
674                    data.to_vec()
675                };
676
677                let mut results =
678                    pooling::mean_pool_batch(&hidden, &per_seq_masks, max_len, self.dimensions);
679                for emb in &mut results {
680                    pooling::normalize_l2(emb);
681                }
682                Ok(results)
683            }
684            GraphInputs::EmbeddingBag { input_ids, offsets } => {
685                let batch = inputs.len();
686                let mut flat_ids: Vec<i64> = Vec::new();
687                let mut adjusted_offsets: Vec<i64> = Vec::with_capacity(batch);
688                let mut last_offset = 0i64;
689
690                for inp in inputs {
691                    adjusted_offsets.push(last_offset);
692                    if !inp.input_ids.is_empty() {
693                        flat_ids.extend(inp.input_ids.iter().map(|&x| x as i64));
694                        last_offset = flat_ids.len() as i64;
695                    }
696                }
697
698                if flat_ids.is_empty() {
699                    return Ok(vec![vec![0.0; self.dimensions]; batch]);
700                }
701
702                let ids_array = ndarray::Array1::from_shape_vec(flat_ids.len(), flat_ids)?;
703                let offsets_array = ndarray::Array1::from_shape_vec(batch, adjusted_offsets)?;
704                let ids_tensor = ort::value::Tensor::from_array(ids_array)?;
705                let offsets_tensor = ort::value::Tensor::from_array(offsets_array)?;
706
707                let mut _guard = onnx
708                    .session
709                    .lock()
710                    .unwrap_or_else(std::sync::PoisonError::into_inner);
711                let outputs = _guard.run(ort::inputs![
712                    input_ids.as_str() => ids_tensor,
713                    offsets.as_str() => offsets_tensor,
714                ])?;
715                let (_, out_data) =
716                    outputs[onnx.output_name.as_str()].try_extract_tensor::<f32>()?;
717                let out = out_data.to_vec();
718
719                let mut results: Vec<Vec<f32>> = out
720                    .chunks_exact(self.dimensions)
721                    .map(<[f32]>::to_vec)
722                    .collect();
723                while results.len() < batch {
724                    results.push(vec![0.0; self.dimensions]);
725                }
726                for emb in &mut results {
727                    pooling::normalize_l2(emb);
728                }
729                Ok(results)
730            }
731        }
732    }
733
734    #[cfg(not(feature = "embeddings"))]
735    fn run_inference(&self, _input: &TokenizedInput) -> anyhow::Result<Vec<f32>> {
736        anyhow::bail!("Embeddings feature not enabled")
737    }
738
739    #[cfg(not(feature = "embeddings"))]
740    fn run_inference_batch(&self, _inputs: &[TokenizedInput]) -> anyhow::Result<Vec<Vec<f32>>> {
741        anyhow::bail!("Embeddings feature not enabled")
742    }
743}
744
745/// Load the appropriate tokenizer for the model config.
746#[cfg(feature = "embeddings")]
747fn load_tokenizer(model_dir: &Path, config: &ModelConfig) -> anyhow::Result<TokenizerKind> {
748    match &config.vocab_file {
749        VocabSource::VocabTxt(filename) => {
750            let path = model_dir.join(filename);
751            let tok = WordPieceTokenizer::from_file(&path)?;
752            Ok(TokenizerKind::WordPiece(tok))
753        }
754        VocabSource::TokenizerJson(filename) => {
755            let path = model_dir.join(filename);
756            let tok = tokenizer::HfTokenizerWrapper::from_file(&path).map_err(|e| {
757                anyhow::anyhow!(
758                    "Failed to load tokenizer.json for {}: {e}. Custom models must ship a \
759                     HuggingFace tokenizer.json with a supported model type (WordPiece/BPE).",
760                    config.name
761                )
762            })?;
763            Ok(TokenizerKind::HfTokenizer(tok))
764        }
765    }
766}
767
768/// Tokenize text using whatever tokenizer backend is loaded.
769fn tokenize(tokenizer: &TokenizerKind, text: &str, max_len: usize) -> TokenizedInput {
770    #[cfg(not(feature = "embeddings"))]
771    let _ = (text, max_len);
772    match *tokenizer {
773        #[cfg(feature = "embeddings")]
774        TokenizerKind::WordPiece(ref wp) => wp.encode(text, max_len),
775        #[cfg(feature = "embeddings")]
776        TokenizerKind::HfTokenizer(ref hf) => hf.encode(text, max_len),
777    }
778}
779
780/// Detect embedding dimensions by running a dummy inference.
781#[cfg(feature = "embeddings")]
782fn detect_dimensions(
783    session: &mut ort::session::Session,
784    tokenizer: &TokenizerKind,
785    graph_inputs: &GraphInputs,
786    output_name: &str,
787    max_seq_len: usize,
788) -> Option<usize> {
789    let dummy = tokenize(tokenizer, "test", max_seq_len.min(8));
790    let seq_len = dummy.input_ids.len();
791    if seq_len == 0 {
792        return None;
793    }
794
795    let outputs = match graph_inputs {
796        GraphInputs::Transformer {
797            input_ids,
798            attention_mask,
799            token_type_ids,
800        } => {
801            let ids_vec: Vec<i64> = dummy.input_ids.iter().map(|&x| x as i64).collect();
802            let mask_vec: Vec<i64> = dummy.attention_mask.iter().map(|&x| x as i64).collect();
803            let ids_array = ndarray::Array2::from_shape_vec((1, seq_len), ids_vec).ok()?;
804            let mask_array = ndarray::Array2::from_shape_vec((1, seq_len), mask_vec).ok()?;
805            let ids_tensor = ort::value::Tensor::from_array(ids_array).ok()?;
806            let mask_tensor = ort::value::Tensor::from_array(mask_array).ok()?;
807
808            if let Some(type_id) = token_type_ids {
809                let type_vec: Vec<i64> = dummy.token_type_ids.iter().map(|&x| x as i64).collect();
810                let type_array = ndarray::Array2::from_shape_vec((1, seq_len), type_vec).ok()?;
811                let type_tensor = ort::value::Tensor::from_array(type_array).ok()?;
812                session
813                    .run(ort::inputs![
814                        input_ids.as_str() => ids_tensor,
815                        attention_mask.as_str() => mask_tensor,
816                        type_id.as_str() => type_tensor,
817                    ])
818                    .ok()?
819            } else {
820                session
821                    .run(ort::inputs![
822                        input_ids.as_str() => ids_tensor,
823                        attention_mask.as_str() => mask_tensor,
824                    ])
825                    .ok()?
826            }
827        }
828        GraphInputs::EmbeddingBag { input_ids, offsets } => {
829            let ids_vec: Vec<i64> = dummy.input_ids.iter().map(|&x| x as i64).collect();
830            let ids_array = ndarray::Array1::from_shape_vec(seq_len, ids_vec).ok()?;
831            let offsets_array = ndarray::Array1::from_shape_vec(1, vec![0i64]).ok()?;
832            let ids_tensor = ort::value::Tensor::from_array(ids_array).ok()?;
833            let offsets_tensor = ort::value::Tensor::from_array(offsets_array).ok()?;
834            session
835                .run(ort::inputs![
836                    input_ids.as_str() => ids_tensor,
837                    offsets.as_str() => offsets_tensor,
838                ])
839                .ok()?
840        }
841    };
842
843    let (shape, _) = outputs[output_name].try_extract_tensor::<f32>().ok()?;
844
845    match graph_inputs {
846        // Shape is [batch=1, seq_len, dim].
847        GraphInputs::Transformer { .. } => shape.last().copied().map(|s| s as usize),
848        // Already pooled: [batch=1, dim] — the last axis IS the dim, but be
849        // explicit about the rank so a surprising graph fails loudly into
850        // the config fallback instead of mis-probing.
851        GraphInputs::EmbeddingBag { .. } => {
852            if shape.len() == 2 {
853                shape.last().copied().map(|s| s as usize)
854            } else {
855                None
856            }
857        }
858    }
859}
860
861/// Compute cosine similarity between two L2-normalized vectors.
862/// Both vectors must be pre-normalized for correct results.
863///
864/// Uses the chunked, autovectorizable dot product from `crate::core::embedding_quant`
865/// (turbovec-derived) so every semantic-search hot path gets SIMD throughput.
866pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
867    debug_assert_eq!(a.len(), b.len(), "vectors must have equal dimensions");
868    crate::core::embedding_quant::dot_f32(a, b)
869}
870
871/// Compute cosine similarity without requiring pre-normalization.
872pub fn cosine_similarity_raw(a: &[f32], b: &[f32]) -> f32 {
873    debug_assert_eq!(a.len(), b.len());
874    use crate::core::embedding_quant::dot_f32;
875    let dot = dot_f32(a, b);
876    let norm_a = dot_f32(a, a).sqrt();
877    let norm_b = dot_f32(b, b).sqrt();
878    if norm_a == 0.0 || norm_b == 0.0 {
879        return 0.0;
880    }
881    dot / (norm_a * norm_b)
882}
883
884#[cfg(feature = "embeddings")]
885static SHARED_ENGINE: std::sync::OnceLock<anyhow::Result<EmbeddingEngine>> =
886    std::sync::OnceLock::new();
887
888/// Global singleton embedding engine. Loaded once, shared across all consumers.
889/// Returns None if the embeddings feature is disabled or the model fails to load.
890/// NOTE: This function BLOCKS on first call while loading the ONNX model.
891/// For non-blocking access, use `try_shared_engine()` instead.
892#[cfg(feature = "embeddings")]
893pub fn shared_engine() -> Option<&'static EmbeddingEngine> {
894    shared_engine_result().ok()
895}
896
897/// Global singleton embedding engine with the load error preserved for callers
898/// that can surface diagnostics to users.
899#[cfg(feature = "embeddings")]
900pub fn shared_engine_result() -> anyhow::Result<&'static EmbeddingEngine> {
901    SHARED_ENGINE
902        .get_or_init(EmbeddingEngine::load_default)
903        .as_ref()
904        .map_err(|e| anyhow::anyhow!("{e}"))
905}
906
907/// Non-blocking variant: returns the engine ONLY if already loaded.
908/// Never triggers model loading or download. Safe to call on hot paths.
909#[cfg(feature = "embeddings")]
910pub fn try_shared_engine() -> Option<&'static EmbeddingEngine> {
911    SHARED_ENGINE.get()?.as_ref().ok()
912}
913
914/// Resolve the deterministic-inference policy (#895): the
915/// `LEAN_CTX_EMBEDDING_DETERMINISTIC` env var wins in either direction,
916/// otherwise `[embedding].deterministic` from config, otherwise `false`.
917#[cfg(feature = "embeddings")]
918fn deterministic_inference() -> bool {
919    if let Ok(v) = std::env::var("LEAN_CTX_EMBEDDING_DETERMINISTIC") {
920        return matches!(
921            v.trim().to_lowercase().as_str(),
922            "1" | "true" | "yes" | "on"
923        );
924    }
925    crate::core::config::Config::load()
926        .embedding
927        .deterministic
928        .unwrap_or(false)
929}
930
931/// Whether this process may load the ONNX model on a **detached background
932/// thread** (#519).
933///
934/// ONNX Runtime registers its op schemas in global C++ static state while a
935/// model is loading. If a detached loader thread is still mid-load when the
936/// process returns from `main`, it races `libonnxruntime`'s static-destructor
937/// teardown — a use-after-free SIGSEGV inside `onnx::OpSchema` on an ORT worker
938/// thread. The shipped `lean-ctx` daemon/MCP server is long-lived, so its
939/// warmup always finishes well before exit; short-lived processes (`cargo test`/
940/// bench/doctest binaries, build-time generators) can exit mid-load, so we
941/// refuse the background spawn for them. Their semantic features simply stay
942/// cold — blocking, on-thread loads still work and always complete before exit,
943/// which is race-free.
944///
945/// Note: blocking [`shared_engine`] loads are intentionally NOT gated — they
946/// finish on the caller's thread before the process exits, so no worker is ever
947/// active during teardown.
948#[cfg(feature = "embeddings")]
949pub fn background_load_allowed() -> bool {
950    // Unit tests compile with cfg(test): a cheap, unambiguous short-circuit.
951    // Integration/bench/doctest binaries link the lib in its normal config
952    // (cfg(test) is false), so they are caught by the executable-path probe.
953    if cfg!(test) {
954        return false;
955    }
956    !current_exe_is_test_artifact()
957}
958
959/// `true` when the running executable is a Cargo test/bench/doctest artifact.
960#[cfg(feature = "embeddings")]
961fn current_exe_is_test_artifact() -> bool {
962    std::env::current_exe()
963        .ok()
964        .as_deref()
965        .is_some_and(exe_path_is_test_artifact)
966}
967
968/// Pure predicate (unit-testable): Cargo places test, bench and doctest binaries
969/// directly inside `…/target/<profile>/deps/`. The shipped binary lives in a
970/// package `bin` directory (`/usr/bin`, `~/.local/bin`, `…/Homebrew/bin`, …) and
971/// is never a direct child of a `deps/` directory, so the parent-dir name is an
972/// install-location-independent signal (survives renames of the binary). (#519)
973#[cfg(feature = "embeddings")]
974fn exe_path_is_test_artifact(path: &Path) -> bool {
975    path.parent()
976        .and_then(Path::file_name)
977        .and_then(|name| name.to_str())
978        .is_some_and(|name| name == "deps")
979}
980
981#[cfg(test)]
982mod tests {
983    use super::*;
984
985    #[test]
986    fn cosine_similarity_identical() {
987        let a = vec![1.0, 0.0, 0.0];
988        let b = vec![1.0, 0.0, 0.0];
989        assert!((cosine_similarity(&a, &b) - 1.0).abs() < 1e-6);
990    }
991
992    #[test]
993    fn cosine_similarity_orthogonal() {
994        let a = vec![1.0, 0.0, 0.0];
995        let b = vec![0.0, 1.0, 0.0];
996        assert!(cosine_similarity(&a, &b).abs() < 1e-6);
997    }
998
999    #[test]
1000    fn cosine_similarity_opposite() {
1001        let a = vec![1.0, 0.0, 0.0];
1002        let b = vec![-1.0, 0.0, 0.0];
1003        assert!((cosine_similarity(&a, &b) + 1.0).abs() < 1e-6);
1004    }
1005
1006    #[test]
1007    fn cosine_similarity_raw_unnormalized() {
1008        let a = vec![3.0, 4.0];
1009        let b = vec![3.0, 4.0];
1010        assert!((cosine_similarity_raw(&a, &b) - 1.0).abs() < 1e-6);
1011    }
1012
1013    #[test]
1014    fn cosine_similarity_raw_zero_vector() {
1015        let a = vec![0.0, 0.0];
1016        let b = vec![1.0, 2.0];
1017        assert_eq!(cosine_similarity_raw(&a, &b), 0.0);
1018    }
1019
1020    #[test]
1021    fn model_directory_env_override_and_availability() {
1022        // Serialize env mutation: LEAN_CTX_MODELS_DIR is process-global and
1023        // shared with `ensure_downloaded_is_offline_noop_when_model_present`.
1024        let _lock = crate::core::data_dir::test_env_lock();
1025        let unique = "/tmp/lean_ctx_test_embed_42xyz";
1026        crate::test_env::set_var("LEAN_CTX_MODELS_DIR", unique);
1027        let dir = EmbeddingEngine::model_directory();
1028        assert_eq!(dir.to_string_lossy(), unique);
1029        assert!(!EmbeddingEngine::is_available());
1030        crate::test_env::remove_var("LEAN_CTX_MODELS_DIR");
1031    }
1032
1033    /// #545: with a complete model cache, `ensure_downloaded` is a no-op that
1034    /// never touches the network and agrees with `is_available` on the model
1035    /// directory. The build path relies on this so a cold availability check can
1036    /// route through the (real) download without redundantly re-fetching a model
1037    /// that is already present. Both gates use plain existence checks, so tiny
1038    /// placeholder files are enough to exercise the short-circuit offline.
1039    #[test]
1040    fn ensure_downloaded_is_offline_noop_when_model_present() {
1041        // Serialize env mutation (LEAN_CTX_MODELS_DIR is process-global) so a
1042        // sibling env test can't clobber the dir between set_var and the checks.
1043        let _lock = crate::core::data_dir::test_env_lock();
1044        let tmp = std::env::temp_dir().join(format!("lc-embed-545-{}", std::process::id()));
1045        crate::test_env::set_var("LEAN_CTX_MODELS_DIR", tmp.to_str().unwrap());
1046
1047        let selected = model_registry::resolve_model();
1048        let config = selected.config();
1049        let model_dir = tmp.join(selected.storage_dir_name());
1050        std::fs::create_dir_all(&model_dir).unwrap();
1051        // The default depends on whether ONNX Runtime is installed here, so
1052        // write whichever weights file the resolved model uses.
1053        std::fs::write(model_dir.join(config.local_model_file()), b"weights").unwrap();
1054        std::fs::write(model_dir.join(config.vocab_file.filename()), b"vocab").unwrap();
1055
1056        assert!(EmbeddingEngine::is_available());
1057        assert!(EmbeddingEngine::ensure_downloaded().is_ok());
1058
1059        crate::test_env::remove_var("LEAN_CTX_MODELS_DIR");
1060        std::fs::remove_dir_all(&tmp).ok();
1061    }
1062
1063    /// #519: Cargo test/bench/doctest binaries live under `…/deps/`; the shipped
1064    /// binary lives in a `bin` directory. The parent-dir probe must distinguish
1065    /// them so background ORT loads are refused only in short-lived processes.
1066    #[test]
1067    #[cfg(feature = "embeddings")]
1068    fn exe_path_test_artifact_detection() {
1069        // Cargo test/bench/doctest artifacts: parent dir is `deps`.
1070        assert!(exe_path_is_test_artifact(Path::new(
1071            "/repo/rust/target/debug/deps/conformance_suite-0a1b2c3d4e5f6789"
1072        )));
1073        assert!(exe_path_is_test_artifact(Path::new(
1074            "/repo/rust/target/release/deps/lean_ctx-deadbeefcafef00d"
1075        )));
1076        // Shipped/installed binary: never a direct child of `deps`.
1077        assert!(!exe_path_is_test_artifact(Path::new(
1078            "/usr/local/bin/lean-ctx"
1079        )));
1080        assert!(!exe_path_is_test_artifact(Path::new(
1081            "/Users/x/.local/bin/lean-ctx"
1082        )));
1083        // A renamed shipped binary is still allowed (rename-independent signal).
1084        assert!(!exe_path_is_test_artifact(Path::new("/opt/tools/ctx")));
1085        // The plain target dir build (e.g. `target/debug/lean-ctx`) is not under
1086        // `deps/` — treated as a product binary, not a test artifact.
1087        assert!(!exe_path_is_test_artifact(Path::new(
1088            "/repo/rust/target/debug/lean-ctx"
1089        )));
1090    }
1091
1092    /// In the unit-test binary `background_load_allowed` must be false via the
1093    /// `cfg!(test)` short-circuit — no detached ORT load may ever be spawned
1094    /// from a test process (the #519 teardown race).
1095    #[test]
1096    #[cfg(feature = "embeddings")]
1097    fn background_load_disallowed_in_tests() {
1098        assert!(!background_load_allowed());
1099    }
1100
1101    /// GL #452: the EmbeddingBag detection is purely name-based — exactly two
1102    /// inputs with the second named `offsets`. Everything else (classic 2-/
1103    /// 3-input transformers, unnamed graphs) must stay on the transformer path.
1104    #[test]
1105    #[cfg(feature = "embeddings")]
1106    fn embedding_bag_signature_detection() {
1107        // model2vec / potion export.
1108        assert!(is_embedding_bag_signature(&[
1109            "input_ids".to_string(),
1110            "offsets".to_string()
1111        ]));
1112        // Transformers: mask second, optional token types third.
1113        assert!(!is_embedding_bag_signature(&[
1114            "input_ids".to_string(),
1115            "attention_mask".to_string()
1116        ]));
1117        assert!(!is_embedding_bag_signature(&[
1118            "input_ids".to_string(),
1119            "attention_mask".to_string(),
1120            "token_type_ids".to_string()
1121        ]));
1122        // Wrong arity never flips the topology.
1123        assert!(!is_embedding_bag_signature(&["input_ids".to_string()]));
1124        assert!(!is_embedding_bag_signature(&[
1125            "input_ids".to_string(),
1126            "offsets".to_string(),
1127            "extra".to_string()
1128        ]));
1129    }
1130
1131    // NOTE: `try_shared_engine_returns_none_when_not_initialized` lives in
1132    // `tests/embeddings_shared_engine.rs` (own process). SHARED_ENGINE is a
1133    // process-wide OnceLock: in the unit-test suite any sibling test that
1134    // legitimately loads the engine (or #551 background activation) would
1135    // initialize it first and make the assertion order-dependent/flaky.
1136
1137    /// Live proof for GL #397: loads a real HuggingFace repo through the
1138    /// `hf:org/repo@rev` scheme (download → SHA-256 lockfile → tokenizer.json →
1139    /// ONNX inference → dimension probe). Ignored by default (network + ~91MB);
1140    /// run explicitly:
1141    /// `cargo test --lib --features embeddings -- --ignored custom_hf_model_end_to_end`
1142    #[test]
1143    #[ignore = "downloads a real model from HuggingFace (~91MB)"]
1144    #[cfg(feature = "embeddings")]
1145    fn custom_hf_model_end_to_end() {
1146        let model = model_registry::EmbeddingModel::from_str_name(
1147            "hf:sentence-transformers/all-MiniLM-L6-v2@main",
1148        )
1149        .expect("valid hf: spec");
1150
1151        let base = std::env::temp_dir().join("lean_ctx_test_custom_hf_e2e");
1152        let engine = EmbeddingEngine::load_model(&base, model.clone()).expect("load custom model");
1153
1154        assert_eq!(engine.dimensions(), 384, "probed dims from ONNX graph");
1155        assert_eq!(
1156            engine.model_name(),
1157            "hf:sentence-transformers/all-MiniLM-L6-v2@main"
1158        );
1159
1160        let v = engine.embed("fn main() { println!(\"hello\"); }").unwrap();
1161        assert_eq!(v.len(), 384);
1162        let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
1163        assert!((norm - 1.0).abs() < 1e-3, "L2-normalized, got {norm}");
1164
1165        // Lockfile must exist and pin both artifacts.
1166        let lock_path = base.join(model.storage_dir_name()).join("model.lock.json");
1167        let lock: std::collections::BTreeMap<String, String> =
1168            serde_json::from_str(&std::fs::read_to_string(&lock_path).unwrap()).unwrap();
1169        assert!(lock.contains_key("model.onnx"));
1170        assert!(lock.contains_key("tokenizer.json"));
1171
1172        // Semantic sanity: similar code closer than unrelated text.
1173        let a = engine.embed("read a file from disk").unwrap();
1174        let b = engine.embed("load file contents from filesystem").unwrap();
1175        let c = engine.embed("the weather in Zurich is sunny").unwrap();
1176        assert!(
1177            cosine_similarity(&a, &b) > cosine_similarity(&a, &c),
1178            "related texts must be closer"
1179        );
1180    }
1181
1182    /// Live proof for GL #452: a model2vec EmbeddingBag graph end-to-end
1183    /// through the same `hf:` scheme (potion-base-8M, ~30MB). Ignored by
1184    /// default (network); run explicitly:
1185    /// `cargo test --lib --features embeddings -- --ignored model2vec_potion_end_to_end`
1186    #[test]
1187    #[ignore = "downloads a real model from HuggingFace (~30MB)"]
1188    #[cfg(feature = "embeddings")]
1189    fn model2vec_potion_end_to_end() {
1190        let model =
1191            model_registry::EmbeddingModel::from_str_name("hf:minishlab/potion-base-8M@main")
1192                .expect("valid hf: spec");
1193
1194        let base = std::env::temp_dir().join("lean_ctx_test_model2vec_e2e");
1195        let engine =
1196            EmbeddingEngine::load_model(&base, model.clone()).expect("load model2vec model");
1197
1198        // potion-base-8M is 256d; the probe must read it off the rank-2
1199        // output, not assume a [1, seq, dim] transformer shape.
1200        assert_eq!(engine.dimensions(), 256, "probed dims from EmbeddingBag");
1201
1202        let code_vec = engine.embed("fn main() { println!(\"hello\"); }").unwrap();
1203        assert_eq!(code_vec.len(), 256);
1204        let norm: f32 = code_vec.iter().map(|x| x * x).sum::<f32>().sqrt();
1205        assert!((norm - 1.0).abs() < 1e-3, "L2-normalized, got {norm}");
1206
1207        // Distinct inputs must not collapse to one vector.
1208        let sql_vec = engine.embed("SELECT * FROM users WHERE id = 1").unwrap();
1209        assert!(cosine_similarity(&code_vec, &sql_vec) < 0.999);
1210
1211        // Semantic sanity survives the static-embedding quality trade-off.
1212        let read_vec = engine.embed("read a file from disk").unwrap();
1213        let load_vec = engine.embed("load file contents from filesystem").unwrap();
1214        let weather_vec = engine.embed("the weather in Zurich is sunny").unwrap();
1215        assert!(
1216            cosine_similarity(&read_vec, &load_vec) > cosine_similarity(&read_vec, &weather_vec),
1217            "related texts must be closer"
1218        );
1219
1220        // Empty input: zero vector, no inference panic.
1221        let empty_vec = engine.embed("").unwrap();
1222        assert_eq!(empty_vec.len(), 256);
1223    }
1224}