Skip to main content

itzma_core/scan/
mod.rs

1//! Reading a namespace in id order: [`Namespace::scan`](crate::Namespace::scan)
2//! and the k-way merge it shares with
3//! [`Namespace::filter`](crate::Namespace::filter).
4//!
5//! A scan loads the manifest once, folds the WAL tail once, opens every live
6//! segment once and then hands out batches from one merge that it keeps
7//! between them. Nothing is reopened per batch, which is the difference from
8//! paging `filter`. The stream is a producer future and a channel polled
9//! together inside [`ScanStream`], so no task is spawned: work advances only
10//! while the stream is polled.
11
12pub(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
45/// Reloads of the manifest in a row without a batch handed out in between,
46/// before a stale read is returned as an error.
47pub(crate) const MAX_RELOADS: u32 = 3;
48
49/// Rows per batch when none is asked for.
50pub const DEFAULT_SCAN_BATCH_ROWS: usize = 8_192;
51/// The most rows one batch may ask for.
52pub const MAX_SCAN_BATCH_ROWS: usize = 65_536;
53
54/// Settings for [`Namespace::scan`](crate::Namespace::scan).
55#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
56#[serde(default)]
57#[non_exhaustive]
58pub struct ScanOptions {
59    /// Return only documents that match. Checked against the schema before
60    /// any storage call.
61    pub filter: Option<Predicate>,
62    /// What each batch carries besides ids.
63    pub columns: Columns,
64    /// The most rows per batch, 1 to [`MAX_SCAN_BATCH_ROWS`]. Default
65    /// [`DEFAULT_SCAN_BATCH_ROWS`].
66    pub batch_rows: usize,
67    /// Start after this id, in byte order. Pass the last batch's
68    /// [`ScanBatch::last_id`] to resume a scan.
69    pub after: Option<String>,
70    /// Stop after this id, which is included, in byte order. With
71    /// [`after`](Self::after) it bounds a range scan; an `until` at or below
72    /// `after` is an empty scan.
73    pub until: Option<String>,
74    /// Stop after this many rows in all.
75    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    /// Set [`filter`](Self::filter).
93    #[must_use]
94    pub fn filter(mut self, predicate: Predicate) -> Self {
95        self.filter = Some(predicate);
96        self
97    }
98
99    /// Set [`columns`](Self::columns).
100    #[must_use]
101    pub fn columns(mut self, columns: Columns) -> Self {
102        self.columns = columns;
103        self
104    }
105
106    /// Set [`batch_rows`](Self::batch_rows).
107    #[must_use]
108    pub fn batch_rows(mut self, rows: usize) -> Self {
109        self.batch_rows = rows;
110        self
111    }
112
113    /// Set [`after`](Self::after).
114    #[must_use]
115    pub fn after(mut self, id: impl Into<String>) -> Self {
116        self.after = Some(id.into());
117        self
118    }
119
120    /// Set [`until`](Self::until).
121    #[must_use]
122    pub fn until(mut self, id: impl Into<String>) -> Self {
123        self.until = Some(id.into());
124        self
125    }
126
127    /// Set [`after`](Self::after) and [`until`](Self::until) from one of
128    /// [`Namespace::scan_splits`](crate::Namespace::scan_splits)'s ranges.
129    #[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    /// Set [`limit`](Self::limit).
137    #[must_use]
138    pub fn limit(mut self, rows: u64) -> Self {
139        self.limit = Some(rows);
140        self
141    }
142}
143
144/// What a scan's batches carry besides ids, which are always there.
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146#[serde(default)]
147#[non_exhaustive]
148pub struct Columns {
149    /// The vectors, as one [`Matrix`] per batch. Default `true`.
150    pub vectors: bool,
151    /// Which attributes. Default [`AttrColumns::All`].
152    pub attrs: AttrColumns,
153    /// The sparse vectors, `None` for a document without one.
154    /// Default `true`.
155    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    /// Ids and nothing else.
170    #[must_use]
171    pub fn ids_only() -> Self {
172        Self {
173            vectors: false,
174            attrs: AttrColumns::None,
175            sparse: false,
176        }
177    }
178
179    /// Set [`vectors`](Self::vectors).
180    #[must_use]
181    pub fn vectors(mut self, on: bool) -> Self {
182        self.vectors = on;
183        self
184    }
185
186    /// Set [`sparse`](Self::sparse).
187    #[must_use]
188    pub fn sparse(mut self, on: bool) -> Self {
189        self.sparse = on;
190        self
191    }
192
193    /// Set [`attrs`](Self::attrs).
194    #[must_use]
195    pub fn attrs(mut self, attrs: AttrColumns) -> Self {
196        self.attrs = attrs;
197        self
198    }
199}
200
201/// Which attributes a scan returns.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
203#[non_exhaustive]
204pub enum AttrColumns {
205    /// None: [`ScanBatch::attrs`] is `None`.
206    None,
207    /// Every attribute, exactly as stored.
208    #[default]
209    All,
210    /// Only these declared fields. A row's attribute object keeps just these
211    /// keys (an object with none of them comes back empty), and a row with no
212    /// attributes stays `None`. Refused on a namespace without an attribute
213    /// schema, and for a field the schema does not declare.
214    Fields(Vec<String>),
215}
216
217/// One of the ranges [`Namespace::scan_splits`](crate::Namespace::scan_splits)
218/// proposes: the ids above `after` and up to and including `until`, either
219/// end unbounded when `None`. Pass it to [`ScanOptions::range`].
220#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
221#[non_exhaustive]
222pub struct ScanRange {
223    /// Ids strictly above this one, or from the first when `None`.
224    pub after: Option<String>,
225    /// Ids up to and including this one, or to the last when `None`.
226    pub until: Option<String>,
227}
228
229/// One batch of a scan, in ascending id order.
230#[derive(Debug, Clone, PartialEq)]
231#[non_exhaustive]
232pub struct ScanBatch {
233    /// The documents' ids.
234    pub ids: Vec<String>,
235    /// The documents' vectors, row `i` for `ids[i]`. `None` when
236    /// [`Columns::vectors`] is off.
237    pub vectors: Option<Matrix>,
238    /// Each document's attributes, `None` for a document without any. `None`
239    /// as a whole when [`Columns::attrs`] is [`AttrColumns::None`].
240    pub attrs: Option<Vec<Option<Value>>>,
241    /// Each document's sparse vector, `None` for a document without one.
242    /// `None` as a whole when [`Columns::sparse`] is off.
243    pub sparse: Option<Vec<Option<SparseVector>>>,
244    /// The last id of the batch: pass it as [`ScanOptions::after`] to resume.
245    pub last_id: String,
246}
247
248/// The batches of a scan; see [`Namespace::scan`](crate::Namespace::scan).
249///
250/// Dropping it stops the scan and every read in flight.
251pub 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
289/// What a scan owns, so its stream can outlive the handle's borrow.
290pub(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
299/// Refuse options that cannot run, before any storage call. The filter itself
300/// is checked by the caller, the same way a query's is.
301pub(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
310/// Refuse a projection naming a field the schema does not declare
311/// (`UnknownAttr`), or any field on a free-form namespace (`InvalidQuery`).
312pub(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
331/// The stream of a validated scan.
332pub(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        // The receiver may be gone, and then nobody is left to tell.
340        let _ = tx.send(Err(err)).await;
341    }
342}
343
344/// How far the scan has got, across reloads.
345struct Progress {
346    after: Option<String>,
347    left: u64,
348    /// Whether a batch went out since the last reload.
349    sent: bool,
350}
351
352/// Why a pass over one manifest stopped.
353enum Stop {
354    /// The end, the limit, or a consumer that went away.
355    Done,
356    /// A stale read: the manifest may have moved.
357    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
398/// `err` came from reading against `stale`. A scan is not a snapshot, so it
399/// carries on from a newer manifest. A stale read with a moved manifest gives
400/// the fresh one, and the scan carries on after its last row. Anything else,
401/// an unmoved manifest (the object really is gone), or [`MAX_RELOADS`]
402/// reloads without a batch handed out in between, returns `err`.
403async 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
420/// Stream batches from `manifest`, with the whole WAL tail folded, until the
421/// end, the limit, or a stale read.
422async 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
478/// The WAL past `folded`, folded into one layer on the maintenance lane.
479async 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    /// A namespace whose manifest moved after `stale` was loaded, and a
581    /// stale-read error to hand `reload`.
582    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, &current, 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}