Skip to main content

itzma_core/
segment.rs

1//! Segments: immutable binary snapshots of a layer.
2//!
3//! A segment is one object, `<namespace>/segments/<lo>-<hi>/data.bin`, holding
4//! the net effect of WAL entries `lo` through `hi`. The id carries the range,
5//! so the manifest can be checked for contiguity from the ids alone, and the
6//! bytes are a pure function of the range: any compactor building the same
7//! range produces the same object, which is what lets a rerun or a racing
8//! compactor reuse an existing one.
9//!
10//! Three formats exist, and [`decode`] reads all of them. Version 1 is a flat
11//! run of sections. Version 2 (in the private `v2` module) holds the
12//! same content in blocks with a directory and a Bloom filter at the end, so a
13//! reader can fetch pieces of it. Version 3 (the same module with
14//! `columns` and `zone`) stores a typed namespace's attributes as columns per
15//! block with a zone map beside them. [`encode_with_schema`] writes any of
16//! them as compaction does, and the namespace's `segment_format` level decides
17//! which one compaction writes.
18//!
19//! Ids and tombstones are sorted, strictly ascending, and never overlap.
20//! [`decode`] checks every length against the bytes that remain before
21//! allocating and never panics.
22
23mod 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
56/// The newest segment version this build reads, and the highest level
57/// [`Namespace::upgrade_segment_format`](crate::Namespace::upgrade_segment_format)
58/// accepts. [`decode`] rejects a version above it (and 0) with
59/// [`ItzmaError::UnsupportedFormat`]. A change to an encoding must add a
60/// version, because correctness relies on two builders producing identical
61/// bytes.
62pub const FORMAT_VERSION: u32 = 3;
63
64/// The segment level a namespace created by this build starts at, which can
65/// trail [`FORMAT_VERSION`]: a new version is readable first and written by
66/// default only once it pays off (version 3 is opt-in until its zone
67/// maps are used).
68pub const DEFAULT_FORMAT: u32 = 2;
69
70const MAGIC: [u8; 4] = *b"ITZS";
71/// Magic, version, dim, doc count, tombstone count.
72const FETCH_CONCURRENCY: usize = 16;
73
74/// The id of the segment covering WAL seqs `lo` through `hi`: both numbers
75/// zero-padded to 20 digits, so ids sort in range order.
76///
77/// ```
78/// use itzma_core::segment::segment_id;
79///
80/// assert_eq!(segment_id(1, 10), "00000000000000000001-00000000000000000010");
81/// ```
82pub fn segment_id(lo: u64, hi: u64) -> String {
83    format!("{lo:020}-{hi:020}")
84}
85
86/// Recover `(lo, hi)` from a segment id, or `None` unless the id is exactly
87/// what [`segment_id`] produces and `1 <= lo <= hi`.
88pub 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
94/// Object key of a segment: `<namespace>/segments/<id>/data.bin`. The
95/// directory leaves room for index files beside the data later.
96///
97/// Does not validate `namespace`; that is [`Namespace`](crate::Namespace)'s job.
98pub fn segment_path(namespace: &str, id: &str) -> Path {
99    Path::from(format!("{namespace}/segments/{id}/data.bin"))
100}
101
102/// The file names under one segment's prefix: its data object, its sidecars,
103/// and every derived index object, named or not.
104pub(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
121/// The highest generation of one kind the manifest names for the segment or
122/// any object under its prefix carries, 0 if none.
123pub(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
136/// Key of a segment's generation high-water mark: the highest generation any
137/// derived object of the segment has claimed, in decimal.
138pub(crate) fn generation_mark_path(namespace: &str, id: &str) -> Path {
139    Path::from(format!("{namespace}/segments/{id}/generation"))
140}
141
142/// The mark never holds more than a u32 in decimal.
143const MAX_MARK_BYTES: u64 = 10;
144
145/// Claim the generation a new derived object of the segment takes: one above
146/// `floor` and above the segment's high-water mark, which is raised to it
147/// before the caller writes anything. A generation a reader may still hold is
148/// then never reused, even after `gc` collected the highest object
149/// and a lost manifest stopped naming it. The three index kinds
150/// share the mark, so one kind's numbers can skip.
151///
152/// # Errors
153///
154/// [`ItzmaError::CorruptIndex`] for a mark that is not a decimal u32 (reading
155/// it low could reuse a number), [`ItzmaError::ManifestContention`] after 32
156/// lost races on the mark, and [`ItzmaError::Storage`] for anything else.
157pub(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
189/// The mark and the version to tie a raise to, or `(0, None)` when there is
190/// no mark yet (a segment never indexed, or indexed before the mark existed,
191/// whose objects the listing still covers).
192async 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
221/// Check the manifest invariant on its segment list: every id parses, the
222/// first range starts at 1, each next range starts one past the previous end,
223/// and the last range ends at `folded_through`. An empty list requires
224/// `folded_through == 0`.
225///
226/// # Errors
227///
228/// [`ItzmaError::CorruptManifest`] describing the first violation.
229pub 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
253/// Encode a layer as a segment object of the version a new namespace writes
254/// ([`DEFAULT_FORMAT`]) for vectors of length `dim`. See [`encode_as`].
255pub fn encode(layer: &Layer, dim: usize) -> Result<Bytes> {
256    encode_as(layer, dim, DEFAULT_FORMAT)
257}
258
259/// Encode a layer as a segment object of `version` (1, 2 or 3) for vectors of
260/// length `dim`, with attributes stored as JSON. At version 3 that is the
261/// layout of a free-form namespace; a typed namespace's segments are what
262/// [`encode_with_schema`] writes.
263///
264/// The result depends only on the layer's contents, not on the order things
265/// were inserted. The caller decides whether tombstones belong: a base segment
266/// (range starting at 1) should have had them dropped first.
267///
268/// # Errors
269///
270/// - [`ItzmaError::UnsupportedFormat`] for any other `version`.
271/// - [`ItzmaError::DimensionMismatch`] if any document's vector is not `dim`
272///   long, so a hand-edited WAL cannot produce a corrupt segment.
273/// - [`ItzmaError::Serde`] / [`ItzmaError::CorruptSegment`] if an attribute
274///   cannot be serialized or a field is longer than 4 GiB.
275pub 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
280/// Encode a layer as the segment object `compact` writes at `version` for a
281/// namespace with `schema`: at version 3 a typed namespace's attributes become
282/// columns and zone maps. Versions 1 and 2 ignore the attribute
283/// schema, so this equals [`encode_as`] there.
284///
285/// # Errors
286///
287/// As [`encode_as`], plus [`ItzmaError::CorruptSegment`] at version 3 for a
288/// document whose attributes the schema does not allow, which a strict write
289/// never stores.
290pub 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
295/// [`encode_as`] without joining the chunks, with the segment's `sparse.bin`
296/// beside it (`None` when no document has a sparse vector): what compaction
297/// writes.
298pub(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        // Column and zone blocks a block per chunk, in parallel on a pool
309        // thread, handed to the writer in order.
310        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    // JSON per document, a block per chunk in parallel on a pool thread,
319    // unless the writer takes the values themselves; the chunks
320    // come back in order, so the bytes are the same either way.
321    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/// The vector length as the u32 the formats store, after checking that every
353/// document has that length.
354#[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
379/// The `reason` of the error for a segment the store does not have. Callers
380/// recognise it through [`is_missing`], never by text.
381const MISSING: &str = "missing from the store";
382
383/// The error for a segment the store does not have: one the manifest lists, or
384/// one that was there a moment ago.
385pub(crate) fn missing(path: &Path) -> ItzmaError {
386    ItzmaError::CorruptSegment {
387        path: path.to_string(),
388        reason: MISSING.into(),
389    }
390}
391
392/// Whether `err` is what [`missing`] builds. Garbage collection deletes
393/// segments, so a missing one may only mean the caller read a stale manifest.
394/// Callers reload the manifest before treating it as damage.
395pub(crate) fn is_missing(err: &ItzmaError) -> bool {
396    matches!(err, ItzmaError::CorruptSegment { reason, .. } if reason == MISSING)
397}
398
399/// Decode a segment object (version 2 or 3) for a namespace whose vectors
400/// have length `dim`. `path` is only used to label errors.
401///
402/// # Errors
403///
404/// - [`ItzmaError::UnsupportedFormat`] for a `format_version` other than 2 or 3.
405/// - [`ItzmaError::CorruptSegment`] for anything else wrong with the bytes:
406///   truncation, bad magic, a dimension different from `dim`, counts larger
407///   than the object can hold, ids or tombstones out of order, an id that is
408///   both a document and a tombstone, invalid UTF-8 or JSON, trailing bytes,
409///   and for version 2 a directory, block, offset or Bloom filter that does
410///   not match the content.
411pub 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
422/// Whether two id-sorted lists share an entry. One pass over both.
423fn 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
435/// A cursor over the object's bytes. Every read is bounds-checked and
436/// failures carry the object's key.
437struct 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/// A dense `rows x dim` matrix of `f32`, row-major, one allocation for the
505/// whole thing. `RangedSegment::vectors_of`
506/// returns this instead of `Vec<Vec<f32>>` (one heap allocation per row) so
507/// a rerank walks contiguous memory and the distance kernels see
508/// one slice per row of the same buffer. A scan hands one out per batch.
509#[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    /// Number of rows.
518    pub fn rows(&self) -> usize {
519        self.rows
520    }
521
522    /// Values per row.
523    pub fn dim(&self) -> usize {
524        self.dim
525    }
526
527    /// Every value, row after row.
528    pub fn values(&self) -> &[f32] {
529        &self.values
530    }
531
532    /// Row `i`'s `dim` values.
533    ///
534    /// # Panics
535    ///
536    /// If `i >= self.rows()`.
537    pub fn row(&self, i: usize) -> &[f32] {
538        let start = i * self.dim;
539        &self.values[start..start + self.dim]
540    }
541
542    /// The values, row after row, without a copy.
543    pub fn into_values(self) -> Vec<f32> {
544        self.values
545    }
546}
547
548/// Fetch one segment object whole, charging its bytes to `budget` before
549/// they are read. Above `policy`'s `split_above`, the object is
550/// fetched as parallel planner parts instead of one connection.
551pub(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
564/// Fetch one segment and decode it on `lane`.
565async 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
579/// [`decode`] on `lane`'s compute pool when the object is big enough to be
580/// worth a hand-off.
581pub(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
588/// [`encode_parts`] on `lane`'s compute pool when the layer is big enough to
589/// be worth a hand-off. The layer comes back with the parts, so it
590/// is dropped on the caller's thread, not the pool's.
591pub(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/// What the first bytes of a segment object say, from a 20-byte ranged read.
607#[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
614/// Magic, version, dim, doc count: the part of the header both versions share.
615const PEEK_LEN: u64 = 4 + 4 + 4 + 8;
616
617/// Read the version, dimension and document count of a segment without its
618/// body, charged to `budget`.
619///
620/// # Errors
621///
622/// [`ItzmaError::CorruptSegment`] if the object is missing (see [`is_missing`])
623/// or does not start with a segment header, [`ItzmaError::UnsupportedFormat`]
624/// for a version other than 1 or 2.
625pub(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
651/// Fetch and decode the listed segments, up to 16 requests in flight, and
652/// overlay them oldest to newest into one layer. Each segment is charged to
653/// `budget` before its body is read.
654///
655/// A listed segment that the store does not have is reported as
656/// [`ItzmaError::CorruptSegment`] (see [`is_missing`]). It means damage only
657/// if the manifest is current: garbage collection may have deleted the segment
658/// after the caller loaded an older manifest.
659pub(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    // Owned ids: a closure over `&String` is inferred as higher-ranked, and
669    // rustc then cannot prove the stream `Send`, so `Namespace::query` and
670    // `compact` could not be moved into `tokio::spawn`.
671    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
681/// Fetch a segment whole and decode it as a view, on `lane`'s pool.
682async 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    // Weighed by what it holds, which is not the object's size.
696    let weight = view.weight();
697    Ok((std::sync::Arc::new(view), weight))
698}
699
700/// The segments `ids` of `namespace`, in order, for a flat scan, through
701/// `decoded` when the handle has one.
702///
703/// # Errors
704///
705/// [`missing`] for a segment that is gone, [`ItzmaError::CorruptSegment`],
706/// and [`ItzmaError::ReadBudgetExceeded`] for a miss over the budget.
707#[allow(clippy::too_many_arguments)] // the handle's read settings
708pub(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    // Owned ids: a closure over `&String` is inferred as higher-ranked, and
719    // rustc then cannot prove the stream `Send` (see `read_all_uncached`).
720    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        // The same object labelled version 1, which this build does not read.
772        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    /// `n` documents of `dim` values, every third with attributes, and ten
802    /// tombstones: past the compute pool's inline threshold at `n = 20_000`.
803    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    /// A version 2 object, the format the tests below decode.
900    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        // 4: the first version this build does not read.
972        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"), // gap
1078            (ids(&[(1, 3), (3, 4)]), 4, "starts at 3"), // overlap
1079            (ids(&[(2, 3)]), 3, "starts at 2"),         // does not begin at 1
1080            (ids(&[(1, 3)]), 4, "folded"),              // last hi differs from folded
1081            (vec![], 5, "folded"),                      // folded with no segments
1082            (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}