1use bytes::Bytes;
22#[cfg(test)]
23use bytes::BytesMut;
24use std::ops::Range;
25
26use object_store::ObjectStore;
27use object_store::path::Path;
28
29use crate::budget::ReadBudget;
30use crate::cpu::{self, Cost, Lane};
31use crate::document::SparseVector;
32use crate::error::{ItzmaError, Result};
33use crate::fetch::FetchPolicy;
34use crate::layer::Layer;
35
36const MAGIC: [u8; 4] = *b"ITZS";
37pub(crate) const FORMAT_VERSION: u32 = 1;
38const HEADER_LEN: usize = 4 + 4 + 4;
40const DIR_ENTRY_LEN: usize = 2 + 8;
42
43pub fn sparse_path(namespace: &str, id: &str) -> Path {
47 Path::from(format!("{namespace}/segments/{id}/sparse.bin"))
48}
49
50#[cfg(test)]
55pub(crate) fn encode(layer: &Layer) -> Result<Bytes> {
56 let mut writer = SparseWriter::new();
57 for doc in layer.sorted_docs() {
58 writer.row(doc.sparse.as_ref())?;
59 }
60 let (payload, _) = writer.finish()?;
61 Ok(payload.into())
62}
63
64pub(crate) struct SparseWriter {
68 dir: Vec<(u16, u64)>,
69 body: crate::segment::Chunks,
70 any: bool,
71}
72
73impl SparseWriter {
74 pub(crate) fn new() -> Self {
75 Self {
76 dir: Vec::new(),
77 body: crate::segment::Chunks::default(),
78 any: false,
79 }
80 }
81
82 pub(crate) fn row(&mut self, sparse: Option<&SparseVector>) -> Result<()> {
84 self.any |= sparse.is_some();
85 let terms = sparse.map_or(&[][..], Vec::as_slice);
86 let term_count = u16::try_from(terms.len()).map_err(|_| ItzmaError::CorruptSegment {
87 path: "(encoding)".into(),
88 reason: "a row has more sparse terms than fit a u16".into(),
89 })?;
90 self.dir.push((term_count, self.body.len()));
91 let mut row = Vec::with_capacity(terms.len() * 8);
92 for &(term, weight) in terms {
93 row.extend_from_slice(&term.to_le_bytes());
94 row.extend_from_slice(&weight.to_le_bytes());
95 }
96 self.body.push(&row);
97 Ok(())
98 }
99
100 #[cfg(test)]
102 pub(crate) fn finish(self) -> Result<(object_store::PutPayload, bool)> {
103 let (body, any) = self.finish_body()?;
104 Ok((body.into_memory()?, any))
105 }
106
107 pub(crate) fn spill_to(&mut self, spill: &crate::put::Spill) {
109 self.body.spill_to(spill);
110 }
111
112 pub(crate) fn finish_body(self) -> Result<(crate::put::Body, bool)> {
114 let rows = u32::try_from(self.dir.len()).map_err(|_| ItzmaError::CorruptSegment {
115 path: "(encoding)".into(),
116 reason: "too many rows for sparse.bin's u32 row count".into(),
117 })?;
118 let mut head = Vec::with_capacity(HEADER_LEN + self.dir.len() * DIR_ENTRY_LEN);
119 head.extend_from_slice(&MAGIC);
120 head.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
121 head.extend_from_slice(&rows.to_le_bytes());
122 for (term_count, byte_offset) in &self.dir {
123 head.extend_from_slice(&term_count.to_le_bytes());
124 head.extend_from_slice(&byte_offset.to_le_bytes());
125 }
126 let mut body = crate::put::Body::default();
127 body.push(Bytes::from(head));
128 self.body.into_body(&mut body)?;
129 Ok((body, self.any))
130 }
131}
132
133#[cfg(test)]
136pub(crate) fn reference_encode(layer: &Layer) -> Result<Bytes> {
137 let docs = layer.sorted_docs();
138 let rows = u32::try_from(docs.len()).map_err(|_| ItzmaError::CorruptSegment {
139 path: "(encoding)".into(),
140 reason: "too many rows for sparse.bin's u32 row count".into(),
141 })?;
142
143 let mut body = BytesMut::new();
144 let mut dir = Vec::with_capacity(docs.len());
145 for doc in &docs {
146 let terms = doc.sparse.as_deref().unwrap_or(&[]);
147 let term_count = u16::try_from(terms.len()).map_err(|_| ItzmaError::CorruptSegment {
148 path: "(encoding)".into(),
149 reason: "a row has more sparse terms than fit a u16".into(),
150 })?;
151 dir.push((term_count, body.len() as u64));
152 for &(term, weight) in terms {
153 body.extend_from_slice(&term.to_le_bytes());
154 body.extend_from_slice(&weight.to_le_bytes());
155 }
156 }
157
158 let mut out = BytesMut::with_capacity(HEADER_LEN + dir.len() * DIR_ENTRY_LEN + body.len());
159 out.extend_from_slice(&MAGIC);
160 out.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
161 out.extend_from_slice(&rows.to_le_bytes());
162 for (term_count, byte_offset) in &dir {
163 out.extend_from_slice(&term_count.to_le_bytes());
164 out.extend_from_slice(&byte_offset.to_le_bytes());
165 }
166 out.extend_from_slice(&body);
167 Ok(out.freeze())
168}
169
170struct Reader<'a> {
174 path: &'a str,
175 buf: &'a [u8],
176 pos: usize,
177}
178
179impl<'a> Reader<'a> {
180 fn new(path: &'a str, buf: &'a [u8]) -> Self {
181 Self { path, buf, pos: 0 }
182 }
183
184 fn corrupt(&self, reason: impl Into<String>) -> ItzmaError {
185 ItzmaError::CorruptSegment {
186 path: self.path.to_string(),
187 reason: reason.into(),
188 }
189 }
190
191 fn take(&mut self, n: usize) -> Result<&'a [u8]> {
192 let out = self
193 .buf
194 .get(self.pos..)
195 .and_then(|rest| rest.get(..n))
196 .ok_or_else(|| self.corrupt("sparse.bin is truncated"))?;
197 self.pos += n;
198 Ok(out)
199 }
200
201 fn u16(&mut self) -> Result<u16> {
202 let bytes = self.take(2)?;
203 Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
204 }
205
206 fn u32(&mut self) -> Result<u32> {
207 let bytes = self.take(4)?;
208 Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
209 }
210
211 fn u64(&mut self) -> Result<u64> {
212 let bytes = self.take(8)?;
213 let mut a = [0u8; 8];
214 a.copy_from_slice(bytes);
215 Ok(u64::from_le_bytes(a))
216 }
217
218 fn f32(&mut self) -> Result<f32> {
219 Ok(f32::from_bits(self.u32()?))
220 }
221}
222
223pub(crate) fn decode(path: &str, bytes: &[u8], rows: u64) -> Result<Vec<Option<SparseVector>>> {
234 let mut r = Reader::new(path, bytes);
235 if r.take(4)? != MAGIC {
236 return Err(r.corrupt("bad magic"));
237 }
238 match r.u32()? {
239 FORMAT_VERSION => {}
240 version => return Err(ItzmaError::UnsupportedFormat { version }),
241 }
242 let got_rows = u64::from(r.u32()?);
243 if got_rows != rows {
244 return Err(r.corrupt(format!("{got_rows} rows, the segment has {rows}")));
245 }
246 let mut dir = Vec::with_capacity(got_rows as usize);
247 for _ in 0..got_rows {
248 dir.push((r.u16()?, r.u64()?));
249 }
250 let body_start = r.pos;
251 let mut out = Vec::with_capacity(got_rows as usize);
252 for &(term_count, byte_offset) in &dir {
253 if term_count == 0 {
254 out.push(None);
255 continue;
256 }
257 let start = body_start
258 .checked_add(byte_offset as usize)
259 .ok_or_else(|| r.corrupt("row offset overflows"))?;
260 let mut row = Reader {
261 path,
262 buf: bytes,
263 pos: start,
264 };
265 let mut terms = Vec::with_capacity(term_count as usize);
266 for _ in 0..term_count {
267 let term = row.u32()?;
268 let weight = row.f32()?;
269 terms.push((term, weight));
270 }
271 out.push(Some(terms));
272 }
273 Ok(out)
274}
275
276const RUN_GAP: u32 = 64;
280
281pub(crate) struct SparseRows<'a> {
285 store: &'a dyn ObjectStore,
286 budget: &'a ReadBudget,
287 path: Path,
288 dir: Vec<(u16, u64)>,
289 body_start: u64,
290}
291
292impl<'a> SparseRows<'a> {
293 pub(crate) async fn open(
303 store: &'a dyn ObjectStore,
304 namespace: &str,
305 id: &str,
306 rows: u64,
307 budget: &'a ReadBudget,
308 ) -> Result<Option<Self>> {
309 let path = sparse_path(namespace, id);
310 let head = match charged_range(store, budget, &path, 0..HEADER_LEN as u64).await {
311 Ok(head) => head,
312 Err(e) if is_missing(&e) => return Ok(None),
313 Err(e) => return Err(e),
314 };
315 let name = path.to_string();
316 let mut r = Reader::new(&name, &head);
317 if r.take(4)? != MAGIC {
318 return Err(r.corrupt("bad magic"));
319 }
320 match r.u32()? {
321 FORMAT_VERSION => {}
322 version => return Err(ItzmaError::UnsupportedFormat { version }),
323 }
324 let got_rows = u64::from(r.u32()?);
325 if got_rows != rows {
326 return Err(r.corrupt(format!("{got_rows} rows, the segment has {rows}")));
327 }
328 let body_start = HEADER_LEN as u64 + rows * DIR_ENTRY_LEN as u64;
329 let raw = charged_range(store, budget, &path, HEADER_LEN as u64..body_start).await?;
330 let mut r = Reader::new(&name, &raw);
331 let mut dir = Vec::with_capacity(rows as usize);
332 for _ in 0..rows {
333 dir.push((r.u16()?, r.u64()?));
334 }
335 Ok(Some(Self {
336 store,
337 budget,
338 path,
339 dir,
340 body_start,
341 }))
342 }
343
344 fn span(&self, rows: &Range<u64>) -> Option<Result<Range<u64>>> {
346 if rows.is_empty() {
347 return None;
348 }
349 let first = self.dir.get(rows.start as usize)?;
350 let (count, last) = self.dir.get(rows.end as usize - 1)?;
351 let end = last.checked_add(u64::from(*count) * 8);
352 Some(match end {
353 Some(end) if end >= first.1 => Ok(first.1..end),
354 _ => Err(self.corrupt("row offsets go backwards or overflow")),
355 })
356 }
357
358 pub(crate) fn bytes_of(&self, rows: Range<u64>) -> u64 {
361 match self.span(&rows) {
362 Some(Ok(span)) => span.end - span.start,
363 _ => 0,
364 }
365 }
366
367 pub(crate) async fn rows(&self, rows: Range<u64>) -> Result<Vec<Option<SparseVector>>> {
375 let span = match self.span(&rows) {
376 None if rows.is_empty() => return Ok(Vec::new()),
377 None => return Err(self.corrupt("rows past the directory")),
378 Some(span) => span?,
379 };
380 let range = self
381 .body_start
382 .checked_add(span.start)
383 .zip(self.body_start.checked_add(span.end))
384 .map(|(start, end)| start..end)
385 .ok_or_else(|| self.corrupt("row offset overflows"))?;
386 let body = charged_range(self.store, self.budget, &self.path, range).await?;
387 let name = self.path.to_string();
388 let mut out = Vec::with_capacity((rows.end - rows.start) as usize);
389 for &(term_count, offset) in &self.dir[rows.start as usize..rows.end as usize] {
390 if term_count == 0 {
391 out.push(None);
392 continue;
393 }
394 let at = offset
395 .checked_sub(span.start)
396 .ok_or_else(|| self.corrupt("row offsets go backwards"))?;
397 let mut row = Reader {
398 path: &name,
399 buf: &body,
400 pos: usize::try_from(at).unwrap_or(usize::MAX),
401 };
402 let mut terms = Vec::with_capacity(term_count as usize);
403 for _ in 0..term_count {
404 terms.push((row.u32()?, row.f32()?));
405 }
406 out.push(Some(terms));
407 }
408 Ok(out)
409 }
410
411 pub(crate) async fn rows_at(&self, rows: &[u32]) -> Result<Vec<Option<SparseVector>>> {
419 let mut runs: Vec<Range<usize>> = Vec::new();
420 for (i, pair) in rows.windows(2).enumerate() {
421 if pair[1].saturating_sub(pair[0]) > RUN_GAP {
422 let start = runs.last().map_or(0, |r| r.end);
423 runs.push(start..i + 1);
424 }
425 }
426 if !rows.is_empty() {
427 let start = runs.last().map_or(0, |r| r.end);
428 runs.push(start..rows.len());
429 }
430 let fetched = futures::future::try_join_all((0..runs.len()).map(|i| {
433 let run = &rows[runs[i].clone()];
434 let (lo, hi) = (run[0], run[run.len() - 1]);
435 self.rows(u64::from(lo)..u64::from(hi) + 1)
436 }))
437 .await?;
438 let mut out = Vec::with_capacity(rows.len());
439 for (run, mut span) in runs.iter().zip(fetched) {
440 let run = &rows[run.clone()];
441 let lo = run[0];
442 for &row in run {
443 out.push(span.get_mut((row - lo) as usize).and_then(Option::take));
444 }
445 }
446 Ok(out)
447 }
448
449 fn corrupt(&self, reason: &str) -> ItzmaError {
450 ItzmaError::CorruptSegment {
451 path: self.path.to_string(),
452 reason: reason.into(),
453 }
454 }
455}
456
457async fn charged_range(
461 store: &dyn ObjectStore,
462 budget: &ReadBudget,
463 path: &Path,
464 range: Range<u64>,
465) -> Result<Bytes> {
466 if range.is_empty() {
467 return Ok(Bytes::new());
468 }
469 let options = object_store::GetOptions {
470 range: Some(object_store::GetRange::Bounded(range.clone())),
471 ..object_store::GetOptions::default()
472 };
473 let got = match store.get_opts(path, options).await {
474 Ok(got) => got,
475 Err(object_store::Error::NotFound { .. }) => return Err(missing(path)),
476 Err(e) => return Err(e.into()),
477 };
478 budget.charge(path.as_ref(), range.end - range.start)?;
479 let bytes = got.bytes().await?;
480 if bytes.len() as u64 != range.end - range.start {
481 return Err(ItzmaError::CorruptSegment {
482 path: path.to_string(),
483 reason: "sparse.bin is truncated".into(),
484 });
485 }
486 Ok(bytes)
487}
488
489const MISSING: &str = "missing from the store";
491
492pub(crate) fn missing(path: &Path) -> ItzmaError {
496 ItzmaError::CorruptSegment {
497 path: path.to_string(),
498 reason: MISSING.into(),
499 }
500}
501
502pub(crate) fn is_missing(err: &ItzmaError) -> bool {
504 matches!(err, ItzmaError::CorruptSegment { reason, .. } if reason == MISSING)
505}
506
507pub(crate) async fn fetch_bytes(
511 store: &dyn ObjectStore,
512 path: &Path,
513 budget: &ReadBudget,
514 policy: &FetchPolicy,
515) -> Result<Bytes> {
516 match crate::fetch::whole_object(store, budget, policy, path).await {
517 Ok(bytes) => Ok(bytes),
518 Err(ItzmaError::Storage(object_store::Error::NotFound { .. })) => Err(missing(path)),
519 Err(e) => Err(e),
520 }
521}
522
523pub(crate) async fn fetch_with_sparse(
533 store: &dyn ObjectStore,
534 namespace: &str,
535 id: &str,
536 dim: usize,
537 budget: &ReadBudget,
538 policy: &FetchPolicy,
539 lane: Lane,
540) -> Result<Layer> {
541 let data_path = crate::segment::segment_path(namespace, id);
542 let bytes = crate::segment::fetch_bytes(store, &data_path, budget, policy).await?;
543 let path = sparse_path(namespace, id);
544 let sparse_bytes = match fetch_bytes(store, &path, budget, policy).await {
545 Ok(sparse_bytes) => Some(sparse_bytes),
546 Err(e) if is_missing(&e) => None,
547 Err(e) => return Err(e),
548 };
549 let cost = Cost::Bytes(bytes.len() + sparse_bytes.as_ref().map_or(0, Bytes::len));
550 cpu::run(lane, cost, move || {
551 let mut layer = crate::segment::decode(data_path.as_ref(), &bytes, dim)?;
552 if let Some(sparse_bytes) = sparse_bytes {
553 let sorted_ids: Vec<String> =
554 layer.sorted_docs().iter().map(|d| d.id.clone()).collect();
555 let vectors = decode(path.as_ref(), &sparse_bytes, sorted_ids.len() as u64)?;
556 layer.set_sparse(&sorted_ids, vectors);
557 }
558 Ok(layer)
559 })
560 .await
561}
562
563const FETCH_CONCURRENCY: usize = 16;
566
567pub(crate) async fn read_all_with_sparse(
571 store: &dyn ObjectStore,
572 namespace: &str,
573 ids: &[String],
574 dim: usize,
575 budget: &ReadBudget,
576 policy: &FetchPolicy,
577 lane: Lane,
578) -> Result<Layer> {
579 use futures::stream::{self, StreamExt, TryStreamExt};
580 stream::iter(ids.iter().cloned())
584 .map(|id| async move {
585 fetch_with_sparse(store, namespace, &id, dim, budget, policy, lane).await
586 })
587 .buffered(FETCH_CONCURRENCY)
588 .try_fold(Layer::new(), |mut acc, segment| async move {
589 acc.overlay(segment);
590 Ok::<_, ItzmaError>(acc)
591 })
592 .await
593}
594
595#[cfg(test)]
596mod tests {
597 use super::*;
598 use crate::document::{Document, WalOp};
599
600 fn layer_of(docs: Vec<Document>) -> Layer {
601 let mut layer = Layer::new();
602 for d in docs {
603 layer.apply(WalOp::Upsert(d));
604 }
605 layer
606 }
607
608 fn doc(id: &str, sparse: Option<Vec<(u32, f32)>>) -> Document {
609 Document {
610 id: id.into(),
611 vector: vec![0.0],
612 attrs: None,
613 sparse,
614 }
615 }
616
617 #[test]
618 fn encode_decode_round_trips_in_row_order() {
619 let layer = layer_of(vec![
621 doc("c", Some(vec![(5, 1.0)])),
622 doc("a", None),
623 doc("b", Some(vec![(1, 0.5), (2, 0.25)])),
624 ]);
625 let bytes = encode(&layer).expect("encode");
626 let rows = layer.doc_count() as u64;
627 let decoded = decode("p", &bytes, rows).expect("decode");
628 assert_eq!(
629 decoded,
630 vec![
631 None, Some(vec![(1, 0.5), (2, 0.25)]), Some(vec![(5, 1.0)]), ]
635 );
636 }
637
638 #[test]
639 fn encode_of_an_empty_layer_decodes_to_no_rows() {
640 let layer = Layer::new();
641 let bytes = encode(&layer).expect("encode");
642 assert_eq!(
643 decode("p", &bytes, 0).expect("decode"),
644 Vec::<Option<Vec<(u32, f32)>>>::new()
645 );
646 }
647
648 #[test]
649 fn decode_rejects_a_row_count_mismatch() {
650 let layer = layer_of(vec![doc("a", None)]);
651 let bytes = encode(&layer).expect("encode");
652 let err = decode("p", &bytes, 2).unwrap_err();
653 assert!(matches!(err, ItzmaError::CorruptSegment { .. }));
654 }
655
656 #[test]
657 fn every_truncation_and_bit_flip_is_refused_never_panics() {
658 let layer = layer_of(vec![
659 doc("a", Some(vec![(1, 1.0), (2, 2.0)])),
660 doc("b", Some(vec![(3, 3.0)])),
661 ]);
662 let good = encode(&layer).expect("encode");
663 for len in 0..good.len() {
664 let _ = decode("p", &good[..len], 2); }
666 for i in 0..good.len() {
667 let mut bad = good.to_vec();
668 bad[i] ^= 0xFF;
669 let _ = decode("p", &bad, 2); }
671 }
672
673 const NS: &str = "ns";
674 const ID: &str = "00000000000000000001-00000000000000000003";
675
676 fn sparse_layer(n: usize) -> Layer {
679 layer_of(
680 (0..n)
681 .map(|i| {
682 let terms = (i % 3 != 0).then(|| {
683 (0..i % 4 + 1)
684 .map(|t| (t as u32 * 3 + i as u32, i as f32 + 0.5))
685 .collect()
686 });
687 doc(&format!("d{i:05}"), terms)
688 })
689 .collect(),
690 )
691 }
692
693 async fn stored(bytes: Bytes) -> object_store::memory::InMemory {
694 use object_store::ObjectStoreExt;
695 let store = object_store::memory::InMemory::new();
696 store
697 .put(&sparse_path(NS, ID), bytes.into())
698 .await
699 .expect("put");
700 store
701 }
702
703 #[tokio::test]
704 async fn rows_read_forward_equal_the_whole_decode() {
705 for n in [0usize, 1, 7, 300] {
706 let bytes = encode(&sparse_layer(n)).expect("encode");
707 let want = decode("p", &bytes, n as u64).expect("decode");
708 let store = stored(bytes).await;
709 let budget = ReadBudget::unlimited();
710 let rows = SparseRows::open(&store, NS, ID, n as u64, &budget)
711 .await
712 .expect("open")
713 .expect("present");
714 for per in [1u64, 7, 1000] {
715 let mut got = Vec::new();
716 let mut start = 0u64;
717 while start < n as u64 {
718 let end = (start + per).min(n as u64);
719 got.extend(rows.rows(start..end).await.expect("rows"));
720 start = end;
721 }
722 assert_eq!(got, want, "{n} rows, {per} per read");
723 }
724 }
725 }
726
727 #[tokio::test]
728 async fn a_read_is_charged_its_rows_and_bytes_of_says_so() {
729 let bytes = encode(&sparse_layer(300)).expect("encode");
730 let store = stored(bytes).await;
731 let budget = ReadBudget::unlimited();
732 let rows = SparseRows::open(&store, NS, ID, 300, &budget)
733 .await
734 .expect("open")
735 .expect("present");
736 assert_eq!(budget.used(), (HEADER_LEN + 300 * DIR_ENTRY_LEN) as u64);
737 let before = budget.used();
738 rows.rows(10..20).await.expect("rows");
739 assert_eq!(budget.used() - before, rows.bytes_of(10..20));
740 assert!(rows.bytes_of(10..20) > 0);
741 assert_eq!(rows.bytes_of(0..0), 0);
742 }
743
744 #[tokio::test]
745 async fn a_missing_sidecar_is_none() {
746 let store = object_store::memory::InMemory::new();
747 let budget = ReadBudget::unlimited();
748 let opened = SparseRows::open(&store, NS, ID, 3, &budget)
749 .await
750 .expect("open");
751 assert!(opened.is_none());
752 assert_eq!(budget.used(), 0, "nothing was read, so nothing is charged");
753 }
754
755 #[tokio::test]
756 async fn a_row_count_that_disagrees_is_refused() {
757 let store = stored(encode(&sparse_layer(5)).expect("encode")).await;
758 let budget = ReadBudget::unlimited();
759 let err = SparseRows::open(&store, NS, ID, 6, &budget)
760 .await
761 .err()
762 .expect("refused");
763 assert!(matches!(err, ItzmaError::CorruptSegment { .. }), "{err:?}");
764 }
765
766 async fn read_all(bytes: Bytes, rows: u64) -> Result<Vec<Option<SparseVector>>> {
768 let store = stored(bytes).await;
769 let budget = ReadBudget::unlimited();
770 match SparseRows::open(&store, NS, ID, rows, &budget).await? {
771 Some(sidecar) => sidecar.rows(0..rows).await,
772 None => Ok(Vec::new()),
773 }
774 }
775
776 #[tokio::test]
777 async fn every_truncation_and_bit_flip_of_the_forward_reader_is_refused_never_panics() {
778 let good = encode(&sparse_layer(4)).expect("encode");
779 let want = decode("p", &good, 4).expect("decode");
780 for len in 0..good.len() {
781 assert!(
782 read_all(good.slice(..len), 4).await.is_err(),
783 "truncated to {len}"
784 );
785 }
786 for i in 0..good.len() {
787 let mut bad = good.to_vec();
788 bad[i] ^= 0xFF;
789 if let Ok(got) = read_all(Bytes::from(bad), 4).await {
792 assert_eq!(got.len(), want.len(), "flip at {i}");
793 }
794 }
795 }
796}