1use 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
16pub const DEFAULT_STREAM_TARGET_BYTES: usize = wal::MAX_BODY_BYTES / 2;
19
20pub const DEFAULT_STREAM_DEPTH: usize = 2;
22
23const MAX_STREAM_KEY: usize = 107;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[non_exhaustive]
30pub struct StreamOptions {
31 pub target_bytes: usize,
35 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 #[must_use]
53 pub fn target_bytes(mut self, bytes: usize) -> Self {
54 self.target_bytes = bytes;
55 self
56 }
57
58 #[must_use]
60 pub fn depth(mut self, depth: usize) -> Self {
61 self.depth = depth;
62 self
63 }
64
65 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
89#[non_exhaustive]
90pub struct StreamReport {
91 pub first_seq: Option<u64>,
93 pub last_seq: Option<u64>,
95 pub rows: u64,
98 pub objects: u64,
100}
101
102#[derive(Debug)]
106pub struct StreamError {
107 pub landed: StreamReport,
109 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
129struct Encoded {
131 object: Object,
132 rows: u64,
133 sparse: bool,
134}
135
136enum Object {
137 Plain(Bytes),
138 Keyed(String, wal_codec::Keyed),
140}
141
142pub(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 match (written, encoded) {
176 (Err(error), _) | (Ok(()), Err(Some(error))) => Err(StreamError { landed, error }),
177 _ => Ok(landed),
178 }
179}
180
181async 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 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
232async 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 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 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
265async 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
301pub(crate) struct Chunker {
312 target: u64,
313 pending: Option<DocColumns>,
314 sparse: Option<bool>,
316 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 pub(crate) fn push(&mut self, mut cols: DocColumns) -> Result<Vec<DocColumns>> {
339 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 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 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 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 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}