itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
//! Merge winners into one [`ScanBatch`]: the predicate and the projection,
//! run on the maintenance pool a slice of winners at a time, then the vectors
//! and sparse vectors of the rows that are kept, fetched per source.

use std::sync::{Arc, Mutex, PoisonError};

use futures::future::try_join_all;
use serde_json::Value;

use super::merge::{Attrs, Merge, Origin, Winner};
use super::{AttrColumns, ScanBatch};
use crate::budget::ReadBudget;
use crate::cpu::{self, Cost, Lane};
use crate::document::SparseVector;
use crate::error::{ItzmaError, Result};
use crate::predicate::Predicate;
use crate::segment::Matrix;

/// The most winners drawn from the merge between two renewals of the read
/// budget. A selective filter can pass over the whole namespace before a
/// batch fills; drawing in slices keeps what one budget is charged to about
/// one slice of ids and attributes (the windows they come from are not kept)
/// plus the vectors of the rows the batch keeps.
const SLICE: usize = 1_024;

/// What every batch of one scan applies to its winners.
pub(crate) struct BatchPlan {
    pub(crate) predicate: Option<Predicate>,
    pub(crate) attrs: AttrColumns,
    pub(crate) vectors: bool,
    pub(crate) sparse: bool,
    pub(crate) dim: usize,
    /// Where the batch's attribute work runs.
    pub(crate) lane: Lane,
}

impl BatchPlan {
    /// Whether attributes need parsing at all.
    fn parses(&self) -> bool {
        self.predicate.is_some() || self.attrs != AttrColumns::None
    }
}

/// A winner that passed the predicate, its attributes projected.
struct Kept {
    source: usize,
    row: Option<u32>,
    id: String,
    attrs: Option<Value>,
}

/// The next batch of at most `want` rows, `None` once the merge is done.
///
/// # Errors
///
/// The merge's read errors, and
/// [`ItzmaError::CorruptSegment`](crate::ItzmaError::CorruptSegment) for stored
/// attributes that are not JSON.
pub(crate) async fn next_batch(
    merge: &mut Merge<'_>,
    want: usize,
    plan: &Arc<BatchPlan>,
    budget: &ReadBudget,
) -> Result<Option<ScanBatch>> {
    let mut kept: Vec<Kept> = Vec::new();
    let labels = Arc::new(merge.labels());
    while kept.len() < want {
        budget.renew();
        let slice = (want - kept.len()).min(SLICE);
        let mut candidates = Vec::with_capacity(slice);
        while candidates.len() < slice {
            let Some(winner) = merge.next().await? else {
                break;
            };
            candidates.push(winner);
        }
        if candidates.is_empty() {
            break;
        }
        let bytes = candidates.iter().map(|w| raw_len(&w.attrs)).sum();
        let plan = Arc::clone(plan);
        let labels = Arc::clone(&labels);
        let more = cpu::run(plan.lane, Cost::Bytes(bytes), move || {
            keep(candidates, &plan, &labels)
        })
        .await?;
        kept.extend(more);
    }
    let Some(last_id) = kept.last().map(|k| k.id.clone()) else {
        return Ok(None);
    };
    let (vectors, sparse) = fetch_columns(merge, &kept, plan).await?;
    let (ids, attrs): (Vec<String>, Vec<Option<Value>>) =
        kept.into_iter().map(|k| (k.id, k.attrs)).unzip();
    let attrs = (plan.attrs != AttrColumns::None).then_some(attrs);
    Ok(Some(ScanBatch {
        ids,
        vectors,
        attrs,
        sparse,
        last_id,
    }))
}

/// What one source gives for its kept rows, in the order of `positions`.
struct Fetched {
    positions: Vec<usize>,
    sparse: Option<Vec<Option<SparseVector>>>,
}

/// The vectors and sparse vectors of `kept`, in its order, each source's rows
/// fetched at once and every source at the same time. Every source decodes
/// its vectors straight into the batch's one matrix as they arrive, so a
/// batch never holds its vectors twice .
async fn fetch_columns(
    merge: &Merge<'_>,
    kept: &[Kept],
    plan: &BatchPlan,
) -> Result<(Option<Matrix>, Option<Vec<Option<SparseVector>>>)> {
    if !plan.vectors && !plan.sparse {
        return Ok((None, None));
    }
    let mut groups: Vec<Vec<usize>> = Vec::new();
    for (position, k) in kept.iter().enumerate() {
        if groups.len() <= k.source {
            groups.resize_with(k.source + 1, Vec::new);
        }
        groups[k.source].push(position);
    }
    let sources: Vec<usize> = (0..groups.len())
        .filter(|&s| !groups[s].is_empty())
        .collect();
    let mut values = if plan.vectors {
        vec![0.0f32; kept.len() * plan.dim]
    } else {
        Vec::new()
    };
    let fetched = {
        let out = Mutex::new(values.as_mut_slice());
        let out = plan.vectors.then_some(&out);
        // Indexed by position, not mapped over borrowed values (see
        // `query::open_sources`).
        try_join_all(
            (0..sources.len())
                .map(|i| fetch_source(merge, sources[i], &groups[sources[i]], kept, plan, out)),
        )
        .await?
    };
    let mut sparse: Option<Vec<Option<SparseVector>>> = plan.sparse.then(|| vec![None; kept.len()]);
    for group in fetched {
        if let (Some(sparse), Some(rows)) = (sparse.as_mut(), group.sparse) {
            for (&position, row) in group.positions.iter().zip(rows) {
                sparse[position] = row;
            }
        }
    }
    let vectors = plan.vectors.then_some(Matrix {
        rows: kept.len(),
        dim: plan.dim,
        values,
    });
    Ok((vectors, sparse))
}

/// Source `source`'s kept rows at `positions` of `kept`: their vectors
/// written into `out` at those positions, when the scan returns vectors.
async fn fetch_source(
    merge: &Merge<'_>,
    source: usize,
    positions: &[usize],
    kept: &[Kept],
    plan: &BatchPlan,
    out: Option<&Mutex<&mut [f32]>>,
) -> Result<Fetched> {
    match merge.origin(source) {
        Origin::Segment(segment, sparse_rows) => {
            let rows = positions
                .iter()
                .map(|&p| {
                    kept[p]
                        .row
                        .ok_or_else(|| segment.corrupt("a document without a row"))
                })
                .collect::<Result<Vec<u32>>>()?;
            let vectors = async {
                match out {
                    Some(out) => segment.vectors_into(&rows, positions, out).await,
                    None => Ok(()),
                }
            };
            let sparse = async {
                match (plan.sparse, sparse_rows) {
                    (false, _) => Ok(None),
                    (true, None) => Ok(Some(vec![None; rows.len()])),
                    // A source yields rows in id order, which in a version 2
                    // segment is row order, as `rows_at` needs.
                    (true, Some(sparse_rows)) => sparse_rows.rows_at(&rows).await.map(Some),
                }
            };
            let ((), sparse) = futures::try_join!(vectors, sparse)?;
            Ok(Fetched {
                positions: positions.to_vec(),
                sparse,
            })
        }
        Origin::Layer(layer, label) => {
            let docs = positions
                .iter()
                .map(|&p| {
                    layer
                        .doc(&kept[p].id)
                        .ok_or_else(|| ItzmaError::CorruptSegment {
                            path: label.to_string(),
                            reason: format!("a winner it does not hold: {}", kept[p].id),
                        })
                })
                .collect::<Result<Vec<_>>>()?;
            if let Some(doc) = docs.iter().find(|d| d.vector.len() != plan.dim) {
                return Err(ItzmaError::CorruptSegment {
                    path: label.to_string(),
                    reason: format!("a vector of the wrong length: {}", doc.id),
                });
            }
            if let Some(out) = out {
                let mut out = out.lock().unwrap_or_else(PoisonError::into_inner);
                for (&position, doc) in positions.iter().zip(&docs) {
                    out[position * plan.dim..(position + 1) * plan.dim]
                        .copy_from_slice(&doc.vector);
                }
            }
            let sparse = plan
                .sparse
                .then(|| docs.iter().map(|d| d.sparse.clone()).collect());
            Ok(Fetched {
                positions: positions.to_vec(),
                sparse,
            })
        }
    }
}

fn raw_len(attrs: &Attrs) -> usize {
    match attrs {
        Attrs::Stored(stored) => stored.cost(),
        Attrs::Parsed(_) => 0,
    }
}

/// Parse, test and project `candidates`, keeping the ones that match.
fn keep(candidates: Vec<Winner>, plan: &BatchPlan, labels: &[String]) -> Result<Vec<Kept>> {
    let mut kept = Vec::with_capacity(candidates.len());
    for winner in candidates {
        let attrs = if plan.parses() {
            match winner.attrs {
                Attrs::Parsed(attrs) => attrs,
                Attrs::Stored(stored) => stored.value(&labels[winner.source])?,
            }
        } else {
            None
        };
        if plan
            .predicate
            .as_ref()
            .is_some_and(|p| !p.matches(attrs.as_ref()))
        {
            continue;
        }
        kept.push(Kept {
            source: winner.source,
            row: winner.row,
            id: winner.id,
            attrs: project(attrs, &plan.attrs),
        });
    }
    Ok(kept)
}

/// `attrs` cut down to what the scan asked for.
pub(crate) fn project(attrs: Option<Value>, columns: &AttrColumns) -> Option<Value> {
    match columns {
        AttrColumns::None => None,
        AttrColumns::All => attrs,
        AttrColumns::Fields(names) => attrs.map(|value| match value {
            Value::Object(mut map) => Value::Object(
                names
                    .iter()
                    .filter_map(|name| map.remove_entry(name.as_str()))
                    .collect(),
            ),
            other => other,
        }),
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;
    use crate::document::{Document, WalOp};
    use crate::layer::Layer;

    #[test]
    fn fields_keep_only_named_keys() {
        let fields = AttrColumns::Fields(vec!["a".into(), "c".into()]);
        assert_eq!(
            project(Some(json!({ "a": 1, "b": 2 })), &fields),
            Some(json!({ "a": 1 }))
        );
        assert_eq!(project(Some(json!({ "b": 2 })), &fields), Some(json!({})));
        assert_eq!(project(None, &fields), None);
        assert_eq!(project(Some(json!({ "a": 1 })), &AttrColumns::None), None);
    }

    #[tokio::test]
    async fn a_bad_vector_in_a_layer_names_the_layer_s_path() {
        let mut layer = Layer::new();
        layer.apply(WalOp::Upsert(Document {
            id: "a".to_string(),
            vector: vec![1.0],
            attrs: None,
            sparse: None,
        }));
        let mut merge = Merge::of_layer(layer, "docs/wal");
        let plan = Arc::new(BatchPlan {
            predicate: None,
            attrs: AttrColumns::None,
            vectors: true,
            sparse: false,
            dim: 2,
            lane: Lane::Maintenance,
        });
        let err = next_batch(&mut merge, 8, &plan, &ReadBudget::unlimited())
            .await
            .expect_err("a vector of the wrong length");
        match err {
            ItzmaError::CorruptSegment { path, reason } => {
                assert_eq!(path, "docs/wal");
                assert!(reason.contains("wrong length"), "{reason}");
            }
            other => panic!("{other:?}"),
        }
    }
}