1use std::collections::BTreeSet;
4
5use serde::{Deserialize, Serialize};
6
7use crate::document::Chunk;
8use crate::error::{RagError, Result};
9
10pub const MAX_FIELD_LEN: usize = 64;
12
13#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25#[non_exhaustive]
26pub enum Field {
27 Metadata(String),
29 DocumentId,
31 SourceUri,
33 ChunkId,
35}
36
37impl Field {
38 pub fn metadata(key: impl Into<String>) -> Self {
40 Self::Metadata(key.into())
41 }
42
43 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(rename_all = "snake_case")]
89#[non_exhaustive]
90pub enum Filter {
91 Eq(Field, String),
93 In(Field, Vec<String>),
95 Exists(Field),
97 And(Vec<Filter>),
99 Or(Vec<Filter>),
101 Not(Box<Filter>),
103}
104
105impl Filter {
106 pub fn eq(field: Field, value: impl Into<String>) -> Self {
108 Self::Eq(field, value.into())
109 }
110
111 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 pub fn exists(field: Field) -> Self {
122 Self::Exists(field)
123 }
124
125 pub fn and(filters: impl IntoIterator<Item = Filter>) -> Self {
127 Self::And(filters.into_iter().collect())
128 }
129
130 pub fn or(filters: impl IntoIterator<Item = Filter>) -> Self {
132 Self::Or(filters.into_iter().collect())
133 }
134
135 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 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 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 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
215impl std::ops::Not for Filter {
217 type Output = Filter;
218
219 fn not(self) -> Filter {
220 Filter::Not(Box::new(self))
221 }
222}
223
224pub(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}