pub(crate) mod batch;
pub(crate) mod merge;
pub(crate) mod split;
pub use split::MAX_SCAN_SPLITS;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use futures::channel::mpsc;
use futures::{SinkExt, Stream, StreamExt};
use object_store::ObjectStore;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::budget::ReadBudget;
use crate::cpu::Lane;
use crate::document::{Schema, SparseVector};
use crate::error::{ItzmaError, Result};
use crate::fetch::FetchPolicy;
use crate::layer::{self, Layer};
use crate::manifest::Manifest;
use crate::namespace::is_stale_read;
use crate::predicate::Predicate;
use crate::segment::Matrix;
use crate::{view, wal};
use batch::{BatchPlan, next_batch};
use merge::{Merge, Mode, Open, window_bytes};
pub(crate) const MAX_RELOADS: u32 = 3;
pub const DEFAULT_SCAN_BATCH_ROWS: usize = 8_192;
pub const MAX_SCAN_BATCH_ROWS: usize = 65_536;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct ScanOptions {
pub filter: Option<Predicate>,
pub columns: Columns,
pub batch_rows: usize,
pub after: Option<String>,
pub until: Option<String>,
pub limit: Option<u64>,
}
impl Default for ScanOptions {
fn default() -> Self {
Self {
filter: None,
columns: Columns::default(),
batch_rows: DEFAULT_SCAN_BATCH_ROWS,
after: None,
until: None,
limit: None,
}
}
}
impl ScanOptions {
#[must_use]
pub fn filter(mut self, predicate: Predicate) -> Self {
self.filter = Some(predicate);
self
}
#[must_use]
pub fn columns(mut self, columns: Columns) -> Self {
self.columns = columns;
self
}
#[must_use]
pub fn batch_rows(mut self, rows: usize) -> Self {
self.batch_rows = rows;
self
}
#[must_use]
pub fn after(mut self, id: impl Into<String>) -> Self {
self.after = Some(id.into());
self
}
#[must_use]
pub fn until(mut self, id: impl Into<String>) -> Self {
self.until = Some(id.into());
self
}
#[must_use]
pub fn range(mut self, range: &ScanRange) -> Self {
self.after.clone_from(&range.after);
self.until.clone_from(&range.until);
self
}
#[must_use]
pub fn limit(mut self, rows: u64) -> Self {
self.limit = Some(rows);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct Columns {
pub vectors: bool,
pub attrs: AttrColumns,
pub sparse: bool,
}
impl Default for Columns {
fn default() -> Self {
Self {
vectors: true,
attrs: AttrColumns::All,
sparse: true,
}
}
}
impl Columns {
#[must_use]
pub fn ids_only() -> Self {
Self {
vectors: false,
attrs: AttrColumns::None,
sparse: false,
}
}
#[must_use]
pub fn vectors(mut self, on: bool) -> Self {
self.vectors = on;
self
}
#[must_use]
pub fn sparse(mut self, on: bool) -> Self {
self.sparse = on;
self
}
#[must_use]
pub fn attrs(mut self, attrs: AttrColumns) -> Self {
self.attrs = attrs;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub enum AttrColumns {
None,
#[default]
All,
Fields(Vec<String>),
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ScanRange {
pub after: Option<String>,
pub until: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ScanBatch {
pub ids: Vec<String>,
pub vectors: Option<Matrix>,
pub attrs: Option<Vec<Option<Value>>>,
pub sparse: Option<Vec<Option<SparseVector>>>,
pub last_id: String,
}
pub struct ScanStream {
producer: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
batches: mpsc::Receiver<Result<ScanBatch>>,
}
impl fmt::Debug for ScanStream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ScanStream")
.field("running", &self.producer.is_some())
.finish_non_exhaustive()
}
}
impl ScanStream {
fn new(
producer: impl Future<Output = ()> + Send + 'static,
batches: mpsc::Receiver<Result<ScanBatch>>,
) -> Self {
Self {
producer: Some(Box::pin(producer)),
batches,
}
}
}
impl Stream for ScanStream {
type Item = Result<ScanBatch>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if let Some(producer) = self.producer.as_mut() {
if producer.as_mut().poll(cx).is_ready() {
self.producer = None;
}
}
self.batches.poll_next_unpin(cx)
}
}
pub(crate) struct Owned {
pub(crate) store: Arc<dyn ObjectStore>,
pub(crate) namespace: String,
pub(crate) schema: Schema,
pub(crate) policy: FetchPolicy,
pub(crate) read_budget: u64,
pub(crate) options: ScanOptions,
}
pub(crate) fn validate(options: &ScanOptions, schema: &Schema) -> Result<()> {
if !(1..=MAX_SCAN_BATCH_ROWS).contains(&options.batch_rows) {
return Err(ItzmaError::InvalidQuery(
"scan batch_rows must be between 1 and 65536",
));
}
check_projection(&options.columns.attrs, &schema.attrs)
}
pub(crate) fn check_projection(
attrs: &AttrColumns,
schema: &crate::attrs::AttrSchema,
) -> Result<()> {
if let AttrColumns::Fields(names) = attrs {
if schema.is_free_form() {
return Err(ItzmaError::InvalidQuery(
"this namespace has no attribute schema, so there are no fields to project",
));
}
if let Some(name) = names.iter().find(|n| schema.get(n).is_none()) {
return Err(ItzmaError::UnknownAttr {
field: name.clone(),
});
}
}
Ok(())
}
pub(crate) fn start(owned: Owned) -> ScanStream {
let (tx, rx) = mpsc::channel(0);
ScanStream::new(produce(owned, tx), rx)
}
async fn produce(owned: Owned, mut tx: mpsc::Sender<Result<ScanBatch>>) {
if let Err(err) = run(&owned, &mut tx).await {
let _ = tx.send(Err(err)).await;
}
}
struct Progress {
after: Option<String>,
left: u64,
sent: bool,
}
enum Stop {
Done,
Stale(ItzmaError),
}
async fn run(o: &Owned, tx: &mut mpsc::Sender<Result<ScanBatch>>) -> Result<()> {
let budget = ReadBudget::new(o.read_budget);
let plan = Arc::new(BatchPlan {
predicate: o.options.filter.clone(),
attrs: o.options.columns.attrs.clone(),
vectors: o.options.columns.vectors,
sparse: o.options.columns.sparse,
dim: o.schema.dim,
lane: Lane::Maintenance,
});
if o.options.limit == Some(0) {
return Ok(());
}
if let (Some(after), Some(until)) = (&o.options.after, &o.options.until) {
if after >= until {
return Ok(());
}
}
let mut progress = Progress {
after: o.options.after.clone(),
left: o.options.limit.unwrap_or(u64::MAX),
sent: false,
};
let mut manifest = view::load_checked(&*o.store, &o.namespace).await?;
let mut reloads = 0;
loop {
match pass(o, &manifest, &budget, &plan, &mut progress, tx).await? {
Stop::Done => return Ok(()),
Stop::Stale(err) => {
if std::mem::take(&mut progress.sent) {
reloads = 0;
}
manifest = reload(o, &manifest, err, &mut reloads).await?;
}
}
}
}
async fn reload(
o: &Owned,
stale: &Manifest,
err: ItzmaError,
reloads: &mut u32,
) -> Result<Manifest> {
if !is_stale_read(&err) || *reloads >= MAX_RELOADS {
return Err(err);
}
let fresh = view::load_checked(&*o.store, &o.namespace).await?;
if fresh == *stale {
return Err(err);
}
*reloads += 1;
Ok(fresh)
}
async fn pass(
o: &Owned,
manifest: &Manifest,
budget: &ReadBudget,
plan: &Arc<BatchPlan>,
progress: &mut Progress,
tx: &mut mpsc::Sender<Result<ScanBatch>>,
) -> Result<Stop> {
if progress.left == 0 {
return Ok(Stop::Done);
}
budget.renew();
let after = progress.after.clone();
let open = Open {
store: &*o.store,
namespace: &o.namespace,
dim: o.schema.dim,
budget,
policy: &o.policy,
attr_indexes: &manifest.attr_indexes,
attrs: &o.schema.attrs,
decoded: None,
predicate: o.options.filter.as_ref(),
after: after.as_deref(),
until: o.options.until.as_deref(),
mode: Mode::Forward {
window_bytes: window_bytes(o.read_budget, manifest.live_segments.len() + 1),
},
with_sparse: o.options.columns.sparse,
};
let tail = read_tail(&*o.store, &o.namespace, manifest.wal_folded_through, budget);
let mut merge = match Merge::open(&open, &manifest.live_segments, tail).await {
Ok(merge) => merge,
Err(err) if is_stale_read(&err) => return Ok(Stop::Stale(err)),
Err(err) => return Err(err),
};
loop {
let want = usize::try_from(progress.left)
.unwrap_or(usize::MAX)
.min(o.options.batch_rows);
match next_batch(&mut merge, want, plan, budget).await {
Ok(None) => return Ok(Stop::Done),
Ok(Some(batch)) => {
progress.left -= batch.ids.len() as u64;
progress.after = Some(batch.last_id.clone());
progress.sent = true;
if tx.send(Ok(batch)).await.is_err() || progress.left == 0 {
return Ok(Stop::Done);
}
}
Err(err) if is_stale_read(&err) => return Ok(Stop::Stale(err)),
Err(err) => return Err(err),
}
}
}
async fn read_tail(
store: &dyn ObjectStore,
namespace: &str,
folded: u64,
budget: &ReadBudget,
) -> Result<Arc<Layer>> {
let log = wal::stream_log(store, namespace, folded, budget, Lane::Maintenance).await?;
let (layer, _) = layer::fold_log(log).await?;
Ok(Arc::new(layer))
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use futures::FutureExt;
use super::*;
fn batch(id: &str) -> ScanBatch {
ScanBatch {
ids: vec![id.to_string()],
vectors: None,
attrs: None,
sparse: None,
last_id: id.to_string(),
}
}
#[tokio::test]
async fn the_producer_advances_only_when_polled() {
let sent = Arc::new(AtomicUsize::new(0));
let (mut tx, rx) = mpsc::channel(0);
let counter = Arc::clone(&sent);
let mut stream = ScanStream::new(
async move {
for i in 0..10 {
counter.fetch_add(1, Ordering::SeqCst);
if tx.send(Ok(batch(&format!("{i}")))).await.is_err() {
return;
}
}
},
rx,
);
tokio::task::yield_now().await;
assert_eq!(sent.load(Ordering::SeqCst), 0, "nothing runs unpolled");
let first = stream.next().await.expect("a batch").expect("ok");
assert_eq!(first.ids, ["0"]);
assert!(
sent.load(Ordering::SeqCst) <= 2,
"one sent, one at most buffered"
);
let rest: Vec<_> = stream.collect().await;
assert_eq!(rest.len(), 9);
}
#[tokio::test]
async fn dropping_the_stream_drops_the_producer() {
struct Guard(Arc<AtomicBool>);
impl Drop for Guard {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
let dropped = Arc::new(AtomicBool::new(false));
let guard = Guard(Arc::clone(&dropped));
let (mut tx, rx) = mpsc::channel(0);
let mut stream = ScanStream::new(
async move {
let _guard = guard;
for i in 0.. {
if tx.send(Ok(batch(&format!("{i}")))).await.is_err() {
return;
}
}
},
rx,
);
assert!(stream.next().now_or_never().flatten().is_some());
assert!(!dropped.load(Ordering::SeqCst));
drop(stream);
assert!(dropped.load(Ordering::SeqCst));
}
#[tokio::test]
async fn an_error_ends_the_stream() {
let (mut tx, rx) = mpsc::channel(0);
let mut stream = ScanStream::new(
async move {
let _ = tx.send(Ok(batch("a"))).await;
let _ = tx.send(Err(ItzmaError::InvalidQuery("boom"))).await;
},
rx,
);
assert!(stream.next().await.expect("item").is_ok());
assert!(stream.next().await.expect("item").is_err());
assert!(stream.next().await.is_none());
assert!(stream.next().await.is_none());
}
async fn moved() -> (Owned, Manifest, ItzmaError) {
let store: Arc<dyn ObjectStore> = Arc::new(object_store::memory::InMemory::new());
let schema = Schema::new(1, crate::Metric::L2);
let ns = crate::Namespace::create(Arc::clone(&store), "docs", schema.clone())
.await
.expect("create");
let stale = view::load_checked(&*store, "docs").await.expect("load");
let doc = crate::Document {
id: "a".into(),
vector: vec![0.0],
attrs: None,
sparse: None,
};
ns.upsert(vec![doc]).await.expect("upsert");
ns.compact(&crate::CompactionOptions::default())
.await
.expect("compact");
let owned = Owned {
store,
namespace: "docs".into(),
schema,
policy: FetchPolicy::local(),
read_budget: u64::MAX,
options: ScanOptions::default(),
};
let err = crate::segment::missing(&crate::segment::segment_path("docs", "gone"));
(owned, stale, err)
}
#[tokio::test]
async fn a_moved_manifest_is_reloaded_until_the_cap() {
let (owned, stale, err) = moved().await;
let mut reloads = 0;
let fresh = reload(&owned, &stale, err, &mut reloads)
.await
.expect("reloaded");
assert_ne!(fresh, stale);
assert_eq!(reloads, 1);
let (owned, stale, err) = moved().await;
let mut reloads = MAX_RELOADS;
let err = reload(&owned, &stale, err, &mut reloads)
.await
.expect_err("capped");
assert!(crate::segment::is_missing(&err), "{err:?}");
assert_eq!(reloads, MAX_RELOADS);
}
#[tokio::test]
async fn an_unmoved_manifest_or_another_error_is_returned() {
let (owned, stale, _) = moved().await;
let current = view::load_checked(&*owned.store, "docs")
.await
.expect("load");
let mut reloads = 0;
let missing = crate::segment::missing(&crate::segment::segment_path("docs", "gone"));
let err = reload(&owned, ¤t, missing, &mut reloads)
.await
.expect_err("unmoved");
assert!(crate::segment::is_missing(&err), "{err:?}");
let other = ItzmaError::InvalidQuery("not stale");
let err = reload(&owned, &stale, other, &mut reloads)
.await
.expect_err("not stale");
assert!(matches!(err, ItzmaError::InvalidQuery(_)));
assert_eq!(reloads, 0);
}
}