Skip to main content

lean_ctx/core/embeddings/
model_registry.rs

1//! Embedding model registry — model configs, selection, and metadata.
2//!
3//! Supports multiple ONNX embedding models with different dimensions,
4//! tokenizers, and download sources. Models are selected via the
5//! `LEAN_CTX_EMBEDDING_MODEL` env var or the `[embedding].model` key in `config.toml`
6//! (env var wins) — see [`resolve_model`].
7//!
8//! Besides the built-ins, any compatible HuggingFace repo can be loaded with
9//! `model = "hf:org/repo[@revision]"` (GL #397, upstream #328): the repo must
10//! ship an ONNX export (`onnx/model.onnx`) and a `tokenizer.json`. This custom
11//! path probes the ONNX graph for its real input/output signature, so it suits
12//! code-specialized models (e.g. `hf:jinaai/jina-embeddings-v2-base-code`) that
13//! need no hand-maintained config. See `docs/guides/custom-embeddings.md`.
14
15use std::fmt;
16
17/// Supported embedding models.
18#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
19#[serde(rename_all = "kebab-case")]
20pub enum EmbeddingModel {
21    /// all-MiniLM-L6-v2 — generic sentence embeddings (384d, ~91MB).
22    /// Default model for backward compatibility.
23    AllMiniLmL6V2,
24    /// nomic-embed-text-v1.5 — top MTEB general-purpose (768d, ~547MB).
25    /// Matryoshka representation learning, supports dimension truncation.
26    NomicEmbedV1_5,
27    /// Any HuggingFace repo with an ONNX export + tokenizer.json
28    /// (`hf:org/repo[@revision]`, GL #397).
29    Custom(CustomModelSpec),
30}
31
32/// A user-supplied HuggingFace embedding model (`hf:org/repo[@revision]`).
33#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
34pub struct CustomModelSpec {
35    /// HuggingFace repo id, e.g. `jinaai/jina-embeddings-v2-base-code`.
36    pub repo: String,
37    /// Optional revision pin (tag/branch/commit). `None` resolves `main` —
38    /// supply-chain-wise a pin is strongly recommended and the resolver warns
39    /// without one.
40    pub revision: Option<String>,
41    /// Embedding dimensions (`[embedding].dimensions`). When unset, the real
42    /// value is detected from a probe inference at load time; this is only the
43    /// declared fallback.
44    pub dimensions: Option<usize>,
45}
46
47impl CustomModelSpec {
48    /// Parse `org/repo[@revision]` (the part after the `hf:` scheme).
49    /// Returns `None` when the repo id is not plausibly a HuggingFace repo.
50    fn parse(s: &str) -> Option<Self> {
51        let (repo, revision) = match s.split_once('@') {
52            Some((r, rev)) => (
53                r.trim(),
54                Some(rev.trim().to_string()).filter(|v| !v.is_empty()),
55            ),
56            None => (s.trim(), None),
57        };
58        // A HF repo id is exactly `owner/name` with no whitespace.
59        let mut parts = repo.split('/');
60        let (owner, name) = (parts.next()?, parts.next()?);
61        if parts.next().is_some()
62            || owner.is_empty()
63            || name.is_empty()
64            || repo.chars().any(char::is_whitespace)
65        {
66            return None;
67        }
68        Some(Self {
69            repo: repo.to_string(),
70            revision,
71            dimensions: None,
72        })
73    }
74
75    /// Filesystem-safe storage slug, unique per repo+revision.
76    fn storage_slug(&self) -> String {
77        let mut slug = String::from("hf-");
78        for c in self.repo.chars() {
79            slug.push(match c {
80                'a'..='z' | '0'..='9' | '-' => c,
81                'A'..='Z' => c.to_ascii_lowercase(),
82                _ => '-',
83            });
84        }
85        if let Some(rev) = &self.revision {
86            slug.push('-');
87            for c in rev.chars().take(16) {
88                slug.push(match c {
89                    'a'..='z' | '0'..='9' | '-' => c,
90                    'A'..='Z' => c.to_ascii_lowercase(),
91                    _ => '-',
92                });
93            }
94        }
95        slug
96    }
97}
98
99impl EmbeddingModel {
100    pub const DEFAULT: Self = Self::AllMiniLmL6V2;
101
102    pub fn config(&self) -> ModelConfig {
103        match self {
104            Self::AllMiniLmL6V2 => ModelConfig {
105                model: self.clone(),
106                name: "all-MiniLM-L6-v2".into(),
107                hf_repo: "sentence-transformers/all-MiniLM-L6-v2".into(),
108                revision: None,
109                onnx_path: "onnx/model.onnx".into(),
110                vocab_file: VocabSource::VocabTxt("vocab.txt".into()),
111                dimensions: 384,
112                max_seq_len: 256,
113                model_min_bytes: 1_000_000,
114                vocab_min_bytes: 100_000,
115                query_prefix: None,
116                document_prefix: None,
117                needs_token_type_ids: true,
118            },
119            Self::NomicEmbedV1_5 => ModelConfig {
120                model: self.clone(),
121                name: "nomic-embed-text-v1.5".into(),
122                hf_repo: "nomic-ai/nomic-embed-text-v1.5".into(),
123                revision: None,
124                onnx_path: "onnx/model.onnx".into(),
125                vocab_file: VocabSource::VocabTxt("vocab.txt".into()),
126                dimensions: 768,
127                max_seq_len: 512,
128                model_min_bytes: 100_000_000,
129                vocab_min_bytes: 100_000,
130                query_prefix: Some("search_query: ".into()),
131                document_prefix: Some("search_document: ".into()),
132                needs_token_type_ids: false,
133            },
134            Self::Custom(spec) => ModelConfig {
135                model: self.clone(),
136                // The canonical name doubles as the index `model_id`, so a
137                // repo or revision change triggers the one-shot re-index.
138                name: match &spec.revision {
139                    Some(rev) => format!("hf:{}@{rev}", spec.repo),
140                    None => format!("hf:{}", spec.repo),
141                },
142                hf_repo: spec.repo.clone(),
143                revision: spec.revision.clone(),
144                onnx_path: "onnx/model.onnx".into(),
145                // Custom repos must ship a HuggingFace tokenizer.json — the
146                // universal format (WordPiece/BPE/Unigram all serialize to it).
147                vocab_file: VocabSource::TokenizerJson("tokenizer.json".into()),
148                // Declared fallback; the probe inference at load time detects
149                // the real width (`detect_dimensions`) and wins.
150                dimensions: spec.dimensions.unwrap_or(768),
151                max_seq_len: 512,
152                model_min_bytes: 1_000_000,
153                vocab_min_bytes: 1_000,
154                query_prefix: None,
155                document_prefix: None,
156                // Probed from the ONNX graph at load time; BERT-style models
157                // with a third input still get token_type_ids wired up.
158                needs_token_type_ids: false,
159            },
160        }
161    }
162
163    /// Parse model name from string (env var / config file).
164    ///
165    /// Accepts the built-in aliases plus the `hf:org/repo[@revision]` scheme
166    /// for custom HuggingFace models (GL #397).
167    pub fn from_str_name(s: &str) -> Option<Self> {
168        let trimmed = s.trim();
169        if let Some(rest) = trimmed.strip_prefix("hf:") {
170            return CustomModelSpec::parse(rest).map(Self::Custom);
171        }
172        match trimmed.to_lowercase().replace('_', "-").as_str() {
173            "all-minilm-l6-v2" | "minilm" | "default" => Some(Self::AllMiniLmL6V2),
174            "nomic-embed-v1.5" | "nomic-embed-text-v1.5" | "nomic" | "nomic-embed" => {
175                Some(Self::NomicEmbedV1_5)
176            }
177            _ => None,
178        }
179    }
180
181    /// All built-in model variants (custom models are user-defined).
182    pub const ALL: &'static [Self] = &[Self::AllMiniLmL6V2, Self::NomicEmbedV1_5];
183
184    /// Unique subdirectory name for model storage isolation.
185    pub fn storage_dir_name(&self) -> String {
186        match self {
187            Self::AllMiniLmL6V2 => "all-minilm-l6-v2".to_string(),
188            Self::NomicEmbedV1_5 => "nomic-embed-v1.5".to_string(),
189            Self::Custom(spec) => spec.storage_slug(),
190        }
191    }
192}
193
194impl fmt::Display for EmbeddingModel {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        f.write_str(&self.config().name)
197    }
198}
199
200/// Vocabulary/tokenizer source for a model.
201#[derive(Debug, Clone)]
202pub enum VocabSource {
203    /// Standard BERT vocab.txt (one token per line, WordPiece).
204    VocabTxt(String),
205    /// HuggingFace tokenizer.json (BPE/Unigram/WordPiece via JSON config).
206    TokenizerJson(String),
207}
208
209impl VocabSource {
210    pub fn filename(&self) -> &str {
211        match self {
212            Self::VocabTxt(f) | Self::TokenizerJson(f) => f,
213        }
214    }
215
216    pub fn is_wordpiece(&self) -> bool {
217        matches!(self, Self::VocabTxt(_))
218    }
219}
220
221/// Complete configuration for a single embedding model.
222#[derive(Debug, Clone)]
223pub struct ModelConfig {
224    pub model: EmbeddingModel,
225    pub name: String,
226    pub hf_repo: String,
227    /// Optional revision pin for custom models (`None` = `main`).
228    pub revision: Option<String>,
229    pub onnx_path: String,
230    pub vocab_file: VocabSource,
231    pub dimensions: usize,
232    pub max_seq_len: usize,
233    pub model_min_bytes: u64,
234    pub vocab_min_bytes: u64,
235    /// Optional prefix prepended to queries before embedding.
236    pub query_prefix: Option<String>,
237    /// Optional prefix prepended to documents/code before embedding.
238    pub document_prefix: Option<String>,
239    /// Whether the model expects token_type_ids input (BERT-style).
240    /// Some models (e.g. nomic-embed) only use input_ids + attention_mask.
241    pub needs_token_type_ids: bool,
242}
243
244impl ModelConfig {
245    fn resolve_base(&self) -> String {
246        format!(
247            "https://huggingface.co/{}/resolve/{}",
248            self.hf_repo,
249            self.revision.as_deref().unwrap_or("main")
250        )
251    }
252
253    /// Full HuggingFace download URL for the ONNX model file.
254    pub fn model_url(&self) -> String {
255        format!("{}/{}", self.resolve_base(), self.onnx_path)
256    }
257
258    /// Full HuggingFace download URL for the vocabulary/tokenizer file.
259    pub fn vocab_url(&self) -> String {
260        format!("{}/{}", self.resolve_base(), self.vocab_file.filename())
261    }
262}
263
264/// Resolve which embedding model to use.
265///
266/// Priority: `LEAN_CTX_EMBEDDING_MODEL` env var > `[embedding].model` in `config.toml` >
267/// the default model. An unrecognized name is skipped (with a warning) so a typo in one
268/// source never silently swaps the model — which would otherwise force a full re-index.
269pub fn resolve_model() -> EmbeddingModel {
270    resolve_model_with_source().0
271}
272
273/// Which setting selected the embedding model (#2049: `embeddings status`
274/// says so, because the env var and `config.toml` are easy to confuse).
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub enum ModelSource {
277    /// `LEAN_CTX_EMBEDDING_MODEL`, with its raw value.
278    Env(String),
279    /// `[embedding].model` in `config.toml`, with its raw value.
280    Config(String),
281    /// Nothing (valid) set.
282    Default,
283}
284
285/// [`resolve_model`] plus the setting it came from.
286pub fn resolve_model_with_source() -> (EmbeddingModel, ModelSource) {
287    let env_val = std::env::var("LEAN_CTX_EMBEDDING_MODEL").ok();
288    let embedding_cfg = crate::core::config::Config::load().embedding;
289    resolve_model_with_source_from(
290        env_val.as_deref(),
291        embedding_cfg.model.as_deref(),
292        embedding_cfg.dimensions,
293    )
294}
295
296/// Pure model resolution used by [`resolve_model`]; kept separate so the env-var/config
297/// precedence is unit-testable without touching the process environment or the on-disk
298/// `config.toml`.
299#[cfg(test)]
300fn resolve_model_from(
301    env_val: Option<&str>,
302    config_val: Option<&str>,
303    config_dims: Option<usize>,
304) -> EmbeddingModel {
305    resolve_model_with_source_from(env_val, config_val, config_dims).0
306}
307
308fn resolve_model_with_source_from(
309    env_val: Option<&str>,
310    config_val: Option<&str>,
311    config_dims: Option<usize>,
312) -> (EmbeddingModel, ModelSource) {
313    for (source, raw) in [
314        ("LEAN_CTX_EMBEDDING_MODEL", env_val),
315        ("[embedding].model", config_val),
316    ] {
317        let Some(name) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
318            continue;
319        };
320        let origin = if source == "LEAN_CTX_EMBEDDING_MODEL" {
321            ModelSource::Env(name.to_string())
322        } else {
323            ModelSource::Config(name.to_string())
324        };
325        match EmbeddingModel::from_str_name(name) {
326            Some(EmbeddingModel::Custom(mut spec)) => {
327                spec.dimensions = config_dims;
328                if spec.revision.is_none() {
329                    tracing::warn!(
330                        "Custom embedding model {:?} has no revision pin — supply-chain best \
331                         practice is `hf:{}@<commit-or-tag>` so upstream pushes can never \
332                         silently change your index",
333                        spec.repo,
334                        spec.repo
335                    );
336                }
337                return (EmbeddingModel::Custom(spec), origin);
338            }
339            Some(model) => return (model, origin),
340            None => {
341                tracing::warn!(
342                    "Unknown embedding model {name:?} from {source}; using {} instead \
343                     (built-ins: minilm, nomic — or hf:org/repo[@rev])",
344                    EmbeddingModel::DEFAULT
345                );
346            }
347        }
348    }
349    (EmbeddingModel::DEFAULT, ModelSource::Default)
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    #[test]
357    fn default_model_is_minilm() {
358        assert_eq!(EmbeddingModel::DEFAULT, EmbeddingModel::AllMiniLmL6V2);
359    }
360
361    #[test]
362    fn from_str_name_variants() {
363        assert_eq!(
364            EmbeddingModel::from_str_name("minilm"),
365            Some(EmbeddingModel::AllMiniLmL6V2)
366        );
367        assert_eq!(
368            EmbeddingModel::from_str_name("nomic-embed-v1.5"),
369            Some(EmbeddingModel::NomicEmbedV1_5)
370        );
371        assert_eq!(
372            EmbeddingModel::from_str_name("nomic"),
373            Some(EmbeddingModel::NomicEmbedV1_5)
374        );
375        assert_eq!(
376            EmbeddingModel::from_str_name("default"),
377            Some(EmbeddingModel::AllMiniLmL6V2)
378        );
379        assert_eq!(EmbeddingModel::from_str_name("unknown"), None);
380        // The removed jina built-in must no longer resolve as an alias; it is
381        // reachable only via the explicit `hf:` custom scheme.
382        assert_eq!(EmbeddingModel::from_str_name("jina-code-v2"), None);
383        assert_eq!(EmbeddingModel::from_str_name("jina"), None);
384    }
385
386    #[test]
387    fn custom_hf_scheme_parses_repo_and_revision() {
388        let m = EmbeddingModel::from_str_name("hf:jinaai/jina-embeddings-v2-base-code").unwrap();
389        let EmbeddingModel::Custom(spec) = &m else {
390            panic!("expected custom")
391        };
392        assert_eq!(spec.repo, "jinaai/jina-embeddings-v2-base-code");
393        assert_eq!(spec.revision, None);
394
395        let m = EmbeddingModel::from_str_name("hf:org/model@abc123").unwrap();
396        let EmbeddingModel::Custom(spec) = &m else {
397            panic!("expected custom")
398        };
399        assert_eq!(spec.repo, "org/model");
400        assert_eq!(spec.revision.as_deref(), Some("abc123"));
401    }
402
403    #[test]
404    fn custom_hf_scheme_rejects_invalid_repos() {
405        for bad in [
406            "hf:",
407            "hf:no-slash",
408            "hf:too/many/slashes",
409            "hf:with space/repo",
410            "hf:/leading",
411            "hf:trailing/",
412            "hf:org/model@",
413        ] {
414            let parsed = EmbeddingModel::from_str_name(bad);
415            if bad == "hf:org/model@" {
416                // Empty revision degrades to an unpinned spec, not a reject.
417                let Some(EmbeddingModel::Custom(spec)) = parsed else {
418                    panic!("expected custom for {bad}")
419                };
420                assert_eq!(spec.revision, None);
421            } else {
422                assert_eq!(parsed, None, "{bad} should be rejected");
423            }
424        }
425    }
426
427    #[test]
428    fn custom_config_urls_and_storage() {
429        let m = EmbeddingModel::from_str_name("hf:Org/My_Model@v1.2").unwrap();
430        let cfg = m.config();
431        assert_eq!(
432            cfg.model_url(),
433            "https://huggingface.co/Org/My_Model/resolve/v1.2/onnx/model.onnx"
434        );
435        assert_eq!(
436            cfg.vocab_url(),
437            "https://huggingface.co/Org/My_Model/resolve/v1.2/tokenizer.json"
438        );
439        assert!(!cfg.vocab_file.is_wordpiece());
440        assert_eq!(cfg.name, "hf:Org/My_Model@v1.2");
441        assert_eq!(m.storage_dir_name(), "hf-org-my-model-v1-2");
442    }
443
444    #[test]
445    fn custom_storage_slugs_differ_per_revision() {
446        let a = EmbeddingModel::from_str_name("hf:org/model@aaa").unwrap();
447        let b = EmbeddingModel::from_str_name("hf:org/model@bbb").unwrap();
448        let c = EmbeddingModel::from_str_name("hf:org/model").unwrap();
449        let slugs = [
450            a.storage_dir_name(),
451            b.storage_dir_name(),
452            c.storage_dir_name(),
453        ];
454        let unique: std::collections::HashSet<_> = slugs.iter().collect();
455        assert_eq!(unique.len(), 3);
456    }
457
458    #[test]
459    fn all_models_have_valid_configs() {
460        for model in EmbeddingModel::ALL {
461            let cfg = model.config();
462            assert!(!cfg.name.is_empty());
463            assert!(!cfg.hf_repo.is_empty());
464            assert!(cfg.dimensions > 0);
465            assert!(cfg.max_seq_len > 0);
466            assert!(cfg.model_min_bytes > 0);
467            assert!(cfg.vocab_min_bytes > 0);
468        }
469    }
470
471    #[test]
472    fn model_urls_are_valid() {
473        for model in EmbeddingModel::ALL {
474            let cfg = model.config();
475            let model_url = cfg.model_url();
476            let vocab_url = cfg.vocab_url();
477            assert!(model_url.starts_with("https://huggingface.co/"));
478            assert!(vocab_url.starts_with("https://huggingface.co/"));
479            assert!(model_url.contains("resolve/main"));
480        }
481    }
482
483    #[test]
484    fn storage_dir_names_are_unique() {
485        let names: Vec<_> = EmbeddingModel::ALL
486            .iter()
487            .map(EmbeddingModel::storage_dir_name)
488            .collect();
489        let unique: std::collections::HashSet<_> = names.iter().collect();
490        assert_eq!(names.len(), unique.len());
491    }
492
493    #[test]
494    fn display_uses_model_name() {
495        assert_eq!(
496            format!("{}", EmbeddingModel::AllMiniLmL6V2),
497            "all-MiniLM-L6-v2"
498        );
499        assert_eq!(
500            format!("{}", EmbeddingModel::NomicEmbedV1_5),
501            "nomic-embed-text-v1.5"
502        );
503    }
504
505    #[test]
506    fn resolve_defaults_when_nothing_set() {
507        assert_eq!(
508            resolve_model_from(None, None, None),
509            EmbeddingModel::DEFAULT
510        );
511        assert_eq!(
512            resolve_model_from(Some(""), Some("   "), None),
513            EmbeddingModel::DEFAULT
514        );
515    }
516
517    #[test]
518    fn config_selects_model_when_env_unset() {
519        assert_eq!(
520            resolve_model_from(None, Some("nomic"), None),
521            EmbeddingModel::NomicEmbedV1_5
522        );
523        assert_eq!(
524            resolve_model_from(None, Some("minilm"), None),
525            EmbeddingModel::AllMiniLmL6V2
526        );
527    }
528
529    #[test]
530    fn resolution_reports_the_setting_that_won() {
531        assert_eq!(
532            resolve_model_with_source_from(Some(" nomic "), Some("minilm"), None).1,
533            ModelSource::Env("nomic".into())
534        );
535        assert_eq!(
536            resolve_model_with_source_from(Some("bogus"), Some("nomic"), None).1,
537            ModelSource::Config("nomic".into())
538        );
539        assert_eq!(
540            resolve_model_with_source_from(None, Some("nope"), None).1,
541            ModelSource::Default
542        );
543    }
544
545    #[test]
546    fn env_var_overrides_config() {
547        assert_eq!(
548            resolve_model_from(Some("minilm"), Some("nomic"), None),
549            EmbeddingModel::AllMiniLmL6V2
550        );
551    }
552
553    #[test]
554    fn unknown_name_falls_through_then_defaults() {
555        // Bad env value → valid config value wins.
556        assert_eq!(
557            resolve_model_from(Some("bogus"), Some("nomic"), None),
558            EmbeddingModel::NomicEmbedV1_5
559        );
560        // Bad everywhere → default (never silently breaks the index).
561        assert_eq!(
562            resolve_model_from(Some("bogus"), Some("nope"), None),
563            EmbeddingModel::DEFAULT
564        );
565        // Empty/whitespace in the higher-priority source is skipped, not treated as a match.
566        assert_eq!(
567            resolve_model_from(Some("   "), Some("nomic"), None),
568            EmbeddingModel::NomicEmbedV1_5
569        );
570    }
571
572    #[test]
573    fn resolve_custom_picks_up_config_dimensions() {
574        let m = resolve_model_from(None, Some("hf:org/model@pin"), Some(1024));
575        let EmbeddingModel::Custom(spec) = m else {
576            panic!("expected custom")
577        };
578        assert_eq!(spec.dimensions, Some(1024));
579        assert_eq!(spec.revision.as_deref(), Some("pin"));
580    }
581
582    #[test]
583    fn nomic_has_prefixes() {
584        let cfg = EmbeddingModel::NomicEmbedV1_5.config();
585        assert!(cfg.query_prefix.is_some());
586        assert!(cfg.document_prefix.is_some());
587        assert!(!cfg.needs_token_type_ids);
588    }
589
590    #[test]
591    fn minilm_is_wordpiece() {
592        let cfg = EmbeddingModel::AllMiniLmL6V2.config();
593        assert!(cfg.vocab_file.is_wordpiece());
594    }
595
596    #[test]
597    fn builtin_models_have_valid_vocab_sources() {
598        // All current built-ins are WordPiece (vocab.txt) models. Custom HF
599        // repos use tokenizer.json, but those are user-defined, not built-ins.
600        for model in EmbeddingModel::ALL {
601            assert!(
602                model.config().vocab_file.is_wordpiece(),
603                "{model} should use WordPiece vocab.txt"
604            );
605        }
606    }
607
608    #[test]
609    fn custom_models_use_tokenizer_json() {
610        let m = EmbeddingModel::from_str_name("hf:org/model").unwrap();
611        assert!(!m.config().vocab_file.is_wordpiece());
612        assert_eq!(m.config().vocab_file.filename(), "tokenizer.json");
613    }
614}