itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
//! Split points for range scans: ids that cut a namespace into
//! ranges of about the same number of documents, taken from the first id of
//! each block in the segment directories, so finding them reads no data.

use futures::stream::{self, StreamExt, TryStreamExt};
use object_store::ObjectStore;

use super::ScanRange;
use crate::budget::ReadBudget;
use crate::error::{ItzmaError, Result};
use crate::fetch::FETCH_CONCURRENCY;
use crate::fetch::FetchPolicy;
use crate::segment::RangedSegment;
use crate::view;

/// The most ranges one call may ask for.
pub const MAX_SCAN_SPLITS: usize = 1_024;

/// Up to `n` ranges covering namespace `namespace`, cut where the live
/// version 2 segments' blocks say the documents divide evenly. Version 1
/// segments and the WAL tail add no cuts; their rows land in whichever range
/// holds them.
///
/// # Errors
///
/// [`ItzmaError::InvalidQuery`] for an `n` outside 1 to [`MAX_SCAN_SPLITS`],
/// before any storage call; otherwise the errors of loading the manifest and
/// opening segments, and [`ItzmaError::ReadBudgetExceeded`].
pub(crate) async fn splits(
    store: &dyn ObjectStore,
    namespace: &str,
    dim: usize,
    budget: &ReadBudget,
    policy: &FetchPolicy,
    n: usize,
) -> Result<Vec<ScanRange>> {
    if !(1..=MAX_SCAN_SPLITS).contains(&n) {
        return Err(ItzmaError::InvalidQuery(
            "scan_splits needs between 1 and 1024 ranges",
        ));
    }
    if n == 1 {
        return Ok(vec![ScanRange::default()]);
    }
    let manifest = view::load_checked(store, namespace).await?;
    let ids = &manifest.live_segments;
    // Indexed by position, not mapped over borrowed values (see
    // `query::open_sources`).
    let opened: Vec<RangedSegment<'_>> = stream::iter(0..ids.len())
        .map(|at| RangedSegment::open(store, namespace, &ids[at], dim, budget, policy, None))
        .buffered(FETCH_CONCURRENCY)
        .try_collect()
        .await?;
    let blocks: Vec<(String, u64)> = opened
        .iter()
        .flat_map(|segment| {
            segment
                .block_firsts()
                .map(|(id, rows)| (id.to_string(), rows))
        })
        .collect();
    Ok(ranges_from(split_points(blocks, n)))
}

/// Up to `n - 1` ids, strictly ascending, that cut the blocks described by
/// `blocks` (each block's first id and its row count, in any order and from
/// any number of segments) into `n` runs of about equal weight.
pub(crate) fn split_points(mut blocks: Vec<(String, u64)>, n: usize) -> Vec<String> {
    if n < 2 || blocks.is_empty() {
        return Vec::new();
    }
    blocks.sort_unstable_by(|a, b| a.0.cmp(&b.0));
    let mut merged: Vec<(String, u64)> = Vec::with_capacity(blocks.len());
    for (id, weight) in blocks {
        match merged.last_mut() {
            Some((last, total)) if *last == id => *total += weight,
            _ => merged.push((id, weight)),
        }
    }
    let total: u64 = merged.iter().map(|(_, w)| w).sum();
    let mut points: Vec<String> = Vec::with_capacity(n - 1);
    let mut before = 0u64;
    let mut k = 1u64;
    let n = n as u64;
    for (id, weight) in merged {
        // The first block at or past the k-th n-th of the weight gives the cut:
        // its first id ends one range (`until` is inclusive) and the rest of
        // the block opens the next.
        while k < n
            && before > 0
            && u128::from(before) * u128::from(n) >= u128::from(total) * u128::from(k)
        {
            if points.last() != Some(&id) {
                points.push(id.clone());
            }
            k += 1;
        }
        before += weight;
    }
    points
}

/// The ranges `points` cut out: contiguous, `(after, until]`, the first
/// unbounded below and the last above.
pub(crate) fn ranges_from(points: Vec<String>) -> Vec<ScanRange> {
    let mut ranges = Vec::with_capacity(points.len() + 1);
    let mut after = None;
    for point in points {
        ranges.push(ScanRange {
            after: after.take(),
            until: Some(point.clone()),
        });
        after = Some(point);
    }
    ranges.push(ScanRange { after, until: None });
    ranges
}

#[cfg(test)]
mod tests {
    use super::*;

    fn blocks(ids: &[(&str, u64)]) -> Vec<(String, u64)> {
        ids.iter().map(|(id, w)| ((*id).to_string(), *w)).collect()
    }

    #[test]
    fn equal_blocks_split_evenly() {
        let ids: Vec<(String, u64)> = (0..8).map(|i| (format!("k{i}"), 256)).collect();
        assert_eq!(split_points(ids, 4), ["k2", "k4", "k6"]);
    }

    #[test]
    fn a_heavy_block_takes_a_range_of_its_own() {
        let ids = blocks(&[("a", 1_000), ("b", 10), ("c", 10), ("d", 10)]);
        assert_eq!(split_points(ids, 2), ["b"]);
    }

    #[test]
    fn fewer_blocks_than_ranges_gives_fewer_points() {
        let ids = blocks(&[("a", 256), ("m", 256)]);
        assert_eq!(split_points(ids, 8), ["m"]);
    }

    #[test]
    fn the_same_first_id_in_two_segments_counts_once_as_a_point() {
        let ids = blocks(&[("m", 256), ("a", 256), ("m", 256), ("x", 256)]);
        let points = split_points(ids, 4);
        assert!(points.windows(2).all(|w| w[0] < w[1]), "{points:?}");
        assert_eq!(points, ["m", "x"]);
    }

    #[test]
    fn one_range_or_nothing_to_split_gives_no_points() {
        assert!(split_points(blocks(&[("a", 1), ("b", 1)]), 1).is_empty());
        assert!(split_points(Vec::new(), 4).is_empty());
    }

    #[test]
    fn ranges_are_contiguous_and_cover_everything() {
        let ranges = ranges_from(vec!["f".into(), "p".into()]);
        assert_eq!(
            ranges,
            [
                ScanRange {
                    after: None,
                    until: Some("f".into())
                },
                ScanRange {
                    after: Some("f".into()),
                    until: Some("p".into())
                },
                ScanRange {
                    after: Some("p".into()),
                    until: None
                },
            ]
        );
        assert_eq!(
            ranges_from(Vec::new()),
            [ScanRange {
                after: None,
                until: None
            }]
        );
    }
}