chroma_types/
collection.rs

1use std::str::FromStr;
2
3use super::{Metadata, MetadataValueConversionError};
4use crate::{
5    chroma_proto, test_segment, CollectionConfiguration, InternalCollectionConfiguration, KnnIndex,
6    Schema, 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, ensuring both are consistent.
232    pub fn reconcile_schema_with_config(&mut self, knn_index: KnnIndex) -> Result<(), SchemaError> {
233        let reconciled_schema = Schema::reconcile_schema_and_config(
234            self.schema.as_ref(),
235            Some(&self.config),
236            knn_index,
237        )?;
238
239        self.config = InternalCollectionConfiguration::try_from(&reconciled_schema)
240            .map_err(|reason| SchemaError::InvalidSchema { reason })?;
241        self.schema = Some(reconciled_schema);
242
243        Ok(())
244    }
245
246    pub fn test_collection(dim: i32) -> Self {
247        Collection {
248            name: "test_collection".to_string(),
249            dimension: Some(dim),
250            tenant: "default_tenant".to_string(),
251            database: "default_database".to_string(),
252            database_id: DatabaseUuid::new(),
253            ..Default::default()
254        }
255    }
256}
257
258#[derive(Error, Debug)]
259pub enum CollectionConversionError {
260    #[error("Invalid config: {0}")]
261    InvalidConfig(#[from] serde_json::Error),
262    #[error("Invalid UUID")]
263    InvalidUuid,
264    #[error(transparent)]
265    MetadataValueConversionError(#[from] MetadataValueConversionError),
266    #[error("Missing Database Id")]
267    MissingDatabaseId,
268}
269
270impl ChromaError for CollectionConversionError {
271    fn code(&self) -> ErrorCodes {
272        match self {
273            CollectionConversionError::InvalidConfig(_) => ErrorCodes::InvalidArgument,
274            CollectionConversionError::InvalidUuid => ErrorCodes::InvalidArgument,
275            CollectionConversionError::MetadataValueConversionError(e) => e.code(),
276            CollectionConversionError::MissingDatabaseId => ErrorCodes::Internal,
277        }
278    }
279}
280
281impl TryFrom<chroma_proto::Collection> for Collection {
282    type Error = CollectionConversionError;
283
284    fn try_from(proto_collection: chroma_proto::Collection) -> Result<Self, Self::Error> {
285        let collection_id = CollectionUuid::from_str(&proto_collection.id)
286            .map_err(|_| CollectionConversionError::InvalidUuid)?;
287        let collection_metadata: Option<Metadata> = match proto_collection.metadata {
288            Some(proto_metadata) => match proto_metadata.try_into() {
289                Ok(metadata) => Some(metadata),
290                Err(e) => return Err(CollectionConversionError::MetadataValueConversionError(e)),
291            },
292            None => None,
293        };
294        // TODO(@codetheweb): this be updated to error with "missing field" once all SysDb deployments are up-to-date
295        let updated_at = match proto_collection.updated_at {
296            Some(updated_at) => {
297                SystemTime::UNIX_EPOCH
298                    + Duration::new(updated_at.seconds as u64, updated_at.nanos as u32)
299            }
300            None => SystemTime::now(),
301        };
302        let database_id = match proto_collection.database_id {
303            Some(db_id) => DatabaseUuid::from_str(&db_id)
304                .map_err(|_| CollectionConversionError::InvalidUuid)?,
305            None => {
306                return Err(CollectionConversionError::MissingDatabaseId);
307            }
308        };
309        let schema = match proto_collection.schema_str {
310            Some(schema_str) if !schema_str.is_empty() => Some(serde_json::from_str(&schema_str)?),
311            _ => None,
312        };
313
314        Ok(Collection {
315            collection_id,
316            name: proto_collection.name,
317            config: serde_json::from_str(&proto_collection.configuration_json_str)?,
318            schema,
319            metadata: collection_metadata,
320            dimension: proto_collection.dimension,
321            tenant: proto_collection.tenant,
322            database: proto_collection.database,
323            log_position: proto_collection.log_position,
324            version: proto_collection.version,
325            total_records_post_compaction: proto_collection.total_records_post_compaction,
326            size_bytes_post_compaction: proto_collection.size_bytes_post_compaction,
327            last_compaction_time_secs: proto_collection.last_compaction_time_secs,
328            version_file_path: proto_collection.version_file_path,
329            root_collection_id: proto_collection
330                .root_collection_id
331                .map(|uuid| CollectionUuid(Uuid::try_parse(&uuid).unwrap())),
332            lineage_file_path: proto_collection.lineage_file_path,
333            updated_at,
334            database_id,
335        })
336    }
337}
338
339#[derive(Error, Debug)]
340pub enum CollectionToProtoError {
341    #[error("Could not serialize config: {0}")]
342    ConfigSerialization(#[from] serde_json::Error),
343}
344
345impl ChromaError for CollectionToProtoError {
346    fn code(&self) -> ErrorCodes {
347        match self {
348            CollectionToProtoError::ConfigSerialization(_) => ErrorCodes::Internal,
349        }
350    }
351}
352
353impl TryFrom<Collection> for chroma_proto::Collection {
354    type Error = CollectionToProtoError;
355
356    fn try_from(value: Collection) -> Result<Self, Self::Error> {
357        Ok(Self {
358            id: value.collection_id.0.to_string(),
359            name: value.name,
360            configuration_json_str: serde_json::to_string(&value.config)?,
361            schema_str: value
362                .schema
363                .map(|s| serde_json::to_string(&s))
364                .transpose()?,
365            metadata: value.metadata.map(Into::into),
366            dimension: value.dimension,
367            tenant: value.tenant,
368            database: value.database,
369            log_position: value.log_position,
370            version: value.version,
371            total_records_post_compaction: value.total_records_post_compaction,
372            size_bytes_post_compaction: value.size_bytes_post_compaction,
373            last_compaction_time_secs: value.last_compaction_time_secs,
374            version_file_path: value.version_file_path,
375            root_collection_id: value.root_collection_id.map(|uuid| uuid.0.to_string()),
376            lineage_file_path: value.lineage_file_path,
377            updated_at: Some(value.updated_at.into()),
378            database_id: Some(value.database_id.0.to_string()),
379        })
380    }
381}
382
383#[derive(Clone, Debug)]
384pub struct CollectionAndSegments {
385    pub collection: Collection,
386    pub metadata_segment: Segment,
387    pub record_segment: Segment,
388    pub vector_segment: Segment,
389}
390
391impl CollectionAndSegments {
392    // If dimension is not set and vector segment has no files,
393    // we assume this is an uninitialized collection
394    pub fn is_uninitialized(&self) -> bool {
395        self.collection.dimension.is_none() && self.vector_segment.file_path.is_empty()
396    }
397
398    pub fn test(dim: i32) -> Self {
399        let collection = Collection::test_collection(dim);
400        let collection_uuid = collection.collection_id;
401        Self {
402            collection,
403            metadata_segment: test_segment(collection_uuid, SegmentScope::METADATA),
404            record_segment: test_segment(collection_uuid, SegmentScope::RECORD),
405            vector_segment: test_segment(collection_uuid, SegmentScope::VECTOR),
406        }
407    }
408}
409
410#[derive(Deserialize, Serialize, Debug, Clone)]
411#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
412pub struct CreateCollectionPayload {
413    pub name: String,
414    pub schema: Option<Schema>,
415    pub configuration: Option<CollectionConfiguration>,
416    pub metadata: Option<Metadata>,
417    #[serde(default)]
418    pub get_or_create: bool,
419}
420
421#[derive(Deserialize, Serialize, Debug, Clone)]
422#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
423pub struct UpdateCollectionPayload {
424    pub new_name: Option<String>,
425    pub new_metadata: Option<UpdateMetadata>,
426    pub new_configuration: Option<UpdateCollectionConfiguration>,
427}
428
429#[cfg(test)]
430mod test {
431    use super::*;
432
433    #[test]
434    fn test_collection_try_from() {
435        // Create a valid Schema and serialize it
436        let schema = Schema::new_default(crate::KnnIndex::Spann);
437        let schema_str = serde_json::to_string(&schema).unwrap();
438
439        let proto_collection = chroma_proto::Collection {
440            id: "00000000-0000-0000-0000-000000000000".to_string(),
441            name: "foo".to_string(),
442            configuration_json_str: "{\"a\": \"param\", \"b\": \"param2\", \"3\": true}"
443                .to_string(),
444            schema_str: Some(schema_str),
445            metadata: None,
446            dimension: None,
447            tenant: "baz".to_string(),
448            database: "qux".to_string(),
449            log_position: 0,
450            version: 0,
451            total_records_post_compaction: 0,
452            size_bytes_post_compaction: 0,
453            last_compaction_time_secs: 0,
454            version_file_path: Some("version_file_path".to_string()),
455            root_collection_id: Some("00000000-0000-0000-0000-000000000000".to_string()),
456            lineage_file_path: Some("lineage_file_path".to_string()),
457            updated_at: Some(prost_types::Timestamp {
458                seconds: 1,
459                nanos: 1,
460            }),
461            database_id: Some("00000000-0000-0000-0000-000000000000".to_string()),
462        };
463        let converted_collection: Collection = proto_collection.try_into().unwrap();
464        assert_eq!(
465            converted_collection.collection_id,
466            CollectionUuid(Uuid::nil())
467        );
468        assert_eq!(converted_collection.name, "foo".to_string());
469        assert_eq!(converted_collection.metadata, None);
470        assert_eq!(converted_collection.dimension, None);
471        assert_eq!(converted_collection.tenant, "baz".to_string());
472        assert_eq!(converted_collection.database, "qux".to_string());
473        assert_eq!(converted_collection.total_records_post_compaction, 0);
474        assert_eq!(converted_collection.size_bytes_post_compaction, 0);
475        assert_eq!(converted_collection.last_compaction_time_secs, 0);
476        assert_eq!(
477            converted_collection.version_file_path,
478            Some("version_file_path".to_string())
479        );
480        assert_eq!(
481            converted_collection.root_collection_id,
482            Some(CollectionUuid(Uuid::nil()))
483        );
484        assert_eq!(
485            converted_collection.lineage_file_path,
486            Some("lineage_file_path".to_string())
487        );
488        assert_eq!(
489            converted_collection.updated_at,
490            SystemTime::UNIX_EPOCH + Duration::new(1, 1)
491        );
492        assert_eq!(converted_collection.database_id, DatabaseUuid(Uuid::nil()));
493    }
494
495    #[test]
496    fn storage_prefix_for_log_format() {
497        let collection_id = Uuid::parse_str("34e72052-5e60-47cb-be88-19a9715b7026")
498            .map(CollectionUuid)
499            .unwrap();
500        let prefix = collection_id.storage_prefix_for_log();
501        assert_eq!("logs/34e72052-5e60-47cb-be88-19a9715b7026", prefix);
502    }
503}