Skip to main content

adk_rag/
subject.rs

1//! A vector store as a [`SubjectDataStore`] for `adk_core::subject::SubjectRights`.
2
3use std::sync::Arc;
4
5use adk_core::subject::{StoreErasure, StoreSupport, SubjectDataStore, SubjectScope};
6use async_trait::async_trait;
7use serde_json::{Value, json};
8
9use crate::filter::{Field, Filter};
10use crate::scope::Scope;
11use crate::vectorstore::VectorStore;
12
13/// The metadata key that names the data subject a chunk is about. Declare it filterable on
14/// the collection ([`CollectionSpec::with_filterable`](crate::CollectionSpec::with_filterable))
15/// and set it to the subject's user id on every document ingested about a person.
16pub const SUBJECT_METADATA_KEY: &str = "adk_subject";
17
18/// Where a store keeps a subject's chunks.
19#[derive(Debug, Clone, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum SubjectPartition {
22    /// In the listed scopes, tagged with [`SUBJECT_METADATA_KEY`]; erasure deletes the
23    /// tagged chunks with [`VectorStore::delete_where`].
24    Tagged {
25        /// The scopes searched for the subject's chunks.
26        scopes: Vec<Scope>,
27    },
28    /// In a scope of their own, `Scope::from_parts([app, user])`; erasure purges the scope
29    /// with [`VectorStore::purge_scope`].
30    ScopePerUser,
31}
32
33/// Exports and erases a data subject's chunks in the listed collections of a
34/// [`VectorStore`].
35///
36/// | Partition | Finds the subject's chunks | Erases them with |
37/// |-----------|----------------------------|------------------|
38/// | [`Tagged`](SubjectPartition::Tagged) | `adk_subject` metadata equal to a user id of the scope, in each listed scope | `delete_where` |
39/// | [`ScopePerUser`](SubjectPartition::ScopePerUser) | The scope `[app, user]` of each application and user id of the scope | `purge_scope` |
40///
41/// The vector store trait lists no chunk text, so the export names each collection and
42/// scope with the number of the subject's chunks it holds. A backend whose deletes complete
43/// later, or keep earlier table versions, declares it with
44/// [`with_support`](Self::with_support).
45///
46/// # Example
47///
48/// ```rust
49/// use std::sync::Arc;
50/// use adk_core::principal::SubjectRef;
51/// use adk_core::subject::{SubjectDataStore, SubjectScope};
52/// use adk_rag::{
53///     Chunk, CollectionSpec, InMemoryVectorStore, RagSubjectData, SUBJECT_METADATA_KEY, Scope,
54///     SubjectPartition, VectorStore,
55/// };
56///
57/// # #[tokio::main(flavor = "current_thread")]
58/// # async fn main() -> adk_core::Result<()> {
59/// let store = Arc::new(InMemoryVectorStore::new());
60/// let spec = CollectionSpec::new(2).with_filterable([SUBJECT_METADATA_KEY]);
61/// store.create_collection("support_notes", &spec).await?;
62/// let note = Chunk::new("n1", "ticket-7", "Prefers email.")
63///     .with_embedding(vec![1.0, 0.0])
64///     .with_metadata(SUBJECT_METADATA_KEY, "alice");
65/// store.upsert("support_notes", &Scope::single_tenant(), &[note]).await?;
66///
67/// let chunks = RagSubjectData::new(
68///     store,
69///     ["support_notes"],
70///     SubjectPartition::Tagged { scopes: vec![Scope::single_tenant()] },
71/// );
72/// let erased = chunks.erase(&SubjectScope::new(["shop"], SubjectRef::human("alice"))).await?;
73/// assert_eq!(erased.deleted, 1);
74/// # Ok(())
75/// # }
76/// ```
77pub struct RagSubjectData {
78    store: Arc<dyn VectorStore>,
79    collections: Vec<String>,
80    partition: SubjectPartition,
81    support: StoreSupport,
82}
83
84impl RagSubjectData {
85    /// The subject's chunks in `collections` of `store`, kept as `partition` says.
86    pub fn new<I, S>(
87        store: Arc<dyn VectorStore>,
88        collections: I,
89        partition: SubjectPartition,
90    ) -> Self
91    where
92        I: IntoIterator<Item = S>,
93        S: Into<String>,
94    {
95        Self {
96            store,
97            collections: collections.into_iter().map(Into::into).collect(),
98            partition,
99            support: StoreSupport::Hard,
100        }
101    }
102
103    /// Declares how the store erases, such as [`StoreSupport::Eventual`] for a managed
104    /// service whose deletes complete later.
105    #[must_use]
106    pub fn with_support(mut self, support: StoreSupport) -> Self {
107        self.support = support;
108        self
109    }
110
111    /// Each `(scope, filter)` that holds the subject's chunks: the filter is `None` for a
112    /// scope that is the subject's own.
113    fn targets(&self, subject: &SubjectScope) -> adk_core::Result<Vec<(Scope, Option<Filter>)>> {
114        match &self.partition {
115            SubjectPartition::Tagged { scopes } => {
116                let ids: Vec<String> = subject.user_ids().into_iter().map(str::to_owned).collect();
117                let tagged = Filter::In(Field::metadata(SUBJECT_METADATA_KEY), ids);
118                Ok(scopes.iter().map(|scope| (scope.clone(), Some(tagged.clone()))).collect())
119            }
120            SubjectPartition::ScopePerUser => {
121                let mut targets = Vec::new();
122                for app_name in &subject.app_names {
123                    for user_id in subject.user_ids() {
124                        targets.push((Scope::from_parts([app_name.as_str(), user_id])?, None));
125                    }
126                }
127                Ok(targets)
128            }
129        }
130    }
131}
132
133impl std::fmt::Debug for RagSubjectData {
134    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135        f.debug_struct("RagSubjectData")
136            .field("collections", &self.collections)
137            .field("partition", &self.partition)
138            .finish_non_exhaustive()
139    }
140}
141
142#[async_trait]
143impl SubjectDataStore for RagSubjectData {
144    fn name(&self) -> &str {
145        "rag"
146    }
147
148    fn support(&self) -> StoreSupport {
149        self.support
150    }
151
152    async fn export(&self, subject: &SubjectScope) -> adk_core::Result<Value> {
153        let mut held = Vec::new();
154        for collection in &self.collections {
155            for (scope, filter) in self.targets(subject)? {
156                let chunks = self.store.count(collection, &scope, filter.as_ref()).await?;
157                if chunks > 0 {
158                    held.push(json!({
159                        "collection": collection,
160                        "scope": scope.as_str(),
161                        "chunks": chunks,
162                    }));
163                }
164            }
165        }
166        Ok(json!({ "collections": held }))
167    }
168
169    async fn erase(&self, subject: &SubjectScope) -> adk_core::Result<StoreErasure> {
170        let mut deleted = 0;
171        for collection in &self.collections {
172            for (scope, filter) in self.targets(subject)? {
173                deleted += match &filter {
174                    Some(filter) => self.store.delete_where(collection, &scope, filter).await?,
175                    None => self.store.purge_scope(collection, &scope).await?,
176                };
177            }
178        }
179        Ok(StoreErasure::deleted(deleted))
180    }
181}