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