1use crate::{storage::{self, KnowledgeBase}, text, types::*, Error, Result};
2use parking_lot::{Condvar, Mutex};
3use rusqlite::{params, params_from_iter, types::Value as SqlValue, Connection, OptionalExtension};
4use serde::{Deserialize, Serialize};
5use std::{cmp::Ordering, collections::{BTreeMap, BinaryHeap, HashMap, HashSet},
6 sync::{atomic::{AtomicBool, Ordering as AtomicOrdering}, Arc, Weak}, thread::JoinHandle};
7
8fn text_version() -> u32 { 1 }
9fn default_encoding() -> String { "sq8".into() }
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
11pub struct EmbeddingSpace {
12 pub id: String,
13 pub model: String,
15 pub dimension: usize,
16 #[serde(default = "text_version")] pub text_version: u32,
17 #[serde(default = "default_encoding")] pub encoding: String,
19}
20#[derive(Debug, Clone)]
22pub(crate) struct EmbeddingInput { pub key: RecordKey, pub text: String, pub fingerprint: String }
23#[derive(Debug, Clone)]
25pub(crate) struct EmbeddingWrite { pub key: RecordKey, pub fingerprint: String, pub values: Vec<f32> }
26
27#[derive(Clone)]
28pub struct EmbeddingStore(pub(crate) KnowledgeBase);
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum EmbedErrorKind {
36 TooLarge,
38 RateLimited,
40 Other,
42}
43
44impl EmbedErrorKind {
45 pub fn code(self) -> &'static str {
46 match self { Self::TooLarge => "too_large", Self::RateLimited => "rate_limited", Self::Other => "other" }
47 }
48 pub fn from_code(code: &str) -> Option<Self> {
49 match code { "too_large" => Some(Self::TooLarge), "rate_limited" => Some(Self::RateLimited), "other" => Some(Self::Other), _ => None }
50 }
51}
52
53#[derive(Debug, Clone)]
55pub struct EmbedCallbackError { pub kind: EmbedErrorKind, pub message: String }
56
57impl EmbedCallbackError {
58 pub fn new(kind: EmbedErrorKind, message: impl Into<String>) -> Self { Self { kind, message: message.into() } }
59 pub fn too_large(message: impl Into<String>) -> Self { Self::new(EmbedErrorKind::TooLarge, message) }
60 pub fn rate_limited(message: impl Into<String>) -> Self { Self::new(EmbedErrorKind::RateLimited, message) }
61 pub fn other(message: impl Into<String>) -> Self { Self::new(EmbedErrorKind::Other, message) }
62}
63
64impl std::fmt::Display for EmbedCallbackError {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}: {}", self.kind.code(), self.message) }
66}
67impl std::error::Error for EmbedCallbackError {}
68
69pub trait Embedder: Send {
71 fn embed(&mut self, texts: &[String]) -> std::result::Result<Vec<Vec<f32>>, EmbedCallbackError>;
72}
73
74impl<F> Embedder for F
75where F: FnMut(&[String]) -> std::result::Result<Vec<Vec<f32>>, EmbedCallbackError> + Send {
76 fn embed(&mut self, texts: &[String]) -> std::result::Result<Vec<Vec<f32>>, EmbedCallbackError> { self(texts) }
77}
78
79fn default_max_batch() -> usize { 32 }
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
82pub struct EmbedderOptions {
83 #[serde(default = "default_max_batch")] pub max_batch: usize,
84 #[serde(default)] pub max_tokens_per_text: Option<usize>,
86}
87impl Default for EmbedderOptions {
88 fn default() -> Self { Self { max_batch: default_max_batch(), max_tokens_per_text: None } }
89}
90
91pub(crate) struct EmbedderEntry {
92 pub options: EmbedderOptions,
93 pub effective_batch: usize,
95 pub embedder: Box<dyn Embedder>,
96}
97
98impl EmbedderEntry {
99 pub(crate) fn embed(&mut self, texts: &[String]) -> std::result::Result<Vec<Vec<f32>>, EmbedCallbackError> {
101 match self.options.max_tokens_per_text {
102 Some(budget) => {
103 let budgeted: Vec<String> = texts.iter().map(|value| text::truncate_to_tokens(value, budget)).collect();
104 self.embedder.embed(&budgeted)
105 }
106 None => self.embedder.embed(texts),
107 }
108 }
109}
110
111#[derive(Default)]
113pub(crate) struct EmbedderRegistry { entries: Mutex<HashMap<String, Arc<Mutex<EmbedderEntry>>>> }
114
115impl EmbedderRegistry {
116 pub fn new() -> Self { Self::default() }
117 pub fn space_ids(&self) -> Vec<String> {
118 let mut ids: Vec<String> = self.entries.lock().keys().cloned().collect();
119 ids.sort();
120 ids
121 }
122 pub fn get(&self, space_id: &str) -> Option<Arc<Mutex<EmbedderEntry>>> { self.entries.lock().get(space_id).cloned() }
123 pub fn register(&self, space_id: String, entry: EmbedderEntry) { self.entries.lock().insert(space_id, Arc::new(Mutex::new(entry))); }
124 pub fn remove(&self, space_id: &str) -> bool { self.entries.lock().remove(space_id).is_some() }
125}
126
127const SAMPLE_TEXTS: [&str; 3] = ["样本一 sample", "样本二 sample", "样本三 sample"];
129
130const RATE_LIMIT_ATTEMPTS: u32 = 3;
131const RATE_LIMIT_BACKOFF_MS: u64 = 20;
132
133pub(crate) fn get_space(conn: &Connection, id: &str) -> Result<EmbeddingSpace> {
134 conn.query_row("SELECT id,model,dimension,text_version,encoding FROM embedding_spaces WHERE id=?1", [id], |r|
135 Ok(EmbeddingSpace { id: r.get(0)?, model: r.get(1)?, dimension: r.get::<_, u32>(2)? as usize, text_version: r.get(3)?, encoding: r.get(4)? })).optional()?
136 .ok_or_else(|| Error::NotFound(format!("embedding space {id}")))
137}
138
139pub(crate) fn normalize(values: &[f32], dimension: usize) -> Result<Vec<f32>> {
140 if values.len() != dimension { return Err(Error::InvalidVector(format!("expected dimension {dimension}, received {}", values.len()))); }
141 if values.iter().any(|v| !v.is_finite()) { return Err(Error::InvalidVector("values must be finite".into())); }
142 let norm = values.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>().sqrt();
143 if norm == 0.0 || !norm.is_finite() { return Err(Error::InvalidVector("zero or invalid vector norm".into())); }
144 Ok(values.iter().map(|v| (f64::from(*v) / norm) as f32).collect())
145}
146
147#[inline]
150fn dot(a: &[f32], b: &[f32]) -> f32 {
151 let mut acc = [0f32; 8];
152 let chunks = a.len() / 8;
153 for c in 0..chunks {
154 let o = c * 8;
155 for k in 0..8 { acc[k] += a[o + k] * b[o + k]; }
156 }
157 let mut sum = acc.iter().sum::<f32>();
158 for i in chunks * 8..a.len() { sum += a[i] * b[i]; }
159 sum
160}
161
162fn encode_query_sq8(query: &[f32]) -> (Vec<i8>, f32) {
166 let max = query.iter().fold(0f32, |m, v| m.max(v.abs()));
167 let scale = if max == 0.0 { 1.0 } else { max / 127.0 };
168 let codes = query.iter().map(|v| (v / scale).round().clamp(-127.0, 127.0) as i8).collect();
169 (codes, scale)
170}
171
172#[inline]
176fn dot_codes(left: &[i8], right: &[i8]) -> i32 {
177 #[cfg(target_arch = "x86_64")]
178 {
179 if std::is_x86_feature_detected!("avx2") { return unsafe { dot_codes_avx2(left, right) }; }
181 }
182 dot_codes_scalar(left, right)
183}
184
185fn dot_codes_scalar(left: &[i8], right: &[i8]) -> i32 {
186 left.iter().zip(right).map(|(a, b)| i32::from(*a) * i32::from(*b)).sum()
187}
188
189#[cfg(target_arch = "x86_64")]
192#[target_feature(enable = "avx2")]
193unsafe fn dot_codes_avx2(left: &[i8], right: &[i8]) -> i32 {
194 use std::arch::x86_64::*;
195 let mut acc = _mm256_setzero_si256();
196 let chunks = left.len() / 16;
197 for c in 0..chunks {
198 let o = c * 16;
199 let a = _mm_loadu_si128(left.as_ptr().add(o) as *const __m128i);
200 let b = _mm_loadu_si128(right.as_ptr().add(o) as *const __m128i);
201 acc = _mm256_add_epi32(acc, _mm256_madd_epi16(_mm256_cvtepi8_epi16(a), _mm256_cvtepi8_epi16(b)));
202 }
203 let mut total = {
204 let sum = _mm_add_epi32(_mm256_castsi256_si128(acc), _mm256_extracti128_si256(acc, 1));
205 let sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0b01_00_11_10));
206 let sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0b10_11_00_01));
207 _mm_cvtsi128_si32(sum)
208 };
209 for i in chunks * 16..left.len() { total += i32::from(left[i]) * i32::from(right[i]); }
210 total
211}
212
213fn encode_values(normalized: &[f32], encoding: &str) -> Result<Vec<u8>> {
216 match encoding {
217 "f32" => Ok(normalized.iter().flat_map(|v| v.to_le_bytes()).collect()),
218 "sq8" => {
219 let max = normalized.iter().fold(0f32, |m, v| m.max(v.abs()));
220 let scale = if max == 0.0 { 1.0 } else { max / 127.0 };
221 let mut out = Vec::with_capacity(4 + normalized.len());
222 out.extend_from_slice(&scale.to_le_bytes());
223 for v in normalized {
224 out.push((v / scale).round().clamp(-127.0, 127.0) as i8 as u8);
225 }
226 Ok(out)
227 }
228 other => Err(Error::Validation(format!("unknown encoding {other}"))),
229 }
230}
231
232fn decode_values(bytes: &[u8], dimension: usize, encoding: &str) -> Result<Vec<f32>> {
234 match encoding {
235 "f32" => {
236 if bytes.len() != dimension * 4 { return Err(Error::InvalidVector("stored vector dimension mismatch".into())); }
237 Ok(bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())
238 }
239 "sq8" => {
240 let (scale, codes) = decode_sq8(bytes, dimension)?;
241 Ok(codes.into_iter().map(|c| f32::from(c) * scale).collect())
242 }
243 other => Err(Error::Validation(format!("unknown encoding {other}"))),
244 }
245}
246
247fn decode_sq8(bytes: &[u8], dimension: usize) -> Result<(f32, Vec<i8>)> {
250 if bytes.len() != dimension + 4 { return Err(Error::InvalidVector("stored vector dimension mismatch".into())); }
251 let scale = f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
252 Ok((scale, bytes[4..].iter().map(|b| *b as i8).collect()))
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262pub(crate) enum VectorizeTarget { Memory, Graph, Notes }
263
264impl VectorizeTarget {
265 pub(crate) const ALL: [Self; 3] = [Self::Memory, Self::Graph, Self::Notes];
266
267 pub(crate) fn as_str(self) -> &'static str {
268 match self { Self::Memory => "memory", Self::Graph => "graph", Self::Notes => "notes" }
269 }
270
271 pub(crate) fn parse(value: &str) -> Result<Self> {
272 Self::ALL.into_iter().find(|target| target.as_str() == value)
273 .ok_or_else(|| Error::Validation(format!("vectorize target must be memory, graph or notes, got {value}")))
274 }
275
276 pub(crate) fn kinds(self) -> &'static [RecordKind] {
278 match self {
279 Self::Memory => &[RecordKind::Memory],
280 Self::Graph => &[RecordKind::Entity, RecordKind::Relation, RecordKind::Event],
281 Self::Notes => &[RecordKind::Chunk],
282 }
283 }
284
285 fn default_enabled(self) -> bool { !matches!(self, Self::Notes) }
287}
288
289fn vectorize_key(namespace: &str) -> String { format!("vectorize:{}", text::normalized_tag(namespace)) }
291
292fn target_vectorize_key(namespace: &str, target: VectorizeTarget) -> String {
294 format!("{}:{}", vectorize_key(namespace), target.as_str())
295}
296
297pub(crate) fn namespace_vectorization(conn: &Connection, namespace: &str) -> Result<bool> {
299 let value: Option<i64> = conn.query_row("SELECT value FROM meta WHERE key=?1", [vectorize_key(namespace)], |r| r.get(0)).optional()?;
300 Ok(value != Some(0))
301}
302
303pub(crate) fn target_vectorization(conn: &Connection, namespace: &str, target: VectorizeTarget) -> Result<bool> {
305 let value: Option<i64> = conn.query_row("SELECT value FROM meta WHERE key=?1", [target_vectorize_key(namespace, target)], |r| r.get(0)).optional()?;
306 Ok(value.map_or_else(|| target.default_enabled(), |value| value != 0))
307}
308
309pub(crate) fn enabled_kinds(conn: &Connection, namespace: &str) -> Result<Vec<RecordKind>> {
312 if !namespace_vectorization(conn, namespace)? { return Ok(Vec::new()); }
313 let mut kinds = Vec::new();
314 for target in VectorizeTarget::ALL {
315 if target_vectorization(conn, namespace, target)? { kinds.extend_from_slice(target.kinds()); }
316 }
317 Ok(kinds)
318}
319
320pub(crate) fn ready_kinds(conn: &Connection, namespace: &str, space_id: &str) -> Result<Vec<RecordKind>> {
323 if !namespace_vectorization(conn, namespace)? { return Ok(Vec::new()); }
324 let mut kinds = Vec::new();
325 for target in VectorizeTarget::ALL {
326 if target_vectorization(conn, namespace, target)? && vector_ready(conn, namespace, space_id, target)? {
327 kinds.extend_from_slice(target.kinds());
328 }
329 }
330 Ok(kinds)
331}
332
333fn enabled_kinds_sql() -> String {
336 VectorizeTarget::ALL.iter().map(|target| target_enabled_sql(*target)).collect::<Vec<_>>().join(" OR ")
337}
338
339fn target_enabled_sql(target: VectorizeTarget) -> String {
341 let codes = target.kinds().iter().map(|kind| kind.code().to_string()).collect::<Vec<_>>().join(",");
342 format!("(r.kind IN ({codes}) AND COALESCE((SELECT value FROM meta WHERE key='vectorize:'||n.text||':{}'),{}) = 1)",
343 target.as_str(), i64::from(target.default_enabled()))
344}
345
346pub(crate) fn pending_candidates(conn: &Connection, index: &crate::index::TextIndex, space_id: &str, namespace: Option<&str>,
354 target: Option<VectorizeTarget>, limit: usize, after: Option<i64>, ids: Option<&[i64]>) -> Result<Vec<EmbeddingInput>> {
355 let mut sql = String::from("SELECT r.id,r.kind,r.payload_json,r.fingerprint FROM records r JOIN strings n ON n.id=r.namespace_id WHERE 1=1");
356 let mut values: Vec<SqlValue> = Vec::new();
357 if let Some(namespace) = namespace {
358 sql.push_str(" AND n.text=?");
359 values.push(SqlValue::Text(text::normalized_tag(namespace)));
360 }
361 sql.push_str(&format!(" AND ({})", match target { Some(target) => target_enabled_sql(target), None => enabled_kinds_sql() }));
362 sql.push_str(" AND COALESCE((SELECT value FROM meta WHERE key='vectorize:'||n.text),1)=1");
363 sql.push_str(" AND NOT EXISTS(SELECT 1 FROM embeddings e WHERE e.space_id=? AND e.record_id=r.id AND e.fingerprint=r.fingerprint)");
364 values.push(SqlValue::Text(space_id.into()));
365 if let Some(ids) = ids {
366 if ids.is_empty() { return Ok(Vec::new()); }
367 sql.push_str(&format!(" AND r.id IN ({})", vec!["?"; ids.len()].join(",")));
368 values.extend(ids.iter().map(|id| SqlValue::Integer(*id)));
369 }
370 if let Some(cursor) = after {
371 sql.push_str(" AND r.id>?");
372 values.push(SqlValue::Integer(cursor));
373 }
374 sql.push_str(" ORDER BY r.id LIMIT ?");
375 values.push(SqlValue::Integer(limit as i64));
376 let mut stmt = conn.prepare(&sql)?;
377 let mut items = Vec::new();
378 let mut candidates: Vec<(i64, i64, String, String)> = Vec::new();
379 for row in stmt.query_map(params_from_iter(values), |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?)))? {
380 candidates.push(row?);
381 }
382 let chunk_ids: Vec<i64> = candidates.iter().filter(|(_, kind, _, _)| *kind == RecordKind::Chunk.code()).map(|(id, _, _, _)| *id).collect();
384 let bodies = if chunk_ids.is_empty() { BTreeMap::new() } else { index.bodies(&chunk_ids)? };
385 for (id, kind_code, payload_json, fingerprint) in candidates {
386 let kind = RecordKind::from_code(kind_code).ok_or_else(|| Error::Validation("invalid stored record kind".into()))?;
387 let payload: Option<serde_json::Value> = serde_json::from_str(&payload_json).ok();
388 let body = match kind {
389 RecordKind::Chunk => bodies.get(&id).cloned().unwrap_or_default(),
390 _ => payload.as_ref().map(|payload| storage::record_text(kind, payload)).unwrap_or_default(),
391 };
392 let name = match (kind, &payload) {
394 (RecordKind::Entity, Some(payload)) => payload.get("name").and_then(serde_json::Value::as_str).unwrap_or("").to_string(),
395 _ => String::new(),
396 };
397 let text = match (kind, record_tags(conn, id)?) {
399 (RecordKind::Memory, tags) if !tags.is_empty() => format!("{body}\n{}", tags.join(" ")),
400 (RecordKind::Entity, _) if !name.is_empty() => format!("{name}\n{body}"),
401 _ => body,
402 };
403 items.push(EmbeddingInput { key: RecordKey { id }, text, fingerprint });
404 }
405 Ok(items)
406}
407
408fn embeddable(input: &EmbeddingInput) -> bool { !input.text.trim().is_empty() }
411
412const GAP_PROBE: usize = 256;
414
415fn has_gap(conn: &Connection, index: &crate::index::TextIndex, space_id: &str, namespace: &str, target: VectorizeTarget) -> Result<bool> {
418 let mut cursor: Option<i64> = None;
419 loop {
420 let candidates = pending_candidates(conn, index, space_id, Some(namespace), Some(target), GAP_PROBE, cursor, None)?;
421 let Some(last) = candidates.last() else { return Ok(false) };
422 if candidates.iter().any(embeddable) { return Ok(true); }
423 cursor = Some(last.key.id);
424 }
425}
426
427fn vector_ready_key(namespace: &str, space_id: &str, target: VectorizeTarget) -> String {
432 format!("vector_ready:{}:{}:{}", text::normalized_tag(namespace), space_id, target.as_str())
433}
434
435pub(crate) fn vector_ready(conn: &Connection, namespace: &str, space_id: &str, target: VectorizeTarget) -> Result<bool> {
437 let value: Option<i64> = conn.query_row("SELECT value FROM meta WHERE key=?1", [vector_ready_key(namespace, space_id, target)], |r| r.get(0)).optional()?;
438 Ok(value == Some(1))
439}
440
441fn set_vector_ready(conn: &Connection, namespace: &str, space_id: &str, target: VectorizeTarget, ready: bool) -> Result<()> {
443 if ready {
444 conn.execute("INSERT INTO meta(key,value) VALUES (?1,1) ON CONFLICT(key) DO UPDATE SET value=1", [vector_ready_key(namespace, space_id, target)])?;
445 } else {
446 conn.execute("DELETE FROM meta WHERE key=?1", [vector_ready_key(namespace, space_id, target)])?;
447 }
448 Ok(())
449}
450
451pub(crate) fn clear_vector_ready(conn: &Connection, namespace: &str) -> Result<()> {
454 let prefix = format!("vector_ready:{}:", text::normalized_tag(namespace));
455 conn.execute("DELETE FROM meta WHERE substr(key,1,?1)=?2", params![prefix.chars().count() as i64, prefix])?;
456 Ok(())
457}
458
459fn record_tags(conn: &Connection, id: i64) -> Result<Vec<String>> {
461 let mut stmt = conn.prepare("SELECT t.text FROM record_tags rt JOIN strings t ON t.id=rt.tag_id WHERE rt.record_id=?1 ORDER BY t.text")?;
462 let mut tags = Vec::new();
463 for row in stmt.query_map([id], |r| r.get::<_, String>(0))? { tags.push(row?); }
464 Ok(tags)
465}
466
467enum EmbedOutcome { Vectors(Vec<Vec<f32>>), Shrunk, Failed(String) }
469
470fn embed_with_retry(entry: &mut EmbedderEntry, texts: &[String]) -> EmbedOutcome {
473 let mut attempts = 0u32;
474 loop {
475 match entry.embed(texts) {
476 Ok(values) => return EmbedOutcome::Vectors(values),
477 Err(error) if error.kind == EmbedErrorKind::TooLarge => {
478 if entry.effective_batch <= 1 { return EmbedOutcome::Failed(format!("batch size 1 was still rejected: {}", error.message)); }
479 entry.effective_batch /= 2;
480 return EmbedOutcome::Shrunk;
481 }
482 Err(error) if error.kind == EmbedErrorKind::RateLimited && attempts < RATE_LIMIT_ATTEMPTS => {
483 attempts += 1;
484 std::thread::sleep(std::time::Duration::from_millis(RATE_LIMIT_BACKOFF_MS * u64::from(attempts)));
485 }
486 Err(error) => return EmbedOutcome::Failed(error.message),
487 }
488 }
489}
490
491#[derive(Debug, Clone, Default, Serialize, Deserialize)]
493pub struct SyncReport { pub scanned: usize, pub written: usize, pub batches: usize, pub interrupted: Option<String> }
494
495impl EmbeddingStore {
496 pub fn register_space(&self, space: EmbeddingSpace) -> Result<WriteReceipt<EmbeddingSpace>> {
497 storage::validate_identity("space id", &space.id)?;
498 storage::validate_identity("model", &space.model)?;
499 if !(1..=65_536).contains(&space.dimension) || space.text_version != 1 { return Err(Error::Validation("dimension must be 1..65536 and text_version must be 1".into())); }
500 if space.encoding != "f32" && space.encoding != "sq8" { return Err(Error::Validation("encoding must be \"f32\" or \"sq8\"".into())); }
501 self.0.mutate_meta(|tx| {
502 match get_space(tx, &space.id) {
503 Ok(old) if old == space => return Ok(old),
504 Ok(_) => return Err(Error::Conflict("embedding space is immutable; register a new ID for a new model or dimension".into())),
505 Err(Error::NotFound(_)) => (),
506 Err(err) => return Err(err),
507 }
508 tx.execute("INSERT INTO embedding_spaces(id,model,dimension,text_version,encoding) VALUES (?1,?2,?3,?4,?5)", params![space.id, space.model, space.dimension as i64, space.text_version, space.encoding])?;
509 Ok(space)
510 })
511 }
512 pub fn spaces(&self) -> Result<Vec<EmbeddingSpace>> {
513 let state = self.0.read()?;
514 let mut stmt = state.conn().prepare("SELECT id,model,dimension,text_version,encoding FROM embedding_spaces ORDER BY id")?;
515 let rows = stmt.query_map([], |r| Ok(EmbeddingSpace { id: r.get(0)?, model: r.get(1)?, dimension: r.get::<_, u32>(2)? as usize, text_version: r.get(3)?, encoding: r.get(4)? }))?;
516 Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
517 }
518
519 pub fn register_embedder<F: Embedder + 'static>(&self, space_id: &str, embedder: F) -> Result<()> {
521 self.register_embedder_with(space_id, embedder, EmbedderOptions::default())
522 }
523
524 pub fn register_embedder_with<F: Embedder + 'static>(&self, space_id: &str, embedder: F, options: EmbedderOptions) -> Result<()> {
528 storage::validate_identity("space id", space_id)?;
529 if !(1..=10_000).contains(&options.max_batch) { return Err(Error::Validation("max_batch must be between 1 and 10000".into())); }
530 if options.max_tokens_per_text == Some(0) { return Err(Error::Validation("max_tokens_per_text must be positive".into())); }
531 let space = { let state = self.0.read()?; get_space(state.conn(), space_id)? };
532 let mut entry = EmbedderEntry { options, effective_batch: options.max_batch, embedder: Box::new(embedder) };
533 let samples: Vec<String> = SAMPLE_TEXTS.iter().take(3.min(entry.effective_batch)).map(|sample| (*sample).to_string()).collect();
534 let produced = entry.embed(&samples)
536 .map_err(|error| Error::Validation(format!("embedder failed during registration ({}): {}", error.kind.code(), error.message)))?;
537 validate_vectors(&produced, samples.len(), &space)?;
538 self.0.engine.embedders.register(space_id.to_string(), entry);
539 if let Some(vectorizer) = self.0.engine.vectorizer.get() { vectorizer.notify_work(); }
541 Ok(())
542 }
543
544 pub fn embedder_space(&self, space_id: &str) -> Result<Option<EmbeddingSpace>> {
546 let state = self.0.read()?;
547 match get_space(state.conn(), space_id) { Ok(space) => Ok(Some(space)), Err(Error::NotFound(_)) => Ok(None), Err(error) => Err(error) }
548 }
549
550 pub fn unregister_embedder(&self, space_id: &str) -> Result<bool> { Ok(self.0.engine.embedders.remove(space_id)) }
551
552 pub fn namespace_vectorization(&self, namespace: &str) -> Result<bool> {
554 storage::validate_identity("namespace", namespace)?;
555 let state = self.0.read()?;
556 namespace_vectorization(state.conn(), namespace)
557 }
558
559 pub fn set_namespace_vectorization(&self, namespace: &str, enabled: bool) -> Result<WriteReceipt<bool>> {
560 storage::validate_identity("namespace", namespace)?;
561 let receipt = self.0.mutate_meta(|tx| {
562 tx.execute("INSERT INTO meta(key,value) VALUES (?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
563 params![vectorize_key(namespace), i64::from(enabled)])?;
564 clear_vector_ready(tx, namespace)?;
566 Ok(enabled)
567 })?;
568 if let Some(vectorizer) = self.0.engine.vectorizer.get() { vectorizer.notify_work(); }
570 Ok(receipt)
571 }
572
573 pub fn vectorization(&self, namespace: &str, target: &str) -> Result<bool> {
576 storage::validate_identity("namespace", namespace)?;
577 let target = VectorizeTarget::parse(target)?;
578 let state = self.0.read()?;
579 target_vectorization(state.conn(), namespace, target)
580 }
581
582 pub fn set_vectorization(&self, namespace: &str, target: &str, enabled: bool) -> Result<WriteReceipt<bool>> {
584 storage::validate_identity("namespace", namespace)?;
585 let target = VectorizeTarget::parse(target)?;
586 let receipt = self.0.mutate_meta(|tx| {
587 tx.execute("INSERT INTO meta(key,value) VALUES (?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
588 params![target_vectorize_key(namespace, target), i64::from(enabled)])?;
589 clear_vector_ready(tx, namespace)?;
591 Ok(enabled)
592 })?;
593 if let Some(vectorizer) = self.0.engine.vectorizer.get() { vectorizer.notify_work(); }
595 Ok(receipt)
596 }
597
598 pub fn vector_ready(&self, namespace: &str, space_id: &str, target: &str) -> Result<bool> {
601 storage::validate_identity("namespace", namespace)?;
602 storage::validate_identity("space id", space_id)?;
603 let target = VectorizeTarget::parse(target)?;
604 let state = self.0.read()?;
605 vector_ready(state.conn(), namespace, space_id, target)
606 }
607
608 pub fn sync(&self, space_id: &str, batch: usize) -> Result<WriteReceipt<SyncReport>> {
616 storage::validate_limit(batch)?;
617 if self.0.engine.embedders.get(space_id).is_none() {
618 return Err(Error::Validation(format!("no embedder registered for space {space_id}")));
619 }
620 let report = self.fill(space_id, batch, true)?;
621 let state = self.0.read()?;
622 Ok(WriteReceipt { value: report, revision: storage::current_revision(state.conn())? })
623 }
624
625 fn fill(&self, space_id: &str, batch: usize, blocking: bool) -> Result<SyncReport> {
628 let _filling = if blocking { None } else { self.0.engine.vectorizer.get().map(|vectorizer| vectorizer.begin_fill()) };
631 let Some(entry) = self.0.engine.embedders.get(space_id) else { return Ok(SyncReport::default()) };
632 self.0.catch_up_index()?;
634 let report = self.drain(space_id, &entry, batch, blocking)?;
635 if report.interrupted.is_some() { self.0.note_degrade(Degrade::EmbedFailed); }
636 self.verify_and_mark(space_id)?;
637 Ok(report)
638 }
639
640 fn verify_and_mark(&self, space_id: &str) -> Result<()> {
647 for _ in 0..VERIFY_ATTEMPTS {
648 let (revision, marks) = {
649 let state = self.0.read()?;
650 let index = self.0.index()?;
651 let conn = state.conn();
652 let pending: i64 = conn.query_row("SELECT COUNT(*) FROM index_updates", [], |r| r.get(0))?;
654 if pending > 0 { return Ok(()); }
655 let revision = storage::current_revision(conn)?;
656 let mut marks = Vec::new();
657 for namespace in storage::record_namespaces(conn)? {
658 for target in VectorizeTarget::ALL {
659 let enabled = target_vectorization(conn, &namespace, target)?;
661 let ready = enabled && !has_gap(conn, &index, space_id, &namespace, target)?;
662 marks.push((namespace.clone(), target, ready));
663 }
664 }
665 (revision, marks)
666 };
667 let settled = { let state = self.0.read()?; storage::current_revision(state.conn())? == revision };
669 if !settled { continue; }
670 self.0.mutate_meta(|tx| {
671 let pending: i64 = tx.query_row("SELECT COUNT(*) FROM index_updates", [], |r| r.get(0))?;
673 if pending > 0 { return Ok(()); }
674 for (namespace, target, ready) in &marks { set_vector_ready(tx, namespace, space_id, *target, *ready)?; }
675 Ok(())
676 })?;
677 return Ok(());
678 }
679 Ok(())
680 }
681
682 fn drain(&self, space_id: &str, entry: &Arc<Mutex<EmbedderEntry>>, batch: usize, blocking: bool) -> Result<SyncReport> {
684 let mut report = SyncReport::default();
685 let acquired = if blocking { Some(entry.lock()) } else { entry.try_lock() };
686 let Some(mut guard) = acquired else { return Ok(report) };
688 let mut cursor: Option<i64> = None;
689 loop {
690 let limit = batch.min(guard.effective_batch).max(1);
691 let candidates = {
692 let state = self.0.read()?;
693 let index = self.0.index()?;
694 pending_candidates(state.conn(), &index, space_id, None, None, limit, cursor, None)?
695 };
696 let Some(last) = candidates.last().map(|input| input.key.id) else { break };
699 let pending: Vec<EmbeddingInput> = candidates.into_iter().filter(embeddable).collect();
700 if pending.is_empty() { cursor = Some(last); continue; }
701 report.scanned += pending.len();
702 let texts: Vec<String> = pending.iter().map(|input| input.text.clone()).collect();
703 let values = match embed_with_retry(&mut guard, &texts) {
704 EmbedOutcome::Shrunk => continue,
706 EmbedOutcome::Failed(message) => { report.interrupted = Some(message); break; }
707 EmbedOutcome::Vectors(values) => values,
708 };
709 if values.len() != pending.len() {
710 report.interrupted = Some(format!("embedder returned {} vectors for {} inputs", values.len(), pending.len()));
711 break;
712 }
713 let writes: Vec<EmbeddingWrite> = pending.iter().zip(values).map(|(input, vector)|
714 EmbeddingWrite { key: input.key, fingerprint: input.fingerprint.clone(), values: vector }).collect();
715 match self.put(space_id, &writes) {
716 Ok(receipt) => { report.written += receipt.value; report.batches += 1; }
717 Err(Error::StaleRevision(_)) => {}
719 Err(error) => return Err(error),
720 }
721 cursor = Some(last);
722 }
723 Ok(report)
724 }
725
726 pub(crate) fn put(&self, space_id: &str, writes: &[EmbeddingWrite]) -> Result<WriteReceipt<usize>> {
728 self.0.mutate(|tx| {
729 let space = get_space(tx, space_id)?;
730 for write in writes {
731 let actual: Option<String> = tx.query_row("SELECT fingerprint FROM records WHERE id=?1", [write.key.id], |r| r.get(0)).optional()?;
732 let actual = actual.ok_or_else(|| Error::NotFound(write.key.id.to_string()))?;
733 if actual != write.fingerprint { return Err(Error::StaleRevision(write.key.id.to_string())); }
734 let normalized = normalize(&write.values, space.dimension)?;
735 let bytes = encode_values(&normalized, &space.encoding)?;
736 tx.execute("INSERT INTO embeddings(space_id,record_id,fingerprint,vector) VALUES (?1,?2,?3,?4)
737 ON CONFLICT(space_id,record_id) DO UPDATE SET fingerprint=excluded.fingerprint,vector=excluded.vector",
738 params![space_id, write.key.id, write.fingerprint, bytes])?;
739 }
740 for write in writes { storage::touch_record_namespace(tx, write.key.id)?; }
742 Ok(writes.len())
743 })
744 }
745
746 pub fn delete_space(&self, id: &str) -> Result<WriteReceipt<bool>> {
747 self.0.mutate_meta(|tx| Ok(tx.execute("DELETE FROM embedding_spaces WHERE id=?1", [id])? > 0))
748 }
749}
750
751fn validate_vectors(produced: &[Vec<f32>], expected: usize, space: &EmbeddingSpace) -> Result<()> {
753 if produced.len() != expected {
754 return Err(Error::InvalidVector(format!("embedder returned {} vectors for {expected} inputs", produced.len())));
755 }
756 for values in produced {
757 normalize(values, space.dimension)
758 .map_err(|error| Error::InvalidVector(format!("embedder output does not satisfy space {}: {error}", space.id)))?;
759 }
760 Ok(())
761}
762
763const SWEEP_BATCH: usize = 32;
767
768const VERIFY_ATTEMPTS: usize = 3;
770
771pub(crate) struct Vectorizer {
778 stopping: Mutex<bool>,
780 signal: Condvar,
782 pending: AtomicBool,
785 filling: AtomicBool,
788 handle: Mutex<Option<JoinHandle<()>>>,
789}
790
791pub(crate) struct FillGuard(Arc<Vectorizer>);
793
794impl Drop for FillGuard {
795 fn drop(&mut self) { self.0.filling.store(false, AtomicOrdering::SeqCst); }
796}
797
798impl Vectorizer {
799 pub(crate) fn start(engine: &Arc<crate::storage::Engine>) -> Result<Arc<Self>> {
802 let vectorizer = Arc::new(Self { stopping: Mutex::new(false), signal: Condvar::new(),
803 pending: AtomicBool::new(true), filling: AtomicBool::new(false), handle: Mutex::new(None) });
804 let worker = Arc::clone(&vectorizer);
805 let engine = Arc::downgrade(engine);
806 let handle = std::thread::Builder::new().name("p-memory-vectorize".into())
807 .spawn(move || work_loop(&engine, &worker))?;
808 *vectorizer.handle.lock() = Some(handle);
809 Ok(vectorizer)
810 }
811
812 fn begin_fill(self: &Arc<Self>) -> FillGuard {
814 self.filling.store(true, AtomicOrdering::SeqCst);
815 FillGuard(Arc::clone(self))
816 }
817
818 pub(crate) fn is_filling(&self) -> bool { self.filling.load(AtomicOrdering::SeqCst) }
820
821 pub(crate) fn notify_work(&self) {
824 let _guard = self.stopping.lock();
825 self.pending.store(true, AtomicOrdering::SeqCst);
826 self.signal.notify_all();
827 }
828
829 pub(crate) fn stop(&self) {
831 {
832 let mut stopping = self.stopping.lock();
833 *stopping = true;
834 self.signal.notify_all();
835 }
836 if let Some(handle) = self.handle.lock().take() { let _ = handle.join(); }
837 }
838}
839
840fn work_loop(engine: &Weak<crate::storage::Engine>, vectorizer: &Vectorizer) {
844 loop {
845 {
846 let mut stopping = vectorizer.stopping.lock();
847 while !*stopping && !vectorizer.pending.load(AtomicOrdering::SeqCst) {
849 vectorizer.signal.wait(&mut stopping);
850 }
851 if *stopping { return; }
852 }
853 vectorizer.pending.store(false, AtomicOrdering::SeqCst);
855 let Some(engine) = engine.upgrade() else { return };
856 let kb = KnowledgeBase { engine };
857 loop {
858 let mut progressed = false;
859 for space_id in kb.engine.embedders.space_ids() {
860 if let Ok(report) = EmbeddingStore(kb.clone()).fill(&space_id, SWEEP_BATCH, false) {
862 if report.written > 0 { progressed = true; }
863 }
864 }
865 if !progressed { break; }
866 }
867 }
868}
869
870struct VectorRow { key: RecordKey, kind: RecordKind, tags: Vec<String>, note: i64 }
872enum PartitionData {
875 F32(Vec<f32>),
876 Sq8 { codes: Vec<i8>, scales: Vec<f32> },
877}
878pub(crate) struct Partition { dimension: usize, rows: Vec<VectorRow>, data: PartitionData }
880
881struct Candidate { score: f64, key: RecordKey }
883impl PartialEq for Candidate { fn eq(&self, other: &Self) -> bool { self.score == other.score && self.key == other.key } }
884impl Eq for Candidate {}
885impl PartialOrd for Candidate { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } }
886impl Ord for Candidate {
887 fn cmp(&self, other: &Self) -> Ordering { other.score.total_cmp(&self.score).then_with(|| self.key.cmp(&other.key)) }
888}
889
890impl Partition {
891 pub fn load(conn: &Connection, space: &EmbeddingSpace, namespace: &str, scope: &str) -> Result<Option<Self>> {
894 let namespace = text::normalized_tag(namespace);
895 let scope = text::normalized_tag(scope);
896 let mut stmt = conn.prepare("SELECT r.id,r.kind,e.vector,
901 (SELECT json_group_array(t.text) FROM record_tags rt JOIN strings t ON t.id=rt.tag_id WHERE rt.record_id=r.id),
902 COALESCE((SELECT c.note_id FROM chunks c WHERE c.record_id=r.id),0)
903 FROM embeddings e JOIN records r ON r.id=e.record_id AND r.fingerprint=e.fingerprint
904 WHERE e.space_id=?1 AND r.namespace_id=(SELECT id FROM strings WHERE text=?2)
905 AND r.scope_id=(SELECT id FROM strings WHERE text=?3)")?;
906 let sq8 = space.encoding == "sq8";
907 let mut partition = Self {
908 dimension: space.dimension,
909 rows: vec![],
910 data: if sq8 { PartitionData::Sq8 { codes: vec![], scales: vec![] } } else { PartitionData::F32(vec![]) },
911 };
912 let mut rows = stmt.query(params![space.id, namespace, scope])?;
913 while let Some(row) = rows.next()? {
914 let key = RecordKey { id: row.get(0)? };
915 let kind = RecordKind::from_code(row.get::<_, i64>(1)?).ok_or_else(|| Error::InvalidVector("invalid stored record kind".into()))?;
916 let bytes: Vec<u8> = row.get(2)?;
917 let tags: Vec<String> = serde_json::from_str(&row.get::<_, String>(3)?)?;
918 let note: i64 = row.get(4)?;
919 match &mut partition.data {
920 PartitionData::F32(values) => {
921 let decoded = decode_values(&bytes, space.dimension, "f32")?;
922 if decoded.iter().any(|v| !v.is_finite()) { return Err(Error::InvalidVector("stored vector contains nonfinite values".into())); }
923 values.extend(decoded);
924 }
925 PartitionData::Sq8 { codes, scales } => {
926 let (scale, decoded) = decode_sq8(&bytes, space.dimension)?;
927 if !scale.is_finite() { return Err(Error::InvalidVector("stored vector contains nonfinite values".into())); }
928 scales.push(scale);
929 codes.extend(decoded);
930 }
931 }
932 partition.rows.push(VectorRow { key, kind, tags, note });
933 }
934 Ok(if partition.rows.is_empty() { None } else { Some(partition) })
935 }
936
937 fn matches(&self, row: &VectorRow, kinds: &[RecordKind], tags: &[String], note_ids: &[i64], allowed: Option<&HashSet<i64>>) -> bool {
940 if allowed.is_some_and(|set| !set.contains(&row.key.id)) { return false; }
941 if !note_ids.is_empty() && !note_ids.contains(&row.note) { return false; }
942 (kinds.is_empty() || kinds.contains(&row.kind)) && tags.iter().all(|t| row.tags.contains(t))
943 }
944
945 fn retain(heap: &mut BinaryHeap<Candidate>, key: RecordKey, scored: f64, limit: usize) {
947 let score = scored.clamp(-1.0, 1.0);
948 if heap.len() < limit { heap.push(Candidate { score, key }); }
949 else if let Some(worst) = heap.peek() {
950 if score > worst.score || (score == worst.score && key < worst.key) {
951 heap.pop(); heap.push(Candidate { score, key });
952 }
953 }
954 }
955
956 pub fn search(&self, query: &[f32], kinds: &[RecordKind], tags: &[String], note_ids: &[i64], limit: usize, allowed: Option<&HashSet<i64>>) -> Result<Vec<(RecordKey, f64)>> {
959 let query = normalize(query, self.dimension)?;
960 let mut heap = BinaryHeap::<Candidate>::new();
961 match &self.data {
962 PartitionData::F32(values) => {
963 for (i, row) in self.rows.iter().enumerate() {
964 if !self.matches(row, kinds, tags, note_ids, allowed) { continue; }
965 let offset = i * self.dimension;
966 Self::retain(&mut heap, row.key, f64::from(dot(&query, &values[offset..offset + self.dimension])), limit);
967 }
968 }
969 PartitionData::Sq8 { codes, scales } => {
970 let (query_codes, query_scale) = encode_query_sq8(&query);
972 for (i, row) in self.rows.iter().enumerate() {
973 if !self.matches(row, kinds, tags, note_ids, allowed) { continue; }
974 let offset = i * self.dimension;
975 let raw = query_scale * scales[i] * dot_codes(&query_codes, &codes[offset..offset + self.dimension]) as f32;
976 Self::retain(&mut heap, row.key, f64::from(raw), limit);
977 }
978 }
979 }
980 let mut result: Vec<_> = heap.into_iter().map(|c| (c.key, c.score)).collect();
981 result.sort_by(|a,b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
982 Ok(result)
983 }
984}
985
986#[cfg(test)]
987mod tests {
988 use super::*;
989 use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
990
991 #[test]
993 fn integer_kernel_matches_scalar() {
994 for dimension in [1usize, 15, 16, 17, 250, 1024] {
995 let left: Vec<i8> = (0..dimension).map(|i| ((i * 37 % 255) as i32 - 127) as i8).collect();
996 let right: Vec<i8> = (0..dimension).map(|i| ((i * 91 % 255) as i32 - 127) as i8).collect();
997 assert_eq!(dot_codes(&left, &right), dot_codes_scalar(&left, &right), "dimension {dimension}");
998 }
999 }
1000
1001 #[test]
1005 fn tied_scores_break_by_key_whatever_the_row_order() {
1006 let dimension = 4usize;
1007 let query = vec![1.0f32, 0.0, 0.0, 0.0];
1008 let build = |order: &[i64]| Partition {
1010 dimension,
1011 rows: order.iter().map(|id| VectorRow { key: RecordKey { id: *id }, kind: RecordKind::Memory, tags: vec![], note: 0 }).collect(),
1012 data: PartitionData::F32(order.iter().flat_map(|_| [1.0f32, 0.0, 0.0, 0.0]).collect()),
1013 };
1014 let top_two = |partition: &Partition| -> Vec<i64> {
1015 partition.search(&query, &[], &[], &[], 2, None).unwrap().into_iter().map(|(key, _)| key.id).collect()
1016 };
1017 assert_eq!(top_two(&build(&[1, 2, 3, 4])), vec![1, 2], "并列时取 key 最小的两条");
1018 assert_eq!(top_two(&build(&[4, 3, 2, 1])), vec![1, 2], "换个行序,结果必须一样");
1019 }
1020
1021 #[test]
1023 fn quantized_query_tracks_decoded_f32_kernel() {
1024 let dimension = 256usize;
1025 let stored_raw: Vec<f32> = (0..dimension).map(|i| (i as f32 * 0.37).sin() + 0.25).collect();
1026 let query_raw: Vec<f32> = (0..dimension).map(|i| (i as f32 * 0.11).cos() - 0.1).collect();
1027 let stored = normalize(&stored_raw, dimension).unwrap();
1028 let query = normalize(&query_raw, dimension).unwrap();
1029 let encoded = encode_values(&stored, "sq8").unwrap();
1030 let (scale, codes) = decode_sq8(&encoded, dimension).unwrap();
1031 let decoded = decode_values(&encoded, dimension, "sq8").unwrap();
1032 let reference = dot(&query, &decoded);
1033 let (query_codes, query_scale) = encode_query_sq8(&query);
1034 let actual = query_scale * scale * dot_codes(&query_codes, &codes) as f32;
1035 assert!((reference - actual).abs() < 1e-3, "reference {reference} vs actual {actual}");
1037 }
1038
1039 #[test]
1041 fn oversized_batches_shrink_and_persist() {
1042 let lengths = std::sync::Arc::new(Mutex::new(Vec::<usize>::new()));
1043 let observed = lengths.clone();
1044 let mut entry = EmbedderEntry {
1045 options: EmbedderOptions { max_batch: 8, max_tokens_per_text: None },
1046 effective_batch: 8,
1047 embedder: Box::new(move |texts: &[String]| {
1048 observed.lock().push(texts.len());
1049 if texts.len() > 4 { return Err(EmbedCallbackError::too_large("too many texts")); }
1050 Ok(texts.iter().map(|_| vec![1.0f32, 0.0]).collect())
1051 }),
1052 };
1053 let texts: Vec<String> = (0..8).map(|i| format!("文本 {i}")).collect();
1054 assert!(matches!(embed_with_retry(&mut entry, &texts), EmbedOutcome::Shrunk));
1055 assert_eq!(entry.effective_batch, 4, "减半值应当写在 entry 上并持久");
1056 assert!(matches!(embed_with_retry(&mut entry, &texts[..4]), EmbedOutcome::Vectors(_)));
1057 assert_eq!(*lengths.lock(), vec![8, 4]);
1058 }
1059
1060 #[test]
1062 fn callback_errors_are_classified() {
1063 let mut broken = EmbedderEntry {
1064 options: EmbedderOptions::default(), effective_batch: 1,
1065 embedder: Box::new(|_: &[String]| Err(EmbedCallbackError::too_large("still too large"))),
1066 };
1067 assert!(matches!(embed_with_retry(&mut broken, &["a".to_string()]), EmbedOutcome::Failed(_)));
1068 assert_eq!(broken.effective_batch, 1);
1069
1070 let attempts = std::sync::Arc::new(AtomicUsize::new(0));
1071 let counter = attempts.clone();
1072 let mut throttled = EmbedderEntry {
1073 options: EmbedderOptions::default(), effective_batch: 4,
1074 embedder: Box::new(move |_: &[String]| {
1075 let attempt = counter.fetch_add(1, AtomicOrdering::SeqCst);
1076 if attempt < 2 { Err(EmbedCallbackError::rate_limited("slow down")) } else { Ok(vec![vec![1.0f32, 0.0]]) }
1077 }),
1078 };
1079 assert!(matches!(embed_with_retry(&mut throttled, &["a".to_string()]), EmbedOutcome::Vectors(_)));
1080 assert_eq!(attempts.load(AtomicOrdering::SeqCst), 3, "限流应当退避重试后成功");
1081 assert_eq!(throttled.effective_batch, 4, "限流不触发减半");
1082 }
1083}