Skip to main content

mito2/compaction/
picker.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::fmt::Debug;
16use std::sync::Arc;
17
18use api::v1::region::compact_request;
19use common_time::range::TimestampRange;
20use common_time::{TimeToLive, Timestamp};
21use serde::{Deserialize, Serialize};
22
23use crate::compaction::compactor::CompactionRegion;
24use crate::compaction::last_non_null::LastNonNullPicker;
25use crate::compaction::twcs::TwcsPicker;
26use crate::compaction::window::WindowedCompactionPicker;
27use crate::compaction::{CompactionOutput, SerializedCompactionOutput};
28use crate::error::Result;
29use crate::region::options::{CompactionOptions, MergeMode, RegionOptions};
30use crate::sst::file::{FileHandle, FileMeta};
31use crate::sst::file_purger::FilePurger;
32use crate::sst::version::LevelMeta;
33
34/// Picker picks input SST files for compaction.
35/// Different compaction strategy may implement different pickers.
36#[async_trait::async_trait]
37pub trait Picker: Debug + Send + Sync + 'static {
38    /// Picks input SST files for compaction.
39    async fn pick(&self, compaction_region: &CompactionRegion) -> Result<Option<PickerOutput>>;
40}
41
42/// PickerOutput is the output of a [`Picker`].
43/// It contains the outputs of the compaction and the expired SST files.
44#[derive(Default, Clone, Debug)]
45pub struct PickerOutput {
46    pub outputs: Vec<CompactionOutput>,
47    pub expired_ssts: Vec<FileHandle>,
48    pub time_window_size: i64,
49    /// Max single output file size in bytes.
50    pub max_file_size: Option<usize>,
51}
52
53/// SerializedPickerOutput is a serialized version of PickerOutput by replacing [CompactionOutput] and [FileHandle] with [SerializedCompactionOutput] and [FileMeta].
54#[derive(Default, Clone, Debug, Serialize, Deserialize)]
55pub struct SerializedPickerOutput {
56    pub outputs: Vec<SerializedCompactionOutput>,
57    pub expired_ssts: Vec<FileMeta>,
58    pub time_window_size: i64,
59    pub max_file_size: Option<usize>,
60}
61
62impl From<&PickerOutput> for SerializedPickerOutput {
63    fn from(input: &PickerOutput) -> Self {
64        let outputs = input
65            .outputs
66            .iter()
67            .map(|output| SerializedCompactionOutput {
68                output_level: output.output_level,
69                inputs: output.inputs.iter().map(|s| s.meta_ref().clone()).collect(),
70                filter_deleted: output.filter_deleted,
71                output_time_range: output.output_time_range,
72            })
73            .collect();
74        let expired_ssts = input
75            .expired_ssts
76            .iter()
77            .map(|s| s.meta_ref().clone())
78            .collect();
79        Self {
80            outputs,
81            expired_ssts,
82            time_window_size: input.time_window_size,
83            max_file_size: input.max_file_size,
84        }
85    }
86}
87
88impl PickerOutput {
89    /// Converts a [SerializedPickerOutput] to a [PickerOutput]. File statistics
90    /// retain their original encoding; comparisons supply their own schema context.
91    pub fn from_serialized(
92        input: SerializedPickerOutput,
93        file_purger: Arc<dyn FilePurger>,
94    ) -> Self {
95        let outputs = input
96            .outputs
97            .into_iter()
98            .map(|output| CompactionOutput {
99                output_level: output.output_level,
100                inputs: output
101                    .inputs
102                    .into_iter()
103                    .map(|file_meta| FileHandle::new(file_meta, file_purger.clone()))
104                    .collect(),
105                filter_deleted: output.filter_deleted,
106                output_time_range: output.output_time_range,
107            })
108            .collect();
109
110        let expired_ssts = input
111            .expired_ssts
112            .into_iter()
113            .map(|file_meta| FileHandle::new(file_meta, file_purger.clone()))
114            .collect();
115
116        Self {
117            outputs,
118            expired_ssts,
119            time_window_size: input.time_window_size,
120            max_file_size: input.max_file_size,
121        }
122    }
123}
124
125/// Creates a picker for the request and the region's compaction and merge modes.
126pub fn new_picker(
127    compact_request_options: &compact_request::Options,
128    region_options: &RegionOptions,
129    max_background_tasks: Option<usize>,
130    time_range: Option<TimestampRange>,
131    manual: bool,
132) -> Arc<dyn Picker> {
133    if let compact_request::Options::StrictWindow(window) = compact_request_options {
134        let window = if window.window_seconds == 0 {
135            None
136        } else {
137            Some(window.window_seconds)
138        };
139        // Strict-window outputs already include every overlapping file segment
140        // within each disjoint, half-open output range, including LastNonNull.
141        Arc::new(WindowedCompactionPicker::new(window).with_time_range(time_range)) as Arc<_>
142    } else {
143        let picker = match &region_options.compaction {
144            CompactionOptions::Twcs(twcs_opts) => TwcsPicker {
145                trigger_file_num: twcs_opts.active_window_trigger_file_num,
146                active_window_l1_merge_trigger: twcs_opts.active_window_l1_merge_trigger,
147                inactive_window_trigger_file_num: twcs_opts.inactive_window_trigger_file_num,
148                inactive_window_l1_merge_trigger: twcs_opts.inactive_window_l1_merge_trigger,
149                time_window_seconds: twcs_opts.time_window_seconds(),
150                max_output_file_size: twcs_opts.max_output_file_size.map(|r| r.as_bytes()),
151                append_mode: region_options.append_mode,
152                merge_mode: region_options.merge_mode(),
153                max_background_tasks,
154                time_range,
155                all_windows_inactive: manual,
156            },
157        };
158        if region_options.merge_mode() == MergeMode::LastNonNull {
159            // LastNonNull correctness spans windows and levels, so wrap the seed
160            // picker instead of trusting TWCS's independent windows.
161            Arc::new(LastNonNullPicker::new(picker))
162        } else {
163            Arc::new(picker)
164        }
165    }
166}
167
168/// Finds all expired SSTs across levels.
169pub(super) fn get_expired_ssts(
170    levels: &[LevelMeta],
171    ttl: Option<TimeToLive>,
172    now: Timestamp,
173) -> Vec<FileHandle> {
174    let Some(ttl) = ttl else {
175        return vec![];
176    };
177
178    levels
179        .iter()
180        .flat_map(|l| l.get_expired_files(&now, &ttl).into_iter())
181        .collect()
182}
183
184#[cfg(test)]
185mod tests {
186    use store_api::storage::FileId;
187
188    use super::*;
189    use crate::compaction::test_util::new_file_handle;
190    use crate::test_util::new_noop_file_purger;
191
192    #[test]
193    fn test_picker_output_serialization() {
194        let inputs_file_handle = vec![
195            new_file_handle(FileId::random(), 0, 999, 0),
196            new_file_handle(FileId::random(), 0, 999, 0),
197            new_file_handle(FileId::random(), 0, 999, 0),
198        ];
199        let expired_ssts_file_handle = vec![
200            new_file_handle(FileId::random(), 0, 999, 0),
201            new_file_handle(FileId::random(), 0, 999, 0),
202        ];
203
204        let picker_output = PickerOutput {
205            outputs: vec![
206                CompactionOutput {
207                    output_level: 0,
208                    inputs: inputs_file_handle.clone(),
209                    filter_deleted: false,
210                    output_time_range: None,
211                },
212                CompactionOutput {
213                    output_level: 0,
214                    inputs: inputs_file_handle.clone(),
215                    filter_deleted: false,
216                    output_time_range: None,
217                },
218            ],
219            expired_ssts: expired_ssts_file_handle.clone(),
220            time_window_size: 1000,
221            max_file_size: None,
222        };
223
224        let picker_output_str =
225            serde_json::to_string(&SerializedPickerOutput::from(&picker_output)).unwrap();
226        let serialized_picker_output: SerializedPickerOutput =
227            serde_json::from_str(&picker_output_str).unwrap();
228        let picker_output_from_serialized =
229            PickerOutput::from_serialized(serialized_picker_output, new_noop_file_purger());
230
231        picker_output
232            .expired_ssts
233            .iter()
234            .zip(picker_output_from_serialized.expired_ssts.iter())
235            .for_each(|(expected, actual)| {
236                assert_eq!(expected.meta_ref(), actual.meta_ref());
237            });
238
239        picker_output
240            .outputs
241            .iter()
242            .zip(picker_output_from_serialized.outputs.iter())
243            .for_each(|(expected, actual)| {
244                assert_eq!(expected.output_level, actual.output_level);
245                expected
246                    .inputs
247                    .iter()
248                    .zip(actual.inputs.iter())
249                    .for_each(|(expected, actual)| {
250                        assert_eq!(expected.meta_ref(), actual.meta_ref());
251                    });
252                assert_eq!(expected.filter_deleted, actual.filter_deleted);
253                assert_eq!(expected.output_time_range, actual.output_time_range);
254            });
255    }
256}