chroma_types/
collection.rs

1use std::str::FromStr;
2
3use super::{Metadata, MetadataValueConversionError};
4use crate::{
5    chroma_proto, test_segment, CollectionConfiguration, InternalCollectionConfiguration, Schema,
6    SchemaError, Segment, SegmentScope, UpdateCollectionConfiguration, UpdateMetadata,
7};
8use chroma_error::{ChromaError, ErrorCodes};
9use serde::{Deserialize, Serialize};
10use std::time::{Duration, SystemTime};
11use thiserror::Error;
12use uuid::Uuid;
13
14#[cfg(feature = "pyo3")]
15use pyo3::{exceptions::PyValueError, types::PyAnyMethods};
16
17/// CollectionUuid is a wrapper around Uuid to provide a type for the collection id.
18#[derive(
19    Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize,
20)]
21#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
22pub struct CollectionUuid(pub Uuid);
23
24/// DatabaseUuid is a wrapper around Uuid to provide a type for the database id.
25#[derive(
26    Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize,
27)]
28#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
29pub struct DatabaseUuid(pub Uuid);
30
31impl DatabaseUuid {
32    pub fn new() -> Self {
33        DatabaseUuid(Uuid::new_v4())
34    }
35}
36
37impl CollectionUuid {
38    pub fn new() -> Self {
39        CollectionUuid(Uuid::new_v4())
40    }
41
42    pub fn storage_prefix_for_log(&self) -> String {
43        format!("logs/{}", self)
44    }
45}
46
47impl std::str::FromStr for CollectionUuid {
48    type Err = uuid::Error;
49
50    fn from_str(s: &str) -> Result<Self, Self::Err> {
51        match Uuid::parse_str(s) {
52            Ok(uuid) => Ok(CollectionUuid(uuid)),
53            Err(err) => Err(err),
54        }
55    }
56}
57
58impl std::str::FromStr for DatabaseUuid {
59    type Err = uuid::Error;
60
61    fn from_str(s: &str) -> Result<Self, Self::Err> {
62        match Uuid::parse_str(s) {
63            Ok(uuid) => Ok(DatabaseUuid(uuid)),
64            Err(err) => Err(err),
65        }
66    }
67}
68
69impl std::fmt::Display for DatabaseUuid {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        write!(f, "{}", self.0)
72    }
73}
74
75impl std::fmt::Display for CollectionUuid {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        write!(f, "{}", self.0)
78    }
79}
80
81fn serialize_internal_collection_configuration<S: serde::Serializer>(
82    config: &InternalCollectionConfiguration,
83    serializer: S,
84) -> Result<S::Ok, S::Error> {
85    let collection_config: CollectionConfiguration = config.clone().into();
86    collection_config.serialize(serializer)
87}
88
89fn deserialize_internal_collection_configuration<'de, D: serde::Deserializer<'de>>(
90    deserializer: D,
91) -> Result<InternalCollectionConfiguration, D::Error> {
92    let collection_config = CollectionConfiguration::deserialize(deserializer)?;
93    collection_config
94        .try_into()
95        .map_err(serde::de::Error::custom)
96}
97
98#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
99#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
100#[cfg_attr(feature = "pyo3", pyo3::pyclass)]
101pub struct Collection {
102    #[serde(rename = "id")]
103    pub collection_id: CollectionUuid,
104    pub name: String,
105    #[serde(
106        serialize_with = "serialize_internal_collection_configuration",
107        deserialize_with = "deserialize_internal_collection_configuration",
108        rename = "configuration_json"
109    )]
110    #[cfg_attr(feature = "utoipa", schema(value_type = CollectionConfiguration))]
111    pub config: InternalCollectionConfiguration,
112    pub schema: Option<Schema>,
113    pub metadata: Option<Metadata>,
114    pub dimension: Option<i32>,
115    pub tenant: String,
116    pub database: String,
117    pub log_position: i64,
118    pub version: i32,
119    #[serde(skip)]
120    pub total_records_post_compaction: u64,
121    #[serde(skip)]
122    pub size_bytes_post_compaction: u64,
123    #[serde(skip)]
124    pub last_compaction_time_secs: u64,
125    #[serde(skip)]
126    pub version_file_path: Option<String>,
127    #[serde(skip)]
128    pub root_collection_id: Option<CollectionUuid>,
129    #[serde(skip)]
130    pub lineage_file_path: Option<String>,
131    #[serde(skip, default = "SystemTime::now")]
132    pub updated_at: SystemTime,
133    #[serde(skip)]
134    pub database_id: DatabaseUuid,
135}
136
137impl Default for Collection {
138    fn default() -> Self {
139        Self {
140            collection_id: CollectionUuid::new(),
141            name: "".to_string(),
142            config: InternalCollectionConfiguration::default_hnsw(),
143            schema: None,
144            metadata: None,
145            dimension: None,
146            tenant: "".to_string(),
147            database: "".to_string(),
148            log_position: 0,
149            version: 0,
150            total_records_post_compaction: 0,
151            size_bytes_post_compaction: 0,
152            last_compaction_time_secs: 0,
153            version_file_path: None,
154            root_collection_id: None,
155            lineage_file_path: None,
156            updated_at: SystemTime::now(),
157            database_id: DatabaseUuid::new(),
158        }
159    }
160}
161
162#[cfg(feature = "pyo3")]
163#[pyo3::pymethods]
164impl Collection {
165    #[getter]
166    fn id<'py>(&self, py: pyo3::Python<'py>) -> pyo3::PyResult<pyo3::Bound<'py, pyo3::PyAny>> {
167        let res = pyo3::prelude::PyModule::import(py, "uuid")?
168            .getattr("UUID")?
169            .call1((self.collection_id.to_string(),))?;
170        Ok(res)
171    }
172
173    #[getter]
174    fn configuration<'py>(
175        &self,
176        py: pyo3::Python<'py>,
177    ) -> pyo3::PyResult<pyo3::Bound<'py, pyo3::PyAny>> {
178        let config: crate::CollectionConfiguration = self.config.clone().into();
179        let config_json_str = serde_json::to_string(&config).unwrap();
180        let res = pyo3::prelude::PyModule::import(py, "json")?
181            .getattr("loads")?
182            .call1((config_json_str,))?;
183        Ok(res)
184    }
185
186    #[getter]
187    fn schema<'py>(
188        &self,
189        py: pyo3::Python<'py>,
190    ) -> pyo3::PyResult<Option<pyo3::Bound<'py, pyo3::PyAny>>> {
191        match self.schema.as_ref() {
192            Some(schema) => {
193                let schema_json = serde_json::to_string(schema)
194                    .map_err(|err| PyValueError::new_err(err.to_string()))?;
195                let res = pyo3::prelude::PyModule::import(py, "json")?
196                    .getattr("loads")?
197                    .call1((schema_json,))?;
198                Ok(Some(res))
199            }
200            None => Ok(None),
201        }
202    }
203
204    #[getter]
205    pub fn name(&self) -> &str {
206        &self.name
207    }
208
209    #[getter]
210    pub fn metadata(&self) -> Option<Metadata> {
211        self.metadata.clone()
212    }
213
214    #[getter]
215    pub fn dimension(&self) -> Option<i32> {
216        self.dimension
217    }
218
219    #[getter]
220    pub fn tenant(&self) -> &str {
221        &self.tenant
222    }
223
224    #[getter]
225    pub fn database(&self) -> &str {
226        &self.database
227    }
228}
229
230impl Collection {
231    /// Reconcile the collection schema and configuration when serving read requests.
232    ///
233    /// The read path needs to tolerate collections that only have a configuration persisted.
234    /// This helper hydrates `schema` from the stored configuration when needed, or regenerates
235    /// the configuration from the existing schema to keep both representations consistent.
236    pub fn reconcile_schema_for_read(&mut self) -> Result<(), SchemaError> {
237        if let Some(schema) = self.schema.as_ref() {
238            self.config = InternalCollectionConfiguration::try_from(schema)
239                .map_err(|reason| SchemaError::InvalidSchema { reason })?;
240        } else {
241            self.schema = Some(Schema::try_from(&self.config)?);
242        }
243
244        Ok(())
245    }
246
247    pub fn test_collection(dim: i32) -> Self {
248        Collection {
249            name: "test_collection".to_string(),
250            dimension: Some(dim),
251            tenant: "default_tenant".to_string(),
252            database: "default_database".to_string(),
253            database_id: DatabaseUuid::new(),
254            ..Default::default()
255        }
256    }
257}
258
259#[derive(Error, Debug)]
260pub enum CollectionConversionError {
261    #[error("Invalid config: {0}")]
262    InvalidConfig(#[from] serde_json::Error),
263    #[error("Invalid UUID")]
264    InvalidUuid,
265    #[error(transparent)]
266    MetadataValueConversionError(#[from] MetadataValueConversionError),
267    #[error("Missing Database Id")]
268    MissingDatabaseId,
269}
270
271impl ChromaError for CollectionConversionError {
272    fn code(&self) -> ErrorCodes {
273        match self {
274            CollectionConversionError::InvalidConfig(_) => ErrorCodes::InvalidArgument,
275            CollectionConversionError::InvalidUuid => ErrorCodes::InvalidArgument,
276            CollectionConversionError::MetadataValueConversionError(e) => e.code(),
277            CollectionConversionError::MissingDatabaseId => ErrorCodes::Internal,
278        }
279    }
280}
281
282impl TryFrom<chroma_proto::Collection> for Collection {
283    type Error = CollectionConversionError;
284
285    fn try_from(proto_collection: chroma_proto::Collection) -> Result<Self, Self::Error> {
286        let collection_id = CollectionUuid::from_str(&proto_collection.id)
287            .map_err(|_| CollectionConversionError::InvalidUuid)?;
288        let collection_metadata: Option<Metadata> = match proto_collection.metadata {
289            Some(proto_metadata) => match proto_metadata.try_into() {
290                Ok(metadata) => Some(metadata),
291                Err(e) => return Err(CollectionConversionError::MetadataValueConversionError(e)),
292            },
293            None => None,
294        };
295        // TODO(@codetheweb): this be updated to error with "missing field" once all SysDb deployments are up-to-date
296        let updated_at = match proto_collection.updated_at {
297            Some(updated_at) => {
298                SystemTime::UNIX_EPOCH
299                    + Duration::new(updated_at.seconds as u64, updated_at.nanos as u32)
300            }
301            None => SystemTime::now(),
302        };
303        let database_id = match proto_collection.database_id {
304            Some(db_id) => DatabaseUuid::from_str(&db_id)
305                .map_err(|_| CollectionConversionError::InvalidUuid)?,
306            None => {
307                return Err(CollectionConversionError::MissingDatabaseId);
308            }
309        };
310        let schema = match proto_collection.schema_str {
311            Some(schema_str) if !schema_str.is_empty() => Some(serde_json::from_str(&schema_str)?),
312            _ => None,
313        };
314
315        Ok(Collection {
316            collection_id,
317            name: proto_collection.name,
318            config: serde_json::from_str(&proto_collection.configuration_json_str)?,
319            schema,
320            metadata: collection_metadata,
321            dimension: proto_collection.dimension,
322            tenant: proto_collection.tenant,
323            database: proto_collection.database,
324            log_position: proto_collection.log_position,
325            version: proto_collection.version,
326            total_records_post_compaction: proto_collection.total_records_post_compaction,
327            size_bytes_post_compaction: proto_collection.size_bytes_post_compaction,
328            last_compaction_time_secs: proto_collection.last_compaction_time_secs,
329            version_file_path: proto_collection.version_file_path,
330            root_collection_id: proto_collection
331                .root_collection_id
332                .map(|uuid| CollectionUuid(Uuid::try_parse(&uuid).unwrap())),
333            lineage_file_path: proto_collection.lineage_file_path,
334            updated_at,
335            database_id,
336        })
337    }
338}
339
340#[derive(Error, Debug)]
341pub enum CollectionToProtoError {
342    #[error("Could not serialize config: {0}")]
343    ConfigSerialization(#[from] serde_json::Error),
344}
345
346impl ChromaError for CollectionToProtoError {
347    fn code(&self) -> ErrorCodes {
348        match self {
349            CollectionToProtoError::ConfigSerialization(_) => ErrorCodes::Internal,
350        }
351    }
352}
353
354impl TryFrom<Collection> for chroma_proto::Collection {
355    type Error = CollectionToProtoError;
356
357    fn try_from(value: Collection) -> Result<Self, Self::Error> {
358        Ok(Self {
359            id: value.collection_id.0.to_string(),
360            name: value.name,
361            configuration_json_str: serde_json::to_string(&value.config)?,
362            schema_str: value
363                .schema
364                .map(|s| serde_json::to_string(&s))
365                .transpose()?,
366            metadata: value.metadata.map(Into::into),
367            dimension: value.dimension,
368            tenant: value.tenant,
369            database: value.database,
370            log_position: value.log_position,
371            version: value.version,
372            total_records_post_compaction: value.total_records_post_compaction,
373            size_bytes_post_compaction: value.size_bytes_post_compaction,
374            last_compaction_time_secs: value.last_compaction_time_secs,
375            version_file_path: value.version_file_path,
376            root_collection_id: value.root_collection_id.map(|uuid| uuid.0.to_string()),
377            lineage_file_path: value.lineage_file_path,
378            updated_at: Some(value.updated_at.into()),
379            database_id: Some(value.database_id.0.to_string()),
380        })
381    }
382}
383
384#[derive(Clone, Debug)]
385pub struct CollectionAndSegments {
386    pub collection: Collection,
387    pub metadata_segment: Segment,
388    pub record_segment: Segment,
389    pub vector_segment: Segment,
390}
391
392impl CollectionAndSegments {
393    // If dimension is not set and vector segment has no files,
394    // we assume this is an uninitialized collection
395    pub fn is_uninitialized(&self) -> bool {
396        self.collection.dimension.is_none() && self.vector_segment.file_path.is_empty()
397    }
398
399    pub fn test(dim: i32) -> Self {
400        let collection = Collection::test_collection(dim);
401        let collection_uuid = collection.collection_id;
402        Self {
403            collection,
404            metadata_segment: test_segment(collection_uuid, SegmentScope::METADATA),
405            record_segment: test_segment(collection_uuid, SegmentScope::RECORD),
406            vector_segment: test_segment(collection_uuid, SegmentScope::VECTOR),
407        }
408    }
409}
410
411#[derive(Deserialize, Serialize, Debug, Clone)]
412#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
413pub struct CreateCollectionPayload {
414    pub name: String,
415    pub schema: Option<Schema>,
416    pub configuration: Option<CollectionConfiguration>,
417    pub metadata: Option<Metadata>,
418    #[serde(default)]
419    pub get_or_create: bool,
420}
421
422#[derive(Deserialize, Serialize, Debug, Clone)]
423#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
424pub struct UpdateCollectionPayload {
425    pub new_name: Option<String>,
426    pub new_metadata: Option<UpdateMetadata>,
427    pub new_configuration: Option<UpdateCollectionConfiguration>,
428}
429
430#[cfg(test)]
431mod test {
432    use super::*;
433
434    #[test]
435    fn test_collection_try_from() {
436        // Create a valid Schema and serialize it
437        let schema = Schema::new_default(crate::KnnIndex::Spann);
438        let schema_str = serde_json::to_string(&schema).unwrap();
439
440        let proto_collection = chroma_proto::Collection {
441            id: "00000000-0000-0000-0000-000000000000".to_string(),
442            name: "foo".to_string(),
443            configuration_json_str: "{\"a\": \"param\", \"b\": \"param2\", \"3\": true}"
444                .to_string(),
445            schema_str: Some(schema_str),
446            metadata: None,
447            dimension: None,
448            tenant: "baz".to_string(),
449            database: "qux".to_string(),
450            log_position: 0,
451            version: 0,
452            total_records_post_compaction: 0,
453            size_bytes_post_compaction: 0,
454            last_compaction_time_secs: 0,
455            version_file_path: Some("version_file_path".to_string()),
456            root_collection_id: Some("00000000-0000-0000-0000-000000000000".to_string()),
457            lineage_file_path: Some("lineage_file_path".to_string()),
458            updated_at: Some(prost_types::Timestamp {
459                seconds: 1,
460                nanos: 1,
461            }),
462            database_id: Some("00000000-0000-0000-0000-000000000000".to_string()),
463        };
464        let converted_collection: Collection = proto_collection.try_into().unwrap();
465        assert_eq!(
466            converted_collection.collection_id,
467            CollectionUuid(Uuid::nil())
468        );
469        assert_eq!(converted_collection.name, "foo".to_string());
470        assert_eq!(converted_collection.metadata, None);
471        assert_eq!(converted_collection.dimension, None);
472        assert_eq!(converted_collection.tenant, "baz".to_string());
473        assert_eq!(converted_collection.database, "qux".to_string());
474        assert_eq!(converted_collection.total_records_post_compaction, 0);
475        assert_eq!(converted_collection.size_bytes_post_compaction, 0);
476        assert_eq!(converted_collection.last_compaction_time_secs, 0);
477        assert_eq!(
478            converted_collection.version_file_path,
479            Some("version_file_path".to_string())
480        );
481        assert_eq!(
482            converted_collection.root_collection_id,
483            Some(CollectionUuid(Uuid::nil()))
484        );
485        assert_eq!(
486            converted_collection.lineage_file_path,
487            Some("lineage_file_path".to_string())
488        );
489        assert_eq!(
490            converted_collection.updated_at,
491            SystemTime::UNIX_EPOCH + Duration::new(1, 1)
492        );
493        assert_eq!(converted_collection.database_id, DatabaseUuid(Uuid::nil()));
494    }
495
496    #[test]
497    fn storage_prefix_for_log_format() {
498        let collection_id = Uuid::parse_str("34e72052-5e60-47cb-be88-19a9715b7026")
499            .map(CollectionUuid)
500            .unwrap();
501        let prefix = collection_id.storage_prefix_for_log();
502        assert_eq!("logs/34e72052-5e60-47cb-be88-19a9715b7026", prefix);
503    }
504}