Skip to main content

tsdb_reader/chunks/
range.rs

1//! Chunk selection by time range.
2//!
3//! A series' chunks are stored in ascending time order, so a query range can be
4//! turned into a contiguous slice of the chunk list without decoding anything:
5//! binary search for the first chunk whose `max_time` reaches the range start,
6//! and stop at the first chunk that begins after the range end.
7//!
8//! This is the block-internal optimisation the query layer relies on; deciding
9//! *which* range a PromQL expression needs (e.g. the extra five minutes for
10//! `rate(...[5m])`) belongs to the query layer, not here.
11
12use std::ops::Range;
13
14use crate::index::{ChunkMeta, SeriesRef};
15use crate::time_range::TimeRange;
16
17/// Index range of the chunks of a series that can hold samples in `range`.
18///
19/// Chunk metadata is a closed interval (`[min_time, max_time]`) while the query
20/// range is half-open, which is why the comparisons below are not symmetric.
21/// Returns an empty range when nothing overlaps.
22pub fn chunk_index_range(chunks: &[ChunkMeta], range: TimeRange) -> Range<usize> {
23    if range.is_empty() || chunks.is_empty() {
24        return 0..0;
25    }
26    // Chunks whose last sample is before the range start cannot contribute.
27    let start = chunks.partition_point(|chunk| chunk.max_time < range.min_time);
28    // From there, stop at the first chunk that starts at or after the end.
29    let end = start + chunks[start..].partition_point(|chunk| chunk.min_time < range.max_time);
30    start..end
31}
32
33/// The chunks of `chunks` that can hold samples in `range`, in time order.
34pub fn chunks_in_range<'a>(
35    chunks: &'a [ChunkMeta],
36    range: TimeRange,
37) -> impl Iterator<Item = &'a ChunkMeta> + 'a {
38    let bounds = chunk_index_range(chunks, range);
39    chunks[bounds].iter()
40}
41
42impl SeriesRef {
43    /// The series' chunks that can hold samples in `range`, in time order.
44    ///
45    /// Chunks outside the range are not returned, so a caller never decodes
46    /// data it cannot use. Samples inside a returned chunk still need the
47    /// per-sample range filter, because a chunk can straddle the boundaries.
48    pub fn chunks_in_range(&self, range: TimeRange) -> impl Iterator<Item = &ChunkMeta> + '_ {
49        chunks_in_range(&self.chunks, range)
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    fn chunk(min_time: i64, max_time: i64) -> ChunkMeta {
58        ChunkMeta {
59            reference: min_time as u64,
60            min_time,
61            max_time,
62        }
63    }
64
65    /// Three consecutive chunks: [0,10] [11,20] [21,30].
66    fn chunks() -> Vec<ChunkMeta> {
67        vec![chunk(0, 10), chunk(11, 20), chunk(21, 30)]
68    }
69
70    fn selected(range: TimeRange) -> Vec<i64> {
71        chunks_in_range(&chunks(), range)
72            .map(|c| c.min_time)
73            .collect()
74    }
75
76    #[test]
77    fn a_range_inside_one_chunk_selects_only_that_chunk() {
78        assert_eq!(selected(TimeRange::new(5, 8)), vec![0]);
79        assert_eq!(selected(TimeRange::new(12, 15)), vec![11]);
80    }
81
82    #[test]
83    fn a_range_spanning_boundaries_selects_the_touched_chunks() {
84        // Touching the end of the first chunk counts: its last sample is at 10.
85        assert_eq!(selected(TimeRange::new(10, 12)), vec![0, 11]);
86        assert_eq!(selected(TimeRange::new(20, 22)), vec![11, 21]);
87        assert_eq!(selected(TimeRange::new(0, 100)), vec![0, 11, 21]);
88    }
89
90    #[test]
91    fn a_range_between_chunks_selects_nothing() {
92        // [30, 31) starts after the last chunk ends at 30 and before nothing;
93        // chunk [21,30] ends exactly at the range start minus one, so it is
94        // included (its max_time is 30, the range starts at 30).
95        assert_eq!(selected(TimeRange::new(31, 40)), Vec::<i64>::new());
96        assert_eq!(selected(TimeRange::new(-10, 0)), Vec::<i64>::new());
97        // A range that starts exactly at max_time + 1 excludes the chunk.
98        assert_eq!(selected(TimeRange::new(11, 11)), Vec::<i64>::new());
99    }
100
101    #[test]
102    fn empty_ranges_and_empty_series_select_nothing() {
103        assert_eq!(selected(TimeRange::new(5, 5)), Vec::<i64>::new());
104        assert_eq!(selected(TimeRange::new(9, 3)), Vec::<i64>::new());
105        assert_eq!(
106            chunks_in_range(&[], TimeRange::all()).count(),
107            0,
108            "an empty chunk list has nothing to select"
109        );
110    }
111
112    #[test]
113    fn the_index_range_matches_the_iterator() {
114        let chunks = chunks();
115        for (start, end) in [(0, 5), (10, 12), (20, 22), (31, 40), (5, 5)] {
116            let range = TimeRange::new(start, end);
117            let bounds = chunk_index_range(&chunks, range);
118            let iterated: Vec<usize> = chunks_in_range(&chunks, range)
119                .map(|c| {
120                    chunks
121                        .iter()
122                        .position(|x| x.reference == c.reference)
123                        .unwrap()
124                })
125                .collect();
126            assert_eq!(iterated, (bounds.start..bounds.end).collect::<Vec<_>>());
127        }
128    }
129}