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 pub namespace: String, pub scope: String, pub kind: RecordKind, pub tags: Vec<String>, pub note_id: i64 }
24#[derive(Debug, Clone)]
26pub(crate) struct EmbeddingWrite { pub key: RecordKey, pub fingerprint: String, pub values: Vec<f32>,
27 pub namespace: String, pub scope: String, pub kind: RecordKind, pub tags: Vec<String>, pub note_id: i64 }
28
29#[derive(Clone)]
30pub struct EmbeddingStore(pub(crate) KnowledgeBase);
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "snake_case")]
37pub enum EmbedErrorKind {
38 TooLarge,
40 RateLimited,
42 Other,
44}
45
46impl EmbedErrorKind {
47 pub fn code(self) -> &'static str {
48 match self { Self::TooLarge => "too_large", Self::RateLimited => "rate_limited", Self::Other => "other" }
49 }
50 pub fn from_code(code: &str) -> Option<Self> {
51 match code { "too_large" => Some(Self::TooLarge), "rate_limited" => Some(Self::RateLimited), "other" => Some(Self::Other), _ => None }
52 }
53}
54
55#[derive(Debug, Clone)]
57pub struct EmbedCallbackError { pub kind: EmbedErrorKind, pub message: String }
58
59impl EmbedCallbackError {
60 pub fn new(kind: EmbedErrorKind, message: impl Into<String>) -> Self { Self { kind, message: message.into() } }
61 pub fn too_large(message: impl Into<String>) -> Self { Self::new(EmbedErrorKind::TooLarge, message) }
62 pub fn rate_limited(message: impl Into<String>) -> Self { Self::new(EmbedErrorKind::RateLimited, message) }
63 pub fn other(message: impl Into<String>) -> Self { Self::new(EmbedErrorKind::Other, message) }
64}
65
66impl std::fmt::Display for EmbedCallbackError {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}: {}", self.kind.code(), self.message) }
68}
69impl std::error::Error for EmbedCallbackError {}
70
71pub trait Embedder: Send {
73 fn embed(&mut self, texts: &[String]) -> std::result::Result<Vec<Vec<f32>>, EmbedCallbackError>;
74}
75
76impl<F> Embedder for F
77where F: FnMut(&[String]) -> std::result::Result<Vec<Vec<f32>>, EmbedCallbackError> + Send {
78 fn embed(&mut self, texts: &[String]) -> std::result::Result<Vec<Vec<f32>>, EmbedCallbackError> { self(texts) }
79}
80
81fn default_max_batch() -> usize { 32 }
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
84pub struct EmbedderOptions {
85 #[serde(default = "default_max_batch")] pub max_batch: usize,
86 #[serde(default)] pub max_tokens_per_text: Option<usize>,
88}
89impl Default for EmbedderOptions {
90 fn default() -> Self { Self { max_batch: default_max_batch(), max_tokens_per_text: None } }
91}
92
93pub(crate) struct EmbedderEntry {
94 pub options: EmbedderOptions,
95 pub effective_batch: usize,
97 pub embedder: Box<dyn Embedder>,
98}
99
100impl EmbedderEntry {
101 pub(crate) fn embed(&mut self, texts: &[String]) -> std::result::Result<Vec<Vec<f32>>, EmbedCallbackError> {
103 match self.options.max_tokens_per_text {
104 Some(budget) => {
105 let budgeted: Vec<String> = texts.iter().map(|value| text::truncate_to_tokens(value, budget)).collect();
106 self.embedder.embed(&budgeted)
107 }
108 None => self.embedder.embed(texts),
109 }
110 }
111}
112
113#[derive(Default)]
115pub(crate) struct EmbedderRegistry { entries: Mutex<HashMap<String, Arc<Mutex<EmbedderEntry>>>> }
116
117impl EmbedderRegistry {
118 pub fn new() -> Self { Self::default() }
119 pub fn space_ids(&self) -> Vec<String> {
120 let mut ids: Vec<String> = self.entries.lock().keys().cloned().collect();
121 ids.sort();
122 ids
123 }
124 pub fn get(&self, space_id: &str) -> Option<Arc<Mutex<EmbedderEntry>>> { self.entries.lock().get(space_id).cloned() }
125 pub fn register(&self, space_id: String, entry: EmbedderEntry) { self.entries.lock().insert(space_id, Arc::new(Mutex::new(entry))); }
126 pub fn remove(&self, space_id: &str) -> bool { self.entries.lock().remove(space_id).is_some() }
127}
128
129const SAMPLE_TEXTS: [&str; 3] = ["样本一 sample", "样本二 sample", "样本三 sample"];
131
132const RATE_LIMIT_ATTEMPTS: u32 = 3;
133const RATE_LIMIT_BACKOFF_MS: u64 = 20;
134
135pub(crate) fn get_space(conn: &Connection, id: &str) -> Result<EmbeddingSpace> {
136 conn.query_row("SELECT id,model,dimension,text_version,encoding FROM embedding_spaces WHERE id=?1", [id], |r|
137 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()?
138 .ok_or_else(|| Error::NotFound(format!("embedding space {id}")))
139}
140
141pub(crate) fn normalize(values: &[f32], dimension: usize) -> Result<Vec<f32>> {
142 if values.len() != dimension { return Err(Error::InvalidVector(format!("expected dimension {dimension}, received {}", values.len()))); }
143 if values.iter().any(|v| !v.is_finite()) { return Err(Error::InvalidVector("values must be finite".into())); }
144 let norm = values.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>().sqrt();
145 if norm == 0.0 || !norm.is_finite() { return Err(Error::InvalidVector("zero or invalid vector norm".into())); }
146 Ok(values.iter().map(|v| (f64::from(*v) / norm) as f32).collect())
147}
148
149#[inline]
152fn dot(a: &[f32], b: &[f32]) -> f32 {
153 let mut acc = [0f32; 8];
154 let chunks = a.len() / 8;
155 for c in 0..chunks {
156 let o = c * 8;
157 for k in 0..8 { acc[k] += a[o + k] * b[o + k]; }
158 }
159 let mut sum = acc.iter().sum::<f32>();
160 for i in chunks * 8..a.len() { sum += a[i] * b[i]; }
161 sum
162}
163
164fn encode_query_sq8(query: &[f32]) -> (Vec<i8>, f32) {
168 let max = query.iter().fold(0f32, |m, v| m.max(v.abs()));
169 let scale = if max == 0.0 { 1.0 } else { max / 127.0 };
170 let codes = query.iter().map(|v| (v / scale).round().clamp(-127.0, 127.0) as i8).collect();
171 (codes, scale)
172}
173
174#[inline]
178fn dot_codes(left: &[i8], right: &[i8]) -> i32 {
179 #[cfg(target_arch = "x86_64")]
180 {
181 if std::is_x86_feature_detected!("avx2") { return unsafe { dot_codes_avx2(left, right) }; }
183 }
184 dot_codes_scalar(left, right)
185}
186
187fn dot_codes_scalar(left: &[i8], right: &[i8]) -> i32 {
188 left.iter().zip(right).map(|(a, b)| i32::from(*a) * i32::from(*b)).sum()
189}
190
191#[cfg(target_arch = "x86_64")]
194#[target_feature(enable = "avx2")]
195unsafe fn dot_codes_avx2(left: &[i8], right: &[i8]) -> i32 {
196 use std::arch::x86_64::*;
197 let mut acc = _mm256_setzero_si256();
198 let chunks = left.len() / 16;
199 for c in 0..chunks {
200 let o = c * 16;
201 let a = _mm_loadu_si128(left.as_ptr().add(o) as *const __m128i);
202 let b = _mm_loadu_si128(right.as_ptr().add(o) as *const __m128i);
203 acc = _mm256_add_epi32(acc, _mm256_madd_epi16(_mm256_cvtepi8_epi16(a), _mm256_cvtepi8_epi16(b)));
204 }
205 let mut total = {
206 let sum = _mm_add_epi32(_mm256_castsi256_si128(acc), _mm256_extracti128_si256(acc, 1));
207 let sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0b01_00_11_10));
208 let sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0b10_11_00_01));
209 _mm_cvtsi128_si32(sum)
210 };
211 for i in chunks * 16..left.len() { total += i32::from(left[i]) * i32::from(right[i]); }
212 total
213}
214
215fn encode_values(normalized: &[f32], encoding: &str) -> Result<Vec<u8>> {
218 match encoding {
219 "f32" => Ok(normalized.iter().flat_map(|v| v.to_le_bytes()).collect()),
220 "sq8" => {
221 let max = normalized.iter().fold(0f32, |m, v| m.max(v.abs()));
222 let scale = if max == 0.0 { 1.0 } else { max / 127.0 };
223 let mut out = Vec::with_capacity(4 + normalized.len());
224 out.extend_from_slice(&scale.to_le_bytes());
225 for v in normalized {
226 out.push((v / scale).round().clamp(-127.0, 127.0) as i8 as u8);
227 }
228 Ok(out)
229 }
230 other => Err(Error::Validation(format!("unknown encoding {other}"))),
231 }
232}
233
234fn decode_values(bytes: &[u8], dimension: usize, encoding: &str) -> Result<Vec<f32>> {
236 match encoding {
237 "f32" => {
238 if bytes.len() != dimension * 4 { return Err(Error::InvalidVector("stored vector dimension mismatch".into())); }
239 Ok(bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())
240 }
241 "sq8" => {
242 let (scale, codes) = decode_sq8(bytes, dimension)?;
243 Ok(codes.into_iter().map(|c| f32::from(c) * scale).collect())
244 }
245 other => Err(Error::Validation(format!("unknown encoding {other}"))),
246 }
247}
248
249fn decode_sq8(bytes: &[u8], dimension: usize) -> Result<(f32, Vec<i8>)> {
252 if bytes.len() != dimension + 4 { return Err(Error::InvalidVector("stored vector dimension mismatch".into())); }
253 let scale = f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
254 Ok((scale, bytes[4..].iter().map(|b| *b as i8).collect()))
255}
256
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub(crate) enum VectorizeTarget { Memory, Graph, Notes }
265
266impl VectorizeTarget {
267 pub(crate) const ALL: [Self; 3] = [Self::Memory, Self::Graph, Self::Notes];
268
269 pub(crate) fn as_str(self) -> &'static str {
270 match self { Self::Memory => "memory", Self::Graph => "graph", Self::Notes => "notes" }
271 }
272
273 pub(crate) fn parse(value: &str) -> Result<Self> {
274 Self::ALL.into_iter().find(|target| target.as_str() == value)
275 .ok_or_else(|| Error::Validation(format!("vectorize target must be memory, graph or notes, got {value}")))
276 }
277
278 pub(crate) fn kinds(self) -> &'static [RecordKind] {
280 match self {
281 Self::Memory => &[RecordKind::Memory],
282 Self::Graph => &[RecordKind::Entity, RecordKind::Relation, RecordKind::Event],
283 Self::Notes => &[RecordKind::Chunk],
284 }
285 }
286
287 fn default_enabled(self) -> bool { !matches!(self, Self::Notes) }
289}
290
291fn vectorize_key(namespace: &str) -> String { format!("vectorize:{}", text::normalized_tag(namespace)) }
293
294fn target_vectorize_key(namespace: &str, target: VectorizeTarget) -> String {
296 format!("{}:{}", vectorize_key(namespace), target.as_str())
297}
298
299pub(crate) fn namespace_vectorization(conn: &Connection, namespace: &str) -> Result<bool> {
301 let value: Option<i64> = conn.query_row("SELECT value FROM meta WHERE key=?1", [vectorize_key(namespace)], |r| r.get(0)).optional()?;
302 Ok(value != Some(0))
303}
304
305pub(crate) fn target_vectorization(conn: &Connection, namespace: &str, target: VectorizeTarget) -> Result<bool> {
307 let value: Option<i64> = conn.query_row("SELECT value FROM meta WHERE key=?1", [target_vectorize_key(namespace, target)], |r| r.get(0)).optional()?;
308 Ok(value.map_or_else(|| target.default_enabled(), |value| value != 0))
309}
310
311pub(crate) fn enabled_kinds(conn: &Connection, namespace: &str) -> Result<Vec<RecordKind>> {
314 if !namespace_vectorization(conn, namespace)? { return Ok(Vec::new()); }
315 let mut kinds = Vec::new();
316 for target in VectorizeTarget::ALL {
317 if target_vectorization(conn, namespace, target)? { kinds.extend_from_slice(target.kinds()); }
318 }
319 Ok(kinds)
320}
321
322pub(crate) fn ready_kinds(conn: &Connection, namespace: &str, space_id: &str) -> Result<Vec<RecordKind>> {
325 if !namespace_vectorization(conn, namespace)? { return Ok(Vec::new()); }
326 let mut kinds = Vec::new();
327 for target in VectorizeTarget::ALL {
328 if target_vectorization(conn, namespace, target)? && vector_ready(conn, namespace, space_id, target)? {
329 kinds.extend_from_slice(target.kinds());
330 }
331 }
332 Ok(kinds)
333}
334
335fn enabled_kinds_sql() -> String {
338 VectorizeTarget::ALL.iter().map(|target| target_enabled_sql(*target)).collect::<Vec<_>>().join(" OR ")
339}
340
341fn target_enabled_sql(target: VectorizeTarget) -> String {
343 let codes = target.kinds().iter().map(|kind| kind.code().to_string()).collect::<Vec<_>>().join(",");
344 format!("(r.kind IN ({codes}) AND COALESCE((SELECT value FROM meta WHERE key='vectorize:'||n.text||':{}'),{}) = 1)",
345 target.as_str(), i64::from(target.default_enabled()))
346}
347
348pub(crate) fn pending_candidates(conn: &Connection, index: &crate::index::TextIndex, space_id: &str, namespace: Option<&str>,
356 target: Option<VectorizeTarget>, limit: usize, after: Option<i64>, ids: Option<&[i64]>) -> Result<Vec<EmbeddingInput>> {
357 let mut sql = String::from("SELECT r.id,r.kind,r.payload_json,r.fingerprint,n.text,s.text FROM records r \
358 JOIN strings n ON n.id=r.namespace_id JOIN strings s ON s.id=r.scope_id WHERE 1=1");
359 let mut values: Vec<SqlValue> = Vec::new();
360 if let Some(namespace) = namespace {
361 sql.push_str(" AND n.text=?");
362 values.push(SqlValue::Text(text::normalized_tag(namespace)));
363 }
364 sql.push_str(&format!(" AND ({})", match target { Some(target) => target_enabled_sql(target), None => enabled_kinds_sql() }));
365 sql.push_str(" AND COALESCE((SELECT value FROM meta WHERE key='vectorize:'||n.text),1)=1");
366 sql.push_str(&format!(" AND NOT EXISTS(SELECT 1 FROM vectors.embeddings e WHERE e.space_id=? AND e.record_id=r.id AND e.fingerprint=r.fingerprint)"));
367 values.push(SqlValue::Text(space_id.into()));
368 if let Some(ids) = ids {
369 if ids.is_empty() { return Ok(Vec::new()); }
370 sql.push_str(&format!(" AND r.id IN ({})", vec!["?"; ids.len()].join(",")));
371 values.extend(ids.iter().map(|id| SqlValue::Integer(*id)));
372 }
373 if let Some(cursor) = after {
374 sql.push_str(" AND r.id>?");
375 values.push(SqlValue::Integer(cursor));
376 }
377 sql.push_str(" ORDER BY r.id LIMIT ?");
378 values.push(SqlValue::Integer(limit as i64));
379 let mut stmt = conn.prepare(&sql)?;
380 let mut items = Vec::new();
381 let mut candidates: Vec<(i64, i64, String, String, String, String)> = Vec::new();
382 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)?, r.get::<_, String>(4)?, r.get::<_, String>(5)?)))? {
383 candidates.push(row?);
384 }
385 let chunk_ids: Vec<i64> = candidates.iter().filter(|(_, kind, _, _, _, _)| *kind == RecordKind::Chunk.code()).map(|(id, _, _, _, _, _)| *id).collect();
387 let bodies = if chunk_ids.is_empty() { BTreeMap::new() } else { index.bodies(&chunk_ids)? };
388 for (id, kind_code, payload_json, fingerprint, namespace, scope) in candidates {
389 let kind = RecordKind::from_code(kind_code).ok_or_else(|| Error::Validation("invalid stored record kind".into()))?;
390 let payload: Option<serde_json::Value> = serde_json::from_str(&payload_json).ok();
391 let body = match kind {
392 RecordKind::Chunk => bodies.get(&id).cloned().unwrap_or_default(),
393 _ => payload.as_ref().map(|payload| storage::record_text(kind, payload)).unwrap_or_default(),
394 };
395 let name = match (kind, &payload) {
397 (RecordKind::Entity, Some(payload)) => payload.get("name").and_then(serde_json::Value::as_str).unwrap_or("").to_string(),
398 _ => String::new(),
399 };
400 let tags = record_tags(conn, id)?;
401 let text = match (kind, &tags) {
403 (RecordKind::Memory, tags) if !tags.is_empty() => format!("{body}\n{}", tags.join(" ")),
404 (RecordKind::Entity, _) if !name.is_empty() => format!("{name}\n{body}"),
405 _ => body,
406 };
407 let note_id = if kind == RecordKind::Chunk {
408 conn.query_row("SELECT note_id FROM chunks WHERE record_id=?1", [id], |r| r.get(0)).optional()?.unwrap_or(0)
409 } else { 0 };
410 items.push(EmbeddingInput { key: RecordKey { id }, text, fingerprint, namespace, scope, kind, tags, note_id });
411 }
412 Ok(items)
413}
414
415fn embeddable(input: &EmbeddingInput) -> bool { !input.text.trim().is_empty() }
418
419const GAP_PROBE: usize = 256;
421
422fn has_gap(conn: &Connection, index: &crate::index::TextIndex, space_id: &str, namespace: &str, target: VectorizeTarget) -> Result<bool> {
425 let mut cursor: Option<i64> = None;
426 loop {
427 let candidates = pending_candidates(conn, index, space_id, Some(namespace), Some(target), GAP_PROBE, cursor, None)?;
428 let Some(last) = candidates.last() else { return Ok(false) };
429 if candidates.iter().any(embeddable) { return Ok(true); }
430 cursor = Some(last.key.id);
431 }
432}
433
434fn vector_ready_key(namespace: &str, space_id: &str, target: VectorizeTarget) -> String {
439 format!("vector_ready:{}:{}:{}", text::normalized_tag(namespace), space_id, target.as_str())
440}
441
442pub(crate) fn vector_ready(conn: &Connection, namespace: &str, space_id: &str, target: VectorizeTarget) -> Result<bool> {
445 let key = vector_ready_key(namespace, space_id, target);
446 let value: Option<String> = conn.query_row("SELECT value FROM vectors.vector_meta WHERE key=?1",
447 [&key], |r| r.get(0)).optional()?;
448 Ok(value.as_deref() == Some("1"))
449}
450
451fn set_vector_ready(conn: &Connection, namespace: &str, space_id: &str, target: VectorizeTarget, ready: bool) -> Result<()> {
453 let key = vector_ready_key(namespace, space_id, target);
454 if ready {
455 conn.execute("INSERT INTO vector_meta(key,value) VALUES (?1,'1') ON CONFLICT(key) DO UPDATE SET value='1'",
456 [&key])?;
457 } else {
458 conn.execute("DELETE FROM vector_meta WHERE key=?1", [&key])?;
459 }
460 Ok(())
461}
462
463pub(crate) fn clear_vector_ready(conn: &Connection, namespace: &str) -> Result<()> {
468 let prefix = format!("vector_ready:{}:", text::normalized_tag(namespace));
469 conn.execute("DELETE FROM vector_meta WHERE substr(key,1,?1)=?2",
470 params![prefix.chars().count() as i64, prefix])?;
471 Ok(())
472}
473
474fn record_tags(conn: &Connection, id: i64) -> Result<Vec<String>> {
476 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")?;
477 let mut tags = Vec::new();
478 for row in stmt.query_map([id], |r| r.get::<_, String>(0))? { tags.push(row?); }
479 Ok(tags)
480}
481
482enum EmbedOutcome { Vectors(Vec<Vec<f32>>), Shrunk, Failed(String) }
484
485fn embed_with_retry(entry: &mut EmbedderEntry, texts: &[String]) -> EmbedOutcome {
488 let mut attempts = 0u32;
489 loop {
490 match entry.embed(texts) {
491 Ok(values) => return EmbedOutcome::Vectors(values),
492 Err(error) if error.kind == EmbedErrorKind::TooLarge => {
493 if entry.effective_batch <= 1 { return EmbedOutcome::Failed(format!("batch size 1 was still rejected: {}", error.message)); }
494 entry.effective_batch /= 2;
495 return EmbedOutcome::Shrunk;
496 }
497 Err(error) if error.kind == EmbedErrorKind::RateLimited && attempts < RATE_LIMIT_ATTEMPTS => {
498 attempts += 1;
499 std::thread::sleep(std::time::Duration::from_millis(RATE_LIMIT_BACKOFF_MS * u64::from(attempts)));
500 }
501 Err(error) => return EmbedOutcome::Failed(error.message),
502 }
503 }
504}
505
506#[derive(Debug, Clone, Default, Serialize, Deserialize)]
508pub struct SyncReport { pub scanned: usize, pub written: usize, pub batches: usize, pub interrupted: Option<String> }
509
510impl EmbeddingStore {
511 pub fn register_space(&self, space: EmbeddingSpace) -> Result<WriteReceipt<EmbeddingSpace>> {
512 storage::validate_identity("space id", &space.id)?;
513 storage::validate_identity("model", &space.model)?;
514 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())); }
515 if space.encoding != "f32" && space.encoding != "sq8" { return Err(Error::Validation("encoding must be \"f32\" or \"sq8\"".into())); }
516 self.0.mutate_meta(|tx| {
517 match get_space(tx, &space.id) {
518 Ok(old) if old == space => return Ok(old),
519 Ok(_) => return Err(Error::Conflict("embedding space is immutable; register a new ID for a new model or dimension".into())),
520 Err(Error::NotFound(_)) => (),
521 Err(err) => return Err(err),
522 }
523 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])?;
524 Ok(space)
525 })
526 }
527 pub fn spaces(&self) -> Result<Vec<EmbeddingSpace>> {
528 let state = self.0.read()?;
529 let mut stmt = state.conn().prepare("SELECT id,model,dimension,text_version,encoding FROM embedding_spaces ORDER BY id")?;
530 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)? }))?;
531 Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
532 }
533
534 pub fn register_embedder<F: Embedder + 'static>(&self, space_id: &str, embedder: F) -> Result<()> {
536 self.register_embedder_with(space_id, embedder, EmbedderOptions::default())
537 }
538
539 pub fn register_embedder_with<F: Embedder + 'static>(&self, space_id: &str, embedder: F, options: EmbedderOptions) -> Result<()> {
543 storage::validate_identity("space id", space_id)?;
544 if !(1..=10_000).contains(&options.max_batch) { return Err(Error::Validation("max_batch must be between 1 and 10000".into())); }
545 if options.max_tokens_per_text == Some(0) { return Err(Error::Validation("max_tokens_per_text must be positive".into())); }
546 let space = { let state = self.0.read()?; get_space(state.conn(), space_id)? };
547 let mut entry = EmbedderEntry { options, effective_batch: options.max_batch, embedder: Box::new(embedder) };
548 let samples: Vec<String> = SAMPLE_TEXTS.iter().take(3.min(entry.effective_batch)).map(|sample| (*sample).to_string()).collect();
549 let produced = entry.embed(&samples)
551 .map_err(|error| Error::Validation(format!("embedder failed during registration ({}): {}", error.kind.code(), error.message)))?;
552 validate_vectors(&produced, samples.len(), &space)?;
553 self.0.engine.embedders.register(space_id.to_string(), entry);
554 if let Some(vectorizer) = self.0.engine.vectorizer.get() { vectorizer.notify_work(); }
556 Ok(())
557 }
558
559 pub fn embedder_space(&self, space_id: &str) -> Result<Option<EmbeddingSpace>> {
561 let state = self.0.read()?;
562 match get_space(state.conn(), space_id) { Ok(space) => Ok(Some(space)), Err(Error::NotFound(_)) => Ok(None), Err(error) => Err(error) }
563 }
564
565 pub fn unregister_embedder(&self, space_id: &str) -> Result<bool> { Ok(self.0.engine.embedders.remove(space_id)) }
566
567 pub fn namespace_vectorization(&self, namespace: &str) -> Result<bool> {
569 storage::validate_identity("namespace", namespace)?;
570 let state = self.0.read()?;
571 namespace_vectorization(state.conn(), namespace)
572 }
573
574 pub fn set_namespace_vectorization(&self, namespace: &str, enabled: bool) -> Result<WriteReceipt<bool>> {
575 storage::validate_identity("namespace", namespace)?;
576 let receipt = self.0.mutate_meta(|tx| {
577 tx.execute("INSERT INTO meta(key,value) VALUES (?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
578 params![vectorize_key(namespace), i64::from(enabled)])?;
579 Ok(enabled)
580 })?;
581 {
583 let mut guard = self.0.engine.vector_writer.lock();
584 if let Some(writer) = guard.as_mut() {
585 clear_vector_ready(&writer.conn, namespace)?;
586 }
587 }
588 if let Some(vectorizer) = self.0.engine.vectorizer.get() { vectorizer.notify_work(); }
590 Ok(receipt)
591 }
592
593 pub fn vectorization(&self, namespace: &str, target: &str) -> Result<bool> {
596 storage::validate_identity("namespace", namespace)?;
597 let target = VectorizeTarget::parse(target)?;
598 let state = self.0.read()?;
599 target_vectorization(state.conn(), namespace, target)
600 }
601
602 pub fn set_vectorization(&self, namespace: &str, target: &str, enabled: bool) -> Result<WriteReceipt<bool>> {
604 storage::validate_identity("namespace", namespace)?;
605 let target = VectorizeTarget::parse(target)?;
606 let receipt = self.0.mutate_meta(|tx| {
607 tx.execute("INSERT INTO meta(key,value) VALUES (?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
608 params![target_vectorize_key(namespace, target), i64::from(enabled)])?;
609 Ok(enabled)
610 })?;
611 {
613 let mut guard = self.0.engine.vector_writer.lock();
614 if let Some(writer) = guard.as_mut() {
615 clear_vector_ready(&writer.conn, namespace)?;
616 }
617 }
618 if let Some(vectorizer) = self.0.engine.vectorizer.get() { vectorizer.notify_work(); }
620 Ok(receipt)
621 }
622
623 pub fn vector_ready(&self, namespace: &str, space_id: &str, target: &str) -> Result<bool> {
626 storage::validate_identity("namespace", namespace)?;
627 storage::validate_identity("space id", space_id)?;
628 let target = VectorizeTarget::parse(target)?;
629 let state = self.0.read()?;
630 vector_ready(state.conn(), namespace, space_id, target)
631 }
632
633 pub fn sync(&self, space_id: &str, batch: usize) -> Result<WriteReceipt<SyncReport>> {
641 storage::validate_limit(batch)?;
642 if self.0.engine.embedders.get(space_id).is_none() {
643 return Err(Error::Validation(format!("no embedder registered for space {space_id}")));
644 }
645 let report = self.fill(space_id, batch, true)?;
646 let state = self.0.read()?;
647 Ok(WriteReceipt { value: report, revision: storage::current_revision(state.conn())? })
648 }
649
650 fn fill(&self, space_id: &str, batch: usize, blocking: bool) -> Result<SyncReport> {
653 let Some(entry) = self.0.engine.embedders.get(space_id) else { return Ok(SyncReport::default()) };
654 self.0.catch_up_index(blocking)?;
655 let report = self.drain(space_id, &entry, batch, blocking)?;
656 if report.interrupted.is_some() { self.0.note_degrade(Degrade::EmbedFailed); }
657 self.verify_and_mark(space_id)?;
658 Ok(report)
659 }
660
661 fn verify_and_mark(&self, space_id: &str) -> Result<()> {
668 for _attempt in 0..VERIFY_ATTEMPTS {
669 let (revision, marks) = {
670 let state = self.0.read()?;
671 let index = self.0.index()?;
672 let conn = state.conn();
673 let pending: i64 = conn.query_row("SELECT COUNT(*) FROM index_updates", [], |r| r.get(0))?;
674 if pending > 0 { return Ok(()); }
675 let revision = storage::current_revision(conn)?;
676 let mut marks = Vec::new();
677 for namespace in storage::record_namespaces(conn)? {
678 for target in VectorizeTarget::ALL {
679 let enabled = target_vectorization(conn, &namespace, target)?;
680 let gap = has_gap(conn, &index, space_id, &namespace, target)?;
681 let ready = enabled && !gap;
682 marks.push((namespace.clone(), target, ready));
683 }
684 }
685 (revision, marks)
686 };
687 {
688 let mut guard = self.0.engine.vector_writer.lock();
689 let writer = guard.as_mut().ok_or(Error::Closed)?;
690 let (current_rev, pending) = {
691 let state = self.0.read()?;
692 let conn = state.conn();
693 let pending: i64 = conn.query_row("SELECT COUNT(*) FROM index_updates", [], |r| r.get(0))?;
694 let current_rev = storage::current_revision(conn)?;
695 (current_rev, pending)
696 };
697 if pending > 0 || current_rev != revision {
698 continue;
699 }
700 for (namespace, target, ready) in &marks {
701 set_vector_ready(&writer.conn, namespace, space_id, *target, *ready)?;
702 }
703 return Ok(());
704 }
705 }
706 Ok(())
707 }
708
709 fn drain(&self, space_id: &str, entry: &Arc<Mutex<EmbedderEntry>>, batch: usize, blocking: bool) -> Result<SyncReport> {
711 let mut report = SyncReport::default();
712 let acquired = if blocking { Some(entry.lock()) } else { entry.try_lock() };
713 let Some(mut guard) = acquired else { return Ok(report); };
714 let mut cursor: Option<i64> = None;
715 loop {
716 let limit = batch.min(guard.effective_batch).max(1);
717 let candidates = {
718 let state = self.0.read()?;
719 let index = self.0.index()?;
720 pending_candidates(state.conn(), &index, space_id, None, None, limit, cursor, None)?
721 };
722 let Some(last) = candidates.last().map(|input| input.key.id) else { break };
723 let pending: Vec<EmbeddingInput> = candidates.into_iter().filter(embeddable).collect();
724 if pending.is_empty() { cursor = Some(last); continue; }
725 report.scanned += pending.len();
726 let texts: Vec<String> = pending.iter().map(|input| input.text.clone()).collect();
727 let values = match embed_with_retry(&mut guard, &texts) {
728 EmbedOutcome::Shrunk => continue,
729 EmbedOutcome::Failed(message) => { report.interrupted = Some(message); break; }
730 EmbedOutcome::Vectors(values) => values,
731 };
732 if values.len() != pending.len() {
733 report.interrupted = Some(format!("embedder returned {} vectors for {} inputs", values.len(), pending.len()));
734 break;
735 }
736 let writes: Vec<EmbeddingWrite> = pending.iter().zip(values).map(|(input, vector)|
737 EmbeddingWrite { key: input.key, fingerprint: input.fingerprint.clone(), values: vector,
738 namespace: input.namespace.clone(), scope: input.scope.clone(), kind: input.kind,
739 tags: input.tags.clone(), note_id: input.note_id }).collect();
740 match self.put(space_id, &writes) {
741 Ok(receipt) => { report.written += receipt.value; report.batches += 1; }
742 Err(Error::StaleRevision(_)) => {}
743 Err(error) => return Err(error),
744 }
745 cursor = Some(last);
746 }
747 Ok(report)
748 }
749
750 pub(crate) fn put(&self, space_id: &str, writes: &[EmbeddingWrite]) -> Result<WriteReceipt<usize>> {
753 let space = { let state = self.0.read()?; get_space(state.conn(), space_id)? };
754 {
756 let state = self.0.read()?;
757 for write in writes {
758 let actual: Option<String> = state.conn().query_row("SELECT fingerprint FROM records WHERE id=?1", [write.key.id], |r| r.get(0)).optional()?;
759 let actual = actual.ok_or_else(|| Error::NotFound(write.key.id.to_string()))?;
760 if actual != write.fingerprint { return Err(Error::StaleRevision(write.key.id.to_string())); }
761 }
762 }
763 let mut guard = self.0.engine.vector_writer.lock();
764 let writer = guard.as_mut().ok_or(Error::Closed)?;
765 let tx = writer.conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
766 for write in writes {
767 let normalized = normalize(&write.values, space.dimension)?;
768 let bytes = encode_values(&normalized, &space.encoding)?;
769 tx.execute("INSERT INTO embeddings(space_id,record_id,namespace,scope,kind,tags_json,note_id,fingerprint,vector)
770 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)
771 ON CONFLICT(space_id,record_id) DO UPDATE SET
772 namespace=excluded.namespace,scope=excluded.scope,kind=excluded.kind,
773 tags_json=excluded.tags_json,note_id=excluded.note_id,
774 fingerprint=excluded.fingerprint,vector=excluded.vector",
775 params![space_id, write.key.id, write.namespace, write.scope, write.kind.code(),
776 serde_json::to_string(&write.tags)?, write.note_id, write.fingerprint, bytes])?;
777 }
778 tx.commit()?;
779 let touched: std::collections::HashSet<String> = writes.iter().map(|w| w.namespace.clone()).collect();
781 self.0.engine.vectors.invalidate_namespaces(&touched);
782 Ok(WriteReceipt { value: writes.len(), revision: 0 })
783 }
784
785 pub fn delete_space(&self, id: &str) -> Result<WriteReceipt<bool>> {
788 let receipt = self.0.mutate_meta(|tx| {
789 let deleted = tx.execute("DELETE FROM embedding_spaces WHERE id=?1", [id])? > 0;
790 Ok(deleted)
791 })?;
792 if receipt.value {
793 let mut guard = self.0.engine.vector_writer.lock();
794 if let Some(writer) = guard.as_mut() {
795 writer.conn.execute("DELETE FROM embeddings WHERE space_id=?1", [id])?;
796 writer.conn.execute("DELETE FROM vector_meta WHERE key GLOB 'vector_ready:*:'||?1||':*'", [id])?;
799 }
800 }
801 self.0.engine.vectors.invalidate();
803 Ok(receipt)
804 }
805}
806
807fn validate_vectors(produced: &[Vec<f32>], expected: usize, space: &EmbeddingSpace) -> Result<()> {
809 if produced.len() != expected {
810 return Err(Error::InvalidVector(format!("embedder returned {} vectors for {expected} inputs", produced.len())));
811 }
812 for values in produced {
813 normalize(values, space.dimension)
814 .map_err(|error| Error::InvalidVector(format!("embedder output does not satisfy space {}: {error}", space.id)))?;
815 }
816 Ok(())
817}
818
819const SWEEP_BATCH: usize = 32;
823
824const VERIFY_ATTEMPTS: usize = 3;
826
827pub(crate) struct Vectorizer {
834 stopping: Mutex<bool>,
836 signal: Condvar,
838 pending: AtomicBool,
841 handle: Mutex<Option<JoinHandle<()>>>,
842}
843
844impl Vectorizer {
845 pub(crate) fn start(engine: &Arc<crate::storage::Engine>) -> Result<Arc<Self>> {
848 let vectorizer = Arc::new(Self { stopping: Mutex::new(false), signal: Condvar::new(),
849 pending: AtomicBool::new(true), handle: Mutex::new(None) });
850 let worker = Arc::clone(&vectorizer);
851 let engine = Arc::downgrade(engine);
852 let handle = std::thread::Builder::new().name("p-memory-vectorize".into())
853 .spawn(move || work_loop(&engine, &worker))?;
854 *vectorizer.handle.lock() = Some(handle);
855 Ok(vectorizer)
856 }
857
858 pub(crate) fn notify_work(&self) {
861 let _guard = self.stopping.lock();
862 self.pending.store(true, AtomicOrdering::SeqCst);
863 self.signal.notify_all();
864 }
865
866 pub(crate) fn stop(&self) {
868 {
869 let mut stopping = self.stopping.lock();
870 *stopping = true;
871 self.signal.notify_all();
872 }
873 if let Some(handle) = self.handle.lock().take() { let _ = handle.join(); }
874 }
875}
876
877fn work_loop(engine: &Weak<crate::storage::Engine>, vectorizer: &Vectorizer) {
881 loop {
882 {
883 let mut stopping = vectorizer.stopping.lock();
884 while !*stopping && !vectorizer.pending.load(AtomicOrdering::SeqCst) {
886 vectorizer.signal.wait(&mut stopping);
887 }
888 if *stopping { return; }
889 }
890 vectorizer.pending.store(false, AtomicOrdering::SeqCst);
892 let Some(engine) = engine.upgrade() else { return };
893 let kb = KnowledgeBase { engine };
894 loop {
895 let mut progressed = false;
896 for space_id in kb.engine.embedders.space_ids() {
897 if let Ok(report) = EmbeddingStore(kb.clone()).fill(&space_id, SWEEP_BATCH, false) {
899 if report.written > 0 { progressed = true; }
900 }
901 }
902 if !progressed { break; }
903 }
904 }
905}
906
907struct VectorRow { key: RecordKey, kind: RecordKind, tags: Vec<String>, note: i64, #[allow(dead_code)] fingerprint: String }
909enum PartitionData {
912 F32(Vec<f32>),
913 Sq8 { codes: Vec<i8>, scales: Vec<f32> },
914}
915pub(crate) struct Partition { dimension: usize, rows: Vec<VectorRow>, data: PartitionData }
917
918struct Candidate { score: f64, key: RecordKey }
920impl PartialEq for Candidate { fn eq(&self, other: &Self) -> bool { self.score == other.score && self.key == other.key } }
921impl Eq for Candidate {}
922impl PartialOrd for Candidate { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } }
923impl Ord for Candidate {
924 fn cmp(&self, other: &Self) -> Ordering { other.score.total_cmp(&self.score).then_with(|| self.key.cmp(&other.key)) }
925}
926
927impl Partition {
928 pub fn load(conn: &Connection, space: &EmbeddingSpace, namespace: &str, scope: &str) -> Result<Option<Self>> {
931 let namespace = text::normalized_tag(namespace);
932 let scope = text::normalized_tag(scope);
933 let mut stmt = conn.prepare("SELECT record_id,kind,vector,tags_json,note_id,fingerprint
940 FROM embeddings WHERE space_id=?1 AND namespace=?2 AND scope=?3")?;
941 let sq8 = space.encoding == "sq8";
942 let mut partition = Self {
943 dimension: space.dimension,
944 rows: vec![],
945 data: if sq8 { PartitionData::Sq8 { codes: vec![], scales: vec![] } } else { PartitionData::F32(vec![]) },
946 };
947 let mut rows = stmt.query(params![space.id, namespace, scope])?;
948 while let Some(row) = rows.next()? {
949 let key = RecordKey { id: row.get(0)? };
950 let kind = RecordKind::from_code(row.get::<_, i64>(1)?).ok_or_else(|| Error::InvalidVector("invalid stored record kind".into()))?;
951 let bytes: Vec<u8> = row.get(2)?;
952 let tags: Vec<String> = serde_json::from_str(&row.get::<_, String>(3)?)?;
953 let note: i64 = row.get(4)?;
954 let fingerprint: String = row.get(5)?;
956 match &mut partition.data {
957 PartitionData::F32(values) => {
958 let decoded = decode_values(&bytes, space.dimension, "f32")?;
959 if decoded.iter().any(|v| !v.is_finite()) { return Err(Error::InvalidVector("stored vector contains nonfinite values".into())); }
960 values.extend(decoded);
961 }
962 PartitionData::Sq8 { codes, scales } => {
963 let (scale, decoded) = decode_sq8(&bytes, space.dimension)?;
964 if !scale.is_finite() { return Err(Error::InvalidVector("stored vector contains nonfinite values".into())); }
965 scales.push(scale);
966 codes.extend(decoded);
967 }
968 }
969 partition.rows.push(VectorRow { key, kind, tags, note, fingerprint });
970 }
971 Ok(if partition.rows.is_empty() { None } else { Some(partition) })
972 }
973
974 fn matches(&self, row: &VectorRow, kinds: &[RecordKind], tags: &[String], note_ids: &[i64], allowed: Option<&HashSet<i64>>) -> bool {
977 if allowed.is_some_and(|set| !set.contains(&row.key.id)) { return false; }
978 if !note_ids.is_empty() && !note_ids.contains(&row.note) { return false; }
979 (kinds.is_empty() || kinds.contains(&row.kind)) && tags.iter().all(|t| row.tags.contains(t))
980 }
981
982 fn retain(heap: &mut BinaryHeap<Candidate>, key: RecordKey, scored: f64, limit: usize) {
984 let score = scored.clamp(-1.0, 1.0);
985 if heap.len() < limit { heap.push(Candidate { score, key }); }
986 else if let Some(worst) = heap.peek() {
987 if score > worst.score || (score == worst.score && key < worst.key) {
988 heap.pop(); heap.push(Candidate { score, key });
989 }
990 }
991 }
992
993 pub fn search(&self, query: &[f32], kinds: &[RecordKind], tags: &[String], note_ids: &[i64], limit: usize, allowed: Option<&HashSet<i64>>) -> Result<Vec<(RecordKey, f64)>> {
996 let query = normalize(query, self.dimension)?;
997 let mut heap = BinaryHeap::<Candidate>::new();
998 match &self.data {
999 PartitionData::F32(values) => {
1000 for (i, row) in self.rows.iter().enumerate() {
1001 if !self.matches(row, kinds, tags, note_ids, allowed) { continue; }
1002 let offset = i * self.dimension;
1003 Self::retain(&mut heap, row.key, f64::from(dot(&query, &values[offset..offset + self.dimension])), limit);
1004 }
1005 }
1006 PartitionData::Sq8 { codes, scales } => {
1007 let (query_codes, query_scale) = encode_query_sq8(&query);
1009 for (i, row) in self.rows.iter().enumerate() {
1010 if !self.matches(row, kinds, tags, note_ids, allowed) { continue; }
1011 let offset = i * self.dimension;
1012 let raw = query_scale * scales[i] * dot_codes(&query_codes, &codes[offset..offset + self.dimension]) as f32;
1013 Self::retain(&mut heap, row.key, f64::from(raw), limit);
1014 }
1015 }
1016 }
1017 let mut result: Vec<_> = heap.into_iter().map(|c| (c.key, c.score)).collect();
1018 result.sort_by(|a,b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1019 Ok(result)
1020 }
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025 use super::*;
1026 use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
1027
1028 #[test]
1030 fn integer_kernel_matches_scalar() {
1031 for dimension in [1usize, 15, 16, 17, 250, 1024] {
1032 let left: Vec<i8> = (0..dimension).map(|i| ((i * 37 % 255) as i32 - 127) as i8).collect();
1033 let right: Vec<i8> = (0..dimension).map(|i| ((i * 91 % 255) as i32 - 127) as i8).collect();
1034 assert_eq!(dot_codes(&left, &right), dot_codes_scalar(&left, &right), "dimension {dimension}");
1035 }
1036 }
1037
1038 #[test]
1042 fn tied_scores_break_by_key_whatever_the_row_order() {
1043 let dimension = 4usize;
1044 let query = vec![1.0f32, 0.0, 0.0, 0.0];
1045 let build = |order: &[i64]| Partition {
1047 dimension,
1048 rows: order.iter().map(|id| VectorRow { key: RecordKey { id: *id }, kind: RecordKind::Memory, tags: vec![], note: 0, fingerprint: String::new() }).collect(),
1049 data: PartitionData::F32(order.iter().flat_map(|_| [1.0f32, 0.0, 0.0, 0.0]).collect()),
1050 };
1051 let top_two = |partition: &Partition| -> Vec<i64> {
1052 partition.search(&query, &[], &[], &[], 2, None).unwrap().into_iter().map(|(key, _)| key.id).collect()
1053 };
1054 assert_eq!(top_two(&build(&[1, 2, 3, 4])), vec![1, 2], "并列时取 key 最小的两条");
1055 assert_eq!(top_two(&build(&[4, 3, 2, 1])), vec![1, 2], "换个行序,结果必须一样");
1056 }
1057
1058 #[test]
1060 fn quantized_query_tracks_decoded_f32_kernel() {
1061 let dimension = 256usize;
1062 let stored_raw: Vec<f32> = (0..dimension).map(|i| (i as f32 * 0.37).sin() + 0.25).collect();
1063 let query_raw: Vec<f32> = (0..dimension).map(|i| (i as f32 * 0.11).cos() - 0.1).collect();
1064 let stored = normalize(&stored_raw, dimension).unwrap();
1065 let query = normalize(&query_raw, dimension).unwrap();
1066 let encoded = encode_values(&stored, "sq8").unwrap();
1067 let (scale, codes) = decode_sq8(&encoded, dimension).unwrap();
1068 let decoded = decode_values(&encoded, dimension, "sq8").unwrap();
1069 let reference = dot(&query, &decoded);
1070 let (query_codes, query_scale) = encode_query_sq8(&query);
1071 let actual = query_scale * scale * dot_codes(&query_codes, &codes) as f32;
1072 assert!((reference - actual).abs() < 1e-3, "reference {reference} vs actual {actual}");
1074 }
1075
1076 #[test]
1078 fn oversized_batches_shrink_and_persist() {
1079 let lengths = std::sync::Arc::new(Mutex::new(Vec::<usize>::new()));
1080 let observed = lengths.clone();
1081 let mut entry = EmbedderEntry {
1082 options: EmbedderOptions { max_batch: 8, max_tokens_per_text: None },
1083 effective_batch: 8,
1084 embedder: Box::new(move |texts: &[String]| {
1085 observed.lock().push(texts.len());
1086 if texts.len() > 4 { return Err(EmbedCallbackError::too_large("too many texts")); }
1087 Ok(texts.iter().map(|_| vec![1.0f32, 0.0]).collect())
1088 }),
1089 };
1090 let texts: Vec<String> = (0..8).map(|i| format!("文本 {i}")).collect();
1091 assert!(matches!(embed_with_retry(&mut entry, &texts), EmbedOutcome::Shrunk));
1092 assert_eq!(entry.effective_batch, 4, "减半值应当写在 entry 上并持久");
1093 assert!(matches!(embed_with_retry(&mut entry, &texts[..4]), EmbedOutcome::Vectors(_)));
1094 assert_eq!(*lengths.lock(), vec![8, 4]);
1095 }
1096
1097 #[test]
1099 fn callback_errors_are_classified() {
1100 let mut broken = EmbedderEntry {
1101 options: EmbedderOptions::default(), effective_batch: 1,
1102 embedder: Box::new(|_: &[String]| Err(EmbedCallbackError::too_large("still too large"))),
1103 };
1104 assert!(matches!(embed_with_retry(&mut broken, &["a".to_string()]), EmbedOutcome::Failed(_)));
1105 assert_eq!(broken.effective_batch, 1);
1106
1107 let attempts = std::sync::Arc::new(AtomicUsize::new(0));
1108 let counter = attempts.clone();
1109 let mut throttled = EmbedderEntry {
1110 options: EmbedderOptions::default(), effective_batch: 4,
1111 embedder: Box::new(move |_: &[String]| {
1112 let attempt = counter.fetch_add(1, AtomicOrdering::SeqCst);
1113 if attempt < 2 { Err(EmbedCallbackError::rate_limited("slow down")) } else { Ok(vec![vec![1.0f32, 0.0]]) }
1114 }),
1115 };
1116 assert!(matches!(embed_with_retry(&mut throttled, &["a".to_string()]), EmbedOutcome::Vectors(_)));
1117 assert_eq!(attempts.load(AtomicOrdering::SeqCst), 3, "限流应当退避重试后成功");
1118 assert_eq!(throttled.effective_batch, 4, "限流不触发减半");
1119 }
1120}
1121
1122pub(crate) fn migrate_vectors(root: &std::path::Path, main_conn: &mut Connection) -> Result<()> {
1126 let path = root.join("vectors.sqlite3");
1127 let mut vector_conn = open_vector_writer_for_migration(&path)?;
1129 vector_conn.execute_batch(include_str!("vectors_schema.sql"))?;
1130 let mut stmt = main_conn.prepare("SELECT space_id,record_id,fingerprint,vector FROM embeddings")?;
1133 let rows: Vec<(String, i64, String, Vec<u8>)> = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))?
1134 .collect::<std::result::Result<_, _>>()?;
1135 drop(stmt);
1136 let tx = vector_conn.transaction()?;
1138 for (space_id, record_id, fingerprint, vector) in rows {
1139 let (namespace, scope, kind, tags_json, note_id): (String, String, i64, String, i64) = main_conn.query_row(
1140 "SELECT n.text,s.text,r.kind,
1141 COALESCE((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),'[]'),
1142 COALESCE((SELECT c.note_id FROM chunks c WHERE c.record_id=r.id),0)
1143 FROM records r JOIN strings n ON n.id=r.namespace_id JOIN strings s ON s.id=r.scope_id WHERE r.id=?1",
1144 [record_id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)))?;
1145 tx.execute("INSERT OR REPLACE INTO embeddings(space_id,record_id,namespace,scope,kind,tags_json,note_id,fingerprint,vector)
1146 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)",
1147 params![space_id, record_id, namespace, scope, kind, tags_json, note_id, fingerprint, vector])?;
1148 }
1149 let mut ready_stmt = main_conn.prepare("SELECT key,value FROM meta WHERE key LIKE 'vector_ready:%'")?;
1151 let ready_rows: Vec<(String, i64)> = ready_stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::<std::result::Result<_, _>>()?;
1152 drop(ready_stmt);
1153 for (key, value) in ready_rows {
1154 tx.execute("INSERT OR REPLACE INTO vector_meta(key,value) VALUES (?1,?2)", params![key, value.to_string()])?;
1155 }
1156 tx.commit()?;
1157 main_conn.execute_batch("DROP TABLE embeddings; DELETE FROM meta WHERE key LIKE 'vector_ready:%';")?;
1159 Ok(())
1160}
1161
1162fn open_vector_writer_for_migration(path: &std::path::Path) -> Result<Connection> {
1164 let conn = Connection::open(path)?;
1165 conn.execute_batch("PRAGMA busy_timeout=5000; PRAGMA synchronous=NORMAL;")?;
1166 Ok(conn)
1167}