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