Skip to main content

chroma_types/
metadata.rs

1use chroma_error::{ChromaError, ErrorCodes};
2use itertools::Itertools;
3use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer};
4use serde_json::{Number, Value};
5use sprs::CsVec;
6use std::{
7    cmp::Ordering,
8    collections::{HashMap, HashSet},
9    mem::size_of_val,
10    ops::{BitAnd, BitOr},
11};
12use thiserror::Error;
13
14use crate::chroma_proto;
15
16#[cfg(feature = "pyo3")]
17use pyo3::types::{PyAnyMethods, PyDictMethods};
18
19#[cfg(feature = "testing")]
20use proptest::prelude::*;
21
22#[derive(Serialize, Deserialize)]
23struct SparseVectorSerdeHelper {
24    #[serde(rename = "#type")]
25    type_tag: Option<String>,
26    indices: Vec<u32>,
27    values: Vec<f32>,
28    tokens: Option<Vec<String>>,
29}
30
31/// Represents a sparse vector using parallel arrays for indices and values.
32///
33/// On deserialization: accepts both old format `{"indices": [...], "values": [...]}`
34/// and new format `{"#type": "sparse_vector", "indices": [...], "values": [...]}`.
35///
36/// On serialization: always includes `#type` field with value `"sparse_vector"`.
37#[derive(Clone, Debug, PartialEq)]
38#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
39pub struct SparseVector {
40    /// Dimension indices
41    pub indices: Vec<u32>,
42    /// Values corresponding to each index
43    pub values: Vec<f32>,
44    /// Tokens corresponding to each index
45    pub tokens: Option<Vec<String>>,
46}
47
48// Custom deserializer: accept both old and new formats
49impl<'de> Deserialize<'de> for SparseVector {
50    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
51    where
52        D: Deserializer<'de>,
53    {
54        let helper = SparseVectorSerdeHelper::deserialize(deserializer)?;
55
56        // If #type is present, validate it
57        if let Some(type_tag) = &helper.type_tag {
58            if type_tag != "sparse_vector" {
59                return Err(serde::de::Error::custom(format!(
60                    "Expected #type='sparse_vector', got '{}'",
61                    type_tag
62                )));
63            }
64        }
65
66        Ok(SparseVector {
67            indices: helper.indices,
68            values: helper.values,
69            tokens: helper.tokens,
70        })
71    }
72}
73
74// Custom serializer: always include #type field
75impl Serialize for SparseVector {
76    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
77    where
78        S: Serializer,
79    {
80        let helper = SparseVectorSerdeHelper {
81            type_tag: Some("sparse_vector".to_string()),
82            indices: self.indices.clone(),
83            values: self.values.clone(),
84            tokens: self.tokens.clone(),
85        };
86        helper.serialize(serializer)
87    }
88}
89
90/// Length mismatch between indices, values, and tokens in a sparse vector.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub struct SparseVectorLengthMismatch;
93
94impl std::fmt::Display for SparseVectorLengthMismatch {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        write!(
97            f,
98            "Sparse vector indices, values, and tokens (when present) must have the same length"
99        )
100    }
101}
102
103impl std::error::Error for SparseVectorLengthMismatch {}
104
105impl ChromaError for SparseVectorLengthMismatch {
106    fn code(&self) -> ErrorCodes {
107        ErrorCodes::InvalidArgument
108    }
109}
110
111impl SparseVector {
112    /// Create a new sparse vector from parallel arrays.
113    pub fn new(indices: Vec<u32>, values: Vec<f32>) -> Result<Self, SparseVectorLengthMismatch> {
114        if indices.len() != values.len() {
115            return Err(SparseVectorLengthMismatch);
116        }
117        Ok(Self {
118            indices,
119            values,
120            tokens: None,
121        })
122    }
123
124    /// Create a new sparse vector from parallel arrays.
125    pub fn new_with_tokens(
126        indices: Vec<u32>,
127        values: Vec<f32>,
128        tokens: Vec<String>,
129    ) -> Result<Self, SparseVectorLengthMismatch> {
130        if indices.len() != values.len() {
131            return Err(SparseVectorLengthMismatch);
132        }
133        if tokens.len() != indices.len() {
134            return Err(SparseVectorLengthMismatch);
135        }
136        Ok(Self {
137            indices,
138            values,
139            tokens: Some(tokens),
140        })
141    }
142
143    /// Create a sparse vector from an iterator of (index, value) pairs.
144    pub fn from_pairs(pairs: impl IntoIterator<Item = (u32, f32)>) -> Self {
145        let mut indices = vec![];
146        let mut values = vec![];
147        for (index, value) in pairs {
148            indices.push(index);
149            values.push(value);
150        }
151        let tokens = None;
152        Self {
153            indices,
154            values,
155            tokens,
156        }
157    }
158
159    /// Create a sparse vector from an iterator of (string, index, value) pairs.
160    pub fn from_triples(triples: impl IntoIterator<Item = (String, u32, f32)>) -> Self {
161        let mut tokens = vec![];
162        let mut indices = vec![];
163        let mut values = vec![];
164        for (token, index, value) in triples {
165            tokens.push(token);
166            indices.push(index);
167            values.push(value);
168        }
169        let tokens = Some(tokens);
170        Self {
171            indices,
172            values,
173            tokens,
174        }
175    }
176
177    /// Iterate over (index, value) pairs.
178    pub fn iter(&self) -> impl Iterator<Item = (u32, f32)> + '_ {
179        self.indices
180            .iter()
181            .copied()
182            .zip(self.values.iter().copied())
183    }
184
185    /// Validate the sparse vector
186    pub fn validate(&self) -> Result<(), MetadataValueConversionError> {
187        // Check that indices and values have the same length
188        if self.indices.len() != self.values.len() {
189            return Err(MetadataValueConversionError::SparseVectorLengthMismatch);
190        }
191
192        // Check that tokens (if present) align with indices
193        if let Some(tokens) = self.tokens.as_ref() {
194            if tokens.len() != self.indices.len() {
195                return Err(MetadataValueConversionError::SparseVectorLengthMismatch);
196            }
197        }
198
199        // Check that indices are sorted in strictly ascending order (no duplicates)
200        for i in 1..self.indices.len() {
201            if self.indices[i] <= self.indices[i - 1] {
202                return Err(MetadataValueConversionError::SparseVectorIndicesNotSorted);
203            }
204        }
205
206        Ok(())
207    }
208}
209
210impl Eq for SparseVector {}
211
212impl Ord for SparseVector {
213    fn cmp(&self, other: &Self) -> Ordering {
214        self.indices.cmp(&other.indices).then_with(|| {
215            for (a, b) in self.values.iter().zip(other.values.iter()) {
216                match a.total_cmp(b) {
217                    Ordering::Equal => continue,
218                    other => return other,
219                }
220            }
221            self.values.len().cmp(&other.values.len())
222        })
223    }
224}
225
226impl PartialOrd for SparseVector {
227    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
228        Some(self.cmp(other))
229    }
230}
231
232impl TryFrom<chroma_proto::SparseVector> for SparseVector {
233    type Error = SparseVectorLengthMismatch;
234
235    fn try_from(proto: chroma_proto::SparseVector) -> Result<Self, Self::Error> {
236        if proto.tokens.is_empty() {
237            SparseVector::new(proto.indices, proto.values)
238        } else {
239            SparseVector::new_with_tokens(proto.indices, proto.values, proto.tokens)
240        }
241    }
242}
243
244impl From<SparseVector> for chroma_proto::SparseVector {
245    fn from(sparse: SparseVector) -> Self {
246        chroma_proto::SparseVector {
247            indices: sparse.indices,
248            values: sparse.values,
249            tokens: sparse.tokens.unwrap_or_default(),
250        }
251    }
252}
253
254/// Convert SparseVector to sprs::CsVec for efficient sparse operations
255impl From<&SparseVector> for CsVec<f32> {
256    fn from(sparse: &SparseVector) -> Self {
257        let (indices, values) = sparse
258            .iter()
259            .map(|(index, value)| (index as usize, value))
260            .unzip();
261        CsVec::new(u32::MAX as usize, indices, values)
262    }
263}
264
265impl From<SparseVector> for CsVec<f32> {
266    fn from(sparse: SparseVector) -> Self {
267        (&sparse).into()
268    }
269}
270
271#[cfg(feature = "pyo3")]
272impl<'py> pyo3::IntoPyObject<'py> for SparseVector {
273    type Target = pyo3::PyAny;
274    type Output = pyo3::Bound<'py, Self::Target>;
275    type Error = pyo3::PyErr;
276
277    fn into_pyobject(self, py: pyo3::Python<'py>) -> Result<Self::Output, Self::Error> {
278        use pyo3::types::PyDict;
279
280        let dict = PyDict::new(py);
281        dict.set_item("indices", self.indices)?;
282        dict.set_item("values", self.values)?;
283        dict.set_item("tokens", self.tokens)?;
284        Ok(dict.into_any())
285    }
286}
287
288#[cfg(feature = "pyo3")]
289impl<'py> pyo3::FromPyObject<'py> for SparseVector {
290    fn extract_bound(ob: &pyo3::Bound<'py, pyo3::PyAny>) -> pyo3::PyResult<Self> {
291        use pyo3::types::PyDict;
292
293        let dict = ob.downcast::<PyDict>()?;
294        let indices_obj = dict.get_item("indices")?;
295        if indices_obj.is_none() {
296            return Err(pyo3::exceptions::PyKeyError::new_err(
297                "missing 'indices' key",
298            ));
299        }
300        let indices: Vec<u32> = indices_obj.unwrap().extract()?;
301
302        let values_obj = dict.get_item("values")?;
303        if values_obj.is_none() {
304            return Err(pyo3::exceptions::PyKeyError::new_err(
305                "missing 'values' key",
306            ));
307        }
308        let values: Vec<f32> = values_obj.unwrap().extract()?;
309
310        let tokens_obj = dict.get_item("tokens")?;
311        let tokens = match tokens_obj {
312            Some(obj) if obj.is_none() => None,
313            Some(obj) => Some(obj.extract::<Vec<String>>()?),
314            None => None,
315        };
316
317        let result = match tokens {
318            Some(tokens) => SparseVector::new_with_tokens(indices, values, tokens),
319            None => SparseVector::new(indices, values),
320        };
321
322        result.map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
323    }
324}
325
326#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
327#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
328#[cfg_attr(feature = "testing", derive(proptest_derive::Arbitrary))]
329#[serde(untagged)]
330pub enum UpdateMetadataValue {
331    Bool(bool),
332    Int(i64),
333    #[cfg_attr(
334        feature = "testing",
335        proptest(
336            strategy = "(-1e6..=1e6f32).prop_map(|v| UpdateMetadataValue::Float(v as f64)).boxed()"
337        )
338    )]
339    Float(f64),
340    Str(String),
341    #[cfg_attr(feature = "testing", proptest(skip))]
342    SparseVector(SparseVector),
343    // Array types for multi-valued metadata fields
344    // TODO: Add support for these in proptests
345    #[cfg_attr(feature = "testing", proptest(skip))]
346    BoolArray(Vec<bool>),
347    #[cfg_attr(feature = "testing", proptest(skip))]
348    IntArray(Vec<i64>),
349    #[cfg_attr(feature = "testing", proptest(skip))]
350    FloatArray(Vec<f64>),
351    #[cfg_attr(feature = "testing", proptest(skip))]
352    StringArray(Vec<String>),
353    None,
354}
355
356#[cfg(feature = "pyo3")]
357impl<'py> pyo3::FromPyObject<'py> for UpdateMetadataValue {
358    fn extract_bound(ob: &pyo3::Bound<'py, pyo3::PyAny>) -> pyo3::PyResult<Self> {
359        use pyo3::types::PyList;
360
361        if ob.is_none() {
362            Ok(UpdateMetadataValue::None)
363        } else if let Ok(value) = ob.extract::<bool>() {
364            Ok(UpdateMetadataValue::Bool(value))
365        } else if let Ok(value) = ob.extract::<i64>() {
366            Ok(UpdateMetadataValue::Int(value))
367        } else if let Ok(value) = ob.extract::<f64>() {
368            Ok(UpdateMetadataValue::Float(value))
369        } else if let Ok(value) = ob.extract::<String>() {
370            Ok(UpdateMetadataValue::Str(value))
371        } else if let Ok(value) = ob.extract::<SparseVector>() {
372            Ok(UpdateMetadataValue::SparseVector(value))
373        } else if let Ok(list) = ob.downcast::<PyList>() {
374            // Empty lists are not allowed
375            if list.is_empty()? {
376                return Err(pyo3::exceptions::PyValueError::new_err(
377                    "Empty lists are not allowed as metadata values",
378                ));
379            }
380            // Try to extract entire list as each type.
381            // We check all elements (not just the first) to handle mixed-numeric
382            // lists like [1, 2.5, 3] which should be inferred as FloatArray.
383            if let Ok(arr) = list.extract::<Vec<bool>>() {
384                Ok(UpdateMetadataValue::BoolArray(arr))
385            } else if let Ok(arr) = list.extract::<Vec<i64>>() {
386                Ok(UpdateMetadataValue::IntArray(arr))
387            } else if let Ok(arr) = list.extract::<Vec<f64>>() {
388                Ok(UpdateMetadataValue::FloatArray(arr))
389            } else if let Ok(arr) = list.extract::<Vec<String>>() {
390                Ok(UpdateMetadataValue::StringArray(arr))
391            } else {
392                Err(pyo3::exceptions::PyTypeError::new_err(
393                    "Cannot convert Python list to UpdateMetadataValue: mixed or unsupported element types",
394                ))
395            }
396        } else {
397            Err(pyo3::exceptions::PyTypeError::new_err(
398                "Cannot convert Python object to UpdateMetadataValue",
399            ))
400        }
401    }
402}
403
404impl From<bool> for UpdateMetadataValue {
405    fn from(b: bool) -> Self {
406        Self::Bool(b)
407    }
408}
409
410impl From<i64> for UpdateMetadataValue {
411    fn from(v: i64) -> Self {
412        Self::Int(v)
413    }
414}
415
416impl From<i32> for UpdateMetadataValue {
417    fn from(v: i32) -> Self {
418        Self::Int(v as i64)
419    }
420}
421
422impl From<f64> for UpdateMetadataValue {
423    fn from(v: f64) -> Self {
424        Self::Float(v)
425    }
426}
427
428impl From<f32> for UpdateMetadataValue {
429    fn from(v: f32) -> Self {
430        Self::Float(v as f64)
431    }
432}
433
434impl From<String> for UpdateMetadataValue {
435    fn from(v: String) -> Self {
436        Self::Str(v)
437    }
438}
439
440impl From<&str> for UpdateMetadataValue {
441    fn from(v: &str) -> Self {
442        Self::Str(v.to_string())
443    }
444}
445
446impl From<SparseVector> for UpdateMetadataValue {
447    fn from(v: SparseVector) -> Self {
448        Self::SparseVector(v)
449    }
450}
451
452impl From<Vec<bool>> for UpdateMetadataValue {
453    fn from(v: Vec<bool>) -> Self {
454        Self::BoolArray(v)
455    }
456}
457
458impl From<Vec<i64>> for UpdateMetadataValue {
459    fn from(v: Vec<i64>) -> Self {
460        Self::IntArray(v)
461    }
462}
463
464impl From<Vec<f64>> for UpdateMetadataValue {
465    fn from(v: Vec<f64>) -> Self {
466        Self::FloatArray(v)
467    }
468}
469
470impl From<Vec<String>> for UpdateMetadataValue {
471    fn from(v: Vec<String>) -> Self {
472        Self::StringArray(v)
473    }
474}
475
476#[derive(Error, Debug)]
477pub enum UpdateMetadataValueConversionError {
478    #[error("Invalid metadata value, valid values are: Int, Float, Str, Bool, None")]
479    InvalidValue,
480}
481
482impl ChromaError for UpdateMetadataValueConversionError {
483    fn code(&self) -> ErrorCodes {
484        match self {
485            UpdateMetadataValueConversionError::InvalidValue => ErrorCodes::InvalidArgument,
486        }
487    }
488}
489
490impl TryFrom<&chroma_proto::UpdateMetadataValue> for UpdateMetadataValue {
491    type Error = UpdateMetadataValueConversionError;
492
493    fn try_from(value: &chroma_proto::UpdateMetadataValue) -> Result<Self, Self::Error> {
494        match &value.value {
495            Some(chroma_proto::update_metadata_value::Value::BoolValue(value)) => {
496                Ok(UpdateMetadataValue::Bool(*value))
497            }
498            Some(chroma_proto::update_metadata_value::Value::IntValue(value)) => {
499                Ok(UpdateMetadataValue::Int(*value))
500            }
501            Some(chroma_proto::update_metadata_value::Value::FloatValue(value)) => {
502                Ok(UpdateMetadataValue::Float(*value))
503            }
504            Some(chroma_proto::update_metadata_value::Value::StringValue(value)) => {
505                Ok(UpdateMetadataValue::Str(value.clone()))
506            }
507            Some(chroma_proto::update_metadata_value::Value::SparseVectorValue(value)) => {
508                let sparse = value
509                    .clone()
510                    .try_into()
511                    .map_err(|_| UpdateMetadataValueConversionError::InvalidValue)?;
512                Ok(UpdateMetadataValue::SparseVector(sparse))
513            }
514            Some(chroma_proto::update_metadata_value::Value::BoolListValue(value)) => {
515                Ok(UpdateMetadataValue::BoolArray(value.values.clone()))
516            }
517            Some(chroma_proto::update_metadata_value::Value::IntListValue(value)) => {
518                Ok(UpdateMetadataValue::IntArray(value.values.clone()))
519            }
520            Some(chroma_proto::update_metadata_value::Value::DoubleListValue(value)) => {
521                Ok(UpdateMetadataValue::FloatArray(value.values.clone()))
522            }
523            Some(chroma_proto::update_metadata_value::Value::StringListValue(value)) => {
524                Ok(UpdateMetadataValue::StringArray(value.values.clone()))
525            }
526            // Used to communicate that the user wants to delete this key.
527            None => Ok(UpdateMetadataValue::None),
528        }
529    }
530}
531
532impl From<UpdateMetadataValue> for chroma_proto::UpdateMetadataValue {
533    fn from(value: UpdateMetadataValue) -> Self {
534        match value {
535            UpdateMetadataValue::Bool(value) => chroma_proto::UpdateMetadataValue {
536                value: Some(chroma_proto::update_metadata_value::Value::BoolValue(value)),
537            },
538            UpdateMetadataValue::Int(value) => chroma_proto::UpdateMetadataValue {
539                value: Some(chroma_proto::update_metadata_value::Value::IntValue(value)),
540            },
541            UpdateMetadataValue::Float(value) => chroma_proto::UpdateMetadataValue {
542                value: Some(chroma_proto::update_metadata_value::Value::FloatValue(
543                    value,
544                )),
545            },
546            UpdateMetadataValue::Str(value) => chroma_proto::UpdateMetadataValue {
547                value: Some(chroma_proto::update_metadata_value::Value::StringValue(
548                    value,
549                )),
550            },
551            UpdateMetadataValue::SparseVector(sparse_vec) => chroma_proto::UpdateMetadataValue {
552                value: Some(
553                    chroma_proto::update_metadata_value::Value::SparseVectorValue(
554                        sparse_vec.into(),
555                    ),
556                ),
557            },
558            UpdateMetadataValue::BoolArray(values) => chroma_proto::UpdateMetadataValue {
559                value: Some(chroma_proto::update_metadata_value::Value::BoolListValue(
560                    chroma_proto::BoolListValue { values },
561                )),
562            },
563            UpdateMetadataValue::IntArray(values) => chroma_proto::UpdateMetadataValue {
564                value: Some(chroma_proto::update_metadata_value::Value::IntListValue(
565                    chroma_proto::IntListValue { values },
566                )),
567            },
568            UpdateMetadataValue::FloatArray(values) => chroma_proto::UpdateMetadataValue {
569                value: Some(chroma_proto::update_metadata_value::Value::DoubleListValue(
570                    chroma_proto::DoubleListValue { values },
571                )),
572            },
573            UpdateMetadataValue::StringArray(values) => chroma_proto::UpdateMetadataValue {
574                value: Some(chroma_proto::update_metadata_value::Value::StringListValue(
575                    chroma_proto::StringListValue { values },
576                )),
577            },
578            UpdateMetadataValue::None => chroma_proto::UpdateMetadataValue { value: None },
579        }
580    }
581}
582
583impl TryFrom<&UpdateMetadataValue> for MetadataValue {
584    type Error = MetadataValueConversionError;
585
586    fn try_from(value: &UpdateMetadataValue) -> Result<Self, Self::Error> {
587        match value {
588            UpdateMetadataValue::Bool(value) => Ok(MetadataValue::Bool(*value)),
589            UpdateMetadataValue::Int(value) => Ok(MetadataValue::Int(*value)),
590            UpdateMetadataValue::Float(value) => Ok(MetadataValue::Float(*value)),
591            UpdateMetadataValue::Str(value) => Ok(MetadataValue::Str(value.clone())),
592            UpdateMetadataValue::SparseVector(value) => {
593                Ok(MetadataValue::SparseVector(value.clone()))
594            }
595            UpdateMetadataValue::BoolArray(value) => Ok(MetadataValue::BoolArray(value.clone())),
596            UpdateMetadataValue::IntArray(value) => Ok(MetadataValue::IntArray(value.clone())),
597            UpdateMetadataValue::FloatArray(value) => Ok(MetadataValue::FloatArray(value.clone())),
598            UpdateMetadataValue::StringArray(value) => {
599                Ok(MetadataValue::StringArray(value.clone()))
600            }
601            UpdateMetadataValue::None => Err(MetadataValueConversionError::InvalidValue),
602        }
603    }
604}
605
606/*
607===========================================
608MetadataValue
609===========================================
610*/
611
612#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
613#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
614#[cfg_attr(feature = "testing", derive(proptest_derive::Arbitrary))]
615#[cfg_attr(feature = "pyo3", derive(pyo3::IntoPyObject))]
616#[serde(untagged)]
617pub enum MetadataValue {
618    Bool(bool),
619    Int(i64),
620    #[cfg_attr(
621        feature = "testing",
622        proptest(
623            strategy = "(-1e6..=1e6f32).prop_map(|v| MetadataValue::Float(v as f64)).boxed()"
624        )
625    )]
626    Float(f64),
627    Str(String),
628    #[cfg_attr(feature = "testing", proptest(skip))]
629    SparseVector(SparseVector),
630    // Array types for multi-valued metadata fields
631    // TODO: Add support for these in proptests
632    #[cfg_attr(feature = "testing", proptest(skip))]
633    BoolArray(Vec<bool>),
634    #[cfg_attr(feature = "testing", proptest(skip))]
635    IntArray(Vec<i64>),
636    #[cfg_attr(feature = "testing", proptest(skip))]
637    FloatArray(Vec<f64>),
638    #[cfg_attr(feature = "testing", proptest(skip))]
639    StringArray(Vec<String>),
640}
641
642#[cfg(feature = "pyo3")]
643impl<'py> pyo3::FromPyObject<'py> for MetadataValue {
644    fn extract_bound(ob: &pyo3::Bound<'py, pyo3::PyAny>) -> pyo3::PyResult<Self> {
645        use pyo3::types::PyList;
646
647        if let Ok(value) = ob.extract::<bool>() {
648            Ok(MetadataValue::Bool(value))
649        } else if let Ok(value) = ob.extract::<i64>() {
650            Ok(MetadataValue::Int(value))
651        } else if let Ok(value) = ob.extract::<f64>() {
652            Ok(MetadataValue::Float(value))
653        } else if let Ok(value) = ob.extract::<String>() {
654            Ok(MetadataValue::Str(value))
655        } else if let Ok(value) = ob.extract::<SparseVector>() {
656            Ok(MetadataValue::SparseVector(value))
657        } else if let Ok(list) = ob.downcast::<PyList>() {
658            // Empty lists are not allowed
659            if list.is_empty()? {
660                return Err(pyo3::exceptions::PyValueError::new_err(
661                    "Empty lists are not allowed as metadata values",
662                ));
663            }
664            // Try to extract entire list as each type.
665            // We check all elements (not just the first) to handle mixed-numeric
666            // lists like [1, 2.5, 3] which should be inferred as FloatArray.
667            if let Ok(arr) = list.extract::<Vec<bool>>() {
668                Ok(MetadataValue::BoolArray(arr))
669            } else if let Ok(arr) = list.extract::<Vec<i64>>() {
670                Ok(MetadataValue::IntArray(arr))
671            } else if let Ok(arr) = list.extract::<Vec<f64>>() {
672                Ok(MetadataValue::FloatArray(arr))
673            } else if let Ok(arr) = list.extract::<Vec<String>>() {
674                Ok(MetadataValue::StringArray(arr))
675            } else {
676                Err(pyo3::exceptions::PyTypeError::new_err(
677                    "Cannot convert Python list to MetadataValue: mixed or unsupported element types",
678                ))
679            }
680        } else {
681            Err(pyo3::exceptions::PyTypeError::new_err(
682                "Cannot convert Python object to MetadataValue",
683            ))
684        }
685    }
686}
687
688impl std::fmt::Display for MetadataValue {
689    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
690        match self {
691            MetadataValue::Bool(v) => write!(f, "{}", v),
692            MetadataValue::Int(v) => write!(f, "{}", v),
693            MetadataValue::Float(v) => write!(f, "{}", v),
694            MetadataValue::Str(v) => write!(f, "\"{}\"", v),
695            MetadataValue::SparseVector(v) => write!(f, "SparseVector(len={})", v.values.len()),
696            MetadataValue::BoolArray(v) => write!(f, "BoolArray(len={})", v.len()),
697            MetadataValue::IntArray(v) => write!(f, "IntArray(len={})", v.len()),
698            MetadataValue::FloatArray(v) => write!(f, "FloatArray(len={})", v.len()),
699            MetadataValue::StringArray(v) => write!(f, "StringArray(len={})", v.len()),
700        }
701    }
702}
703
704impl Eq for MetadataValue {}
705
706#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
707pub enum MetadataValueType {
708    Bool,
709    Int,
710    Float,
711    Str,
712    SparseVector,
713    BoolArray,
714    IntArray,
715    FloatArray,
716    StringArray,
717}
718
719impl MetadataValue {
720    pub fn value_type(&self) -> MetadataValueType {
721        match self {
722            MetadataValue::Bool(_) => MetadataValueType::Bool,
723            MetadataValue::Int(_) => MetadataValueType::Int,
724            MetadataValue::Float(_) => MetadataValueType::Float,
725            MetadataValue::Str(_) => MetadataValueType::Str,
726            MetadataValue::SparseVector(_) => MetadataValueType::SparseVector,
727            MetadataValue::BoolArray(_) => MetadataValueType::BoolArray,
728            MetadataValue::IntArray(_) => MetadataValueType::IntArray,
729            MetadataValue::FloatArray(_) => MetadataValueType::FloatArray,
730            MetadataValue::StringArray(_) => MetadataValueType::StringArray,
731        }
732    }
733}
734
735impl From<&MetadataValue> for MetadataValueType {
736    fn from(value: &MetadataValue) -> Self {
737        value.value_type()
738    }
739}
740
741impl From<bool> for MetadataValue {
742    fn from(v: bool) -> Self {
743        MetadataValue::Bool(v)
744    }
745}
746
747impl From<i64> for MetadataValue {
748    fn from(v: i64) -> Self {
749        MetadataValue::Int(v)
750    }
751}
752
753impl From<i32> for MetadataValue {
754    fn from(v: i32) -> Self {
755        MetadataValue::Int(v as i64)
756    }
757}
758
759impl From<f64> for MetadataValue {
760    fn from(v: f64) -> Self {
761        MetadataValue::Float(v)
762    }
763}
764
765impl From<f32> for MetadataValue {
766    fn from(v: f32) -> Self {
767        MetadataValue::Float(v as f64)
768    }
769}
770
771impl From<String> for MetadataValue {
772    fn from(v: String) -> Self {
773        MetadataValue::Str(v)
774    }
775}
776
777impl From<&str> for MetadataValue {
778    fn from(v: &str) -> Self {
779        MetadataValue::Str(v.to_string())
780    }
781}
782
783impl From<SparseVector> for MetadataValue {
784    fn from(v: SparseVector) -> Self {
785        MetadataValue::SparseVector(v)
786    }
787}
788
789impl From<Vec<bool>> for MetadataValue {
790    fn from(v: Vec<bool>) -> Self {
791        MetadataValue::BoolArray(v)
792    }
793}
794
795impl From<Vec<i64>> for MetadataValue {
796    fn from(v: Vec<i64>) -> Self {
797        MetadataValue::IntArray(v)
798    }
799}
800
801impl From<Vec<i32>> for MetadataValue {
802    fn from(v: Vec<i32>) -> Self {
803        MetadataValue::IntArray(v.into_iter().map(|x| x as i64).collect())
804    }
805}
806
807impl From<Vec<f64>> for MetadataValue {
808    fn from(v: Vec<f64>) -> Self {
809        MetadataValue::FloatArray(v)
810    }
811}
812
813impl From<Vec<f32>> for MetadataValue {
814    fn from(v: Vec<f32>) -> Self {
815        MetadataValue::FloatArray(v.into_iter().map(|x| x as f64).collect())
816    }
817}
818
819impl From<Vec<String>> for MetadataValue {
820    fn from(v: Vec<String>) -> Self {
821        MetadataValue::StringArray(v)
822    }
823}
824
825impl From<Vec<&str>> for MetadataValue {
826    fn from(v: Vec<&str>) -> Self {
827        MetadataValue::StringArray(v.into_iter().map(|s| s.to_string()).collect())
828    }
829}
830
831/// We need `Eq` and `Ord` since we want to use this as a key in `BTreeMap`
832///
833/// For cross-type comparisons, we define a consistent ordering based on variant position:
834/// Bool < Int < Float < Str < SparseVector < BoolArray < IntArray < FloatArray < StringArray
835#[allow(clippy::derive_ord_xor_partial_ord)]
836impl Ord for MetadataValue {
837    fn cmp(&self, other: &Self) -> Ordering {
838        // Define type ordering based on variant position
839        fn type_order(val: &MetadataValue) -> u8 {
840            match val {
841                MetadataValue::Bool(_) => 0,
842                MetadataValue::Int(_) => 1,
843                MetadataValue::Float(_) => 2,
844                MetadataValue::Str(_) => 3,
845                MetadataValue::SparseVector(_) => 4,
846                MetadataValue::BoolArray(_) => 5,
847                MetadataValue::IntArray(_) => 6,
848                MetadataValue::FloatArray(_) => 7,
849                MetadataValue::StringArray(_) => 8,
850            }
851        }
852
853        // Chain type ordering with value ordering
854        type_order(self).cmp(&type_order(other)).then_with(|| {
855            match (self, other) {
856                (MetadataValue::Bool(left), MetadataValue::Bool(right)) => left.cmp(right),
857                (MetadataValue::Int(left), MetadataValue::Int(right)) => left.cmp(right),
858                (MetadataValue::Float(left), MetadataValue::Float(right)) => left.total_cmp(right),
859                (MetadataValue::Str(left), MetadataValue::Str(right)) => left.cmp(right),
860                (MetadataValue::SparseVector(left), MetadataValue::SparseVector(right)) => {
861                    left.cmp(right)
862                }
863                (MetadataValue::BoolArray(left), MetadataValue::BoolArray(right)) => {
864                    left.cmp(right)
865                }
866                (MetadataValue::IntArray(left), MetadataValue::IntArray(right)) => left.cmp(right),
867                (MetadataValue::FloatArray(left), MetadataValue::FloatArray(right)) => {
868                    // Compare element by element using total_cmp for f64
869                    for (l, r) in left.iter().zip(right.iter()) {
870                        match l.total_cmp(r) {
871                            Ordering::Equal => continue,
872                            other => return other,
873                        }
874                    }
875                    left.len().cmp(&right.len())
876                }
877                (MetadataValue::StringArray(left), MetadataValue::StringArray(right)) => {
878                    left.cmp(right)
879                }
880                _ => Ordering::Equal, // Different types, but type_order already handled this
881            }
882        })
883    }
884}
885
886impl PartialOrd for MetadataValue {
887    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
888        Some(self.cmp(other))
889    }
890}
891
892impl TryFrom<&MetadataValue> for bool {
893    type Error = MetadataValueConversionError;
894
895    fn try_from(value: &MetadataValue) -> Result<Self, Self::Error> {
896        match value {
897            MetadataValue::Bool(value) => Ok(*value),
898            _ => Err(MetadataValueConversionError::InvalidValue),
899        }
900    }
901}
902
903impl TryFrom<&MetadataValue> for i64 {
904    type Error = MetadataValueConversionError;
905
906    fn try_from(value: &MetadataValue) -> Result<Self, Self::Error> {
907        match value {
908            MetadataValue::Int(value) => Ok(*value),
909            _ => Err(MetadataValueConversionError::InvalidValue),
910        }
911    }
912}
913
914impl TryFrom<&MetadataValue> for f64 {
915    type Error = MetadataValueConversionError;
916
917    fn try_from(value: &MetadataValue) -> Result<Self, Self::Error> {
918        match value {
919            MetadataValue::Float(value) => Ok(*value),
920            _ => Err(MetadataValueConversionError::InvalidValue),
921        }
922    }
923}
924
925impl TryFrom<&MetadataValue> for String {
926    type Error = MetadataValueConversionError;
927
928    fn try_from(value: &MetadataValue) -> Result<Self, Self::Error> {
929        match value {
930            MetadataValue::Str(value) => Ok(value.clone()),
931            _ => Err(MetadataValueConversionError::InvalidValue),
932        }
933    }
934}
935
936impl From<MetadataValue> for UpdateMetadataValue {
937    fn from(value: MetadataValue) -> Self {
938        match value {
939            MetadataValue::Bool(v) => UpdateMetadataValue::Bool(v),
940            MetadataValue::Int(v) => UpdateMetadataValue::Int(v),
941            MetadataValue::Float(v) => UpdateMetadataValue::Float(v),
942            MetadataValue::Str(v) => UpdateMetadataValue::Str(v),
943            MetadataValue::SparseVector(v) => UpdateMetadataValue::SparseVector(v),
944            MetadataValue::BoolArray(v) => UpdateMetadataValue::BoolArray(v),
945            MetadataValue::IntArray(v) => UpdateMetadataValue::IntArray(v),
946            MetadataValue::FloatArray(v) => UpdateMetadataValue::FloatArray(v),
947            MetadataValue::StringArray(v) => UpdateMetadataValue::StringArray(v),
948        }
949    }
950}
951
952impl From<MetadataValue> for Value {
953    fn from(value: MetadataValue) -> Self {
954        match value {
955            MetadataValue::Bool(val) => Self::Bool(val),
956            MetadataValue::Int(val) => Self::Number(
957                Number::from_i128(val as i128).expect("i64 should be representable in JSON"),
958            ),
959            MetadataValue::Float(val) => Self::Number(
960                Number::from_f64(val).expect("Inf and NaN should not be present in MetadataValue"),
961            ),
962            MetadataValue::Str(val) => Self::String(val),
963            MetadataValue::SparseVector(val) => {
964                let mut map = serde_json::Map::new();
965                map.insert(
966                    "indices".to_string(),
967                    Value::Array(
968                        val.indices
969                            .iter()
970                            .map(|&i| Value::Number(i.into()))
971                            .collect(),
972                    ),
973                );
974                map.insert(
975                    "values".to_string(),
976                    Value::Array(
977                        val.values
978                            .iter()
979                            .map(|&v| {
980                                Value::Number(
981                                    Number::from_f64(v as f64)
982                                        .expect("Float number should not be NaN or infinite"),
983                                )
984                            })
985                            .collect(),
986                    ),
987                );
988                Self::Object(map)
989            }
990            MetadataValue::BoolArray(vals) => {
991                Self::Array(vals.into_iter().map(Value::Bool).collect())
992            }
993            MetadataValue::IntArray(vals) => Self::Array(
994                vals.into_iter()
995                    .map(|v| {
996                        Value::Number(
997                            Number::from_i128(v as i128)
998                                .expect("i64 should be representable in JSON"),
999                        )
1000                    })
1001                    .collect(),
1002            ),
1003            MetadataValue::FloatArray(vals) => Self::Array(
1004                vals.into_iter()
1005                    .map(|v| {
1006                        Value::Number(
1007                            Number::from_f64(v)
1008                                .expect("Inf and NaN should not be present in MetadataValue"),
1009                        )
1010                    })
1011                    .collect(),
1012            ),
1013            MetadataValue::StringArray(vals) => {
1014                Self::Array(vals.into_iter().map(Value::String).collect())
1015            }
1016        }
1017    }
1018}
1019
1020#[derive(Error, Debug)]
1021pub enum MetadataValueConversionError {
1022    #[error("Invalid metadata value, valid values are: Int, Float, Str")]
1023    InvalidValue,
1024    #[error("Metadata key cannot start with '#' or '$': {0}")]
1025    InvalidKey(String),
1026    #[error("Sparse vector indices, values, and tokens (when present) must have the same length")]
1027    SparseVectorLengthMismatch,
1028    #[error("Sparse vector indices must be sorted in strictly ascending order (no duplicates)")]
1029    SparseVectorIndicesNotSorted,
1030}
1031
1032impl ChromaError for MetadataValueConversionError {
1033    fn code(&self) -> ErrorCodes {
1034        match self {
1035            MetadataValueConversionError::InvalidValue => ErrorCodes::InvalidArgument,
1036            MetadataValueConversionError::InvalidKey(_) => ErrorCodes::InvalidArgument,
1037            MetadataValueConversionError::SparseVectorLengthMismatch => ErrorCodes::InvalidArgument,
1038            MetadataValueConversionError::SparseVectorIndicesNotSorted => {
1039                ErrorCodes::InvalidArgument
1040            }
1041        }
1042    }
1043}
1044
1045impl TryFrom<&chroma_proto::UpdateMetadataValue> for MetadataValue {
1046    type Error = MetadataValueConversionError;
1047
1048    fn try_from(value: &chroma_proto::UpdateMetadataValue) -> Result<Self, Self::Error> {
1049        match &value.value {
1050            Some(chroma_proto::update_metadata_value::Value::BoolValue(value)) => {
1051                Ok(MetadataValue::Bool(*value))
1052            }
1053            Some(chroma_proto::update_metadata_value::Value::IntValue(value)) => {
1054                Ok(MetadataValue::Int(*value))
1055            }
1056            Some(chroma_proto::update_metadata_value::Value::FloatValue(value)) => {
1057                Ok(MetadataValue::Float(*value))
1058            }
1059            Some(chroma_proto::update_metadata_value::Value::StringValue(value)) => {
1060                Ok(MetadataValue::Str(value.clone()))
1061            }
1062            Some(chroma_proto::update_metadata_value::Value::SparseVectorValue(value)) => {
1063                let sparse = value
1064                    .clone()
1065                    .try_into()
1066                    .map_err(|_| MetadataValueConversionError::SparseVectorLengthMismatch)?;
1067                Ok(MetadataValue::SparseVector(sparse))
1068            }
1069            Some(chroma_proto::update_metadata_value::Value::BoolListValue(value)) => {
1070                Ok(MetadataValue::BoolArray(value.values.clone()))
1071            }
1072            Some(chroma_proto::update_metadata_value::Value::IntListValue(value)) => {
1073                Ok(MetadataValue::IntArray(value.values.clone()))
1074            }
1075            Some(chroma_proto::update_metadata_value::Value::DoubleListValue(value)) => {
1076                Ok(MetadataValue::FloatArray(value.values.clone()))
1077            }
1078            Some(chroma_proto::update_metadata_value::Value::StringListValue(value)) => {
1079                Ok(MetadataValue::StringArray(value.values.clone()))
1080            }
1081            _ => Err(MetadataValueConversionError::InvalidValue),
1082        }
1083    }
1084}
1085
1086impl From<MetadataValue> for chroma_proto::UpdateMetadataValue {
1087    fn from(value: MetadataValue) -> Self {
1088        match value {
1089            MetadataValue::Int(value) => chroma_proto::UpdateMetadataValue {
1090                value: Some(chroma_proto::update_metadata_value::Value::IntValue(value)),
1091            },
1092            MetadataValue::Float(value) => chroma_proto::UpdateMetadataValue {
1093                value: Some(chroma_proto::update_metadata_value::Value::FloatValue(
1094                    value,
1095                )),
1096            },
1097            MetadataValue::Str(value) => chroma_proto::UpdateMetadataValue {
1098                value: Some(chroma_proto::update_metadata_value::Value::StringValue(
1099                    value,
1100                )),
1101            },
1102            MetadataValue::Bool(value) => chroma_proto::UpdateMetadataValue {
1103                value: Some(chroma_proto::update_metadata_value::Value::BoolValue(value)),
1104            },
1105            MetadataValue::SparseVector(sparse_vec) => chroma_proto::UpdateMetadataValue {
1106                value: Some(
1107                    chroma_proto::update_metadata_value::Value::SparseVectorValue(
1108                        sparse_vec.into(),
1109                    ),
1110                ),
1111            },
1112            MetadataValue::BoolArray(values) => chroma_proto::UpdateMetadataValue {
1113                value: Some(chroma_proto::update_metadata_value::Value::BoolListValue(
1114                    chroma_proto::BoolListValue { values },
1115                )),
1116            },
1117            MetadataValue::IntArray(values) => chroma_proto::UpdateMetadataValue {
1118                value: Some(chroma_proto::update_metadata_value::Value::IntListValue(
1119                    chroma_proto::IntListValue { values },
1120                )),
1121            },
1122            MetadataValue::FloatArray(values) => chroma_proto::UpdateMetadataValue {
1123                value: Some(chroma_proto::update_metadata_value::Value::DoubleListValue(
1124                    chroma_proto::DoubleListValue { values },
1125                )),
1126            },
1127            MetadataValue::StringArray(values) => chroma_proto::UpdateMetadataValue {
1128                value: Some(chroma_proto::update_metadata_value::Value::StringListValue(
1129                    chroma_proto::StringListValue { values },
1130                )),
1131            },
1132        }
1133    }
1134}
1135
1136/*
1137===========================================
1138UpdateMetadata
1139===========================================
1140*/
1141pub type UpdateMetadata = HashMap<String, UpdateMetadataValue>;
1142
1143/**
1144 * Check if two metadata are close to equal. Ignores small differences in float values.
1145 */
1146pub fn are_update_metadatas_close_to_equal(
1147    metadata1: &UpdateMetadata,
1148    metadata2: &UpdateMetadata,
1149) -> bool {
1150    assert_eq!(metadata1.len(), metadata2.len());
1151
1152    for (key, value) in metadata1.iter() {
1153        if !metadata2.contains_key(key) {
1154            return false;
1155        }
1156        let other_value = metadata2.get(key).unwrap();
1157
1158        if let (UpdateMetadataValue::Float(value), UpdateMetadataValue::Float(other_value)) =
1159            (value, other_value)
1160        {
1161            if (value - other_value).abs() > 1e-6 {
1162                return false;
1163            }
1164        } else if value != other_value {
1165            return false;
1166        }
1167    }
1168
1169    true
1170}
1171
1172pub fn are_metadatas_close_to_equal(metadata1: &Metadata, metadata2: &Metadata) -> bool {
1173    assert_eq!(metadata1.len(), metadata2.len());
1174
1175    for (key, value) in metadata1.iter() {
1176        if !metadata2.contains_key(key) {
1177            return false;
1178        }
1179        let other_value = metadata2.get(key).unwrap();
1180
1181        if let (MetadataValue::Float(value), MetadataValue::Float(other_value)) =
1182            (value, other_value)
1183        {
1184            if (value - other_value).abs() > 1e-6 {
1185                return false;
1186            }
1187        } else if value != other_value {
1188            return false;
1189        }
1190    }
1191
1192    true
1193}
1194
1195impl TryFrom<chroma_proto::UpdateMetadata> for UpdateMetadata {
1196    type Error = UpdateMetadataValueConversionError;
1197
1198    fn try_from(proto_metadata: chroma_proto::UpdateMetadata) -> Result<Self, Self::Error> {
1199        let mut metadata = UpdateMetadata::new();
1200        for (key, value) in proto_metadata.metadata.iter() {
1201            let value = match value.try_into() {
1202                Ok(value) => value,
1203                Err(_) => return Err(UpdateMetadataValueConversionError::InvalidValue),
1204            };
1205            metadata.insert(key.clone(), value);
1206        }
1207        Ok(metadata)
1208    }
1209}
1210
1211impl From<UpdateMetadata> for chroma_proto::UpdateMetadata {
1212    fn from(metadata: UpdateMetadata) -> Self {
1213        let mut metadata = metadata;
1214        let mut proto_metadata = chroma_proto::UpdateMetadata {
1215            metadata: HashMap::new(),
1216        };
1217        for (key, value) in metadata.drain() {
1218            let proto_value = value.into();
1219            proto_metadata.metadata.insert(key.clone(), proto_value);
1220        }
1221        proto_metadata
1222    }
1223}
1224
1225/*
1226===========================================
1227Metadata
1228===========================================
1229*/
1230
1231pub type Metadata = HashMap<String, MetadataValue>;
1232pub type DeletedMetadata = HashSet<String>;
1233
1234pub fn logical_size_of_metadata(metadata: &Metadata) -> usize {
1235    metadata
1236        .iter()
1237        .map(|(k, v)| {
1238            k.len()
1239                + match v {
1240                    MetadataValue::Bool(b) => size_of_val(b),
1241                    MetadataValue::Int(i) => size_of_val(i),
1242                    MetadataValue::Float(f) => size_of_val(f),
1243                    MetadataValue::Str(s) => s.len(),
1244                    MetadataValue::SparseVector(v) => {
1245                        size_of_val(&v.indices[..]) + size_of_val(&v.values[..])
1246                    }
1247                    MetadataValue::BoolArray(arr) => size_of_val(&arr[..]),
1248                    MetadataValue::IntArray(arr) => size_of_val(&arr[..]),
1249                    MetadataValue::FloatArray(arr) => size_of_val(&arr[..]),
1250                    MetadataValue::StringArray(arr) => arr.iter().map(|s| s.len()).sum::<usize>(),
1251                }
1252        })
1253        .sum()
1254}
1255
1256pub fn get_metadata_value_as<'a, T>(
1257    metadata: &'a Metadata,
1258    key: &str,
1259) -> Result<T, Box<MetadataValueConversionError>>
1260where
1261    T: TryFrom<&'a MetadataValue, Error = MetadataValueConversionError>,
1262{
1263    let res = match metadata.get(key) {
1264        Some(value) => T::try_from(value),
1265        None => return Err(Box::new(MetadataValueConversionError::InvalidValue)),
1266    };
1267    match res {
1268        Ok(value) => Ok(value),
1269        Err(_) => Err(Box::new(MetadataValueConversionError::InvalidValue)),
1270    }
1271}
1272
1273impl TryFrom<chroma_proto::UpdateMetadata> for Metadata {
1274    type Error = MetadataValueConversionError;
1275
1276    fn try_from(proto_metadata: chroma_proto::UpdateMetadata) -> Result<Self, Self::Error> {
1277        let mut metadata = Metadata::new();
1278        for (key, value) in proto_metadata.metadata.iter() {
1279            let maybe_value: Result<MetadataValue, Self::Error> = value.try_into();
1280            if maybe_value.is_err() {
1281                return Err(MetadataValueConversionError::InvalidValue);
1282            }
1283            let value = maybe_value.unwrap();
1284            metadata.insert(key.clone(), value);
1285        }
1286        Ok(metadata)
1287    }
1288}
1289
1290impl From<Metadata> for chroma_proto::UpdateMetadata {
1291    fn from(metadata: Metadata) -> Self {
1292        let mut metadata = metadata;
1293        let mut proto_metadata = chroma_proto::UpdateMetadata {
1294            metadata: HashMap::new(),
1295        };
1296        for (key, value) in metadata.drain() {
1297            let proto_value = value.into();
1298            proto_metadata.metadata.insert(key.clone(), proto_value);
1299        }
1300        proto_metadata
1301    }
1302}
1303
1304#[derive(Debug, Default)]
1305pub struct MetadataDelta<'referred_data> {
1306    pub metadata_to_update: HashMap<
1307        &'referred_data str,
1308        (&'referred_data MetadataValue, &'referred_data MetadataValue),
1309    >,
1310    pub metadata_to_delete: HashMap<&'referred_data str, &'referred_data MetadataValue>,
1311    pub metadata_to_insert: HashMap<&'referred_data str, &'referred_data MetadataValue>,
1312}
1313
1314impl MetadataDelta<'_> {
1315    pub fn new() -> Self {
1316        Self::default()
1317    }
1318}
1319
1320/*
1321===========================================
1322Metadata queries
1323===========================================
1324*/
1325
1326#[derive(Clone, Debug, Error, PartialEq)]
1327pub enum WhereConversionError {
1328    #[error("Error: {0}")]
1329    Cause(String),
1330    #[error("{0} -> {1}")]
1331    Trace(String, Box<Self>),
1332}
1333
1334impl WhereConversionError {
1335    pub fn cause(msg: impl ToString) -> Self {
1336        Self::Cause(msg.to_string())
1337    }
1338
1339    pub fn trace(self, context: impl ToString) -> Self {
1340        Self::Trace(context.to_string(), Box::new(self))
1341    }
1342}
1343
1344/// This `Where` enum serves as an unified representation for the `where` and `where_document` clauses.
1345/// Although this is not unified in the API level due to legacy design choices, in the future we will be
1346/// unifying them together, and the structure of the unified AST should be identical to the one here.
1347/// Currently both `where` and `where_document` clauses will be translated into `Where`, and if both are
1348/// present we simply create a conjunction of both clauses as the actual filter. This is consistent with
1349/// the semantics we used to have when the `where` and `where_document` clauses are treated seperately.
1350// TODO: Remove this note once the `where` clause and `where_document` clause is unified in the API level.
1351#[derive(Clone, Debug, PartialEq)]
1352#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1353pub enum Where {
1354    Composite(CompositeExpression),
1355    Document(DocumentExpression),
1356    Metadata(MetadataExpression),
1357}
1358
1359impl std::fmt::Display for Where {
1360    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1361        match self {
1362            Where::Composite(composite) => {
1363                let fragment = composite
1364                    .children
1365                    .iter()
1366                    .map(|child| format!("{}", child))
1367                    .collect::<Vec<_>>()
1368                    .join(match composite.operator {
1369                        BooleanOperator::And => " & ",
1370                        BooleanOperator::Or => " | ",
1371                    });
1372                write!(f, "({})", fragment)
1373            }
1374            Where::Metadata(expr) => write!(f, "{}", expr),
1375            Where::Document(expr) => write!(f, "{}", expr),
1376        }
1377    }
1378}
1379
1380impl serde::Serialize for Where {
1381    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1382    where
1383        S: Serializer,
1384    {
1385        match self {
1386            Where::Composite(composite) => {
1387                let mut map = serializer.serialize_map(Some(1))?;
1388                let op_key = match composite.operator {
1389                    BooleanOperator::And => "$and",
1390                    BooleanOperator::Or => "$or",
1391                };
1392                map.serialize_entry(op_key, &composite.children)?;
1393                map.end()
1394            }
1395            Where::Document(doc) => {
1396                let mut outer_map = serializer.serialize_map(Some(1))?;
1397                let mut inner_map = serde_json::Map::new();
1398                let op_key = match doc.operator {
1399                    DocumentOperator::Contains => "$contains",
1400                    DocumentOperator::NotContains => "$not_contains",
1401                    DocumentOperator::Regex => "$regex",
1402                    DocumentOperator::NotRegex => "$not_regex",
1403                };
1404                inner_map.insert(
1405                    op_key.to_string(),
1406                    serde_json::Value::String(doc.pattern.clone()),
1407                );
1408                outer_map.serialize_entry("#document", &inner_map)?;
1409                outer_map.end()
1410            }
1411            Where::Metadata(meta) => {
1412                let mut outer_map = serializer.serialize_map(Some(1))?;
1413                let mut inner_map = serde_json::Map::new();
1414
1415                match &meta.comparison {
1416                    MetadataComparison::Primitive(op, value) => {
1417                        let op_key = match op {
1418                            PrimitiveOperator::Equal => "$eq",
1419                            PrimitiveOperator::NotEqual => "$ne",
1420                            PrimitiveOperator::GreaterThan => "$gt",
1421                            PrimitiveOperator::GreaterThanOrEqual => "$gte",
1422                            PrimitiveOperator::LessThan => "$lt",
1423                            PrimitiveOperator::LessThanOrEqual => "$lte",
1424                        };
1425                        let value_json =
1426                            serde_json::to_value(value).map_err(serde::ser::Error::custom)?;
1427                        inner_map.insert(op_key.to_string(), value_json);
1428                    }
1429                    MetadataComparison::Set(op, set_value) => {
1430                        let op_key = match op {
1431                            SetOperator::In => "$in",
1432                            SetOperator::NotIn => "$nin",
1433                        };
1434                        let values_json = match set_value {
1435                            MetadataSetValue::Bool(v) => serde_json::to_value(v),
1436                            MetadataSetValue::Int(v) => serde_json::to_value(v),
1437                            MetadataSetValue::Float(v) => serde_json::to_value(v),
1438                            MetadataSetValue::Str(v) => serde_json::to_value(v),
1439                        }
1440                        .map_err(serde::ser::Error::custom)?;
1441                        inner_map.insert(op_key.to_string(), values_json);
1442                    }
1443                    MetadataComparison::ArrayContains(op, value) => {
1444                        let op_key = match op {
1445                            ContainsOperator::Contains => "$contains",
1446                            ContainsOperator::NotContains => "$not_contains",
1447                        };
1448                        let value_json =
1449                            serde_json::to_value(value).map_err(serde::ser::Error::custom)?;
1450                        inner_map.insert(op_key.to_string(), value_json);
1451                    }
1452                }
1453
1454                outer_map.serialize_entry(&meta.key, &inner_map)?;
1455                outer_map.end()
1456            }
1457        }
1458    }
1459}
1460
1461impl From<bool> for Where {
1462    fn from(value: bool) -> Self {
1463        if value {
1464            Where::conjunction(vec![])
1465        } else {
1466            Where::disjunction(vec![])
1467        }
1468    }
1469}
1470
1471impl Where {
1472    pub fn conjunction(children: impl IntoIterator<Item = Where>) -> Self {
1473        // If children.len() == 0, we will return a conjunction that is always true.
1474        // If children.len() == 1, we will return the single child.
1475        // Otherwise, we will return a conjunction of the children.
1476
1477        let mut children: Vec<_> = children
1478            .into_iter()
1479            .flat_map(|expr| {
1480                if let Where::Composite(CompositeExpression {
1481                    operator: BooleanOperator::And,
1482                    children,
1483                }) = expr
1484                {
1485                    return children;
1486                }
1487                vec![expr]
1488            })
1489            .dedup()
1490            .collect();
1491
1492        if children.len() == 1 {
1493            return children.pop().expect("just checked len is 1");
1494        }
1495
1496        Self::Composite(CompositeExpression {
1497            operator: BooleanOperator::And,
1498            children,
1499        })
1500    }
1501    pub fn disjunction(children: impl IntoIterator<Item = Where>) -> Self {
1502        // If children.len() == 0, we will return a disjunction that is always false.
1503        // If children.len() == 1, we will return the single child.
1504        // Otherwise, we will return a disjunction of the children.
1505
1506        let mut children: Vec<_> = children
1507            .into_iter()
1508            .flat_map(|expr| {
1509                if let Where::Composite(CompositeExpression {
1510                    operator: BooleanOperator::Or,
1511                    children,
1512                }) = expr
1513                {
1514                    return children;
1515                }
1516                vec![expr]
1517            })
1518            .dedup()
1519            .collect();
1520
1521        if children.len() == 1 {
1522            return children.pop().expect("just checked len is 1");
1523        }
1524
1525        Self::Composite(CompositeExpression {
1526            operator: BooleanOperator::Or,
1527            children,
1528        })
1529    }
1530
1531    pub fn fts_query_length(&self) -> u64 {
1532        match self {
1533            Where::Composite(composite_expression) => composite_expression
1534                .children
1535                .iter()
1536                .map(Where::fts_query_length)
1537                .sum(),
1538            // The query length is defined to be the number of trigram tokens
1539            Where::Document(document_expression) => {
1540                document_expression.pattern.len().max(3) as u64 - 2
1541            }
1542            Where::Metadata(_) => 0,
1543        }
1544    }
1545
1546    pub fn metadata_predicate_count(&self) -> u64 {
1547        match self {
1548            Where::Composite(composite_expression) => composite_expression
1549                .children
1550                .iter()
1551                .map(Where::metadata_predicate_count)
1552                .sum(),
1553            Where::Document(_) => 0,
1554            Where::Metadata(metadata_expression) => match &metadata_expression.comparison {
1555                MetadataComparison::Primitive(_, _) => 1,
1556                MetadataComparison::Set(_, metadata_set_value) => match metadata_set_value {
1557                    MetadataSetValue::Bool(items) => items.len() as u64,
1558                    MetadataSetValue::Int(items) => items.len() as u64,
1559                    MetadataSetValue::Float(items) => items.len() as u64,
1560                    MetadataSetValue::Str(items) => items.len() as u64,
1561                },
1562                MetadataComparison::ArrayContains(_, _) => 1,
1563            },
1564        }
1565    }
1566}
1567
1568impl BitAnd for Where {
1569    type Output = Where;
1570
1571    fn bitand(self, rhs: Self) -> Self::Output {
1572        Self::conjunction([self, rhs])
1573    }
1574}
1575
1576impl BitOr for Where {
1577    type Output = Where;
1578
1579    fn bitor(self, rhs: Self) -> Self::Output {
1580        Self::disjunction([self, rhs])
1581    }
1582}
1583
1584impl TryFrom<chroma_proto::Where> for Where {
1585    type Error = WhereConversionError;
1586
1587    fn try_from(proto_where: chroma_proto::Where) -> Result<Self, Self::Error> {
1588        let where_inner = proto_where
1589            .r#where
1590            .ok_or(WhereConversionError::cause("Invalid Where"))?;
1591        Ok(match where_inner {
1592            chroma_proto::r#where::Where::DirectComparison(direct_comparison) => {
1593                Self::Metadata(direct_comparison.try_into()?)
1594            }
1595            chroma_proto::r#where::Where::Children(where_children) => {
1596                Self::Composite(where_children.try_into()?)
1597            }
1598            chroma_proto::r#where::Where::DirectDocumentComparison(direct_where_document) => {
1599                Self::Document(direct_where_document.into())
1600            }
1601        })
1602    }
1603}
1604
1605impl TryFrom<Where> for chroma_proto::Where {
1606    type Error = WhereConversionError;
1607
1608    fn try_from(value: Where) -> Result<Self, Self::Error> {
1609        let proto_where = match value {
1610            Where::Composite(composite_expression) => {
1611                chroma_proto::r#where::Where::Children(composite_expression.try_into()?)
1612            }
1613            Where::Document(document_expression) => {
1614                chroma_proto::r#where::Where::DirectDocumentComparison(document_expression.into())
1615            }
1616            Where::Metadata(metadata_expression) => chroma_proto::r#where::Where::DirectComparison(
1617                chroma_proto::DirectComparison::try_from(metadata_expression)
1618                    .map_err(|err| err.trace("MetadataExpression"))?,
1619            ),
1620        };
1621        Ok(Self {
1622            r#where: Some(proto_where),
1623        })
1624    }
1625}
1626
1627#[derive(Clone, Debug, PartialEq)]
1628#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1629pub struct CompositeExpression {
1630    pub operator: BooleanOperator,
1631    pub children: Vec<Where>,
1632}
1633
1634impl TryFrom<chroma_proto::WhereChildren> for CompositeExpression {
1635    type Error = WhereConversionError;
1636
1637    fn try_from(proto_children: chroma_proto::WhereChildren) -> Result<Self, Self::Error> {
1638        let operator = proto_children.operator().into();
1639        let children = proto_children
1640            .children
1641            .into_iter()
1642            .map(Where::try_from)
1643            .collect::<Result<Vec<_>, _>>()
1644            .map_err(|err| err.trace("Child Where of CompositeExpression"))?;
1645        Ok(Self { operator, children })
1646    }
1647}
1648
1649impl TryFrom<CompositeExpression> for chroma_proto::WhereChildren {
1650    type Error = WhereConversionError;
1651
1652    fn try_from(value: CompositeExpression) -> Result<Self, Self::Error> {
1653        Ok(Self {
1654            operator: chroma_proto::BooleanOperator::from(value.operator) as i32,
1655            children: value
1656                .children
1657                .into_iter()
1658                .map(chroma_proto::Where::try_from)
1659                .collect::<Result<_, _>>()?,
1660        })
1661    }
1662}
1663
1664#[derive(Clone, Debug, PartialEq)]
1665#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1666pub enum BooleanOperator {
1667    And,
1668    Or,
1669}
1670
1671impl From<chroma_proto::BooleanOperator> for BooleanOperator {
1672    fn from(value: chroma_proto::BooleanOperator) -> Self {
1673        match value {
1674            chroma_proto::BooleanOperator::And => Self::And,
1675            chroma_proto::BooleanOperator::Or => Self::Or,
1676        }
1677    }
1678}
1679
1680impl From<BooleanOperator> for chroma_proto::BooleanOperator {
1681    fn from(value: BooleanOperator) -> Self {
1682        match value {
1683            BooleanOperator::And => Self::And,
1684            BooleanOperator::Or => Self::Or,
1685        }
1686    }
1687}
1688
1689#[derive(Clone, Debug, PartialEq)]
1690#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1691pub struct DocumentExpression {
1692    pub operator: DocumentOperator,
1693    pub pattern: String,
1694}
1695
1696impl std::fmt::Display for DocumentExpression {
1697    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1698        let op_str = match self.operator {
1699            DocumentOperator::Contains => "CONTAINS",
1700            DocumentOperator::NotContains => "NOT CONTAINS",
1701            DocumentOperator::Regex => "REGEX",
1702            DocumentOperator::NotRegex => "NOT REGEX",
1703        };
1704        write!(f, "#document {} \"{}\"", op_str, self.pattern)
1705    }
1706}
1707
1708impl From<chroma_proto::DirectWhereDocument> for DocumentExpression {
1709    fn from(value: chroma_proto::DirectWhereDocument) -> Self {
1710        Self {
1711            operator: value.operator().into(),
1712            pattern: value.pattern,
1713        }
1714    }
1715}
1716
1717impl From<DocumentExpression> for chroma_proto::DirectWhereDocument {
1718    fn from(value: DocumentExpression) -> Self {
1719        Self {
1720            pattern: value.pattern,
1721            operator: chroma_proto::WhereDocumentOperator::from(value.operator) as i32,
1722        }
1723    }
1724}
1725
1726#[derive(Clone, Debug, PartialEq)]
1727#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1728pub enum DocumentOperator {
1729    Contains,
1730    NotContains,
1731    Regex,
1732    NotRegex,
1733}
1734impl From<chroma_proto::WhereDocumentOperator> for DocumentOperator {
1735    fn from(value: chroma_proto::WhereDocumentOperator) -> Self {
1736        match value {
1737            chroma_proto::WhereDocumentOperator::Contains => Self::Contains,
1738            chroma_proto::WhereDocumentOperator::NotContains => Self::NotContains,
1739            chroma_proto::WhereDocumentOperator::Regex => Self::Regex,
1740            chroma_proto::WhereDocumentOperator::NotRegex => Self::NotRegex,
1741        }
1742    }
1743}
1744
1745impl From<DocumentOperator> for chroma_proto::WhereDocumentOperator {
1746    fn from(value: DocumentOperator) -> Self {
1747        match value {
1748            DocumentOperator::Contains => Self::Contains,
1749            DocumentOperator::NotContains => Self::NotContains,
1750            DocumentOperator::Regex => Self::Regex,
1751            DocumentOperator::NotRegex => Self::NotRegex,
1752        }
1753    }
1754}
1755
1756#[derive(Clone, Debug, PartialEq)]
1757#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1758pub struct MetadataExpression {
1759    pub key: String,
1760    pub comparison: MetadataComparison,
1761}
1762
1763impl std::fmt::Display for MetadataExpression {
1764    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1765        match &self.comparison {
1766            MetadataComparison::Primitive(op, value) => {
1767                write!(f, "{} {} {}", self.key, op, value)
1768            }
1769            MetadataComparison::Set(op, set_value) => {
1770                write!(f, "{} {} {}", self.key, op, set_value)
1771            }
1772            MetadataComparison::ArrayContains(op, value) => {
1773                write!(f, "{} {} {}", self.key, op, value)
1774            }
1775        }
1776    }
1777}
1778
1779/// Helper to convert a `GenericComparator` and a `MetadataValue` into either a
1780/// `MetadataComparison::Primitive` (for EQ/NE) or `MetadataComparison::Contains`
1781/// (for CONTAINS/NOT_CONTAINS).
1782fn generic_comparator_to_metadata_comparison(
1783    comparator: chroma_proto::GenericComparator,
1784    value: MetadataValue,
1785) -> MetadataComparison {
1786    match comparator {
1787        chroma_proto::GenericComparator::Eq | chroma_proto::GenericComparator::Ne => {
1788            // SAFETY: We just matched Eq | Ne, so try_into() a
1789            // PrimitiveOperator will always succeed.
1790            MetadataComparison::Primitive(comparator.try_into().unwrap(), value)
1791        }
1792        chroma_proto::GenericComparator::ArrayContains => {
1793            MetadataComparison::ArrayContains(ContainsOperator::Contains, value)
1794        }
1795        chroma_proto::GenericComparator::ArrayNotContains => {
1796            MetadataComparison::ArrayContains(ContainsOperator::NotContains, value)
1797        }
1798    }
1799}
1800
1801impl TryFrom<chroma_proto::DirectComparison> for MetadataExpression {
1802    type Error = WhereConversionError;
1803
1804    fn try_from(value: chroma_proto::DirectComparison) -> Result<Self, Self::Error> {
1805        let proto_comparison = value
1806            .comparison
1807            .ok_or(WhereConversionError::cause("Invalid MetadataExpression"))?;
1808        let comparison = match proto_comparison {
1809            chroma_proto::direct_comparison::Comparison::SingleStringOperand(
1810                single_string_comparison,
1811            ) => generic_comparator_to_metadata_comparison(
1812                single_string_comparison.comparator(),
1813                MetadataValue::Str(single_string_comparison.value),
1814            ),
1815            chroma_proto::direct_comparison::Comparison::StringListOperand(
1816                string_list_comparison,
1817            ) => MetadataComparison::Set(
1818                string_list_comparison.list_operator().into(),
1819                MetadataSetValue::Str(string_list_comparison.values),
1820            ),
1821            chroma_proto::direct_comparison::Comparison::SingleIntOperand(
1822                single_int_comparison,
1823            ) => {
1824                let comparator =
1825                    single_int_comparison
1826                        .comparator
1827                        .ok_or(WhereConversionError::cause(
1828                            "Invalid scalar integer operator",
1829                        ))?;
1830                let value = MetadataValue::Int(single_int_comparison.value);
1831                match comparator {
1832                    chroma_proto::single_int_comparison::Comparator::GenericComparator(op) => {
1833                        let generic = chroma_proto::GenericComparator::try_from(op)
1834                            .map_err(WhereConversionError::cause)?;
1835                        generic_comparator_to_metadata_comparison(generic, value)
1836                    }
1837                    chroma_proto::single_int_comparison::Comparator::NumberComparator(op) => {
1838                        MetadataComparison::Primitive(
1839                            chroma_proto::NumberComparator::try_from(op)
1840                                .map_err(WhereConversionError::cause)?
1841                                .into(),
1842                            value,
1843                        )
1844                    }
1845                }
1846            }
1847            chroma_proto::direct_comparison::Comparison::IntListOperand(int_list_comparison) => {
1848                MetadataComparison::Set(
1849                    int_list_comparison.list_operator().into(),
1850                    MetadataSetValue::Int(int_list_comparison.values),
1851                )
1852            }
1853            chroma_proto::direct_comparison::Comparison::SingleDoubleOperand(
1854                single_double_comparison,
1855            ) => {
1856                let comparator = single_double_comparison
1857                    .comparator
1858                    .ok_or(WhereConversionError::cause("Invalid scalar float operator"))?;
1859                let value = MetadataValue::Float(single_double_comparison.value);
1860                match comparator {
1861                    chroma_proto::single_double_comparison::Comparator::GenericComparator(op) => {
1862                        let generic = chroma_proto::GenericComparator::try_from(op)
1863                            .map_err(WhereConversionError::cause)?;
1864                        generic_comparator_to_metadata_comparison(generic, value)
1865                    }
1866                    chroma_proto::single_double_comparison::Comparator::NumberComparator(op) => {
1867                        MetadataComparison::Primitive(
1868                            chroma_proto::NumberComparator::try_from(op)
1869                                .map_err(WhereConversionError::cause)?
1870                                .into(),
1871                            value,
1872                        )
1873                    }
1874                }
1875            }
1876            chroma_proto::direct_comparison::Comparison::DoubleListOperand(
1877                double_list_comparison,
1878            ) => MetadataComparison::Set(
1879                double_list_comparison.list_operator().into(),
1880                MetadataSetValue::Float(double_list_comparison.values),
1881            ),
1882            chroma_proto::direct_comparison::Comparison::BoolListOperand(bool_list_comparison) => {
1883                MetadataComparison::Set(
1884                    bool_list_comparison.list_operator().into(),
1885                    MetadataSetValue::Bool(bool_list_comparison.values),
1886                )
1887            }
1888            chroma_proto::direct_comparison::Comparison::SingleBoolOperand(
1889                single_bool_comparison,
1890            ) => generic_comparator_to_metadata_comparison(
1891                single_bool_comparison.comparator(),
1892                MetadataValue::Bool(single_bool_comparison.value),
1893            ),
1894        };
1895        Ok(Self {
1896            key: value.key,
1897            comparison,
1898        })
1899    }
1900}
1901
1902impl TryFrom<MetadataExpression> for chroma_proto::DirectComparison {
1903    type Error = WhereConversionError;
1904
1905    fn try_from(value: MetadataExpression) -> Result<Self, Self::Error> {
1906        let comparison = match value.comparison {
1907            MetadataComparison::Primitive(primitive_operator, metadata_value) => match metadata_value {
1908                MetadataValue::Bool(value) => chroma_proto::direct_comparison::Comparison::SingleBoolOperand(chroma_proto::SingleBoolComparison { value, comparator: chroma_proto::GenericComparator::try_from(primitive_operator)? as i32 }),
1909                MetadataValue::Int(value) => chroma_proto::direct_comparison::Comparison::SingleIntOperand(chroma_proto::SingleIntComparison { value, comparator: Some(match primitive_operator {
1910                                generic_operator @ PrimitiveOperator::Equal | generic_operator @ PrimitiveOperator::NotEqual => chroma_proto::single_int_comparison::Comparator::GenericComparator(chroma_proto::GenericComparator::try_from(generic_operator)? as i32),
1911                                numeric => chroma_proto::single_int_comparison::Comparator::NumberComparator(chroma_proto::NumberComparator::try_from(numeric)? as i32) }),
1912                            }),
1913                MetadataValue::Float(value) => chroma_proto::direct_comparison::Comparison::SingleDoubleOperand(chroma_proto::SingleDoubleComparison { value, comparator: Some(match primitive_operator {
1914                                generic_operator @ PrimitiveOperator::Equal | generic_operator @ PrimitiveOperator::NotEqual => chroma_proto::single_double_comparison::Comparator::GenericComparator(chroma_proto::GenericComparator::try_from(generic_operator)? as i32),
1915                                numeric => chroma_proto::single_double_comparison::Comparator::NumberComparator(chroma_proto::NumberComparator::try_from(numeric)? as i32) }),
1916                            }),
1917                MetadataValue::Str(value) => chroma_proto::direct_comparison::Comparison::SingleStringOperand(chroma_proto::SingleStringComparison { value, comparator: chroma_proto::GenericComparator::try_from(primitive_operator)? as i32 }),
1918                MetadataValue::SparseVector(_) => return Err(WhereConversionError::Cause("Comparison with sparse vector is not supported".to_string())),
1919                MetadataValue::BoolArray(_) | MetadataValue::IntArray(_) | MetadataValue::FloatArray(_) | MetadataValue::StringArray(_) => {
1920                    return Err(WhereConversionError::Cause("Primitive comparison with array metadata values is not supported".to_string()))
1921                }
1922            },
1923            MetadataComparison::Set(set_operator, metadata_set_value) => match metadata_set_value {
1924                MetadataSetValue::Bool(vec) => chroma_proto::direct_comparison::Comparison::BoolListOperand(chroma_proto::BoolListComparison { values: vec, list_operator: chroma_proto::ListOperator::from(set_operator) as i32 }),
1925                MetadataSetValue::Int(vec) => chroma_proto::direct_comparison::Comparison::IntListOperand(chroma_proto::IntListComparison { values: vec, list_operator: chroma_proto::ListOperator::from(set_operator) as i32 }),
1926                MetadataSetValue::Float(vec) => chroma_proto::direct_comparison::Comparison::DoubleListOperand(chroma_proto::DoubleListComparison { values: vec, list_operator: chroma_proto::ListOperator::from(set_operator) as i32 }),
1927                MetadataSetValue::Str(vec) => chroma_proto::direct_comparison::Comparison::StringListOperand(chroma_proto::StringListComparison { values: vec, list_operator: chroma_proto::ListOperator::from(set_operator) as i32 }),
1928            },
1929            MetadataComparison::ArrayContains(contains_operator, metadata_value) => {
1930                let comparator = chroma_proto::GenericComparator::from(contains_operator) as i32;
1931                match metadata_value {
1932                    MetadataValue::Bool(value) => chroma_proto::direct_comparison::Comparison::SingleBoolOperand(chroma_proto::SingleBoolComparison { value, comparator }),
1933                    MetadataValue::Int(value) => chroma_proto::direct_comparison::Comparison::SingleIntOperand(chroma_proto::SingleIntComparison { value, comparator: Some(chroma_proto::single_int_comparison::Comparator::GenericComparator(comparator)) }),
1934                    MetadataValue::Float(value) => chroma_proto::direct_comparison::Comparison::SingleDoubleOperand(chroma_proto::SingleDoubleComparison { value, comparator: Some(chroma_proto::single_double_comparison::Comparator::GenericComparator(comparator)) }),
1935                    MetadataValue::Str(value) => chroma_proto::direct_comparison::Comparison::SingleStringOperand(chroma_proto::SingleStringComparison { value, comparator }),
1936                    MetadataValue::SparseVector(_) => return Err(WhereConversionError::Cause("Contains comparison with sparse vector is not supported".to_string())),
1937                    MetadataValue::BoolArray(_) | MetadataValue::IntArray(_) | MetadataValue::FloatArray(_) | MetadataValue::StringArray(_) => {
1938                        return Err(WhereConversionError::Cause("Contains comparison value must be a scalar, not an array".to_string()))
1939                    }
1940                }
1941            },
1942        };
1943        Ok(Self {
1944            key: value.key,
1945            comparison: Some(comparison),
1946        })
1947    }
1948}
1949
1950#[derive(Clone, Debug, PartialEq)]
1951#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1952pub enum MetadataComparison {
1953    Primitive(PrimitiveOperator, MetadataValue),
1954    Set(SetOperator, MetadataSetValue),
1955    /// Array contains: check if an array metadata field contains (or does not
1956    /// contain) a specific scalar value.
1957    ArrayContains(ContainsOperator, MetadataValue),
1958}
1959
1960impl std::fmt::Display for MetadataComparison {
1961    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1962        match self {
1963            MetadataComparison::Primitive(op, val) => {
1964                let type_name = match val {
1965                    MetadataValue::Bool(_) => "Bool",
1966                    MetadataValue::Int(_) => "Int",
1967                    MetadataValue::Float(_) => "Float",
1968                    MetadataValue::Str(_) => "Str",
1969                    MetadataValue::SparseVector(_) => "SparseVector",
1970                    MetadataValue::BoolArray(_) => "BoolArray",
1971                    MetadataValue::IntArray(_) => "IntArray",
1972                    MetadataValue::FloatArray(_) => "FloatArray",
1973                    MetadataValue::StringArray(_) => "StringArray",
1974                };
1975                write!(f, "Primitive({}, {})", op, type_name)
1976            }
1977            MetadataComparison::Set(op, val) => {
1978                let type_name = match val {
1979                    MetadataSetValue::Bool(_) => "Bool",
1980                    MetadataSetValue::Int(_) => "Int",
1981                    MetadataSetValue::Float(_) => "Float",
1982                    MetadataSetValue::Str(_) => "Str",
1983                };
1984                write!(f, "Set({}, {})", op, type_name)
1985            }
1986            MetadataComparison::ArrayContains(op, val) => {
1987                let type_name = match val {
1988                    MetadataValue::Bool(_) => "Bool",
1989                    MetadataValue::Int(_) => "Int",
1990                    MetadataValue::Float(_) => "Float",
1991                    MetadataValue::Str(_) => "Str",
1992                    MetadataValue::SparseVector(_) => "SparseVector",
1993                    MetadataValue::BoolArray(_) => "BoolArray",
1994                    MetadataValue::IntArray(_) => "IntArray",
1995                    MetadataValue::FloatArray(_) => "FloatArray",
1996                    MetadataValue::StringArray(_) => "StringArray",
1997                };
1998                write!(f, "ArrayContains({}, {})", op, type_name)
1999            }
2000        }
2001    }
2002}
2003
2004#[derive(Clone, Debug, PartialEq)]
2005#[cfg_attr(feature = "testing", derive(proptest_derive::Arbitrary))]
2006pub enum PrimitiveOperator {
2007    Equal,
2008    NotEqual,
2009    GreaterThan,
2010    GreaterThanOrEqual,
2011    LessThan,
2012    LessThanOrEqual,
2013}
2014
2015impl std::fmt::Display for PrimitiveOperator {
2016    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2017        let op_str = match self {
2018            PrimitiveOperator::Equal => "=",
2019            PrimitiveOperator::NotEqual => "≠",
2020            PrimitiveOperator::GreaterThan => ">",
2021            PrimitiveOperator::GreaterThanOrEqual => "≥",
2022            PrimitiveOperator::LessThan => "<",
2023            PrimitiveOperator::LessThanOrEqual => "≤",
2024        };
2025        write!(f, "{}", op_str)
2026    }
2027}
2028
2029impl TryFrom<chroma_proto::GenericComparator> for PrimitiveOperator {
2030    type Error = WhereConversionError;
2031
2032    fn try_from(value: chroma_proto::GenericComparator) -> Result<Self, Self::Error> {
2033        match value {
2034            chroma_proto::GenericComparator::Eq => Ok(Self::Equal),
2035            chroma_proto::GenericComparator::Ne => Ok(Self::NotEqual),
2036            chroma_proto::GenericComparator::ArrayContains
2037            | chroma_proto::GenericComparator::ArrayNotContains => {
2038                Err(WhereConversionError::cause(
2039                    "ArrayContains/ArrayNotContains cannot be converted to PrimitiveOperator",
2040                ))
2041            }
2042        }
2043    }
2044}
2045
2046impl TryFrom<PrimitiveOperator> for chroma_proto::GenericComparator {
2047    type Error = WhereConversionError;
2048
2049    fn try_from(value: PrimitiveOperator) -> Result<Self, Self::Error> {
2050        match value {
2051            PrimitiveOperator::Equal => Ok(Self::Eq),
2052            PrimitiveOperator::NotEqual => Ok(Self::Ne),
2053            op => Err(WhereConversionError::cause(format!("{op:?} ∉ [=, ≠]"))),
2054        }
2055    }
2056}
2057
2058impl From<chroma_proto::NumberComparator> for PrimitiveOperator {
2059    fn from(value: chroma_proto::NumberComparator) -> Self {
2060        match value {
2061            chroma_proto::NumberComparator::Gt => Self::GreaterThan,
2062            chroma_proto::NumberComparator::Gte => Self::GreaterThanOrEqual,
2063            chroma_proto::NumberComparator::Lt => Self::LessThan,
2064            chroma_proto::NumberComparator::Lte => Self::LessThanOrEqual,
2065        }
2066    }
2067}
2068
2069impl TryFrom<PrimitiveOperator> for chroma_proto::NumberComparator {
2070    type Error = WhereConversionError;
2071
2072    fn try_from(value: PrimitiveOperator) -> Result<Self, Self::Error> {
2073        match value {
2074            PrimitiveOperator::GreaterThan => Ok(Self::Gt),
2075            PrimitiveOperator::GreaterThanOrEqual => Ok(Self::Gte),
2076            PrimitiveOperator::LessThan => Ok(Self::Lt),
2077            PrimitiveOperator::LessThanOrEqual => Ok(Self::Lte),
2078            op => Err(WhereConversionError::cause(format!(
2079                "{op:?} ∉ [≤, <, >, ≥]"
2080            ))),
2081        }
2082    }
2083}
2084
2085#[derive(Clone, Debug, PartialEq, Eq)]
2086#[cfg_attr(feature = "testing", derive(proptest_derive::Arbitrary))]
2087pub enum SetOperator {
2088    In,
2089    NotIn,
2090}
2091
2092impl std::fmt::Display for SetOperator {
2093    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2094        let op_str = match self {
2095            SetOperator::In => "∈",
2096            SetOperator::NotIn => "∉",
2097        };
2098        write!(f, "{}", op_str)
2099    }
2100}
2101
2102impl From<chroma_proto::ListOperator> for SetOperator {
2103    fn from(value: chroma_proto::ListOperator) -> Self {
2104        match value {
2105            chroma_proto::ListOperator::In => Self::In,
2106            chroma_proto::ListOperator::Nin => Self::NotIn,
2107        }
2108    }
2109}
2110
2111impl From<SetOperator> for chroma_proto::ListOperator {
2112    fn from(value: SetOperator) -> Self {
2113        match value {
2114            SetOperator::In => Self::In,
2115            SetOperator::NotIn => Self::Nin,
2116        }
2117    }
2118}
2119
2120#[derive(Clone, Debug, PartialEq, Eq)]
2121#[cfg_attr(feature = "testing", derive(proptest_derive::Arbitrary))]
2122pub enum ContainsOperator {
2123    Contains,
2124    NotContains,
2125}
2126
2127impl std::fmt::Display for ContainsOperator {
2128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2129        let op_str = match self {
2130            ContainsOperator::Contains => "contains",
2131            ContainsOperator::NotContains => "not_contains",
2132        };
2133        write!(f, "{}", op_str)
2134    }
2135}
2136
2137impl From<ContainsOperator> for chroma_proto::GenericComparator {
2138    fn from(value: ContainsOperator) -> Self {
2139        match value {
2140            ContainsOperator::Contains => Self::ArrayContains,
2141            ContainsOperator::NotContains => Self::ArrayNotContains,
2142        }
2143    }
2144}
2145
2146#[derive(Clone, Debug, PartialEq)]
2147#[cfg_attr(feature = "testing", derive(proptest_derive::Arbitrary))]
2148pub enum MetadataSetValue {
2149    Bool(Vec<bool>),
2150    Int(Vec<i64>),
2151    Float(Vec<f64>),
2152    Str(Vec<String>),
2153}
2154
2155impl std::fmt::Display for MetadataSetValue {
2156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2157        match self {
2158            MetadataSetValue::Bool(values) => {
2159                let values_str = values
2160                    .iter()
2161                    .map(|v| format!("\"{}\"", v))
2162                    .collect::<Vec<_>>()
2163                    .join(", ");
2164                write!(f, "[{}]", values_str)
2165            }
2166            MetadataSetValue::Int(values) => {
2167                let values_str = values
2168                    .iter()
2169                    .map(|v| v.to_string())
2170                    .collect::<Vec<_>>()
2171                    .join(", ");
2172                write!(f, "[{}]", values_str)
2173            }
2174            MetadataSetValue::Float(values) => {
2175                let values_str = values
2176                    .iter()
2177                    .map(|v| v.to_string())
2178                    .collect::<Vec<_>>()
2179                    .join(", ");
2180                write!(f, "[{}]", values_str)
2181            }
2182            MetadataSetValue::Str(values) => {
2183                let values_str = values
2184                    .iter()
2185                    .map(|v| format!("\"{}\"", v))
2186                    .collect::<Vec<_>>()
2187                    .join(", ");
2188                write!(f, "[{}]", values_str)
2189            }
2190        }
2191    }
2192}
2193
2194impl MetadataSetValue {
2195    pub fn value_type(&self) -> MetadataValueType {
2196        match self {
2197            MetadataSetValue::Bool(_) => MetadataValueType::Bool,
2198            MetadataSetValue::Int(_) => MetadataValueType::Int,
2199            MetadataSetValue::Float(_) => MetadataValueType::Float,
2200            MetadataSetValue::Str(_) => MetadataValueType::Str,
2201        }
2202    }
2203}
2204
2205impl From<Vec<bool>> for MetadataSetValue {
2206    fn from(values: Vec<bool>) -> Self {
2207        MetadataSetValue::Bool(values)
2208    }
2209}
2210
2211impl From<Vec<i64>> for MetadataSetValue {
2212    fn from(values: Vec<i64>) -> Self {
2213        MetadataSetValue::Int(values)
2214    }
2215}
2216
2217impl From<Vec<i32>> for MetadataSetValue {
2218    fn from(values: Vec<i32>) -> Self {
2219        MetadataSetValue::Int(values.into_iter().map(|v| v as i64).collect())
2220    }
2221}
2222
2223impl From<Vec<f64>> for MetadataSetValue {
2224    fn from(values: Vec<f64>) -> Self {
2225        MetadataSetValue::Float(values)
2226    }
2227}
2228
2229impl From<Vec<f32>> for MetadataSetValue {
2230    fn from(values: Vec<f32>) -> Self {
2231        MetadataSetValue::Float(values.into_iter().map(|v| v as f64).collect())
2232    }
2233}
2234
2235impl From<Vec<String>> for MetadataSetValue {
2236    fn from(values: Vec<String>) -> Self {
2237        MetadataSetValue::Str(values)
2238    }
2239}
2240
2241impl From<Vec<&str>> for MetadataSetValue {
2242    fn from(values: Vec<&str>) -> Self {
2243        MetadataSetValue::Str(values.into_iter().map(|s| s.to_string()).collect())
2244    }
2245}
2246
2247// TODO: Deprecate where_document
2248impl TryFrom<chroma_proto::WhereDocument> for Where {
2249    type Error = WhereConversionError;
2250
2251    fn try_from(proto_document: chroma_proto::WhereDocument) -> Result<Self, Self::Error> {
2252        match proto_document.r#where_document {
2253            Some(chroma_proto::where_document::WhereDocument::Direct(proto_comparison)) => {
2254                let operator = match TryInto::<chroma_proto::WhereDocumentOperator>::try_into(
2255                    proto_comparison.operator,
2256                ) {
2257                    Ok(operator) => operator,
2258                    Err(_) => {
2259                        return Err(WhereConversionError::cause(
2260                            "[Deprecated] Invalid where document operator",
2261                        ))
2262                    }
2263                };
2264                let comparison = DocumentExpression {
2265                    pattern: proto_comparison.pattern,
2266                    operator: operator.into(),
2267                };
2268                Ok(Where::Document(comparison))
2269            }
2270            Some(chroma_proto::where_document::WhereDocument::Children(proto_children)) => {
2271                let operator = match TryInto::<chroma_proto::BooleanOperator>::try_into(
2272                    proto_children.operator,
2273                ) {
2274                    Ok(operator) => operator,
2275                    Err(_) => {
2276                        return Err(WhereConversionError::cause(
2277                            "[Deprecated] Invalid boolean operator",
2278                        ))
2279                    }
2280                };
2281                let children = CompositeExpression {
2282                    children: proto_children
2283                        .children
2284                        .into_iter()
2285                        .map(|child| child.try_into())
2286                        .collect::<Result<_, _>>()?,
2287                    operator: operator.into(),
2288                };
2289                Ok(Where::Composite(children))
2290            }
2291            None => Err(WhereConversionError::cause("[Deprecated] Invalid where")),
2292        }
2293    }
2294}
2295
2296#[cfg(test)]
2297mod tests {
2298    use crate::operator::Key;
2299
2300    use super::*;
2301
2302    // This is needed for the tests that round trip to the python world.
2303    #[cfg(feature = "pyo3")]
2304    fn ensure_python_interpreter() {
2305        static PYTHON_INIT: std::sync::Once = std::sync::Once::new();
2306        PYTHON_INIT.call_once(|| {
2307            pyo3::prepare_freethreaded_python();
2308        });
2309    }
2310
2311    #[test]
2312    fn test_update_metadata_try_from() {
2313        let mut proto_metadata = chroma_proto::UpdateMetadata {
2314            metadata: HashMap::new(),
2315        };
2316        proto_metadata.metadata.insert(
2317            "foo".to_string(),
2318            chroma_proto::UpdateMetadataValue {
2319                value: Some(chroma_proto::update_metadata_value::Value::IntValue(42)),
2320            },
2321        );
2322        proto_metadata.metadata.insert(
2323            "bar".to_string(),
2324            chroma_proto::UpdateMetadataValue {
2325                value: Some(chroma_proto::update_metadata_value::Value::FloatValue(42.0)),
2326            },
2327        );
2328        proto_metadata.metadata.insert(
2329            "baz".to_string(),
2330            chroma_proto::UpdateMetadataValue {
2331                value: Some(chroma_proto::update_metadata_value::Value::StringValue(
2332                    "42".to_string(),
2333                )),
2334            },
2335        );
2336        // Add sparse vector test
2337        proto_metadata.metadata.insert(
2338            "sparse".to_string(),
2339            chroma_proto::UpdateMetadataValue {
2340                value: Some(
2341                    chroma_proto::update_metadata_value::Value::SparseVectorValue(
2342                        chroma_proto::SparseVector {
2343                            indices: vec![0, 5, 10],
2344                            values: vec![0.1, 0.5, 0.9],
2345                            tokens: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()],
2346                        },
2347                    ),
2348                ),
2349            },
2350        );
2351        let converted_metadata: UpdateMetadata = proto_metadata.try_into().unwrap();
2352        assert_eq!(converted_metadata.len(), 4);
2353        assert_eq!(
2354            converted_metadata.get("foo").unwrap(),
2355            &UpdateMetadataValue::Int(42)
2356        );
2357        assert_eq!(
2358            converted_metadata.get("bar").unwrap(),
2359            &UpdateMetadataValue::Float(42.0)
2360        );
2361        assert_eq!(
2362            converted_metadata.get("baz").unwrap(),
2363            &UpdateMetadataValue::Str("42".to_string())
2364        );
2365        assert_eq!(
2366            converted_metadata.get("sparse").unwrap(),
2367            &UpdateMetadataValue::SparseVector(
2368                SparseVector::new_with_tokens(
2369                    vec![0, 5, 10],
2370                    vec![0.1, 0.5, 0.9],
2371                    vec!["foo".to_string(), "bar".to_string(), "baz".to_string(),],
2372                )
2373                .unwrap()
2374            )
2375        );
2376    }
2377
2378    #[test]
2379    fn test_metadata_try_from() {
2380        let mut proto_metadata = chroma_proto::UpdateMetadata {
2381            metadata: HashMap::new(),
2382        };
2383        proto_metadata.metadata.insert(
2384            "foo".to_string(),
2385            chroma_proto::UpdateMetadataValue {
2386                value: Some(chroma_proto::update_metadata_value::Value::IntValue(42)),
2387            },
2388        );
2389        proto_metadata.metadata.insert(
2390            "bar".to_string(),
2391            chroma_proto::UpdateMetadataValue {
2392                value: Some(chroma_proto::update_metadata_value::Value::FloatValue(42.0)),
2393            },
2394        );
2395        proto_metadata.metadata.insert(
2396            "baz".to_string(),
2397            chroma_proto::UpdateMetadataValue {
2398                value: Some(chroma_proto::update_metadata_value::Value::StringValue(
2399                    "42".to_string(),
2400                )),
2401            },
2402        );
2403        // Add sparse vector test
2404        proto_metadata.metadata.insert(
2405            "sparse".to_string(),
2406            chroma_proto::UpdateMetadataValue {
2407                value: Some(
2408                    chroma_proto::update_metadata_value::Value::SparseVectorValue(
2409                        chroma_proto::SparseVector {
2410                            indices: vec![1, 10, 100],
2411                            values: vec![0.2, 0.4, 0.6],
2412                            tokens: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()],
2413                        },
2414                    ),
2415                ),
2416            },
2417        );
2418        let converted_metadata: Metadata = proto_metadata.try_into().unwrap();
2419        assert_eq!(converted_metadata.len(), 4);
2420        assert_eq!(
2421            converted_metadata.get("foo").unwrap(),
2422            &MetadataValue::Int(42)
2423        );
2424        assert_eq!(
2425            converted_metadata.get("bar").unwrap(),
2426            &MetadataValue::Float(42.0)
2427        );
2428        assert_eq!(
2429            converted_metadata.get("baz").unwrap(),
2430            &MetadataValue::Str("42".to_string())
2431        );
2432        assert_eq!(
2433            converted_metadata.get("sparse").unwrap(),
2434            &MetadataValue::SparseVector(
2435                SparseVector::new_with_tokens(
2436                    vec![1, 10, 100],
2437                    vec![0.2, 0.4, 0.6],
2438                    vec!["foo".to_string(), "bar".to_string(), "baz".to_string(),],
2439                )
2440                .unwrap()
2441            )
2442        );
2443    }
2444
2445    #[test]
2446    fn test_where_clause_simple_from() {
2447        let proto_where = chroma_proto::Where {
2448            r#where: Some(chroma_proto::r#where::Where::DirectComparison(
2449                chroma_proto::DirectComparison {
2450                    key: "foo".to_string(),
2451                    comparison: Some(
2452                        chroma_proto::direct_comparison::Comparison::SingleIntOperand(
2453                            chroma_proto::SingleIntComparison {
2454                                value: 42,
2455                                comparator: Some(chroma_proto::single_int_comparison::Comparator::GenericComparator(chroma_proto::GenericComparator::Eq as i32)),
2456                            },
2457                        ),
2458                    ),
2459                },
2460            )),
2461        };
2462        let where_clause: Where = proto_where.try_into().unwrap();
2463        match where_clause {
2464            Where::Metadata(comparison) => {
2465                assert_eq!(comparison.key, "foo");
2466                match comparison.comparison {
2467                    MetadataComparison::Primitive(_, value) => {
2468                        assert_eq!(value, MetadataValue::Int(42));
2469                    }
2470                    _ => panic!("Invalid comparison type"),
2471                }
2472            }
2473            _ => panic!("Invalid where type"),
2474        }
2475    }
2476
2477    #[test]
2478    fn test_where_clause_with_children() {
2479        let proto_where = chroma_proto::Where {
2480            r#where: Some(chroma_proto::r#where::Where::Children(
2481                chroma_proto::WhereChildren {
2482                    children: vec![
2483                        chroma_proto::Where {
2484                            r#where: Some(chroma_proto::r#where::Where::DirectComparison(
2485                                chroma_proto::DirectComparison {
2486                                    key: "foo".to_string(),
2487                                    comparison: Some(
2488                                        chroma_proto::direct_comparison::Comparison::SingleIntOperand(
2489                                            chroma_proto::SingleIntComparison {
2490                                                value: 42,
2491                                                comparator: Some(chroma_proto::single_int_comparison::Comparator::GenericComparator(chroma_proto::GenericComparator::Eq as i32)),
2492                                            },
2493                                        ),
2494                                    ),
2495                                },
2496                            )),
2497                        },
2498                        chroma_proto::Where {
2499                            r#where: Some(chroma_proto::r#where::Where::DirectComparison(
2500                                chroma_proto::DirectComparison {
2501                                    key: "bar".to_string(),
2502                                    comparison: Some(
2503                                        chroma_proto::direct_comparison::Comparison::SingleIntOperand(
2504                                            chroma_proto::SingleIntComparison {
2505                                                value: 42,
2506                                                comparator: Some(chroma_proto::single_int_comparison::Comparator::GenericComparator(chroma_proto::GenericComparator::Eq as i32)),
2507                                            },
2508                                        ),
2509                                    ),
2510                                },
2511                            )),
2512                        },
2513                    ],
2514                    operator: chroma_proto::BooleanOperator::And.into(),
2515                },
2516            )),
2517        };
2518        let where_clause: Where = proto_where.try_into().unwrap();
2519        match where_clause {
2520            Where::Composite(children) => {
2521                assert_eq!(children.children.len(), 2);
2522                assert_eq!(children.operator, BooleanOperator::And);
2523            }
2524            _ => panic!("Invalid where type"),
2525        }
2526    }
2527
2528    #[test]
2529    fn test_where_document_simple() {
2530        let proto_where = chroma_proto::WhereDocument {
2531            r#where_document: Some(chroma_proto::where_document::WhereDocument::Direct(
2532                chroma_proto::DirectWhereDocument {
2533                    pattern: "foo".to_string(),
2534                    operator: chroma_proto::WhereDocumentOperator::Contains.into(),
2535                },
2536            )),
2537        };
2538        let where_document: Where = proto_where.try_into().unwrap();
2539        match where_document {
2540            Where::Document(comparison) => {
2541                assert_eq!(comparison.pattern, "foo");
2542                assert_eq!(comparison.operator, DocumentOperator::Contains);
2543            }
2544            _ => panic!("Invalid where document type"),
2545        }
2546    }
2547
2548    #[test]
2549    fn test_where_document_with_children() {
2550        let proto_where = chroma_proto::WhereDocument {
2551            r#where_document: Some(chroma_proto::where_document::WhereDocument::Children(
2552                chroma_proto::WhereDocumentChildren {
2553                    children: vec![
2554                        chroma_proto::WhereDocument {
2555                            r#where_document: Some(
2556                                chroma_proto::where_document::WhereDocument::Direct(
2557                                    chroma_proto::DirectWhereDocument {
2558                                        pattern: "foo".to_string(),
2559                                        operator: chroma_proto::WhereDocumentOperator::Contains
2560                                            .into(),
2561                                    },
2562                                ),
2563                            ),
2564                        },
2565                        chroma_proto::WhereDocument {
2566                            r#where_document: Some(
2567                                chroma_proto::where_document::WhereDocument::Direct(
2568                                    chroma_proto::DirectWhereDocument {
2569                                        pattern: "bar".to_string(),
2570                                        operator: chroma_proto::WhereDocumentOperator::Contains
2571                                            .into(),
2572                                    },
2573                                ),
2574                            ),
2575                        },
2576                    ],
2577                    operator: chroma_proto::BooleanOperator::And.into(),
2578                },
2579            )),
2580        };
2581        let where_document: Where = proto_where.try_into().unwrap();
2582        match where_document {
2583            Where::Composite(children) => {
2584                assert_eq!(children.children.len(), 2);
2585                assert_eq!(children.operator, BooleanOperator::And);
2586            }
2587            _ => panic!("Invalid where document type"),
2588        }
2589    }
2590
2591    #[test]
2592    fn test_sparse_vector_new() {
2593        let indices = vec![0, 5, 10];
2594        let values = vec![0.1, 0.5, 0.9];
2595        let sparse = SparseVector::new(indices.clone(), values.clone()).unwrap();
2596        assert_eq!(sparse.indices, indices);
2597        assert_eq!(sparse.values, values);
2598    }
2599
2600    #[test]
2601    fn test_sparse_vector_from_pairs() {
2602        let pairs = vec![(0, 0.1), (5, 0.5), (10, 0.9)];
2603        let sparse = SparseVector::from_pairs(pairs.clone());
2604        assert_eq!(sparse.indices, vec![0, 5, 10]);
2605        assert_eq!(sparse.values, vec![0.1, 0.5, 0.9]);
2606    }
2607
2608    #[test]
2609    fn test_sparse_vector_from_triples() {
2610        let triples = vec![
2611            ("foo".to_string(), 0, 0.1),
2612            ("bar".to_string(), 5, 0.5),
2613            ("baz".to_string(), 10, 0.9),
2614        ];
2615        let sparse = SparseVector::from_triples(triples.clone());
2616        assert_eq!(sparse.indices, vec![0, 5, 10]);
2617        assert_eq!(sparse.values, vec![0.1, 0.5, 0.9]);
2618    }
2619
2620    #[test]
2621    fn test_sparse_vector_iter() {
2622        let sparse = SparseVector::new(vec![0, 5, 10], vec![0.1, 0.5, 0.9]).unwrap();
2623        let collected: Vec<(u32, f32)> = sparse.iter().collect();
2624        assert_eq!(collected, vec![(0, 0.1), (5, 0.5), (10, 0.9)]);
2625    }
2626
2627    #[test]
2628    fn test_sparse_vector_ordering() {
2629        let sparse1 = SparseVector::new(vec![0, 5], vec![0.1, 0.5]).unwrap();
2630        let sparse2 = SparseVector::new(vec![0, 5], vec![0.1, 0.5]).unwrap();
2631        let sparse3 = SparseVector::new(vec![0, 6], vec![0.1, 0.5]).unwrap();
2632        let sparse4 = SparseVector::new(vec![0, 5], vec![0.1, 0.6]).unwrap();
2633
2634        assert_eq!(sparse1, sparse2);
2635        assert!(sparse1 < sparse3);
2636        assert!(sparse1 < sparse4);
2637    }
2638
2639    #[test]
2640    fn test_sparse_vector_proto_conversion() {
2641        let tokens = vec![
2642            "token1".to_string(),
2643            "token2".to_string(),
2644            "token3".to_string(),
2645        ];
2646        let sparse =
2647            SparseVector::new_with_tokens(vec![1, 10, 100], vec![0.2, 0.4, 0.6], tokens.clone())
2648                .unwrap();
2649        let proto: chroma_proto::SparseVector = sparse.clone().into();
2650        assert_eq!(proto.indices, vec![1, 10, 100]);
2651        assert_eq!(proto.values, vec![0.2, 0.4, 0.6]);
2652        assert_eq!(proto.tokens, tokens.clone());
2653
2654        let converted: SparseVector = proto.try_into().unwrap();
2655        assert_eq!(converted, sparse);
2656        assert_eq!(converted.tokens, Some(tokens));
2657    }
2658
2659    #[test]
2660    fn test_sparse_vector_proto_conversion_empty_tokens() {
2661        let sparse = SparseVector::new(vec![0, 5, 10], vec![0.1, 0.5, 0.9]).unwrap();
2662        let proto: chroma_proto::SparseVector = sparse.clone().into();
2663        assert_eq!(proto.indices, vec![0, 5, 10]);
2664        assert_eq!(proto.values, vec![0.1, 0.5, 0.9]);
2665        assert_eq!(proto.tokens, Vec::<String>::new());
2666
2667        let converted: SparseVector = proto.try_into().unwrap();
2668        assert_eq!(converted, sparse);
2669        assert_eq!(converted.tokens, None);
2670    }
2671
2672    #[test]
2673    fn test_sparse_vector_logical_size() {
2674        let metadata = Metadata::from([(
2675            "sparse".to_string(),
2676            MetadataValue::SparseVector(
2677                SparseVector::new(vec![0, 1, 2, 3, 4], vec![0.1, 0.2, 0.3, 0.4, 0.5]).unwrap(),
2678            ),
2679        )]);
2680
2681        let size = logical_size_of_metadata(&metadata);
2682        // Size should include the key string length and the sparse vector data
2683        // "sparse" = 6 bytes + 5 * 4 bytes (u32 indices) + 5 * 4 bytes (f32 values) = 46 bytes
2684        assert_eq!(size, 46);
2685    }
2686
2687    #[test]
2688    fn test_sparse_vector_validation() {
2689        // Valid sparse vector
2690        let sparse = SparseVector::new(vec![1, 2, 3], vec![0.1, 0.2, 0.3]).unwrap();
2691        assert!(sparse.validate().is_ok());
2692
2693        // Length mismatch
2694        let sparse = SparseVector::new(vec![1, 2, 3], vec![0.1, 0.2]);
2695        assert!(sparse.is_err());
2696        let result = SparseVector::new(vec![1, 2, 3], vec![0.1, 0.2, 0.3])
2697            .unwrap()
2698            .validate();
2699        assert!(result.is_ok());
2700
2701        // Tokens length mismatch with indices/values
2702        let sparse = SparseVector::new_with_tokens(
2703            vec![1, 2, 3],
2704            vec![0.1, 0.2, 0.3],
2705            vec!["a".to_string(), "b".to_string()],
2706        );
2707        assert!(sparse.is_err());
2708
2709        // Unsorted indices (descending order)
2710        let sparse = SparseVector::new(vec![3, 1, 2], vec![0.3, 0.1, 0.2]).unwrap();
2711        let result = sparse.validate();
2712        assert!(result.is_err());
2713        assert!(matches!(
2714            result.unwrap_err(),
2715            MetadataValueConversionError::SparseVectorIndicesNotSorted
2716        ));
2717
2718        // Duplicate indices (not strictly ascending)
2719        let sparse = SparseVector::new(vec![1, 2, 2, 3], vec![0.1, 0.2, 0.3, 0.4]).unwrap();
2720        let result = sparse.validate();
2721        assert!(result.is_err());
2722        assert!(matches!(
2723            result.unwrap_err(),
2724            MetadataValueConversionError::SparseVectorIndicesNotSorted
2725        ));
2726
2727        // Descending at one point
2728        let sparse = SparseVector::new(vec![1, 3, 2], vec![0.1, 0.3, 0.2]).unwrap();
2729        let result = sparse.validate();
2730        assert!(result.is_err());
2731        assert!(matches!(
2732            result.unwrap_err(),
2733            MetadataValueConversionError::SparseVectorIndicesNotSorted
2734        ));
2735    }
2736
2737    #[test]
2738    fn test_sparse_vector_deserialize_old_format() {
2739        // Old format without #type field (backward compatibility)
2740        let json = r#"{"indices": [0, 1, 2], "values": [1.0, 2.0, 3.0]}"#;
2741        let sv: SparseVector = serde_json::from_str(json).unwrap();
2742        assert_eq!(sv.indices, vec![0, 1, 2]);
2743        assert_eq!(sv.values, vec![1.0, 2.0, 3.0]);
2744    }
2745
2746    #[test]
2747    fn test_sparse_vector_deserialize_new_format() {
2748        // New format with #type field
2749        let json =
2750            "{\"#type\": \"sparse_vector\", \"indices\": [0, 1, 2], \"values\": [1.0, 2.0, 3.0]}";
2751        let sv: SparseVector = serde_json::from_str(json).unwrap();
2752        assert_eq!(sv.indices, vec![0, 1, 2]);
2753        assert_eq!(sv.values, vec![1.0, 2.0, 3.0]);
2754    }
2755
2756    #[test]
2757    fn test_sparse_vector_deserialize_new_format_field_order() {
2758        // New format with different field order (should still work)
2759        let json = "{\"indices\": [5, 10], \"#type\": \"sparse_vector\", \"values\": [0.5, 1.0]}";
2760        let sv: SparseVector = serde_json::from_str(json).unwrap();
2761        assert_eq!(sv.indices, vec![5, 10]);
2762        assert_eq!(sv.values, vec![0.5, 1.0]);
2763    }
2764
2765    #[test]
2766    fn test_sparse_vector_deserialize_wrong_type_tag() {
2767        // Wrong #type field value should fail
2768        let json = "{\"#type\": \"dense_vector\", \"indices\": [0, 1], \"values\": [1.0, 2.0]}";
2769        let result: Result<SparseVector, _> = serde_json::from_str(json);
2770        assert!(result.is_err());
2771        let err_msg = result.unwrap_err().to_string();
2772        assert!(err_msg.contains("sparse_vector"));
2773    }
2774
2775    #[test]
2776    fn test_sparse_vector_serialize_always_has_type() {
2777        // Serialization should always include #type field
2778        let sv = SparseVector::new(vec![0, 1, 2], vec![1.0, 2.0, 3.0]).unwrap();
2779        let json = serde_json::to_value(&sv).unwrap();
2780
2781        assert_eq!(json["#type"], "sparse_vector");
2782        assert_eq!(json["indices"], serde_json::json!([0, 1, 2]));
2783        assert_eq!(json["values"], serde_json::json!([1.0, 2.0, 3.0]));
2784    }
2785
2786    #[test]
2787    fn test_sparse_vector_roundtrip_with_type() {
2788        // Test that serialize -> deserialize preserves the data
2789        let original = SparseVector::new(vec![0, 5, 10, 15], vec![0.1, 0.5, 1.0, 1.5]).unwrap();
2790        let json = serde_json::to_string(&original).unwrap();
2791
2792        // Verify the serialized JSON contains #type
2793        assert!(json.contains("\"#type\":\"sparse_vector\""));
2794
2795        let deserialized: SparseVector = serde_json::from_str(&json).unwrap();
2796        assert_eq!(original, deserialized);
2797    }
2798
2799    #[test]
2800    fn test_sparse_vector_in_metadata_old_format() {
2801        // Test that old format works when sparse vector is in metadata
2802        let json = r#"{"key": "value", "sparse": {"indices": [0, 1], "values": [1.0, 2.0]}}"#;
2803        let map: HashMap<String, serde_json::Value> = serde_json::from_str(json).unwrap();
2804
2805        let sparse_value = &map["sparse"];
2806        let sv: SparseVector = serde_json::from_value(sparse_value.clone()).unwrap();
2807        assert_eq!(sv.indices, vec![0, 1]);
2808        assert_eq!(sv.values, vec![1.0, 2.0]);
2809    }
2810
2811    #[test]
2812    fn test_sparse_vector_in_metadata_new_format() {
2813        // Test that new format works when sparse vector is in metadata
2814        let json = "{\"key\": \"value\", \"sparse\": {\"#type\": \"sparse_vector\", \"indices\": [0, 1], \"values\": [1.0, 2.0]}}";
2815        let map: HashMap<String, serde_json::Value> = serde_json::from_str(json).unwrap();
2816
2817        let sparse_value = &map["sparse"];
2818        let sv: SparseVector = serde_json::from_value(sparse_value.clone()).unwrap();
2819        assert_eq!(sv.indices, vec![0, 1]);
2820        assert_eq!(sv.values, vec![1.0, 2.0]);
2821    }
2822
2823    #[test]
2824    fn test_sparse_vector_tokens_roundtrip_old_to_new() {
2825        // Old format without tokens field should deserialize with tokens=None
2826        let json = r#"{"indices": [0, 1, 2], "values": [1.0, 2.0, 3.0]}"#;
2827        let sv: SparseVector = serde_json::from_str(json).unwrap();
2828        assert_eq!(sv.indices, vec![0, 1, 2]);
2829        assert_eq!(sv.values, vec![1.0, 2.0, 3.0]);
2830        assert_eq!(sv.tokens, None);
2831
2832        // Serialize and verify it includes #type but no tokens field when None
2833        let serialized = serde_json::to_value(&sv).unwrap();
2834        assert_eq!(serialized["#type"], "sparse_vector");
2835        assert_eq!(serialized["indices"], serde_json::json!([0, 1, 2]));
2836        assert_eq!(serialized["values"], serde_json::json!([1.0, 2.0, 3.0]));
2837        assert_eq!(serialized["tokens"], serde_json::Value::Null);
2838    }
2839
2840    #[test]
2841    fn test_sparse_vector_tokens_roundtrip_new_to_new() {
2842        // New format with tokens field
2843        let sv_with_tokens = SparseVector::new_with_tokens(
2844            vec![0, 1, 2],
2845            vec![1.0, 2.0, 3.0],
2846            vec!["foo".to_string(), "bar".to_string(), "baz".to_string()],
2847        )
2848        .unwrap();
2849
2850        // Serialize
2851        let serialized = serde_json::to_string(&sv_with_tokens).unwrap();
2852        assert!(serialized.contains("\"#type\":\"sparse_vector\""));
2853        assert!(serialized.contains("\"tokens\""));
2854
2855        // Deserialize and verify tokens are preserved
2856        let deserialized: SparseVector = serde_json::from_str(&serialized).unwrap();
2857        assert_eq!(deserialized.indices, vec![0, 1, 2]);
2858        assert_eq!(deserialized.values, vec![1.0, 2.0, 3.0]);
2859        assert_eq!(
2860            deserialized.tokens,
2861            Some(vec![
2862                "foo".to_string(),
2863                "bar".to_string(),
2864                "baz".to_string()
2865            ])
2866        );
2867    }
2868
2869    #[test]
2870    fn test_sparse_vector_tokens_deserialize_with_tokens_field() {
2871        // Test deserializing JSON that explicitly includes tokens field
2872        let json = r##"{"#type": "sparse_vector", "indices": [5, 10], "values": [0.5, 1.0], "tokens": ["token1", "token2"]}"##;
2873        let sv: SparseVector = serde_json::from_str(json).unwrap();
2874        assert_eq!(sv.indices, vec![5, 10]);
2875        assert_eq!(sv.values, vec![0.5, 1.0]);
2876        assert_eq!(
2877            sv.tokens,
2878            Some(vec!["token1".to_string(), "token2".to_string()])
2879        );
2880    }
2881
2882    #[test]
2883    fn test_sparse_vector_tokens_backward_compatibility() {
2884        // Verify old format (no tokens, no #type) deserializes correctly
2885        let old_json = r#"{"indices": [1, 2], "values": [0.1, 0.2]}"#;
2886        let old_sv: SparseVector = serde_json::from_str(old_json).unwrap();
2887
2888        // Verify new format (with #type, with tokens) deserializes correctly
2889        let new_json = r##"{"#type": "sparse_vector", "indices": [1, 2], "values": [0.1, 0.2], "tokens": ["a", "b"]}"##;
2890        let new_sv: SparseVector = serde_json::from_str(new_json).unwrap();
2891
2892        // Both should have same indices and values
2893        assert_eq!(old_sv.indices, new_sv.indices);
2894        assert_eq!(old_sv.values, new_sv.values);
2895
2896        // Old should have None tokens, new should have Some tokens
2897        assert_eq!(old_sv.tokens, None);
2898        assert_eq!(new_sv.tokens, Some(vec!["a".to_string(), "b".to_string()]));
2899    }
2900
2901    #[test]
2902    fn test_sparse_vector_from_triples_preserves_tokens() {
2903        let triples = vec![
2904            ("apple".to_string(), 10, 0.5),
2905            ("banana".to_string(), 20, 0.7),
2906            ("cherry".to_string(), 30, 0.9),
2907        ];
2908        let sv = SparseVector::from_triples(triples.clone());
2909
2910        assert_eq!(sv.indices, vec![10, 20, 30]);
2911        assert_eq!(sv.values, vec![0.5, 0.7, 0.9]);
2912        assert_eq!(
2913            sv.tokens,
2914            Some(vec![
2915                "apple".to_string(),
2916                "banana".to_string(),
2917                "cherry".to_string()
2918            ])
2919        );
2920
2921        // Roundtrip through serialization
2922        let serialized = serde_json::to_string(&sv).unwrap();
2923        let deserialized: SparseVector = serde_json::from_str(&serialized).unwrap();
2924
2925        assert_eq!(deserialized.indices, sv.indices);
2926        assert_eq!(deserialized.values, sv.values);
2927        assert_eq!(deserialized.tokens, sv.tokens);
2928    }
2929
2930    #[cfg(feature = "pyo3")]
2931    #[test]
2932    fn test_sparse_vector_pyo3_roundtrip_with_tokens() {
2933        ensure_python_interpreter();
2934
2935        pyo3::Python::with_gil(|py| {
2936            use pyo3::types::PyDict;
2937            use pyo3::IntoPyObject;
2938
2939            let dict_in = PyDict::new(py);
2940            dict_in.set_item("indices", vec![0u32, 1, 2]).unwrap();
2941            dict_in
2942                .set_item("values", vec![0.1f32, 0.2f32, 0.3f32])
2943                .unwrap();
2944            dict_in
2945                .set_item("tokens", vec!["foo", "bar", "baz"])
2946                .unwrap();
2947
2948            let sparse: SparseVector = dict_in.clone().into_any().extract().unwrap();
2949            assert_eq!(sparse.indices, vec![0, 1, 2]);
2950            assert_eq!(sparse.values, vec![0.1, 0.2, 0.3]);
2951            assert_eq!(
2952                sparse.tokens,
2953                Some(vec![
2954                    "foo".to_string(),
2955                    "bar".to_string(),
2956                    "baz".to_string()
2957                ])
2958            );
2959
2960            let py_obj = sparse.clone().into_pyobject(py).unwrap();
2961            let dict_out = py_obj.downcast::<PyDict>().unwrap();
2962            let tokens_obj = dict_out.get_item("tokens").unwrap();
2963            let tokens: Vec<String> = tokens_obj
2964                .expect("expected tokens key in Python dict")
2965                .extract()
2966                .unwrap();
2967            assert_eq!(
2968                tokens,
2969                vec!["foo".to_string(), "bar".to_string(), "baz".to_string()]
2970            );
2971        });
2972    }
2973
2974    #[cfg(feature = "pyo3")]
2975    #[test]
2976    fn test_sparse_vector_pyo3_roundtrip_without_tokens() {
2977        ensure_python_interpreter();
2978
2979        pyo3::Python::with_gil(|py| {
2980            use pyo3::types::PyDict;
2981            use pyo3::IntoPyObject;
2982
2983            let dict_in = PyDict::new(py);
2984            dict_in.set_item("indices", vec![5u32]).unwrap();
2985            dict_in.set_item("values", vec![1.5f32]).unwrap();
2986
2987            let sparse: SparseVector = dict_in.clone().into_any().extract().unwrap();
2988            assert_eq!(sparse.indices, vec![5]);
2989            assert_eq!(sparse.values, vec![1.5]);
2990            assert!(sparse.tokens.is_none());
2991
2992            let py_obj = sparse.into_pyobject(py).unwrap();
2993            let dict_out = py_obj.downcast::<PyDict>().unwrap();
2994            let tokens_obj = dict_out.get_item("tokens").unwrap();
2995            let tokens_value = tokens_obj.expect("expected tokens key in Python dict");
2996            assert!(
2997                tokens_value.is_none(),
2998                "expected tokens value in Python dict to be None"
2999            );
3000        });
3001    }
3002
3003    #[test]
3004    fn test_simplifies_identities() {
3005        let all: Where = true.into();
3006        assert_eq!(all.clone() & all.clone(), true.into());
3007        assert_eq!(all.clone() | all.clone(), true.into());
3008
3009        let foo = Key::field("foo").eq("bar");
3010        assert_eq!(foo.clone() & all.clone(), foo.clone());
3011        assert_eq!(all.clone() & foo.clone(), foo.clone());
3012
3013        let none: Where = false.into();
3014        assert_eq!(foo.clone() | none.clone(), foo.clone());
3015        assert_eq!(none | foo.clone(), foo);
3016    }
3017
3018    #[test]
3019    fn test_flattens() {
3020        let foo = Key::field("foo").eq("bar");
3021        let baz = Key::field("baz").eq("quux");
3022
3023        let and_nested = foo.clone() & (baz.clone() & foo.clone());
3024        assert_eq!(
3025            and_nested,
3026            Where::Composite(CompositeExpression {
3027                operator: BooleanOperator::And,
3028                children: vec![foo.clone(), baz.clone(), foo.clone()]
3029            })
3030        );
3031
3032        let or_nested = foo.clone() | (baz.clone() | foo.clone());
3033        assert_eq!(
3034            or_nested,
3035            Where::Composite(CompositeExpression {
3036                operator: BooleanOperator::Or,
3037                children: vec![foo.clone(), baz.clone(), foo.clone()]
3038            })
3039        );
3040    }
3041}