itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! Typed attributes: the declared type of each field, and the check
//! a document's `attrs` has to pass to be written.

//!
//! A namespace declares its fields when it is created and never changes them,
//! so a stored value always has the type the schema names. A field that is
//! missing or `null` is "null", and every field may be.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::error::{ItzmaError, Result};

/// The most fields one namespace may declare.
pub const MAX_ATTR_FIELDS: usize = 256;
/// The longest field name, in bytes.
pub const MAX_FIELD_NAME_LEN: usize = 64;
/// The most elements one set value may hold.
pub const MAX_SET_ELEMENTS: usize = 1_024;

/// The type of one attribute field.
///
/// A set is a JSON array in the stored document. Order and duplicates do not
/// count when a filter matches it, and the stored array is returned as written.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AttrType {
    /// `true` or `false`.
    #[serde(rename = "bool")]
    Bool,
    /// A finite JSON number, compared as `f64`.
    #[serde(rename = "number")]
    Number,
    /// A string.
    #[serde(rename = "string")]
    Text,
    /// An array of strings, matched as a set.
    #[serde(rename = "set<string>")]
    TextSet,
    /// An array of numbers, matched as a set.
    #[serde(rename = "set<number>")]
    NumberSet,
}

impl AttrType {
    /// The name the schema object uses for this type, such as `set<string>`.
    pub fn name(self) -> &'static str {
        match self {
            Self::Bool => "bool",
            Self::Number => "number",
            Self::Text => "string",
            Self::TextSet => "set<string>",
            Self::NumberSet => "set<number>",
        }
    }
}

/// The name of a JSON value's kind, for error messages.
fn kind_of(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "bool",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

/// One field's declaration: its type, and whether it is indexed for fast
/// filtering (`Namespace::filter` and a query's `filter` option prune
/// through `Namespace::index_attrs`'s derived index instead of scanning
/// every row). Serializes as a bare type name when not indexed (`"number"`,
/// the exact bytes this crate has always written) and as an object when it
/// is (`{"type": "number", "indexed": true}`), so a schema with no indexed
/// field round-trips through exactly the bytes it always has.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FieldDecl {
    ty: AttrType,
    indexed: bool,
}

impl Serialize for FieldDecl {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        if !self.indexed {
            return self.ty.serialize(serializer);
        }
        #[derive(Serialize)]
        struct Detailed {
            #[serde(rename = "type")]
            ty: AttrType,
            indexed: bool,
        }
        Detailed {
            ty: self.ty,
            indexed: true,
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for FieldDecl {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Wire {
            Bare(AttrType),
            Detailed {
                #[serde(rename = "type")]
                ty: AttrType,
                #[serde(default)]
                indexed: bool,
            },
        }
        Ok(match Wire::deserialize(deserializer)? {
            Wire::Bare(ty) => FieldDecl { ty, indexed: false },
            Wire::Detailed { ty, indexed } => FieldDecl { ty, indexed },
        })
    }
}

/// The attribute fields of a namespace and their types.
///
/// Built once, at [`Namespace::create`](crate::Namespace::create), and as
/// immutable afterwards as the dimension and the metric. An empty schema means
/// the namespace takes no attributes at all.
///
/// A namespace made before typed attributes existed has no schema and stays
/// free-form. That state is private to the crate: nothing public builds it, so
/// nothing new can be created free-form.
///
/// # Examples
///
/// ```
/// use itzma_core::{AttrSchema, AttrType};
///
/// let attrs = AttrSchema::new()
///     .field("price", AttrType::Number)
///     .field("active", AttrType::Bool)
///     .field("tags", AttrType::TextSet);
/// assert_eq!(attrs.get("price"), Some(AttrType::Number));
/// assert_eq!(attrs.get("colour"), None);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct AttrSchema {
    /// `None` is the schemaless state.
    fields: Option<BTreeMap<String, FieldDecl>>,
}

impl AttrSchema {
    /// An empty schema: a namespace that takes no attributes. Add fields with
    /// [`field`](Self::field).
    // Not `Default`: the default state of a schema is free-form, which is
    // private, and an empty typed schema is a different thing.
    #[allow(clippy::new_without_default)]
    pub const fn new() -> Self {
        Self {
            fields: Some(BTreeMap::new()),
        }
    }

    /// Declare a field, replacing an earlier declaration of the same name.
    /// Names and counts are checked by `create`.
    #[must_use]
    pub fn field(mut self, name: impl Into<String>, ty: AttrType) -> Self {
        self.fields
            .get_or_insert_with(BTreeMap::new)
            .insert(name.into(), FieldDecl { ty, indexed: false });
        self
    }

    /// Declare a field that is indexed for fast filtering:
    /// [`Namespace::filter`](crate::Namespace::filter) and a query's
    /// `filter` option can prune to matching rows through the derived index
    /// [`Namespace::index_attrs`](crate::Namespace::index_attrs) builds,
    /// instead of scanning every row. Set once at `create`, like every other
    /// field declaration: there is no way to index a field after the fact.
    #[must_use]
    pub fn indexed_field(mut self, name: impl Into<String>, ty: AttrType) -> Self {
        self.fields
            .get_or_insert_with(BTreeMap::new)
            .insert(name.into(), FieldDecl { ty, indexed: true });
        self
    }

    /// The declared type of `name`, if it is declared.
    pub fn get(&self, name: &str) -> Option<AttrType> {
        self.fields.as_ref()?.get(name).map(|decl| decl.ty)
    }

    /// Whether `name` is declared and marked indexed. Test-only: production
    /// code asks [`indexed_field_names`](Self::indexed_field_names) for the
    /// whole set instead of one name at a time.
    #[cfg(test)]
    pub(crate) fn is_indexed(&self, name: &str) -> bool {
        self.fields
            .as_ref()
            .and_then(|f| f.get(name))
            .is_some_and(|decl| decl.indexed)
    }

    /// Every indexed field's name, in name order.
    pub(crate) fn indexed_field_names(&self) -> impl Iterator<Item = &str> {
        self.fields
            .iter()
            .flatten()
            .filter(|(_, decl)| decl.indexed)
            .map(|(name, _)| name.as_str())
    }

    /// Every declared field and its type, in name order.
    pub fn fields(&self) -> impl Iterator<Item = (&str, AttrType)> {
        self.fields
            .iter()
            .flatten()
            .map(|(name, decl)| (name.as_str(), decl.ty))
    }

    /// The schemaless state: no declared fields, attributes
    /// unchecked, `filter` refused.
    pub(crate) fn free_form() -> Self {
        Self { fields: None }
    }

    /// True for the schemaless state: attributes are free-form JSON,
    /// unchecked. No namespace this build opens is in it; encoders use it.
    pub(crate) fn is_free_form(&self) -> bool {
        self.fields.is_none()
    }

    /// Check the declaration itself, at `create`: not free-form, few enough
    /// fields, well-formed names.
    ///
    /// # Errors
    ///
    /// [`ItzmaError::InvalidSchema`].
    pub(crate) fn check_declaration(&self) -> Result<()> {
        let Some(fields) = &self.fields else {
            return Err(ItzmaError::InvalidSchema(
                "a new namespace must declare its attribute schema",
            ));
        };
        if fields.len() > MAX_ATTR_FIELDS {
            return Err(ItzmaError::InvalidSchema("too many attribute fields"));
        }
        let well_formed = |name: &String| {
            (1..=MAX_FIELD_NAME_LEN).contains(&name.len())
                && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
        };
        if !fields.keys().all(well_formed) {
            return Err(ItzmaError::InvalidSchema(
                "attribute field names must match [A-Za-z0-9_]{1,64}",
            ));
        }
        Ok(())
    }

    /// Check a document's `attrs` against the schema. A free-form schema
    /// accepts anything.
    ///
    /// # Errors
    ///
    /// - [`ItzmaError::InvalidAttrs`] if `attrs` is not a JSON object, or a set
    ///   has more than [`MAX_SET_ELEMENTS`] elements.
    /// - [`ItzmaError::UnknownAttr`] for a key the schema does not declare.
    /// - [`ItzmaError::AttrTypeMismatch`] for a value of the wrong type.
    pub(crate) fn validate(&self, attrs: Option<&Value>) -> Result<()> {
        let Some(fields) = &self.fields else {
            return Ok(());
        };
        let Some(attrs) = attrs else {
            return Ok(());
        };
        let Value::Object(map) = attrs else {
            return Err(ItzmaError::InvalidAttrs("attrs must be a JSON object"));
        };
        for (name, value) in map {
            let decl = fields.get(name).ok_or_else(|| ItzmaError::UnknownAttr {
                field: name.clone(),
            })?;
            check_value(name, decl.ty, value)?;
        }
        Ok(())
    }
}

/// One value against its declared type. `null` is always fine.
fn check_value(field: &str, ty: AttrType, value: &Value) -> Result<()> {
    let fits = match (ty, value) {
        (_, Value::Null)
        | (AttrType::Bool, Value::Bool(_))
        | (AttrType::Number, Value::Number(_))
        | (AttrType::Text, Value::String(_)) => true,
        (AttrType::TextSet, Value::Array(items)) => {
            check_len(items)?;
            items.iter().all(Value::is_string)
        }
        (AttrType::NumberSet, Value::Array(items)) => {
            check_len(items)?;
            items.iter().all(Value::is_number)
        }
        _ => false,
    };
    if fits {
        Ok(())
    } else {
        Err(ItzmaError::AttrTypeMismatch {
            field: field.to_string(),
            expected: ty.name(),
            found: kind_of(value),
        })
    }
}

fn check_len(items: &[Value]) -> Result<()> {
    if items.len() > MAX_SET_ELEMENTS {
        return Err(ItzmaError::InvalidAttrs("a set has too many elements"));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    fn schema() -> AttrSchema {
        AttrSchema::new()
            .field("active", AttrType::Bool)
            .field("price", AttrType::Number)
            .field("name", AttrType::Text)
            .field("tags", AttrType::TextSet)
            .field("scores", AttrType::NumberSet)
    }

    fn check(attrs: Value) -> Result<()> {
        schema().validate(Some(&attrs))
    }

    #[test]
    fn a_good_document_passes() {
        check(json!({
            "active": true, "price": 9.5, "name": "x",
            "tags": ["a", "b", "a"], "scores": [1, 2.5]
        }))
        .expect("valid");
    }

    #[test]
    fn none_an_empty_object_null_values_and_empty_sets_pass() {
        assert!(schema().validate(None).is_ok());
        check(json!({})).expect("empty object");
        check(json!({"active": null, "price": null})).expect("nulls");
        check(json!({"tags": [], "scores": []})).expect("empty sets");
    }

    #[test]
    fn attrs_must_be_an_object() {
        for bad in [json!(null), json!(3), json!("x"), json!([1])] {
            assert!(matches!(
                check(bad),
                Err(ItzmaError::InvalidAttrs("attrs must be a JSON object"))
            ));
        }
    }

    #[test]
    fn an_undeclared_field_is_refused_by_name() {
        match check(json!({"colour": "red"})) {
            Err(ItzmaError::UnknownAttr { field }) => assert_eq!(field, "colour"),
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn each_wrong_type_is_a_mismatch_naming_both_sides() {
        let cases = [
            (json!({"active": "yes"}), "active", "bool", "string"),
            (json!({"price": "9"}), "price", "number", "string"),
            (json!({"name": 4}), "name", "string", "number"),
            (json!({"tags": "a"}), "tags", "set<string>", "string"),
            (json!({"tags": [1]}), "tags", "set<string>", "array"),
            (json!({"scores": ["a"]}), "scores", "set<number>", "array"),
            (
                json!({"scores": {"a": 1}}),
                "scores",
                "set<number>",
                "object",
            ),
        ];
        for (attrs, field, expected, found) in cases {
            match check(attrs.clone()) {
                Err(ItzmaError::AttrTypeMismatch {
                    field: f,
                    expected: e,
                    found: g,
                }) => assert_eq!((f.as_str(), e, g), (field, expected, found), "{attrs}"),
                other => panic!("{attrs}: {other:?}"),
            }
        }
    }

    #[test]
    fn a_set_over_the_limit_is_refused_and_one_at_it_passes() {
        let at: Vec<String> = (0..MAX_SET_ELEMENTS).map(|i| i.to_string()).collect();
        check(json!({ "tags": at })).expect("at the limit");
        let over: Vec<String> = (0..=MAX_SET_ELEMENTS).map(|i| i.to_string()).collect();
        assert!(matches!(
            check(json!({ "tags": over })),
            Err(ItzmaError::InvalidAttrs(_))
        ));
    }

    #[test]
    fn a_free_form_schema_accepts_anything() {
        let free = AttrSchema::free_form();
        assert!(free.is_free_form());
        free.validate(Some(&json!({"anything": [1, {"x": null}]})))
            .expect("free-form");
        free.validate(Some(&json!(3))).expect("even a non-object");
    }

    #[test]
    fn the_declaration_is_checked() {
        assert!(schema().check_declaration().is_ok());
        assert!(AttrSchema::new().check_declaration().is_ok());
        assert!(AttrSchema::free_form().check_declaration().is_err());
        for bad in ["", "has space", "dash-ed", "ünï", &"x".repeat(65)] {
            let s = AttrSchema::new().field(bad, AttrType::Bool);
            assert!(s.check_declaration().is_err(), "{bad:?}");
        }
        let ok = AttrSchema::new().field("x".repeat(64), AttrType::Bool);
        assert!(ok.check_declaration().is_ok());
        let many = (0..=MAX_ATTR_FIELDS).fold(AttrSchema::new(), |s, i| {
            s.field(format!("f{i}"), AttrType::Bool)
        });
        assert!(many.check_declaration().is_err());
    }

    #[test]
    fn the_wire_form_is_a_map_of_type_names() {
        let json = serde_json::to_string(&schema()).expect("serialize");
        assert_eq!(
            json,
            r#"{"active":"bool","name":"string","price":"number","scores":"set<number>","tags":"set<string>"}"#
        );
        let back: AttrSchema = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, schema());
        assert_eq!(
            serde_json::to_string(&AttrSchema::new()).expect("serialize"),
            "{}"
        );
    }

    #[test]
    fn a_schema_serializes_as_bare_type_names() {
        let s = AttrSchema::new()
            .field("price", AttrType::Number)
            .field("tags", AttrType::TextSet);
        assert_eq!(
            serde_json::to_string(&s).unwrap(),
            r#"{"price":"number","tags":"set<string>"}"#
        );
    }

    #[test]
    fn indexed_field_is_reported_by_is_indexed_and_listed_by_name() {
        let s = AttrSchema::new()
            .field("name", AttrType::Text)
            .indexed_field("price", AttrType::Number);
        assert!(s.is_indexed("price"));
        assert!(!s.is_indexed("name"));
        assert!(!s.is_indexed("nope"));
        assert_eq!(s.indexed_field_names().collect::<Vec<_>>(), vec!["price"]);
    }

    #[test]
    fn indexed_field_keeps_its_type_through_get_and_fields() {
        let s = AttrSchema::new().indexed_field("price", AttrType::Number);
        assert_eq!(s.get("price"), Some(AttrType::Number));
        assert_eq!(
            s.fields().collect::<Vec<_>>(),
            vec![("price", AttrType::Number)]
        );
    }

    #[test]
    fn a_schema_with_no_indexed_field_serializes_byte_identical_to_before() {
        let s = AttrSchema::new()
            .field("price", AttrType::Number)
            .field("tags", AttrType::TextSet);
        assert_eq!(
            serde_json::to_string(&s).unwrap(),
            r#"{"price":"number","tags":"set<string>"}"#
        );
    }

    #[test]
    fn an_indexed_field_serializes_as_an_object_and_round_trips() {
        let s = AttrSchema::new().indexed_field("price", AttrType::Number);
        let json = serde_json::to_string(&s).unwrap();
        assert_eq!(json, r#"{"price":{"type":"number","indexed":true}}"#);
        let back: AttrSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(back, s);
    }

    #[test]
    fn the_bare_string_wire_form_from_before_indexing_existed_still_parses() {
        let back: AttrSchema = serde_json::from_str(r#"{"price":"number"}"#).unwrap();
        assert!(!back.is_indexed("price"));
        assert_eq!(back.get("price"), Some(AttrType::Number));
    }

    #[test]
    fn a_detailed_field_with_indexed_false_parses_as_not_indexed() {
        let back: AttrSchema =
            serde_json::from_str(r#"{"price":{"type":"number","indexed":false}}"#).unwrap();
        assert!(!back.is_indexed("price"));
    }
}