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    #[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    /// Spill the body's sealed chunks to files under `spill`.
108    pub(crate) fn spill_to(&mut self, spill: &crate::put::Spill) {
109        self.body.spill_to(spill);
110    }
111
112    /// [`finish`](Self::finish) as a body, which may be in a spill file.
113    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/// The encoder [`SparseWriter`] replaced, kept as the reference its
134/// equality test compares against.
135#[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
170/// A cursor over `sparse.bin`'s bytes. Every read is bounds-checked; failures
171/// carry the object's key and raise `CorruptSegment`, the same variant
172/// `data.bin`'s own decoder uses — this is segment data, just derived.
173struct 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
223/// Decode `bytes` into one entry per row (`None` for a row with no sparse
224/// vector), checked against the segment's own row count.
225///
226/// # Errors
227///
228/// [`ItzmaError::CorruptSegment`] for a bad magic, an unsupported version, a
229/// row count that disagrees with `rows`, a directory entry or row that runs
230/// past the object, or an overflowing offset.
231/// [`ItzmaError::UnsupportedFormat`] for a container version this build does
232/// not read.
233pub(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
276/// Kept rows at most this far apart are read in one range by
277/// [`SparseRows::rows_at`]: below it, a request costs more than the rows
278/// between.
279const RUN_GAP: u32 = 64;
280
281/// A segment's `sparse.bin`, read forward a range of rows at a time by a
282/// streaming merge: the directory once, then one body request per
283/// range. Every request is charged to the budget before it is sent.
284pub(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    /// Open segment `id`'s sidecar for a segment of `rows` documents, or
294    /// `Ok(None)` when it has none. Reads and checks the header and the
295    /// directory.
296    ///
297    /// # Errors
298    ///
299    /// [`ItzmaError::CorruptSegment`] for a bad magic, a row count other than
300    /// `rows`, or a directory past the object; [`ItzmaError::UnsupportedFormat`]
301    /// for a version this build does not read.
302    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    /// Where `rows`' bytes are, relative to the body, or `None` for no rows.
345    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    /// The body bytes `rows` take, for sizing a read-ahead window; 0 for rows
359    /// the directory does not hold.
360    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    /// Rows `rows`, in order, `None` for a row without a sparse vector.
368    ///
369    /// # Errors
370    ///
371    /// [`ItzmaError::CorruptSegment`] for rows the directory does not hold or
372    /// whose bytes run past what the directory says, [`missing`] for an
373    /// object that is gone.
374    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    /// The listed rows, ascending, in order. Rows within [`RUN_GAP`] of each
412    /// other are read as one range and the runs are fetched at the same time,
413    /// so rows a filter dropped between two far-apart kept rows cost nothing.
414    ///
415    /// # Errors
416    ///
417    /// As for [`rows`](Self::rows).
418    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        // Indexed by position, not mapped over borrowed values (see
431        // `query::open_sources`).
432        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
457/// One ranged GET of a sidecar, charged once the response headers say the
458/// object is there and before its body is read, as every segment read is
459///: a missing object is [`missing`] and costs nothing.
460async 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
489/// The `reason` of the error for a `sparse.bin` the store does not have.
490const MISSING: &str = "missing from the store";
491
492/// The error for a segment's sparse sidecar the store lacks. A segment with
493/// no sparse documents legitimately has none — callers check
494/// [`is_missing`] and treat it as "no sparse data here," not damage.
495pub(crate) fn missing(path: &Path) -> ItzmaError {
496    ItzmaError::CorruptSegment {
497        path: path.to_string(),
498        reason: MISSING.into(),
499    }
500}
501
502/// Whether `err` is what [`missing`] builds.
503pub(crate) fn is_missing(err: &ItzmaError) -> bool {
504    matches!(err, ItzmaError::CorruptSegment { reason, .. } if reason == MISSING)
505}
506
507/// Fetch one `sparse.bin` object whole, charging its bytes to `budget`
508/// before they are read. Above `policy`'s `split_above`, the
509/// object is fetched as parallel planner parts instead of one connection.
510pub(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
523/// Decode one segment's data and, if it has one, its sparse sidecar, and
524/// return a layer whose live documents carry their sparse vectors. Row `i`
525/// of `sparse.bin` is `layer.sorted_docs()[i]`, the same order `data.bin`
526/// and `sparse.bin` were both built from (`crate::compaction`).
527///
528/// # Errors
529///
530/// Whatever `segment::decode` or [`decode`] give. A missing `sparse.bin` is
531/// not an error: the segment simply has no sparse documents.
532pub(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
563/// Requests in flight at once when fetching several segments (mirrors
564/// `segment::read_all`'s own constant).
565const FETCH_CONCURRENCY: usize = 16;
566
567/// Fetch and decode the listed segments (each with its sparse sidecar, if it
568/// has one) and overlay them oldest to newest — the sparse-aware sibling of
569/// `segment::read_all`, used by the query engine's unindexed-segment source.
570pub(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    // Owned ids: a closure over `&String` is inferred as higher-ranked,
581    // which then fails "Send is not general enough" (see
582    // `segment::read_all`'s own comment on the same shape of fix).
583    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        // sorted_docs() is ascending by id: "a", "b", "c".
620        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,                            // "a"
632                Some(vec![(1, 0.5), (2, 0.25)]), // "b"
633                Some(vec![(5, 1.0)]),            // "c"
634            ]
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); // must not panic
665        }
666        for i in 0..good.len() {
667            let mut bad = good.to_vec();
668            bad[i] ^= 0xFF;
669            let _ = decode("p", &bad, 2); // must not panic
670        }
671    }
672
673    const NS: &str = "ns";
674    const ID: &str = "00000000000000000001-00000000000000000003";
675
676    /// Rows 0 to `n`, every third without a sparse vector, the others with
677    /// one to four terms.
678    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    /// Every row of a sidecar holding `bytes`, read forward in one range.
767    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            // A flip inside a weight still decodes, to another weight; every
790            // other flip must be an error. Neither may panic.
791            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}