Skip to main content

semquery_core/
traits.rs

1//! Async boundaries:
2//! - [`Storage`] is sync (SQLite is local blocking IO).
3//! - [`Embedder`] / [`Reranker`] / [`Llm`] are async (heavy inference).
4//!
5//! [`Storage`]: crate::traits::Storage
6//! [`Embedder`]: crate::traits::Embedder
7//! [`Reranker`]: crate::traits::Reranker
8//! [`Llm`]: crate::traits::Llm
9
10use std::collections::HashMap;
11
12use async_trait::async_trait;
13use serde::{Deserialize, Serialize};
14
15use crate::error::Result;
16use crate::models::{Chunk, ChunkCandidate, Collection, Document, DocumentSource, ModelRole, ModelSpec};
17
18#[async_trait]
19pub trait Embedder: Send + Sync {
20  fn dimension(&self) -> usize;
21  fn model_name(&self) -> &str;
22  async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>>;
23}
24
25#[async_trait]
26pub trait Reranker: Send + Sync {
27  async fn rerank(&self, query: &str, chunks: &[Chunk]) -> Result<Vec<crate::models::ScoredChunk>>;
28}
29
30#[async_trait]
31pub trait Llm: Send + Sync {
32  async fn complete(&self, prompt: &str) -> Result<String>;
33
34  /// Streamed generation: calls `on_token` for each decoded piece as it is
35  /// produced, and returns the full text when generation ends.
36  async fn complete_stream(&self, prompt: &str, on_token: &mut (dyn FnMut(String) + Send + Sync)) -> Result<String> {
37    let text = self.complete(prompt).await?;
38    on_token(text.clone());
39    Ok(text)
40  }
41}
42
43pub trait Chunker: Send + Sync {
44  fn chunk(&self, text: &str) -> Vec<ChunkCandidate>;
45}
46
47pub trait FileReader: Send + Sync {
48  /// File extensions this reader handles, without the leading dot
49  /// (e.g. `["txt", "md"]` or `["pdf"]`).
50  fn extensions(&self) -> &[&str];
51
52  /// Read a single file and return its content as a `DocumentSource`.
53  /// Return `Ok(None)` to silently skip the file (e.g. empty or
54  /// non-UTF-8).
55  fn read(&self, path: &std::path::Path) -> Result<Option<DocumentSource>>;
56}
57
58pub trait WordSegmenter: Send + Sync {
59  fn segment(&self, text: &str) -> String;
60}
61
62pub trait Storage: Send + Sync {
63  /// Initialize all storage tables. Pass `0` to skip creating the vector
64  /// table when no embedder is available yet.
65  fn init(&self, vector_dimension: usize) -> Result<()>;
66
67  // ---- reads / queries ----
68
69  fn get_document(&self, doc_id: &str) -> Result<Option<Document>>;
70  fn list_documents(&self) -> Result<Vec<Document>>;
71  fn get_document_paths(&self, doc_ids: &[String]) -> Result<HashMap<String, String>>;
72  fn get_chunks(&self, chunk_ids: &[String]) -> Result<Vec<Chunk>>;
73  fn search_vectors(&self, embedding: &[f32], top_k: usize) -> Result<Vec<(String, f32)>>;
74  fn search_text(&self, query: &str, top_k: usize) -> Result<Vec<(String, f32)>>;
75  fn get_model_version(&self, role: ModelRole) -> Result<Option<ModelSpec>>;
76  fn set_model_version_atomic(&self, role: ModelRole, version: &ModelSpec) -> Result<()>;
77  fn get_meta(&self, key: &str) -> Result<Option<String>>;
78  fn set_meta_atomic(&self, key: &str, value: &str) -> Result<()>;
79  fn list_collections(&self) -> Result<Vec<Collection>>;
80
81  // ---- counts ----
82
83  fn count_chunks(&self) -> Result<usize>;
84
85  // ---- transactions ----
86
87  /// Begin a write transaction covering `documents` / `chunks` / `vec_chunks`
88  /// / `fts_chunks` / `model_versions`. Operations on the returned [`StorageTx`]
89  /// are atomic: they either all commit via [`StorageTx::commit`] or all roll
90  /// back when the transaction is dropped without committing.
91  fn begin_tx(&self) -> Result<Box<dyn StorageTx + '_>>;
92}
93
94/// Atomic write transaction over the indexed tables. All mutations flow
95/// through this trait so a re-index / re-embed failure cannot leave the
96/// store half-written.
97pub trait StorageTx {
98  fn add_document(&mut self, doc: &Document) -> Result<()>;
99  fn set_document_path(&mut self, doc_id: &str, path: &str) -> Result<()>;
100  fn delete_document(&mut self, doc_id: &str) -> Result<()>;
101  fn add_chunks(&mut self, chunks: &[Chunk]) -> Result<()>;
102  fn add_chunk_documents(&mut self, chunk_ids: &[String], doc_id: &str) -> Result<()>;
103  fn delete_chunks_by_doc(&mut self, doc_id: &str) -> Result<()>;
104  fn add_vectors(&mut self, chunk_ids: &[String], embeddings: &[Vec<f32>]) -> Result<()>;
105  fn add_fts_chunks(&mut self, chunk_ids: &[String], tokenized_texts: &[String]) -> Result<()>;
106  fn set_model_version(&mut self, role: ModelRole, version: &ModelSpec) -> Result<()>;
107  fn add_collection(&mut self, name: &str, path: &str) -> Result<()>;
108  fn delete_collection(&mut self, name: &str) -> Result<()>;
109  fn clear_collections(&mut self) -> Result<()>;
110  fn commit(&mut self) -> Result<()>;
111}
112
113/// Events emitted while building or rebuilding an index.
114///
115/// Consume these events via [`Indexer::index_file_stream`](semquery_indexer::Indexer::index_file_stream),
116/// [`Indexer::index_directory_stream`](semquery_indexer::Indexer::index_directory_stream), or the
117/// [`Engine::index_stream`](semquery::Engine::index_stream) family of methods.
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119#[serde(tag = "type", rename_all = "snake_case")]
120pub enum IndexEvent {
121  /// Indexing started; number of sources/files to process.
122  ScanStart {
123    /// Total number of sources or files that will be processed.
124    total_sources: usize,
125  },
126
127  /// A source is about to be indexed.
128  SourceStarted {
129    /// Identifier of the source (e.g. collection name).
130    source_id: String,
131  },
132
133  /// A file was parsed into chunks.
134  FileParsed {
135    /// Identifier of the source this file belongs to.
136    source_id: String,
137    /// Path of the parsed file.
138    path: String,
139    /// Number of chunks produced from the file.
140    chunks: usize,
141  },
142
143  /// A model file needs downloading from the model hub (not yet cached).
144  /// Emitted as the first events of a lazy index stream, before any retrieval
145  /// of an already-built index happens.
146  ModelDownloadStart {
147    /// Which model role this file belongs to.
148    role: ModelRole,
149    /// HuggingFace repo id, e.g. `BAAI/bge-small-zh-v1.5`.
150    repo_id: String,
151    /// File within the repo.
152    filename: String,
153  },
154
155  /// A model file download finished.
156  ModelDownloadComplete {
157    /// Which model role this file belongs to.
158    role: ModelRole,
159    /// Wall time of the download, in milliseconds.
160    elapsed_ms: u64,
161  },
162
163  /// A batch of chunks is being embedded.
164  EmbeddingBatch {
165    /// Number of chunks in this batch.
166    count: usize,
167  },
168
169  /// The index store is being written.
170  WritingStore,
171
172  /// A source finished indexing.
173  SourceComplete {
174    /// Identifier of the source.
175    source_id: String,
176    /// Number of chunks indexed for this source.
177    chunks: usize,
178  },
179
180  /// Indexing is complete.
181  Complete {
182    /// Total number of files indexed.
183    files: usize,
184    /// Total number of chunks indexed.
185    chunks: usize,
186    /// Total number of files skipped because they were unchanged.
187    files_skipped: usize,
188    /// Total number of files removed because they no longer exist.
189    files_removed: usize,
190  },
191
192  /// An error occurred.
193  Error {
194    /// Human-readable error message.
195    message: String,
196  },
197}