Skip to main content

itzma_core/
stream.rs

1//! Streaming columnar ingest: the chunker that cuts a stream of
2//! batches into WAL-sized chunks.
3
4use bytes::Bytes;
5use futures::{Stream, StreamExt};
6use serde::{Deserialize, Serialize};
7
8use crate::columns::DocColumns;
9use crate::cpu::{self, Cost, Lane};
10use crate::document::Schema;
11use crate::error::{ItzmaError, Result};
12use crate::namespace::Namespace;
13use crate::wal::{self, WriteKey};
14use crate::wal_codec::{self, COUNTS_LEN};
15
16/// The default [`StreamOptions::target_bytes`]: half the WAL's 64 MiB body
17/// limit, so a chunk's own estimate never pushes it over.
18pub const DEFAULT_STREAM_TARGET_BYTES: usize = wal::MAX_BODY_BYTES / 2;
19
20/// The default [`StreamOptions::depth`].
21pub const DEFAULT_STREAM_DEPTH: usize = 2;
22
23/// The longest key a keyed stream takes: each chunk's key is `<key>#<n>`,
24/// a WAL key is at most 128 bytes, and `n` can take 20 digits.
25const MAX_STREAM_KEY: usize = 107;
26
27/// How [`Namespace::upsert_stream`] cuts and queues a stream.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[non_exhaustive]
30pub struct StreamOptions {
31    /// About how many encoded body bytes each WAL object holds: 1 to
32    /// [`wal::MAX_BODY_BYTES`]. A single row bigger than this is an object of
33    /// its own. Default [`DEFAULT_STREAM_TARGET_BYTES`].
34    pub target_bytes: usize,
35    /// How many encoded chunks may wait for the writer, at least 1. Memory
36    /// is about `(depth + 2) * target_bytes`, whatever the input's size.
37    /// Default [`DEFAULT_STREAM_DEPTH`].
38    pub depth: usize,
39}
40
41impl Default for StreamOptions {
42    fn default() -> Self {
43        Self {
44            target_bytes: DEFAULT_STREAM_TARGET_BYTES,
45            depth: DEFAULT_STREAM_DEPTH,
46        }
47    }
48}
49
50impl StreamOptions {
51    /// Set [`target_bytes`](Self::target_bytes).
52    #[must_use]
53    pub fn target_bytes(mut self, bytes: usize) -> Self {
54        self.target_bytes = bytes;
55        self
56    }
57
58    /// Set [`depth`](Self::depth).
59    #[must_use]
60    pub fn depth(mut self, depth: usize) -> Self {
61        self.depth = depth;
62        self
63    }
64
65    /// Check the options, as [`Namespace::upsert_stream`] does before it
66    /// reads its input.
67    ///
68    /// # Errors
69    ///
70    /// [`ItzmaError::InvalidConfig`] for a `target_bytes` of 0 or above
71    /// [`wal::MAX_BODY_BYTES`], or a `depth` of 0.
72    pub fn validate(&self) -> Result<()> {
73        if self.target_bytes == 0 || self.target_bytes > wal::MAX_BODY_BYTES {
74            return Err(ItzmaError::InvalidConfig(
75                "target_bytes must be 1 to the WAL's 64 MiB body limit",
76            ));
77        }
78        if self.depth == 0 {
79            return Err(ItzmaError::InvalidConfig("depth must be at least 1"));
80        }
81        Ok(())
82    }
83}
84
85/// What a stream wrote: the first and last seq it landed at, and how many
86/// rows and objects. On an error, [`StreamError::landed`] is this for what
87/// landed before it.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
89#[non_exhaustive]
90pub struct StreamReport {
91    /// The seq of the first object written, `None` if none was.
92    pub first_seq: Option<u64>,
93    /// The seq of the last object written, `None` if none was.
94    pub last_seq: Option<u64>,
95    /// The rows written. After an error, an unkeyed load resumes by feeding
96    /// its input again from this row.
97    pub rows: u64,
98    /// The WAL objects written.
99    pub objects: u64,
100}
101
102/// A stream that stopped: the error, and what landed before it. Every
103/// object in [`landed`](Self::landed) is whole and in the WAL, one after the
104/// other.
105#[derive(Debug)]
106pub struct StreamError {
107    /// What was written before the error.
108    pub landed: StreamReport,
109    /// Why the stream stopped.
110    pub error: ItzmaError,
111}
112
113impl std::fmt::Display for StreamError {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        write!(
116            f,
117            "{} (after {} rows in {} objects)",
118            self.error, self.landed.rows, self.landed.objects
119        )
120    }
121}
122
123impl std::error::Error for StreamError {
124    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
125        Some(&self.error)
126    }
127}
128
129/// An encoded chunk on its way to the writer.
130struct Encoded {
131    object: Object,
132    rows: u64,
133    sparse: bool,
134}
135
136enum Object {
137    Plain(Bytes),
138    /// The chunk's own key, `<key>#<n>`, and its object.
139    Keyed(String, wal_codec::Keyed),
140}
141
142/// Run a stream: an encode stage and a write stage joined in one future,
143/// with a channel of `depth` encoded chunks between them. The write stage
144/// puts one object at a time; when the channel is full the encode stage
145/// waits, and the input is not polled.
146pub(crate) async fn run<S>(
147    ns: &Namespace,
148    input: S,
149    options: &StreamOptions,
150    key: Option<&WriteKey>,
151) -> std::result::Result<StreamReport, StreamError>
152where
153    S: Stream<Item = Result<DocColumns>> + Send,
154{
155    let refuse = |error| StreamError {
156        landed: StreamReport::default(),
157        error,
158    };
159    options.validate().map_err(refuse)?;
160    if let Some(write) = key {
161        write.validate().map_err(refuse)?;
162        if write.key.len() > MAX_STREAM_KEY {
163            return Err(refuse(ItzmaError::InvalidKey(
164                "a stream key must be 1 to 107 bytes, leaving room for the chunk number",
165            )));
166        }
167    }
168    let (tx, rx) = tokio::sync::mpsc::channel(options.depth);
169    let (encoded, (landed, written)) = futures::join!(
170        encode_stage(ns.schema(), input, options.target_bytes, key, tx),
171        write_stage(ns, rx, key.and_then(|write| write.search_from)),
172    );
173    // A write error is always about an earlier chunk than an encode error:
174    // once the writer stops, the encoder's next send fails and it stops too.
175    match (written, encoded) {
176        (Err(error), _) | (Ok(()), Err(Some(error))) => Err(StreamError { landed, error }),
177        _ => Ok(landed),
178    }
179}
180
181/// Cut the input into chunks, check and encode each, and send it on. `Err(None)`
182/// means the writer stopped first, which is its error to report.
183async fn encode_stage<S>(
184    schema: &Schema,
185    input: S,
186    target: usize,
187    key: Option<&WriteKey>,
188    tx: tokio::sync::mpsc::Sender<Encoded>,
189) -> std::result::Result<(), Option<ItzmaError>>
190where
191    S: Stream<Item = Result<DocColumns>> + Send,
192{
193    let mut input = std::pin::pin!(input);
194    let mut chunker = Chunker::new(target as u64);
195    let mut chunks = 0u64;
196    loop {
197        // Wait for the next batch or for the writer to stop, whichever comes
198        // first: a writer that failed must not wait on a source that may
199        // take long, or forever, to fill another chunk.
200        let next = {
201            let closed = std::pin::pin!(tx.closed());
202            match futures::future::select(input.next(), closed).await {
203                futures::future::Either::Left((next, _)) => next,
204                futures::future::Either::Right(_) => return Err(None),
205            }
206        };
207        let Some(batch) = next else {
208            break;
209        };
210        for chunk in chunker.push(batch?)? {
211            send(&tx, encode(schema, chunk, key, chunks).await?).await?;
212            chunks += 1;
213        }
214    }
215    if let Some(chunk) = chunker.finish() {
216        send(&tx, encode(schema, chunk, key, chunks).await?).await?;
217        chunks += 1;
218    }
219    if chunks == 0 {
220        return Err(Some(ItzmaError::EmptyBatch));
221    }
222    Ok(())
223}
224
225async fn send(
226    tx: &tokio::sync::mpsc::Sender<Encoded>,
227    encoded: Encoded,
228) -> std::result::Result<(), Option<ItzmaError>> {
229    tx.send(encoded).await.map_err(|_| None)
230}
231
232/// Check one chunk and encode it on the compute pool; a keyed stream's
233/// chunk `n` is keyed `<key>#<n>`.
234async fn encode(
235    schema: &Schema,
236    chunk: DocColumns,
237    key: Option<&WriteKey>,
238    n: u64,
239) -> Result<Encoded> {
240    let rows = chunk.rows() as u64;
241    let sparse = chunk.has_sparse();
242    // A rough size: the vectors and a little for each row's id and
243    // attributes. It only decides whether to hand the work off.
244    let cost = Cost::Bytes(chunk.vectors().len() * 4 + chunk.rows() * 64);
245    let encode_key = key.map(|write| format!("{}#{n}", write.key));
246    let schema = schema.clone();
247    // The checks run on the pool too: a chunk's per-row checks (cosine norms
248    // among them) are as much work as its encoding.
249    let encoded = cpu::run(Lane::Query, cost, move || {
250        chunk.validate(&schema)?;
251        match encode_key {
252            None => wal_codec::encode_columns(&chunk, wal::MAX_BODY_BYTES).map(Object::Plain),
253            Some(key) => wal_codec::encode_columns_keyed(&chunk, wal::MAX_BODY_BYTES, &key)
254                .map(|object| Object::Keyed(key, object)),
255        }
256    })
257    .await?;
258    Ok(Encoded {
259        object: encoded,
260        rows,
261        sparse,
262    })
263}
264
265/// Put each encoded chunk, one at a time, and count what landed. Stops at
266/// the first error, which closes the channel and so stops the encoder.
267///
268/// A keyed retry looks for each chunk from `search_from` on, and moves that
269/// point to just past each chunk it lands or finds: a stream's chunks are in
270/// the WAL in order, so chunk `n + 1` is never before chunk `n`. The first
271/// chunk's search covers the WAL from where the caller says the first
272/// attempt started; every later one only what follows the chunk before it.
273async fn write_stage(
274    ns: &Namespace,
275    mut rx: tokio::sync::mpsc::Receiver<Encoded>,
276    mut search_from: Option<u64>,
277) -> (StreamReport, Result<()>) {
278    let mut report = StreamReport::default();
279    while let Some(chunk) = rx.recv().await {
280        let landed = match chunk.object {
281            Object::Plain(bytes) => ns.append_bytes(bytes, chunk.sparse).await,
282            Object::Keyed(key, object) => {
283                let write = WriteKey { key, search_from };
284                ns.append_bytes_keyed(&write, object, chunk.sparse).await
285            }
286        };
287        match landed {
288            Ok(seq) => {
289                search_from = search_from.map(|_| seq + 1);
290                report.first_seq.get_or_insert(seq);
291                report.last_seq = Some(seq);
292                report.rows += chunk.rows;
293                report.objects += 1;
294            }
295            Err(error) => return (report, Err(error)),
296        }
297    }
298    (report, Ok(()))
299}
300
301/// Cuts a stream of batches into chunks of about `target` encoded bytes.
302///
303/// Rows are added one at a time, and a row that would take the chunk past
304/// `target` starts the next chunk, unless the chunk is still empty (a row
305/// bigger than `target` is a chunk of its own). So where the chunks fall
306/// depends only on the rows, never on how the input was batched, which a
307/// keyed stream needs: a retry must cut the same chunks to find them by key.
308/// A row's size counts its sparse entry whenever the input has a sparse
309/// column, a slight over-estimate for a chunk where no row has one; the
310/// batches of one stream must therefore all have a sparse column or none.
311pub(crate) struct Chunker {
312    target: u64,
313    pending: Option<DocColumns>,
314    /// Whether the stream's batches have a sparse column, set by the first.
315    sparse: Option<bool>,
316    /// The body bytes `pending` would encode to, counts included.
317    bytes: u64,
318    scratch: Vec<u8>,
319}
320
321impl Chunker {
322    pub(crate) fn new(target: u64) -> Self {
323        Self {
324            target,
325            pending: None,
326            sparse: None,
327            bytes: COUNTS_LEN as u64,
328            scratch: Vec::new(),
329        }
330    }
331
332    /// Take `cols` in and return every chunk it completed, in order.
333    ///
334    /// # Errors
335    ///
336    /// [`ItzmaError::InvalidColumns`](crate::ItzmaError::InvalidColumns) if
337    /// `cols` does not have the columns of the batches before it.
338    pub(crate) fn push(&mut self, mut cols: DocColumns) -> Result<Vec<DocColumns>> {
339        // A row's size counts a sparse entry when the stream has a sparse
340        // column; a stream that switched would size rows by its batching.
341        let sparse = cols.sparse().is_some();
342        if *self.sparse.get_or_insert(sparse) != sparse {
343            return Err(ItzmaError::InvalidColumns(
344                "batches in one stream must all have a sparse column or none",
345            ));
346        }
347        let mut rows_in_chunk = self.pending.as_ref().map_or(0, DocColumns::rows);
348        let mut cuts = Vec::new();
349        for row in 0..cols.rows() {
350            let size = wal_codec::row_body_bytes(&cols, row, sparse, &mut self.scratch);
351            if rows_in_chunk > 0 && self.bytes + size > self.target {
352                cuts.push(row);
353                self.bytes = COUNTS_LEN as u64;
354                rows_in_chunk = 0;
355            }
356            self.bytes += size;
357            rows_in_chunk += 1;
358        }
359        // Cut from the back: each `split_off` then copies only its own piece,
360        // so a batch many times the target is copied about once. Cutting
361        // from the front copied the whole rest of the batch for every chunk
362        // and left each chunk holding the batch's capacity.
363        let mut pieces = Vec::with_capacity(cuts.len());
364        for &cut in cuts.iter().rev() {
365            pieces.push(cols.split_off(cut));
366        }
367        pieces.reverse();
368        cols.shrink_to_fit();
369        let mut done = Vec::with_capacity(cuts.len());
370        if cols.rows() > 0 {
371            self.add(cols)?;
372        }
373        for piece in pieces {
374            done.extend(self.pending.take());
375            self.pending = Some(piece);
376        }
377        Ok(done)
378    }
379
380    /// The last, partly filled chunk, if any rows are left.
381    pub(crate) fn finish(self) -> Option<DocColumns> {
382        self.pending
383    }
384
385    fn add(&mut self, cols: DocColumns) -> Result<()> {
386        match &mut self.pending {
387            Some(pending) => pending.append(cols),
388            None => {
389                self.pending = Some(cols);
390                Ok(())
391            }
392        }
393    }
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399    use crate::columns::{AttrColumn, DocColumns};
400    use crate::wal_codec::columns_body_size;
401
402    /// Rows `from..to` of a fixed table: ids and a text attribute of varied
403    /// lengths, so rows have different sizes.
404    fn rows(from: usize, to: usize) -> DocColumns {
405        let (mut ids, mut id_offsets) = (Vec::new(), vec![0u32]);
406        let (mut text, mut text_offsets) = (Vec::new(), vec![0u32]);
407        let mut vectors = Vec::new();
408        for i in from..to {
409            ids.extend_from_slice(format!("id-{i}-{}", "x".repeat(i % 37)).as_bytes());
410            id_offsets.push(ids.len() as u32);
411            text.extend_from_slice("t".repeat((i * 7) % 300).as_bytes());
412            text_offsets.push(text.len() as u32);
413            vectors.extend_from_slice(&[i as f32, 1.0, 2.0, 3.0]);
414        }
415        let n = to - from;
416        DocColumns::new(ids, id_offsets, vectors, 4)
417            .unwrap()
418            .with_attr(
419                "note",
420                AttrColumn::Text {
421                    valid: (from..to).map(|i| i % 5 != 0).collect(),
422                    bytes: text,
423                    offsets: text_offsets,
424                },
425            )
426            .unwrap()
427            .with_attr("n", AttrColumn::Null { rows: n })
428            .unwrap()
429    }
430
431    /// Feed `batches` through a chunker and return each chunk's ids.
432    fn chunk(target: u64, batches: Vec<DocColumns>) -> Vec<Vec<String>> {
433        let mut chunker = Chunker::new(target);
434        let mut out = Vec::new();
435        for batch in batches {
436            out.extend(chunker.push(batch).unwrap());
437        }
438        out.extend(chunker.finish());
439        out.iter()
440            .map(|c| (0..c.rows()).map(|r| c.id(r).to_string()).collect())
441            .collect()
442    }
443
444    const TOTAL: usize = 1_000;
445    const TARGET: u64 = 10 * 1024;
446
447    #[test]
448    fn chunks_do_not_depend_on_how_the_input_was_batched() {
449        let whole = chunk(TARGET, vec![rows(0, TOTAL)]);
450        let singles = chunk(TARGET, (0..TOTAL).map(|i| rows(i, i + 1)).collect());
451        let mut state = 7u64;
452        let mut ragged = Vec::new();
453        let mut at = 0;
454        while at < TOTAL {
455            state = state
456                .wrapping_mul(6_364_136_223_846_793_005)
457                .wrapping_add(1);
458            let next = (at + 1 + (state >> 33) as usize % 90).min(TOTAL);
459            ragged.push(rows(at, next));
460            at = next;
461        }
462        let ragged = chunk(TARGET, ragged);
463        assert!(whole.len() > 5, "{} chunks", whole.len());
464        assert_eq!(whole, singles);
465        assert_eq!(whole, ragged);
466        let all: Vec<String> = whole.concat();
467        assert_eq!(all.len(), TOTAL);
468    }
469
470    #[test]
471    fn every_chunk_stays_under_the_target_unless_it_is_one_row() {
472        let mut chunker = Chunker::new(TARGET);
473        let mut chunks = chunker.push(rows(0, TOTAL)).unwrap();
474        chunks.extend(chunker.finish());
475        for c in &chunks {
476            assert!(
477                columns_body_size(c) <= TARGET || c.rows() == 1,
478                "{} bytes in {} rows",
479                columns_body_size(c),
480                c.rows()
481            );
482        }
483    }
484
485    #[test]
486    fn a_row_bigger_than_the_target_is_its_own_chunk() {
487        let mut chunker = Chunker::new(64);
488        let mut chunks = chunker.push(rows(0, 3)).unwrap();
489        chunks.extend(chunker.finish());
490        assert_eq!(
491            chunks.iter().map(DocColumns::rows).collect::<Vec<_>>(),
492            [1, 1, 1]
493        );
494    }
495
496    #[test]
497    fn empty_batches_and_an_empty_stream_make_no_chunk() {
498        let mut chunker = Chunker::new(TARGET);
499        assert!(chunker.push(rows(0, 0)).unwrap().is_empty());
500        assert!(chunker.finish().is_none());
501    }
502
503    #[test]
504    fn append_rejects_other_columns() {
505        let mut a = rows(0, 2);
506        let other_dim = DocColumns::new(b"z".to_vec(), vec![0, 1], vec![1.0], 1).unwrap();
507        assert!(a.append(other_dim).is_err());
508        let fewer_columns = DocColumns::new(b"z".to_vec(), vec![0, 1], vec![1.0; 4], 4).unwrap();
509        assert!(a.append(fewer_columns).is_err());
510    }
511
512    #[test]
513    fn a_null_column_then_a_typed_one_appends() {
514        let typed = |from: usize, to: usize| {
515            let n = to - from;
516            let mut c = rows(from, to);
517            c = c
518                .without_attr("n")
519                .with_attr(
520                    "n",
521                    AttrColumn::I64 {
522                        valid: vec![true; n],
523                        values: (from..to).map(|i| i as i64).collect(),
524                    },
525                )
526                .unwrap();
527            c
528        };
529        let mut nulls_first = rows(0, 2);
530        nulls_first.append(typed(2, 4)).unwrap();
531        let mut typed_first = typed(0, 2);
532        typed_first.append(rows(2, 4)).unwrap();
533        let kinds = |c: &DocColumns| {
534            c.attrs()
535                .iter()
536                .find(|(name, _)| name == "n")
537                .map(|(_, col)| (0..4).map(|r| col.is_null(r)).collect::<Vec<_>>())
538                .unwrap()
539        };
540        assert_eq!(kinds(&nulls_first), [true, true, false, false]);
541        assert_eq!(kinds(&typed_first), [false, false, true, true]);
542    }
543
544    #[test]
545    fn split_off_then_append_restores_the_batch() {
546        let whole = rows(0, 50);
547        for at in [0, 1, 17, 49, 50] {
548            let mut head = whole.clone();
549            let tail = head.split_off(at);
550            assert_eq!((head.rows(), tail.rows()), (at, 50 - at));
551            head.append(tail).unwrap();
552            assert_eq!(head, whole, "split at {at}");
553        }
554    }
555}