Skip to main content

adk_rag/
pipeline.rs

1//! RAG pipeline orchestrator.
2//!
3//! The [`RagPipeline`] coordinates the full ingest-and-query workflow by
4//! composing an [`EmbeddingProvider`], a [`VectorStore`], a [`Chunker`],
5//! and an optional [`Reranker`].
6//!
7//! # Example
8//!
9//! ```rust,ignore
10//! use adk_rag::{RagPipeline, RagConfig, InMemoryVectorStore, FixedSizeChunker, Scope};
11//!
12//! let pipeline = RagPipeline::builder()
13//!     .config(RagConfig::default())
14//!     .embedding_provider(Arc::new(my_embedder))
15//!     .vector_store(Arc::new(InMemoryVectorStore::new()))
16//!     .chunker(Arc::new(FixedSizeChunker::new(512, 100)))
17//!     .build()?;
18//!
19//! pipeline.create_collection("docs").await?;
20//! let tenant = pipeline.scoped(Scope::from_parts(["support", "tenant-42"])?);
21//! tenant.ingest("docs", &document).await?;
22//! let results = tenant.query("docs", "search query").await?;
23//! ```
24
25use 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
41/// The RAG pipeline orchestrator.
42///
43/// Coordinates document ingestion (chunk → embed → store) and query
44/// execution (embed → search → rerank → filter). Construct one via
45/// [`RagPipeline::builder()`]. Ingest and query go through [`RagPipeline::scoped`], which
46/// binds them to one [`Scope`].
47pub 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 metadata keys of each collection this pipeline created.
54    filterable: RwLock<HashMap<String, BTreeSet<String>>>,
55}
56
57impl RagPipeline {
58    /// Create a new [`RagPipelineBuilder`].
59    pub fn builder() -> RagPipelineBuilder {
60        RagPipelineBuilder::default()
61    }
62
63    /// Return a reference to the pipeline configuration.
64    pub fn config(&self) -> &RagConfig {
65        &self.config
66    }
67
68    /// Return a reference to the embedding provider.
69    pub fn embedding_provider(&self) -> &Arc<dyn EmbeddingProvider> {
70        &self.embedding_provider
71    }
72
73    /// Return a reference to the vector store.
74    pub fn vector_store(&self) -> &Arc<dyn VectorStore> {
75        &self.vector_store
76    }
77
78    /// Create a named collection in the vector store.
79    ///
80    /// The collection is created with the dimensionality reported by the
81    /// configured [`EmbeddingProvider`].
82    ///
83    /// # Errors
84    ///
85    /// Returns [`RagError::PipelineError`] if the vector store operation fails.
86    pub async fn create_collection(&self, name: &str) -> Result<()> {
87        self.create_collection_with_filterable(name, Vec::<String>::new()).await
88    }
89
90    /// Create a named collection whose `filterable` metadata keys a [`Filter`] may name.
91    ///
92    /// The pipeline remembers the keys, and refuses a filter that names any other metadata
93    /// key with [`RagError::UnsupportedFilter`] before any I/O. Call this at startup for every
94    /// collection the pipeline filters, including one another process created: creation is
95    /// idempotent.
96    ///
97    /// # Example
98    ///
99    /// ```rust,ignore
100    /// pipeline.create_collection_with_filterable("docs", ["lang", "section"]).await?;
101    /// ```
102    ///
103    /// # Errors
104    ///
105    /// Returns [`RagError::PipelineError`] if the vector store operation fails, including
106    /// for a key outside the rule in [`CollectionSpec::with_filterable`].
107    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    /// Checks `filter`'s shape and that its metadata keys are declared on `collection`.
127    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    /// Delete a named collection from the vector store.
134    ///
135    /// # Errors
136    ///
137    /// Returns [`RagError::PipelineError`] if the vector store operation fails.
138    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    /// A view of the pipeline that ingests into, searches, and deletes from one scope.
148    ///
149    /// Every operation on stored chunks goes through a [`ScopedRag`], so none can read,
150    /// write, or delete across scopes. The scope comes from the application, such as the
151    /// authenticated tenant, never from a model.
152    ///
153    /// # Example
154    ///
155    /// ```rust,ignore
156    /// use adk_rag::Scope;
157    ///
158    /// let tenant = pipeline.scoped(Scope::from_parts(["support", tenant_id])?);
159    /// tenant.ingest("docs", &document).await?;
160    /// let results = tenant.query("docs", "refund window").await?;
161    /// ```
162    pub fn scoped(&self, scope: Scope) -> ScopedRag<'_> {
163        ScopedRag { pipeline: self, scope }
164    }
165}
166
167/// Options for [`ScopedRag::query_with`].
168///
169/// # Example
170///
171/// ```rust
172/// use adk_rag::QueryOptions;
173///
174/// use adk_rag::{Field, Filter};
175///
176/// let options = QueryOptions::new()
177///     .with_top_k(3)
178///     .with_filter(Filter::eq(Field::metadata("lang"), "en"));
179/// assert_eq!(options.top_k, Some(3));
180/// ```
181#[derive(Debug, Clone, Default, PartialEq, Eq)]
182#[non_exhaustive]
183pub struct QueryOptions {
184    /// The most results to retrieve; the pipeline's configured `top_k` when `None`.
185    pub top_k: Option<usize>,
186    /// Only chunks the filter matches are candidates.
187    pub filter: Option<Filter>,
188}
189
190impl QueryOptions {
191    /// Options that change nothing about the configured query.
192    pub fn new() -> Self {
193        Self::default()
194    }
195
196    /// Retrieves `top_k` results instead of the configured number.
197    #[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    /// Searches only the chunks `filter` matches; the vector store applies the filter before
204    /// the top `k` are chosen.
205    #[must_use]
206    pub fn with_filter(mut self, filter: Filter) -> Self {
207        self.filter = Some(filter);
208        self
209    }
210}
211
212/// A [`RagPipeline`] bound to one [`Scope`], from [`RagPipeline::scoped`].
213///
214/// Ingest writes the scope's chunks, queries search only the scope's chunks, and deletes
215/// remove only the scope's chunks.
216pub struct ScopedRag<'a> {
217    pipeline: &'a RagPipeline,
218    scope: Scope,
219}
220
221impl ScopedRag<'_> {
222    /// The scope every operation acts on.
223    pub fn scope(&self) -> &Scope {
224        &self.scope
225    }
226
227    /// Ingest a single document into the scope: chunk → embed → store, replacing the
228    /// document's earlier chunks.
229    ///
230    /// The new chunks are upserted first, then the document's chunks in the scope that the
231    /// new version no longer has are deleted, so a search never finds the document without
232    /// chunks and a shorter version leaves no stale chunks. A document with empty text
233    /// removes the document's chunks. Returns the chunks that were stored (with embeddings
234    /// attached).
235    ///
236    /// # Errors
237    ///
238    /// Returns [`RagError::PipelineError`] if embedding or storage fails, or if
239    /// the embedding provider returns a different number of vectors than there
240    /// are chunks, including the document ID in the error message.
241    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        // 1. Chunk the document
245        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        // 2. Collect chunk texts for batch embedding
253        let texts: Vec<&str> = chunks.iter().map(|c| c.text.as_str()).collect();
254
255        // 3. Generate embeddings
256        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        // 4. Attach embeddings to chunks. `zip` would silently drop the chunks
262        // left without a vector, so a count mismatch fails the ingest instead.
263        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        // 5. Upsert into the scope
282        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        // 6. Remove the document's chunks the new version no longer has
288        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    /// Ingest multiple documents into the scope through the chunk → embed → store workflow.
310    ///
311    /// Returns all chunks that were stored across all documents.
312    ///
313    /// # Errors
314    ///
315    /// Returns [`RagError::PipelineError`] on the first document that fails,
316    /// including the document ID in the error message.
317    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    /// Query the scope: embed → search → rerank → filter by threshold.
331    ///
332    /// Returns search results ordered by descending relevance score. Results
333    /// below the configured `similarity_threshold` are filtered out.
334    ///
335    /// # Errors
336    ///
337    /// Returns [`RagError::PipelineError`] if embedding or search fails.
338    pub async fn query(&self, collection: &str, query: &str) -> Result<Vec<SearchResult>> {
339        self.query_with(collection, query, &QueryOptions::new()).await
340    }
341
342    /// Query the scope as [`query`](Self::query) does, with `options` applied.
343    ///
344    /// The reranker and the similarity threshold apply as they do to [`query`](Self::query).
345    ///
346    /// # Example
347    ///
348    /// ```rust,ignore
349    /// use adk_rag::QueryOptions;
350    ///
351    /// let options = QueryOptions::new().with_top_k(3);
352    /// let results = pipeline.scoped(scope).query_with("docs", "refund window", &options).await?;
353    /// assert!(results.len() <= 3);
354    /// ```
355    ///
356    /// # Errors
357    ///
358    /// Returns [`RagError::ConfigError`] if `options.top_k` is 0,
359    /// [`RagError::UnsupportedFilter`] before any I/O if `options.filter` is malformed or
360    /// names a metadata key the collection did not declare, and [`RagError::PipelineError`]
361    /// if embedding, search, or reranking fails.
362    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        // 1. Embed the query
378        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        // 2. Search the scope
384        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        // 3. Rerank if a reranker is configured
398        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        // 4. Filter by similarity threshold
408        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    /// The number of chunks the scope holds in `collection`.
418    ///
419    /// # Errors
420    ///
421    /// Returns [`RagError::PipelineError`] if the vector store operation fails.
422    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    /// The number of the scope's chunks in `collection` that `filter` matches.
430    ///
431    /// # Errors
432    ///
433    /// Returns [`RagError::UnsupportedFilter`] before any I/O for a malformed filter or an
434    /// undeclared metadata key, and [`RagError::PipelineError`] if the vector store fails.
435    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    /// Delete the scope's chunks in `collection` that `filter` matches, returning how many
444    /// were deleted.
445    ///
446    /// Other scopes' chunks are untouched. [`purge_scope`](Self::purge_scope) deletes a
447    /// whole scope; an empty `And`, `Or`, or `In` is refused rather than read as "all".
448    ///
449    /// # Example
450    ///
451    /// ```rust,ignore
452    /// use adk_rag::{Field, Filter};
453    ///
454    /// let retired = Filter::eq(Field::metadata("status"), "retired");
455    /// let deleted = pipeline.scoped(scope).delete_where("docs", &retired).await?;
456    /// ```
457    ///
458    /// # Errors
459    ///
460    /// Returns [`RagError::UnsupportedFilter`] before any I/O for a malformed filter or an
461    /// undeclared metadata key, and [`RagError::PipelineError`] if the vector store fails.
462    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    /// Delete every chunk of `document_id` in the scope, returning how many were deleted.
480    ///
481    /// # Errors
482    ///
483    /// Returns [`RagError::PipelineError`] if the vector store fails.
484    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    /// Delete every chunk the scope holds in `collection`, returning how many it held.
489    ///
490    /// Other scopes' chunks in the collection are untouched.
491    ///
492    /// # Errors
493    ///
494    /// Returns [`RagError::PipelineError`] if the vector store operation fails.
495    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/// Builder for constructing a [`RagPipeline`].
507///
508/// All fields except `reranker` are required. Call [`build()`](RagPipelineBuilder::build)
509/// to validate and produce the pipeline.
510///
511/// # Example
512///
513/// ```rust,ignore
514/// let pipeline = RagPipeline::builder()
515///     .config(RagConfig::default())
516///     .embedding_provider(Arc::new(embedder))
517///     .vector_store(Arc::new(store))
518///     .chunker(Arc::new(chunker))
519///     .reranker(Arc::new(reranker))  // optional
520///     .build()?;
521/// ```
522#[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    /// Set the pipeline configuration.
533    pub fn config(mut self, config: RagConfig) -> Self {
534        self.config = Some(config);
535        self
536    }
537
538    /// Set the embedding provider.
539    pub fn embedding_provider(mut self, provider: Arc<dyn EmbeddingProvider>) -> Self {
540        self.embedding_provider = Some(provider);
541        self
542    }
543
544    /// Set the vector store backend.
545    pub fn vector_store(mut self, store: Arc<dyn VectorStore>) -> Self {
546        self.vector_store = Some(store);
547        self
548    }
549
550    /// Set the document chunker.
551    pub fn chunker(mut self, chunker: Arc<dyn Chunker>) -> Self {
552        self.chunker = Some(chunker);
553        self
554    }
555
556    /// Set an optional reranker for post-search result reordering.
557    pub fn reranker(mut self, reranker: Arc<dyn Reranker>) -> Self {
558        self.reranker = Some(reranker);
559        self
560    }
561
562    /// Build the [`RagPipeline`], validating that all required fields are set.
563    ///
564    /// # Errors
565    ///
566    /// Returns [`RagError::ConfigError`] if any required field is missing.
567    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    /// Returns one vector fewer than it was asked for.
599    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    /// Embeds a text as its byte length and 1.
617    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        // The same document ID in two scopes keeps two sets of chunks.
684        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    /// Counts embed calls, to show a refused filter costs no embedding.
701    #[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        // A shorter version leaves no stale chunks.
761        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        // An empty version removes the document; another document and scope are untouched.
772        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}