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
//! Chunk selection by time range.
//!
//! A series' chunks are stored in ascending time order, so a query range can be
//! turned into a contiguous slice of the chunk list without decoding anything:
//! binary search for the first chunk whose `max_time` reaches the range start,
//! and stop at the first chunk that begins after the range end.
//!
//! This is the block-internal optimisation the query layer relies on; deciding
//! *which* range a PromQL expression needs (e.g. the extra five minutes for
//! `rate(...[5m])`) belongs to the query layer, not here.

use std::ops::Range;

use crate::index::{ChunkMeta, SeriesRef};
use crate::time_range::TimeRange;

/// Index range of the chunks of a series that can hold samples in `range`.
///
/// Chunk metadata is a closed interval (`[min_time, max_time]`) while the query
/// range is half-open, which is why the comparisons below are not symmetric.
/// Returns an empty range when nothing overlaps.
pub fn chunk_index_range(chunks: &[ChunkMeta], range: TimeRange) -> Range<usize> {
    if range.is_empty() || chunks.is_empty() {
        return 0..0;
    }
    // Chunks whose last sample is before the range start cannot contribute.
    let start = chunks.partition_point(|chunk| chunk.max_time < range.min_time);
    // From there, stop at the first chunk that starts at or after the end.
    let end = start + chunks[start..].partition_point(|chunk| chunk.min_time < range.max_time);
    start..end
}

/// The chunks of `chunks` that can hold samples in `range`, in time order.
pub fn chunks_in_range<'a>(
    chunks: &'a [ChunkMeta],
    range: TimeRange,
) -> impl Iterator<Item = &'a ChunkMeta> + 'a {
    let bounds = chunk_index_range(chunks, range);
    chunks[bounds].iter()
}

impl SeriesRef {
    /// The series' chunks that can hold samples in `range`, in time order.
    ///
    /// Chunks outside the range are not returned, so a caller never decodes
    /// data it cannot use. Samples inside a returned chunk still need the
    /// per-sample range filter, because a chunk can straddle the boundaries.
    pub fn chunks_in_range(&self, range: TimeRange) -> impl Iterator<Item = &ChunkMeta> + '_ {
        chunks_in_range(&self.chunks, range)
    }
}

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

    fn chunk(min_time: i64, max_time: i64) -> ChunkMeta {
        ChunkMeta {
            reference: min_time as u64,
            min_time,
            max_time,
        }
    }

    /// Three consecutive chunks: [0,10] [11,20] [21,30].
    fn chunks() -> Vec<ChunkMeta> {
        vec![chunk(0, 10), chunk(11, 20), chunk(21, 30)]
    }

    fn selected(range: TimeRange) -> Vec<i64> {
        chunks_in_range(&chunks(), range)
            .map(|c| c.min_time)
            .collect()
    }

    #[test]
    fn a_range_inside_one_chunk_selects_only_that_chunk() {
        assert_eq!(selected(TimeRange::new(5, 8)), vec![0]);
        assert_eq!(selected(TimeRange::new(12, 15)), vec![11]);
    }

    #[test]
    fn a_range_spanning_boundaries_selects_the_touched_chunks() {
        // Touching the end of the first chunk counts: its last sample is at 10.
        assert_eq!(selected(TimeRange::new(10, 12)), vec![0, 11]);
        assert_eq!(selected(TimeRange::new(20, 22)), vec![11, 21]);
        assert_eq!(selected(TimeRange::new(0, 100)), vec![0, 11, 21]);
    }

    #[test]
    fn a_range_between_chunks_selects_nothing() {
        // [30, 31) starts after the last chunk ends at 30 and before nothing;
        // chunk [21,30] ends exactly at the range start minus one, so it is
        // included (its max_time is 30, the range starts at 30).
        assert_eq!(selected(TimeRange::new(31, 40)), Vec::<i64>::new());
        assert_eq!(selected(TimeRange::new(-10, 0)), Vec::<i64>::new());
        // A range that starts exactly at max_time + 1 excludes the chunk.
        assert_eq!(selected(TimeRange::new(11, 11)), Vec::<i64>::new());
    }

    #[test]
    fn empty_ranges_and_empty_series_select_nothing() {
        assert_eq!(selected(TimeRange::new(5, 5)), Vec::<i64>::new());
        assert_eq!(selected(TimeRange::new(9, 3)), Vec::<i64>::new());
        assert_eq!(
            chunks_in_range(&[], TimeRange::all()).count(),
            0,
            "an empty chunk list has nothing to select"
        );
    }

    #[test]
    fn the_index_range_matches_the_iterator() {
        let chunks = chunks();
        for (start, end) in [(0, 5), (10, 12), (20, 22), (31, 40), (5, 5)] {
            let range = TimeRange::new(start, end);
            let bounds = chunk_index_range(&chunks, range);
            let iterated: Vec<usize> = chunks_in_range(&chunks, range)
                .map(|c| {
                    chunks
                        .iter()
                        .position(|x| x.reference == c.reference)
                        .unwrap()
                })
                .collect();
            assert_eq!(iterated, (bounds.start..bounds.end).collect::<Vec<_>>());
        }
    }
}