Skip to main content

adk_rag/
filter.rs

1//! Portable filters over stored chunks.
2
3use std::collections::BTreeSet;
4
5use serde::{Deserialize, Serialize};
6
7use crate::document::Chunk;
8use crate::error::{RagError, Result};
9
10/// The longest metadata key a filter can name, in bytes.
11pub const MAX_FIELD_LEN: usize = 64;
12
13/// A chunk field a [`Filter`] tests.
14///
15/// # Example
16///
17/// ```rust
18/// use adk_rag::Field;
19///
20/// let section = Field::metadata("section");
21/// assert_eq!(section, Field::Metadata("section".to_string()));
22/// ```
23#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25#[non_exhaustive]
26pub enum Field {
27    /// A metadata entry. Its key must be declared filterable on the collection.
28    Metadata(String),
29    /// The chunk's document ID, which every chunk has.
30    DocumentId,
31    /// The chunk's source URI, which a chunk may lack.
32    SourceUri,
33    /// The chunk ID, which every chunk has.
34    ChunkId,
35}
36
37impl Field {
38    /// The metadata entry named `key`.
39    pub fn metadata(key: impl Into<String>) -> Self {
40        Self::Metadata(key.into())
41    }
42
43    /// Whether every chunk has this field.
44    #[cfg(feature = "agent-retrieval")]
45    pub(crate) fn always_present(&self) -> bool {
46        match self {
47            Self::DocumentId | Self::ChunkId => true,
48            Self::Metadata(_) | Self::SourceUri => false,
49        }
50    }
51
52    fn value<'a>(&self, chunk: &'a Chunk) -> Option<&'a str> {
53        match self {
54            Self::Metadata(key) => chunk.metadata.get(key).map(String::as_str),
55            Self::DocumentId => Some(&chunk.document_id),
56            Self::SourceUri => chunk.source_uri.as_deref(),
57            Self::ChunkId => Some(&chunk.id),
58        }
59    }
60}
61
62/// A predicate over stored chunks, applied inside the vector store.
63///
64/// Every backend compiles a filter into its own query language with bound parameters or
65/// typed expressions and applies it with the scope before the top `k` are chosen, so a
66/// filtered search returns the nearest matching chunks rather than the matching part of the
67/// global nearest. A backend that cannot express a filter fails with
68/// [`RagError::UnsupportedFilter`] before any I/O; it never ignores a predicate or applies
69/// part of one.
70///
71/// Values are strings. A field a chunk lacks matches no `Eq` or `In` and fails `Exists`, so
72/// `Not(Eq(field, value))` matches chunks without the field.
73///
74/// # Example
75///
76/// ```rust
77/// use adk_rag::{Chunk, Field, Filter};
78///
79/// let filter = Filter::and([
80///     Filter::eq(Field::metadata("lang"), "en"),
81///     !Filter::is_in(Field::DocumentId, ["draft-1", "draft-2"]),
82/// ]);
83///
84/// let chunk = Chunk::new("guide_0", "guide", "text").with_metadata("lang", "en");
85/// assert!(filter.matches(&chunk));
86/// ```
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(rename_all = "snake_case")]
89#[non_exhaustive]
90pub enum Filter {
91    /// The field is present and equals the value.
92    Eq(Field, String),
93    /// The field is present and equals one of the values. The list is not empty.
94    In(Field, Vec<String>),
95    /// The field is present.
96    Exists(Field),
97    /// Every filter matches. The list is not empty.
98    And(Vec<Filter>),
99    /// At least one filter matches. The list is not empty.
100    Or(Vec<Filter>),
101    /// The filter does not match.
102    Not(Box<Filter>),
103}
104
105impl Filter {
106    /// Matches chunks whose `field` equals `value`.
107    pub fn eq(field: Field, value: impl Into<String>) -> Self {
108        Self::Eq(field, value.into())
109    }
110
111    /// Matches chunks whose `field` equals one of `values`.
112    pub fn is_in<I, S>(field: Field, values: I) -> Self
113    where
114        I: IntoIterator<Item = S>,
115        S: Into<String>,
116    {
117        Self::In(field, values.into_iter().map(Into::into).collect())
118    }
119
120    /// Matches chunks that have `field`.
121    pub fn exists(field: Field) -> Self {
122        Self::Exists(field)
123    }
124
125    /// Matches chunks every filter matches.
126    pub fn and(filters: impl IntoIterator<Item = Filter>) -> Self {
127        Self::And(filters.into_iter().collect())
128    }
129
130    /// Matches chunks at least one filter matches.
131    pub fn or(filters: impl IntoIterator<Item = Filter>) -> Self {
132        Self::Or(filters.into_iter().collect())
133    }
134
135    /// Whether `chunk` matches, by the semantics every backend implements.
136    ///
137    /// The in-memory store searches with this evaluator, and the shared contract compares
138    /// every other backend against it.
139    pub fn matches(&self, chunk: &Chunk) -> bool {
140        match self {
141            Self::Eq(field, value) => field.value(chunk) == Some(value.as_str()),
142            Self::In(field, values) => {
143                field.value(chunk).is_some_and(|actual| values.iter().any(|v| v == actual))
144            }
145            Self::Exists(field) => field.value(chunk).is_some(),
146            Self::And(filters) => filters.iter().all(|filter| filter.matches(chunk)),
147            Self::Or(filters) => filters.iter().any(|filter| filter.matches(chunk)),
148            Self::Not(filter) => !filter.matches(chunk),
149        }
150    }
151
152    /// Checks the filter's shape: every `And`, `Or`, and `In` list is non-empty, and every
153    /// metadata key is 1 to [`MAX_FIELD_LEN`] ASCII letters, digits, and underscores,
154    /// starting with a letter or underscore.
155    ///
156    /// # Errors
157    ///
158    /// Returns [`RagError::UnsupportedFilter`] naming the first violation.
159    pub fn validate(&self) -> Result<()> {
160        match self {
161            Self::Eq(field, _) | Self::Exists(field) => validate_field(field),
162            Self::In(field, values) => {
163                if values.is_empty() {
164                    return Err(unsupported("an `In` filter needs at least one value"));
165                }
166                validate_field(field)
167            }
168            Self::And(filters) | Self::Or(filters) => {
169                if filters.is_empty() {
170                    return Err(unsupported("an `And` or `Or` filter needs at least one filter"));
171                }
172                filters.iter().try_for_each(Filter::validate)
173            }
174            Self::Not(filter) => filter.validate(),
175        }
176    }
177
178    /// Checks the filter's shape and that every metadata key it names is in `filterable`.
179    ///
180    /// # Errors
181    ///
182    /// Returns [`RagError::UnsupportedFilter`] for a malformed filter or an undeclared key.
183    pub fn validate_declared(&self, collection: &str, filterable: &BTreeSet<String>) -> Result<()> {
184        self.validate()?;
185        let mut undeclared = None;
186        self.visit_fields(&mut |field| {
187            if let Field::Metadata(key) = field
188                && !filterable.contains(key)
189                && undeclared.is_none()
190            {
191                undeclared = Some(key.clone());
192            }
193        });
194        match undeclared {
195            Some(key) => Err(unsupported(&format!(
196                "metadata key `{key}` is not declared filterable on collection '{collection}'; \
197                 create the collection with it in `CollectionSpec::with_filterable`"
198            ))),
199            None => Ok(()),
200        }
201    }
202
203    /// Calls `visit` with every field the filter names.
204    pub(crate) fn visit_fields(&self, visit: &mut impl FnMut(&Field)) {
205        match self {
206            Self::Eq(field, _) | Self::In(field, _) | Self::Exists(field) => visit(field),
207            Self::And(filters) | Self::Or(filters) => {
208                filters.iter().for_each(|filter| filter.visit_fields(visit));
209            }
210            Self::Not(filter) => filter.visit_fields(visit),
211        }
212    }
213}
214
215/// `!filter` matches chunks `filter` does not match.
216impl std::ops::Not for Filter {
217    type Output = Filter;
218
219    fn not(self) -> Filter {
220        Filter::Not(Box::new(self))
221    }
222}
223
224/// Checks a metadata key against the rule every backend can store as a column or field name.
225pub(crate) fn validate_field_name(key: &str) -> Result<()> {
226    let valid = !key.is_empty()
227        && key.len() <= MAX_FIELD_LEN
228        && key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
229        && !key.starts_with(|c: char| c.is_ascii_digit());
230    if valid {
231        Ok(())
232    } else {
233        Err(unsupported(&format!(
234            "metadata key `{key}` cannot be filtered: use 1 to {MAX_FIELD_LEN} ASCII letters, \
235             digits, or underscores, starting with a letter or underscore"
236        )))
237    }
238}
239
240fn validate_field(field: &Field) -> Result<()> {
241    match field {
242        Field::Metadata(key) => validate_field_name(key),
243        Field::DocumentId | Field::SourceUri | Field::ChunkId => Ok(()),
244    }
245}
246
247fn unsupported(reason: &str) -> RagError {
248    RagError::UnsupportedFilter(reason.to_string())
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    fn chunk() -> Chunk {
256        Chunk::new("doc_0", "doc", "text").with_metadata("lang", "en")
257    }
258
259    #[test]
260    fn a_missing_field_matches_no_comparison_and_its_negation_matches() {
261        let chunk = chunk();
262        let tier = Field::metadata("tier");
263        assert!(!Filter::eq(tier.clone(), "gold").matches(&chunk));
264        assert!(!Filter::is_in(tier.clone(), ["gold"]).matches(&chunk));
265        assert!(!Filter::exists(tier.clone()).matches(&chunk));
266        assert!((!Filter::eq(tier, "gold")).matches(&chunk));
267        assert!(!Filter::exists(Field::SourceUri).matches(&chunk));
268        assert!(Filter::exists(Field::ChunkId).matches(&chunk));
269    }
270
271    #[test]
272    fn combinators_follow_boolean_logic() {
273        let chunk = chunk();
274        let en = Filter::eq(Field::metadata("lang"), "en");
275        let fr = Filter::eq(Field::metadata("lang"), "fr");
276        assert!(Filter::and([en.clone(), Filter::eq(Field::DocumentId, "doc")]).matches(&chunk));
277        assert!(!Filter::and([en.clone(), fr.clone()]).matches(&chunk));
278        assert!(Filter::or([fr.clone(), en.clone()]).matches(&chunk));
279        assert!(Filter::is_in(Field::ChunkId, ["doc_1", "doc_0"]).matches(&chunk));
280        assert!(!(!en).matches(&chunk));
281    }
282
283    #[test]
284    fn validate_rejects_empty_lists_and_unstorable_keys() {
285        let rejected = [
286            Filter::and([]),
287            Filter::or([]),
288            Filter::is_in(Field::DocumentId, Vec::<String>::new()),
289            Filter::eq(Field::metadata(""), "x"),
290            Filter::eq(Field::metadata("a.b"), "x"),
291            Filter::eq(Field::metadata("9lives"), "x"),
292            Filter::eq(Field::metadata("x".repeat(MAX_FIELD_LEN + 1)), "x"),
293            !Filter::and([Filter::exists(Field::metadata("a-b"))]),
294        ];
295        for filter in rejected {
296            assert!(
297                matches!(filter.validate(), Err(RagError::UnsupportedFilter(_))),
298                "{filter:?} is accepted"
299            );
300        }
301        Filter::eq(Field::metadata("_tenant_2"), "x").validate().expect("valid key");
302    }
303
304    #[test]
305    fn validate_declared_names_the_undeclared_key() {
306        let declared = BTreeSet::from(["lang".to_string()]);
307        let filter = Filter::and([
308            Filter::eq(Field::metadata("lang"), "en"),
309            Filter::eq(Field::metadata("tier"), "gold"),
310            Filter::eq(Field::DocumentId, "doc"),
311        ]);
312        let error = filter.validate_declared("docs", &declared).expect_err("undeclared");
313        assert!(error.to_string().contains("`tier` is not declared"), "{error}");
314        Filter::eq(Field::SourceUri, "x").validate_declared("docs", &BTreeSet::new()).unwrap();
315    }
316
317    #[test]
318    fn filters_round_trip_through_json() {
319        let filter = Filter::or([
320            Filter::eq(Field::metadata("lang"), "en"),
321            !Filter::exists(Field::SourceUri),
322        ]);
323        let json = serde_json::to_value(&filter).unwrap();
324        assert_eq!(
325            json,
326            serde_json::json!({ "or": [
327                { "eq": [{ "metadata": "lang" }, "en"] },
328                { "not": { "exists": "source_uri" } },
329            ]})
330        );
331        assert_eq!(serde_json::from_value::<Filter>(json).unwrap(), filter);
332    }
333}