Skip to main content

itzma_core/
columns.rs

1//! A batch of upserts held as columns.
2//!
3//! An Arrow table arrives as columns and the WAL stores columns, so a load
4//! that turned every row into a [`Document`](crate::Document) and back would
5//! copy every vector three times and build a JSON tree per row for nothing.
6//! [`DocColumns`] keeps the batch as flat buffers: ids as one UTF-8 buffer and
7//! offsets, vectors as one row-major `f32` slice, one typed column per
8//! attribute and an optional sparse column. The constructors check the shape
9//! (offsets, lengths, UTF-8), and [`DocColumns::validate`] checks the batch
10//! against a namespace's schema the way `upsert` checks documents, column by
11//! column.
12
13use crate::attrs::{AttrType, MAX_SET_ELEMENTS};
14use crate::document::{self, Schema};
15use crate::error::{ItzmaError, Result};
16
17/// A batch of upserts as columns. Build it with [`DocColumns::new`], then
18/// [`with_attr`](Self::with_attr) and [`with_sparse`](Self::with_sparse);
19/// the constructors are the only way in, so every batch is well formed.
20///
21/// Every row has every attribute column: a column cannot leave a field out
22/// of one row, only make it `null` there (`valid` false). A batch with no
23/// attribute columns writes no attributes at all, as a document with
24/// `attrs: None` does.
25#[derive(Debug, Clone, PartialEq)]
26#[non_exhaustive]
27pub struct DocColumns {
28    ids: Vec<u8>,
29    id_offsets: Vec<u32>,
30    vectors: Vec<f32>,
31    dim: usize,
32    /// Sorted by name, in byte order: the order `serde_json` writes an
33    /// object's keys in, which keeps the WAL bytes equal to `upsert`'s.
34    attrs: Vec<(String, AttrColumn)>,
35    sparse: Option<SparseColumn>,
36}
37
38/// One attribute column of a [`DocColumns`] batch.
39///
40/// `valid[row]` false means the field is `null` on that row, and whatever
41/// the value buffers hold there is ignored. A set's `offsets` (one more than
42/// the rows) cut its items into rows, and `items_valid` says which items are
43/// not `null`. Numbers keep their kind, so `5` stays an integer and `5.0` a
44/// float, as `serde_json` writes them.
45#[derive(Debug, Clone, PartialEq)]
46#[non_exhaustive]
47pub enum AttrColumn {
48    /// A column that is `null` on every one of `rows` rows (Arrow's `Null`
49    /// type).
50    Null {
51        /// The number of rows.
52        rows: usize,
53    },
54    /// Booleans.
55    Bool {
56        /// Which rows are not `null`.
57        valid: Vec<bool>,
58        /// One value a row.
59        values: Vec<bool>,
60    },
61    /// Integers.
62    I64 {
63        /// Which rows are not `null`.
64        valid: Vec<bool>,
65        /// One value a row.
66        values: Vec<i64>,
67    },
68    /// Floating-point numbers. A valid value must be finite.
69    F64 {
70        /// Which rows are not `null`.
71        valid: Vec<bool>,
72        /// One value a row.
73        values: Vec<f64>,
74    },
75    /// Strings, as one UTF-8 buffer cut by `offsets`.
76    Text {
77        /// Which rows are not `null`.
78        valid: Vec<bool>,
79        /// Every row's bytes, one after the other.
80        bytes: Vec<u8>,
81        /// `rows + 1` offsets into `bytes`.
82        offsets: Vec<u32>,
83    },
84    /// Sets of integers.
85    I64Set {
86        /// Which rows are not `null`.
87        valid: Vec<bool>,
88        /// `rows + 1` offsets into the items.
89        offsets: Vec<u32>,
90        /// Which items are not `null`.
91        items_valid: Vec<bool>,
92        /// One value an item.
93        values: Vec<i64>,
94    },
95    /// Sets of floating-point numbers. A valid item must be finite.
96    F64Set {
97        /// Which rows are not `null`.
98        valid: Vec<bool>,
99        /// `rows + 1` offsets into the items.
100        offsets: Vec<u32>,
101        /// Which items are not `null`.
102        items_valid: Vec<bool>,
103        /// One value an item.
104        values: Vec<f64>,
105    },
106    /// Sets of strings.
107    TextSet {
108        /// Which rows are not `null`.
109        valid: Vec<bool>,
110        /// `rows + 1` offsets into the items.
111        offsets: Vec<u32>,
112        /// Which items are not `null`.
113        items_valid: Vec<bool>,
114        /// Every item's bytes, one after the other.
115        bytes: Vec<u8>,
116        /// One more than the items: offsets into `bytes`.
117        byte_offsets: Vec<u32>,
118    },
119}
120
121/// The sparse vectors of a [`DocColumns`] batch: row `i`'s terms
122/// are `terms[offsets[i]..offsets[i + 1]]` with the weights beside them. A
123/// row that is not `valid` has no sparse vector; a valid row with no terms
124/// has an empty one.
125#[derive(Debug, Clone, PartialEq)]
126#[non_exhaustive]
127pub struct SparseColumn {
128    valid: Vec<bool>,
129    offsets: Vec<u32>,
130    terms: Vec<u32>,
131    weights: Vec<f32>,
132}
133
134fn malformed<T>(reason: &'static str) -> Result<T> {
135    Err(ItzmaError::InvalidColumns(reason))
136}
137
138/// Whether `offsets` cut `end` items or bytes into `count` runs: `count + 1`
139/// entries, from 0, never going down, ending at `end`.
140fn offsets_fit(offsets: &[u32], count: usize, end: usize) -> bool {
141    offsets.len() == count + 1
142        && offsets.first() == Some(&0)
143        && offsets.windows(2).all(|w| w[0] <= w[1])
144        && offsets.last().map(|&last| last as usize) == Some(end)
145}
146
147/// Whether every run `offsets` cuts out of `bytes` is UTF-8 on its own.
148fn runs_are_utf8(bytes: &[u8], offsets: &[u32]) -> bool {
149    offsets
150        .windows(2)
151        .all(|w| std::str::from_utf8(&bytes[w[0] as usize..w[1] as usize]).is_ok())
152}
153
154/// The run `at` of a buffer whose runs were checked to be UTF-8.
155fn run_str<'a>(bytes: &'a [u8], offsets: &[u32], at: usize) -> &'a str {
156    let run = &bytes[offsets[at] as usize..offsets[at + 1] as usize];
157    std::str::from_utf8(run).unwrap_or_default()
158}
159
160/// Keep `offsets[..=at]` and return the rest, rebased to start at 0, with
161/// the position in the buffer where the cut falls.
162fn split_offsets(offsets: &mut Vec<u32>, at: usize) -> (Vec<u32>, usize) {
163    let cut = offsets[at];
164    let tail = offsets[at..].iter().map(|o| o - cut).collect();
165    offsets.truncate(at + 1);
166    (tail, cut as usize)
167}
168
169/// Add `other`'s runs after these: its offsets shifted past our last one.
170fn append_offsets(offsets: &mut Vec<u32>, other: &[u32]) -> Result<()> {
171    let base = offsets.last().copied().unwrap_or(0);
172    for &o in other.iter().skip(1) {
173        let shifted = base.checked_add(o).ok_or(ItzmaError::InvalidColumns(
174            "a batch is too big for its offsets",
175        ))?;
176        offsets.push(shifted);
177    }
178    Ok(())
179}
180
181fn run_range(offsets: &[u32], at: usize) -> std::ops::Range<usize> {
182    offsets[at] as usize..offsets[at + 1] as usize
183}
184
185impl DocColumns {
186    /// A batch of `id_offsets.len() - 1` rows with no attributes and no
187    /// sparse vectors: row `i`'s id is `ids[id_offsets[i]..id_offsets[i + 1]]`
188    /// and its vector `vectors[i * dim..(i + 1) * dim]`.
189    ///
190    /// # Errors
191    ///
192    /// [`ItzmaError::InvalidColumns`] if the offsets do not start at 0, go
193    /// down or do not end at `ids.len()`, an id is not UTF-8 on its own, or
194    /// `vectors` is not `rows * dim` long.
195    pub fn new(ids: Vec<u8>, id_offsets: Vec<u32>, vectors: Vec<f32>, dim: usize) -> Result<Self> {
196        let rows = id_offsets.len().saturating_sub(1);
197        if !offsets_fit(&id_offsets, rows, ids.len()) {
198            return malformed("id offsets must run from 0 to the end of the ids, never going down");
199        }
200        if !runs_are_utf8(&ids, &id_offsets) {
201            return malformed("every id must be UTF-8");
202        }
203        if Some(vectors.len()) != rows.checked_mul(dim) {
204            return malformed("vectors must hold rows times dim values");
205        }
206        Ok(Self {
207            ids,
208            id_offsets,
209            vectors,
210            dim,
211            attrs: Vec::new(),
212            sparse: None,
213        })
214    }
215
216    /// Add an attribute column named `name`.
217    ///
218    /// # Errors
219    ///
220    /// [`ItzmaError::InvalidColumns`] if the name is empty or already used,
221    /// or the column does not have one entry a row (see [`AttrColumn`]), or
222    /// its offsets or text are malformed.
223    pub fn with_attr(mut self, name: impl Into<String>, column: AttrColumn) -> Result<Self> {
224        let name = name.into();
225        if name.is_empty() {
226            return malformed("an attribute column needs a name");
227        }
228        column.check_shape(self.rows())?;
229        match self.attrs.binary_search_by(|(n, _)| n.as_str().cmp(&name)) {
230            Ok(_) => malformed("two attribute columns have the same name"),
231            Err(at) => {
232                self.attrs.insert(at, (name, column));
233                Ok(self)
234            }
235        }
236    }
237
238    /// Add the sparse column.
239    ///
240    /// # Errors
241    ///
242    /// [`ItzmaError::InvalidColumns`] if it does not mark every row.
243    pub fn with_sparse(mut self, sparse: SparseColumn) -> Result<Self> {
244        if sparse.valid.len() != self.rows() {
245            return malformed("the sparse column must mark every row");
246        }
247        self.sparse = Some(sparse);
248        Ok(self)
249    }
250
251    /// The number of rows.
252    pub fn rows(&self) -> usize {
253        self.id_offsets.len().saturating_sub(1)
254    }
255
256    /// The length of every vector.
257    pub fn dim(&self) -> usize {
258        self.dim
259    }
260
261    /// Check the batch against a namespace's schema, without writing: the
262    /// checks [`Namespace::upsert`](crate::Namespace::upsert) runs on each
263    /// document, run column by column. An input with one defect gets exactly
264    /// the error `upsert` gives for the same documents; with several, the
265    /// first one reported can differ, since every id is checked before any
266    /// vector, every vector before any sparse vector, and so on.
267    ///
268    /// # Errors
269    ///
270    /// - [`ItzmaError::EmptyBatch`] for a batch of no rows.
271    /// - [`ItzmaError::InvalidId`] for an empty id or one longer than
272    ///   [`MAX_ID_BYTES`](crate::document::MAX_ID_BYTES).
273    /// - [`ItzmaError::DimensionMismatch`] and [`ItzmaError::InvalidVector`]
274    ///   for vectors, as [`Schema::validate`] decides, and for sparse vectors.
275    /// - [`ItzmaError::UnknownAttr`], [`ItzmaError::AttrTypeMismatch`] and
276    ///   [`ItzmaError::InvalidAttrs`] for attributes. A free-form namespace
277    ///   checks only that every number is finite, since JSON has no NaN.
278    pub fn validate(&self, schema: &Schema) -> Result<()> {
279        let rows = self.rows();
280        if rows == 0 {
281            return Err(ItzmaError::EmptyBatch);
282        }
283        for row in 0..rows {
284            document::validate_id(self.id(row))?;
285        }
286        if self.dim != schema.dim {
287            return Err(ItzmaError::DimensionMismatch {
288                expected: schema.dim,
289                got: self.dim,
290            });
291        }
292        for row in 0..rows {
293            schema.validate(self.vector(row))?;
294        }
295        if let Some(sparse) = &self.sparse {
296            for row in 0..rows {
297                if let Some((terms, weights)) = sparse.row(row) {
298                    document::validate_sparse_terms(
299                        terms.iter().copied(),
300                        weights.iter().copied(),
301                    )?;
302                }
303            }
304        }
305        for (name, column) in &self.attrs {
306            if !schema.attrs.is_free_form() {
307                let Some(ty) = schema.attrs.get(name) else {
308                    return Err(ItzmaError::UnknownAttr {
309                        field: name.clone(),
310                    });
311                };
312                column.check_type(name, ty, rows)?;
313            }
314            column.check_finite()?;
315        }
316        Ok(())
317    }
318
319    pub(crate) fn id(&self, row: usize) -> &str {
320        run_str(&self.ids, &self.id_offsets, row)
321    }
322
323    pub(crate) fn vector(&self, row: usize) -> &[f32] {
324        &self.vectors[row * self.dim..(row + 1) * self.dim]
325    }
326
327    pub(crate) fn vectors(&self) -> &[f32] {
328        &self.vectors
329    }
330
331    pub(crate) fn attrs(&self) -> &[(String, AttrColumn)] {
332        &self.attrs
333    }
334
335    pub(crate) fn sparse(&self) -> Option<&SparseColumn> {
336        self.sparse.as_ref()
337    }
338
339    /// Add `other`'s rows after these, for the stream's chunker. Both must
340    /// have the same `dim` and the same attribute names; a column that is
341    /// [`AttrColumn::Null`] on one side takes the other side's kind. A batch
342    /// without a sparse column appends to one with it as rows without
343    /// sparse vectors, and the other way round.
344    ///
345    /// # Errors
346    ///
347    /// [`ItzmaError::InvalidColumns`] if the batches do not share their
348    /// columns, or the result would not fit its `u32` offsets.
349    pub(crate) fn append(&mut self, other: DocColumns) -> Result<()> {
350        if self.rows() == 0 && self.attrs.is_empty() && self.sparse.is_none() {
351            *self = other;
352            return Ok(());
353        }
354        let same_names = self.attrs.len() == other.attrs.len()
355            && self
356                .attrs
357                .iter()
358                .zip(&other.attrs)
359                .all(|((a, _), (b, _))| a == b);
360        if self.dim != other.dim || !same_names {
361            return malformed("batches in one stream must have the same columns");
362        }
363        let (rows, other_rows) = (self.rows(), other.rows());
364        append_offsets(&mut self.id_offsets, &other.id_offsets)?;
365        self.ids.extend_from_slice(&other.ids);
366        self.vectors.extend_from_slice(&other.vectors);
367        for ((_, mine), (_, theirs)) in self.attrs.iter_mut().zip(other.attrs) {
368            mine.append(theirs)?;
369        }
370        match (&mut self.sparse, other.sparse) {
371            (None, None) => {}
372            (Some(mine), theirs) => {
373                mine.append(theirs.unwrap_or_else(|| SparseColumn::empty(other_rows)))?;
374            }
375            (mine @ None, Some(theirs)) => {
376                let mut column = SparseColumn::empty(rows);
377                column.append(theirs)?;
378                *mine = Some(column);
379            }
380        }
381        Ok(())
382    }
383
384    /// Split off rows `at..` into a batch of their own and keep `..at`.
385    pub(crate) fn split_off(&mut self, at: usize) -> DocColumns {
386        let (id_offsets, cut) = split_offsets(&mut self.id_offsets, at);
387        DocColumns {
388            ids: self.ids.split_off(cut),
389            id_offsets,
390            vectors: self.vectors.split_off(at * self.dim),
391            dim: self.dim,
392            attrs: self
393                .attrs
394                .iter_mut()
395                .map(|(name, column)| (name.clone(), column.split_off(at)))
396                .collect(),
397            sparse: self.sparse.as_mut().map(|sparse| sparse.split_off(at)),
398        }
399    }
400
401    /// Give back spare capacity, as a `split_off` leaves the head holding
402    /// all of it.
403    pub(crate) fn shrink_to_fit(&mut self) {
404        self.ids.shrink_to_fit();
405        self.id_offsets.shrink_to_fit();
406        self.vectors.shrink_to_fit();
407        for (_, column) in &mut self.attrs {
408            column.shrink_to_fit();
409        }
410        if let Some(sparse) = &mut self.sparse {
411            sparse.valid.shrink_to_fit();
412            sparse.offsets.shrink_to_fit();
413            sparse.terms.shrink_to_fit();
414            sparse.weights.shrink_to_fit();
415        }
416    }
417
418    /// The batch without the column `name`, for tests that build a variant.
419    #[cfg(test)]
420    pub(crate) fn without_attr(mut self, name: &str) -> Self {
421        self.attrs.retain(|(n, _)| n != name);
422        self
423    }
424
425    /// Whether any row has a sparse vector, which makes the batch a version
426    /// 4 or 5 object that needs WAL level 5.
427    pub(crate) fn has_sparse(&self) -> bool {
428        self.sparse.as_ref().is_some_and(SparseColumn::any)
429    }
430}
431
432impl AttrColumn {
433    /// Check that the column has `rows` rows and well-formed offsets and text.
434    fn check_shape(&self, rows: usize) -> Result<()> {
435        let ok = match self {
436            AttrColumn::Null { rows: n } => *n == rows,
437            AttrColumn::Bool { valid, values } => valid.len() == rows && values.len() == rows,
438            AttrColumn::I64 { valid, values } => valid.len() == rows && values.len() == rows,
439            AttrColumn::F64 { valid, values } => valid.len() == rows && values.len() == rows,
440            AttrColumn::Text {
441                valid,
442                bytes,
443                offsets,
444            } => {
445                if !(valid.len() == rows && offsets_fit(offsets, rows, bytes.len())) {
446                    false
447                } else if !runs_are_utf8(bytes, offsets) {
448                    return malformed("text must be UTF-8");
449                } else {
450                    true
451                }
452            }
453            AttrColumn::I64Set {
454                valid,
455                offsets,
456                items_valid,
457                values,
458            } => set_fits(valid, offsets, items_valid, values.len(), rows),
459            AttrColumn::F64Set {
460                valid,
461                offsets,
462                items_valid,
463                values,
464            } => set_fits(valid, offsets, items_valid, values.len(), rows),
465            AttrColumn::TextSet {
466                valid,
467                offsets,
468                items_valid,
469                bytes,
470                byte_offsets,
471            } => {
472                let items = items_valid.len();
473                if !(set_fits(valid, offsets, items_valid, items, rows)
474                    && offsets_fit(byte_offsets, items, bytes.len()))
475                {
476                    false
477                } else if !runs_are_utf8(bytes, byte_offsets) {
478                    return malformed("text must be UTF-8");
479                } else {
480                    true
481                }
482            }
483        };
484        if ok {
485            Ok(())
486        } else {
487            malformed("an attribute column must have one entry a row, with offsets that fit")
488        }
489    }
490
491    /// Check every non-null row against the declared type `ty`, the way
492    /// `attrs::check_value` checks a JSON value: a set's length first, then
493    /// its items, and a `null` item never fits a typed set.
494    fn check_type(&self, field: &str, ty: AttrType, rows: usize) -> Result<()> {
495        let mismatch = |found: &'static str| {
496            Err(ItzmaError::AttrTypeMismatch {
497                field: field.to_string(),
498                expected: ty.name(),
499                found,
500            })
501        };
502        let (kind, item_ty) = match self {
503            AttrColumn::Null { .. } => return Ok(()),
504            AttrColumn::Bool { .. } => ("bool", AttrType::Bool),
505            AttrColumn::I64 { .. } | AttrColumn::F64 { .. } => ("number", AttrType::Number),
506            AttrColumn::Text { .. } => ("string", AttrType::Text),
507            AttrColumn::I64Set { .. } | AttrColumn::F64Set { .. } => ("array", AttrType::NumberSet),
508            AttrColumn::TextSet { .. } => ("array", AttrType::TextSet),
509        };
510        for row in (0..rows).filter(|&row| !self.is_null(row)) {
511            let Some((offsets, items_valid)) = self.set_parts() else {
512                if ty != item_ty {
513                    return mismatch(kind);
514                }
515                continue;
516            };
517            if !matches!(ty, AttrType::TextSet | AttrType::NumberSet) {
518                return mismatch(kind);
519            }
520            let items = run_range(offsets, row);
521            if items.len() > MAX_SET_ELEMENTS {
522                return Err(ItzmaError::InvalidAttrs("a set has too many elements"));
523            }
524            let all_valid = items_valid[items.clone()].iter().all(|&v| v);
525            if !(items.is_empty() || (all_valid && ty == item_ty)) {
526                return mismatch(kind);
527            }
528        }
529        Ok(())
530    }
531
532    /// Every non-null number is finite: JSON has no NaN or infinity.
533    fn check_finite(&self) -> Result<()> {
534        let finite = match self {
535            AttrColumn::F64 { valid, values } => values
536                .iter()
537                .zip(valid)
538                .all(|(v, &ok)| !ok || v.is_finite()),
539            AttrColumn::F64Set {
540                valid,
541                offsets,
542                items_valid,
543                values,
544            } => (0..valid.len()).filter(|&row| valid[row]).all(|row| {
545                run_range(offsets, row).all(|i| !items_valid[i] || values[i].is_finite())
546            }),
547            _ => true,
548        };
549        if finite {
550            Ok(())
551        } else {
552            Err(ItzmaError::InvalidAttrs("attribute numbers must be finite"))
553        }
554    }
555
556    /// A set column's offsets and item validity.
557    fn set_parts(&self) -> Option<(&[u32], &[bool])> {
558        match self {
559            AttrColumn::I64Set {
560                offsets,
561                items_valid,
562                ..
563            }
564            | AttrColumn::F64Set {
565                offsets,
566                items_valid,
567                ..
568            }
569            | AttrColumn::TextSet {
570                offsets,
571                items_valid,
572                ..
573            } => Some((offsets, items_valid)),
574            _ => None,
575        }
576    }
577
578    /// The same kind of column, `null` on each of `rows` rows.
579    fn empty_like(&self, rows: usize) -> AttrColumn {
580        let valid = vec![false; rows];
581        let offsets = vec![0u32; rows + 1];
582        match self {
583            AttrColumn::Null { .. } => AttrColumn::Null { rows },
584            AttrColumn::Bool { .. } => AttrColumn::Bool {
585                valid,
586                values: vec![false; rows],
587            },
588            AttrColumn::I64 { .. } => AttrColumn::I64 {
589                valid,
590                values: vec![0; rows],
591            },
592            AttrColumn::F64 { .. } => AttrColumn::F64 {
593                valid,
594                values: vec![0.0; rows],
595            },
596            AttrColumn::Text { .. } => AttrColumn::Text {
597                valid,
598                bytes: Vec::new(),
599                offsets,
600            },
601            AttrColumn::I64Set { .. } => AttrColumn::I64Set {
602                valid,
603                offsets,
604                items_valid: Vec::new(),
605                values: Vec::new(),
606            },
607            AttrColumn::F64Set { .. } => AttrColumn::F64Set {
608                valid,
609                offsets,
610                items_valid: Vec::new(),
611                values: Vec::new(),
612            },
613            AttrColumn::TextSet { .. } => AttrColumn::TextSet {
614                valid,
615                offsets,
616                items_valid: Vec::new(),
617                bytes: Vec::new(),
618                byte_offsets: vec![0],
619            },
620        }
621    }
622
623    /// Add `other`'s rows after these. A `Null` column on either side takes
624    /// the other's kind, its rows `null`.
625    fn append(&mut self, other: AttrColumn) -> Result<()> {
626        let other = match (&*self, other) {
627            (AttrColumn::Null { rows }, AttrColumn::Null { rows: more }) => {
628                *self = AttrColumn::Null { rows: rows + more };
629                return Ok(());
630            }
631            (AttrColumn::Null { rows }, other) => {
632                *self = other.empty_like(*rows);
633                other
634            }
635            (_, AttrColumn::Null { rows }) => self.empty_like(rows),
636            (_, other) => other,
637        };
638        match (self, other) {
639            (
640                AttrColumn::Bool { valid, values },
641                AttrColumn::Bool {
642                    valid: v,
643                    values: x,
644                },
645            ) => {
646                valid.extend(v);
647                values.extend(x);
648            }
649            (
650                AttrColumn::I64 { valid, values },
651                AttrColumn::I64 {
652                    valid: v,
653                    values: x,
654                },
655            ) => {
656                valid.extend(v);
657                values.extend(x);
658            }
659            (
660                AttrColumn::F64 { valid, values },
661                AttrColumn::F64 {
662                    valid: v,
663                    values: x,
664                },
665            ) => {
666                valid.extend(v);
667                values.extend(x);
668            }
669            (
670                AttrColumn::Text {
671                    valid,
672                    bytes,
673                    offsets,
674                },
675                AttrColumn::Text {
676                    valid: v,
677                    bytes: b,
678                    offsets: o,
679                },
680            ) => {
681                append_offsets(offsets, &o)?;
682                valid.extend(v);
683                bytes.extend(b);
684            }
685            (
686                AttrColumn::I64Set {
687                    valid,
688                    offsets,
689                    items_valid,
690                    values,
691                },
692                AttrColumn::I64Set {
693                    valid: v,
694                    offsets: o,
695                    items_valid: iv,
696                    values: x,
697                },
698            ) => {
699                append_offsets(offsets, &o)?;
700                valid.extend(v);
701                items_valid.extend(iv);
702                values.extend(x);
703            }
704            (
705                AttrColumn::F64Set {
706                    valid,
707                    offsets,
708                    items_valid,
709                    values,
710                },
711                AttrColumn::F64Set {
712                    valid: v,
713                    offsets: o,
714                    items_valid: iv,
715                    values: x,
716                },
717            ) => {
718                append_offsets(offsets, &o)?;
719                valid.extend(v);
720                items_valid.extend(iv);
721                values.extend(x);
722            }
723            (
724                AttrColumn::TextSet {
725                    valid,
726                    offsets,
727                    items_valid,
728                    bytes,
729                    byte_offsets,
730                },
731                AttrColumn::TextSet {
732                    valid: v,
733                    offsets: o,
734                    items_valid: iv,
735                    bytes: b,
736                    byte_offsets: bo,
737                },
738            ) => {
739                append_offsets(offsets, &o)?;
740                append_offsets(byte_offsets, &bo)?;
741                valid.extend(v);
742                items_valid.extend(iv);
743                bytes.extend(b);
744            }
745            _ => {
746                return malformed(
747                    "batches in one stream must give each attribute column the same kind: a number column cannot switch between integers and floats",
748                );
749            }
750        }
751        Ok(())
752    }
753
754    fn shrink_to_fit(&mut self) {
755        match self {
756            AttrColumn::Null { .. } => {}
757            AttrColumn::Bool { valid, values } => {
758                valid.shrink_to_fit();
759                values.shrink_to_fit();
760            }
761            AttrColumn::I64 { valid, values } => {
762                valid.shrink_to_fit();
763                values.shrink_to_fit();
764            }
765            AttrColumn::F64 { valid, values } => {
766                valid.shrink_to_fit();
767                values.shrink_to_fit();
768            }
769            AttrColumn::Text {
770                valid,
771                bytes,
772                offsets,
773            } => {
774                valid.shrink_to_fit();
775                bytes.shrink_to_fit();
776                offsets.shrink_to_fit();
777            }
778            AttrColumn::I64Set {
779                valid,
780                offsets,
781                items_valid,
782                values,
783            } => {
784                valid.shrink_to_fit();
785                offsets.shrink_to_fit();
786                items_valid.shrink_to_fit();
787                values.shrink_to_fit();
788            }
789            AttrColumn::F64Set {
790                valid,
791                offsets,
792                items_valid,
793                values,
794            } => {
795                valid.shrink_to_fit();
796                offsets.shrink_to_fit();
797                items_valid.shrink_to_fit();
798                values.shrink_to_fit();
799            }
800            AttrColumn::TextSet {
801                valid,
802                offsets,
803                items_valid,
804                bytes,
805                byte_offsets,
806            } => {
807                valid.shrink_to_fit();
808                offsets.shrink_to_fit();
809                items_valid.shrink_to_fit();
810                bytes.shrink_to_fit();
811                byte_offsets.shrink_to_fit();
812            }
813        }
814    }
815
816    /// Split off rows `at..` and keep `..at`.
817    fn split_off(&mut self, at: usize) -> AttrColumn {
818        match self {
819            AttrColumn::Null { rows } => {
820                let tail = *rows - at;
821                *rows = at;
822                AttrColumn::Null { rows: tail }
823            }
824            AttrColumn::Bool { valid, values } => AttrColumn::Bool {
825                valid: valid.split_off(at),
826                values: values.split_off(at),
827            },
828            AttrColumn::I64 { valid, values } => AttrColumn::I64 {
829                valid: valid.split_off(at),
830                values: values.split_off(at),
831            },
832            AttrColumn::F64 { valid, values } => AttrColumn::F64 {
833                valid: valid.split_off(at),
834                values: values.split_off(at),
835            },
836            AttrColumn::Text {
837                valid,
838                bytes,
839                offsets,
840            } => {
841                let (offsets, cut) = split_offsets(offsets, at);
842                AttrColumn::Text {
843                    valid: valid.split_off(at),
844                    bytes: bytes.split_off(cut),
845                    offsets,
846                }
847            }
848            AttrColumn::I64Set {
849                valid,
850                offsets,
851                items_valid,
852                values,
853            } => {
854                let (offsets, cut) = split_offsets(offsets, at);
855                AttrColumn::I64Set {
856                    valid: valid.split_off(at),
857                    offsets,
858                    items_valid: items_valid.split_off(cut),
859                    values: values.split_off(cut),
860                }
861            }
862            AttrColumn::F64Set {
863                valid,
864                offsets,
865                items_valid,
866                values,
867            } => {
868                let (offsets, cut) = split_offsets(offsets, at);
869                AttrColumn::F64Set {
870                    valid: valid.split_off(at),
871                    offsets,
872                    items_valid: items_valid.split_off(cut),
873                    values: values.split_off(cut),
874                }
875            }
876            AttrColumn::TextSet {
877                valid,
878                offsets,
879                items_valid,
880                bytes,
881                byte_offsets,
882            } => {
883                let (offsets, cut) = split_offsets(offsets, at);
884                let (byte_offsets, byte_cut) = split_offsets(byte_offsets, cut);
885                AttrColumn::TextSet {
886                    valid: valid.split_off(at),
887                    offsets,
888                    items_valid: items_valid.split_off(cut),
889                    bytes: bytes.split_off(byte_cut),
890                    byte_offsets,
891                }
892            }
893        }
894    }
895
896    /// Whether row `row` is `null`.
897    pub(crate) fn is_null(&self, row: usize) -> bool {
898        match self {
899            AttrColumn::Null { .. } => true,
900            AttrColumn::Bool { valid, .. }
901            | AttrColumn::I64 { valid, .. }
902            | AttrColumn::F64 { valid, .. }
903            | AttrColumn::Text { valid, .. }
904            | AttrColumn::I64Set { valid, .. }
905            | AttrColumn::F64Set { valid, .. }
906            | AttrColumn::TextSet { valid, .. } => !valid[row],
907        }
908    }
909
910    /// Row `row`'s string, for a `Text` column.
911    pub(crate) fn text<'a>(bytes: &'a [u8], offsets: &[u32], row: usize) -> &'a str {
912        run_str(bytes, offsets, row)
913    }
914
915    /// The item range of row `row` in a set column's items.
916    pub(crate) fn items(offsets: &[u32], row: usize) -> std::ops::Range<usize> {
917        run_range(offsets, row)
918    }
919}
920
921fn set_fits(
922    valid: &[bool],
923    offsets: &[u32],
924    items_valid: &[bool],
925    values: usize,
926    rows: usize,
927) -> bool {
928    valid.len() == rows
929        && offsets_fit(offsets, rows, items_valid.len())
930        && values == items_valid.len()
931}
932
933impl SparseColumn {
934    /// The sparse vectors of `valid.len()` rows.
935    ///
936    /// # Errors
937    ///
938    /// [`ItzmaError::InvalidColumns`] if `offsets` do not cut `terms` into one
939    /// run a row, or `terms` and `weights` differ in length.
940    pub fn new(
941        valid: Vec<bool>,
942        offsets: Vec<u32>,
943        terms: Vec<u32>,
944        weights: Vec<f32>,
945    ) -> Result<Self> {
946        if !offsets_fit(&offsets, valid.len(), terms.len()) || terms.len() != weights.len() {
947            return malformed(
948                "sparse offsets must cut the terms into one run a row, with a weight a term",
949            );
950        }
951        Ok(Self {
952            valid,
953            offsets,
954            terms,
955            weights,
956        })
957    }
958
959    /// `rows` rows with no sparse vector.
960    fn empty(rows: usize) -> Self {
961        Self {
962            valid: vec![false; rows],
963            offsets: vec![0; rows + 1],
964            terms: Vec::new(),
965            weights: Vec::new(),
966        }
967    }
968
969    fn append(&mut self, other: SparseColumn) -> Result<()> {
970        append_offsets(&mut self.offsets, &other.offsets)?;
971        self.valid.extend(other.valid);
972        self.terms.extend(other.terms);
973        self.weights.extend(other.weights);
974        Ok(())
975    }
976
977    fn split_off(&mut self, at: usize) -> SparseColumn {
978        let (offsets, cut) = split_offsets(&mut self.offsets, at);
979        SparseColumn {
980            valid: self.valid.split_off(at),
981            offsets,
982            terms: self.terms.split_off(cut),
983            weights: self.weights.split_off(cut),
984        }
985    }
986
987    /// Row `row`'s terms and weights, or `None` when it has no sparse vector.
988    pub(crate) fn row(&self, row: usize) -> Option<(&[u32], &[f32])> {
989        if !self.valid[row] {
990            return None;
991        }
992        let range = run_range(&self.offsets, row);
993        Some((&self.terms[range.clone()], &self.weights[range]))
994    }
995
996    /// Whether any row has a sparse vector, which is what makes a batch a
997    /// version 4 or 5 object.
998    pub(crate) fn any(&self) -> bool {
999        self.valid.iter().any(|&v| v)
1000    }
1001}
1002
1003#[cfg(test)]
1004mod tests {
1005    use super::*;
1006    use crate::error::ItzmaError;
1007
1008    fn ids(list: &[&str]) -> (Vec<u8>, Vec<u32>) {
1009        let mut bytes = Vec::new();
1010        let mut offsets = vec![0];
1011        for id in list {
1012            bytes.extend_from_slice(id.as_bytes());
1013            offsets.push(bytes.len() as u32);
1014        }
1015        (bytes, offsets)
1016    }
1017
1018    fn two_rows() -> DocColumns {
1019        let (bytes, offsets) = ids(&["a", "bc"]);
1020        DocColumns::new(bytes, offsets, vec![1.0, 2.0, 3.0, 4.0], 2).unwrap()
1021    }
1022
1023    fn malformed<T: std::fmt::Debug>(result: Result<T>) {
1024        assert!(
1025            matches!(result, Err(ItzmaError::InvalidColumns(_))),
1026            "{result:?}"
1027        );
1028    }
1029
1030    #[test]
1031    fn id_offsets_must_start_at_zero() {
1032        malformed(DocColumns::new(b"ab".to_vec(), vec![1, 2], vec![0.0], 1));
1033    }
1034
1035    #[test]
1036    fn id_offsets_must_not_decrease() {
1037        malformed(DocColumns::new(
1038            b"ab".to_vec(),
1039            vec![0, 2, 1],
1040            vec![0.0, 0.0],
1041            1,
1042        ));
1043    }
1044
1045    #[test]
1046    fn id_offsets_must_end_at_the_buffer() {
1047        malformed(DocColumns::new(b"abc".to_vec(), vec![0, 2], vec![0.0], 1));
1048    }
1049
1050    #[test]
1051    fn an_id_cannot_split_a_character() {
1052        // "é" is two bytes.
1053        malformed(DocColumns::new(
1054            "é".as_bytes().to_vec(),
1055            vec![0, 1, 2],
1056            vec![0.0, 0.0],
1057            1,
1058        ));
1059    }
1060
1061    #[test]
1062    fn vectors_must_be_rows_times_dim() {
1063        let (bytes, offsets) = ids(&["a", "b"]);
1064        malformed(DocColumns::new(bytes, offsets, vec![1.0, 2.0, 3.0], 2));
1065    }
1066
1067    #[test]
1068    fn a_column_must_mark_every_row() {
1069        malformed(two_rows().with_attr(
1070            "price",
1071            AttrColumn::F64 {
1072                valid: vec![true],
1073                values: vec![1.0, 2.0],
1074            },
1075        ));
1076        malformed(two_rows().with_attr("n", AttrColumn::Null { rows: 3 }));
1077    }
1078
1079    #[test]
1080    fn text_must_be_utf8() {
1081        malformed(two_rows().with_attr(
1082            "name",
1083            AttrColumn::Text {
1084                valid: vec![true, true],
1085                bytes: vec![0xff, b'a'],
1086                offsets: vec![0, 1, 2],
1087            },
1088        ));
1089    }
1090
1091    #[test]
1092    fn set_items_must_line_up() {
1093        malformed(two_rows().with_attr(
1094            "tags",
1095            AttrColumn::I64Set {
1096                valid: vec![true, true],
1097                offsets: vec![0, 1, 3],
1098                items_valid: vec![true, true],
1099                values: vec![1, 2, 3],
1100            },
1101        ));
1102    }
1103
1104    #[test]
1105    fn names_are_not_empty_and_not_repeated() {
1106        let price = || AttrColumn::Null { rows: 2 };
1107        malformed(two_rows().with_attr("", price()));
1108        malformed(
1109            two_rows()
1110                .with_attr("price", price())
1111                .unwrap()
1112                .with_attr("price", price()),
1113        );
1114    }
1115
1116    #[test]
1117    fn a_sparse_column_must_cover_every_row() {
1118        let sparse = SparseColumn::new(vec![true], vec![0, 1], vec![7], vec![1.0]).unwrap();
1119        malformed(two_rows().with_sparse(sparse));
1120        malformed(SparseColumn::new(
1121            vec![true],
1122            vec![0, 2],
1123            vec![7],
1124            vec![1.0],
1125        ));
1126    }
1127
1128    #[test]
1129    fn a_good_batch_round_trips_its_accessors() {
1130        let cols = two_rows()
1131            .with_attr(
1132                "z",
1133                AttrColumn::F64 {
1134                    valid: vec![true, false],
1135                    values: vec![1.5, 0.0],
1136                },
1137            )
1138            .unwrap()
1139            .with_attr("a", AttrColumn::Null { rows: 2 })
1140            .unwrap()
1141            .with_sparse(
1142                SparseColumn::new(vec![true, false], vec![0, 2, 2], vec![3, 9], vec![0.5, 1.0])
1143                    .unwrap(),
1144            )
1145            .unwrap();
1146        assert_eq!((cols.rows(), cols.dim()), (2, 2));
1147        assert_eq!((cols.id(0), cols.id(1)), ("a", "bc"));
1148        assert_eq!(cols.vector(1), &[3.0, 4.0]);
1149        let names: Vec<&str> = cols.attrs().iter().map(|(n, _)| n.as_str()).collect();
1150        assert_eq!(names, ["a", "z"]);
1151        let sparse = cols.sparse().unwrap();
1152        assert_eq!(sparse.row(0), Some((&[3, 9][..], &[0.5, 1.0][..])));
1153        assert_eq!(sparse.row(1), None);
1154    }
1155}