mito2/compaction/
compactor.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::num::NonZero;
16use std::sync::Arc;
17use std::time::Duration;
18
19use api::v1::region::compact_request;
20use common_meta::key::SchemaMetadataManagerRef;
21use common_telemetry::{info, warn};
22use common_time::TimeToLive;
23use either::Either;
24use itertools::Itertools;
25use object_store::manager::ObjectStoreManagerRef;
26use partition::expr::PartitionExpr;
27use serde::{Deserialize, Serialize};
28use snafu::{OptionExt, ResultExt};
29use store_api::metadata::RegionMetadataRef;
30use store_api::region_request::PathType;
31use store_api::storage::RegionId;
32
33use crate::access_layer::{
34    AccessLayer, AccessLayerRef, Metrics, OperationType, SstWriteRequest, WriteType,
35};
36use crate::cache::{CacheManager, CacheManagerRef};
37use crate::compaction::picker::{PickerOutput, new_picker};
38use crate::compaction::{CompactionOutput, CompactionSstReaderBuilder, find_ttl};
39use crate::config::MitoConfig;
40use crate::error::{
41    EmptyRegionDirSnafu, InvalidPartitionExprSnafu, JoinSnafu, ObjectStoreNotFoundSnafu, Result,
42};
43use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList};
44use crate::manifest::manager::{RegionManifestManager, RegionManifestOptions, RemoveFileOptions};
45use crate::manifest::storage::manifest_compress_type;
46use crate::metrics;
47use crate::read::{FlatSource, Source};
48use crate::region::opener::new_manifest_dir;
49use crate::region::options::RegionOptions;
50use crate::region::version::VersionRef;
51use crate::region::{ManifestContext, RegionLeaderState, RegionRoleState};
52use crate::schedule::scheduler::LocalScheduler;
53use crate::sst::FormatType;
54use crate::sst::file::FileMeta;
55use crate::sst::file_purger::LocalFilePurger;
56use crate::sst::index::intermediate::IntermediateManager;
57use crate::sst::index::puffin_manager::PuffinManagerFactory;
58use crate::sst::location::region_dir_from_table_dir;
59use crate::sst::parquet::WriteOptions;
60use crate::sst::version::{SstVersion, SstVersionRef};
61
62/// Region version for compaction that does not hold memtables.
63#[derive(Clone)]
64pub struct CompactionVersion {
65    /// Metadata of the region.
66    ///
67    /// Altering metadata isn't frequent, storing metadata in Arc to allow sharing
68    /// metadata and reuse metadata when creating a new `Version`.
69    pub(crate) metadata: RegionMetadataRef,
70    /// Options of the region.
71    pub(crate) options: RegionOptions,
72    /// SSTs of the region.
73    pub(crate) ssts: SstVersionRef,
74    /// Inferred compaction time window.
75    pub(crate) compaction_time_window: Option<Duration>,
76}
77
78impl From<VersionRef> for CompactionVersion {
79    fn from(value: VersionRef) -> Self {
80        Self {
81            metadata: value.metadata.clone(),
82            options: value.options.clone(),
83            ssts: value.ssts.clone(),
84            compaction_time_window: value.compaction_time_window,
85        }
86    }
87}
88
89/// CompactionRegion represents a region that needs to be compacted.
90/// It's the subset of MitoRegion.
91#[derive(Clone)]
92pub struct CompactionRegion {
93    pub region_id: RegionId,
94    pub region_options: RegionOptions,
95
96    pub(crate) engine_config: Arc<MitoConfig>,
97    pub(crate) region_metadata: RegionMetadataRef,
98    pub(crate) cache_manager: CacheManagerRef,
99    /// Access layer to get the table path and path type.
100    pub access_layer: AccessLayerRef,
101    pub(crate) manifest_ctx: Arc<ManifestContext>,
102    pub(crate) current_version: CompactionVersion,
103    pub(crate) file_purger: Option<Arc<LocalFilePurger>>,
104    pub(crate) ttl: Option<TimeToLive>,
105
106    /// Controls the parallelism of this compaction task. Default is 1.
107    ///
108    /// The parallel is inside this compaction task, not across different compaction tasks.
109    /// It can be different windows of the same compaction task or something like this.
110    pub max_parallelism: usize,
111}
112
113/// OpenCompactionRegionRequest represents the request to open a compaction region.
114#[derive(Debug, Clone)]
115pub struct OpenCompactionRegionRequest {
116    pub region_id: RegionId,
117    pub table_dir: String,
118    pub path_type: PathType,
119    pub region_options: RegionOptions,
120    pub max_parallelism: usize,
121}
122
123/// Open a compaction region from a compaction request.
124/// It's simple version of RegionOpener::open().
125pub async fn open_compaction_region(
126    req: &OpenCompactionRegionRequest,
127    mito_config: &MitoConfig,
128    object_store_manager: ObjectStoreManagerRef,
129    ttl_provider: Either<TimeToLive, SchemaMetadataManagerRef>,
130) -> Result<CompactionRegion> {
131    let object_store = {
132        let name = &req.region_options.storage;
133        if let Some(name) = name {
134            object_store_manager
135                .find(name)
136                .with_context(|| ObjectStoreNotFoundSnafu {
137                    object_store: name.clone(),
138                })?
139        } else {
140            object_store_manager.default_object_store()
141        }
142    };
143
144    let access_layer = {
145        let puffin_manager_factory = PuffinManagerFactory::new(
146            &mito_config.index.aux_path,
147            mito_config.index.staging_size.as_bytes(),
148            Some(mito_config.index.write_buffer_size.as_bytes() as _),
149            mito_config.index.staging_ttl,
150        )
151        .await?;
152        let intermediate_manager =
153            IntermediateManager::init_fs(mito_config.index.aux_path.clone()).await?;
154
155        Arc::new(AccessLayer::new(
156            &req.table_dir,
157            req.path_type,
158            object_store.clone(),
159            puffin_manager_factory,
160            intermediate_manager,
161        ))
162    };
163
164    let manifest_manager = {
165        let region_manifest_options = RegionManifestOptions {
166            manifest_dir: new_manifest_dir(&region_dir_from_table_dir(
167                &req.table_dir,
168                req.region_id,
169                req.path_type,
170            )),
171            object_store: object_store.clone(),
172            compress_type: manifest_compress_type(mito_config.compress_manifest),
173            checkpoint_distance: mito_config.manifest_checkpoint_distance,
174            remove_file_options: RemoveFileOptions {
175                enable_gc: mito_config.gc.enable,
176            },
177        };
178
179        RegionManifestManager::open(region_manifest_options, &Default::default())
180            .await?
181            .with_context(|| EmptyRegionDirSnafu {
182                region_id: req.region_id,
183                region_dir: region_dir_from_table_dir(&req.table_dir, req.region_id, req.path_type),
184            })?
185    };
186
187    let manifest = manifest_manager.manifest();
188    let region_metadata = manifest.metadata.clone();
189    let manifest_ctx = Arc::new(ManifestContext::new(
190        manifest_manager,
191        RegionRoleState::Leader(RegionLeaderState::Writable),
192    ));
193
194    let file_purger = {
195        let purge_scheduler = Arc::new(LocalScheduler::new(mito_config.max_background_purges));
196        Arc::new(LocalFilePurger::new(
197            purge_scheduler.clone(),
198            access_layer.clone(),
199            None,
200        ))
201    };
202
203    let current_version = {
204        let mut ssts = SstVersion::new();
205        ssts.add_files(file_purger.clone(), manifest.files.values().cloned());
206        CompactionVersion {
207            metadata: region_metadata.clone(),
208            options: req.region_options.clone(),
209            ssts: Arc::new(ssts),
210            compaction_time_window: manifest.compaction_time_window,
211        }
212    };
213
214    let ttl = match ttl_provider {
215        // Use the specified ttl.
216        Either::Left(ttl) => ttl,
217        // Get the ttl from the schema metadata manager.
218        Either::Right(schema_metadata_manager) => find_ttl(
219            req.region_id.table_id(),
220            current_version.options.ttl,
221            &schema_metadata_manager,
222        )
223        .await
224        .unwrap_or_else(|e| {
225            warn!(e; "Failed to get ttl for region: {}", region_metadata.region_id);
226            TimeToLive::default()
227        }),
228    };
229
230    Ok(CompactionRegion {
231        region_id: req.region_id,
232        region_options: req.region_options.clone(),
233        engine_config: Arc::new(mito_config.clone()),
234        region_metadata: region_metadata.clone(),
235        cache_manager: Arc::new(CacheManager::default()),
236        access_layer,
237        manifest_ctx,
238        current_version,
239        file_purger: Some(file_purger),
240        ttl: Some(ttl),
241        max_parallelism: req.max_parallelism,
242    })
243}
244
245impl CompactionRegion {
246    /// Get the file purger of the compaction region.
247    pub fn file_purger(&self) -> Option<Arc<LocalFilePurger>> {
248        self.file_purger.clone()
249    }
250
251    /// Stop the file purger scheduler of the compaction region.
252    pub async fn stop_purger_scheduler(&self) -> Result<()> {
253        if let Some(file_purger) = &self.file_purger {
254            file_purger.stop_scheduler().await
255        } else {
256            Ok(())
257        }
258    }
259}
260
261/// `[MergeOutput]` represents the output of merging SST files.
262#[derive(Default, Clone, Debug, Serialize, Deserialize)]
263pub struct MergeOutput {
264    pub files_to_add: Vec<FileMeta>,
265    pub files_to_remove: Vec<FileMeta>,
266    pub compaction_time_window: Option<i64>,
267}
268
269impl MergeOutput {
270    pub fn is_empty(&self) -> bool {
271        self.files_to_add.is_empty() && self.files_to_remove.is_empty()
272    }
273
274    pub fn input_file_size(&self) -> u64 {
275        self.files_to_remove.iter().map(|f| f.file_size).sum()
276    }
277
278    pub fn output_file_size(&self) -> u64 {
279        self.files_to_add.iter().map(|f| f.file_size).sum()
280    }
281}
282
283/// Compactor is the trait that defines the compaction logic.
284#[async_trait::async_trait]
285pub trait Compactor: Send + Sync + 'static {
286    /// Merge SST files for a region.
287    async fn merge_ssts(
288        &self,
289        compaction_region: &CompactionRegion,
290        picker_output: PickerOutput,
291    ) -> Result<MergeOutput>;
292
293    /// Update the manifest after merging SST files.
294    async fn update_manifest(
295        &self,
296        compaction_region: &CompactionRegion,
297        merge_output: MergeOutput,
298    ) -> Result<RegionEdit>;
299
300    /// Execute compaction for a region.
301    async fn compact(
302        &self,
303        compaction_region: &CompactionRegion,
304        compact_request_options: compact_request::Options,
305    ) -> Result<()>;
306}
307
308/// DefaultCompactor is the default implementation of Compactor.
309pub struct DefaultCompactor;
310
311impl DefaultCompactor {
312    /// Merge a single compaction output into SST files.
313    async fn merge_single_output(
314        compaction_region: CompactionRegion,
315        output: CompactionOutput,
316        write_opts: WriteOptions,
317    ) -> Result<Vec<FileMeta>> {
318        let region_id = compaction_region.region_id;
319        let storage = compaction_region.region_options.storage.clone();
320        let index_options = compaction_region
321            .current_version
322            .options
323            .index_options
324            .clone();
325        let append_mode = compaction_region.current_version.options.append_mode;
326        let merge_mode = compaction_region.current_version.options.merge_mode();
327        let flat_format = compaction_region
328            .region_options
329            .sst_format
330            .map(|format| format == FormatType::Flat)
331            .unwrap_or(
332                compaction_region
333                    .engine_config
334                    .default_experimental_flat_format,
335            );
336
337        let index_config = compaction_region.engine_config.index.clone();
338        let inverted_index_config = compaction_region.engine_config.inverted_index.clone();
339        let fulltext_index_config = compaction_region.engine_config.fulltext_index.clone();
340        let bloom_filter_index_config = compaction_region.engine_config.bloom_filter_index.clone();
341
342        let input_file_names = output
343            .inputs
344            .iter()
345            .map(|f| f.file_id().to_string())
346            .join(",");
347        let max_sequence = output
348            .inputs
349            .iter()
350            .map(|f| f.meta_ref().sequence)
351            .max()
352            .flatten();
353        let builder = CompactionSstReaderBuilder {
354            metadata: compaction_region.region_metadata.clone(),
355            sst_layer: compaction_region.access_layer.clone(),
356            cache: compaction_region.cache_manager.clone(),
357            inputs: &output.inputs,
358            append_mode,
359            filter_deleted: output.filter_deleted,
360            time_range: output.output_time_range,
361            merge_mode,
362        };
363        let source = if flat_format {
364            let reader = builder.build_flat_sst_reader().await?;
365            Either::Right(FlatSource::Stream(reader))
366        } else {
367            let reader = builder.build_sst_reader().await?;
368            Either::Left(Source::Reader(reader))
369        };
370        let mut metrics = Metrics::new(WriteType::Compaction);
371        let region_metadata = compaction_region.region_metadata.clone();
372        let sst_infos = compaction_region
373            .access_layer
374            .write_sst(
375                SstWriteRequest {
376                    op_type: OperationType::Compact,
377                    metadata: region_metadata.clone(),
378                    source,
379                    cache_manager: compaction_region.cache_manager.clone(),
380                    storage,
381                    max_sequence: max_sequence.map(NonZero::get),
382                    index_options,
383                    index_config,
384                    inverted_index_config,
385                    fulltext_index_config,
386                    bloom_filter_index_config,
387                },
388                &write_opts,
389                &mut metrics,
390            )
391            .await?;
392        // Convert partition expression once outside the map
393        let partition_expr = match &region_metadata.partition_expr {
394            None => None,
395            Some(json_str) if json_str.is_empty() => None,
396            Some(json_str) => PartitionExpr::from_json_str(json_str).with_context(|_| {
397                InvalidPartitionExprSnafu {
398                    expr: json_str.clone(),
399                }
400            })?,
401        };
402
403        let output_files = sst_infos
404            .into_iter()
405            .map(|sst_info| FileMeta {
406                region_id,
407                file_id: sst_info.file_id,
408                time_range: sst_info.time_range,
409                level: output.output_level,
410                file_size: sst_info.file_size,
411                available_indexes: sst_info.index_metadata.build_available_indexes(),
412                index_file_size: sst_info.index_metadata.file_size,
413                index_file_id: None,
414                num_rows: sst_info.num_rows as u64,
415                num_row_groups: sst_info.num_row_groups,
416                sequence: max_sequence,
417                partition_expr: partition_expr.clone(),
418                num_series: sst_info.num_series,
419            })
420            .collect::<Vec<_>>();
421        let output_file_names = output_files.iter().map(|f| f.file_id.to_string()).join(",");
422        info!(
423            "Region {} compaction inputs: [{}], outputs: [{}], flat_format: {}, metrics: {:?}",
424            region_id, input_file_names, output_file_names, flat_format, metrics
425        );
426        metrics.observe();
427        Ok(output_files)
428    }
429}
430
431#[async_trait::async_trait]
432impl Compactor for DefaultCompactor {
433    async fn merge_ssts(
434        &self,
435        compaction_region: &CompactionRegion,
436        mut picker_output: PickerOutput,
437    ) -> Result<MergeOutput> {
438        let mut futs = Vec::with_capacity(picker_output.outputs.len());
439        let mut compacted_inputs =
440            Vec::with_capacity(picker_output.outputs.iter().map(|o| o.inputs.len()).sum());
441        let internal_parallelism = compaction_region.max_parallelism.max(1);
442        let compaction_time_window = picker_output.time_window_size;
443
444        for output in picker_output.outputs.drain(..) {
445            let inputs_to_remove: Vec<_> =
446                output.inputs.iter().map(|f| f.meta_ref().clone()).collect();
447            compacted_inputs.extend(inputs_to_remove.iter().cloned());
448            let write_opts = WriteOptions {
449                write_buffer_size: compaction_region.engine_config.sst_write_buffer_size,
450                max_file_size: picker_output.max_file_size,
451                ..Default::default()
452            };
453            futs.push(Self::merge_single_output(
454                compaction_region.clone(),
455                output,
456                write_opts,
457            ));
458        }
459        let mut output_files = Vec::with_capacity(futs.len());
460        while !futs.is_empty() {
461            let mut task_chunk = Vec::with_capacity(internal_parallelism);
462            for _ in 0..internal_parallelism {
463                if let Some(task) = futs.pop() {
464                    task_chunk.push(common_runtime::spawn_compact(task));
465                }
466            }
467            let metas = futures::future::try_join_all(task_chunk)
468                .await
469                .context(JoinSnafu)?
470                .into_iter()
471                .collect::<Result<Vec<Vec<_>>>>()?;
472            output_files.extend(metas.into_iter().flatten());
473        }
474
475        // In case of remote compaction, we still allow the region edit after merge to
476        // clean expired ssts.
477        let mut inputs: Vec<_> = compacted_inputs.into_iter().collect();
478        inputs.extend(
479            picker_output
480                .expired_ssts
481                .iter()
482                .map(|f| f.meta_ref().clone()),
483        );
484
485        Ok(MergeOutput {
486            files_to_add: output_files,
487            files_to_remove: inputs,
488            compaction_time_window: Some(compaction_time_window),
489        })
490    }
491
492    async fn update_manifest(
493        &self,
494        compaction_region: &CompactionRegion,
495        merge_output: MergeOutput,
496    ) -> Result<RegionEdit> {
497        // Write region edit to manifest.
498        let edit = RegionEdit {
499            files_to_add: merge_output.files_to_add,
500            files_to_remove: merge_output.files_to_remove,
501            // Use current timestamp as the edit timestamp.
502            timestamp_ms: Some(chrono::Utc::now().timestamp_millis()),
503            compaction_time_window: merge_output
504                .compaction_time_window
505                .map(|seconds| Duration::from_secs(seconds as u64)),
506            flushed_entry_id: None,
507            flushed_sequence: None,
508            committed_sequence: None,
509        };
510
511        let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone()));
512        // TODO: We might leak files if we fail to update manifest. We can add a cleanup task to remove them later.
513        compaction_region
514            .manifest_ctx
515            .update_manifest(RegionLeaderState::Writable, action_list)
516            .await?;
517
518        Ok(edit)
519    }
520
521    // The default implementation of compact combines the merge_ssts and update_manifest functions.
522    // Note: It's local compaction and only used for testing purpose.
523    async fn compact(
524        &self,
525        compaction_region: &CompactionRegion,
526        compact_request_options: compact_request::Options,
527    ) -> Result<()> {
528        let picker_output = {
529            let picker_output = new_picker(
530                &compact_request_options,
531                &compaction_region.region_options.compaction,
532                compaction_region.region_options.append_mode,
533                None,
534            )
535            .pick(compaction_region);
536
537            if let Some(picker_output) = picker_output {
538                picker_output
539            } else {
540                info!(
541                    "No files to compact for region_id: {}",
542                    compaction_region.region_id
543                );
544                return Ok(());
545            }
546        };
547
548        let merge_output = self.merge_ssts(compaction_region, picker_output).await?;
549        if merge_output.is_empty() {
550            info!(
551                "No files to compact for region_id: {}",
552                compaction_region.region_id
553            );
554            return Ok(());
555        }
556
557        metrics::COMPACTION_INPUT_BYTES.inc_by(merge_output.input_file_size() as f64);
558        metrics::COMPACTION_OUTPUT_BYTES.inc_by(merge_output.output_file_size() as f64);
559        self.update_manifest(compaction_region, merge_output)
560            .await?;
561
562        Ok(())
563    }
564}