Skip to main content

mito2/read/scan_region/aggr/
overlap.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Finds sources that may share a row in (time, primary key) space.
16
17use std::cmp::{max, min};
18
19/// The inclusive time and primary key bounds of one source.
20///
21/// A missing key range is unknown and conservatively spans every key.
22#[derive(Debug, Clone)]
23pub struct Extent<T, K> {
24    /// Inclusive `(start, end)`; `start <= end`.
25    pub time: (T, T),
26    /// Inclusive `(min, max)`; `min <= max`.
27    pub key: Option<(K, K)>,
28}
29
30/// Returns whether each extent intersects at least one other extent. Bounds
31/// are inclusive in both dimensions, so touching endpoints count as overlap.
32///
33/// Sorts the extents by start time once and sweeps them twice over one
34/// array-backed segment tree on the compressed key coordinates. The forward
35/// sweep finds each extent's conflict with an earlier-starting extent: an
36/// extent that starts no later overlaps if, somewhere in its key range, an
37/// earlier extent ends at or after its start. The reverse sweep finds the
38/// conflict with a later-starting extent in the same way. Expired extents need
39/// no removal, since their bounds fail the comparison. Each sweep queries
40/// before it updates, so the cost is O(N log N), even when many extents
41/// overlap in time but have disjoint keys.
42pub fn find_overlaps<T: Ord, K: Ord>(extents: &[Extent<T, K>]) -> Vec<bool> {
43    // Compress key endpoints into 1..=len. 0 and len + 1 stand for the open
44    // ends of an unknown key range.
45    let mut keys: Vec<&K> = Vec::with_capacity(2 * extents.len());
46    keys.extend(
47        extents
48            .iter()
49            .filter_map(|extent| extent.key.as_ref())
50            .flat_map(|(min, max)| [min, max]),
51    );
52    keys.sort_unstable();
53    keys.dedup();
54    let position = |key: &K| keys.partition_point(|k| *k < key) + 1;
55    let unbounded = keys.len() + 1;
56    let coordinates: Vec<_> = extents
57        .iter()
58        .map(|extent| {
59            debug_assert!(extent.time.0 <= extent.time.1);
60            match &extent.key {
61                Some((min, max)) => {
62                    debug_assert!(min <= max);
63                    (position(min), position(max))
64                }
65                None => (0, unbounded),
66            }
67        })
68        .collect();
69
70    // Equal starts in index order; an unstable sort needs no buffer.
71    let mut order: Vec<usize> = (0..extents.len()).collect();
72    order.sort_unstable_by(|&lhs, &rhs| {
73        extents[lhs]
74            .time
75            .0
76            .cmp(&extents[rhs].time.0)
77            .then(lhs.cmp(&rhs))
78    });
79
80    let mut overlaps = vec![false; extents.len()];
81    let mut tree = BoundTree::new(unbounded + 1);
82    // Latest end time over every key of the extents started so far.
83    for &index in &order {
84        let (low, high) = coordinates[index];
85        let (start, end) = (&extents[index].time.0, &extents[index].time.1);
86        overlaps[index] |= tree
87            .query::<Latest>(low, high)
88            .is_some_and(|last| last >= start);
89        tree.update::<Latest>(low, high, end);
90    }
91    // Earliest start time over every key of the extents starting later.
92    tree.clear();
93    for &index in order.iter().rev() {
94        let (low, high) = coordinates[index];
95        let (start, end) = (&extents[index].time.0, &extents[index].time.1);
96        overlaps[index] |= tree
97            .query::<Earliest>(low, high)
98            .is_some_and(|first| first <= end);
99        tree.update::<Earliest>(low, high, start);
100    }
101    overlaps
102}
103
104/// The quadratic reference implementation of [`find_overlaps`].
105#[cfg(any(test, feature = "test", feature = "testing"))]
106pub fn find_overlaps_pairwise<T: Ord, K: Ord>(extents: &[Extent<T, K>]) -> Vec<bool> {
107    let mut overlaps = vec![false; extents.len()];
108    for (index, lhs) in extents.iter().enumerate() {
109        for (offset, rhs) in extents[index + 1..].iter().enumerate() {
110            let keys_overlap = match (&lhs.key, &rhs.key) {
111                (Some(lhs), Some(rhs)) => (&lhs.0).max(&rhs.0) <= (&lhs.1).min(&rhs.1),
112                _ => true,
113            };
114            if keys_overlap && (&lhs.time.0).max(&rhs.time.0) <= (&lhs.time.1).min(&rhs.time.1) {
115                overlaps[index] = true;
116                overlaps[index + 1 + offset] = true;
117            }
118        }
119    }
120    overlaps
121}
122
123/// The best bound per key coordinate, for range updates and range queries
124/// that take the larger (or smaller) of two bounds.
125///
126/// A bound applied to a whole node is kept on that node and never pushed down,
127/// since an update and a query only ever combine bounds with the same order.
128struct BoundTree<'a, T> {
129    /// The best bound applied to every key of each node.
130    tags: Vec<Option<&'a T>>,
131    /// The best bound applied to any key of each node, including its tag.
132    best: Vec<Option<&'a T>>,
133    /// Number of leaves, a power of two.
134    width: usize,
135}
136
137/// The order in which a [`BoundTree`] keeps the better of two bounds. A type
138/// parameter rather than a function pointer, so each sweep is monomorphized.
139trait Pick {
140    fn pick<'a, T: Ord>(lhs: &'a T, rhs: &'a T) -> &'a T;
141
142    fn combine<'a, T: Ord>(lhs: Option<&'a T>, rhs: Option<&'a T>) -> Option<&'a T> {
143        match (lhs, rhs) {
144            (Some(lhs), Some(rhs)) => Some(Self::pick(lhs, rhs)),
145            (lhs, rhs) => lhs.or(rhs),
146        }
147    }
148}
149
150/// Keeps the larger bound.
151struct Latest;
152
153impl Pick for Latest {
154    fn pick<'a, T: Ord>(lhs: &'a T, rhs: &'a T) -> &'a T {
155        max(lhs, rhs)
156    }
157}
158
159/// Keeps the smaller bound.
160struct Earliest;
161
162impl Pick for Earliest {
163    fn pick<'a, T: Ord>(lhs: &'a T, rhs: &'a T) -> &'a T {
164        min(lhs, rhs)
165    }
166}
167
168impl<'a, T: Ord> BoundTree<'a, T> {
169    fn new(len: usize) -> Self {
170        let width = len.next_power_of_two();
171        Self {
172            tags: vec![None; 2 * width],
173            best: vec![None; 2 * width],
174            width,
175        }
176    }
177
178    fn clear(&mut self) {
179        self.tags.fill(None);
180        self.best.fill(None);
181    }
182
183    /// Applies `bound` to every key in `[low, high]`.
184    fn update<P: Pick>(&mut self, low: usize, high: usize, bound: &'a T) {
185        self.update_in::<P>(1, 0, self.width - 1, low, high, bound);
186    }
187
188    fn update_in<P: Pick>(
189        &mut self,
190        node: usize,
191        node_low: usize,
192        node_high: usize,
193        low: usize,
194        high: usize,
195        bound: &'a T,
196    ) {
197        if high < node_low || node_high < low {
198            return;
199        }
200        self.best[node] = P::combine(self.best[node], Some(bound));
201        if low <= node_low && node_high <= high {
202            self.tags[node] = P::combine(self.tags[node], Some(bound));
203            return;
204        }
205        let mid = node_low + (node_high - node_low) / 2;
206        self.update_in::<P>(2 * node, node_low, mid, low, high, bound);
207        self.update_in::<P>(2 * node + 1, mid + 1, node_high, low, high, bound);
208    }
209
210    /// Returns the best bound applied to any key in `[low, high]`.
211    fn query<P: Pick>(&self, low: usize, high: usize) -> Option<&'a T> {
212        self.query_in::<P>(1, 0, self.width - 1, low, high)
213    }
214
215    fn query_in<P: Pick>(
216        &self,
217        node: usize,
218        node_low: usize,
219        node_high: usize,
220        low: usize,
221        high: usize,
222    ) -> Option<&'a T> {
223        if high < node_low || node_high < low {
224            return None;
225        }
226        if low <= node_low && node_high <= high {
227            return self.best[node];
228        }
229        let mid = node_low + (node_high - node_low) / 2;
230        let children = P::combine(
231            self.query_in::<P>(2 * node, node_low, mid, low, high),
232            self.query_in::<P>(2 * node + 1, mid + 1, node_high, low, high),
233        );
234        // The tag covers the part of the node inside the query range.
235        P::combine(self.tags[node], children)
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use rand::rngs::StdRng;
242    use rand::{Rng, SeedableRng};
243
244    use super::*;
245
246    fn extent(time: (i64, i64), key: Option<(u32, u32)>) -> Extent<i64, u32> {
247        Extent { time, key }
248    }
249
250    #[test]
251    fn test_find_overlaps_boundaries() {
252        for (extents, expected) in [
253            (vec![], vec![]),
254            (vec![extent((0, 10), Some((0, 0)))], vec![false]),
255            // Disjoint keys keep time-overlapping extents independent.
256            (
257                vec![extent((0, 10), Some((0, 4))), extent((5, 15), Some((5, 9)))],
258                vec![false, false],
259            ),
260            // Touching time and key endpoints are inclusive.
261            (
262                vec![
263                    extent((0, 10), Some((0, 4))),
264                    extent((10, 20), Some((4, 9))),
265                ],
266                vec![true, true],
267            ),
268            (
269                vec![
270                    extent((0, 10), Some((0, 4))),
271                    extent((11, 20), Some((0, 4))),
272                ],
273                vec![false, false],
274            ),
275            // An unknown key range overlaps every key.
276            (
277                vec![extent((0, 10), None), extent((5, 6), Some((7, 7)))],
278                vec![true, true],
279            ),
280            (
281                vec![extent((0, 10), None), extent((11, 12), None)],
282                vec![false, false],
283            ),
284            // A contained extent marks the earlier one as well.
285            (
286                vec![
287                    extent((0, 100), Some((0, 9))),
288                    extent((40, 50), Some((3, 3))),
289                ],
290                vec![true, true],
291            ),
292            // Overlap is not transitive.
293            (
294                vec![
295                    extent((0, 10), Some((0, 1))),
296                    extent((5, 15), Some((1, 2))),
297                    extent((12, 20), Some((0, 0))),
298                ],
299                vec![true, true, false],
300            ),
301            // Identical extents.
302            (
303                vec![extent((3, 3), Some((2, 2))), extent((3, 3), Some((2, 2)))],
304                vec![true, true],
305            ),
306        ] {
307            assert_eq!(find_overlaps(&extents), expected, "{extents:?}");
308            assert_eq!(find_overlaps_pairwise(&extents), expected, "{extents:?}");
309        }
310    }
311
312    #[test]
313    fn test_find_overlaps_matches_pairwise() {
314        let mut rng = StdRng::seed_from_u64(0x0c0_ffee);
315        for _ in 0..2000 {
316            let len = rng.random_range(0..40);
317            // Small domains force ties, containment and touching endpoints.
318            let time_domain = rng.random_range(1..60);
319            let key_domain = rng.random_range(1..30);
320            let extents: Vec<_> = (0..len)
321                .map(|_| {
322                    let start = rng.random_range(0..time_domain);
323                    let end = start + rng.random_range(0..time_domain / 4 + 1);
324                    let key = (!rng.random_bool(0.1)).then(|| {
325                        let min = rng.random_range(0..key_domain);
326                        (min, min + rng.random_range(0..key_domain / 4 + 1))
327                    });
328                    extent((start, end), key)
329                })
330                .collect();
331            assert_eq!(
332                find_overlaps(&extents),
333                find_overlaps_pairwise(&extents),
334                "{extents:?}"
335            );
336        }
337    }
338
339    #[test]
340    fn test_find_overlaps_time_overlapping_disjoint_keys() {
341        // The pairwise worst case: every extent overlaps in time, none in key.
342        let extents: Vec<_> = (0..10_000)
343            .map(|i| extent((0, 100), Some((i, i))))
344            .collect();
345        assert!(find_overlaps(&extents).iter().all(|overlap| !overlap));
346    }
347}