Skip to main content

mito2/read/
range.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//! Structs for partition ranges.
16
17use std::collections::BTreeMap;
18
19use bytes::Bytes;
20use common_time::Timestamp;
21use futures::future::BoxFuture;
22use smallvec::{SmallVec, smallvec};
23use store_api::region_engine::PartitionRange;
24use store_api::storage::TimeSeriesDistribution;
25
26use crate::cache::CacheStrategy;
27use crate::compaction::run::merge_primary_key_ranges;
28use crate::memtable::{MemtableRange, MemtableStats};
29use crate::read::scan_region::ScanInput;
30use crate::sst::file::{FileHandle, FileTimeRange, overlaps};
31use crate::sst::parquet::DEFAULT_ROW_GROUP_SIZE;
32use crate::sst::parquet::file_range::{FileRange, FileRangeContextRef};
33use crate::sst::parquet::format::parquet_row_group_time_range;
34use crate::sst::parquet::row_selection::RowGroupSelection;
35
36const ALL_ROW_GROUPS: i64 = -1;
37
38/// Index and metadata for a memtable or file.
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub(crate) struct SourceIndex {
41    /// Index of the memtable and file.
42    pub(crate) index: usize,
43    /// Total number of row groups in this source. 0 if the metadata
44    /// is unavailable. We use this to split files.
45    pub(crate) num_row_groups: u64,
46}
47
48/// Index to access a row group.
49#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct RowGroupIndex {
51    /// Index to the memtable/file.
52    pub(crate) index: usize,
53    /// Row group index in the file.
54    /// Negative index indicates all row groups.
55    pub row_group_index: i64,
56}
57
58/// Meta data of a partition range.
59/// If the scanner is [UnorderedScan], each meta only has one row group or memtable.
60/// If the scanner is [SeqScan], each meta may have multiple row groups and memtables.
61#[derive(Debug, PartialEq, Clone)]
62pub(crate) struct RangeMeta {
63    /// The time range of the range.
64    pub(crate) time_range: FileTimeRange,
65    /// Indices to memtables or files.
66    pub(crate) indices: SmallVec<[SourceIndex; 2]>,
67    /// Indices to memtable/file row groups that this range scans.
68    pub(crate) row_group_indices: SmallVec<[RowGroupIndex; 2]>,
69    /// Estimated number of rows in the range. This can be 0 if the statistics are not available.
70    pub(crate) num_rows: usize,
71}
72
73impl RangeMeta {
74    /// Creates a [PartitionRange] with specific identifier.
75    /// It converts the inclusive max timestamp to exclusive end timestamp.
76    pub(crate) fn new_partition_range(&self, identifier: usize) -> PartitionRange {
77        PartitionRange {
78            start: self.time_range.0,
79            end: Timestamp::new(
80                // The i64::MAX timestamp may be invisible but we don't guarantee to support this
81                // value now.
82                self.time_range
83                    .1
84                    .value()
85                    .checked_add(1)
86                    .unwrap_or(self.time_range.1.value()),
87                self.time_range.1.unit(),
88            ),
89            num_rows: self.num_rows,
90            identifier,
91        }
92    }
93
94    /// Creates a list of ranges from the `input` for seq scan.
95    /// If `input.compaction` is true, it doesn't split the ranges.
96    pub(crate) fn seq_scan_ranges(input: &ScanInput) -> Vec<RangeMeta> {
97        let mut ranges = Vec::with_capacity(input.memtables.len() + input.files.len());
98        Self::push_seq_mem_ranges(&input.memtables, &mut ranges);
99        Self::push_seq_file_ranges(input.memtables.len(), &input.files, &mut ranges);
100
101        #[cfg(feature = "enterprise")]
102        Self::push_extension_ranges(input, &mut ranges);
103
104        let per_series = input.distribution == Some(TimeSeriesDistribution::PerSeries);
105        // Scans with a distribution keep grouping ranges by time only. `RegionScanExec`
106        // declares `(ts, primary key)` ordering for `TimeWindowed`; SeqScan already breaks it
107        // for files that overlap in keys, and splitting by key would break it for disjoint ones.
108        let split_by_key = input.distribution.is_none();
109        let num_memtables = input.memtables.len();
110        let mapper = input.primary_key_mapper();
111        let ranges = ranges
112            .into_iter()
113            .map(|range| {
114                let primary_keys = range.indices[0]
115                    .index
116                    .checked_sub(num_memtables)
117                    .and_then(|i| input.files.get(i))
118                    .filter(|_| split_by_key)
119                    .and_then(|file| file.primary_key_range(mapper));
120                (range, primary_keys)
121            })
122            .collect();
123        let ranges = group_ranges_for_seq_scan(ranges);
124        if input.compaction || per_series {
125            // We don't split ranges in compaction or TimeSeriesDistribution::PerSeries.
126            return ranges;
127        }
128        maybe_split_ranges_for_seq_scan(ranges)
129    }
130
131    /// Creates a list of ranges from the `input` for unordered scan.
132    pub(crate) fn unordered_scan_ranges(input: &ScanInput) -> BoxFuture<'_, Vec<RangeMeta>> {
133        // Keep Moka's async lookup type out of callers' nested scanner futures.
134        Box::pin(async move {
135            let mut ranges = Vec::with_capacity(input.memtables.len() + input.files.len());
136            Self::push_unordered_mem_ranges(&input.memtables, &mut ranges);
137            Self::push_unordered_file_ranges(
138                input.memtables.len(),
139                &input.files,
140                &input.cache_strategy,
141                &mut ranges,
142            )
143            .await;
144
145            #[cfg(feature = "enterprise")]
146            Self::push_extension_ranges(input, &mut ranges);
147
148            ranges
149        })
150    }
151
152    /// Returns true if the time range of given `meta` overlaps with the time range of this meta.
153    fn overlaps(&self, meta: &RangeMeta) -> bool {
154        overlaps(&self.time_range, &meta.time_range)
155    }
156
157    /// Merges given `meta` to this meta.
158    /// It assumes that the time ranges overlap and they don't have the same file or memtable index.
159    fn merge(&mut self, mut other: RangeMeta) {
160        debug_assert!(self.overlaps(&other));
161        debug_assert!(self.indices.iter().all(|idx| !other.indices.contains(idx)));
162        debug_assert!(
163            self.row_group_indices
164                .iter()
165                .all(|idx| !other.row_group_indices.contains(idx))
166        );
167
168        self.time_range = (
169            self.time_range.0.min(other.time_range.0),
170            self.time_range.1.max(other.time_range.1),
171        );
172        self.indices.append(&mut other.indices);
173        self.row_group_indices.append(&mut other.row_group_indices);
174        self.num_rows = self.num_rows.saturating_add(other.num_rows);
175    }
176
177    /// Returns true if we can split the range into multiple smaller ranges and
178    /// still preserve the order for [SeqScan].
179    fn can_split_preserve_order(&self) -> bool {
180        self.indices.len() == 1 && self.indices[0].num_row_groups > 1
181    }
182
183    /// Splits the range if it can preserve the order.
184    fn maybe_split(self, output: &mut Vec<RangeMeta>) {
185        if self.can_split_preserve_order() {
186            let num_row_groups = self.indices[0].num_row_groups;
187            debug_assert_eq!(1, self.row_group_indices.len());
188            debug_assert_eq!(ALL_ROW_GROUPS, self.row_group_indices[0].row_group_index);
189
190            output.reserve(self.row_group_indices.len());
191            let num_rows = self.num_rows / num_row_groups as usize;
192            // Splits by row group.
193            for row_group_index in 0..num_row_groups {
194                output.push(RangeMeta {
195                    time_range: self.time_range,
196                    indices: self.indices.clone(),
197                    row_group_indices: smallvec![RowGroupIndex {
198                        index: self.indices[0].index,
199                        row_group_index: row_group_index as i64,
200                    }],
201                    num_rows,
202                });
203            }
204        } else {
205            output.push(self);
206        }
207    }
208
209    fn push_unordered_mem_ranges(memtables: &[MemRangeBuilder], ranges: &mut Vec<RangeMeta>) {
210        // For append mode, we can parallelize reading memtables.
211        for (memtable_index, memtable) in memtables.iter().enumerate() {
212            let stats = memtable.stats();
213            let Some(time_range) = stats.time_range() else {
214                continue;
215            };
216            for row_group_index in 0..stats.num_ranges() {
217                let num_rows = stats.num_rows() / stats.num_ranges();
218                ranges.push(RangeMeta {
219                    time_range,
220                    indices: smallvec![SourceIndex {
221                        index: memtable_index,
222                        num_row_groups: stats.num_ranges() as u64,
223                    }],
224                    row_group_indices: smallvec![RowGroupIndex {
225                        index: memtable_index,
226                        row_group_index: row_group_index as i64,
227                    }],
228                    num_rows,
229                });
230            }
231        }
232    }
233
234    async fn push_unordered_file_ranges(
235        num_memtables: usize,
236        files: &[FileHandle],
237        cache: &CacheStrategy,
238        ranges: &mut Vec<RangeMeta>,
239    ) {
240        // For append mode, we can parallelize reading row groups.
241        for (i, file) in files.iter().enumerate() {
242            let file_index = num_memtables + i;
243            // Get parquet meta from the cache.
244            let parquet_meta = cache
245                .get_parquet_meta_data_from_mem_cache(file.file_id())
246                .await;
247            if let Some(parquet_meta) = parquet_meta {
248                // Scans each row group.
249                for row_group_index in 0..file.meta_ref().num_row_groups {
250                    let time_range = parquet_row_group_time_range(
251                        file.meta_ref(),
252                        &parquet_meta,
253                        row_group_index as usize,
254                    );
255                    let num_rows = parquet_meta.row_group(row_group_index as usize).num_rows();
256                    ranges.push(RangeMeta {
257                        time_range: time_range.unwrap_or_else(|| file.time_range()),
258                        indices: smallvec![SourceIndex {
259                            index: file_index,
260                            num_row_groups: file.meta_ref().num_row_groups,
261                        }],
262                        row_group_indices: smallvec![RowGroupIndex {
263                            index: file_index,
264                            row_group_index: row_group_index as i64,
265                        }],
266                        num_rows: num_rows as usize,
267                    });
268                }
269            } else if file.meta_ref().num_row_groups > 0 {
270                // Scans each row group.
271                for row_group_index in 0..file.meta_ref().num_row_groups {
272                    ranges.push(RangeMeta {
273                        time_range: file.time_range(),
274                        indices: smallvec![SourceIndex {
275                            index: file_index,
276                            num_row_groups: file.meta_ref().num_row_groups,
277                        }],
278                        row_group_indices: smallvec![RowGroupIndex {
279                            index: file_index,
280                            row_group_index: row_group_index as i64,
281                        }],
282                        num_rows: DEFAULT_ROW_GROUP_SIZE,
283                    });
284                }
285            } else {
286                // If we don't known the number of row groups in advance, scan all row groups.
287                ranges.push(RangeMeta {
288                    time_range: file.time_range(),
289                    indices: smallvec![SourceIndex {
290                        index: file_index,
291                        num_row_groups: 0,
292                    }],
293                    row_group_indices: smallvec![RowGroupIndex {
294                        index: file_index,
295                        row_group_index: ALL_ROW_GROUPS,
296                    }],
297                    // This may be 0.
298                    num_rows: file.meta_ref().num_rows as usize,
299                });
300            }
301        }
302    }
303
304    fn push_seq_mem_ranges(memtables: &[MemRangeBuilder], ranges: &mut Vec<RangeMeta>) {
305        // For non append-only mode, each range only contains one memtable by default.
306        for (i, memtable) in memtables.iter().enumerate() {
307            let stats = memtable.stats();
308            let Some(time_range) = stats.time_range() else {
309                continue;
310            };
311            ranges.push(RangeMeta {
312                time_range,
313                indices: smallvec![SourceIndex {
314                    index: i,
315                    num_row_groups: stats.num_ranges() as u64,
316                }],
317                row_group_indices: smallvec![RowGroupIndex {
318                    index: i,
319                    row_group_index: ALL_ROW_GROUPS,
320                }],
321                num_rows: stats.num_rows(),
322            });
323        }
324    }
325
326    fn push_seq_file_ranges(
327        num_memtables: usize,
328        files: &[FileHandle],
329        ranges: &mut Vec<RangeMeta>,
330    ) {
331        // For non append-only mode, each range only contains one file.
332        for (i, file) in files.iter().enumerate() {
333            let file_index = num_memtables + i;
334            ranges.push(RangeMeta {
335                time_range: file.time_range(),
336                indices: smallvec![SourceIndex {
337                    index: file_index,
338                    num_row_groups: file.meta_ref().num_row_groups,
339                }],
340                row_group_indices: smallvec![RowGroupIndex {
341                    index: file_index,
342                    row_group_index: ALL_ROW_GROUPS,
343                }],
344                num_rows: file.meta_ref().num_rows as usize,
345            });
346        }
347    }
348
349    #[cfg(feature = "enterprise")]
350    fn push_extension_ranges(input: &ScanInput, metas: &mut Vec<RangeMeta>) {
351        for (i, range) in input.extension_ranges().iter().enumerate() {
352            let index = input.num_memtables() + input.num_files() + i;
353            metas.push(RangeMeta {
354                time_range: range.time_range(),
355                indices: smallvec![SourceIndex {
356                    index,
357                    num_row_groups: range.num_row_groups(),
358                }],
359                row_group_indices: smallvec![RowGroupIndex {
360                    index,
361                    row_group_index: ALL_ROW_GROUPS,
362                }],
363                num_rows: range.num_rows() as usize,
364            });
365        }
366    }
367}
368
369/// Groups ranges so that all versions of a (primary key, timestamp) pair stay
370/// together for deduplication. Ranges with disjoint time or primary key ranges
371/// can be scanned independently. An unknown primary key range can match any key.
372/// It assumes each input range only contains a file or a memtable.
373fn group_ranges_for_seq_scan(
374    mut ranges: Vec<(RangeMeta, Option<(Bytes, Bytes)>)>,
375) -> Vec<RangeMeta> {
376    // Sorts ranges by time range (start asc, end desc).
377    ranges.sort_unstable_by(|(a, _), (b, _)| compare_time_ranges(a, b));
378    let mut groups = Vec::with_capacity(ranges.len());
379    // Groups with known keys, by min key to (max key, group). Their key ranges are disjoint.
380    // A group that ended before the current range starts is closed when a lookup reaches it.
381    let mut keyed: BTreeMap<Bytes, (Bytes, RangeMeta)> = BTreeMap::new();
382    // A group with unknown keys. While it is open, `keyed` is empty.
383    let mut unknown: Option<RangeMeta> = None;
384    for (range, primary_keys) in ranges {
385        // Later ranges start no earlier than this one, so groups ending before it are complete.
386        let start = range.time_range.0;
387        let mut current = range;
388        let mut current_keys = primary_keys;
389        if let Some(group) = unknown.take() {
390            if group.time_range.1 < start {
391                groups.push(group);
392            } else {
393                current = merge_ranges(group, current);
394                current_keys = None;
395            }
396        }
397
398        // The key ranges are disjoint, so their upper bounds have the same order as
399        // their lower bounds. Walking backward, stop at the first range ending below `min`.
400        let candidates: Vec<_> = match &current_keys {
401            Some((min, max)) => keyed
402                .range(..=max.clone())
403                .rev()
404                .take_while(|(_, (group_max, _))| group_max >= min)
405                .map(|(group_min, _)| group_min.clone())
406                .collect(),
407            None => keyed.keys().cloned().collect(),
408        };
409        for group_min in candidates {
410            let (group_max, group) = keyed.remove(&group_min).unwrap();
411            if group.time_range.1 < start {
412                groups.push(group);
413            } else {
414                current = merge_ranges(group, current);
415                current_keys = merge_primary_key_ranges(current_keys, Some((group_min, group_max)));
416            }
417        }
418
419        match current_keys {
420            Some((min, max)) => {
421                keyed.insert(min, (max, current));
422            }
423            None => {
424                // Unknown keys overlap every group, so the lookup above emptied `keyed`.
425                debug_assert!(keyed.is_empty());
426                unknown = Some(current);
427            }
428        }
429    }
430    groups.extend(unknown);
431    groups.extend(keyed.into_values().map(|(_, group)| group));
432    groups.sort_unstable_by(compare_time_ranges);
433    groups
434}
435
436/// Appends the smaller range to the larger one, so each index is copied O(log n) times over
437/// all merges of a scan.
438fn merge_ranges(a: RangeMeta, b: RangeMeta) -> RangeMeta {
439    let (mut larger, smaller) = if a.row_group_indices.len() >= b.row_group_indices.len() {
440        (a, b)
441    } else {
442        (b, a)
443    };
444    larger.merge(smaller);
445    larger
446}
447
448fn compare_time_ranges(a: &RangeMeta, b: &RangeMeta) -> std::cmp::Ordering {
449    let (l, r) = (a.time_range, b.time_range);
450    l.0.cmp(&r.0).then_with(|| r.1.cmp(&l.1))
451}
452
453/// Splits the range into multiple smaller ranges.
454/// It assumes the input `ranges` list is created by [group_ranges_for_seq_scan()].
455fn maybe_split_ranges_for_seq_scan(ranges: Vec<RangeMeta>) -> Vec<RangeMeta> {
456    let mut new_ranges = Vec::with_capacity(ranges.len());
457    for range in ranges {
458        range.maybe_split(&mut new_ranges);
459    }
460
461    new_ranges
462}
463
464/// Builder to create file ranges.
465#[derive(Default)]
466pub struct FileRangeBuilder {
467    /// Context for the file.
468    /// None indicates nothing to read.
469    context: Option<FileRangeContextRef>,
470    /// Row group selection for the file to read.
471    selection: RowGroupSelection,
472}
473
474impl FileRangeBuilder {
475    /// Builds a file range builder from context and row groups.
476    pub fn new(context: FileRangeContextRef, selection: RowGroupSelection) -> Self {
477        Self {
478            context: Some(context),
479            selection,
480        }
481    }
482
483    /// Builds file ranges to read.
484    /// Negative `row_group_index` indicates all row groups.
485    pub fn build_ranges(&self, row_group_index: i64, ranges: &mut SmallVec<[FileRange; 2]>) {
486        let Some(context) = self.context.clone() else {
487            return;
488        };
489        if row_group_index >= 0 {
490            let row_group_index = row_group_index as usize;
491            // Scans one row group.
492            let Some(row_selection) = self.selection.get(row_group_index) else {
493                return;
494            };
495            ranges.push(FileRange::new(
496                context,
497                row_group_index,
498                Some(row_selection.clone()),
499            ));
500        } else {
501            // Scans all row groups.
502            ranges.extend(
503                self.selection
504                    .iter()
505                    .map(|(row_group_index, row_selection)| {
506                        FileRange::new(
507                            context.clone(),
508                            *row_group_index,
509                            Some(row_selection.clone()),
510                        )
511                    }),
512            );
513        }
514    }
515
516    /// Returns the estimated memory size of this builder.
517    pub(crate) fn memory_size(&self) -> usize {
518        let context_size = self
519            .context
520            .as_ref()
521            .map(|ctx| ctx.memory_size())
522            .unwrap_or(0);
523        let selection_size = self.selection.mem_usage();
524        context_size + selection_size
525    }
526}
527
528/// Builder to create mem ranges.
529#[derive(Clone)]
530pub(crate) struct MemRangeBuilder {
531    /// Ranges of a memtable.
532    range: MemtableRange,
533    /// Stats of a memtable.
534    stats: MemtableStats,
535}
536
537impl MemRangeBuilder {
538    /// Builds a mem range builder from row groups.
539    pub(crate) fn new(range: MemtableRange, stats: MemtableStats) -> Self {
540        Self { range, stats }
541    }
542
543    /// Builds mem ranges to read in the memtable.
544    /// Negative `row_group_index` indicates all row groups.
545    pub(crate) fn build_ranges(
546        &self,
547        _row_group_index: i64,
548        ranges: &mut SmallVec<[MemtableRange; 2]>,
549    ) {
550        ranges.push(self.range.clone())
551    }
552
553    /// Returns the statistics of the memtable.
554    pub(crate) fn stats(&self) -> &MemtableStats {
555        &self.stats
556    }
557}
558
559#[cfg(test)]
560mod tests {
561    use common_time::Timestamp;
562    use common_time::timestamp::TimeUnit;
563
564    use super::*;
565
566    type Output = (Vec<usize>, i64, i64);
567
568    fn run_group_ranges_test(input: &[(usize, i64, i64)], expect: &[Output]) {
569        let ranges = input
570            .iter()
571            .map(|(idx, start, end)| {
572                let time_range = (
573                    Timestamp::new(*start, TimeUnit::Second),
574                    Timestamp::new(*end, TimeUnit::Second),
575                );
576                let range = RangeMeta {
577                    time_range,
578                    indices: smallvec![SourceIndex {
579                        index: *idx,
580                        num_row_groups: 0,
581                    }],
582                    row_group_indices: smallvec![RowGroupIndex {
583                        index: *idx,
584                        row_group_index: 0
585                    }],
586                    num_rows: 1,
587                };
588                (range, None)
589            })
590            .collect();
591        let output = group_ranges_for_seq_scan(ranges);
592        let actual: Vec<_> = output
593            .iter()
594            .map(|range| {
595                let indices = range.indices.iter().map(|index| index.index).collect();
596                let group_indices: Vec<_> = range
597                    .row_group_indices
598                    .iter()
599                    .map(|idx| idx.index)
600                    .collect();
601                assert_eq!(indices, group_indices);
602                let range = range.time_range;
603                (indices, range.0.value(), range.1.value())
604            })
605            .collect();
606        assert_eq!(expect, actual);
607    }
608
609    #[test]
610    fn test_group_ranges() {
611        // Group 1 part.
612        run_group_ranges_test(&[(1, 0, 2000)], &[(vec![1], 0, 2000)]);
613
614        // 1, 2, 3, 4 => [3, 1, 4], [2]
615        run_group_ranges_test(
616            &[
617                (1, 1000, 2000),
618                (2, 6000, 7000),
619                (3, 0, 1500),
620                (4, 1500, 3000),
621            ],
622            &[(vec![3, 1, 4], 0, 3000), (vec![2], 6000, 7000)],
623        );
624
625        // 1, 2, 3 => [3], [1], [2],
626        run_group_ranges_test(
627            &[(1, 3000, 4000), (2, 4001, 6000), (3, 0, 1000)],
628            &[
629                (vec![3], 0, 1000),
630                (vec![1], 3000, 4000),
631                (vec![2], 4001, 6000),
632            ],
633        );
634
635        // 1, 2, 3 => [3], [1, 2]
636        run_group_ranges_test(
637            &[(1, 3000, 4000), (2, 4000, 6000), (3, 0, 1000)],
638            &[(vec![3], 0, 1000), (vec![1, 2], 3000, 6000)],
639        );
640    }
641
642    /// `(index, start, end, primary key range)` of a range.
643    type KeyedRange = (usize, i64, i64, Option<(&'static str, &'static str)>);
644
645    /// Groups the ranges and returns the sorted indices of each group, in sorted order.
646    fn group_with_keys(input: &[KeyedRange]) -> Vec<Vec<usize>> {
647        let ranges = input
648            .iter()
649            .map(|(idx, start, end, keys)| {
650                let range = RangeMeta {
651                    time_range: (Timestamp::new_second(*start), Timestamp::new_second(*end)),
652                    indices: smallvec![SourceIndex {
653                        index: *idx,
654                        num_row_groups: 0,
655                    }],
656                    row_group_indices: smallvec![RowGroupIndex {
657                        index: *idx,
658                        row_group_index: 0
659                    }],
660                    num_rows: 1,
661                };
662                let keys = keys.map(|(min, max)| {
663                    (
664                        Bytes::copy_from_slice(min.as_bytes()),
665                        Bytes::copy_from_slice(max.as_bytes()),
666                    )
667                });
668                (range, keys)
669            })
670            .collect();
671        let mut groups: Vec<_> = group_ranges_for_seq_scan(ranges)
672            .iter()
673            .map(|range| {
674                let mut indices: Vec<_> = range.indices.iter().map(|i| i.index).collect();
675                indices.sort_unstable();
676                indices
677            })
678            .collect();
679        groups.sort_unstable();
680        groups
681    }
682
683    #[test]
684    fn test_group_ranges_by_primary_keys() {
685        // Outputs of one compaction cover the same time range with disjoint keys.
686        let outputs = [
687            (1, 0, 100, Some(("a", "b"))),
688            (2, 0, 100, Some(("c", "d"))),
689            (3, 0, 100, Some(("e", "f"))),
690        ];
691        assert_eq!(vec![vec![1], vec![2], vec![3]], group_with_keys(&outputs));
692
693        // A range whose keys span two groups joins them; ranges with shared boundary keys overlap.
694        let mut input = outputs.to_vec();
695        input.push((4, 50, 150, Some(("b", "c"))));
696        assert_eq!(vec![vec![1, 2, 4], vec![3]], group_with_keys(&input));
697
698        // Unknown keys may overlap anything in the same time range.
699        let mut input = outputs.to_vec();
700        input.push((4, 90, 200, None));
701        assert_eq!(vec![vec![1, 2, 3, 4]], group_with_keys(&input));
702
703        // Ranges sharing keys still chain through time; a range with other keys stays apart.
704        let input = [
705            (1, 0, 10, Some(("a", "a"))),
706            (2, 5, 20, Some(("a", "b"))),
707            (3, 15, 30, Some(("b", "b"))),
708            (4, 15, 30, Some(("c", "c"))),
709        ];
710        assert_eq!(vec![vec![1, 2, 3], vec![4]], group_with_keys(&input));
711
712        // A group that ended before a range starts stays apart even if their keys overlap.
713        let input = [
714            (1, 0, 10, Some(("a", "b"))),
715            (2, 20, 30, Some(("a", "b"))),
716            (3, 20, 30, Some(("c", "c"))),
717        ];
718        assert_eq!(vec![vec![1], vec![2], vec![3]], group_with_keys(&input));
719
720        // An open group with unknown keys takes every range it overlaps in time.
721        let input = [
722            (1, 0, 50, None),
723            (2, 10, 20, Some(("a", "a"))),
724            (3, 40, 60, Some(("b", "b"))),
725            (4, 70, 80, Some(("a", "a"))),
726            (5, 70, 80, Some(("b", "b"))),
727        ];
728        assert_eq!(
729            vec![vec![1, 2, 3], vec![4], vec![5]],
730            group_with_keys(&input)
731        );
732    }
733
734    #[test]
735    fn test_group_ranges_never_split_overlapping_ranges() {
736        use rand::rngs::StdRng;
737        use rand::{Rng, SeedableRng};
738
739        const KEYS: [&str; 8] = ["a", "b", "c", "d", "e", "f", "g", "h"];
740        let mut rng = StdRng::seed_from_u64(42);
741        for _ in 0..200 {
742            let input: Vec<KeyedRange> = (0..rng.random_range(1..40))
743                .map(|idx| {
744                    let start = rng.random_range(0..100);
745                    let end = start + rng.random_range(0..20);
746                    let keys = rng.random_bool(0.9).then(|| {
747                        let lo = rng.random_range(0..KEYS.len());
748                        let hi = rng.random_range(lo..KEYS.len());
749                        (KEYS[lo], KEYS[hi])
750                    });
751                    (idx, start, end, keys)
752                })
753                .collect();
754            let groups = group_with_keys(&input);
755            let group_of = |idx: usize| groups.iter().position(|g| g.contains(&idx)).unwrap();
756            assert_eq!(input.len(), groups.iter().map(Vec::len).sum::<usize>());
757            for (i, (_, a_start, a_end, a_keys)) in input.iter().enumerate() {
758                for (j, (_, b_start, b_end, b_keys)) in input.iter().enumerate().skip(i + 1) {
759                    let times = a_start.max(b_start) <= a_end.min(b_end);
760                    let keys = match (a_keys, b_keys) {
761                        (Some(a), Some(b)) => a.0.max(b.0) <= a.1.min(b.1),
762                        _ => true,
763                    };
764                    if times && keys {
765                        assert_eq!(group_of(i), group_of(j), "{input:?}");
766                    }
767                }
768            }
769        }
770    }
771
772    #[test]
773    fn test_merge_range() {
774        let mut left = RangeMeta {
775            time_range: (Timestamp::new_second(1000), Timestamp::new_second(2000)),
776            indices: smallvec![SourceIndex {
777                index: 1,
778                num_row_groups: 2,
779            }],
780            row_group_indices: smallvec![
781                RowGroupIndex {
782                    index: 1,
783                    row_group_index: 1
784                },
785                RowGroupIndex {
786                    index: 1,
787                    row_group_index: 2
788                }
789            ],
790            num_rows: 5,
791        };
792        let right = RangeMeta {
793            time_range: (Timestamp::new_second(800), Timestamp::new_second(1200)),
794            indices: smallvec![SourceIndex {
795                index: 2,
796                num_row_groups: 2,
797            }],
798            row_group_indices: smallvec![
799                RowGroupIndex {
800                    index: 2,
801                    row_group_index: 1
802                },
803                RowGroupIndex {
804                    index: 2,
805                    row_group_index: 2
806                }
807            ],
808            num_rows: 4,
809        };
810        left.merge(right);
811
812        assert_eq!(
813            left,
814            RangeMeta {
815                time_range: (Timestamp::new_second(800), Timestamp::new_second(2000)),
816                indices: smallvec![
817                    SourceIndex {
818                        index: 1,
819                        num_row_groups: 2
820                    },
821                    SourceIndex {
822                        index: 2,
823                        num_row_groups: 2
824                    }
825                ],
826                row_group_indices: smallvec![
827                    RowGroupIndex {
828                        index: 1,
829                        row_group_index: 1
830                    },
831                    RowGroupIndex {
832                        index: 1,
833                        row_group_index: 2
834                    },
835                    RowGroupIndex {
836                        index: 2,
837                        row_group_index: 1
838                    },
839                    RowGroupIndex {
840                        index: 2,
841                        row_group_index: 2
842                    },
843                ],
844                num_rows: 9,
845            }
846        );
847    }
848
849    #[test]
850    fn test_split_range() {
851        let range = RangeMeta {
852            time_range: (Timestamp::new_second(1000), Timestamp::new_second(2000)),
853            indices: smallvec![SourceIndex {
854                index: 1,
855                num_row_groups: 2,
856            }],
857            row_group_indices: smallvec![RowGroupIndex {
858                index: 1,
859                row_group_index: ALL_ROW_GROUPS,
860            }],
861            num_rows: 5,
862        };
863
864        assert!(range.can_split_preserve_order());
865        let mut output = Vec::new();
866        range.maybe_split(&mut output);
867
868        assert_eq!(
869            output,
870            &[
871                RangeMeta {
872                    time_range: (Timestamp::new_second(1000), Timestamp::new_second(2000)),
873                    indices: smallvec![SourceIndex {
874                        index: 1,
875                        num_row_groups: 2,
876                    }],
877                    row_group_indices: smallvec![RowGroupIndex {
878                        index: 1,
879                        row_group_index: 0
880                    },],
881                    num_rows: 2,
882                },
883                RangeMeta {
884                    time_range: (Timestamp::new_second(1000), Timestamp::new_second(2000)),
885                    indices: smallvec![SourceIndex {
886                        index: 1,
887                        num_row_groups: 2,
888                    }],
889                    row_group_indices: smallvec![RowGroupIndex {
890                        index: 1,
891                        row_group_index: 1
892                    }],
893                    num_rows: 2,
894                }
895            ]
896        );
897    }
898
899    #[test]
900    fn test_not_split_range() {
901        let range = RangeMeta {
902            time_range: (Timestamp::new_second(1000), Timestamp::new_second(2000)),
903            indices: smallvec![
904                SourceIndex {
905                    index: 1,
906                    num_row_groups: 1,
907                },
908                SourceIndex {
909                    index: 2,
910                    num_row_groups: 1,
911                }
912            ],
913            row_group_indices: smallvec![
914                RowGroupIndex {
915                    index: 1,
916                    row_group_index: 1
917                },
918                RowGroupIndex {
919                    index: 2,
920                    row_group_index: 1
921                }
922            ],
923            num_rows: 5,
924        };
925
926        assert!(!range.can_split_preserve_order());
927        let mut output = Vec::new();
928        range.maybe_split(&mut output);
929        assert_eq!(1, output.len());
930    }
931
932    #[test]
933    fn test_maybe_split_ranges() {
934        let ranges = vec![
935            RangeMeta {
936                time_range: (Timestamp::new_second(0), Timestamp::new_second(500)),
937                indices: smallvec![SourceIndex {
938                    index: 0,
939                    num_row_groups: 1,
940                }],
941                row_group_indices: smallvec![RowGroupIndex {
942                    index: 0,
943                    row_group_index: 0,
944                },],
945                num_rows: 4,
946            },
947            RangeMeta {
948                time_range: (Timestamp::new_second(1000), Timestamp::new_second(2000)),
949                indices: smallvec![SourceIndex {
950                    index: 1,
951                    num_row_groups: 2,
952                }],
953                row_group_indices: smallvec![RowGroupIndex {
954                    index: 1,
955                    row_group_index: ALL_ROW_GROUPS,
956                },],
957                num_rows: 4,
958            },
959            RangeMeta {
960                time_range: (Timestamp::new_second(3000), Timestamp::new_second(4000)),
961                indices: smallvec![
962                    SourceIndex {
963                        index: 2,
964                        num_row_groups: 2,
965                    },
966                    SourceIndex {
967                        index: 3,
968                        num_row_groups: 0,
969                    }
970                ],
971                row_group_indices: smallvec![
972                    RowGroupIndex {
973                        index: 2,
974                        row_group_index: ALL_ROW_GROUPS,
975                    },
976                    RowGroupIndex {
977                        index: 3,
978                        row_group_index: ALL_ROW_GROUPS,
979                    }
980                ],
981                num_rows: 5,
982            },
983        ];
984        let output = maybe_split_ranges_for_seq_scan(ranges);
985        assert_eq!(
986            output,
987            vec![
988                RangeMeta {
989                    time_range: (Timestamp::new_second(0), Timestamp::new_second(500)),
990                    indices: smallvec![SourceIndex {
991                        index: 0,
992                        num_row_groups: 1,
993                    }],
994                    row_group_indices: smallvec![RowGroupIndex {
995                        index: 0,
996                        row_group_index: 0
997                    },],
998                    num_rows: 4,
999                },
1000                RangeMeta {
1001                    time_range: (Timestamp::new_second(1000), Timestamp::new_second(2000)),
1002                    indices: smallvec![SourceIndex {
1003                        index: 1,
1004                        num_row_groups: 2,
1005                    }],
1006                    row_group_indices: smallvec![RowGroupIndex {
1007                        index: 1,
1008                        row_group_index: 0
1009                    },],
1010                    num_rows: 2,
1011                },
1012                RangeMeta {
1013                    time_range: (Timestamp::new_second(1000), Timestamp::new_second(2000)),
1014                    indices: smallvec![SourceIndex {
1015                        index: 1,
1016                        num_row_groups: 2,
1017                    }],
1018                    row_group_indices: smallvec![RowGroupIndex {
1019                        index: 1,
1020                        row_group_index: 1
1021                    }],
1022                    num_rows: 2,
1023                },
1024                RangeMeta {
1025                    time_range: (Timestamp::new_second(3000), Timestamp::new_second(4000)),
1026                    indices: smallvec![
1027                        SourceIndex {
1028                            index: 2,
1029                            num_row_groups: 2
1030                        },
1031                        SourceIndex {
1032                            index: 3,
1033                            num_row_groups: 0,
1034                        }
1035                    ],
1036                    row_group_indices: smallvec![
1037                        RowGroupIndex {
1038                            index: 2,
1039                            row_group_index: ALL_ROW_GROUPS,
1040                        },
1041                        RowGroupIndex {
1042                            index: 3,
1043                            row_group_index: ALL_ROW_GROUPS,
1044                        }
1045                    ],
1046                    num_rows: 5,
1047                },
1048            ]
1049        )
1050    }
1051}