1use serde::{Deserialize, Serialize};
4
5use crate::attrs::AttrSchema;
6use crate::error::{ItzmaError, Result};
7
8#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21pub struct Document {
22 pub id: String,
24 pub vector: Vec<f32>,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub attrs: Option<serde_json::Value>,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub sparse: Option<SparseVector>,
39}
40
41pub type SparseVector = Vec<(u32, f32)>;
47
48pub const MAX_SPARSE_TERMS: usize = u16::MAX as usize;
52
53pub const MAX_ID_BYTES: usize = 512;
60
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
74#[serde(rename_all = "snake_case")]
75pub enum WalOp {
76 Upsert(Document),
78 Delete(String),
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "snake_case")]
90pub enum Metric {
91 Cosine,
94 L2,
97 Dot,
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct Schema {
108 pub dim: usize,
110 pub metric: Metric,
112 #[serde(
116 default = "AttrSchema::free_form",
117 skip_serializing_if = "AttrSchema::is_free_form"
118 )]
119 pub attrs: AttrSchema,
120}
121
122impl Schema {
123 pub const fn new(dim: usize, metric: Metric) -> Self {
126 Self {
127 dim,
128 metric,
129 attrs: AttrSchema::new(),
130 }
131 }
132
133 #[must_use]
135 pub fn with_attrs(mut self, attrs: AttrSchema) -> Self {
136 self.attrs = attrs;
137 self
138 }
139
140 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
177pub(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 pub fn validate_id(&self) -> Result<()> {
204 validate_id(&self.id)
205 }
206
207 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
227pub(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 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}