Skip to main content

tsdb_reader/index/
postings_ops.rs

1//! Set operations over postings: intersection, union and difference.
2//!
3//! A label matcher plan is a tree of these operations over the postings lists of
4//! single label pairs, e.g. `{namespace="prod", service="api"}` becomes
5//! `Intersection(postings(namespace=prod), postings(service=api))`.
6//!
7//! Every operation is lazy and keeps both inputs as cursors, so a plan costs one
8//! `Postings` per leaf and never materialises an intermediate set. Each `seek`
9//! is forwarded to the inputs, which lets the intersection skip large gaps
10//! instead of stepping through them.
11
12use crate::error::Result;
13
14use super::{Postings, PostingsList};
15
16/// A boxed postings source, the currency of this module.
17pub type BoxPostings<'a> = Box<dyn Postings + 'a>;
18
19/// Intersection of two postings lists: references present in both.
20pub struct Intersection<'a> {
21    left: BoxPostings<'a>,
22    right: BoxPostings<'a>,
23    left_value: Option<u64>,
24    right_value: Option<u64>,
25    primed: bool,
26}
27
28impl<'a> Intersection<'a> {
29    /// Builds the intersection of two sources.
30    pub fn new(left: BoxPostings<'a>, right: BoxPostings<'a>) -> Self {
31        Self {
32            left,
33            right,
34            left_value: None,
35            right_value: None,
36            primed: false,
37        }
38    }
39
40    fn prime(&mut self) -> Result<()> {
41        if !self.primed {
42            self.left_value = self.left.next()?;
43            self.right_value = self.right.next()?;
44            self.primed = true;
45        }
46        Ok(())
47    }
48}
49
50impl Postings for Intersection<'_> {
51    fn next(&mut self) -> Result<Option<u64>> {
52        self.prime()?;
53        loop {
54            let (Some(left), Some(right)) = (self.left_value, self.right_value) else {
55                return Ok(None);
56            };
57            if left == right {
58                self.left_value = self.left.next()?;
59                self.right_value = self.right.next()?;
60                return Ok(Some(left));
61            }
62            // Skip ahead on the smaller side; the larger value is a lower bound
63            // the other side can never match below.
64            if left < right {
65                self.left_value = self.left.seek(right)?;
66            } else {
67                self.right_value = self.right.seek(left)?;
68            }
69        }
70    }
71
72    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
73        self.prime()?;
74        if self.left_value.is_some_and(|v| v < target) {
75            self.left_value = self.left.seek(target)?;
76        }
77        if self.right_value.is_some_and(|v| v < target) {
78            self.right_value = self.right.seek(target)?;
79        }
80        self.next()
81    }
82}
83
84/// Union of several postings lists: every reference, once, ascending.
85pub struct Union<'a> {
86    parts: Vec<BoxPostings<'a>>,
87    heads: Vec<Option<u64>>,
88    primed: bool,
89}
90
91impl<'a> Union<'a> {
92    /// Builds the union of `parts`. An empty input yields an empty list.
93    pub fn new(parts: Vec<BoxPostings<'a>>) -> Self {
94        let heads = parts.iter().map(|_| None).collect::<Vec<_>>();
95        Self {
96            parts,
97            heads,
98            primed: false,
99        }
100    }
101
102    fn prime(&mut self) -> Result<()> {
103        if self.primed {
104            return Ok(());
105        }
106        for i in 0..self.parts.len() {
107            self.heads[i] = self.parts[i].next()?;
108        }
109        self.primed = true;
110        Ok(())
111    }
112
113    fn advance(&mut self) -> Result<Option<u64>> {
114        let mut best: Option<(usize, u64)> = None;
115        for (i, head) in self.heads.iter().enumerate() {
116            if let Some(v) = *head {
117                if best.map(|(_, bv)| v < bv).unwrap_or(true) {
118                    best = Some((i, v));
119                }
120            }
121        }
122        let Some((idx, value)) = best else {
123            return Ok(None);
124        };
125        self.heads[idx] = self.parts[idx].next()?;
126        // Drop the same reference from every other part so the union stays
127        // deduplicated even when several values match one series.
128        for i in 0..self.heads.len() {
129            if self.heads[i] == Some(value) {
130                self.heads[i] = self.parts[i].next()?;
131            }
132        }
133        Ok(Some(value))
134    }
135}
136
137impl Postings for Union<'_> {
138    fn next(&mut self) -> Result<Option<u64>> {
139        self.prime()?;
140        self.advance()
141    }
142
143    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
144        self.prime()?;
145        for i in 0..self.heads.len() {
146            if self.heads[i].is_some_and(|head| head < target) {
147                self.heads[i] = self.parts[i].seek(target)?;
148            }
149        }
150        self.advance()
151    }
152}
153
154/// Difference `left \ right`: references in `left` that are absent from `right`.
155pub struct Difference<'a> {
156    left: BoxPostings<'a>,
157    right: BoxPostings<'a>,
158    right_value: Option<u64>,
159    right_done: bool,
160}
161
162impl<'a> Difference<'a> {
163    /// Builds `left` minus `right`.
164    pub fn new(left: BoxPostings<'a>, right: BoxPostings<'a>) -> Self {
165        Self {
166            left,
167            right,
168            right_value: None,
169            right_done: false,
170        }
171    }
172}
173
174impl Difference<'_> {
175    /// Moves the subtrahend to the first reference `>= target`, priming it on
176    /// first use. Afterwards `right_value` is either `>= target` or `None`.
177    fn advance_right_to(&mut self, target: u64) -> Result<()> {
178        loop {
179            match self.right_value {
180                Some(r) if r >= target => return Ok(()),
181                Some(_) => match self.right.seek(target)? {
182                    Some(v) => self.right_value = Some(v),
183                    None => {
184                        self.right_value = None;
185                        self.right_done = true;
186                        return Ok(());
187                    }
188                },
189                None if !self.right_done => {
190                    self.right_value = self.right.next()?;
191                    if self.right_value.is_none() {
192                        self.right_done = true;
193                        return Ok(());
194                    }
195                }
196                None => return Ok(()),
197            }
198        }
199    }
200}
201
202impl Postings for Difference<'_> {
203    fn next(&mut self) -> Result<Option<u64>> {
204        loop {
205            let Some(left) = self.left.next()? else {
206                return Ok(None);
207            };
208            self.advance_right_to(left)?;
209            if self.right_value != Some(left) {
210                return Ok(Some(left));
211            }
212        }
213    }
214
215    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
216        let Some(left) = self.left.seek(target)? else {
217            return Ok(None);
218        };
219        self.advance_right_to(left)?;
220        if self.right_value == Some(left) {
221            return self.next();
222        }
223        Ok(Some(left))
224    }
225}
226
227/// Intersection of two sources, boxed inputs.
228pub fn intersect<'a>(left: BoxPostings<'a>, right: BoxPostings<'a>) -> Intersection<'a> {
229    Intersection::new(left, right)
230}
231
232/// Intersection of all sources; an empty input yields an empty list.
233pub fn intersect_all<'a>(mut parts: Vec<BoxPostings<'a>>) -> BoxPostings<'a> {
234    match parts.len() {
235        0 => Box::new(PostingsList::empty()),
236        1 => parts.pop().expect("length checked"),
237        _ => {
238            let mut iter = parts.into_iter();
239            let mut acc: BoxPostings<'a> = iter.next().expect("length checked");
240            for next in iter {
241                acc = Box::new(Intersection::new(acc, next));
242            }
243            acc
244        }
245    }
246}
247
248/// Union of all sources; an empty input yields an empty list.
249pub fn union_all<'a>(parts: Vec<BoxPostings<'a>>) -> BoxPostings<'a> {
250    if parts.is_empty() {
251        return Box::new(PostingsList::empty());
252    }
253    Box::new(Union::new(parts))
254}
255
256/// `left` minus `right`.
257pub fn difference<'a>(left: BoxPostings<'a>, right: BoxPostings<'a>) -> Difference<'a> {
258    Difference::new(left, right)
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::index::VecPostings;
265
266    fn p(refs: &[u64]) -> BoxPostings<'static> {
267        Box::new(VecPostings::new(refs.to_vec()))
268    }
269
270    fn collect(mut postings: impl Postings) -> Vec<u64> {
271        let mut out = Vec::new();
272        while let Some(v) = postings.next().unwrap() {
273            out.push(v);
274        }
275        out
276    }
277
278    #[test]
279    fn intersection_keeps_only_common_references() {
280        let got = collect(Intersection::new(p(&[1, 3, 5, 9]), p(&[2, 3, 5, 7])));
281        assert_eq!(got, vec![3, 5]);
282    }
283
284    #[test]
285    fn intersection_with_empty_side_is_empty() {
286        assert!(collect(Intersection::new(p(&[1, 2]), p(&[]))).is_empty());
287        assert!(collect(Intersection::new(p(&[]), p(&[1, 2]))).is_empty());
288    }
289
290    #[test]
291    fn intersection_seek_lands_on_the_next_common_reference() {
292        let mut it = Intersection::new(p(&[1, 4, 8, 15]), p(&[2, 4, 9, 15]));
293        assert_eq!(it.seek(5).unwrap(), Some(15));
294        // Seeking past the end yields nothing and stays exhausted.
295        assert_eq!(it.seek(100).unwrap(), None);
296        assert_eq!(it.next().unwrap(), None);
297    }
298
299    #[test]
300    fn union_merges_sorts_and_deduplicates() {
301        let got = collect(Union::new(vec![p(&[1, 4, 9]), p(&[1, 2, 9]), p(&[3])]));
302        assert_eq!(got, vec![1, 2, 3, 4, 9]);
303    }
304
305    #[test]
306    fn union_seek_skips_low_references_in_every_part() {
307        let mut it = Union::new(vec![p(&[1, 5, 9]), p(&[2, 6, 10])]);
308        assert_eq!(it.seek(6).unwrap(), Some(6));
309        assert_eq!(it.next().unwrap(), Some(9));
310        assert_eq!(it.seek(10).unwrap(), Some(10));
311        assert_eq!(it.next().unwrap(), None);
312    }
313
314    #[test]
315    fn difference_removes_common_references() {
316        let got = collect(Difference::new(p(&[1, 2, 3, 4, 5]), p(&[2, 5, 8])));
317        assert_eq!(got, vec![1, 3, 4]);
318    }
319
320    #[test]
321    fn difference_with_empty_subtrahend_is_the_left_side() {
322        let got = collect(Difference::new(p(&[1, 2, 3]), p(&[])));
323        assert_eq!(got, vec![1, 2, 3]);
324        assert!(collect(Difference::new(p(&[]), p(&[1]))).is_empty());
325    }
326
327    #[test]
328    fn difference_seek_skips_removed_references() {
329        let mut it = Difference::new(p(&[1, 2, 3, 4, 5, 6]), p(&[3, 4]));
330        assert_eq!(it.seek(3).unwrap(), Some(5));
331        assert_eq!(it.next().unwrap(), Some(6));
332        assert_eq!(it.seek(99).unwrap(), None);
333    }
334
335    #[test]
336    fn combinators_handle_degenerate_inputs() {
337        assert!(collect(intersect_all(Vec::new())).is_empty());
338        assert!(collect(union_all(Vec::new())).is_empty());
339        assert_eq!(collect(intersect_all(vec![p(&[1, 2])])), vec![1, 2]);
340        assert_eq!(collect(union_all(vec![p(&[1, 2])])), vec![1, 2]);
341        let three = collect(intersect_all(vec![p(&[1, 2, 3]), p(&[2, 3]), p(&[3])]));
342        assert_eq!(three, vec![3]);
343    }
344}