1mod attr_rows;
24mod columns;
25mod ranged;
26mod v2;
27mod view;
28mod writer;
29mod zone;
30
31pub(crate) use ranged::{DocWindow, Held, RangedSegment};
32pub(crate) use v2::BLOCK_ROWS;
33pub(crate) use view::SegmentView;
34pub(crate) use writer::{AttrIn, Chunks, SegmentWriter, attr_json, encode_attr_block};
35
36use bytes::Bytes;
37use futures::stream::{self, StreamExt, TryStreamExt};
38use object_store::path::Path;
39use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions, PutPayload, UpdateVersion};
40
41use crate::attrs::AttrSchema;
42use crate::budget::ReadBudget;
43use crate::cpu::{self, Cost, Lane};
44use crate::decoded::{DecodedRef, What};
45use crate::document::{Document, Schema};
46use crate::error::{ItzmaError, Result};
47use crate::fetch::FetchPolicy;
48use crate::layer::Layer;
49
50pub const FORMAT_VERSION: u32 = 3;
57
58pub const DEFAULT_FORMAT: u32 = 2;
63
64const MAGIC: [u8; 4] = *b"ITZS";
65const FETCH_CONCURRENCY: usize = 16;
67
68pub fn segment_id(lo: u64, hi: u64) -> String {
77 format!("{lo:020}-{hi:020}")
78}
79
80pub fn parse_segment_id(id: &str) -> Option<(u64, u64)> {
83 let (lo, hi) = id.split_once('-')?;
84 let (lo, hi) = (lo.parse::<u64>().ok()?, hi.parse::<u64>().ok()?);
85 ((1..=hi).contains(&lo) && segment_id(lo, hi) == id).then_some((lo, hi))
86}
87
88pub fn segment_path(namespace: &str, id: &str) -> Path {
93 Path::from(format!("{namespace}/segments/{id}/data.bin"))
94}
95
96pub(crate) async fn object_names(
99 store: &dyn ObjectStore,
100 namespace: &str,
101 id: &str,
102) -> Result<Vec<String>> {
103 let prefix = Path::from(format!("{namespace}/segments/{id}"));
104 let metas: Vec<_> = store
105 .list(Some(&prefix))
106 .try_collect()
107 .await
108 .map_err(ItzmaError::from)?;
109 Ok(metas
110 .iter()
111 .filter_map(|meta| meta.location.filename().map(str::to_string))
112 .collect())
113}
114
115pub(crate) fn generation_floor(
118 named: Option<u32>,
119 names: &[String],
120 generation_of: fn(&str) -> Option<u32>,
121) -> u32 {
122 names
123 .iter()
124 .filter_map(|name| generation_of(name))
125 .chain(named)
126 .max()
127 .unwrap_or(0)
128}
129
130pub(crate) fn generation_mark_path(namespace: &str, id: &str) -> Path {
133 Path::from(format!("{namespace}/segments/{id}/generation"))
134}
135
136const MAX_MARK_BYTES: u64 = 10;
138
139pub(crate) async fn claim_generation(
152 store: &dyn ObjectStore,
153 namespace: &str,
154 id: &str,
155 floor: u32,
156) -> Result<u32> {
157 let path = generation_mark_path(namespace, id);
158 for _ in 0..crate::manifest::MAX_UPDATE_ATTEMPTS {
159 let (mark, version) = read_generation_mark(store, &path).await?;
160 let generation = floor.max(mark).saturating_add(1);
161 let mode = match version {
162 Some(version) => PutMode::Update(version),
163 None => PutMode::Create,
164 };
165 let body = Bytes::from(generation.to_string());
166 match store
167 .put_opts(&path, body.into(), PutOptions::from(mode))
168 .await
169 {
170 Ok(_) => return Ok(generation),
171 Err(
172 object_store::Error::Precondition { .. }
173 | object_store::Error::AlreadyExists { .. },
174 ) => continue,
175 Err(e) => return Err(e.into()),
176 }
177 }
178 Err(ItzmaError::ManifestContention {
179 attempts: crate::manifest::MAX_UPDATE_ATTEMPTS,
180 })
181}
182
183async fn read_generation_mark(
187 store: &dyn ObjectStore,
188 path: &Path,
189) -> Result<(u32, Option<UpdateVersion>)> {
190 let result = match store.get(path).await {
191 Ok(result) => result,
192 Err(object_store::Error::NotFound { .. }) => return Ok((0, None)),
193 Err(e) => return Err(e.into()),
194 };
195 let corrupt = |reason: &str| ItzmaError::CorruptIndex {
196 path: path.to_string(),
197 reason: format!("generation mark {reason}"),
198 };
199 if result.meta.size > MAX_MARK_BYTES {
200 return Err(corrupt("is too long"));
201 }
202 let version = UpdateVersion {
203 e_tag: result.meta.e_tag.clone(),
204 version: result.meta.version.clone(),
205 };
206 let bytes = result.bytes().await?;
207 let mark = std::str::from_utf8(&bytes)
208 .ok()
209 .filter(|text| text.bytes().all(|b| b.is_ascii_digit()))
210 .and_then(|text| text.parse::<u32>().ok())
211 .ok_or_else(|| corrupt("is not a decimal number"))?;
212 Ok((mark, Some(version)))
213}
214
215pub fn validate_chain(ids: &[String], folded_through: u64) -> Result<()> {
224 let corrupt = |reason: String| ItzmaError::CorruptManifest(reason);
225 let mut next_lo = 1u64;
226 for id in ids {
227 let (lo, hi) = parse_segment_id(id)
228 .ok_or_else(|| corrupt(format!("segment id {id:?} is malformed")))?;
229 if lo != next_lo {
230 return Err(corrupt(format!(
231 "segment {id} starts at {lo}, expected {next_lo}"
232 )));
233 }
234 next_lo = hi
235 .checked_add(1)
236 .ok_or_else(|| corrupt(format!("segment {id} ends at the largest seq")))?;
237 }
238 let covered = next_lo - 1;
239 if covered != folded_through {
240 return Err(corrupt(format!(
241 "segments cover through {covered} but wal_folded_through is {folded_through}"
242 )));
243 }
244 Ok(())
245}
246
247pub fn encode(layer: &Layer, dim: usize) -> Result<Bytes> {
250 encode_as(layer, dim, DEFAULT_FORMAT)
251}
252
253pub fn encode_as(layer: &Layer, dim: usize, version: u32) -> Result<Bytes> {
270 let (data, _) = encode_parts(layer, dim, version, &AttrSchema::free_form())?;
271 Ok(data.into())
272}
273
274pub fn encode_with_schema(layer: &Layer, schema: &Schema, version: u32) -> Result<Bytes> {
285 let (data, _) = encode_parts(layer, schema.dim, version, &schema.attrs)?;
286 Ok(data.into())
287}
288
289pub(crate) fn encode_parts(
293 layer: &Layer,
294 dim: usize,
295 version: u32,
296 attrs: &AttrSchema,
297) -> Result<(PutPayload, Option<PutPayload>)> {
298 let mut writer = SegmentWriter::new(dim, version, attrs)?;
299 let docs = layer.sorted_docs();
300 let columnar = version >= 3 && !attrs.is_free_form();
301 if columnar {
302 let fields = columns::fields_of(attrs);
305 let blocks = cpu::chunked(&docs, v2::BLOCK_ROWS, |chunk| {
306 let rows: Vec<Option<&serde_json::Value>> =
307 chunk.iter().map(|doc| doc.attrs.as_ref()).collect();
308 encode_attr_block(&fields, &rows)
309 });
310 writer.attr_blocks(blocks.into_iter().collect::<Result<_>>()?)?;
311 }
312 let mut json: Vec<Vec<u8>> = Vec::new();
316 if !columnar {
317 json.reserve(docs.len());
318 for chunk in cpu::chunked(&docs, v2::BLOCK_ROWS, |chunk| {
319 chunk
320 .iter()
321 .map(|doc| attr_json(doc.attrs.as_ref()))
322 .collect::<Result<Vec<_>>>()
323 }) {
324 json.extend(chunk?);
325 }
326 }
327 let tombstones = layer.sorted_tombstones();
328 let mut dead = tombstones.iter().peekable();
329 for (i, doc) in docs.iter().enumerate() {
330 while let Some(id) = dead.next_if(|id| **id < doc.id.as_str()) {
331 writer.tombstone(id)?;
332 }
333 let attrs = if columnar {
334 AttrIn::Encoded
335 } else {
336 AttrIn::Json(&json[i])
337 };
338 writer.doc(&doc.id, &doc.vector, attrs, doc.sparse.as_ref())?;
339 }
340 for id in dead {
341 writer.tombstone(id)?;
342 }
343 writer.finish()
344}
345
346#[cfg(test)]
349fn check_dim(docs: &[&Document], dim: usize) -> Result<u32> {
350 if let Some(bad) = docs.iter().find(|d| d.vector.len() != dim) {
351 return Err(ItzmaError::DimensionMismatch {
352 expected: dim,
353 got: bad.vector.len(),
354 });
355 }
356 u32::try_from(dim).map_err(|_| too_long())
357}
358
359fn put_bytes(buf: &mut Vec<u8>, bytes: &[u8]) -> Result<()> {
360 let len = u32::try_from(bytes.len()).map_err(|_| too_long())?;
361 buf.extend_from_slice(&len.to_le_bytes());
362 buf.extend_from_slice(bytes);
363 Ok(())
364}
365
366fn too_long() -> ItzmaError {
367 ItzmaError::CorruptSegment {
368 path: "(encoding)".into(),
369 reason: "a field is longer than 4 GiB".into(),
370 }
371}
372
373const MISSING: &str = "missing from the store";
376
377pub(crate) fn missing(path: &Path) -> ItzmaError {
380 ItzmaError::CorruptSegment {
381 path: path.to_string(),
382 reason: MISSING.into(),
383 }
384}
385
386pub(crate) fn is_missing(err: &ItzmaError) -> bool {
390 matches!(err, ItzmaError::CorruptSegment { reason, .. } if reason == MISSING)
391}
392
393pub fn decode(path: &str, bytes: &[u8], dim: usize) -> Result<Layer> {
406 let mut r = Reader::new(path, bytes);
407 if r.take(4)? != MAGIC {
408 return Err(r.corrupt("bad magic"));
409 }
410 match r.u32()? {
411 version @ (2 | 3) => v2::decode(r, version, dim),
412 version => Err(ItzmaError::UnsupportedFormat { version }),
413 }
414}
415
416fn overlaps(docs: &[Document], tombstones: &[String]) -> bool {
418 let (mut i, mut j) = (0, 0);
419 while i < docs.len() && j < tombstones.len() {
420 match docs[i].id.cmp(&tombstones[j]) {
421 std::cmp::Ordering::Less => i += 1,
422 std::cmp::Ordering::Greater => j += 1,
423 std::cmp::Ordering::Equal => return true,
424 }
425 }
426 false
427}
428
429struct Reader<'a> {
432 path: &'a str,
433 buf: &'a [u8],
434 pos: usize,
435}
436
437impl<'a> Reader<'a> {
438 fn new(path: &'a str, buf: &'a [u8]) -> Self {
439 Reader { path, buf, pos: 0 }
440 }
441
442 fn corrupt(&self, reason: impl Into<String>) -> ItzmaError {
443 ItzmaError::CorruptSegment {
444 path: self.path.to_string(),
445 reason: reason.into(),
446 }
447 }
448
449 fn remaining(&self) -> usize {
450 self.buf.len().saturating_sub(self.pos)
451 }
452
453 fn take(&mut self, n: usize) -> Result<&'a [u8]> {
454 let out = self
455 .buf
456 .get(self.pos..)
457 .and_then(|rest| rest.get(..n))
458 .ok_or_else(|| self.corrupt("object is truncated"))?;
459 self.pos += n;
460 Ok(out)
461 }
462
463 fn array<const N: usize>(&mut self) -> Result<[u8; N]> {
464 let bytes = self.take(N)?;
465 <[u8; N]>::try_from(bytes).map_err(|_| self.corrupt("object is truncated"))
466 }
467
468 fn u8(&mut self) -> Result<u8> {
469 let [byte] = self.array::<1>()?;
470 Ok(byte)
471 }
472
473 fn u16(&mut self) -> Result<u16> {
474 Ok(u16::from_le_bytes(self.array()?))
475 }
476
477 fn u32(&mut self) -> Result<u32> {
478 Ok(u32::from_le_bytes(self.array()?))
479 }
480
481 fn u64(&mut self) -> Result<u64> {
482 Ok(u64::from_le_bytes(self.array()?))
483 }
484
485 fn string(&mut self, what: &str) -> Result<String> {
486 let len = self.u32()? as usize;
487 let raw = self.take(len)?;
488 std::str::from_utf8(raw)
489 .map(str::to_owned)
490 .map_err(|_| self.corrupt(format!("{what} is not valid UTF-8")))
491 }
492}
493
494#[derive(Debug, Clone, PartialEq)]
500pub struct Matrix {
501 pub(crate) rows: usize,
502 pub(crate) dim: usize,
503 pub(crate) values: Vec<f32>,
504}
505
506impl Matrix {
507 pub fn rows(&self) -> usize {
509 self.rows
510 }
511
512 pub fn dim(&self) -> usize {
514 self.dim
515 }
516
517 pub fn values(&self) -> &[f32] {
519 &self.values
520 }
521
522 pub fn row(&self, i: usize) -> &[f32] {
528 let start = i * self.dim;
529 &self.values[start..start + self.dim]
530 }
531
532 pub fn into_values(self) -> Vec<f32> {
534 self.values
535 }
536}
537
538pub(crate) async fn fetch_bytes(
542 store: &dyn ObjectStore,
543 path: &Path,
544 budget: &ReadBudget,
545 policy: &FetchPolicy,
546) -> Result<Bytes> {
547 match crate::fetch::whole_object(store, budget, policy, path).await {
548 Ok(bytes) => Ok(bytes),
549 Err(ItzmaError::Storage(object_store::Error::NotFound { .. })) => Err(missing(path)),
550 Err(e) => Err(e),
551 }
552}
553
554async fn fetch(
556 store: &dyn ObjectStore,
557 namespace: &str,
558 id: &str,
559 dim: usize,
560 budget: &ReadBudget,
561 policy: &FetchPolicy,
562 lane: Lane,
563) -> Result<Layer> {
564 let path = segment_path(namespace, id);
565 let bytes = fetch_bytes(store, &path, budget, policy).await?;
566 decode_on(lane, path, bytes, dim).await
567}
568
569pub(crate) async fn decode_on(lane: Lane, path: Path, bytes: Bytes, dim: usize) -> Result<Layer> {
572 cpu::run(lane, Cost::Bytes(bytes.len()), move || {
573 decode(path.as_ref(), &bytes, dim)
574 })
575 .await
576}
577
578pub(crate) async fn encode_parts_on(
582 lane: Lane,
583 layer: Layer,
584 dim: usize,
585 version: u32,
586 attrs: AttrSchema,
587) -> Result<(Layer, PutPayload, Option<PutPayload>)> {
588 let cost = Cost::Bytes(layer.doc_count().saturating_mul(dim * 4 + 64));
589 cpu::run(lane, cost, move || {
590 let (data, sparse) = encode_parts(&layer, dim, version, &attrs)?;
591 Ok((layer, data, sparse))
592 })
593 .await
594}
595
596#[derive(Debug, Clone, Copy, PartialEq, Eq)]
598pub(crate) struct Peek {
599 pub(crate) version: u32,
600 pub(crate) dim: u32,
601 pub(crate) doc_count: u64,
602}
603
604const PEEK_LEN: u64 = 4 + 4 + 4 + 8;
606
607pub(crate) async fn peek(
616 store: &dyn ObjectStore,
617 path: &Path,
618 budget: &ReadBudget,
619) -> Result<Peek> {
620 budget.charge(path.as_ref(), PEEK_LEN)?;
621 let bytes = match store.get_range(path, 0..PEEK_LEN).await {
622 Ok(bytes) => bytes,
623 Err(object_store::Error::NotFound { .. }) => return Err(missing(path)),
624 Err(e) => return Err(e.into()),
625 };
626 let mut r = Reader::new(path.as_ref(), &bytes);
627 if r.take(4)? != MAGIC {
628 return Err(r.corrupt("bad magic"));
629 }
630 let version = r.u32()?;
631 if !(2..=FORMAT_VERSION).contains(&version) {
632 return Err(ItzmaError::UnsupportedFormat { version });
633 }
634 Ok(Peek {
635 version,
636 dim: r.u32()?,
637 doc_count: r.u64()?,
638 })
639}
640
641pub(crate) async fn read_all(
650 store: &dyn ObjectStore,
651 namespace: &str,
652 ids: &[String],
653 dim: usize,
654 budget: &ReadBudget,
655 policy: &FetchPolicy,
656 lane: Lane,
657) -> Result<Layer> {
658 stream::iter(ids.iter().cloned())
662 .map(|id| async move { fetch(store, namespace, &id, dim, budget, policy, lane).await })
663 .buffered(FETCH_CONCURRENCY)
664 .try_fold(Layer::new(), |mut acc, segment| async move {
665 acc.overlay(segment);
666 Ok::<_, ItzmaError>(acc)
667 })
668 .await
669}
670
671async fn load_flat(
673 store: &dyn ObjectStore,
674 path: Path,
675 dim: usize,
676 budget: &ReadBudget,
677 policy: &FetchPolicy,
678 lane: Lane,
679) -> Result<(std::sync::Arc<SegmentView>, u64)> {
680 let bytes = fetch_bytes(store, &path, budget, policy).await?;
681 let view = cpu::run(lane, Cost::Bytes(bytes.len()), move || {
682 SegmentView::decode(path.as_ref(), bytes, dim)
683 })
684 .await?;
685 let weight = view.weight();
687 Ok((std::sync::Arc::new(view), weight))
688}
689
690#[allow(clippy::too_many_arguments)] pub(crate) async fn read_flat(
699 store: &dyn ObjectStore,
700 namespace: &str,
701 ids: &[String],
702 dim: usize,
703 budget: &ReadBudget,
704 policy: &FetchPolicy,
705 lane: Lane,
706 decoded: Option<&DecodedRef>,
707) -> Result<Vec<std::sync::Arc<SegmentView>>> {
708 stream::iter(ids.iter().cloned())
711 .map(|id| async move {
712 let path = segment_path(namespace, &id);
713 let Some(decoded) = decoded else {
714 return Ok(load_flat(store, path, dim, budget, policy, lane).await?.0);
715 };
716 let view = decoded
717 .get_or_load(&path, What::View, || {
718 load_flat(store, path.clone(), dim, budget, policy, lane)
719 })
720 .await?;
721 Ok(std::sync::Arc::clone(&*view))
722 })
723 .buffered(FETCH_CONCURRENCY)
724 .try_collect()
725 .await
726}
727
728#[cfg(test)]
729mod tests {
730 use super::*;
731 use crate::cpu::Lane;
732 use crate::document::{Document, WalOp};
733 use crate::error::ItzmaError;
734
735 #[tokio::test]
736 async fn read_flat_gives_views_and_refuses_version_1() {
737 let store = object_store::memory::InMemory::new();
738 let mut layer = Layer::new();
739 for i in 0..3 {
740 layer.apply(WalOp::Upsert(Document {
741 id: format!("d{i}"),
742 vector: vec![i as f32; 2],
743 attrs: None,
744 sparse: None,
745 }));
746 }
747 let ids = [segment_id(1, 1)];
748 let bytes = encode_as(&layer, 2, 2).unwrap();
749 store
750 .put(&segment_path("ns", &ids[0]), bytes.clone().into())
751 .await
752 .unwrap();
753 let budget = ReadBudget::new(1 << 20);
754 let policy = FetchPolicy::local();
755 let got = read_flat(&store, "ns", &ids, 2, &budget, &policy, Lane::Query, None)
756 .await
757 .unwrap();
758 assert_eq!(got[0].rows(), 3);
759 assert_eq!(got[0].vector(2), &[2.0, 2.0]);
760
761 let mut v1 = bytes.to_vec();
763 v1[4..8].copy_from_slice(&1u32.to_le_bytes());
764 store
765 .put(&segment_path("ns", &ids[0]), v1.into())
766 .await
767 .unwrap();
768 let err = read_flat(&store, "ns", &ids, 2, &budget, &policy, Lane::Query, None)
769 .await
770 .err()
771 .unwrap();
772 assert!(
773 matches!(err, ItzmaError::UnsupportedFormat { version: 1 }),
774 "{err:?}"
775 );
776 }
777
778 #[tokio::test]
779 async fn a_missing_segment_is_missing_for_read_flat() {
780 let store = object_store::memory::InMemory::new();
781 let budget = ReadBudget::new(1 << 20);
782 let policy = FetchPolicy::local();
783 let ids = [segment_id(1, 1)];
784 let err = read_flat(&store, "ns", &ids, 2, &budget, &policy, Lane::Query, None)
785 .await
786 .err()
787 .unwrap();
788 assert!(is_missing(&err), "{err:?}");
789 }
790
791 fn big_layer(n: usize, dim: usize) -> Layer {
794 let mut layer = Layer::new();
795 for i in 0..n {
796 layer.apply(WalOp::Upsert(Document {
797 id: format!("d{i:06}"),
798 vector: (0..dim).map(|d| ((i * 31 + d * 7) % 101) as f32).collect(),
799 attrs: (i % 3 == 0).then(|| serde_json::json!({ "n": i, "tag": "x" })),
800 sparse: None,
801 }));
802 }
803 for i in 0..10 {
804 layer.apply(WalOp::Delete(format!("gone{i}")));
805 }
806 layer
807 }
808
809 #[tokio::test]
810 async fn decode_on_a_lane_equals_decode() {
811 let layer = big_layer(20_000, 32);
812 for version in [2, 3] {
813 let bytes = encode_as(&layer, 32, version).unwrap();
814 let direct = decode("p", &bytes, 32).unwrap();
815 let pooled = decode_on(Lane::Query, Path::from("p"), bytes, 32)
816 .await
817 .unwrap();
818 assert_eq!(pooled, direct, "version {version}");
819 }
820 }
821
822 #[tokio::test]
823 async fn encode_on_a_lane_gives_the_same_bytes_and_the_layer_back() {
824 let layer = big_layer(20_000, 32);
825 for version in [2, 3] {
826 let direct = encode_as(&layer, 32, version).unwrap();
827 let (back, data, sparse) = encode_parts_on(
828 Lane::Maintenance,
829 layer.clone(),
830 32,
831 version,
832 AttrSchema::free_form(),
833 )
834 .await
835 .unwrap();
836 assert_eq!(Bytes::from(data), direct, "version {version}");
837 assert!(sparse.is_none());
838 assert_eq!(back, layer);
839 }
840 }
841
842 #[test]
843 fn matrix_row_slices_out_the_right_values_in_order() {
844 let m = Matrix {
845 rows: 3,
846 dim: 2,
847 values: vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
848 };
849 assert_eq!(m.row(0), &[1.0, 2.0]);
850 assert_eq!(m.row(1), &[3.0, 4.0]);
851 assert_eq!(m.row(2), &[5.0, 6.0]);
852 }
853
854 fn up(id: &str, v: &[f32], attrs: Option<serde_json::Value>) -> WalOp {
855 WalOp::Upsert(Document {
856 id: id.into(),
857 vector: v.to_vec(),
858 attrs,
859 sparse: None,
860 })
861 }
862
863 fn layer(ops: Vec<WalOp>) -> Layer {
864 let mut l = Layer::new();
865 for op in ops {
866 l.apply(op);
867 }
868 l
869 }
870
871 fn sample() -> Layer {
872 layer(vec![
873 up(
874 "b",
875 &[1.0, 2.0],
876 Some(serde_json::json!({"k": [1, 2], "s": "x"})),
877 ),
878 up("a", &[-0.5, 0.25], None),
879 up(
880 "ü-日本",
881 &[3.0, 4.0],
882 Some(serde_json::json!("plain string")),
883 ),
884 WalOp::Delete("y".into()),
885 WalOp::Delete("x".into()),
886 ])
887 }
888
889 fn v2(layer: &Layer, dim: usize) -> Result<Bytes> {
891 encode_as(layer, dim, 2)
892 }
893
894 fn corrupt(err: ItzmaError) -> String {
895 match err {
896 ItzmaError::CorruptSegment { reason, .. } => reason,
897 other => panic!("expected CorruptSegment, got {other:?}"),
898 }
899 }
900
901 #[test]
902 fn roundtrip_preserves_docs_attrs_and_tombstones() {
903 let original = sample();
904 let bytes = v2(&original, 2).unwrap();
905 assert_eq!(decode("p", &bytes, 2).unwrap(), original);
906 }
907
908 #[test]
909 fn json_null_attrs_survive_the_roundtrip() {
910 let original = layer(vec![up("a", &[1.0], Some(serde_json::Value::Null))]);
911 let bytes = v2(&original, 1).unwrap();
912 let back = decode("p", &bytes, 1).unwrap();
913 assert_eq!(back.sorted_docs()[0].attrs, Some(serde_json::Value::Null));
914 }
915
916 #[test]
917 fn bytes_do_not_depend_on_insertion_order() {
918 let one = layer(vec![
919 up("a", &[1.0], None),
920 up("b", &[2.0], None),
921 WalOp::Delete("z".into()),
922 ]);
923 let two = layer(vec![
924 WalOp::Delete("z".into()),
925 up("b", &[2.0], None),
926 up("a", &[1.0], None),
927 ]);
928 assert_eq!(v2(&one, 1).unwrap(), v2(&two, 1).unwrap());
929 }
930
931 #[test]
932 fn encode_rejects_a_vector_of_the_wrong_length() {
933 let l = layer(vec![up("a", &[1.0, 2.0, 3.0], None)]);
934 let err = v2(&l, 2).unwrap_err();
935 assert!(matches!(
936 err,
937 ItzmaError::DimensionMismatch {
938 expected: 2,
939 got: 3
940 }
941 ));
942 }
943
944 #[test]
945 fn every_truncation_is_an_error_and_none_panics() {
946 let bytes = v2(&sample(), 2).unwrap();
947 for cut in 0..bytes.len() {
948 assert!(decode("p", &bytes[..cut], 2).is_err(), "cut at {cut}");
949 }
950 }
951
952 #[test]
953 fn decode_rejects_bad_magic() {
954 let mut bytes = v2(&sample(), 2).unwrap().to_vec();
955 bytes[0] = b'X';
956 assert!(corrupt(decode("p", &bytes, 2).unwrap_err()).contains("magic"));
957 }
958
959 #[test]
960 fn decode_reports_an_unknown_version() {
961 for version in [0, 4, u32::MAX] {
963 let mut bytes = v2(&sample(), 2).unwrap().to_vec();
964 bytes[4..8].copy_from_slice(&version.to_le_bytes());
965 assert!(
966 matches!(
967 decode("p", &bytes, 2).unwrap_err(),
968 ItzmaError::UnsupportedFormat { version: v } if v == version
969 ),
970 "version {version}"
971 );
972 }
973 }
974
975 #[test]
976 fn decode_rejects_a_dimension_that_differs_from_the_schema() {
977 let bytes = v2(&sample(), 2).unwrap();
978 assert!(corrupt(decode("p", &bytes, 3).unwrap_err()).contains("dimension"));
979 }
980
981 #[test]
982 fn encode_writes_the_default_version() {
983 let bytes = encode(&sample(), 2).unwrap();
984 assert_eq!(bytes[4..8], DEFAULT_FORMAT.to_le_bytes());
985 assert_eq!((DEFAULT_FORMAT, FORMAT_VERSION), (2, 3));
986 }
987
988 #[test]
989 fn encode_as_writes_the_version_asked_for() {
990 for version in [2, 3] {
991 let bytes = encode_as(&sample(), 2, version).unwrap();
992 assert_eq!(bytes[4..8], version.to_le_bytes());
993 }
994 }
995
996 #[test]
997 fn encode_as_refuses_a_version_it_does_not_write() {
998 for version in [0, 4, u32::MAX] {
999 let err = encode_as(&sample(), 2, version).unwrap_err();
1000 assert!(
1001 matches!(err, ItzmaError::UnsupportedFormat { version: v } if v == version),
1002 "{err:?}"
1003 );
1004 }
1005 }
1006
1007 #[test]
1008 fn a_short_object_is_corrupt_not_unsupported() {
1009 for cut in 0..8 {
1010 let bytes = encode(&sample(), 2).unwrap();
1011 let err = decode("p", &bytes[..cut], 2).unwrap_err();
1012 assert!(matches!(err, ItzmaError::CorruptSegment { .. }), "{cut}");
1013 }
1014 }
1015
1016 #[test]
1017 fn segment_ids_are_zero_padded_ranges() {
1018 assert_eq!(
1019 segment_id(1, 10),
1020 "00000000000000000001-00000000000000000010"
1021 );
1022 assert_eq!(
1023 segment_path("docs", &segment_id(1, 10)).as_ref(),
1024 "docs/segments/00000000000000000001-00000000000000000010/data.bin"
1025 );
1026 }
1027
1028 #[test]
1029 fn parse_segment_id_accepts_only_the_canonical_form() {
1030 assert_eq!(parse_segment_id(&segment_id(3, 9)), Some((3, 9)));
1031 assert_eq!(parse_segment_id(&segment_id(5, 5)), Some((5, 5)));
1032 for bad in [
1033 "",
1034 "1-2",
1035 "00000000000000000001",
1036 "+0000000000000000001-00000000000000000002",
1037 "00000000000000000000-00000000000000000002",
1038 "00000000000000000003-00000000000000000002",
1039 "00000000000000000001-00000000000000000002-x",
1040 "0000000000000000000a-00000000000000000002",
1041 ] {
1042 assert_eq!(parse_segment_id(bad), None, "{bad:?}");
1043 }
1044 }
1045
1046 fn ids(ranges: &[(u64, u64)]) -> Vec<String> {
1047 ranges.iter().map(|(lo, hi)| segment_id(*lo, *hi)).collect()
1048 }
1049
1050 fn manifest_reason(err: ItzmaError) -> String {
1051 match err {
1052 ItzmaError::CorruptManifest(reason) => reason,
1053 other => panic!("expected CorruptManifest, got {other:?}"),
1054 }
1055 }
1056
1057 #[test]
1058 fn validate_chain_accepts_a_contiguous_run() {
1059 assert!(validate_chain(&[], 0).is_ok());
1060 assert!(validate_chain(&ids(&[(1, 3)]), 3).is_ok());
1061 assert!(validate_chain(&ids(&[(1, 3), (4, 4), (5, 9)]), 9).is_ok());
1062 }
1063
1064 #[test]
1065 fn validate_chain_rejects_every_broken_shape() {
1066 let cases = [
1067 (ids(&[(1, 3), (5, 6)]), 6, "starts at 5"), (ids(&[(1, 3), (3, 4)]), 4, "starts at 3"), (ids(&[(2, 3)]), 3, "starts at 2"), (ids(&[(1, 3)]), 4, "folded"), (vec![], 5, "folded"), (vec!["nonsense".to_string()], 0, "malformed"),
1073 ];
1074 for (list, folded, want) in cases {
1075 let reason = manifest_reason(validate_chain(&list, folded).unwrap_err());
1076 assert!(reason.contains(want), "{list:?} folded {folded}: {reason}");
1077 }
1078 }
1079
1080 #[test]
1081 fn validate_chain_does_not_overflow_on_the_largest_range() {
1082 assert!(validate_chain(&ids(&[(1, u64::MAX)]), u64::MAX).is_err());
1083 }
1084
1085 async fn peek_of(bytes: &[u8]) -> (Result<Peek>, ReadBudget) {
1086 use object_store::memory::InMemory;
1087 let store = InMemory::new();
1088 let path = Path::from("docs/segments/x/data.bin");
1089 store
1090 .put(&path, Bytes::copy_from_slice(bytes).into())
1091 .await
1092 .unwrap();
1093 let budget = ReadBudget::new(1_000);
1094 (peek(&store, &path, &budget).await, budget)
1095 }
1096
1097 #[tokio::test]
1098 async fn a_peek_reads_the_version_dimension_and_count_of_either_version() {
1099 let l = sample();
1100 let docs = l.doc_count() as u64;
1101 for version in [2, 3] {
1102 let bytes = encode_as(&l, 2, version).unwrap();
1103 let (got, _) = peek_of(&bytes).await;
1104 assert_eq!(
1105 got.unwrap(),
1106 Peek {
1107 version,
1108 dim: 2,
1109 doc_count: docs
1110 }
1111 );
1112 }
1113 }
1114
1115 #[tokio::test]
1116 async fn a_peek_is_charged_its_twenty_bytes_and_no_more() {
1117 use object_store::memory::InMemory;
1118 let bytes = encode(&sample(), 2).unwrap();
1119 let store = InMemory::new();
1120 let path = Path::from("docs/segments/x/data.bin");
1121 store.put(&path, bytes.into()).await.unwrap();
1122 peek(&store, &path, &ReadBudget::new(20)).await.unwrap();
1123 let err = peek(&store, &path, &ReadBudget::new(19)).await.unwrap_err();
1124 assert!(
1125 matches!(err, ItzmaError::ReadBudgetExceeded { .. }),
1126 "{err:?}"
1127 );
1128 }
1129
1130 #[tokio::test]
1131 async fn a_peek_refuses_what_is_not_a_segment() {
1132 let good = encode(&sample(), 2).unwrap().to_vec();
1133 let mut bad_magic = good.clone();
1134 bad_magic[0] = b'X';
1135 assert!(corrupt(peek_of(&bad_magic).await.0.unwrap_err()).contains("magic"));
1136
1137 let mut future = good.clone();
1138 future[4..8].copy_from_slice(&4u32.to_le_bytes());
1139 assert!(matches!(
1140 peek_of(&future).await.0,
1141 Err(ItzmaError::UnsupportedFormat { version: 4 })
1142 ));
1143 let mut zero = good.clone();
1144 zero[4..8].copy_from_slice(&0u32.to_le_bytes());
1145 assert!(matches!(
1146 peek_of(&zero).await.0,
1147 Err(ItzmaError::UnsupportedFormat { version: 0 })
1148 ));
1149
1150 for cut in 0..20 {
1151 assert!(peek_of(&good[..cut]).await.0.is_err(), "cut at {cut}");
1152 }
1153 }
1154
1155 #[tokio::test]
1156 async fn a_peek_of_a_missing_object_is_missing() {
1157 use object_store::memory::InMemory;
1158 let path = Path::from("docs/segments/x/data.bin");
1159 let err = peek(&InMemory::new(), &path, &ReadBudget::new(100))
1160 .await
1161 .unwrap_err();
1162 assert!(is_missing(&err), "{err:?}");
1163 }
1164}