Skip to main content

itzma_core/
sparse.rs

1//! The `sparse.bin` sidecar: one segment's raw sparse vectors,
2//! row-addressed the same way `data.bin`'s dense matrix is. Written by
3//! compaction only when at least one document in the segment has one
4//! (`crate::compaction`); read whole by `Namespace::index_sparse` to build
5//! the inverted index, and by the query engine's unindexed-segment fallback.
6//!
7//! # Layout
8//!
9//! All integers are little-endian.
10//!
11//! | Section | Contents |
12//! |---|---|
13//! | Header | magic `ITZS`, `format_version` u32, `rows` u32 |
14//! | Directory | `rows` entries: `term_count` u16, `byte_offset` u64 |
15//! | Rows | each row's `term_count` pairs of `(term_id u32, weight f32)` |
16//!
17//! Row `i` is document `i` of the same segment's `data.bin`, in the ascending
18//! id order [`crate::layer::Layer::sorted_docs`] both objects are built from.
19//! A row with no sparse vector has `term_count` 0 and no bytes of its own.
20
21use 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;
38/// Magic, format_version, rows.
39const HEADER_LEN: usize = 4 + 4 + 4;
40/// term_count, byte_offset.
41const DIR_ENTRY_LEN: usize = 2 + 8;
42
43/// Object key of a segment's sparse sidecar:
44/// `<namespace>/segments/<id>/sparse.bin`. Absent when no document in the
45/// segment has a sparse vector.
46pub fn sparse_path(namespace: &str, id: &str) -> Path {
47    Path::from(format!("{namespace}/segments/{id}/sparse.bin"))
48}
49
50/// Encode `layer`'s sparse vectors in `sorted_docs()` order. A document with
51/// none contributes an empty row, not an absent one, so row numbers still
52/// line up with `data.bin`'s. Compaction writes it through
53/// [`crate::segment::SegmentWriter`]; this is the whole-layer form tests use.
54#[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
64/// Builds `sparse.bin` one row at a time, in `data.bin`'s row order. The
65/// directory comes first in the object but is complete only at the end, so
66/// it is written by [`finish`](Self::finish) and the rows go out as chunks.
67pub(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    /// The next row: a document's sparse vector, or `None` for one without.
83    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    /// The object, and whether any row was given a sparse vector.
101    pub(crate) fn finish(self) -> Result<(object_store::PutPayload, bool)> {
102        let rows = u32::try_from(self.dir.len()).map_err(|_| ItzmaError::CorruptSegment {
103            path: "(encoding)".into(),
104            reason: "too many rows for sparse.bin's u32 row count".into(),
105        })?;
106        let mut head = Vec::with_capacity(HEADER_LEN + self.dir.len() * DIR_ENTRY_LEN);
107        head.extend_from_slice(&MAGIC);
108        head.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
109        head.extend_from_slice(&rows.to_le_bytes());
110        for (term_count, byte_offset) in &self.dir {
111            head.extend_from_slice(&term_count.to_le_bytes());
112            head.extend_from_slice(&byte_offset.to_le_bytes());
113        }
114        let payload = std::iter::once(Bytes::from(head))
115            .chain(self.body.into_bytes())
116            .collect();
117        Ok((payload, self.any))
118    }
119}
120
121/// The encoder [`SparseWriter`] replaced, kept as the reference its
122/// equality test compares against.
123#[cfg(test)]
124pub(crate) fn reference_encode(layer: &Layer) -> Result<Bytes> {
125    let docs = layer.sorted_docs();
126    let rows = u32::try_from(docs.len()).map_err(|_| ItzmaError::CorruptSegment {
127        path: "(encoding)".into(),
128        reason: "too many rows for sparse.bin's u32 row count".into(),
129    })?;
130
131    let mut body = BytesMut::new();
132    let mut dir = Vec::with_capacity(docs.len());
133    for doc in &docs {
134        let terms = doc.sparse.as_deref().unwrap_or(&[]);
135        let term_count = u16::try_from(terms.len()).map_err(|_| ItzmaError::CorruptSegment {
136            path: "(encoding)".into(),
137            reason: "a row has more sparse terms than fit a u16".into(),
138        })?;
139        dir.push((term_count, body.len() as u64));
140        for &(term, weight) in terms {
141            body.extend_from_slice(&term.to_le_bytes());
142            body.extend_from_slice(&weight.to_le_bytes());
143        }
144    }
145
146    let mut out = BytesMut::with_capacity(HEADER_LEN + dir.len() * DIR_ENTRY_LEN + body.len());
147    out.extend_from_slice(&MAGIC);
148    out.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
149    out.extend_from_slice(&rows.to_le_bytes());
150    for (term_count, byte_offset) in &dir {
151        out.extend_from_slice(&term_count.to_le_bytes());
152        out.extend_from_slice(&byte_offset.to_le_bytes());
153    }
154    out.extend_from_slice(&body);
155    Ok(out.freeze())
156}
157
158/// A cursor over `sparse.bin`'s bytes. Every read is bounds-checked; failures
159/// carry the object's key and raise `CorruptSegment`, the same variant
160/// `data.bin`'s own decoder uses — this is segment data, just derived.
161struct Reader<'a> {
162    path: &'a str,
163    buf: &'a [u8],
164    pos: usize,
165}
166
167impl<'a> Reader<'a> {
168    fn new(path: &'a str, buf: &'a [u8]) -> Self {
169        Self { path, buf, pos: 0 }
170    }
171
172    fn corrupt(&self, reason: impl Into<String>) -> ItzmaError {
173        ItzmaError::CorruptSegment {
174            path: self.path.to_string(),
175            reason: reason.into(),
176        }
177    }
178
179    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
180        let out = self
181            .buf
182            .get(self.pos..)
183            .and_then(|rest| rest.get(..n))
184            .ok_or_else(|| self.corrupt("sparse.bin is truncated"))?;
185        self.pos += n;
186        Ok(out)
187    }
188
189    fn u16(&mut self) -> Result<u16> {
190        let bytes = self.take(2)?;
191        Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
192    }
193
194    fn u32(&mut self) -> Result<u32> {
195        let bytes = self.take(4)?;
196        Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
197    }
198
199    fn u64(&mut self) -> Result<u64> {
200        let bytes = self.take(8)?;
201        let mut a = [0u8; 8];
202        a.copy_from_slice(bytes);
203        Ok(u64::from_le_bytes(a))
204    }
205
206    fn f32(&mut self) -> Result<f32> {
207        Ok(f32::from_bits(self.u32()?))
208    }
209}
210
211/// Decode `bytes` into one entry per row (`None` for a row with no sparse
212/// vector), checked against the segment's own row count.
213///
214/// # Errors
215///
216/// [`ItzmaError::CorruptSegment`] for a bad magic, an unsupported version, a
217/// row count that disagrees with `rows`, a directory entry or row that runs
218/// past the object, or an overflowing offset.
219/// [`ItzmaError::UnsupportedFormat`] for a container version this build does
220/// not read.
221pub(crate) fn decode(path: &str, bytes: &[u8], rows: u64) -> Result<Vec<Option<SparseVector>>> {
222    let mut r = Reader::new(path, bytes);
223    if r.take(4)? != MAGIC {
224        return Err(r.corrupt("bad magic"));
225    }
226    match r.u32()? {
227        FORMAT_VERSION => {}
228        version => return Err(ItzmaError::UnsupportedFormat { version }),
229    }
230    let got_rows = u64::from(r.u32()?);
231    if got_rows != rows {
232        return Err(r.corrupt(format!("{got_rows} rows, the segment has {rows}")));
233    }
234    let mut dir = Vec::with_capacity(got_rows as usize);
235    for _ in 0..got_rows {
236        dir.push((r.u16()?, r.u64()?));
237    }
238    let body_start = r.pos;
239    let mut out = Vec::with_capacity(got_rows as usize);
240    for &(term_count, byte_offset) in &dir {
241        if term_count == 0 {
242            out.push(None);
243            continue;
244        }
245        let start = body_start
246            .checked_add(byte_offset as usize)
247            .ok_or_else(|| r.corrupt("row offset overflows"))?;
248        let mut row = Reader {
249            path,
250            buf: bytes,
251            pos: start,
252        };
253        let mut terms = Vec::with_capacity(term_count as usize);
254        for _ in 0..term_count {
255            let term = row.u32()?;
256            let weight = row.f32()?;
257            terms.push((term, weight));
258        }
259        out.push(Some(terms));
260    }
261    Ok(out)
262}
263
264/// A segment's `sparse.bin`, read forward a range of rows at a time by a
265/// streaming merge: the directory once, then one body request per
266/// range. Every request is charged to the budget before it is sent.
267pub(crate) struct SparseRows<'a> {
268    store: &'a dyn ObjectStore,
269    budget: &'a ReadBudget,
270    path: Path,
271    dir: Vec<(u16, u64)>,
272    body_start: u64,
273}
274
275impl<'a> SparseRows<'a> {
276    /// Open segment `id`'s sidecar for a segment of `rows` documents, or
277    /// `Ok(None)` when it has none. Reads and checks the header and the
278    /// directory.
279    ///
280    /// # Errors
281    ///
282    /// [`ItzmaError::CorruptSegment`] for a bad magic, a row count other than
283    /// `rows`, or a directory past the object; [`ItzmaError::UnsupportedFormat`]
284    /// for a version this build does not read.
285    pub(crate) async fn open(
286        store: &'a dyn ObjectStore,
287        namespace: &str,
288        id: &str,
289        rows: u64,
290        budget: &'a ReadBudget,
291    ) -> Result<Option<Self>> {
292        let path = sparse_path(namespace, id);
293        let head = match charged_range(store, budget, &path, 0..HEADER_LEN as u64).await {
294            Ok(head) => head,
295            Err(e) if is_missing(&e) => return Ok(None),
296            Err(e) => return Err(e),
297        };
298        let name = path.to_string();
299        let mut r = Reader::new(&name, &head);
300        if r.take(4)? != MAGIC {
301            return Err(r.corrupt("bad magic"));
302        }
303        match r.u32()? {
304            FORMAT_VERSION => {}
305            version => return Err(ItzmaError::UnsupportedFormat { version }),
306        }
307        let got_rows = u64::from(r.u32()?);
308        if got_rows != rows {
309            return Err(r.corrupt(format!("{got_rows} rows, the segment has {rows}")));
310        }
311        let body_start = HEADER_LEN as u64 + rows * DIR_ENTRY_LEN as u64;
312        let raw = charged_range(store, budget, &path, HEADER_LEN as u64..body_start).await?;
313        let mut r = Reader::new(&name, &raw);
314        let mut dir = Vec::with_capacity(rows as usize);
315        for _ in 0..rows {
316            dir.push((r.u16()?, r.u64()?));
317        }
318        Ok(Some(Self {
319            store,
320            budget,
321            path,
322            dir,
323            body_start,
324        }))
325    }
326
327    /// Where `rows`' bytes are, relative to the body, or `None` for no rows.
328    fn span(&self, rows: &Range<u64>) -> Option<Result<Range<u64>>> {
329        if rows.is_empty() {
330            return None;
331        }
332        let first = self.dir.get(rows.start as usize)?;
333        let (count, last) = self.dir.get(rows.end as usize - 1)?;
334        let end = last.checked_add(u64::from(*count) * 8);
335        Some(match end {
336            Some(end) if end >= first.1 => Ok(first.1..end),
337            _ => Err(self.corrupt("row offsets go backwards or overflow")),
338        })
339    }
340
341    /// The body bytes `rows` take, for sizing a read-ahead window; 0 for rows
342    /// the directory does not hold.
343    pub(crate) fn bytes_of(&self, rows: Range<u64>) -> u64 {
344        match self.span(&rows) {
345            Some(Ok(span)) => span.end - span.start,
346            _ => 0,
347        }
348    }
349
350    /// Rows `rows`, in order, `None` for a row without a sparse vector.
351    ///
352    /// # Errors
353    ///
354    /// [`ItzmaError::CorruptSegment`] for rows the directory does not hold or
355    /// whose bytes run past what the directory says, [`missing`] for an
356    /// object that is gone.
357    pub(crate) async fn rows(&self, rows: Range<u64>) -> Result<Vec<Option<SparseVector>>> {
358        let span = match self.span(&rows) {
359            None if rows.is_empty() => return Ok(Vec::new()),
360            None => return Err(self.corrupt("rows past the directory")),
361            Some(span) => span?,
362        };
363        let range = self
364            .body_start
365            .checked_add(span.start)
366            .zip(self.body_start.checked_add(span.end))
367            .map(|(start, end)| start..end)
368            .ok_or_else(|| self.corrupt("row offset overflows"))?;
369        let body = charged_range(self.store, self.budget, &self.path, range).await?;
370        let name = self.path.to_string();
371        let mut out = Vec::with_capacity((rows.end - rows.start) as usize);
372        for &(term_count, offset) in &self.dir[rows.start as usize..rows.end as usize] {
373            if term_count == 0 {
374                out.push(None);
375                continue;
376            }
377            let at = offset
378                .checked_sub(span.start)
379                .ok_or_else(|| self.corrupt("row offsets go backwards"))?;
380            let mut row = Reader {
381                path: &name,
382                buf: &body,
383                pos: usize::try_from(at).unwrap_or(usize::MAX),
384            };
385            let mut terms = Vec::with_capacity(term_count as usize);
386            for _ in 0..term_count {
387                terms.push((row.u32()?, row.f32()?));
388            }
389            out.push(Some(terms));
390        }
391        Ok(out)
392    }
393
394    fn corrupt(&self, reason: &str) -> ItzmaError {
395        ItzmaError::CorruptSegment {
396            path: self.path.to_string(),
397            reason: reason.into(),
398        }
399    }
400}
401
402/// One ranged GET of a sidecar, charged once the response headers say the
403/// object is there and before its body is read, as every segment read is
404///: a missing object is [`missing`] and costs nothing.
405async fn charged_range(
406    store: &dyn ObjectStore,
407    budget: &ReadBudget,
408    path: &Path,
409    range: Range<u64>,
410) -> Result<Bytes> {
411    if range.is_empty() {
412        return Ok(Bytes::new());
413    }
414    let options = object_store::GetOptions {
415        range: Some(object_store::GetRange::Bounded(range.clone())),
416        ..object_store::GetOptions::default()
417    };
418    let got = match store.get_opts(path, options).await {
419        Ok(got) => got,
420        Err(object_store::Error::NotFound { .. }) => return Err(missing(path)),
421        Err(e) => return Err(e.into()),
422    };
423    budget.charge(path.as_ref(), range.end - range.start)?;
424    let bytes = got.bytes().await?;
425    if bytes.len() as u64 != range.end - range.start {
426        return Err(ItzmaError::CorruptSegment {
427            path: path.to_string(),
428            reason: "sparse.bin is truncated".into(),
429        });
430    }
431    Ok(bytes)
432}
433
434/// The `reason` of the error for a `sparse.bin` the store does not have.
435const MISSING: &str = "missing from the store";
436
437/// The error for a segment's sparse sidecar the store lacks. A segment with
438/// no sparse documents legitimately has none — callers check
439/// [`is_missing`] and treat it as "no sparse data here," not damage.
440pub(crate) fn missing(path: &Path) -> ItzmaError {
441    ItzmaError::CorruptSegment {
442        path: path.to_string(),
443        reason: MISSING.into(),
444    }
445}
446
447/// Whether `err` is what [`missing`] builds.
448pub(crate) fn is_missing(err: &ItzmaError) -> bool {
449    matches!(err, ItzmaError::CorruptSegment { reason, .. } if reason == MISSING)
450}
451
452/// Fetch one `sparse.bin` object whole, charging its bytes to `budget`
453/// before they are read. Above `policy`'s `split_above`, the
454/// object is fetched as parallel planner parts instead of one connection.
455pub(crate) async fn fetch_bytes(
456    store: &dyn ObjectStore,
457    path: &Path,
458    budget: &ReadBudget,
459    policy: &FetchPolicy,
460) -> Result<Bytes> {
461    match crate::fetch::whole_object(store, budget, policy, path).await {
462        Ok(bytes) => Ok(bytes),
463        Err(ItzmaError::Storage(object_store::Error::NotFound { .. })) => Err(missing(path)),
464        Err(e) => Err(e),
465    }
466}
467
468/// Decode one segment's data and, if it has one, its sparse sidecar, and
469/// return a layer whose live documents carry their sparse vectors. Row `i`
470/// of `sparse.bin` is `layer.sorted_docs()[i]`, the same order `data.bin`
471/// and `sparse.bin` were both built from (`crate::compaction`).
472///
473/// # Errors
474///
475/// Whatever `segment::decode` or [`decode`] give. A missing `sparse.bin` is
476/// not an error: the segment simply has no sparse documents.
477pub(crate) async fn fetch_with_sparse(
478    store: &dyn ObjectStore,
479    namespace: &str,
480    id: &str,
481    dim: usize,
482    budget: &ReadBudget,
483    policy: &FetchPolicy,
484    lane: Lane,
485) -> Result<Layer> {
486    let data_path = crate::segment::segment_path(namespace, id);
487    let bytes = crate::segment::fetch_bytes(store, &data_path, budget, policy).await?;
488    let path = sparse_path(namespace, id);
489    let sparse_bytes = match fetch_bytes(store, &path, budget, policy).await {
490        Ok(sparse_bytes) => Some(sparse_bytes),
491        Err(e) if is_missing(&e) => None,
492        Err(e) => return Err(e),
493    };
494    let cost = Cost::Bytes(bytes.len() + sparse_bytes.as_ref().map_or(0, Bytes::len));
495    cpu::run(lane, cost, move || {
496        let mut layer = crate::segment::decode(data_path.as_ref(), &bytes, dim)?;
497        if let Some(sparse_bytes) = sparse_bytes {
498            let sorted_ids: Vec<String> =
499                layer.sorted_docs().iter().map(|d| d.id.clone()).collect();
500            let vectors = decode(path.as_ref(), &sparse_bytes, sorted_ids.len() as u64)?;
501            layer.set_sparse(&sorted_ids, vectors);
502        }
503        Ok(layer)
504    })
505    .await
506}
507
508/// Requests in flight at once when fetching several segments (mirrors
509/// `segment::read_all`'s own constant).
510const FETCH_CONCURRENCY: usize = 16;
511
512/// Fetch and decode the listed segments (each with its sparse sidecar, if it
513/// has one) and overlay them oldest to newest — the sparse-aware sibling of
514/// `segment::read_all`, used by the query engine's unindexed-segment source.
515pub(crate) async fn read_all_with_sparse(
516    store: &dyn ObjectStore,
517    namespace: &str,
518    ids: &[String],
519    dim: usize,
520    budget: &ReadBudget,
521    policy: &FetchPolicy,
522    lane: Lane,
523) -> Result<Layer> {
524    use futures::stream::{self, StreamExt, TryStreamExt};
525    // Owned ids: a closure over `&String` is inferred as higher-ranked,
526    // which then fails "Send is not general enough" (see
527    // `segment::read_all`'s own comment on the same shape of fix).
528    stream::iter(ids.iter().cloned())
529        .map(|id| async move {
530            fetch_with_sparse(store, namespace, &id, dim, budget, policy, lane).await
531        })
532        .buffered(FETCH_CONCURRENCY)
533        .try_fold(Layer::new(), |mut acc, segment| async move {
534            acc.overlay(segment);
535            Ok::<_, ItzmaError>(acc)
536        })
537        .await
538}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543    use crate::document::{Document, WalOp};
544
545    fn layer_of(docs: Vec<Document>) -> Layer {
546        let mut layer = Layer::new();
547        for d in docs {
548            layer.apply(WalOp::Upsert(d));
549        }
550        layer
551    }
552
553    fn doc(id: &str, sparse: Option<Vec<(u32, f32)>>) -> Document {
554        Document {
555            id: id.into(),
556            vector: vec![0.0],
557            attrs: None,
558            sparse,
559        }
560    }
561
562    #[test]
563    fn encode_decode_round_trips_in_row_order() {
564        // sorted_docs() is ascending by id: "a", "b", "c".
565        let layer = layer_of(vec![
566            doc("c", Some(vec![(5, 1.0)])),
567            doc("a", None),
568            doc("b", Some(vec![(1, 0.5), (2, 0.25)])),
569        ]);
570        let bytes = encode(&layer).expect("encode");
571        let rows = layer.doc_count() as u64;
572        let decoded = decode("p", &bytes, rows).expect("decode");
573        assert_eq!(
574            decoded,
575            vec![
576                None,                            // "a"
577                Some(vec![(1, 0.5), (2, 0.25)]), // "b"
578                Some(vec![(5, 1.0)]),            // "c"
579            ]
580        );
581    }
582
583    #[test]
584    fn encode_of_an_empty_layer_decodes_to_no_rows() {
585        let layer = Layer::new();
586        let bytes = encode(&layer).expect("encode");
587        assert_eq!(
588            decode("p", &bytes, 0).expect("decode"),
589            Vec::<Option<Vec<(u32, f32)>>>::new()
590        );
591    }
592
593    #[test]
594    fn decode_rejects_a_row_count_mismatch() {
595        let layer = layer_of(vec![doc("a", None)]);
596        let bytes = encode(&layer).expect("encode");
597        let err = decode("p", &bytes, 2).unwrap_err();
598        assert!(matches!(err, ItzmaError::CorruptSegment { .. }));
599    }
600
601    #[test]
602    fn every_truncation_and_bit_flip_is_refused_never_panics() {
603        let layer = layer_of(vec![
604            doc("a", Some(vec![(1, 1.0), (2, 2.0)])),
605            doc("b", Some(vec![(3, 3.0)])),
606        ]);
607        let good = encode(&layer).expect("encode");
608        for len in 0..good.len() {
609            let _ = decode("p", &good[..len], 2); // must not panic
610        }
611        for i in 0..good.len() {
612            let mut bad = good.to_vec();
613            bad[i] ^= 0xFF;
614            let _ = decode("p", &bad, 2); // must not panic
615        }
616    }
617
618    const NS: &str = "ns";
619    const ID: &str = "00000000000000000001-00000000000000000003";
620
621    /// Rows 0 to `n`, every third without a sparse vector, the others with
622    /// one to four terms.
623    fn sparse_layer(n: usize) -> Layer {
624        layer_of(
625            (0..n)
626                .map(|i| {
627                    let terms = (i % 3 != 0).then(|| {
628                        (0..i % 4 + 1)
629                            .map(|t| (t as u32 * 3 + i as u32, i as f32 + 0.5))
630                            .collect()
631                    });
632                    doc(&format!("d{i:05}"), terms)
633                })
634                .collect(),
635        )
636    }
637
638    async fn stored(bytes: Bytes) -> object_store::memory::InMemory {
639        use object_store::ObjectStoreExt;
640        let store = object_store::memory::InMemory::new();
641        store
642            .put(&sparse_path(NS, ID), bytes.into())
643            .await
644            .expect("put");
645        store
646    }
647
648    #[tokio::test]
649    async fn rows_read_forward_equal_the_whole_decode() {
650        for n in [0usize, 1, 7, 300] {
651            let bytes = encode(&sparse_layer(n)).expect("encode");
652            let want = decode("p", &bytes, n as u64).expect("decode");
653            let store = stored(bytes).await;
654            let budget = ReadBudget::unlimited();
655            let rows = SparseRows::open(&store, NS, ID, n as u64, &budget)
656                .await
657                .expect("open")
658                .expect("present");
659            for per in [1u64, 7, 1000] {
660                let mut got = Vec::new();
661                let mut start = 0u64;
662                while start < n as u64 {
663                    let end = (start + per).min(n as u64);
664                    got.extend(rows.rows(start..end).await.expect("rows"));
665                    start = end;
666                }
667                assert_eq!(got, want, "{n} rows, {per} per read");
668            }
669        }
670    }
671
672    #[tokio::test]
673    async fn a_read_is_charged_its_rows_and_bytes_of_says_so() {
674        let bytes = encode(&sparse_layer(300)).expect("encode");
675        let store = stored(bytes).await;
676        let budget = ReadBudget::unlimited();
677        let rows = SparseRows::open(&store, NS, ID, 300, &budget)
678            .await
679            .expect("open")
680            .expect("present");
681        assert_eq!(budget.used(), (HEADER_LEN + 300 * DIR_ENTRY_LEN) as u64);
682        let before = budget.used();
683        rows.rows(10..20).await.expect("rows");
684        assert_eq!(budget.used() - before, rows.bytes_of(10..20));
685        assert!(rows.bytes_of(10..20) > 0);
686        assert_eq!(rows.bytes_of(0..0), 0);
687    }
688
689    #[tokio::test]
690    async fn a_missing_sidecar_is_none() {
691        let store = object_store::memory::InMemory::new();
692        let budget = ReadBudget::unlimited();
693        let opened = SparseRows::open(&store, NS, ID, 3, &budget)
694            .await
695            .expect("open");
696        assert!(opened.is_none());
697        assert_eq!(budget.used(), 0, "nothing was read, so nothing is charged");
698    }
699
700    #[tokio::test]
701    async fn a_row_count_that_disagrees_is_refused() {
702        let store = stored(encode(&sparse_layer(5)).expect("encode")).await;
703        let budget = ReadBudget::unlimited();
704        let err = SparseRows::open(&store, NS, ID, 6, &budget)
705            .await
706            .err()
707            .expect("refused");
708        assert!(matches!(err, ItzmaError::CorruptSegment { .. }), "{err:?}");
709    }
710
711    /// Every row of a sidecar holding `bytes`, read forward in one range.
712    async fn read_all(bytes: Bytes, rows: u64) -> Result<Vec<Option<SparseVector>>> {
713        let store = stored(bytes).await;
714        let budget = ReadBudget::unlimited();
715        match SparseRows::open(&store, NS, ID, rows, &budget).await? {
716            Some(sidecar) => sidecar.rows(0..rows).await,
717            None => Ok(Vec::new()),
718        }
719    }
720
721    #[tokio::test]
722    async fn every_truncation_and_bit_flip_of_the_forward_reader_is_refused_never_panics() {
723        let good = encode(&sparse_layer(4)).expect("encode");
724        let want = decode("p", &good, 4).expect("decode");
725        for len in 0..good.len() {
726            assert!(
727                read_all(good.slice(..len), 4).await.is_err(),
728                "truncated to {len}"
729            );
730        }
731        for i in 0..good.len() {
732            let mut bad = good.to_vec();
733            bad[i] ^= 0xFF;
734            // A flip inside a weight still decodes, to another weight; every
735            // other flip must be an error. Neither may panic.
736            if let Ok(got) = read_all(Bytes::from(bad), 4).await {
737                assert_eq!(got.len(), want.len(), "flip at {i}");
738            }
739        }
740    }
741}