Skip to main content

mito2/compaction/
unit.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
15use std::collections::{BTreeMap, HashMap, HashSet};
16
17use crate::batch_size::estimate_batch_size;
18use crate::compaction::CompactionOutput;
19use crate::compaction::picker::PickerOutput;
20use crate::compaction::reader::MERGED_BATCH_CHANNEL_SIZE;
21use crate::read::seq_scan::compaction_input_channel_size;
22use crate::sst::file::{FileHandle, FileMeta};
23
24/// A complete input dependency group, merged and published atomically.
25///
26/// Logical outputs retain their original input sets and time bounds. In particular,
27/// splitting physical SSTs must never split a strict-window input dependency group.
28#[derive(Debug, Clone)]
29pub(crate) struct CompactionUnit {
30    /// Distinct input SSTs reserved and removed together.
31    pub(crate) inputs: Vec<FileHandle>,
32    /// Original logical outputs; empty for expiration-only maintenance.
33    pub(crate) outputs: Vec<CompactionOutput>,
34    /// Compaction window size in seconds.
35    pub(crate) time_window_size: i64,
36    /// Maximum physical output SST size in bytes.
37    pub(crate) max_file_size: Option<usize>,
38}
39
40impl CompactionUnit {
41    /// Groups outputs by the transitive closure of shared input FileIds.
42    /// Returns `None` for an inconsistent plan that both expires and merges a file.
43    /// Expiration maintenance runs before merge units, matching the legacy pre-merge removal.
44    /// Merge units follow the legacy compactor's tail-first execution order; a shared-input
45    /// group inherits the position of its highest-priority output.
46    pub(crate) fn from_picker(output: PickerOutput) -> Option<Vec<Self>> {
47        let PickerOutput {
48            outputs,
49            expired_ssts,
50            time_window_size,
51            max_file_size,
52        } = output;
53        let mut parents: Vec<_> = (0..outputs.len()).collect();
54        let mut owners = HashMap::new();
55        for (index, output) in outputs.iter().enumerate() {
56            for file in &output.inputs {
57                if let Some(&previous) = owners.get(&file.file_id()) {
58                    let a = root(&mut parents, previous);
59                    let b = root(&mut parents, index);
60                    // Higher output indices are consumed first by the legacy compactor.
61                    parents[a.min(b)] = a.max(b);
62                } else {
63                    owners.insert(file.file_id(), index);
64                }
65            }
66        }
67        if expired_ssts
68            .iter()
69            .any(|f| owners.contains_key(&f.file_id()))
70        {
71            return None;
72        }
73
74        let mut groups: BTreeMap<usize, Vec<CompactionOutput>> = BTreeMap::new();
75        for (index, output) in outputs.into_iter().enumerate() {
76            groups
77                .entry(root(&mut parents, index))
78                .or_default()
79                .push(output);
80        }
81        let mut units = Vec::with_capacity(groups.len() + 1);
82        if !expired_ssts.is_empty() {
83            let mut seen = HashSet::new();
84            units.push(Self {
85                inputs: expired_ssts
86                    .into_iter()
87                    .filter(|f| seen.insert(f.file_id()))
88                    .collect(),
89                outputs: Vec::new(),
90                time_window_size,
91                max_file_size,
92            });
93        }
94        for outputs in groups.into_values().rev() {
95            let mut seen = HashSet::new();
96            let inputs: Vec<_> = outputs
97                .iter()
98                .flat_map(|o| &o.inputs)
99                .filter(|f| seen.insert(f.file_id()))
100                .cloned()
101                .collect();
102            if inputs.is_empty() {
103                continue;
104            }
105            units.push(Self {
106                inputs,
107                outputs,
108                time_window_size,
109                max_file_size,
110            });
111        }
112        Some(units)
113    }
114
115    /// Estimates merge work from distinct input bytes. Expiration-only units do
116    /// not read SSTs; admission assigns them its minimum positive service charge.
117    pub(crate) fn estimated_input_bytes(&self) -> u64 {
118        if self.outputs.is_empty() {
119            return 0;
120        }
121        self.inputs
122            .iter()
123            .fold(0u64, |total, file| total.saturating_add(file.size()))
124    }
125
126    /// Estimates the memory budget of merging this unit. Outputs are merged one after another,
127    /// so the unit needs the budget of its largest output.
128    /// `retains_dedup_batch` is set when the merge deduplicates in `LastNonNull` mode, which keeps
129    /// the previous output batch until the next one shows whether its last row is updated.
130    pub(crate) fn estimated_memory_bytes(
131        &self,
132        read_parallelism: usize,
133        retains_dedup_batch: bool,
134    ) -> u64 {
135        self.outputs
136            .iter()
137            .map(|output| {
138                output_memory_bytes(&output.inputs, read_parallelism, retains_dedup_batch)
139            })
140            .max()
141            .unwrap_or(0)
142    }
143}
144
145/// Returns the bytes of the largest row group of a file once decoded. Dictionary encoding hides
146/// decoded values from the uncompressed size; files written before the decoded size was recorded
147/// report 0 for it.
148fn max_row_group_bytes(meta: &FileMeta) -> u64 {
149    meta.max_row_group_uncompressed_size
150        .max(meta.max_row_group_decoded_size)
151}
152
153/// Row group size of a file, approximated from its file metadata.
154struct RowGroupShape {
155    /// Decoded bytes of the largest row group.
156    bytes: u64,
157    /// Average rows of a row group; the metadata keeps no per-row-group row counts.
158    rows: u64,
159    num_row_groups: u64,
160}
161
162impl RowGroupShape {
163    fn of(meta: &FileMeta) -> Option<Self> {
164        let bytes = max_row_group_bytes(meta);
165        if bytes == 0 || meta.num_rows == 0 || meta.num_row_groups == 0 {
166            return None;
167        }
168        Some(Self {
169            bytes,
170            rows: (meta.num_rows / meta.num_row_groups).max(1),
171            num_row_groups: meta.num_row_groups,
172        })
173    }
174
175    fn row_width(&self) -> u64 {
176        self.bytes.div_ceil(self.rows)
177    }
178}
179
180/// Estimates the peak memory of merging `inputs` into one output, following the read path:
181///
182/// - Every input reader holds its current row group.
183/// - With a read parallelism above 1, every input is read in its own task and also holds
184///   batches ahead of the merge: a full channel, one batch being sent and one in the merge. A
185///   batch never spans row groups, and the batches of an input never exceed the whole file.
186/// - Inputs read serially hold the batch the merge is consuming.
187/// - The merge retains consumed input batches until it emits an output batch.
188/// - `LastNonNull` dedup keeps the previous output batch.
189/// - Merged batches pass a channel to the writer, with one more batch on each side of it.
190///
191/// The writer's row group buffer, index builders and the batch dedup concatenates when a key
192/// spans two batches are not covered.
193fn output_memory_bytes(
194    inputs: &[FileHandle],
195    read_parallelism: usize,
196    retains_dedup_batch: bool,
197) -> u64 {
198    let shapes: Vec<_> = inputs
199        .iter()
200        .filter_map(|file| RowGroupShape::of(file.meta_ref()))
201        .collect();
202    let row_group_bytes = inputs.iter().fold(0u64, |total, file| {
203        total.saturating_add(max_row_group_bytes(file.meta_ref()))
204    });
205    if shapes.is_empty() {
206        return row_group_bytes;
207    }
208    // Compaction reads every input of an output with one batch size, picked from the widest row.
209    // The reader also sees inputs without statistics in `FileMeta`; those are not sized here, so
210    // with mixed inputs the batch size is approximate.
211    let batch_rows =
212        estimate_batch_size(shapes.iter().map(|shape| (shape.rows, shape.bytes))) as u64;
213    let merges = inputs.len() > 1;
214    // Matches the condition under which `SeqScan` spawns a task per input.
215    let batches_per_input = if read_parallelism > 1 && merges {
216        compaction_input_channel_size() as u64 + 2
217    } else {
218        1
219    };
220    let input_batch_bytes = shapes.iter().fold(0u64, |total, shape| {
221        let batch_bytes = batch_rows.min(shape.rows).saturating_mul(shape.row_width());
222        let file_bytes = shape.bytes.saturating_mul(shape.num_row_groups);
223        total.saturating_add(
224            batches_per_input
225                .saturating_mul(batch_bytes)
226                .min(file_bytes),
227        )
228    });
229    // The merge holds one output batch when it merges, `LastNonNull` dedup holds one more, and the
230    // channel to the writer holds the rest. A merged batch has `batch_rows` rows; a single input passes its batches through, and
231    // those never span row groups.
232    let output_batches =
233        MERGED_BATCH_CHANNEL_SIZE as u64 + 2 + u64::from(merges) + u64::from(retains_dedup_batch);
234    let rows_per_batch = if merges {
235        batch_rows
236    } else {
237        batch_rows.min(shapes[0].rows)
238    };
239    let downstream_bytes =
240        widest_rows_bytes(&shapes, output_batches.saturating_mul(rows_per_batch));
241
242    row_group_bytes
243        .saturating_add(input_batch_bytes)
244        .saturating_add(downstream_bytes)
245}
246
247/// Bounds the bytes of `rows` distinct rows drawn from the inputs: the widest rows first, and no
248/// input gives more rows than it has. Batches past the readers hold distinct rows, so one wide
249/// row does not make every row of those batches wide.
250fn widest_rows_bytes(shapes: &[RowGroupShape], rows: u64) -> u64 {
251    let mut by_width: Vec<_> = shapes.iter().collect();
252    by_width.sort_unstable_by_key(|shape| std::cmp::Reverse(shape.row_width()));
253    let mut remaining = rows;
254    let mut bytes = 0u64;
255    for shape in by_width {
256        let taken = remaining.min(shape.rows.saturating_mul(shape.num_row_groups));
257        bytes = bytes.saturating_add(taken.saturating_mul(shape.row_width()));
258        remaining -= taken;
259        if remaining == 0 {
260            break;
261        }
262    }
263    bytes
264}
265
266/// Finds a dependency group's representative while shortening the parent chain.
267fn root(parents: &mut [usize], mut index: usize) -> usize {
268    while parents[index] != index {
269        parents[index] = parents[parents[index]];
270        index = parents[index];
271    }
272    index
273}
274
275#[cfg(test)]
276mod tests {
277    use store_api::storage::FileId;
278
279    use super::*;
280    use crate::compaction::test_util::{new_file_handle, new_file_handle_with_size_and_sequence};
281    use crate::test_util::new_noop_file_purger;
282
283    #[test]
284    fn test_estimated_memory_counts_decoded_row_groups() {
285        let file = |uncompressed, decoded| {
286            FileHandle::new(
287                crate::sst::file::FileMeta {
288                    file_id: FileId::random(),
289                    max_row_group_uncompressed_size: uncompressed,
290                    max_row_group_decoded_size: decoded,
291                    ..Default::default()
292                },
293                crate::test_util::new_noop_file_purger(),
294            )
295        };
296        // A dictionary-encoded file decodes to more than its uncompressed size; a file written
297        // before the decoded size was recorded reports 0 for it.
298        let units = CompactionUnit::from_picker(PickerOutput {
299            outputs: vec![output(vec![file(1 << 20, 128 << 20), file(4 << 20, 0)])],
300            ..Default::default()
301        })
302        .unwrap();
303        assert_eq!(
304            (128 << 20) + (4 << 20),
305            units[0].estimated_memory_bytes(1, false)
306        );
307    }
308
309    /// Builds an L1 output that preserves deletion markers for grouping tests.
310    fn output(inputs: Vec<FileHandle>) -> CompactionOutput {
311        CompactionOutput {
312            inputs,
313            output_level: 1,
314            filter_deleted: false,
315            output_time_range: None,
316        }
317    }
318
319    #[test]
320    fn test_compaction_unit_transitive_inputs() {
321        let files: Vec<_> = (0..3)
322            .map(|i| {
323                new_file_handle_with_size_and_sequence(FileId::random(), 0, 100, 0, 0, (i + 1) * 10)
324            })
325            .collect();
326        let units = CompactionUnit::from_picker(PickerOutput {
327            outputs: vec![
328                output(vec![files[0].clone()]),
329                output(vec![files[2].clone()]),
330                output(vec![files[1].clone()]),
331                output(vec![files[0].clone(), files[1].clone()]),
332            ],
333            time_window_size: 100,
334            max_file_size: Some(1024),
335            ..Default::default()
336        })
337        .unwrap();
338        assert_eq!(2, units.len());
339        assert_eq!(3, units[0].outputs.len());
340        assert_eq!(2, units[0].inputs.len());
341        assert_eq!(files[2].file_id(), units[1].inputs[0].file_id());
342        assert_eq!(30, units[0].estimated_input_bytes());
343        assert_eq!(30, units[1].estimated_input_bytes());
344        assert_eq!(Some(1024), units[0].max_file_size);
345        assert_eq!(100, units[1].time_window_size);
346    }
347
348    #[test]
349    fn test_compaction_unit_group_inherits_highest_output_priority() {
350        let files: Vec<_> = (0..3)
351            .map(|_| new_file_handle(FileId::random(), 0, 100, 0))
352            .collect();
353        let units = CompactionUnit::from_picker(PickerOutput {
354            outputs: [0, 1, 1, 2, 0]
355                .into_iter()
356                .map(|index| output(vec![files[index].clone()]))
357                .collect(),
358            ..Default::default()
359        })
360        .unwrap();
361        assert_eq!(
362            vec![files[0].file_id(), files[2].file_id(), files[1].file_id()],
363            units
364                .iter()
365                .map(|unit| unit.inputs[0].file_id())
366                .collect::<Vec<_>>()
367        );
368        assert_eq!(
369            vec![2, 1, 2],
370            units
371                .iter()
372                .map(|unit| unit.outputs.len())
373                .collect::<Vec<_>>()
374        );
375    }
376
377    #[test]
378    fn test_compaction_unit_expiration_precedes_merge_units() {
379        let files: Vec<_> = (0..3)
380            .map(|_| new_file_handle(FileId::random(), 0, 100, 0))
381            .collect();
382        let units = CompactionUnit::from_picker(PickerOutput {
383            outputs: vec![
384                output(vec![files[0].clone()]),
385                output(vec![files[1].clone()]),
386            ],
387            expired_ssts: vec![files[2].clone()],
388            ..Default::default()
389        })
390        .unwrap();
391
392        assert_eq!(3, units.len());
393        assert!(units[0].outputs.is_empty());
394        assert_eq!(files[2].file_id(), units[0].inputs[0].file_id());
395        assert_eq!(files[1].file_id(), units[1].inputs[0].file_id());
396        assert_eq!(files[0].file_id(), units[2].inputs[0].file_id());
397    }
398
399    #[test]
400    fn test_memory_follows_the_merge_of_each_output() {
401        const MIB: u64 = 1024 * 1024;
402        let file = |row_group_bytes: u64, rows_per_row_group: u64, num_row_groups: u64| {
403            FileHandle::new(
404                FileMeta {
405                    file_id: FileId::random(),
406                    max_row_group_uncompressed_size: row_group_bytes,
407                    num_rows: rows_per_row_group * num_row_groups,
408                    num_row_groups,
409                    ..Default::default()
410                },
411                new_noop_file_purger(),
412            )
413        };
414        let unit = |outputs: Vec<CompactionOutput>| {
415            let mut units = CompactionUnit::from_picker(PickerOutput {
416                outputs,
417                ..Default::default()
418            })
419            .unwrap();
420            assert_eq!(1, units.len());
421            units.pop().unwrap()
422        };
423        // Rows of 512 bytes are read in 8192-row batches of 4 MiB. Each input holds a 50 MiB row
424        // group and the batch the merge consumes; the merge retains one 4 MiB output batch and 4
425        // more sit between the merge and the writer.
426        let wide_groups = || file(50 * MIB, 100 * 1024, 10);
427        let (a, b, c) = (wide_groups(), wide_groups(), wide_groups());
428        let serial = 2 * 50 * MIB + 2 * 4 * MIB + 4 * MIB + 16 * MIB;
429        assert_eq!(
430            serial,
431            unit(vec![output(vec![a.clone(), b.clone()])]).estimated_memory_bytes(1, false)
432        );
433        // `LastNonNull` dedup holds back one more output batch.
434        assert_eq!(
435            serial + 4 * MIB,
436            unit(vec![output(vec![a.clone(), b.clone()])]).estimated_memory_bytes(1, true)
437        );
438        // Read in parallel, each input also holds the batches read ahead of the merge.
439        let parallel = 2 * 50 * MIB + 2 * 16 * MIB + 4 * MIB + 16 * MIB;
440        assert_eq!(
441            parallel,
442            unit(vec![output(vec![a.clone(), b.clone()])]).estimated_memory_bytes(4, false)
443        );
444        // Outputs sharing an input run one after another, so the unit needs one output's budget.
445        assert_eq!(
446            parallel,
447            unit(vec![output(vec![a.clone(), b]), output(vec![a, c])])
448                .estimated_memory_bytes(4, false)
449        );
450
451        // Rows of 1 MiB make 64-row batches, but an input batch stops at its 4-row row group.
452        // The merge output still holds 64 rows.
453        let narrow_groups = || file(4 * MIB, 4, 1000);
454        let (d, e) = (narrow_groups(), narrow_groups());
455        assert_eq!(
456            2 * 4 * MIB + 2 * 16 * MIB + 64 * MIB + 4 * 64 * MIB,
457            unit(vec![output(vec![d.clone(), e])]).estimated_memory_bytes(4, false)
458        );
459        // A single input is read without read-ahead or merge, so its batches stay row groups.
460        assert_eq!(
461            4 * MIB + 4 * MIB + 4 * 4 * MIB,
462            unit(vec![output(vec![d])]).estimated_memory_bytes(4, false)
463        );
464
465        // One 1 MiB row merged with 1 KiB rows: of the 320 rows past the readers, only one is
466        // wide.
467        let (wide_row, narrow_rows) = (file(MIB, 1, 1), file(MIB, 1024, 512));
468        assert_eq!(
469            2 * MIB + MIB + 64 * 1024 + MIB + 319 * 1024,
470            unit(vec![output(vec![wide_row, narrow_rows])]).estimated_memory_bytes(1, false)
471        );
472
473        // Two one-row files of 8 KiB: a batch holds both rows at most, and the batches past
474        // the readers never hold more than the two rows.
475        let (f, g) = (file(8 * 1024, 1, 1), file(8 * 1024, 1, 1));
476        assert_eq!(
477            2 * 8 * 1024 + 2 * 8 * 1024 + 2 * 8 * 1024,
478            unit(vec![output(vec![f, g])]).estimated_memory_bytes(4, false)
479        );
480    }
481
482    #[test]
483    fn test_compaction_unit_expiration_inputs() {
484        let file = new_file_handle(FileId::random(), 0, 100, 0);
485        assert!(
486            CompactionUnit::from_picker(PickerOutput {
487                outputs: vec![output(vec![file.clone()])],
488                expired_ssts: vec![file.clone()],
489                ..Default::default()
490            })
491            .is_none()
492        );
493        let units = CompactionUnit::from_picker(PickerOutput {
494            expired_ssts: vec![file.clone(), file],
495            ..Default::default()
496        })
497        .unwrap();
498        assert_eq!(1, units.len());
499        assert_eq!(1, units[0].inputs.len());
500        assert!(units[0].outputs.is_empty());
501        assert_eq!(0, units[0].estimated_memory_bytes(1, false));
502        assert!(
503            CompactionUnit::from_picker(PickerOutput::default())
504                .unwrap()
505                .is_empty()
506        );
507    }
508}