{{ message }}
Repository navigation
Expand file tree
/
Copy pathembeddings.rs
More file actions
2431 lines (2225 loc) · 95 KB
/
Copy pathembeddings.rs
File metadata and controls
2431 lines (2225 loc) · 95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Text Embedding Providers
//!
//! This module provides a pluggable embedding system for AgenticDB.
//!
//! ## Available Providers
//!
//! - **HashEmbedding**: Fast hash-based placeholder (default, not semantic)
//! - **OnnxEmbedding**: Real semantic embeddings using ONNX Runtime (feature: `onnx-embeddings`) ✅ RECOMMENDED
//! - **LatticeEmbedding**: Real semantic embeddings using lattice-embed, pure-Rust native inference (feature: `lattice-embeddings`)
//! - **CandleEmbedding**: Real embeddings using candle-transformers (feature: `real-embeddings`)
//! - **ApiEmbedding**: External API calls (OpenAI, Anthropic, Cohere, etc.)
//!
//! ## Usage
//!
//! ```rust,no_run
//! use ruvector_core::embeddings::{EmbeddingProvider, HashEmbedding};
//!
//! // Default: Hash-based (fast, but not semantic)
//! let hash_provider = HashEmbedding::new(384);
//! let embedding = hash_provider.embed("hello world")?;
//!
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## ONNX Embeddings (Recommended for Production)
//!
//! ```rust,ignore
//! use ruvector_core::embeddings::{EmbeddingProvider, OnnxEmbedding};
//!
//! // Real semantic embeddings using all-MiniLM-L6-v2
//! let provider = OnnxEmbedding::from_pretrained("sentence-transformers/all-MiniLM-L6-v2")?;
//! let embedding = provider.embed("hello world")?;
//! // "dog" and "cat" WILL be similar (semantic understanding!)
//! ```
use crate::error::{Result, RuvectorError};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use unicode_normalization::UnicodeNormalization;
/// The role of text at a retrieval boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EmbeddingRole {
Query,
Passage,
}
/// Whether a model requires distinct query and passage transforms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EmbeddingRolePolicy {
Symmetric,
Asymmetric,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PoolingStrategy {
Named(PoolingStrategyName),
Custom {
custom: String,
implementation_revision: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PoolingStrategyName {
Mean,
Cls,
LastToken,
WeightedMean,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OutputDtype {
F32,
F16,
Bf16,
I8,
U8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum EmbeddingDistanceMetric {
Cosine,
Dot,
Euclidean,
Manhattan,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PrefixPolicy {
None,
Required,
QueryRecommended,
Custom,
}
/// Complete immutable identity of a retrieval vector space.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmbeddingSpaceIdentity {
pub schema_version: u16,
pub provider: String,
pub model_id: String,
pub model_artifact_sha256: String,
pub model_graph_sha256: String,
pub tokenizer_sha256: String,
pub prompt_template_sha256: String,
pub pooling_strategy: PoolingStrategy,
pub normalize: bool,
pub truncation_tokens: u32,
pub output_dimension: u32,
pub output_dtype: OutputDtype,
pub runtime_revision: String,
pub distance_metric: EmbeddingDistanceMetric,
pub role_policy: EmbeddingRolePolicy,
pub prefix_policy: PrefixPolicy,
pub prefix_policy_version: u32,
}
const EMBEDDING_SPACE_DOMAIN: &[u8] = b"ruvector.embedding-space.v1\0";
/// Revision of this crate's *embedding semantics*, and the only ruvector-owned
/// version number that may reach `runtime_revision` and therefore
/// `embedding_space_id`.
///
/// Bump this ONLY when a change alters the vectors ruvector produces for an
/// otherwise-identical model: pooling, normalization, tokenization, truncation,
/// quantization, or role/prefix handling. Never bump it for a release, a
/// refactor, or a dependency upgrade.
///
/// # Why the crate version is not used here
/// `embedding_space_id` gates corpus compatibility and cache reuse. If the
/// crate version were an input, a routine workspace version bump (2.2.3 → 2.3.0
/// has already happened once in this repo's history) would change every id:
/// every persisted `AgenticDB` corpus would refuse to reopen with
/// `EmbeddingSpaceMismatch`, and 100% of cluster cache entries would be
/// invalidated, without a single vector actually changing. The id must be a
/// function of the embedding function alone.
pub const EMBEDDING_SPACE_FORMAT_REVISION: u32 = 1;
/// Build provenance of the running binary — informational only.
///
/// This is deliberately NOT a field of [`EmbeddingSpaceIdentity`]: the identity
/// is a closed, cross-language wire contract (`schemas/embedding-space-identity-v1.json`
/// pins exactly 17 properties with `additionalProperties: false`, and
/// `npm/packages/ruvector/src/core/embedding-provenance.ts` mirrors it), and
/// every field it carries is hashed into `embedding_space_id`. A build version
/// belongs in logs and diagnostics, not in the vector-space identity — see
/// [`EMBEDDING_SPACE_FORMAT_REVISION`].
pub fn build_revision() -> &'static str {
env!("CARGO_PKG_VERSION")
}
/// `runtime_revision` value for a provider class.
///
/// Identifies which inference stack produced the vectors plus the semantics
/// revision above. It carries no crate or dependency version, so upgrading
/// ruvector or its runtime dependencies leaves every persisted corpus readable
/// and every cache entry valid.
fn runtime_revision_for(provider_class: &str) -> String {
format!("{provider_class}/space-rev-{EMBEDDING_SPACE_FORMAT_REVISION}")
}
impl EmbeddingSpaceIdentity {
pub fn validate(&self) -> Result<()> {
if self.schema_version != 1 {
return Err(RuvectorError::InvalidParameter(format!(
"unsupported embedding identity schema version {}",
self.schema_version
)));
}
if self.output_dimension == 0
|| self.truncation_tokens == 0
|| self.prefix_policy_version == 0
{
return Err(RuvectorError::InvalidParameter(
"embedding identity dimensions, truncation, and policy version must be positive"
.into(),
));
}
for (name, value) in [
("provider", self.provider.as_str()),
("model_id", self.model_id.as_str()),
("runtime_revision", self.runtime_revision.as_str()),
] {
if value.is_empty() || value.nfc().collect::<String>() != value {
return Err(RuvectorError::InvalidParameter(format!(
"embedding identity {name} must be non-empty NFC"
)));
}
}
for (name, value) in [
("model_artifact_sha256", self.model_artifact_sha256.as_str()),
("model_graph_sha256", self.model_graph_sha256.as_str()),
("tokenizer_sha256", self.tokenizer_sha256.as_str()),
(
"prompt_template_sha256",
self.prompt_template_sha256.as_str(),
),
] {
if value.len() != 64
|| !value
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
return Err(RuvectorError::InvalidParameter(format!(
"embedding identity {name} must be lowercase SHA-256 hex"
)));
}
}
Ok(())
}
/// RFC-8785 canonical JSON for this schema. The schema contains no
/// non-integer numbers, so recursively sorting object keys is sufficient.
pub fn canonical_json(&self) -> Result<String> {
self.validate()?;
fn canonical(value: &serde_json::Value, out: &mut String) -> Result<()> {
match value {
serde_json::Value::Null => out.push_str("null"),
serde_json::Value::Bool(v) => out.push_str(if *v { "true" } else { "false" }),
serde_json::Value::Number(v) => out.push_str(&v.to_string()),
serde_json::Value::String(v) => out.push_str(
&serde_json::to_string(v)
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?,
),
serde_json::Value::Array(values) => {
out.push('[');
for (index, item) in values.iter().enumerate() {
if index > 0 {
out.push(',');
}
canonical(item, out)?;
}
out.push(']');
}
serde_json::Value::Object(values) => {
out.push('{');
let mut keys: Vec<_> = values.keys().collect();
keys.sort();
for (index, key) in keys.iter().enumerate() {
if index > 0 {
out.push(',');
}
out.push_str(
&serde_json::to_string(key)
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?,
);
out.push(':');
canonical(&values[*key], out)?;
}
out.push('}');
}
}
Ok(())
}
let value = serde_json::to_value(self)
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
let mut output = String::new();
canonical(&value, &mut output)?;
Ok(output)
}
pub fn embedding_space_id(&self) -> Result<String> {
let mut hash = Sha256::new();
hash.update(EMBEDDING_SPACE_DOMAIN);
hash.update(self.canonical_json()?.as_bytes());
Ok(format!("{:x}", hash.finalize()))
}
}
fn sha256_hex(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
pub fn embedding_cache_key(
identity: &EmbeddingSpaceIdentity,
role: EmbeddingRole,
text: &str,
) -> Result<String> {
let text_hash = sha256_hex(text.as_bytes());
let role = match role {
EmbeddingRole::Query => "query",
EmbeddingRole::Passage => "passage",
};
Ok(format!(
"{}:{role}:{text_hash}",
identity.embedding_space_id()?
))
}
/// The exact query and passage prompt templates a registered model owns.
///
/// `{text}` is the single substitution point. The pair is hashed into
/// [`EmbeddingSpaceIdentity::prompt_template_sha256`], so changing either
/// template changes the embedding-space identity (ADR-281 §1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PromptTemplates {
pub query: &'static str,
pub passage: &'static str,
}
impl PromptTemplates {
/// Hash covering the canonical query and passage template bundle.
pub fn sha256(&self) -> String {
sha256_hex(format!("query={}\0passage={}", self.query, self.passage).as_bytes())
}
/// Apply the role's template to raw caller text. Providers call this
/// exactly once; high-level callers never prepend prefixes themselves.
pub fn apply(&self, role: EmbeddingRole, text: &str) -> String {
let template = match role {
EmbeddingRole::Query => self.query,
EmbeddingRole::Passage => self.passage,
};
template.replace("{text}", text)
}
}
/// One pinned model fixture: exact artifact revision aliases, output
/// dimension, role/prefix policy, and the exact prompt templates.
struct RegistryEntry {
aliases: &'static [&'static str],
output_dimension: u32,
role_policy: EmbeddingRolePolicy,
prefix_policy: PrefixPolicy,
templates: PromptTemplates,
}
const SYMMETRIC_TEMPLATES: PromptTemplates = PromptTemplates {
query: "{text}",
passage: "{text}",
};
const BGE_TEMPLATES: PromptTemplates = PromptTemplates {
query: "Represent this sentence for searching relevant passages: {text}",
passage: "{text}",
};
const E5_TEMPLATES: PromptTemplates = PromptTemplates {
query: "query: {text}",
passage: "passage: {text}",
};
const QWEN3_TEMPLATES: PromptTemplates = PromptTemplates {
query: "Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:{text}",
passage: "{text}",
};
/// Registered models, keyed by exact artifact revision rather than family
/// name (ADR-281 §2). Dimensions and templates come from each model card;
/// an id that is not listed here requires a caller-supplied complete
/// [`EmbeddingSpaceIdentity`].
static MODEL_REGISTRY: &[RegistryEntry] = &[
RegistryEntry {
aliases: &[
"sentence-transformers/all-MiniLM-L6-v2",
"all-MiniLM-L6-v2",
"all-minilm-l6-v2",
],
output_dimension: 384,
role_policy: EmbeddingRolePolicy::Symmetric,
prefix_policy: PrefixPolicy::None,
templates: SYMMETRIC_TEMPLATES,
},
RegistryEntry {
aliases: &[
"sentence-transformers/all-mpnet-base-v2",
"all-mpnet-base-v2",
],
output_dimension: 768,
role_policy: EmbeddingRolePolicy::Symmetric,
prefix_policy: PrefixPolicy::None,
templates: SYMMETRIC_TEMPLATES,
},
RegistryEntry {
aliases: &[
"sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
"paraphrase-multilingual-MiniLM-L12-v2",
"paraphrase-multilingual-minilm-l12-v2",
],
output_dimension: 384,
role_policy: EmbeddingRolePolicy::Symmetric,
prefix_policy: PrefixPolicy::None,
templates: SYMMETRIC_TEMPLATES,
},
RegistryEntry {
aliases: &["BAAI/bge-small-en-v1.5", "bge-small-en-v1.5"],
output_dimension: 384,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::QueryRecommended,
templates: BGE_TEMPLATES,
},
RegistryEntry {
aliases: &["BAAI/bge-base-en-v1.5", "bge-base-en-v1.5"],
output_dimension: 768,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::QueryRecommended,
templates: BGE_TEMPLATES,
},
RegistryEntry {
aliases: &["BAAI/bge-large-en-v1.5", "bge-large-en-v1.5"],
output_dimension: 1024,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::QueryRecommended,
templates: BGE_TEMPLATES,
},
RegistryEntry {
aliases: &["intfloat/e5-small-v2", "e5-small-v2"],
output_dimension: 384,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::Required,
templates: E5_TEMPLATES,
},
RegistryEntry {
aliases: &["intfloat/e5-base-v2", "e5-base-v2"],
output_dimension: 768,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::Required,
templates: E5_TEMPLATES,
},
RegistryEntry {
aliases: &["intfloat/e5-large-v2", "e5-large-v2"],
output_dimension: 1024,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::Required,
templates: E5_TEMPLATES,
},
RegistryEntry {
aliases: &["intfloat/multilingual-e5-small", "multilingual-e5-small"],
output_dimension: 384,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::Required,
templates: E5_TEMPLATES,
},
RegistryEntry {
aliases: &["intfloat/multilingual-e5-base", "multilingual-e5-base"],
output_dimension: 768,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::Required,
templates: E5_TEMPLATES,
},
RegistryEntry {
aliases: &["intfloat/multilingual-e5-large", "multilingual-e5-large"],
output_dimension: 1024,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::Required,
templates: E5_TEMPLATES,
},
RegistryEntry {
aliases: &["Qwen/Qwen3-Embedding-0.6B", "qwen3-embedding-0.6b"],
output_dimension: 1024,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::Required,
templates: QWEN3_TEMPLATES,
},
RegistryEntry {
aliases: &["Qwen/Qwen3-Embedding-4B", "qwen3-embedding-4b"],
output_dimension: 2560,
role_policy: EmbeddingRolePolicy::Asymmetric,
prefix_policy: PrefixPolicy::Required,
templates: QWEN3_TEMPLATES,
},
];
fn registry_entry(model_id: &str) -> Option<&'static RegistryEntry> {
MODEL_REGISTRY
.iter()
.find(|entry| entry.aliases.contains(&model_id))
}
/// The exact prompt templates registered for `model_id`.
///
/// Returns an error for models that carry no registry fixture: their prompt
/// behavior cannot be attested, so no prefix may be guessed for them.
pub fn registry_prompt_templates(model_id: &str) -> Result<PromptTemplates> {
registry_entry(model_id)
.map(|entry| entry.templates)
.ok_or_else(|| {
RuvectorError::InvalidParameter(format!(
"no registered prompt templates for embedding model '{model_id}'"
))
})
}
/// Apply the identity's registered prompt template for `role` to raw text.
///
/// This is the single place a prefix is added, so the text actually embedded
/// always matches the templates hashed into
/// [`EmbeddingSpaceIdentity::prompt_template_sha256`] (ADR-281 §4). A prefix
/// policy that promises a transform but whose templates cannot be verified
/// fails closed rather than silently embedding unprefixed text.
pub fn apply_prompt_template(
identity: &EmbeddingSpaceIdentity,
role: EmbeddingRole,
text: &str,
) -> Result<String> {
match identity.prefix_policy {
PrefixPolicy::None => Ok(text.to_owned()),
PrefixPolicy::Custom => Err(RuvectorError::InvalidParameter(format!(
"model '{}' declares PrefixPolicy::Custom; ruvector has no template for it, so \
embedding would silently drop the model's required prompt",
identity.model_id
))),
PrefixPolicy::Required | PrefixPolicy::QueryRecommended => {
let templates = registry_prompt_templates(&identity.model_id)?;
if templates.sha256() != identity.prompt_template_sha256 {
return Err(RuvectorError::InvalidParameter(format!(
"prompt template hash for '{}' disagrees with the registry fixture; the \
attested identity does not describe the templates that would be applied",
identity.model_id
)));
}
Ok(templates.apply(role, text))
}
}
}
/// A non-attested symmetric identity for providers with no registry fixture
/// (hash placeholders, opaque fleet backends, tests).
///
/// The artifact hashes are derived from `provider`/`model_id`, not from model
/// bytes: this identity states "this vector space is whatever this named
/// provider produces", which is enough to keep corpora from mixing but is not
/// artifact provenance. Attested paths must supply a complete identity.
pub fn default_space_identity(
provider: &str,
model_id: &str,
dimension: usize,
) -> EmbeddingSpaceIdentity {
let fixture = format!("{provider}\0{model_id}\0v1");
EmbeddingSpaceIdentity {
schema_version: 1,
provider: provider.into(),
model_id: model_id.into(),
model_artifact_sha256: sha256_hex(format!("{fixture}\0artifact").as_bytes()),
model_graph_sha256: sha256_hex(format!("{fixture}\0graph").as_bytes()),
tokenizer_sha256: sha256_hex(format!("{fixture}\0tokenizer").as_bytes()),
prompt_template_sha256: sha256_hex(
format!("{fixture}\0query={{text}}\0passage={{text}}").as_bytes(),
),
pooling_strategy: PoolingStrategy::Named(PoolingStrategyName::Mean),
normalize: true,
truncation_tokens: 512,
output_dimension: dimension as u32,
output_dtype: OutputDtype::F32,
runtime_revision: runtime_revision_for("ruvector-core"),
distance_metric: EmbeddingDistanceMetric::Cosine,
role_policy: EmbeddingRolePolicy::Symmetric,
prefix_policy: PrefixPolicy::None,
prefix_policy_version: 1,
}
}
/// Build the identity a registered model must have, from the exact registry
/// fixture for `model_id`.
///
/// Errors when the id is unregistered or when `dimension` disagrees with the
/// registered output dimension — a family-name guess is never substituted.
/// Callers that load real artifacts overwrite the hash fields with digests of
/// the bytes they loaded.
pub fn registry_identity(
provider: &str,
model_id: &str,
dimension: usize,
) -> Result<EmbeddingSpaceIdentity> {
let entry = registry_entry(model_id).ok_or_else(|| {
RuvectorError::InvalidParameter(format!(
"unknown embedding model '{model_id}' requires an explicit complete \
EmbeddingSpaceIdentity"
))
})?;
if entry.output_dimension as usize != dimension {
return Err(RuvectorError::InvalidParameter(format!(
"embedding model '{model_id}' is registered at {} dimensions, not {dimension}",
entry.output_dimension
)));
}
let mut identity = default_space_identity(provider, model_id, dimension);
identity.role_policy = entry.role_policy;
identity.prefix_policy = entry.prefix_policy;
identity.prompt_template_sha256 = entry.templates.sha256();
Ok(identity)
}
static LEGACY_EMBED_CALLS: AtomicU64 = AtomicU64::new(0);
pub fn legacy_embed_call_count() -> u64 {
LEGACY_EMBED_CALLS.load(Ordering::Relaxed)
}
/// Capabilities retained when opening a corpus with an incompatible active
/// embedding space. Vector inspection never invokes the active embedder.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EmbeddingSpaceAccess {
pub text_embedding: bool,
pub corpus_mutation: bool,
pub vector_read: bool,
pub inspect: bool,
pub verify: bool,
pub export: bool,
}
impl EmbeddingSpaceAccess {
pub fn for_identities(
stored: &EmbeddingSpaceIdentity,
active: &EmbeddingSpaceIdentity,
) -> Result<Self> {
let compatible = stored.embedding_space_id()? == active.embedding_space_id()?;
Ok(Self {
text_embedding: compatible,
corpus_mutation: compatible,
vector_read: true,
inspect: true,
verify: true,
export: true,
})
}
}
/// Explicit migration wrapper for symmetric embedding implementations.
pub struct SymmetricEmbeddingAdapter<F>
where
F: Fn(&str) -> Result<Vec<f32>> + Send + Sync,
{
embed_fn: F,
identity: EmbeddingSpaceIdentity,
name: String,
}
impl<F> SymmetricEmbeddingAdapter<F>
where
F: Fn(&str) -> Result<Vec<f32>> + Send + Sync,
{
pub fn new(
name: impl Into<String>,
identity: EmbeddingSpaceIdentity,
embed_fn: F,
) -> Result<Self> {
identity.validate()?;
if identity.role_policy != EmbeddingRolePolicy::Symmetric {
return Err(RuvectorError::InvalidParameter(
"SymmetricEmbeddingAdapter requires role_policy=symmetric".into(),
));
}
Ok(Self {
embed_fn,
identity,
name: name.into(),
})
}
}
impl<F> EmbeddingProvider for SymmetricEmbeddingAdapter<F>
where
F: Fn(&str) -> Result<Vec<f32>> + Send + Sync,
{
fn embed_for(&self, _role: EmbeddingRole, text: &str) -> Result<Vec<f32>> {
(self.embed_fn)(text)
}
fn embedding_space(&self) -> &EmbeddingSpaceIdentity {
&self.identity
}
fn dimensions(&self) -> usize {
self.identity.output_dimension as usize
}
fn name(&self) -> &str {
&self.name
}
}
/// Trait for text embedding providers
pub trait EmbeddingProvider: Send + Sync {
fn embed_for(&self, role: EmbeddingRole, text: &str) -> Result<Vec<f32>>;
fn embedding_space(&self) -> &EmbeddingSpaceIdentity;
fn embed_query(&self, text: &str) -> Result<Vec<f32>> {
self.embed_for(EmbeddingRole::Query, text)
}
fn embed_passage(&self, text: &str) -> Result<Vec<f32>> {
self.embed_for(EmbeddingRole::Passage, text)
}
#[deprecated(note = "use embed_query or embed_passage")]
fn embed(&self, text: &str) -> Result<Vec<f32>> {
LEGACY_EMBED_CALLS.fetch_add(1, Ordering::Relaxed);
self.embed_for(EmbeddingRole::Passage, text)
}
fn embed_batch_for(&self, role: EmbeddingRole, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
texts
.iter()
.map(|text| self.embed_for(role, text))
.collect()
}
fn embed_query_batch(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
self.embed_batch_for(EmbeddingRole::Query, texts)
}
fn embed_passage_batch(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
self.embed_batch_for(EmbeddingRole::Passage, texts)
}
/// Get the dimensionality of embeddings produced by this provider
fn dimensions(&self) -> usize;
/// Get a description of this provider (for logging/debugging)
fn name(&self) -> &str;
}
/// Hash-based embedding provider (placeholder, not semantic)
///
/// ⚠️ **WARNING**: This does NOT produce semantic embeddings!
/// - "dog" and "cat" will NOT be similar
/// - "dog" and "god" WILL be similar (same characters)
///
/// Use this only for:
/// - Testing
/// - Prototyping
/// - When semantic similarity is not required
#[derive(Debug, Clone)]
pub struct HashEmbedding {
dimensions: usize,
identity: EmbeddingSpaceIdentity,
}
impl HashEmbedding {
/// Create a new hash-based embedding provider
pub fn new(dimensions: usize) -> Self {
Self {
dimensions,
identity: default_space_identity("ruvector-hash", "hash-v1", dimensions),
}
}
}
impl EmbeddingProvider for HashEmbedding {
fn embed_for(&self, _role: EmbeddingRole, text: &str) -> Result<Vec<f32>> {
let mut embedding = vec![0.0; self.dimensions];
let bytes = text.as_bytes();
for (i, byte) in bytes.iter().enumerate() {
embedding[i % self.dimensions] += (*byte as f32) / 255.0;
}
// Normalize
let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
if norm > 0.0 {
for val in &mut embedding {
*val /= norm;
}
}
Ok(embedding)
}
fn embedding_space(&self) -> &EmbeddingSpaceIdentity {
&self.identity
}
fn dimensions(&self) -> usize {
self.dimensions
}
fn name(&self) -> &str {
"HashEmbedding (placeholder)"
}
}
/// Real embeddings using candle-transformers
///
/// Requires feature flag: `real-embeddings`
///
/// ⚠️ **Note**: Full candle integration is complex and model-specific.
/// For production use, we recommend:
/// 1. Using the API-based providers (simpler, always up-to-date)
/// 2. Using ONNX Runtime with pre-exported models
/// 3. Implementing your own candle wrapper for your specific model
///
/// This is a stub implementation showing the structure.
/// Users should implement `EmbeddingProvider` trait for their specific models.
#[cfg(feature = "real-embeddings")]
pub mod candle {
use super::*;
/// Candle-based embedding provider stub
///
/// This is a placeholder. For real implementation:
/// 1. Add candle dependencies for your specific model type
/// 2. Implement model loading and inference
/// 3. Handle tokenization appropriately
///
/// Example structure:
/// ```rust,ignore
/// pub struct CandleEmbedding {
/// model: YourModelType,
/// tokenizer: Tokenizer,
/// device: Device,
/// dimensions: usize,
/// }
/// ```
pub struct CandleEmbedding {
dimensions: usize,
model_id: String,
identity: EmbeddingSpaceIdentity,
}
impl CandleEmbedding {
/// Create a stub candle embedding provider
///
/// **This is not a real implementation!**
/// For production, implement with actual model loading.
///
/// # Example
/// ```rust,no_run
/// # #[cfg(feature = "real-embeddings")]
/// # {
/// use ruvector_core::embeddings::candle::CandleEmbedding;
///
/// // This returns an error - real implementation required
/// let result = CandleEmbedding::from_pretrained(
/// "sentence-transformers/all-MiniLM-L6-v2",
/// false
/// );
/// assert!(result.is_err());
/// # }
/// ```
pub fn from_pretrained(model_id: &str, _use_gpu: bool) -> Result<Self> {
Err(RuvectorError::ModelLoadError(format!(
"Candle embedding support is a stub. Please:\n\
1. Use ApiEmbedding for production (recommended)\n\
2. Or implement CandleEmbedding for model: {}\n\
3. See docs for ONNX Runtime integration examples",
model_id
)))
}
}
impl EmbeddingProvider for CandleEmbedding {
fn embed_for(&self, _role: EmbeddingRole, _text: &str) -> Result<Vec<f32>> {
Err(RuvectorError::ModelInferenceError(
"Candle embedding not implemented - use ApiEmbedding instead".to_string(),
))
}
fn embedding_space(&self) -> &EmbeddingSpaceIdentity {
&self.identity
}
fn dimensions(&self) -> usize {
self.dimensions
}
fn name(&self) -> &str {
"CandleEmbedding (stub - not implemented)"
}
}
}
#[cfg(feature = "real-embeddings")]
pub use candle::CandleEmbedding;
/// API-based embedding provider (OpenAI, Anthropic, Cohere, etc.)
///
/// Supports any API that accepts JSON and returns embeddings in a standard format.
///
/// # Example (OpenAI)
/// ```rust,no_run
/// use ruvector_core::embeddings::{EmbeddingProvider, ApiEmbedding};
///
/// # let identity = todo!("load a pinned EmbeddingSpaceIdentity");
/// let provider = ApiEmbedding::openai("sk-...", "text-embedding-3-small", identity)?;
/// let embedding = provider.embed("hello world")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "api-embeddings")]
#[derive(Clone)]
pub struct ApiEmbedding {
api_key: String,
endpoint: String,
model: String,
dimensions: usize,
identity: EmbeddingSpaceIdentity,
client: reqwest::blocking::Client,
}
#[cfg(feature = "api-embeddings")]
impl ApiEmbedding {
/// Create a new API embedding provider
///
/// # Arguments
/// * `api_key` - API key for authentication
/// * `endpoint` - API endpoint URL
/// * `model` - Model identifier
/// * `dimensions` - Expected embedding dimensions
pub fn new(
api_key: String,
endpoint: String,
model: String,
dimensions: usize,
identity: EmbeddingSpaceIdentity,
) -> Result<Self> {
identity.validate()?;
if identity.model_id != model || identity.output_dimension as usize != dimensions {
return Err(RuvectorError::InvalidParameter(
"remote provider identity must match the requested model and dimension".into(),
));
}
// Fail at construction, not on the first embed: a prefix policy this
// provider cannot honor would otherwise send raw text to the API while
// the identity attests that a template was applied. Probing with a
// sample of each role is enough — `apply_prompt_template` is
// deterministic in the identity, not the text.
for role in [EmbeddingRole::Query, EmbeddingRole::Passage] {
apply_prompt_template(&identity, role, "probe")?;
}
Ok(Self {
api_key,
endpoint,
model,
dimensions,
identity,
client: reqwest::blocking::Client::new(),
})
}
/// Create OpenAI embedding provider
///
/// # Models
/// - `text-embedding-3-small` - 1536 dimensions, $0.02/1M tokens
/// - `text-embedding-3-large` - 3072 dimensions, $0.13/1M tokens
/// - `text-embedding-ada-002` - 1536 dimensions (legacy)
pub fn openai(api_key: &str, model: &str, identity: EmbeddingSpaceIdentity) -> Result<Self> {
let dimensions = match model {
"text-embedding-3-large" => 3072,
_ => 1536, // text-embedding-3-small and ada-002
};
Self::new(
api_key.to_string(),
"https://api.openai.com/v1/embeddings".to_string(),
model.to_string(),
dimensions,
identity,
)
}
/// Create Cohere embedding provider
///
/// # Models
/// - `embed-english-v3.0` - 1024 dimensions
/// - `embed-multilingual-v3.0` - 1024 dimensions
pub fn cohere(api_key: &str, model: &str, identity: EmbeddingSpaceIdentity) -> Result<Self> {
Self::new(
api_key.to_string(),
"https://api.cohere.ai/v1/embed".to_string(),
model.to_string(),
1024,
identity,
)
}
/// Create Voyage AI embedding provider
///
/// # Models
/// - `voyage-2` - 1024 dimensions
/// - `voyage-large-2` - 1536 dimensions
pub fn voyage(api_key: &str, model: &str, identity: EmbeddingSpaceIdentity) -> Result<Self> {
let dimensions = if model.contains("large") { 1536 } else { 1024 };
Self::new(
api_key.to_string(),
"https://api.voyageai.com/v1/embeddings".to_string(),
model.to_string(),
dimensions,
identity,
)
}
}
#[cfg(feature = "api-embeddings")]
impl EmbeddingProvider for ApiEmbedding {
fn embed_for(&self, role: EmbeddingRole, text: &str) -> Result<Vec<f32>> {
// Same contract as the ONNX path: the provider owns prefixing, and the
// templates come from the identity's registry fixture so the text sent
// upstream matches what `prompt_template_sha256` attests (ADR-281 §4).
// Endpoints whose own `input_type` handles the role declare
// PrefixPolicy::None and are unaffected.
let prepared = apply_prompt_template(&self.identity, role, text)?;
You can’t perform that action at this time.
