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 attr_rows::Stored;
32pub(crate) use columns::{Column, ColumnBlock, Field, Values};
33#[cfg(test)]
34pub(crate) use columns::{Texts, fields_of};
35pub(crate) use ranged::{DocWindow, Held, RangedSegment, WindowAttrs};
36pub(crate) use v2::BLOCK_ROWS;
37pub(crate) use view::SegmentView;
38pub(crate) use writer::{AttrIn, Chunks, SegmentWriter, attr_json, encode_attr_block};
39pub(crate) use zone::{TextZone, ZoneEntry, ZoneStats};
40#[cfg(test)]
41pub(crate) use zone::{decode_zone, encode_zone};
42
43use bytes::Bytes;
44use futures::stream::{self, StreamExt, TryStreamExt};
45use object_store::path::Path;
46use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions, PutPayload, UpdateVersion};
47
48use crate::attrs::AttrSchema;
49use crate::budget::ReadBudget;
50use crate::cpu::{self, Cost, Lane};
51use crate::decoded::{DecodedRef, What};
52use crate::document::{Document, Schema};
53use crate::error::{ItzmaError, Result};
54use crate::fetch::FetchPolicy;
55use crate::layer::Layer;
56
57/// The newest segment version this build reads, and the highest level
58/// [`Namespace::upgrade_segment_format`](crate::Namespace::upgrade_segment_format)
59/// accepts. [`decode`] rejects a version above it (and 0) with
60/// [`ItzmaError::UnsupportedFormat`]. A change to an encoding must add a
61/// version, because correctness relies on two builders producing identical
62/// bytes.
63pub const FORMAT_VERSION: u32 = 3;
64
65/// The segment level a namespace created by this build starts at, which can
66/// trail [`FORMAT_VERSION`]: a new version is readable first and written by
67/// default only once it pays off (version 3 is opt-in until its zone
68/// maps are used).
69pub const DEFAULT_FORMAT: u32 = 2;
70
71const MAGIC: [u8; 4] = *b"ITZS";
72/// Magic, version, dim, doc count, tombstone count.
73const FETCH_CONCURRENCY: usize = 16;
74
75/// The id of the segment covering WAL seqs `lo` through `hi`: both numbers
76/// zero-padded to 20 digits, so ids sort in range order.
77///
78/// ```
79/// use itzma_core::segment::segment_id;
80///
81/// assert_eq!(segment_id(1, 10), "00000000000000000001-00000000000000000010");
82/// ```
83pub fn segment_id(lo: u64, hi: u64) -> String {
84    format!("{lo:020}-{hi:020}")
85}
86
87/// Recover `(lo, hi)` from a segment id, or `None` unless the id is exactly
88/// what [`segment_id`] produces and `1 <= lo <= hi`.
89pub fn parse_segment_id(id: &str) -> Option<(u64, u64)> {
90    let (lo, hi) = id.split_once('-')?;
91    let (lo, hi) = (lo.parse::<u64>().ok()?, hi.parse::<u64>().ok()?);
92    ((1..=hi).contains(&lo) && segment_id(lo, hi) == id).then_some((lo, hi))
93}
94
95/// Object key of a segment: `<namespace>/segments/<id>/data.bin`. The
96/// directory leaves room for index files beside the data later.
97///
98/// Does not validate `namespace`; that is [`Namespace`](crate::Namespace)'s job.
99pub fn segment_path(namespace: &str, id: &str) -> Path {
100    Path::from(format!("{namespace}/segments/{id}/data.bin"))
101}
102
103/// The file names under one segment's prefix: its data object, its sidecars,
104/// and every derived index object, named or not.
105pub(crate) async fn object_names(
106    store: &dyn ObjectStore,
107    namespace: &str,
108    id: &str,
109) -> Result<Vec<String>> {
110    let prefix = Path::from(format!("{namespace}/segments/{id}"));
111    let metas: Vec<_> = store
112        .list(Some(&prefix))
113        .try_collect()
114        .await
115        .map_err(ItzmaError::from)?;
116    Ok(metas
117        .iter()
118        .filter_map(|meta| meta.location.filename().map(str::to_string))
119        .collect())
120}
121
122/// The highest generation of one kind the manifest names for the segment or
123/// any object under its prefix carries, 0 if none.
124pub(crate) fn generation_floor(
125    named: Option<u32>,
126    names: &[String],
127    generation_of: fn(&str) -> Option<u32>,
128) -> u32 {
129    names
130        .iter()
131        .filter_map(|name| generation_of(name))
132        .chain(named)
133        .max()
134        .unwrap_or(0)
135}
136
137/// Key of a segment's generation high-water mark: the highest generation any
138/// derived object of the segment has claimed, in decimal.
139pub(crate) fn generation_mark_path(namespace: &str, id: &str) -> Path {
140    Path::from(format!("{namespace}/segments/{id}/generation"))
141}
142
143/// The mark never holds more than a u32 in decimal.
144const MAX_MARK_BYTES: u64 = 10;
145
146/// Claim the generation a new derived object of the segment takes: one above
147/// `floor` and above the segment's high-water mark, which is raised to it
148/// before the caller writes anything. A generation a reader may still hold is
149/// then never reused, even after `gc` collected the highest object
150/// and a lost manifest stopped naming it. The three index kinds
151/// share the mark, so one kind's numbers can skip.
152///
153/// # Errors
154///
155/// [`ItzmaError::CorruptIndex`] for a mark that is not a decimal u32 (reading
156/// it low could reuse a number), [`ItzmaError::ManifestContention`] after 32
157/// lost races on the mark, and [`ItzmaError::Storage`] for anything else.
158pub(crate) async fn claim_generation(
159    store: &dyn ObjectStore,
160    namespace: &str,
161    id: &str,
162    floor: u32,
163) -> Result<u32> {
164    let path = generation_mark_path(namespace, id);
165    for _ in 0..crate::manifest::MAX_UPDATE_ATTEMPTS {
166        let (mark, version) = read_generation_mark(store, &path).await?;
167        let generation = floor.max(mark).saturating_add(1);
168        let mode = match version {
169            Some(version) => PutMode::Update(version),
170            None => PutMode::Create,
171        };
172        let body = Bytes::from(generation.to_string());
173        match store
174            .put_opts(&path, body.into(), PutOptions::from(mode))
175            .await
176        {
177            Ok(_) => return Ok(generation),
178            Err(
179                object_store::Error::Precondition { .. }
180                | object_store::Error::AlreadyExists { .. },
181            ) => continue,
182            Err(e) => return Err(e.into()),
183        }
184    }
185    Err(ItzmaError::ManifestContention {
186        attempts: crate::manifest::MAX_UPDATE_ATTEMPTS,
187    })
188}
189
190/// The mark and the version to tie a raise to, or `(0, None)` when there is
191/// no mark yet (a segment never indexed, or indexed before the mark existed,
192/// whose objects the listing still covers).
193async fn read_generation_mark(
194    store: &dyn ObjectStore,
195    path: &Path,
196) -> Result<(u32, Option<UpdateVersion>)> {
197    let result = match store.get(path).await {
198        Ok(result) => result,
199        Err(object_store::Error::NotFound { .. }) => return Ok((0, None)),
200        Err(e) => return Err(e.into()),
201    };
202    let corrupt = |reason: &str| ItzmaError::CorruptIndex {
203        path: path.to_string(),
204        reason: format!("generation mark {reason}"),
205    };
206    if result.meta.size > MAX_MARK_BYTES {
207        return Err(corrupt("is too long"));
208    }
209    let version = UpdateVersion {
210        e_tag: result.meta.e_tag.clone(),
211        version: result.meta.version.clone(),
212    };
213    let bytes = result.bytes().await?;
214    let mark = std::str::from_utf8(&bytes)
215        .ok()
216        .filter(|text| text.bytes().all(|b| b.is_ascii_digit()))
217        .and_then(|text| text.parse::<u32>().ok())
218        .ok_or_else(|| corrupt("is not a decimal number"))?;
219    Ok((mark, Some(version)))
220}
221
222/// Check the manifest invariant on its segment list: every id parses, the
223/// first range starts at 1, each next range starts one past the previous end,
224/// and the last range ends at `folded_through`. An empty list requires
225/// `folded_through == 0`.
226///
227/// # Errors
228///
229/// [`ItzmaError::CorruptManifest`] describing the first violation.
230pub fn validate_chain(ids: &[String], folded_through: u64) -> Result<()> {
231    let corrupt = |reason: String| ItzmaError::CorruptManifest(reason);
232    let mut next_lo = 1u64;
233    for id in ids {
234        let (lo, hi) = parse_segment_id(id)
235            .ok_or_else(|| corrupt(format!("segment id {id:?} is malformed")))?;
236        if lo != next_lo {
237            return Err(corrupt(format!(
238                "segment {id} starts at {lo}, expected {next_lo}"
239            )));
240        }
241        next_lo = hi
242            .checked_add(1)
243            .ok_or_else(|| corrupt(format!("segment {id} ends at the largest seq")))?;
244    }
245    let covered = next_lo - 1;
246    if covered != folded_through {
247        return Err(corrupt(format!(
248            "segments cover through {covered} but wal_folded_through is {folded_through}"
249        )));
250    }
251    Ok(())
252}
253
254/// Encode a layer as a segment object of the version a new namespace writes
255/// ([`DEFAULT_FORMAT`]) for vectors of length `dim`. See [`encode_as`].
256pub fn encode(layer: &Layer, dim: usize) -> Result<Bytes> {
257    encode_as(layer, dim, DEFAULT_FORMAT)
258}
259
260/// Encode a layer as a segment object of `version` (1, 2 or 3) for vectors of
261/// length `dim`, with attributes stored as JSON. At version 3 that is the
262/// layout of a free-form namespace; a typed namespace's segments are what
263/// [`encode_with_schema`] writes.
264///
265/// The result depends only on the layer's contents, not on the order things
266/// were inserted. The caller decides whether tombstones belong: a base segment
267/// (range starting at 1) should have had them dropped first.
268///
269/// # Errors
270///
271/// - [`ItzmaError::UnsupportedFormat`] for any other `version`.
272/// - [`ItzmaError::DimensionMismatch`] if any document's vector is not `dim`
273///   long, so a hand-edited WAL cannot produce a corrupt segment.
274/// - [`ItzmaError::Serde`] / [`ItzmaError::CorruptSegment`] if an attribute
275///   cannot be serialized or a field is longer than 4 GiB.
276pub fn encode_as(layer: &Layer, dim: usize, version: u32) -> Result<Bytes> {
277    let (data, _) = encode_parts(layer, dim, version, &AttrSchema::free_form())?;
278    Ok(data.into())
279}
280
281/// Encode a layer as the segment object `compact` writes at `version` for a
282/// namespace with `schema`: at version 3 a typed namespace's attributes become
283/// columns and zone maps. Versions 1 and 2 ignore the attribute
284/// schema, so this equals [`encode_as`] there.
285///
286/// # Errors
287///
288/// As [`encode_as`], plus [`ItzmaError::CorruptSegment`] at version 3 for a
289/// document whose attributes the schema does not allow, which a strict write
290/// never stores.
291pub fn encode_with_schema(layer: &Layer, schema: &Schema, version: u32) -> Result<Bytes> {
292    let (data, _) = encode_parts(layer, schema.dim, version, &schema.attrs)?;
293    Ok(data.into())
294}
295
296/// [`encode_as`] without joining the chunks, with the segment's `sparse.bin`
297/// beside it (`None` when no document has a sparse vector): what compaction
298/// writes.
299pub(crate) fn encode_parts(
300    layer: &Layer,
301    dim: usize,
302    version: u32,
303    attrs: &AttrSchema,
304) -> Result<(PutPayload, Option<PutPayload>)> {
305    let mut writer = SegmentWriter::new(dim, version, attrs)?;
306    let docs = layer.sorted_docs();
307    let columnar = version >= 3 && !attrs.is_free_form();
308    if columnar {
309        // Column and zone blocks a block per chunk, in parallel on a pool
310        // thread, handed to the writer in order.
311        let fields = columns::fields_of(attrs);
312        let blocks = cpu::chunked(&docs, v2::BLOCK_ROWS, |chunk| {
313            let rows: Vec<Option<&serde_json::Value>> =
314                chunk.iter().map(|doc| doc.attrs.as_ref()).collect();
315            encode_attr_block(&fields, &rows)
316        });
317        writer.attr_blocks(blocks.into_iter().collect::<Result<_>>()?)?;
318    }
319    // JSON per document, a block per chunk in parallel on a pool thread,
320    // unless the writer takes the values themselves; the chunks
321    // come back in order, so the bytes are the same either way.
322    let mut json: Vec<Vec<u8>> = Vec::new();
323    if !columnar {
324        json.reserve(docs.len());
325        for chunk in cpu::chunked(&docs, v2::BLOCK_ROWS, |chunk| {
326            chunk
327                .iter()
328                .map(|doc| attr_json(doc.attrs.as_ref()))
329                .collect::<Result<Vec<_>>>()
330        }) {
331            json.extend(chunk?);
332        }
333    }
334    let tombstones = layer.sorted_tombstones();
335    let mut dead = tombstones.iter().peekable();
336    for (i, doc) in docs.iter().enumerate() {
337        while let Some(id) = dead.next_if(|id| **id < doc.id.as_str()) {
338            writer.tombstone(id)?;
339        }
340        let attrs = if columnar {
341            AttrIn::Encoded
342        } else {
343            AttrIn::Json(&json[i])
344        };
345        writer.doc(&doc.id, &doc.vector, attrs, doc.sparse.as_ref())?;
346    }
347    for id in dead {
348        writer.tombstone(id)?;
349    }
350    writer.finish()
351}
352
353/// The vector length as the u32 the formats store, after checking that every
354/// document has that length.
355#[cfg(test)]
356fn check_dim(docs: &[&Document], dim: usize) -> Result<u32> {
357    if let Some(bad) = docs.iter().find(|d| d.vector.len() != dim) {
358        return Err(ItzmaError::DimensionMismatch {
359            expected: dim,
360            got: bad.vector.len(),
361        });
362    }
363    u32::try_from(dim).map_err(|_| too_long())
364}
365
366fn put_bytes(buf: &mut Vec<u8>, bytes: &[u8]) -> Result<()> {
367    let len = u32::try_from(bytes.len()).map_err(|_| too_long())?;
368    buf.extend_from_slice(&len.to_le_bytes());
369    buf.extend_from_slice(bytes);
370    Ok(())
371}
372
373fn too_long() -> ItzmaError {
374    ItzmaError::CorruptSegment {
375        path: "(encoding)".into(),
376        reason: "a field is longer than 4 GiB".into(),
377    }
378}
379
380/// The `reason` of the error for a segment the store does not have. Callers
381/// recognise it through [`is_missing`], never by text.
382const MISSING: &str = "missing from the store";
383
384/// The error for a segment the store does not have: one the manifest lists, or
385/// one that was there a moment ago.
386pub(crate) fn missing(path: &Path) -> ItzmaError {
387    ItzmaError::CorruptSegment {
388        path: path.to_string(),
389        reason: MISSING.into(),
390    }
391}
392
393/// Whether `err` is what [`missing`] builds. Garbage collection deletes
394/// segments, so a missing one may only mean the caller read a stale manifest.
395/// Callers reload the manifest before treating it as damage.
396pub(crate) fn is_missing(err: &ItzmaError) -> bool {
397    matches!(err, ItzmaError::CorruptSegment { reason, .. } if reason == MISSING)
398}
399
400/// Decode a segment object (version 2 or 3) for a namespace whose vectors
401/// have length `dim`. `path` is only used to label errors.
402///
403/// # Errors
404///
405/// - [`ItzmaError::UnsupportedFormat`] for a `format_version` other than 2 or 3.
406/// - [`ItzmaError::CorruptSegment`] for anything else wrong with the bytes:
407///   truncation, bad magic, a dimension different from `dim`, counts larger
408///   than the object can hold, ids or tombstones out of order, an id that is
409///   both a document and a tombstone, invalid UTF-8 or JSON, trailing bytes,
410///   and for version 2 a directory, block, offset or Bloom filter that does
411///   not match the content.
412pub fn decode(path: &str, bytes: &[u8], dim: usize) -> Result<Layer> {
413    let mut r = Reader::new(path, bytes);
414    if r.take(4)? != MAGIC {
415        return Err(r.corrupt("bad magic"));
416    }
417    match r.u32()? {
418        version @ (2 | 3) => v2::decode(r, version, dim),
419        version => Err(ItzmaError::UnsupportedFormat { version }),
420    }
421}
422
423/// Whether two id-sorted lists share an entry. One pass over both.
424fn overlaps(docs: &[Document], tombstones: &[String]) -> bool {
425    let (mut i, mut j) = (0, 0);
426    while i < docs.len() && j < tombstones.len() {
427        match docs[i].id.cmp(&tombstones[j]) {
428            std::cmp::Ordering::Less => i += 1,
429            std::cmp::Ordering::Greater => j += 1,
430            std::cmp::Ordering::Equal => return true,
431        }
432    }
433    false
434}
435
436/// A cursor over the object's bytes. Every read is bounds-checked and
437/// failures carry the object's key.
438struct Reader<'a> {
439    path: &'a str,
440    buf: &'a [u8],
441    pos: usize,
442}
443
444impl<'a> Reader<'a> {
445    fn new(path: &'a str, buf: &'a [u8]) -> Self {
446        Reader { path, buf, pos: 0 }
447    }
448
449    fn corrupt(&self, reason: impl Into<String>) -> ItzmaError {
450        ItzmaError::CorruptSegment {
451            path: self.path.to_string(),
452            reason: reason.into(),
453        }
454    }
455
456    fn remaining(&self) -> usize {
457        self.buf.len().saturating_sub(self.pos)
458    }
459
460    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
461        let out = self
462            .buf
463            .get(self.pos..)
464            .and_then(|rest| rest.get(..n))
465            .ok_or_else(|| self.corrupt("object is truncated"))?;
466        self.pos += n;
467        Ok(out)
468    }
469
470    fn array<const N: usize>(&mut self) -> Result<[u8; N]> {
471        let bytes = self.take(N)?;
472        <[u8; N]>::try_from(bytes).map_err(|_| self.corrupt("object is truncated"))
473    }
474
475    fn u8(&mut self) -> Result<u8> {
476        let [byte] = self.array::<1>()?;
477        Ok(byte)
478    }
479
480    fn u16(&mut self) -> Result<u16> {
481        Ok(u16::from_le_bytes(self.array()?))
482    }
483
484    fn u32(&mut self) -> Result<u32> {
485        Ok(u32::from_le_bytes(self.array()?))
486    }
487
488    fn u64(&mut self) -> Result<u64> {
489        Ok(u64::from_le_bytes(self.array()?))
490    }
491
492    fn f64(&mut self) -> Result<f64> {
493        Ok(f64::from_le_bytes(self.array()?))
494    }
495
496    fn string(&mut self, what: &str) -> Result<String> {
497        let len = self.u32()? as usize;
498        let raw = self.take(len)?;
499        std::str::from_utf8(raw)
500            .map(str::to_owned)
501            .map_err(|_| self.corrupt(format!("{what} is not valid UTF-8")))
502    }
503}
504
505/// A dense `rows x dim` matrix of `f32`, row-major, one allocation for the
506/// whole thing. `RangedSegment::vectors_of`
507/// returns this instead of `Vec<Vec<f32>>` (one heap allocation per row) so
508/// a rerank walks contiguous memory and the distance kernels see
509/// one slice per row of the same buffer. A scan hands one out per batch.
510#[derive(Debug, Clone, PartialEq)]
511pub struct Matrix {
512    pub(crate) rows: usize,
513    pub(crate) dim: usize,
514    pub(crate) values: Vec<f32>,
515}
516
517impl Matrix {
518    /// Number of rows.
519    pub fn rows(&self) -> usize {
520        self.rows
521    }
522
523    /// Values per row.
524    pub fn dim(&self) -> usize {
525        self.dim
526    }
527
528    /// Every value, row after row.
529    pub fn values(&self) -> &[f32] {
530        &self.values
531    }
532
533    /// Row `i`'s `dim` values.
534    ///
535    /// # Panics
536    ///
537    /// If `i >= self.rows()`.
538    pub fn row(&self, i: usize) -> &[f32] {
539        let start = i * self.dim;
540        &self.values[start..start + self.dim]
541    }
542
543    /// The values, row after row, without a copy.
544    pub fn into_values(self) -> Vec<f32> {
545        self.values
546    }
547}
548
549/// Fetch one segment object whole, charging its bytes to `budget` before
550/// they are read. Above `policy`'s `split_above`, the object is
551/// fetched as parallel planner parts instead of one connection.
552pub(crate) async fn fetch_bytes(
553    store: &dyn ObjectStore,
554    path: &Path,
555    budget: &ReadBudget,
556    policy: &FetchPolicy,
557) -> Result<Bytes> {
558    match crate::fetch::whole_object(store, budget, policy, path).await {
559        Ok(bytes) => Ok(bytes),
560        Err(ItzmaError::Storage(object_store::Error::NotFound { .. })) => Err(missing(path)),
561        Err(e) => Err(e),
562    }
563}
564
565/// Fetch one segment and decode it on `lane`.
566async fn fetch(
567    store: &dyn ObjectStore,
568    namespace: &str,
569    id: &str,
570    dim: usize,
571    budget: &ReadBudget,
572    policy: &FetchPolicy,
573    lane: Lane,
574) -> Result<Layer> {
575    let path = segment_path(namespace, id);
576    let bytes = fetch_bytes(store, &path, budget, policy).await?;
577    decode_on(lane, path, bytes, dim).await
578}
579
580/// [`decode`] on `lane`'s compute pool when the object is big enough to be
581/// worth a hand-off.
582pub(crate) async fn decode_on(lane: Lane, path: Path, bytes: Bytes, dim: usize) -> Result<Layer> {
583    cpu::run(lane, Cost::Bytes(bytes.len()), move || {
584        decode(path.as_ref(), &bytes, dim)
585    })
586    .await
587}
588
589/// [`encode_parts`] on `lane`'s compute pool when the layer is big enough to
590/// be worth a hand-off. The layer comes back with the parts, so it
591/// is dropped on the caller's thread, not the pool's.
592pub(crate) async fn encode_parts_on(
593    lane: Lane,
594    layer: Layer,
595    dim: usize,
596    version: u32,
597    attrs: AttrSchema,
598) -> Result<(Layer, PutPayload, Option<PutPayload>)> {
599    let cost = Cost::Bytes(layer.doc_count().saturating_mul(dim * 4 + 64));
600    cpu::run(lane, cost, move || {
601        let (data, sparse) = encode_parts(&layer, dim, version, &attrs)?;
602        Ok((layer, data, sparse))
603    })
604    .await
605}
606
607/// What the first bytes of a segment object say, from a 20-byte ranged read.
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub(crate) struct Peek {
610    pub(crate) version: u32,
611    pub(crate) dim: u32,
612    pub(crate) doc_count: u64,
613}
614
615/// Magic, version, dim, doc count: the part of the header both versions share.
616const PEEK_LEN: u64 = 4 + 4 + 4 + 8;
617
618/// Read the version, dimension and document count of a segment without its
619/// body, charged to `budget`.
620///
621/// # Errors
622///
623/// [`ItzmaError::CorruptSegment`] if the object is missing (see [`is_missing`])
624/// or does not start with a segment header, [`ItzmaError::UnsupportedFormat`]
625/// for a version other than 1 or 2.
626pub(crate) async fn peek(
627    store: &dyn ObjectStore,
628    path: &Path,
629    budget: &ReadBudget,
630) -> Result<Peek> {
631    budget.charge(path.as_ref(), PEEK_LEN)?;
632    let bytes = match store.get_range(path, 0..PEEK_LEN).await {
633        Ok(bytes) => bytes,
634        Err(object_store::Error::NotFound { .. }) => return Err(missing(path)),
635        Err(e) => return Err(e.into()),
636    };
637    let mut r = Reader::new(path.as_ref(), &bytes);
638    if r.take(4)? != MAGIC {
639        return Err(r.corrupt("bad magic"));
640    }
641    let version = r.u32()?;
642    if !(2..=FORMAT_VERSION).contains(&version) {
643        return Err(ItzmaError::UnsupportedFormat { version });
644    }
645    Ok(Peek {
646        version,
647        dim: r.u32()?,
648        doc_count: r.u64()?,
649    })
650}
651
652/// Fetch and decode the listed segments, up to 16 requests in flight, and
653/// overlay them oldest to newest into one layer. Each segment is charged to
654/// `budget` before its body is read.
655///
656/// A listed segment that the store does not have is reported as
657/// [`ItzmaError::CorruptSegment`] (see [`is_missing`]). It means damage only
658/// if the manifest is current: garbage collection may have deleted the segment
659/// after the caller loaded an older manifest.
660pub(crate) async fn read_all(
661    store: &dyn ObjectStore,
662    namespace: &str,
663    ids: &[String],
664    dim: usize,
665    budget: &ReadBudget,
666    policy: &FetchPolicy,
667    lane: Lane,
668) -> Result<Layer> {
669    // Owned ids: a closure over `&String` is inferred as higher-ranked, and
670    // rustc then cannot prove the stream `Send`, so `Namespace::query` and
671    // `compact` could not be moved into `tokio::spawn`.
672    stream::iter(ids.iter().cloned())
673        .map(|id| async move { fetch(store, namespace, &id, dim, budget, policy, lane).await })
674        .buffered(FETCH_CONCURRENCY)
675        .try_fold(Layer::new(), |mut acc, segment| async move {
676            acc.overlay(segment);
677            Ok::<_, ItzmaError>(acc)
678        })
679        .await
680}
681
682/// Fetch a segment whole and decode it as a view, on `lane`'s pool.
683async fn load_flat(
684    store: &dyn ObjectStore,
685    path: Path,
686    dim: usize,
687    budget: &ReadBudget,
688    policy: &FetchPolicy,
689    lane: Lane,
690) -> Result<(std::sync::Arc<SegmentView>, u64)> {
691    let bytes = fetch_bytes(store, &path, budget, policy).await?;
692    let view = cpu::run(lane, Cost::Bytes(bytes.len()), move || {
693        SegmentView::decode(path.as_ref(), bytes, dim)
694    })
695    .await?;
696    // Weighed by what it holds, which is not the object's size.
697    let weight = view.weight();
698    Ok((std::sync::Arc::new(view), weight))
699}
700
701/// The segments `ids` of `namespace`, in order, for a flat scan, through
702/// `decoded` when the handle has one.
703///
704/// # Errors
705///
706/// [`missing`] for a segment that is gone, [`ItzmaError::CorruptSegment`],
707/// and [`ItzmaError::ReadBudgetExceeded`] for a miss over the budget.
708#[allow(clippy::too_many_arguments)] // the handle's read settings
709pub(crate) async fn read_flat(
710    store: &dyn ObjectStore,
711    namespace: &str,
712    ids: &[String],
713    dim: usize,
714    budget: &ReadBudget,
715    policy: &FetchPolicy,
716    lane: Lane,
717    decoded: Option<&DecodedRef>,
718) -> Result<Vec<std::sync::Arc<SegmentView>>> {
719    // Owned ids: a closure over `&String` is inferred as higher-ranked, and
720    // rustc then cannot prove the stream `Send` (see `read_all_uncached`).
721    stream::iter(ids.iter().cloned())
722        .map(|id| async move {
723            let path = segment_path(namespace, &id);
724            let Some(decoded) = decoded else {
725                return Ok(load_flat(store, path, dim, budget, policy, lane).await?.0);
726            };
727            let view = decoded
728                .get_or_load(&path, What::View, || {
729                    load_flat(store, path.clone(), dim, budget, policy, lane)
730                })
731                .await?;
732            Ok(std::sync::Arc::clone(&*view))
733        })
734        .buffered(FETCH_CONCURRENCY)
735        .try_collect()
736        .await
737}
738
739#[cfg(test)]
740mod tests {
741    use super::*;
742    use crate::cpu::Lane;
743    use crate::document::{Document, WalOp};
744    use crate::error::ItzmaError;
745
746    #[tokio::test]
747    async fn read_flat_gives_views_and_refuses_version_1() {
748        let store = object_store::memory::InMemory::new();
749        let mut layer = Layer::new();
750        for i in 0..3 {
751            layer.apply(WalOp::Upsert(Document {
752                id: format!("d{i}"),
753                vector: vec![i as f32; 2],
754                attrs: None,
755                sparse: None,
756            }));
757        }
758        let ids = [segment_id(1, 1)];
759        let bytes = encode_as(&layer, 2, 2).unwrap();
760        store
761            .put(&segment_path("ns", &ids[0]), bytes.clone().into())
762            .await
763            .unwrap();
764        let budget = ReadBudget::new(1 << 20);
765        let policy = FetchPolicy::local();
766        let got = read_flat(&store, "ns", &ids, 2, &budget, &policy, Lane::Query, None)
767            .await
768            .unwrap();
769        assert_eq!(got[0].rows(), 3);
770        assert_eq!(got[0].vector(2), &[2.0, 2.0]);
771
772        // The same object labelled version 1, which this build does not read.
773        let mut v1 = bytes.to_vec();
774        v1[4..8].copy_from_slice(&1u32.to_le_bytes());
775        store
776            .put(&segment_path("ns", &ids[0]), v1.into())
777            .await
778            .unwrap();
779        let err = read_flat(&store, "ns", &ids, 2, &budget, &policy, Lane::Query, None)
780            .await
781            .err()
782            .unwrap();
783        assert!(
784            matches!(err, ItzmaError::UnsupportedFormat { version: 1 }),
785            "{err:?}"
786        );
787    }
788
789    #[tokio::test]
790    async fn a_missing_segment_is_missing_for_read_flat() {
791        let store = object_store::memory::InMemory::new();
792        let budget = ReadBudget::new(1 << 20);
793        let policy = FetchPolicy::local();
794        let ids = [segment_id(1, 1)];
795        let err = read_flat(&store, "ns", &ids, 2, &budget, &policy, Lane::Query, None)
796            .await
797            .err()
798            .unwrap();
799        assert!(is_missing(&err), "{err:?}");
800    }
801
802    /// `n` documents of `dim` values, every third with attributes, and ten
803    /// tombstones: past the compute pool's inline threshold at `n = 20_000`.
804    fn big_layer(n: usize, dim: usize) -> Layer {
805        let mut layer = Layer::new();
806        for i in 0..n {
807            layer.apply(WalOp::Upsert(Document {
808                id: format!("d{i:06}"),
809                vector: (0..dim).map(|d| ((i * 31 + d * 7) % 101) as f32).collect(),
810                attrs: (i % 3 == 0).then(|| serde_json::json!({ "n": i, "tag": "x" })),
811                sparse: None,
812            }));
813        }
814        for i in 0..10 {
815            layer.apply(WalOp::Delete(format!("gone{i}")));
816        }
817        layer
818    }
819
820    #[tokio::test]
821    async fn decode_on_a_lane_equals_decode() {
822        let layer = big_layer(20_000, 32);
823        for version in [2, 3] {
824            let bytes = encode_as(&layer, 32, version).unwrap();
825            let direct = decode("p", &bytes, 32).unwrap();
826            let pooled = decode_on(Lane::Query, Path::from("p"), bytes, 32)
827                .await
828                .unwrap();
829            assert_eq!(pooled, direct, "version {version}");
830        }
831    }
832
833    #[tokio::test]
834    async fn encode_on_a_lane_gives_the_same_bytes_and_the_layer_back() {
835        let layer = big_layer(20_000, 32);
836        for version in [2, 3] {
837            let direct = encode_as(&layer, 32, version).unwrap();
838            let (back, data, sparse) = encode_parts_on(
839                Lane::Maintenance,
840                layer.clone(),
841                32,
842                version,
843                AttrSchema::free_form(),
844            )
845            .await
846            .unwrap();
847            assert_eq!(Bytes::from(data), direct, "version {version}");
848            assert!(sparse.is_none());
849            assert_eq!(back, layer);
850        }
851    }
852
853    #[test]
854    fn matrix_row_slices_out_the_right_values_in_order() {
855        let m = Matrix {
856            rows: 3,
857            dim: 2,
858            values: vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
859        };
860        assert_eq!(m.row(0), &[1.0, 2.0]);
861        assert_eq!(m.row(1), &[3.0, 4.0]);
862        assert_eq!(m.row(2), &[5.0, 6.0]);
863    }
864
865    fn up(id: &str, v: &[f32], attrs: Option<serde_json::Value>) -> WalOp {
866        WalOp::Upsert(Document {
867            id: id.into(),
868            vector: v.to_vec(),
869            attrs,
870            sparse: None,
871        })
872    }
873
874    fn layer(ops: Vec<WalOp>) -> Layer {
875        let mut l = Layer::new();
876        for op in ops {
877            l.apply(op);
878        }
879        l
880    }
881
882    fn sample() -> Layer {
883        layer(vec![
884            up(
885                "b",
886                &[1.0, 2.0],
887                Some(serde_json::json!({"k": [1, 2], "s": "x"})),
888            ),
889            up("a", &[-0.5, 0.25], None),
890            up(
891                "ü-日本",
892                &[3.0, 4.0],
893                Some(serde_json::json!("plain string")),
894            ),
895            WalOp::Delete("y".into()),
896            WalOp::Delete("x".into()),
897        ])
898    }
899
900    /// A version 2 object, the format the tests below decode.
901    fn v2(layer: &Layer, dim: usize) -> Result<Bytes> {
902        encode_as(layer, dim, 2)
903    }
904
905    fn corrupt(err: ItzmaError) -> String {
906        match err {
907            ItzmaError::CorruptSegment { reason, .. } => reason,
908            other => panic!("expected CorruptSegment, got {other:?}"),
909        }
910    }
911
912    #[test]
913    fn roundtrip_preserves_docs_attrs_and_tombstones() {
914        let original = sample();
915        let bytes = v2(&original, 2).unwrap();
916        assert_eq!(decode("p", &bytes, 2).unwrap(), original);
917    }
918
919    #[test]
920    fn json_null_attrs_survive_the_roundtrip() {
921        let original = layer(vec![up("a", &[1.0], Some(serde_json::Value::Null))]);
922        let bytes = v2(&original, 1).unwrap();
923        let back = decode("p", &bytes, 1).unwrap();
924        assert_eq!(back.sorted_docs()[0].attrs, Some(serde_json::Value::Null));
925    }
926
927    #[test]
928    fn bytes_do_not_depend_on_insertion_order() {
929        let one = layer(vec![
930            up("a", &[1.0], None),
931            up("b", &[2.0], None),
932            WalOp::Delete("z".into()),
933        ]);
934        let two = layer(vec![
935            WalOp::Delete("z".into()),
936            up("b", &[2.0], None),
937            up("a", &[1.0], None),
938        ]);
939        assert_eq!(v2(&one, 1).unwrap(), v2(&two, 1).unwrap());
940    }
941
942    #[test]
943    fn encode_rejects_a_vector_of_the_wrong_length() {
944        let l = layer(vec![up("a", &[1.0, 2.0, 3.0], None)]);
945        let err = v2(&l, 2).unwrap_err();
946        assert!(matches!(
947            err,
948            ItzmaError::DimensionMismatch {
949                expected: 2,
950                got: 3
951            }
952        ));
953    }
954
955    #[test]
956    fn every_truncation_is_an_error_and_none_panics() {
957        let bytes = v2(&sample(), 2).unwrap();
958        for cut in 0..bytes.len() {
959            assert!(decode("p", &bytes[..cut], 2).is_err(), "cut at {cut}");
960        }
961    }
962
963    #[test]
964    fn decode_rejects_bad_magic() {
965        let mut bytes = v2(&sample(), 2).unwrap().to_vec();
966        bytes[0] = b'X';
967        assert!(corrupt(decode("p", &bytes, 2).unwrap_err()).contains("magic"));
968    }
969
970    #[test]
971    fn decode_reports_an_unknown_version() {
972        // 4: the first version this build does not read.
973        for version in [0, 4, u32::MAX] {
974            let mut bytes = v2(&sample(), 2).unwrap().to_vec();
975            bytes[4..8].copy_from_slice(&version.to_le_bytes());
976            assert!(
977                matches!(
978                    decode("p", &bytes, 2).unwrap_err(),
979                    ItzmaError::UnsupportedFormat { version: v } if v == version
980                ),
981                "version {version}"
982            );
983        }
984    }
985
986    #[test]
987    fn decode_rejects_a_dimension_that_differs_from_the_schema() {
988        let bytes = v2(&sample(), 2).unwrap();
989        assert!(corrupt(decode("p", &bytes, 3).unwrap_err()).contains("dimension"));
990    }
991
992    #[test]
993    fn encode_writes_the_default_version() {
994        let bytes = encode(&sample(), 2).unwrap();
995        assert_eq!(bytes[4..8], DEFAULT_FORMAT.to_le_bytes());
996        assert_eq!((DEFAULT_FORMAT, FORMAT_VERSION), (2, 3));
997    }
998
999    #[test]
1000    fn encode_as_writes_the_version_asked_for() {
1001        for version in [2, 3] {
1002            let bytes = encode_as(&sample(), 2, version).unwrap();
1003            assert_eq!(bytes[4..8], version.to_le_bytes());
1004        }
1005    }
1006
1007    #[test]
1008    fn encode_as_refuses_a_version_it_does_not_write() {
1009        for version in [0, 4, u32::MAX] {
1010            let err = encode_as(&sample(), 2, version).unwrap_err();
1011            assert!(
1012                matches!(err, ItzmaError::UnsupportedFormat { version: v } if v == version),
1013                "{err:?}"
1014            );
1015        }
1016    }
1017
1018    #[test]
1019    fn a_short_object_is_corrupt_not_unsupported() {
1020        for cut in 0..8 {
1021            let bytes = encode(&sample(), 2).unwrap();
1022            let err = decode("p", &bytes[..cut], 2).unwrap_err();
1023            assert!(matches!(err, ItzmaError::CorruptSegment { .. }), "{cut}");
1024        }
1025    }
1026
1027    #[test]
1028    fn segment_ids_are_zero_padded_ranges() {
1029        assert_eq!(
1030            segment_id(1, 10),
1031            "00000000000000000001-00000000000000000010"
1032        );
1033        assert_eq!(
1034            segment_path("docs", &segment_id(1, 10)).as_ref(),
1035            "docs/segments/00000000000000000001-00000000000000000010/data.bin"
1036        );
1037    }
1038
1039    #[test]
1040    fn parse_segment_id_accepts_only_the_canonical_form() {
1041        assert_eq!(parse_segment_id(&segment_id(3, 9)), Some((3, 9)));
1042        assert_eq!(parse_segment_id(&segment_id(5, 5)), Some((5, 5)));
1043        for bad in [
1044            "",
1045            "1-2",
1046            "00000000000000000001",
1047            "+0000000000000000001-00000000000000000002",
1048            "00000000000000000000-00000000000000000002",
1049            "00000000000000000003-00000000000000000002",
1050            "00000000000000000001-00000000000000000002-x",
1051            "0000000000000000000a-00000000000000000002",
1052        ] {
1053            assert_eq!(parse_segment_id(bad), None, "{bad:?}");
1054        }
1055    }
1056
1057    fn ids(ranges: &[(u64, u64)]) -> Vec<String> {
1058        ranges.iter().map(|(lo, hi)| segment_id(*lo, *hi)).collect()
1059    }
1060
1061    fn manifest_reason(err: ItzmaError) -> String {
1062        match err {
1063            ItzmaError::CorruptManifest(reason) => reason,
1064            other => panic!("expected CorruptManifest, got {other:?}"),
1065        }
1066    }
1067
1068    #[test]
1069    fn validate_chain_accepts_a_contiguous_run() {
1070        assert!(validate_chain(&[], 0).is_ok());
1071        assert!(validate_chain(&ids(&[(1, 3)]), 3).is_ok());
1072        assert!(validate_chain(&ids(&[(1, 3), (4, 4), (5, 9)]), 9).is_ok());
1073    }
1074
1075    #[test]
1076    fn validate_chain_rejects_every_broken_shape() {
1077        let cases = [
1078            (ids(&[(1, 3), (5, 6)]), 6, "starts at 5"), // gap
1079            (ids(&[(1, 3), (3, 4)]), 4, "starts at 3"), // overlap
1080            (ids(&[(2, 3)]), 3, "starts at 2"),         // does not begin at 1
1081            (ids(&[(1, 3)]), 4, "folded"),              // last hi differs from folded
1082            (vec![], 5, "folded"),                      // folded with no segments
1083            (vec!["nonsense".to_string()], 0, "malformed"),
1084        ];
1085        for (list, folded, want) in cases {
1086            let reason = manifest_reason(validate_chain(&list, folded).unwrap_err());
1087            assert!(reason.contains(want), "{list:?} folded {folded}: {reason}");
1088        }
1089    }
1090
1091    #[test]
1092    fn validate_chain_does_not_overflow_on_the_largest_range() {
1093        assert!(validate_chain(&ids(&[(1, u64::MAX)]), u64::MAX).is_err());
1094    }
1095
1096    async fn peek_of(bytes: &[u8]) -> (Result<Peek>, ReadBudget) {
1097        use object_store::memory::InMemory;
1098        let store = InMemory::new();
1099        let path = Path::from("docs/segments/x/data.bin");
1100        store
1101            .put(&path, Bytes::copy_from_slice(bytes).into())
1102            .await
1103            .unwrap();
1104        let budget = ReadBudget::new(1_000);
1105        (peek(&store, &path, &budget).await, budget)
1106    }
1107
1108    #[tokio::test]
1109    async fn a_peek_reads_the_version_dimension_and_count_of_either_version() {
1110        let l = sample();
1111        let docs = l.doc_count() as u64;
1112        for version in [2, 3] {
1113            let bytes = encode_as(&l, 2, version).unwrap();
1114            let (got, _) = peek_of(&bytes).await;
1115            assert_eq!(
1116                got.unwrap(),
1117                Peek {
1118                    version,
1119                    dim: 2,
1120                    doc_count: docs
1121                }
1122            );
1123        }
1124    }
1125
1126    #[tokio::test]
1127    async fn a_peek_is_charged_its_twenty_bytes_and_no_more() {
1128        use object_store::memory::InMemory;
1129        let bytes = encode(&sample(), 2).unwrap();
1130        let store = InMemory::new();
1131        let path = Path::from("docs/segments/x/data.bin");
1132        store.put(&path, bytes.into()).await.unwrap();
1133        peek(&store, &path, &ReadBudget::new(20)).await.unwrap();
1134        let err = peek(&store, &path, &ReadBudget::new(19)).await.unwrap_err();
1135        assert!(
1136            matches!(err, ItzmaError::ReadBudgetExceeded { .. }),
1137            "{err:?}"
1138        );
1139    }
1140
1141    #[tokio::test]
1142    async fn a_peek_refuses_what_is_not_a_segment() {
1143        let good = encode(&sample(), 2).unwrap().to_vec();
1144        let mut bad_magic = good.clone();
1145        bad_magic[0] = b'X';
1146        assert!(corrupt(peek_of(&bad_magic).await.0.unwrap_err()).contains("magic"));
1147
1148        let mut future = good.clone();
1149        future[4..8].copy_from_slice(&4u32.to_le_bytes());
1150        assert!(matches!(
1151            peek_of(&future).await.0,
1152            Err(ItzmaError::UnsupportedFormat { version: 4 })
1153        ));
1154        let mut zero = good.clone();
1155        zero[4..8].copy_from_slice(&0u32.to_le_bytes());
1156        assert!(matches!(
1157            peek_of(&zero).await.0,
1158            Err(ItzmaError::UnsupportedFormat { version: 0 })
1159        ));
1160
1161        for cut in 0..20 {
1162            assert!(peek_of(&good[..cut]).await.0.is_err(), "cut at {cut}");
1163        }
1164    }
1165
1166    #[tokio::test]
1167    async fn a_peek_of_a_missing_object_is_missing() {
1168        use object_store::memory::InMemory;
1169        let path = Path::from("docs/segments/x/data.bin");
1170        let err = peek(&InMemory::new(), &path, &ReadBudget::new(100))
1171            .await
1172            .unwrap_err();
1173        assert!(is_missing(&err), "{err:?}");
1174    }
1175}