Skip to main content

adk_rag/
scope.rs

1//! The partition key every vector store operation names.
2
3use std::fmt;
4
5use serde::{Deserialize, Serialize};
6
7use crate::error::{RagError, Result};
8
9/// The partition a vector store operation reads, writes, or deletes.
10///
11/// Every [`VectorStore`](crate::VectorStore) operation names a scope, and a stored chunk is
12/// identified by its collection, its scope, and its chunk ID together. Two tenants that
13/// share a collection and ingest the same document ID keep separate chunks, and a search in
14/// one scope never returns another scope's chunks: the scope is applied inside the backend's
15/// search, before the top `k` are chosen.
16///
17/// A scope is an opaque key of 1 to [`Scope::MAX_LEN`] bytes without control characters.
18/// [`Scope::from_parts`] builds one from several parts, such as an application and a
19/// tenant, and [`Scope::single_tenant`] is the scope of an application with one tenant.
20///
21/// # Example
22///
23/// ```rust
24/// use adk_rag::Scope;
25///
26/// let tenant = Scope::from_parts(["support-app", "tenant/42"])?;
27/// assert_eq!(tenant.as_str(), "support-app/tenant%2F42");
28///
29/// let raw = Scope::new("org-7")?;
30/// assert_eq!(raw.to_string(), "org-7");
31/// assert!(Scope::new("").is_err());
32/// # Ok::<(), adk_rag::RagError>(())
33/// ```
34#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
35#[serde(try_from = "String", into = "String")]
36pub struct Scope(String);
37
38impl Scope {
39    /// The longest scope key, in bytes.
40    pub const MAX_LEN: usize = 256;
41
42    /// The key of [`Scope::single_tenant`]. [`Scope::from_parts`] never produces it, because
43    /// it percent-encodes `:`.
44    pub const SINGLE_TENANT_KEY: &'static str = ":single-tenant";
45
46    /// Creates a scope from an opaque key.
47    ///
48    /// # Errors
49    ///
50    /// Returns [`RagError::InvalidScope`] when `key` is empty, longer than
51    /// [`Scope::MAX_LEN`] bytes, or contains a control character.
52    pub fn new(key: impl Into<String>) -> Result<Self> {
53        let key = key.into();
54        if key.is_empty() || key.len() > Self::MAX_LEN {
55            return Err(RagError::InvalidScope(format!(
56                "a scope key is 1 to {} bytes, got {}",
57                Self::MAX_LEN,
58                key.len()
59            )));
60        }
61        if key.chars().any(char::is_control) {
62            return Err(RagError::InvalidScope(
63                "a scope key contains no control characters".to_string(),
64            ));
65        }
66        Ok(Self(key))
67    }
68
69    /// Creates a scope from several parts, such as an application and a tenant.
70    ///
71    /// Each part is percent-encoded, leaving only ASCII letters, digits, `-`, `.`, `_`, and
72    /// `~` as they are, and the parts are joined with `/`. Distinct part lists therefore
73    /// always give distinct scopes.
74    ///
75    /// # Example
76    ///
77    /// ```rust
78    /// use adk_rag::Scope;
79    ///
80    /// let a = Scope::from_parts(["app", "a/b"])?;
81    /// let b = Scope::from_parts(["app", "a", "b"])?;
82    /// assert_ne!(a, b);
83    /// # Ok::<(), adk_rag::RagError>(())
84    /// ```
85    ///
86    /// # Errors
87    ///
88    /// Returns [`RagError::InvalidScope`] when there are no parts, a part is empty, or the
89    /// encoded key is longer than [`Scope::MAX_LEN`] bytes.
90    pub fn from_parts<I, S>(parts: I) -> Result<Self>
91    where
92        I: IntoIterator<Item = S>,
93        S: AsRef<str>,
94    {
95        let mut key = String::new();
96        for (index, part) in parts.into_iter().enumerate() {
97            let part = part.as_ref();
98            if part.is_empty() {
99                return Err(RagError::InvalidScope(format!("scope part {index} is empty")));
100            }
101            if index > 0 {
102                key.push('/');
103            }
104            for byte in part.bytes() {
105                if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
106                    key.push(char::from(byte));
107                } else {
108                    key.push_str(&format!("%{byte:02X}"));
109                }
110            }
111        }
112        if key.is_empty() {
113            return Err(RagError::InvalidScope("a scope needs at least one part".to_string()));
114        }
115        Self::new(key)
116    }
117
118    /// The scope of an application with a single tenant.
119    ///
120    /// Its key is [`Scope::SINGLE_TENANT_KEY`]. pgvector assigns it to rows stored before
121    /// scopes existed.
122    pub fn single_tenant() -> Self {
123        Self(Self::SINGLE_TENANT_KEY.to_string())
124    }
125
126    /// The scope key.
127    pub fn as_str(&self) -> &str {
128        &self.0
129    }
130
131    /// A key that identifies `chunk_id` within this scope, for backends that address a record
132    /// by one string.
133    ///
134    /// The key length-prefixes the scope, so distinct scope and chunk ID pairs never share a
135    /// key.
136    #[cfg(any(feature = "qdrant", feature = "agent-retrieval"))]
137    pub(crate) fn record_key(&self, chunk_id: &str) -> String {
138        format!("{}:{}{chunk_id}", self.0.len(), self.0)
139    }
140}
141
142impl fmt::Display for Scope {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        f.write_str(&self.0)
145    }
146}
147
148impl TryFrom<String> for Scope {
149    type Error = RagError;
150
151    fn try_from(key: String) -> Result<Self> {
152        Self::new(key)
153    }
154}
155
156impl From<Scope> for String {
157    fn from(scope: Scope) -> Self {
158        scope.0
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn new_rejects_empty_long_and_control_keys() {
168        for key in [String::new(), "x".repeat(Scope::MAX_LEN + 1), "a\nb".into(), "a\0b".into()] {
169            assert!(
170                matches!(Scope::new(key.clone()), Err(RagError::InvalidScope(_))),
171                "{key:?} is accepted"
172            );
173        }
174        assert_eq!(
175            Scope::new("x".repeat(Scope::MAX_LEN)).map(|s| s.as_str().len()).ok(),
176            Some(256)
177        );
178    }
179
180    #[test]
181    fn from_parts_is_injective_and_never_yields_the_single_tenant_key() {
182        let lists: [&[&str]; 6] =
183            [&["a", "b"], &["a/b"], &["a%2Fb"], &["a", "b", "c"], &[":single-tenant"], &["a b"]];
184        let keys: Vec<String> = lists
185            .iter()
186            .map(|parts| Scope::from_parts(parts.iter()).expect("valid parts").0)
187            .collect();
188        assert_eq!(
189            keys,
190            ["a/b", "a%2Fb", "a%252Fb", "a/b/c", "%3Asingle-tenant", "a%20b"].map(String::from)
191        );
192        assert!(Scope::from_parts(Vec::<&str>::new()).is_err());
193        assert!(Scope::from_parts(["app", ""]).is_err());
194    }
195
196    #[cfg(any(feature = "qdrant", feature = "agent-retrieval"))]
197    #[test]
198    fn record_keys_of_distinct_pairs_differ() {
199        let ab = Scope::new("ab").unwrap();
200        let a = Scope::new("a").unwrap();
201        assert_ne!(ab.record_key("c"), a.record_key("bc"));
202        assert_eq!(ab.record_key("c"), "2:abc");
203    }
204
205    #[test]
206    fn serde_round_trips_and_validates() {
207        let scope = Scope::from_parts(["app", "t1"]).unwrap();
208        let json = serde_json::to_string(&scope).unwrap();
209        assert_eq!(json, "\"app/t1\"");
210        assert_eq!(serde_json::from_str::<Scope>(&json).unwrap(), scope);
211        assert!(serde_json::from_str::<Scope>("\"\"").is_err());
212    }
213}