Skip to main content

itzma_core/
document.rs

1//! The data model: documents, WAL operations, and the per-namespace schema.
2
3use serde::{Deserialize, Serialize};
4
5use crate::attrs::AttrSchema;
6use crate::error::{ItzmaError, Result};
7
8/// One stored item: an id, a vector, and optional free-form JSON.
9///
10/// The id is the identity. Upserting a document whose id already exists
11/// replaces it wholesale, vector and attributes together.
12///
13/// # JSON form
14///
15/// This is what appears inside WAL objects. `attrs` is left out when `None`:
16///
17/// ```json
18/// {"id": "a", "vector": [0.1, 0.2], "attrs": {"title": "hello"}, "sparse": [[3, 0.9]]}
19/// ```
20#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21pub struct Document {
22    /// Caller-chosen identifier, unique within a namespace. Any string.
23    pub id: String,
24    /// Embedding. Its length must equal the namespace's `dim`, and every
25    /// component must be finite.
26    pub vector: Vec<f32>,
27    /// Arbitrary JSON stored next to the vector and returned on every
28    /// [`Hit`](crate::Hit). It is checked against the namespace's attribute
29    /// schema on write.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub attrs: Option<serde_json::Value>,
32    /// An optional sparse vector, searched by
33    /// [`Namespace::query_sparse`](crate::Namespace::query_sparse). A
34    /// namespace does not declare sparse support up front — some documents
35    /// carry one, some don't, the same shape `attrs` has. `None` on a
36    /// document written before this field existed.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub sparse: Option<SparseVector>,
39}
40
41/// A sparse vector: term id and weight pairs, in the style SPLADE and
42/// similar learned-sparse models produce. Itzma assigns no meaning to a term
43/// id — it is the caller's own vocabulary (a tokenizer's ids, typically) —
44/// and keeps no string dictionary. See
45/// [`Namespace::query_sparse`](crate::Namespace::query_sparse).
46pub type SparseVector = Vec<(u32, f32)>;
47
48/// The most terms one document's sparse vector may hold. The term count is a
49/// `u16` in the WAL object and in `sparse.bin`, and a longer vector is refused
50/// by `upsert` with [`ItzmaError::InvalidVector`] before anything is written.
51pub const MAX_SPARSE_TERMS: usize = u16::MAX as usize;
52
53/// The most bytes an id may be: a document's `id` on `upsert`, or an id
54/// passed to `delete`. An id is a free-form string with no other structure
55/// (a UUID, a natural key, whatever the caller already has), but it is
56/// stored in every WAL object and segment that touches it, so an unbounded
57/// one lets a single write blow up an object's size. 512 bytes covers any
58/// realistic key (a UUID is 36) with room to spare.
59pub const MAX_ID_BYTES: usize = 512;
60
61/// One mutation recorded in the write-ahead log.
62///
63/// Ops replay in log order, and within a WAL object in list order. The last
64/// op touching an id wins, whether that is an upsert or a delete.
65///
66/// # JSON form
67///
68/// Externally tagged, snake_case:
69///
70/// ```json
71/// [{"upsert": {"id": "a", "vector": [1.0, 2.0]}}, {"delete": "b"}]
72/// ```
73#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
74#[serde(rename_all = "snake_case")]
75pub enum WalOp {
76    /// Insert the document, or replace the one with the same id.
77    Upsert(Document),
78    /// Remove the document with this id. Deleting an id that does not exist
79    /// is not an error.
80    Delete(String),
81}
82
83/// How distance between two vectors is measured.
84///
85/// The choice is made once per namespace. Every metric is reported so that
86/// **lower means closer**; see [`crate::search::distance`] for the exact
87/// formulas.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "snake_case")]
90pub enum Metric {
91    /// Angle between vectors, reported as `1 - cosine similarity`. Ignores
92    /// vector length. Zero vectors are rejected on write.
93    Cosine,
94    /// Squared Euclidean distance. The square root is skipped because it does
95    /// not change the ordering.
96    L2,
97    /// Inner product, negated so that a larger dot product sorts first.
98    Dot,
99}
100
101/// The shape every document in a namespace must have.
102///
103/// Fixed when the namespace is created and stored in its manifest, and again in
104/// `schema.json`, which is written once and never changed. It cannot be
105/// changed afterwards; make a new namespace instead.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct Schema {
108    /// Number of components in every vector. Must be at least 1.
109    pub dim: usize,
110    /// Distance metric used by queries.
111    pub metric: Metric,
112    /// The typed attribute fields. Empty means the namespace takes
113    /// no attributes. A schemaless value has none declared and
114    /// stays free-form; nothing public can build that state.
115    #[serde(
116        default = "AttrSchema::free_form",
117        skip_serializing_if = "AttrSchema::is_free_form"
118    )]
119    pub attrs: AttrSchema,
120}
121
122impl Schema {
123    /// A schema with no attribute fields: documents may carry no `attrs`.
124    /// Declare fields with [`with_attrs`](Self::with_attrs).
125    pub const fn new(dim: usize, metric: Metric) -> Self {
126        Self {
127            dim,
128            metric,
129            attrs: AttrSchema::new(),
130        }
131    }
132
133    /// This schema with the attribute fields `attrs`.
134    #[must_use]
135    pub fn with_attrs(mut self, attrs: AttrSchema) -> Self {
136        self.attrs = attrs;
137        self
138    }
139
140    /// Check a vector against this schema without touching storage.
141    ///
142    /// Used on every document written and on every query vector.
143    ///
144    /// # Errors
145    ///
146    /// - [`ItzmaError::DimensionMismatch`] if `vector.len() != self.dim`.
147    /// - [`ItzmaError::InvalidVector`] if any component is NaN or infinite, or
148    ///   if the metric is [`Metric::Cosine`] and every component is zero.
149    ///
150    /// # Examples
151    ///
152    /// ```
153    /// use itzma_core::{Metric, Schema};
154    ///
155    /// let schema = Schema::new(2, Metric::Cosine);
156    /// assert!(schema.validate(&[1.0, 0.5]).is_ok());
157    /// assert!(schema.validate(&[1.0]).is_err());
158    /// assert!(schema.validate(&[0.0, 0.0]).is_err());
159    /// ```
160    pub fn validate(&self, vector: &[f32]) -> Result<()> {
161        if vector.len() != self.dim {
162            return Err(ItzmaError::DimensionMismatch {
163                expected: self.dim,
164                got: vector.len(),
165            });
166        }
167        if vector.iter().any(|x| !x.is_finite()) {
168            return Err(ItzmaError::InvalidVector("non-finite component"));
169        }
170        if self.metric == Metric::Cosine && vector.iter().all(|x| *x == 0.0) {
171            return Err(ItzmaError::InvalidVector("zero vector under cosine"));
172        }
173        Ok(())
174    }
175}
176
177/// Check an id's shape without touching storage: not empty, not longer than
178/// [`MAX_ID_BYTES`]. Shared by [`Document::validate_id`] (a document's `id`
179/// on `upsert`) and by `Namespace::delete`, which has no `Document` to hang
180/// the check on.
181///
182/// # Errors
183///
184/// [`ItzmaError::InvalidId`] if the id is empty or over the limit.
185pub(crate) fn validate_id(id: &str) -> Result<()> {
186    if id.is_empty() {
187        return Err(ItzmaError::InvalidId("empty"));
188    }
189    if id.len() > MAX_ID_BYTES {
190        return Err(ItzmaError::InvalidId("too long"));
191    }
192    Ok(())
193}
194
195impl Document {
196    /// Check this document's id without touching storage. Called on every
197    /// upsert, before [`validate_sparse`](Self::validate_sparse).
198    ///
199    /// # Errors
200    ///
201    /// [`ItzmaError::InvalidId`] if the id is empty or longer than
202    /// [`MAX_ID_BYTES`].
203    pub fn validate_id(&self) -> Result<()> {
204        validate_id(&self.id)
205    }
206
207    /// Check this document's sparse vector, if it has one, without touching
208    /// storage. Called on every upsert, after
209    /// [`Schema::validate`](Schema::validate).
210    ///
211    /// # Errors
212    ///
213    /// [`ItzmaError::InvalidVector`] if the same term id appears twice, a
214    /// weight is NaN or infinite, or there are more than [`MAX_SPARSE_TERMS`]
215    /// terms (the stored term count is a `u16`).
216    pub fn validate_sparse(&self) -> Result<()> {
217        match &self.sparse {
218            None => Ok(()),
219            Some(sparse) => validate_sparse_terms(
220                sparse.iter().map(|(term, _)| *term),
221                sparse.iter().map(|(_, weight)| *weight),
222            ),
223        }
224    }
225}
226
227/// The checks of [`Document::validate_sparse`] on terms and weights given
228/// apart, so a columnar batch runs exactly the same ones.
229pub(crate) fn validate_sparse_terms(
230    terms: impl ExactSizeIterator<Item = u32>,
231    mut weights: impl Iterator<Item = f32>,
232) -> Result<()> {
233    if terms.len() > MAX_SPARSE_TERMS {
234        return Err(ItzmaError::InvalidVector("too many sparse terms"));
235    }
236    if weights.any(|weight| !weight.is_finite()) {
237        return Err(ItzmaError::InvalidVector("non-finite sparse weight"));
238    }
239    let mut seen = std::collections::HashSet::with_capacity(terms.len());
240    let mut terms = terms;
241    if terms.any(|term| !seen.insert(term)) {
242        return Err(ItzmaError::InvalidVector(
243            "duplicate term id in sparse vector",
244        ));
245    }
246    Ok(())
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    fn schema(metric: Metric) -> Schema {
254        Schema::new(3, metric)
255    }
256
257    #[test]
258    fn schema_json_carries_attrs_and_reads_old_json_as_free_form() {
259        let typed = Schema::new(2, Metric::L2)
260            .with_attrs(crate::AttrSchema::new().field("price", crate::AttrType::Number));
261        let json = serde_json::to_string(&typed).unwrap();
262        assert_eq!(
263            json,
264            r#"{"dim":2,"metric":"l2","attrs":{"price":"number"}}"#
265        );
266        assert_eq!(serde_json::from_str::<Schema>(&json).unwrap(), typed);
267
268        let old: Schema = serde_json::from_str(r#"{"dim":2,"metric":"l2"}"#).unwrap();
269        assert!(old.attrs.is_free_form());
270        assert_eq!(
271            serde_json::to_string(&old).unwrap(),
272            r#"{"dim":2,"metric":"l2"}"#,
273            "a free-form schema writes no attrs"
274        );
275    }
276
277    #[test]
278    fn validate_accepts_good_vector() {
279        assert!(schema(Metric::L2).validate(&[1.0, 2.0, 3.0]).is_ok());
280    }
281
282    #[test]
283    fn validate_rejects_wrong_dim() {
284        let err = schema(Metric::L2).validate(&[1.0, 2.0]).unwrap_err();
285        assert!(matches!(
286            err,
287            ItzmaError::DimensionMismatch {
288                expected: 3,
289                got: 2
290            }
291        ));
292    }
293
294    #[test]
295    fn validate_rejects_non_finite() {
296        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
297            let err = schema(Metric::L2).validate(&[1.0, bad, 3.0]).unwrap_err();
298            assert!(matches!(err, ItzmaError::InvalidVector(_)));
299        }
300    }
301
302    #[test]
303    fn validate_rejects_zero_vector_only_for_cosine() {
304        let zero = [0.0, 0.0, 0.0];
305        assert!(matches!(
306            schema(Metric::Cosine).validate(&zero),
307            Err(ItzmaError::InvalidVector(_))
308        ));
309        assert!(schema(Metric::L2).validate(&zero).is_ok());
310        assert!(schema(Metric::Dot).validate(&zero).is_ok());
311    }
312
313    #[test]
314    fn wal_op_json_roundtrip() {
315        let ops = vec![
316            WalOp::Upsert(Document {
317                id: "a".into(),
318                vector: vec![0.1, -2.5, 3.0],
319                attrs: Some(serde_json::json!({"k": "v"})),
320                sparse: None,
321            }),
322            WalOp::Delete("b".into()),
323        ];
324        let json = serde_json::to_vec(&ops).unwrap();
325        let back: Vec<WalOp> = serde_json::from_slice(&json).unwrap();
326        assert_eq!(ops, back);
327    }
328
329    fn sparse_doc(id: &str, terms: &[(u32, f32)]) -> Document {
330        Document {
331            id: id.into(),
332            vector: vec![1.0, 2.0, 3.0],
333            attrs: None,
334            sparse: Some(terms.to_vec()),
335        }
336    }
337
338    #[test]
339    fn validate_sparse_accepts_none_and_distinct_terms() {
340        let mut d = sparse_doc("a", &[(3, 0.5), (10, 0.25)]);
341        assert!(d.validate_sparse().is_ok());
342        d.sparse = None;
343        assert!(d.validate_sparse().is_ok());
344    }
345
346    #[test]
347    fn validate_sparse_rejects_a_duplicate_term_id() {
348        let d = sparse_doc("a", &[(3, 0.5), (3, 0.25)]);
349        let err = d.validate_sparse().unwrap_err();
350        assert!(matches!(err, ItzmaError::InvalidVector(_)));
351    }
352
353    #[test]
354    fn validate_sparse_allows_exactly_the_most_terms_and_refuses_one_more() {
355        let terms = |n: u32| (0..n).map(|t| (t, 1.0)).collect::<Vec<_>>();
356        let at_limit = sparse_doc("a", &terms(MAX_SPARSE_TERMS as u32));
357        assert!(at_limit.validate_sparse().is_ok());
358        let over = sparse_doc("a", &terms(MAX_SPARSE_TERMS as u32 + 1));
359        assert!(matches!(
360            over.validate_sparse(),
361            Err(ItzmaError::InvalidVector("too many sparse terms"))
362        ));
363    }
364
365    #[test]
366    fn validate_sparse_rejects_a_non_finite_weight() {
367        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
368            let d = sparse_doc("a", &[(1, 0.5), (2, bad)]);
369            assert!(matches!(
370                d.validate_sparse(),
371                Err(ItzmaError::InvalidVector(_))
372            ));
373        }
374    }
375
376    fn doc_with_id(id: &str) -> Document {
377        Document {
378            id: id.into(),
379            vector: vec![1.0, 2.0, 3.0],
380            attrs: None,
381            sparse: None,
382        }
383    }
384
385    #[test]
386    fn validate_id_rejects_empty() {
387        let err = doc_with_id("").validate_id().unwrap_err();
388        assert!(matches!(err, ItzmaError::InvalidId(_)));
389    }
390
391    #[test]
392    fn validate_id_allows_exactly_the_limit_and_refuses_one_more() {
393        let at_limit = "a".repeat(MAX_ID_BYTES);
394        assert!(doc_with_id(&at_limit).validate_id().is_ok());
395
396        let over = "a".repeat(MAX_ID_BYTES + 1);
397        assert!(matches!(
398            doc_with_id(&over).validate_id(),
399            Err(ItzmaError::InvalidId("too long"))
400        ));
401    }
402
403    #[test]
404    fn validate_id_accepts_a_normal_id() {
405        assert!(doc_with_id("doc-1").validate_id().is_ok());
406    }
407
408    #[test]
409    fn sparse_field_round_trips_and_is_omitted_when_none() {
410        let with = sparse_doc("a", &[(1, 0.5)]);
411        let json = serde_json::to_value(&with).unwrap();
412        assert_eq!(json["sparse"], serde_json::json!([[1, 0.5]]));
413        let back: Document = serde_json::from_value(json).unwrap();
414        assert_eq!(back, with);
415
416        let without = Document {
417            id: "b".into(),
418            vector: vec![1.0],
419            attrs: None,
420            sparse: None,
421        };
422        let json = serde_json::to_value(&without).unwrap();
423        assert!(
424            json.get("sparse").is_none(),
425            "sparse must be omitted, not null, when None"
426        );
427
428        // A pre-existing WAL object, written before this field existed, must
429        // still decode: no "sparse" key at all.
430        let old = serde_json::json!({"id": "c", "vector": [1.0]});
431        let decoded: Document = serde_json::from_value(old).unwrap();
432        assert_eq!(decoded.sparse, None);
433    }
434}