1pub(crate) mod batch;
13pub(crate) mod merge;
14pub(crate) mod split;
15
16pub use split::MAX_SCAN_SPLITS;
17
18use std::fmt;
19use std::future::Future;
20use std::pin::Pin;
21use std::sync::Arc;
22use std::task::{Context, Poll};
23
24use futures::channel::mpsc;
25use futures::{SinkExt, Stream, StreamExt};
26use object_store::ObjectStore;
27use serde::{Deserialize, Serialize};
28use serde_json::Value;
29
30use crate::budget::ReadBudget;
31use crate::cpu::Lane;
32use crate::document::{Schema, SparseVector};
33use crate::error::{ItzmaError, Result};
34use crate::fetch::FetchPolicy;
35use crate::layer::{self, Layer};
36use crate::manifest::Manifest;
37use crate::namespace::is_stale_read;
38use crate::predicate::Predicate;
39use crate::segment::Matrix;
40use crate::{view, wal};
41
42use batch::{BatchPlan, next_batch};
43use merge::{Merge, Mode, Open, window_bytes};
44
45pub(crate) const MAX_RELOADS: u32 = 3;
48
49pub const DEFAULT_SCAN_BATCH_ROWS: usize = 8_192;
51pub const MAX_SCAN_BATCH_ROWS: usize = 65_536;
53
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
56#[serde(default)]
57#[non_exhaustive]
58pub struct ScanOptions {
59 pub filter: Option<Predicate>,
62 pub columns: Columns,
64 pub batch_rows: usize,
67 pub after: Option<String>,
70 pub until: Option<String>,
74 pub limit: Option<u64>,
76}
77
78impl Default for ScanOptions {
79 fn default() -> Self {
80 Self {
81 filter: None,
82 columns: Columns::default(),
83 batch_rows: DEFAULT_SCAN_BATCH_ROWS,
84 after: None,
85 until: None,
86 limit: None,
87 }
88 }
89}
90
91impl ScanOptions {
92 #[must_use]
94 pub fn filter(mut self, predicate: Predicate) -> Self {
95 self.filter = Some(predicate);
96 self
97 }
98
99 #[must_use]
101 pub fn columns(mut self, columns: Columns) -> Self {
102 self.columns = columns;
103 self
104 }
105
106 #[must_use]
108 pub fn batch_rows(mut self, rows: usize) -> Self {
109 self.batch_rows = rows;
110 self
111 }
112
113 #[must_use]
115 pub fn after(mut self, id: impl Into<String>) -> Self {
116 self.after = Some(id.into());
117 self
118 }
119
120 #[must_use]
122 pub fn until(mut self, id: impl Into<String>) -> Self {
123 self.until = Some(id.into());
124 self
125 }
126
127 #[must_use]
130 pub fn range(mut self, range: &ScanRange) -> Self {
131 self.after.clone_from(&range.after);
132 self.until.clone_from(&range.until);
133 self
134 }
135
136 #[must_use]
138 pub fn limit(mut self, rows: u64) -> Self {
139 self.limit = Some(rows);
140 self
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146#[serde(default)]
147#[non_exhaustive]
148pub struct Columns {
149 pub vectors: bool,
151 pub attrs: AttrColumns,
153 pub sparse: bool,
156}
157
158impl Default for Columns {
159 fn default() -> Self {
160 Self {
161 vectors: true,
162 attrs: AttrColumns::All,
163 sparse: true,
164 }
165 }
166}
167
168impl Columns {
169 #[must_use]
171 pub fn ids_only() -> Self {
172 Self {
173 vectors: false,
174 attrs: AttrColumns::None,
175 sparse: false,
176 }
177 }
178
179 #[must_use]
181 pub fn vectors(mut self, on: bool) -> Self {
182 self.vectors = on;
183 self
184 }
185
186 #[must_use]
188 pub fn sparse(mut self, on: bool) -> Self {
189 self.sparse = on;
190 self
191 }
192
193 #[must_use]
195 pub fn attrs(mut self, attrs: AttrColumns) -> Self {
196 self.attrs = attrs;
197 self
198 }
199}
200
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
203#[non_exhaustive]
204pub enum AttrColumns {
205 None,
207 #[default]
209 All,
210 Fields(Vec<String>),
215}
216
217#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
221#[non_exhaustive]
222pub struct ScanRange {
223 pub after: Option<String>,
225 pub until: Option<String>,
227}
228
229#[derive(Debug, Clone, PartialEq)]
231#[non_exhaustive]
232pub struct ScanBatch {
233 pub ids: Vec<String>,
235 pub vectors: Option<Matrix>,
238 pub attrs: Option<Vec<Option<Value>>>,
241 pub sparse: Option<Vec<Option<SparseVector>>>,
244 pub last_id: String,
246}
247
248pub struct ScanStream {
252 producer: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
253 batches: mpsc::Receiver<Result<ScanBatch>>,
254}
255
256impl fmt::Debug for ScanStream {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 f.debug_struct("ScanStream")
259 .field("running", &self.producer.is_some())
260 .finish_non_exhaustive()
261 }
262}
263
264impl ScanStream {
265 fn new(
266 producer: impl Future<Output = ()> + Send + 'static,
267 batches: mpsc::Receiver<Result<ScanBatch>>,
268 ) -> Self {
269 Self {
270 producer: Some(Box::pin(producer)),
271 batches,
272 }
273 }
274}
275
276impl Stream for ScanStream {
277 type Item = Result<ScanBatch>;
278
279 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
280 if let Some(producer) = self.producer.as_mut() {
281 if producer.as_mut().poll(cx).is_ready() {
282 self.producer = None;
283 }
284 }
285 self.batches.poll_next_unpin(cx)
286 }
287}
288
289pub(crate) struct Owned {
291 pub(crate) store: Arc<dyn ObjectStore>,
292 pub(crate) namespace: String,
293 pub(crate) schema: Schema,
294 pub(crate) policy: FetchPolicy,
295 pub(crate) read_budget: u64,
296 pub(crate) options: ScanOptions,
297}
298
299pub(crate) fn validate(options: &ScanOptions, schema: &Schema) -> Result<()> {
302 if !(1..=MAX_SCAN_BATCH_ROWS).contains(&options.batch_rows) {
303 return Err(ItzmaError::InvalidQuery(
304 "scan batch_rows must be between 1 and 65536",
305 ));
306 }
307 check_projection(&options.columns.attrs, &schema.attrs)
308}
309
310pub(crate) fn check_projection(
313 attrs: &AttrColumns,
314 schema: &crate::attrs::AttrSchema,
315) -> Result<()> {
316 if let AttrColumns::Fields(names) = attrs {
317 if schema.is_free_form() {
318 return Err(ItzmaError::InvalidQuery(
319 "this namespace has no attribute schema, so there are no fields to project",
320 ));
321 }
322 if let Some(name) = names.iter().find(|n| schema.get(n).is_none()) {
323 return Err(ItzmaError::UnknownAttr {
324 field: name.clone(),
325 });
326 }
327 }
328 Ok(())
329}
330
331pub(crate) fn start(owned: Owned) -> ScanStream {
333 let (tx, rx) = mpsc::channel(0);
334 ScanStream::new(produce(owned, tx), rx)
335}
336
337async fn produce(owned: Owned, mut tx: mpsc::Sender<Result<ScanBatch>>) {
338 if let Err(err) = run(&owned, &mut tx).await {
339 let _ = tx.send(Err(err)).await;
341 }
342}
343
344struct Progress {
346 after: Option<String>,
347 left: u64,
348 sent: bool,
350}
351
352enum Stop {
354 Done,
356 Stale(ItzmaError),
358}
359
360async fn run(o: &Owned, tx: &mut mpsc::Sender<Result<ScanBatch>>) -> Result<()> {
361 let budget = ReadBudget::new(o.read_budget);
362 let plan = Arc::new(BatchPlan {
363 predicate: o.options.filter.clone(),
364 attrs: o.options.columns.attrs.clone(),
365 vectors: o.options.columns.vectors,
366 sparse: o.options.columns.sparse,
367 dim: o.schema.dim,
368 lane: Lane::Maintenance,
369 });
370 if o.options.limit == Some(0) {
371 return Ok(());
372 }
373 if let (Some(after), Some(until)) = (&o.options.after, &o.options.until) {
374 if after >= until {
375 return Ok(());
376 }
377 }
378 let mut progress = Progress {
379 after: o.options.after.clone(),
380 left: o.options.limit.unwrap_or(u64::MAX),
381 sent: false,
382 };
383 let mut manifest = view::load_checked(&*o.store, &o.namespace).await?;
384 let mut reloads = 0;
385 loop {
386 match pass(o, &manifest, &budget, &plan, &mut progress, tx).await? {
387 Stop::Done => return Ok(()),
388 Stop::Stale(err) => {
389 if std::mem::take(&mut progress.sent) {
390 reloads = 0;
391 }
392 manifest = reload(o, &manifest, err, &mut reloads).await?;
393 }
394 }
395 }
396}
397
398async fn reload(
404 o: &Owned,
405 stale: &Manifest,
406 err: ItzmaError,
407 reloads: &mut u32,
408) -> Result<Manifest> {
409 if !is_stale_read(&err) || *reloads >= MAX_RELOADS {
410 return Err(err);
411 }
412 let fresh = view::load_checked(&*o.store, &o.namespace).await?;
413 if fresh == *stale {
414 return Err(err);
415 }
416 *reloads += 1;
417 Ok(fresh)
418}
419
420async fn pass(
423 o: &Owned,
424 manifest: &Manifest,
425 budget: &ReadBudget,
426 plan: &Arc<BatchPlan>,
427 progress: &mut Progress,
428 tx: &mut mpsc::Sender<Result<ScanBatch>>,
429) -> Result<Stop> {
430 if progress.left == 0 {
431 return Ok(Stop::Done);
432 }
433 budget.renew();
434 let after = progress.after.clone();
435 let open = Open {
436 store: &*o.store,
437 namespace: &o.namespace,
438 dim: o.schema.dim,
439 budget,
440 policy: &o.policy,
441 attr_indexes: &manifest.attr_indexes,
442 attrs: &o.schema.attrs,
443 decoded: None,
444 predicate: o.options.filter.as_ref(),
445 after: after.as_deref(),
446 until: o.options.until.as_deref(),
447 mode: Mode::Forward {
448 window_bytes: window_bytes(o.read_budget, manifest.live_segments.len() + 1),
449 },
450 with_sparse: o.options.columns.sparse,
451 };
452 let tail = read_tail(&*o.store, &o.namespace, manifest.wal_folded_through, budget);
453 let mut merge = match Merge::open(&open, &manifest.live_segments, tail).await {
454 Ok(merge) => merge,
455 Err(err) if is_stale_read(&err) => return Ok(Stop::Stale(err)),
456 Err(err) => return Err(err),
457 };
458 loop {
459 let want = usize::try_from(progress.left)
460 .unwrap_or(usize::MAX)
461 .min(o.options.batch_rows);
462 match next_batch(&mut merge, want, plan, budget).await {
463 Ok(None) => return Ok(Stop::Done),
464 Ok(Some(batch)) => {
465 progress.left -= batch.ids.len() as u64;
466 progress.after = Some(batch.last_id.clone());
467 progress.sent = true;
468 if tx.send(Ok(batch)).await.is_err() || progress.left == 0 {
469 return Ok(Stop::Done);
470 }
471 }
472 Err(err) if is_stale_read(&err) => return Ok(Stop::Stale(err)),
473 Err(err) => return Err(err),
474 }
475 }
476}
477
478async fn read_tail(
480 store: &dyn ObjectStore,
481 namespace: &str,
482 folded: u64,
483 budget: &ReadBudget,
484) -> Result<Arc<Layer>> {
485 let log = wal::stream_log(store, namespace, folded, budget, Lane::Maintenance).await?;
486 let (layer, _) = layer::fold_log(log).await?;
487 Ok(Arc::new(layer))
488}
489
490#[cfg(test)]
491mod tests {
492 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
493
494 use futures::FutureExt;
495
496 use super::*;
497
498 fn batch(id: &str) -> ScanBatch {
499 ScanBatch {
500 ids: vec![id.to_string()],
501 vectors: None,
502 attrs: None,
503 sparse: None,
504 last_id: id.to_string(),
505 }
506 }
507
508 #[tokio::test]
509 async fn the_producer_advances_only_when_polled() {
510 let sent = Arc::new(AtomicUsize::new(0));
511 let (mut tx, rx) = mpsc::channel(0);
512 let counter = Arc::clone(&sent);
513 let mut stream = ScanStream::new(
514 async move {
515 for i in 0..10 {
516 counter.fetch_add(1, Ordering::SeqCst);
517 if tx.send(Ok(batch(&format!("{i}")))).await.is_err() {
518 return;
519 }
520 }
521 },
522 rx,
523 );
524 tokio::task::yield_now().await;
525 assert_eq!(sent.load(Ordering::SeqCst), 0, "nothing runs unpolled");
526 let first = stream.next().await.expect("a batch").expect("ok");
527 assert_eq!(first.ids, ["0"]);
528 assert!(
529 sent.load(Ordering::SeqCst) <= 2,
530 "one sent, one at most buffered"
531 );
532 let rest: Vec<_> = stream.collect().await;
533 assert_eq!(rest.len(), 9);
534 }
535
536 #[tokio::test]
537 async fn dropping_the_stream_drops_the_producer() {
538 struct Guard(Arc<AtomicBool>);
539 impl Drop for Guard {
540 fn drop(&mut self) {
541 self.0.store(true, Ordering::SeqCst);
542 }
543 }
544 let dropped = Arc::new(AtomicBool::new(false));
545 let guard = Guard(Arc::clone(&dropped));
546 let (mut tx, rx) = mpsc::channel(0);
547 let mut stream = ScanStream::new(
548 async move {
549 let _guard = guard;
550 for i in 0.. {
551 if tx.send(Ok(batch(&format!("{i}")))).await.is_err() {
552 return;
553 }
554 }
555 },
556 rx,
557 );
558 assert!(stream.next().now_or_never().flatten().is_some());
559 assert!(!dropped.load(Ordering::SeqCst));
560 drop(stream);
561 assert!(dropped.load(Ordering::SeqCst));
562 }
563
564 #[tokio::test]
565 async fn an_error_ends_the_stream() {
566 let (mut tx, rx) = mpsc::channel(0);
567 let mut stream = ScanStream::new(
568 async move {
569 let _ = tx.send(Ok(batch("a"))).await;
570 let _ = tx.send(Err(ItzmaError::InvalidQuery("boom"))).await;
571 },
572 rx,
573 );
574 assert!(stream.next().await.expect("item").is_ok());
575 assert!(stream.next().await.expect("item").is_err());
576 assert!(stream.next().await.is_none());
577 assert!(stream.next().await.is_none());
578 }
579
580 async fn moved() -> (Owned, Manifest, ItzmaError) {
583 let store: Arc<dyn ObjectStore> = Arc::new(object_store::memory::InMemory::new());
584 let schema = Schema::new(1, crate::Metric::L2);
585 let ns = crate::Namespace::create(Arc::clone(&store), "docs", schema.clone())
586 .await
587 .expect("create");
588 let stale = view::load_checked(&*store, "docs").await.expect("load");
589 let doc = crate::Document {
590 id: "a".into(),
591 vector: vec![0.0],
592 attrs: None,
593 sparse: None,
594 };
595 ns.upsert(vec![doc]).await.expect("upsert");
596 ns.compact(&crate::CompactionOptions::default())
597 .await
598 .expect("compact");
599 let owned = Owned {
600 store,
601 namespace: "docs".into(),
602 schema,
603 policy: FetchPolicy::local(),
604 read_budget: u64::MAX,
605 options: ScanOptions::default(),
606 };
607 let err = crate::segment::missing(&crate::segment::segment_path("docs", "gone"));
608 (owned, stale, err)
609 }
610
611 #[tokio::test]
612 async fn a_moved_manifest_is_reloaded_until_the_cap() {
613 let (owned, stale, err) = moved().await;
614 let mut reloads = 0;
615 let fresh = reload(&owned, &stale, err, &mut reloads)
616 .await
617 .expect("reloaded");
618 assert_ne!(fresh, stale);
619 assert_eq!(reloads, 1);
620
621 let (owned, stale, err) = moved().await;
622 let mut reloads = MAX_RELOADS;
623 let err = reload(&owned, &stale, err, &mut reloads)
624 .await
625 .expect_err("capped");
626 assert!(crate::segment::is_missing(&err), "{err:?}");
627 assert_eq!(reloads, MAX_RELOADS);
628 }
629
630 #[tokio::test]
631 async fn an_unmoved_manifest_or_another_error_is_returned() {
632 let (owned, stale, _) = moved().await;
633 let current = view::load_checked(&*owned.store, "docs")
634 .await
635 .expect("load");
636 let mut reloads = 0;
637 let missing = crate::segment::missing(&crate::segment::segment_path("docs", "gone"));
638 let err = reload(&owned, ¤t, missing, &mut reloads)
639 .await
640 .expect_err("unmoved");
641 assert!(crate::segment::is_missing(&err), "{err:?}");
642 let other = ItzmaError::InvalidQuery("not stale");
643 let err = reload(&owned, &stale, other, &mut reloads)
644 .await
645 .expect_err("not stale");
646 assert!(matches!(err, ItzmaError::InvalidQuery(_)));
647 assert_eq!(reloads, 0);
648 }
649}