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