1use std::collections::{BTreeSet, HashMap};
26use std::sync::Arc;
27
28use tokio::sync::RwLock;
29use tracing::{error, info};
30
31use crate::chunking::Chunker;
32use crate::config::RagConfig;
33use crate::document::{Chunk, Document, SearchResult};
34use crate::embedding::EmbeddingProvider;
35use crate::error::{RagError, Result};
36use crate::filter::{Field, Filter};
37use crate::reranker::Reranker;
38use crate::scope::Scope;
39use crate::vectorstore::{CollectionSpec, VectorQuery, VectorStore};
40
41pub struct RagPipeline {
48 config: RagConfig,
49 embedding_provider: Arc<dyn EmbeddingProvider>,
50 vector_store: Arc<dyn VectorStore>,
51 chunker: Arc<dyn Chunker>,
52 reranker: Option<Arc<dyn Reranker>>,
53 filterable: RwLock<HashMap<String, BTreeSet<String>>>,
55}
56
57impl RagPipeline {
58 pub fn builder() -> RagPipelineBuilder {
60 RagPipelineBuilder::default()
61 }
62
63 pub fn config(&self) -> &RagConfig {
65 &self.config
66 }
67
68 pub fn embedding_provider(&self) -> &Arc<dyn EmbeddingProvider> {
70 &self.embedding_provider
71 }
72
73 pub fn vector_store(&self) -> &Arc<dyn VectorStore> {
75 &self.vector_store
76 }
77
78 pub async fn create_collection(&self, name: &str) -> Result<()> {
87 self.create_collection_with_filterable(name, Vec::<String>::new()).await
88 }
89
90 pub async fn create_collection_with_filterable<I, S>(
108 &self,
109 name: &str,
110 filterable: I,
111 ) -> Result<()>
112 where
113 I: IntoIterator<Item = S>,
114 S: Into<String>,
115 {
116 let spec =
117 CollectionSpec::new(self.embedding_provider.dimensions()).with_filterable(filterable);
118 self.vector_store.create_collection(name, &spec).await.map_err(|e| {
119 error!(collection = name, error = %e, "failed to create collection");
120 RagError::PipelineError(format!("failed to create collection '{name}': {e}"))
121 })?;
122 self.filterable.write().await.insert(name.to_string(), spec.filterable);
123 Ok(())
124 }
125
126 async fn check_filter(&self, collection: &str, filter: &Filter) -> Result<()> {
128 let filterable = self.filterable.read().await;
129 let declared = filterable.get(collection).cloned().unwrap_or_default();
130 filter.validate_declared(collection, &declared)
131 }
132
133 pub async fn delete_collection(&self, name: &str) -> Result<()> {
139 self.vector_store.delete_collection(name).await.map_err(|e| {
140 error!(collection = name, error = %e, "failed to delete collection");
141 RagError::PipelineError(format!("failed to delete collection '{name}': {e}"))
142 })?;
143 self.filterable.write().await.remove(name);
144 Ok(())
145 }
146
147 pub fn scoped(&self, scope: Scope) -> ScopedRag<'_> {
163 ScopedRag { pipeline: self, scope }
164 }
165}
166
167#[derive(Debug, Clone, Default, PartialEq, Eq)]
182#[non_exhaustive]
183pub struct QueryOptions {
184 pub top_k: Option<usize>,
186 pub filter: Option<Filter>,
188}
189
190impl QueryOptions {
191 pub fn new() -> Self {
193 Self::default()
194 }
195
196 #[must_use]
198 pub fn with_top_k(mut self, top_k: usize) -> Self {
199 self.top_k = Some(top_k);
200 self
201 }
202
203 #[must_use]
206 pub fn with_filter(mut self, filter: Filter) -> Self {
207 self.filter = Some(filter);
208 self
209 }
210}
211
212pub struct ScopedRag<'a> {
217 pipeline: &'a RagPipeline,
218 scope: Scope,
219}
220
221impl ScopedRag<'_> {
222 pub fn scope(&self) -> &Scope {
224 &self.scope
225 }
226
227 pub async fn ingest(&self, collection: &str, document: &Document) -> Result<Vec<Chunk>> {
242 let pipeline = self.pipeline;
243 let scope = self.scope.as_str();
244 let mut chunks = pipeline.chunker.chunk(document);
246 if chunks.is_empty() {
247 let removed = self.delete_document(collection, &document.id).await?;
248 info!(document.id = %document.id, scope, chunk_count = 0, removed, "ingested document (empty)");
249 return Ok(chunks);
250 }
251
252 let texts: Vec<&str> = chunks.iter().map(|c| c.text.as_str()).collect();
254
255 let embeddings = pipeline.embedding_provider.embed_batch(&texts).await.map_err(|e| {
257 error!(document.id = %document.id, error = %e, "embedding failed during ingestion");
258 RagError::PipelineError(format!("embedding failed for document '{}': {e}", document.id))
259 })?;
260
261 if embeddings.len() != chunks.len() {
264 error!(
265 document.id = %document.id,
266 chunk_count = chunks.len(),
267 embedding_count = embeddings.len(),
268 "embedding provider returned the wrong number of vectors"
269 );
270 return Err(RagError::PipelineError(format!(
271 "embedding provider returned {} vectors for {} chunks of document '{}'",
272 embeddings.len(),
273 chunks.len(),
274 document.id
275 )));
276 }
277 for (chunk, embedding) in chunks.iter_mut().zip(embeddings) {
278 chunk.embedding = embedding;
279 }
280
281 pipeline.vector_store.upsert(collection, &self.scope, &chunks).await.map_err(|e| {
283 error!(document.id = %document.id, error = %e, "upsert failed during ingestion");
284 RagError::PipelineError(format!("upsert failed for document '{}': {e}", document.id))
285 })?;
286
287 let stale = Filter::and([
289 Filter::eq(Field::DocumentId, document.id.clone()),
290 !Filter::is_in(Field::ChunkId, chunks.iter().map(|chunk| chunk.id.clone())),
291 ]);
292 let removed =
293 pipeline.vector_store.delete_where(collection, &self.scope, &stale).await.map_err(
294 |e| {
295 error!(document.id = %document.id, error = %e, "stale chunk removal failed");
296 RagError::PipelineError(format!(
297 "removing stale chunks of document '{}' failed: {e}",
298 document.id
299 ))
300 },
301 )?;
302
303 let chunk_count = chunks.len();
304 info!(document.id = %document.id, scope, chunk_count, removed, "ingested document");
305
306 Ok(chunks)
307 }
308
309 pub async fn ingest_batch(
318 &self,
319 collection: &str,
320 documents: &[Document],
321 ) -> Result<Vec<Chunk>> {
322 let mut all_chunks = Vec::new();
323 for document in documents {
324 let chunks = self.ingest(collection, document).await?;
325 all_chunks.extend(chunks);
326 }
327 Ok(all_chunks)
328 }
329
330 pub async fn query(&self, collection: &str, query: &str) -> Result<Vec<SearchResult>> {
339 self.query_with(collection, query, &QueryOptions::new()).await
340 }
341
342 pub async fn query_with(
363 &self,
364 collection: &str,
365 query: &str,
366 options: &QueryOptions,
367 ) -> Result<Vec<SearchResult>> {
368 let pipeline = self.pipeline;
369 let top_k = options.top_k.unwrap_or(pipeline.config.top_k);
370 if top_k == 0 {
371 return Err(RagError::ConfigError("top_k must be greater than 0".to_string()));
372 }
373 if let Some(filter) = &options.filter {
374 pipeline.check_filter(collection, filter).await?;
375 }
376
377 let query_embedding = pipeline.embedding_provider.embed(query).await.map_err(|e| {
379 error!(error = %e, "embedding failed during query");
380 RagError::PipelineError(format!("query embedding failed: {e}"))
381 })?;
382
383 let mut vector_query = VectorQuery::new(&query_embedding, top_k);
385 if let Some(filter) = &options.filter {
386 vector_query = vector_query.with_filter(filter);
387 }
388 let results = pipeline
389 .vector_store
390 .search(collection, &self.scope, &vector_query)
391 .await
392 .map_err(|e| {
393 error!(collection, error = %e, "vector store search failed");
394 RagError::PipelineError(format!("search failed in collection '{collection}': {e}"))
395 })?;
396
397 let results = if let Some(reranker) = &pipeline.reranker {
399 reranker.rerank(query, results).await.map_err(|e| {
400 error!(error = %e, "reranking failed");
401 RagError::PipelineError(format!("reranking failed: {e}"))
402 })?
403 } else {
404 results
405 };
406
407 let threshold = pipeline.config.similarity_threshold;
409 let filtered: Vec<SearchResult> =
410 results.into_iter().filter(|r| r.score >= threshold).collect();
411
412 info!(result_count = filtered.len(), scope = self.scope.as_str(), "query completed");
413
414 Ok(filtered)
415 }
416
417 pub async fn count(&self, collection: &str) -> Result<u64> {
423 self.pipeline.vector_store.count(collection, &self.scope, None).await.map_err(|e| {
424 error!(collection, error = %e, "count failed");
425 RagError::PipelineError(format!("count failed in collection '{collection}': {e}"))
426 })
427 }
428
429 pub async fn count_where(&self, collection: &str, filter: &Filter) -> Result<u64> {
436 self.pipeline.check_filter(collection, filter).await?;
437 self.pipeline.vector_store.count(collection, &self.scope, Some(filter)).await.map_err(|e| {
438 error!(collection, error = %e, "count failed");
439 RagError::PipelineError(format!("count failed in collection '{collection}': {e}"))
440 })
441 }
442
443 pub async fn delete_where(&self, collection: &str, filter: &Filter) -> Result<u64> {
463 self.pipeline.check_filter(collection, filter).await?;
464 let deleted = self
465 .pipeline
466 .vector_store
467 .delete_where(collection, &self.scope, filter)
468 .await
469 .map_err(|e| {
470 error!(collection, error = %e, "delete_where failed");
471 RagError::PipelineError(format!(
472 "delete_where failed in collection '{collection}': {e}"
473 ))
474 })?;
475 info!(collection, scope = self.scope.as_str(), deleted, "deleted matching chunks");
476 Ok(deleted)
477 }
478
479 pub async fn delete_document(&self, collection: &str, document_id: &str) -> Result<u64> {
485 self.delete_where(collection, &Filter::eq(Field::DocumentId, document_id)).await
486 }
487
488 pub async fn purge_scope(&self, collection: &str) -> Result<u64> {
496 let purged =
497 self.pipeline.vector_store.purge_scope(collection, &self.scope).await.map_err(|e| {
498 error!(collection, error = %e, "purge failed");
499 RagError::PipelineError(format!("purge failed in collection '{collection}': {e}"))
500 })?;
501 info!(collection, scope = self.scope.as_str(), purged, "purged scope");
502 Ok(purged)
503 }
504}
505
506#[derive(Default)]
523pub struct RagPipelineBuilder {
524 config: Option<RagConfig>,
525 embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
526 vector_store: Option<Arc<dyn VectorStore>>,
527 chunker: Option<Arc<dyn Chunker>>,
528 reranker: Option<Arc<dyn Reranker>>,
529}
530
531impl RagPipelineBuilder {
532 pub fn config(mut self, config: RagConfig) -> Self {
534 self.config = Some(config);
535 self
536 }
537
538 pub fn embedding_provider(mut self, provider: Arc<dyn EmbeddingProvider>) -> Self {
540 self.embedding_provider = Some(provider);
541 self
542 }
543
544 pub fn vector_store(mut self, store: Arc<dyn VectorStore>) -> Self {
546 self.vector_store = Some(store);
547 self
548 }
549
550 pub fn chunker(mut self, chunker: Arc<dyn Chunker>) -> Self {
552 self.chunker = Some(chunker);
553 self
554 }
555
556 pub fn reranker(mut self, reranker: Arc<dyn Reranker>) -> Self {
558 self.reranker = Some(reranker);
559 self
560 }
561
562 pub fn build(self) -> Result<RagPipeline> {
568 let config =
569 self.config.ok_or_else(|| RagError::ConfigError("config is required".to_string()))?;
570 let embedding_provider = self
571 .embedding_provider
572 .ok_or_else(|| RagError::ConfigError("embedding_provider is required".to_string()))?;
573 let vector_store = self
574 .vector_store
575 .ok_or_else(|| RagError::ConfigError("vector_store is required".to_string()))?;
576 let chunker =
577 self.chunker.ok_or_else(|| RagError::ConfigError("chunker is required".to_string()))?;
578
579 Ok(RagPipeline {
580 config,
581 embedding_provider,
582 vector_store,
583 chunker,
584 reranker: self.reranker,
585 filterable: RwLock::new(HashMap::new()),
586 })
587 }
588}
589
590#[cfg(test)]
591mod tests {
592 use async_trait::async_trait;
593
594 use super::*;
595 use crate::chunking::FixedSizeChunker;
596 use crate::inmemory::InMemoryVectorStore;
597
598 struct ShortEmbedder;
600
601 #[async_trait]
602 impl EmbeddingProvider for ShortEmbedder {
603 async fn embed(&self, _text: &str) -> Result<Vec<f32>> {
604 Ok(vec![1.0, 0.0])
605 }
606
607 async fn embed_batch(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
608 Ok(vec![vec![1.0, 0.0]; texts.len().saturating_sub(1)])
609 }
610
611 fn dimensions(&self) -> usize {
612 2
613 }
614 }
615
616 struct LengthEmbedder;
618
619 #[async_trait]
620 impl EmbeddingProvider for LengthEmbedder {
621 async fn embed(&self, text: &str) -> Result<Vec<f32>> {
622 Ok(vec![text.len() as f32, 1.0])
623 }
624
625 fn dimensions(&self) -> usize {
626 2
627 }
628 }
629
630 fn pipeline(
631 embedder: Arc<dyn EmbeddingProvider>,
632 store: Arc<InMemoryVectorStore>,
633 ) -> RagPipeline {
634 RagPipeline::builder()
635 .config(RagConfig::default())
636 .embedding_provider(embedder)
637 .vector_store(store)
638 .chunker(Arc::new(FixedSizeChunker::try_new(4, 0).expect("valid sizes")))
639 .build()
640 .expect("build pipeline")
641 }
642
643 #[tokio::test]
644 async fn ingest_fails_when_embedder_returns_fewer_vectors_than_chunks() {
645 let store = Arc::new(InMemoryVectorStore::new());
646 let pipeline = pipeline(Arc::new(ShortEmbedder), store.clone());
647 pipeline.create_collection("docs").await.expect("create collection");
648
649 let document = Document::new("doc", "abcdefgh");
650 let scoped = pipeline.scoped(Scope::single_tenant());
651 let err = scoped.ingest("docs", &document).await.expect_err("short embedding batch");
652 assert!(
653 matches!(&err, RagError::PipelineError(message)
654 if message == "embedding provider returned 1 vectors for 2 chunks of document 'doc'"),
655 "unexpected error: {err}"
656 );
657
658 let stored = store.count("docs", &Scope::single_tenant(), None).await.expect("count");
659 assert_eq!(stored, 0, "no chunk may be stored without its embedding");
660 }
661
662 #[tokio::test]
663 async fn query_with_rejects_a_zero_top_k() {
664 let pipeline = pipeline(Arc::new(ShortEmbedder), Arc::new(InMemoryVectorStore::new()));
665 pipeline.create_collection("docs").await.expect("create collection");
666
667 let options = QueryOptions::new().with_top_k(0);
668 let err = pipeline
669 .scoped(Scope::single_tenant())
670 .query_with("docs", "query", &options)
671 .await
672 .expect_err("zero top_k");
673 assert!(matches!(err, RagError::ConfigError(_)), "unexpected error: {err}");
674 }
675
676 #[tokio::test]
677 async fn scopes_share_a_collection_without_sharing_chunks() {
678 let pipeline = pipeline(Arc::new(LengthEmbedder), Arc::new(InMemoryVectorStore::new()));
679 pipeline.create_collection("docs").await.expect("create collection");
680 let tenant_a = pipeline.scoped(Scope::from_parts(["app", "a"]).expect("scope"));
681 let tenant_b = pipeline.scoped(Scope::from_parts(["app", "b"]).expect("scope"));
682
683 tenant_a.ingest("docs", &Document::new("policy", "aaaa")).await.expect("ingest a");
685 tenant_b.ingest("docs", &Document::new("policy", "bbbbbbbb")).await.expect("ingest b");
686
687 let texts = |results: Vec<SearchResult>| -> Vec<String> {
688 results.into_iter().map(|r| r.chunk.text).collect()
689 };
690 assert_eq!(texts(tenant_a.query("docs", "q").await.expect("query a")), ["aaaa"]);
691 assert_eq!(texts(tenant_b.query("docs", "q").await.expect("query b")), ["bbbb", "bbbb"]);
692 assert_eq!(tenant_a.count("docs").await.expect("count a"), 1);
693 assert_eq!(tenant_b.count("docs").await.expect("count b"), 2);
694
695 assert_eq!(tenant_b.purge_scope("docs").await.expect("purge b"), 2);
696 assert_eq!(tenant_b.count("docs").await.expect("count b"), 0);
697 assert_eq!(tenant_a.count("docs").await.expect("count a"), 1, "a is untouched");
698 }
699
700 #[derive(Default)]
702 struct CountingEmbedder {
703 calls: std::sync::atomic::AtomicUsize,
704 }
705
706 #[async_trait]
707 impl EmbeddingProvider for CountingEmbedder {
708 async fn embed(&self, text: &str) -> Result<Vec<f32>> {
709 self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
710 Ok(vec![text.len() as f32, 1.0])
711 }
712
713 fn dimensions(&self) -> usize {
714 2
715 }
716 }
717
718 #[tokio::test]
719 async fn a_filter_on_an_undeclared_key_fails_before_any_io() {
720 let embedder = Arc::new(CountingEmbedder::default());
721 let pipeline = pipeline(embedder.clone(), Arc::new(InMemoryVectorStore::new()));
722 pipeline.create_collection_with_filterable("docs", ["lang"]).await.expect("create");
723 let rag = pipeline.scoped(Scope::single_tenant());
724
725 let undeclared = Filter::eq(Field::metadata("tier"), "gold");
726 let options = QueryOptions::new().with_filter(undeclared.clone());
727 let err = rag.query_with("docs", "q", &options).await.expect_err("undeclared key");
728 assert!(
729 matches!(&err, RagError::UnsupportedFilter(message) if message.contains("`tier`")),
730 "unexpected error: {err}"
731 );
732 assert!(matches!(
733 rag.delete_where("docs", &undeclared).await,
734 Err(RagError::UnsupportedFilter(_))
735 ));
736 assert!(matches!(
737 rag.count_where("unknown_collection", &Filter::eq(Field::metadata("lang"), "en")).await,
738 Err(RagError::UnsupportedFilter(_))
739 ));
740 assert_eq!(embedder.calls.load(std::sync::atomic::Ordering::SeqCst), 0);
741
742 let declared = QueryOptions::new().with_filter(Filter::eq(Field::metadata("lang"), "en"));
743 rag.query_with("docs", "q", &declared).await.expect("a declared key is accepted");
744 let built_in = QueryOptions::new().with_filter(Filter::eq(Field::DocumentId, "doc"));
745 rag.query_with("docs", "q", &built_in).await.expect("built-in fields need no declaration");
746 }
747
748 #[tokio::test]
749 async fn ingest_replaces_the_documents_chunks_in_its_scope() {
750 let pipeline = pipeline(Arc::new(LengthEmbedder), Arc::new(InMemoryVectorStore::new()));
751 pipeline.create_collection("docs").await.expect("create collection");
752 let rag = pipeline.scoped(Scope::new("tenant").expect("scope"));
753 let other = pipeline.scoped(Scope::new("other").expect("scope"));
754
755 rag.ingest("docs", &Document::new("policy", "aaaabbbbcccc")).await.expect("ingest v1");
756 other.ingest("docs", &Document::new("policy", "aaaabbbbcccc")).await.expect("ingest");
757 rag.ingest("docs", &Document::new("other_doc", "zzzz")).await.expect("ingest");
758 assert_eq!(rag.count("docs").await.expect("count"), 4);
759
760 let chunks = rag.ingest("docs", &Document::new("policy", "dddd")).await.expect("ingest v2");
762 assert_eq!(chunks.len(), 1);
763 let policy = Filter::eq(Field::DocumentId, "policy");
764 assert_eq!(rag.count_where("docs", &policy).await.expect("count"), 1);
765 let results = rag
766 .query_with("docs", "q", &QueryOptions::new().with_filter(policy.clone()))
767 .await
768 .expect("query");
769 assert_eq!(results.iter().map(|r| r.chunk.text.as_str()).collect::<Vec<_>>(), ["dddd"]);
770
771 rag.ingest("docs", &Document::new("policy", "")).await.expect("ingest empty");
773 assert_eq!(rag.count_where("docs", &policy).await.expect("count"), 0);
774 assert_eq!(rag.count("docs").await.expect("count"), 1);
775 assert_eq!(other.count_where("docs", &policy).await.expect("count"), 3);
776
777 assert_eq!(other.delete_document("docs", "policy").await.expect("delete"), 3);
778 assert_eq!(other.count("docs").await.expect("count"), 0);
779 assert_eq!(rag.count("docs").await.expect("count"), 1);
780 }
781}