tsdb-reader 0.3.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings and label matchers, tombstones
Documentation
//! Set operations over postings: intersection, union and difference.
//!
//! A label matcher plan is a tree of these operations over the postings lists of
//! single label pairs, e.g. `{namespace="prod", service="api"}` becomes
//! `Intersection(postings(namespace=prod), postings(service=api))`.
//!
//! Every operation is lazy and keeps both inputs as cursors, so a plan costs one
//! `Postings` per leaf and never materialises an intermediate set. Each `seek`
//! is forwarded to the inputs, which lets the intersection skip large gaps
//! instead of stepping through them.

use crate::error::Result;

use super::{Postings, PostingsList};

/// A boxed postings source, the currency of this module.
pub type BoxPostings<'a> = Box<dyn Postings + 'a>;

/// Intersection of two postings lists: references present in both.
pub struct Intersection<'a> {
    left: BoxPostings<'a>,
    right: BoxPostings<'a>,
    left_value: Option<u64>,
    right_value: Option<u64>,
    primed: bool,
}

impl<'a> Intersection<'a> {
    /// Builds the intersection of two sources.
    pub fn new(left: BoxPostings<'a>, right: BoxPostings<'a>) -> Self {
        Self {
            left,
            right,
            left_value: None,
            right_value: None,
            primed: false,
        }
    }

    fn prime(&mut self) -> Result<()> {
        if !self.primed {
            self.left_value = self.left.next()?;
            self.right_value = self.right.next()?;
            self.primed = true;
        }
        Ok(())
    }
}

impl Postings for Intersection<'_> {
    fn next(&mut self) -> Result<Option<u64>> {
        self.prime()?;
        loop {
            let (Some(left), Some(right)) = (self.left_value, self.right_value) else {
                return Ok(None);
            };
            if left == right {
                self.left_value = self.left.next()?;
                self.right_value = self.right.next()?;
                return Ok(Some(left));
            }
            // Skip ahead on the smaller side; the larger value is a lower bound
            // the other side can never match below.
            if left < right {
                self.left_value = self.left.seek(right)?;
            } else {
                self.right_value = self.right.seek(left)?;
            }
        }
    }

    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
        self.prime()?;
        if self.left_value.is_some_and(|v| v < target) {
            self.left_value = self.left.seek(target)?;
        }
        if self.right_value.is_some_and(|v| v < target) {
            self.right_value = self.right.seek(target)?;
        }
        self.next()
    }
}

/// Union of several postings lists: every reference, once, ascending.
pub struct Union<'a> {
    parts: Vec<BoxPostings<'a>>,
    heads: Vec<Option<u64>>,
    primed: bool,
}

impl<'a> Union<'a> {
    /// Builds the union of `parts`. An empty input yields an empty list.
    pub fn new(parts: Vec<BoxPostings<'a>>) -> Self {
        let heads = parts.iter().map(|_| None).collect::<Vec<_>>();
        Self {
            parts,
            heads,
            primed: false,
        }
    }

    fn prime(&mut self) -> Result<()> {
        if self.primed {
            return Ok(());
        }
        for i in 0..self.parts.len() {
            self.heads[i] = self.parts[i].next()?;
        }
        self.primed = true;
        Ok(())
    }

    fn advance(&mut self) -> Result<Option<u64>> {
        let mut best: Option<(usize, u64)> = None;
        for (i, head) in self.heads.iter().enumerate() {
            if let Some(v) = *head {
                if best.map(|(_, bv)| v < bv).unwrap_or(true) {
                    best = Some((i, v));
                }
            }
        }
        let Some((idx, value)) = best else {
            return Ok(None);
        };
        self.heads[idx] = self.parts[idx].next()?;
        // Drop the same reference from every other part so the union stays
        // deduplicated even when several values match one series.
        for i in 0..self.heads.len() {
            if self.heads[i] == Some(value) {
                self.heads[i] = self.parts[i].next()?;
            }
        }
        Ok(Some(value))
    }
}

impl Postings for Union<'_> {
    fn next(&mut self) -> Result<Option<u64>> {
        self.prime()?;
        self.advance()
    }

    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
        self.prime()?;
        for i in 0..self.heads.len() {
            if self.heads[i].is_some_and(|head| head < target) {
                self.heads[i] = self.parts[i].seek(target)?;
            }
        }
        self.advance()
    }
}

/// Difference `left \ right`: references in `left` that are absent from `right`.
pub struct Difference<'a> {
    left: BoxPostings<'a>,
    right: BoxPostings<'a>,
    right_value: Option<u64>,
    right_done: bool,
}

impl<'a> Difference<'a> {
    /// Builds `left` minus `right`.
    pub fn new(left: BoxPostings<'a>, right: BoxPostings<'a>) -> Self {
        Self {
            left,
            right,
            right_value: None,
            right_done: false,
        }
    }
}

impl Difference<'_> {
    /// Moves the subtrahend to the first reference `>= target`, priming it on
    /// first use. Afterwards `right_value` is either `>= target` or `None`.
    fn advance_right_to(&mut self, target: u64) -> Result<()> {
        loop {
            match self.right_value {
                Some(r) if r >= target => return Ok(()),
                Some(_) => match self.right.seek(target)? {
                    Some(v) => self.right_value = Some(v),
                    None => {
                        self.right_value = None;
                        self.right_done = true;
                        return Ok(());
                    }
                },
                None if !self.right_done => {
                    self.right_value = self.right.next()?;
                    if self.right_value.is_none() {
                        self.right_done = true;
                        return Ok(());
                    }
                }
                None => return Ok(()),
            }
        }
    }
}

impl Postings for Difference<'_> {
    fn next(&mut self) -> Result<Option<u64>> {
        loop {
            let Some(left) = self.left.next()? else {
                return Ok(None);
            };
            self.advance_right_to(left)?;
            if self.right_value != Some(left) {
                return Ok(Some(left));
            }
        }
    }

    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
        let Some(left) = self.left.seek(target)? else {
            return Ok(None);
        };
        self.advance_right_to(left)?;
        if self.right_value == Some(left) {
            return self.next();
        }
        Ok(Some(left))
    }
}

/// Intersection of two sources, boxed inputs.
pub fn intersect<'a>(left: BoxPostings<'a>, right: BoxPostings<'a>) -> Intersection<'a> {
    Intersection::new(left, right)
}

/// Intersection of all sources; an empty input yields an empty list.
pub fn intersect_all<'a>(mut parts: Vec<BoxPostings<'a>>) -> BoxPostings<'a> {
    match parts.len() {
        0 => Box::new(PostingsList::empty()),
        1 => parts.pop().expect("length checked"),
        _ => {
            let mut iter = parts.into_iter();
            let mut acc: BoxPostings<'a> = iter.next().expect("length checked");
            for next in iter {
                acc = Box::new(Intersection::new(acc, next));
            }
            acc
        }
    }
}

/// Union of all sources; an empty input yields an empty list.
pub fn union_all<'a>(parts: Vec<BoxPostings<'a>>) -> BoxPostings<'a> {
    if parts.is_empty() {
        return Box::new(PostingsList::empty());
    }
    Box::new(Union::new(parts))
}

/// `left` minus `right`.
pub fn difference<'a>(left: BoxPostings<'a>, right: BoxPostings<'a>) -> Difference<'a> {
    Difference::new(left, right)
}

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

    fn p(refs: &[u64]) -> BoxPostings<'static> {
        Box::new(VecPostings::new(refs.to_vec()))
    }

    fn collect(mut postings: impl Postings) -> Vec<u64> {
        let mut out = Vec::new();
        while let Some(v) = postings.next().unwrap() {
            out.push(v);
        }
        out
    }

    #[test]
    fn intersection_keeps_only_common_references() {
        let got = collect(Intersection::new(p(&[1, 3, 5, 9]), p(&[2, 3, 5, 7])));
        assert_eq!(got, vec![3, 5]);
    }

    #[test]
    fn intersection_with_empty_side_is_empty() {
        assert!(collect(Intersection::new(p(&[1, 2]), p(&[]))).is_empty());
        assert!(collect(Intersection::new(p(&[]), p(&[1, 2]))).is_empty());
    }

    #[test]
    fn intersection_seek_lands_on_the_next_common_reference() {
        let mut it = Intersection::new(p(&[1, 4, 8, 15]), p(&[2, 4, 9, 15]));
        assert_eq!(it.seek(5).unwrap(), Some(15));
        // Seeking past the end yields nothing and stays exhausted.
        assert_eq!(it.seek(100).unwrap(), None);
        assert_eq!(it.next().unwrap(), None);
    }

    #[test]
    fn union_merges_sorts_and_deduplicates() {
        let got = collect(Union::new(vec![p(&[1, 4, 9]), p(&[1, 2, 9]), p(&[3])]));
        assert_eq!(got, vec![1, 2, 3, 4, 9]);
    }

    #[test]
    fn union_seek_skips_low_references_in_every_part() {
        let mut it = Union::new(vec![p(&[1, 5, 9]), p(&[2, 6, 10])]);
        assert_eq!(it.seek(6).unwrap(), Some(6));
        assert_eq!(it.next().unwrap(), Some(9));
        assert_eq!(it.seek(10).unwrap(), Some(10));
        assert_eq!(it.next().unwrap(), None);
    }

    #[test]
    fn difference_removes_common_references() {
        let got = collect(Difference::new(p(&[1, 2, 3, 4, 5]), p(&[2, 5, 8])));
        assert_eq!(got, vec![1, 3, 4]);
    }

    #[test]
    fn difference_with_empty_subtrahend_is_the_left_side() {
        let got = collect(Difference::new(p(&[1, 2, 3]), p(&[])));
        assert_eq!(got, vec![1, 2, 3]);
        assert!(collect(Difference::new(p(&[]), p(&[1]))).is_empty());
    }

    #[test]
    fn difference_seek_skips_removed_references() {
        let mut it = Difference::new(p(&[1, 2, 3, 4, 5, 6]), p(&[3, 4]));
        assert_eq!(it.seek(3).unwrap(), Some(5));
        assert_eq!(it.next().unwrap(), Some(6));
        assert_eq!(it.seek(99).unwrap(), None);
    }

    #[test]
    fn combinators_handle_degenerate_inputs() {
        assert!(collect(intersect_all(Vec::new())).is_empty());
        assert!(collect(union_all(Vec::new())).is_empty());
        assert_eq!(collect(intersect_all(vec![p(&[1, 2])])), vec![1, 2]);
        assert_eq!(collect(union_all(vec![p(&[1, 2])])), vec![1, 2]);
        let three = collect(intersect_all(vec![p(&[1, 2, 3]), p(&[2, 3]), p(&[3])]));
        assert_eq!(three, vec![3]);
    }
}