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_dynamic_options};
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};
45use crate::metrics;
46use crate::read::{FlatSource, Source};
47use crate::region::options::RegionOptions;
48use crate::region::version::VersionRef;
49use crate::region::{ManifestContext, RegionLeaderState, RegionRoleState};
50use crate::schedule::scheduler::LocalScheduler;
51use crate::sst::FormatType;
52use crate::sst::file::FileMeta;
53use crate::sst::file_purger::LocalFilePurger;
54use crate::sst::index::intermediate::IntermediateManager;
55use crate::sst::index::puffin_manager::PuffinManagerFactory;
56use crate::sst::location::region_dir_from_table_dir;
57use crate::sst::parquet::WriteOptions;
58use crate::sst::version::{SstVersion, SstVersionRef};
59
60/// Region version for compaction that does not hold memtables.
61#[derive(Clone)]
62pub struct CompactionVersion {
63    /// Metadata of the region.
64    ///
65    /// Altering metadata isn't frequent, storing metadata in Arc to allow sharing
66    /// metadata and reuse metadata when creating a new `Version`.
67    pub(crate) metadata: RegionMetadataRef,
68    /// Options of the region.
69    pub(crate) options: RegionOptions,
70    /// SSTs of the region.
71    pub(crate) ssts: SstVersionRef,
72    /// Inferred compaction time window.
73    pub(crate) compaction_time_window: Option<Duration>,
74}
75
76impl From<VersionRef> for CompactionVersion {
77    fn from(value: VersionRef) -> Self {
78        Self {
79            metadata: value.metadata.clone(),
80            options: value.options.clone(),
81            ssts: value.ssts.clone(),
82            compaction_time_window: value.compaction_time_window,
83        }
84    }
85}
86
87/// CompactionRegion represents a region that needs to be compacted.
88/// It's the subset of MitoRegion.
89#[derive(Clone)]
90pub struct CompactionRegion {
91    pub region_id: RegionId,
92    pub region_options: RegionOptions,
93
94    pub(crate) engine_config: Arc<MitoConfig>,
95    pub(crate) region_metadata: RegionMetadataRef,
96    pub(crate) cache_manager: CacheManagerRef,
97    /// Access layer to get the table path and path type.
98    pub access_layer: AccessLayerRef,
99    pub(crate) manifest_ctx: Arc<ManifestContext>,
100    pub(crate) current_version: CompactionVersion,
101    pub(crate) file_purger: Option<Arc<LocalFilePurger>>,
102    pub(crate) ttl: Option<TimeToLive>,
103
104    /// Controls the parallelism of this compaction task. Default is 1.
105    ///
106    /// The parallel is inside this compaction task, not across different compaction tasks.
107    /// It can be different windows of the same compaction task or something like this.
108    pub max_parallelism: usize,
109}
110
111/// OpenCompactionRegionRequest represents the request to open a compaction region.
112#[derive(Debug, Clone)]
113pub struct OpenCompactionRegionRequest {
114    pub region_id: RegionId,
115    pub table_dir: String,
116    pub path_type: PathType,
117    pub region_options: RegionOptions,
118    pub max_parallelism: usize,
119}
120
121/// Open a compaction region from a compaction request.
122/// It's simple version of RegionOpener::open().
123pub async fn open_compaction_region(
124    req: &OpenCompactionRegionRequest,
125    mito_config: &MitoConfig,
126    object_store_manager: ObjectStoreManagerRef,
127    ttl_provider: Either<TimeToLive, SchemaMetadataManagerRef>,
128) -> Result<CompactionRegion> {
129    let object_store = {
130        let name = &req.region_options.storage;
131        if let Some(name) = name {
132            object_store_manager
133                .find(name)
134                .with_context(|| ObjectStoreNotFoundSnafu {
135                    object_store: name.clone(),
136                })?
137        } else {
138            object_store_manager.default_object_store()
139        }
140    };
141
142    let access_layer = {
143        let puffin_manager_factory = PuffinManagerFactory::new(
144            &mito_config.index.aux_path,
145            mito_config.index.staging_size.as_bytes(),
146            Some(mito_config.index.write_buffer_size.as_bytes() as _),
147            mito_config.index.staging_ttl,
148        )
149        .await?;
150        let intermediate_manager =
151            IntermediateManager::init_fs(mito_config.index.aux_path.clone()).await?;
152
153        Arc::new(AccessLayer::new(
154            &req.table_dir,
155            req.path_type,
156            object_store.clone(),
157            puffin_manager_factory,
158            intermediate_manager,
159        ))
160    };
161
162    let manifest_manager = {
163        let region_dir = region_dir_from_table_dir(&req.table_dir, req.region_id, req.path_type);
164        let region_manifest_options =
165            RegionManifestOptions::new(mito_config, &region_dir, object_store);
166
167        RegionManifestManager::open(region_manifest_options, &Default::default())
168            .await?
169            .with_context(|| EmptyRegionDirSnafu {
170                region_id: req.region_id,
171                region_dir: region_dir_from_table_dir(&req.table_dir, req.region_id, req.path_type),
172            })?
173    };
174
175    let manifest = manifest_manager.manifest();
176    let region_metadata = manifest.metadata.clone();
177    let manifest_ctx = Arc::new(ManifestContext::new(
178        manifest_manager,
179        RegionRoleState::Leader(RegionLeaderState::Writable),
180    ));
181
182    let file_purger = {
183        let purge_scheduler = Arc::new(LocalScheduler::new(mito_config.max_background_purges));
184        Arc::new(LocalFilePurger::new(
185            purge_scheduler.clone(),
186            access_layer.clone(),
187            None,
188        ))
189    };
190
191    let current_version = {
192        let mut ssts = SstVersion::new();
193        ssts.add_files(file_purger.clone(), manifest.files.values().cloned());
194        CompactionVersion {
195            metadata: region_metadata.clone(),
196            options: req.region_options.clone(),
197            ssts: Arc::new(ssts),
198            compaction_time_window: manifest.compaction_time_window,
199        }
200    };
201
202    let ttl = match ttl_provider {
203        // Use the specified ttl.
204        Either::Left(ttl) => ttl,
205        // Get the ttl from the schema metadata manager.
206        Either::Right(schema_metadata_manager) => {
207            let (_, ttl) = find_dynamic_options(
208                req.region_id.table_id(),
209                &req.region_options,
210                &schema_metadata_manager,
211            )
212            .await
213            .unwrap_or_else(|e| {
214                warn!(e; "Failed to get ttl for region: {}", region_metadata.region_id);
215                (
216                    crate::region::options::CompactionOptions::default(),
217                    TimeToLive::default(),
218                )
219            });
220            ttl
221        }
222    };
223
224    Ok(CompactionRegion {
225        region_id: req.region_id,
226        region_options: req.region_options.clone(),
227        engine_config: Arc::new(mito_config.clone()),
228        region_metadata: region_metadata.clone(),
229        cache_manager: Arc::new(CacheManager::default()),
230        access_layer,
231        manifest_ctx,
232        current_version,
233        file_purger: Some(file_purger),
234        ttl: Some(ttl),
235        max_parallelism: req.max_parallelism,
236    })
237}
238
239impl CompactionRegion {
240    /// Get the file purger of the compaction region.
241    pub fn file_purger(&self) -> Option<Arc<LocalFilePurger>> {
242        self.file_purger.clone()
243    }
244
245    /// Stop the file purger scheduler of the compaction region.
246    pub async fn stop_purger_scheduler(&self) -> Result<()> {
247        if let Some(file_purger) = &self.file_purger {
248            file_purger.stop_scheduler().await
249        } else {
250            Ok(())
251        }
252    }
253}
254
255/// `[MergeOutput]` represents the output of merging SST files.
256#[derive(Default, Clone, Debug, Serialize, Deserialize)]
257pub struct MergeOutput {
258    pub files_to_add: Vec<FileMeta>,
259    pub files_to_remove: Vec<FileMeta>,
260    pub compaction_time_window: Option<i64>,
261}
262
263impl MergeOutput {
264    pub fn is_empty(&self) -> bool {
265        self.files_to_add.is_empty() && self.files_to_remove.is_empty()
266    }
267
268    pub fn input_file_size(&self) -> u64 {
269        self.files_to_remove.iter().map(|f| f.file_size).sum()
270    }
271
272    pub fn output_file_size(&self) -> u64 {
273        self.files_to_add.iter().map(|f| f.file_size).sum()
274    }
275}
276
277/// Compactor is the trait that defines the compaction logic.
278#[async_trait::async_trait]
279pub trait Compactor: Send + Sync + 'static {
280    /// Merge SST files for a region.
281    async fn merge_ssts(
282        &self,
283        compaction_region: &CompactionRegion,
284        picker_output: PickerOutput,
285    ) -> Result<MergeOutput>;
286
287    /// Update the manifest after merging SST files.
288    async fn update_manifest(
289        &self,
290        compaction_region: &CompactionRegion,
291        merge_output: MergeOutput,
292    ) -> Result<RegionEdit>;
293
294    /// Execute compaction for a region.
295    async fn compact(
296        &self,
297        compaction_region: &CompactionRegion,
298        compact_request_options: compact_request::Options,
299    ) -> Result<()>;
300}
301
302/// DefaultCompactor is the default implementation of Compactor.
303pub struct DefaultCompactor;
304
305impl DefaultCompactor {
306    /// Merge a single compaction output into SST files.
307    async fn merge_single_output(
308        compaction_region: CompactionRegion,
309        output: CompactionOutput,
310        write_opts: WriteOptions,
311    ) -> Result<Vec<FileMeta>> {
312        let region_id = compaction_region.region_id;
313        let storage = compaction_region.region_options.storage.clone();
314        let index_options = compaction_region
315            .current_version
316            .options
317            .index_options
318            .clone();
319        let append_mode = compaction_region.current_version.options.append_mode;
320        let merge_mode = compaction_region.current_version.options.merge_mode();
321        let flat_format = compaction_region
322            .region_options
323            .sst_format
324            .map(|format| format == FormatType::Flat)
325            .unwrap_or(
326                compaction_region
327                    .engine_config
328                    .default_experimental_flat_format,
329            );
330
331        let index_config = compaction_region.engine_config.index.clone();
332        let inverted_index_config = compaction_region.engine_config.inverted_index.clone();
333        let fulltext_index_config = compaction_region.engine_config.fulltext_index.clone();
334        let bloom_filter_index_config = compaction_region.engine_config.bloom_filter_index.clone();
335        #[cfg(feature = "vector_index")]
336        let vector_index_config = compaction_region.engine_config.vector_index.clone();
337
338        let input_file_names = output
339            .inputs
340            .iter()
341            .map(|f| f.file_id().to_string())
342            .join(",");
343        let max_sequence = output
344            .inputs
345            .iter()
346            .map(|f| f.meta_ref().sequence)
347            .max()
348            .flatten();
349        let builder = CompactionSstReaderBuilder {
350            metadata: compaction_region.region_metadata.clone(),
351            sst_layer: compaction_region.access_layer.clone(),
352            cache: compaction_region.cache_manager.clone(),
353            inputs: &output.inputs,
354            append_mode,
355            filter_deleted: output.filter_deleted,
356            time_range: output.output_time_range,
357            merge_mode,
358        };
359        let source = if flat_format {
360            let reader = builder.build_flat_sst_reader().await?;
361            Either::Right(FlatSource::Stream(reader))
362        } else {
363            let reader = builder.build_sst_reader().await?;
364            Either::Left(Source::Reader(reader))
365        };
366        let mut metrics = Metrics::new(WriteType::Compaction);
367        let region_metadata = compaction_region.region_metadata.clone();
368        let sst_infos = compaction_region
369            .access_layer
370            .write_sst(
371                SstWriteRequest {
372                    op_type: OperationType::Compact,
373                    metadata: region_metadata.clone(),
374                    source,
375                    cache_manager: compaction_region.cache_manager.clone(),
376                    storage,
377                    max_sequence: max_sequence.map(NonZero::get),
378                    index_options,
379                    index_config,
380                    inverted_index_config,
381                    fulltext_index_config,
382                    bloom_filter_index_config,
383                    #[cfg(feature = "vector_index")]
384                    vector_index_config,
385                },
386                &write_opts,
387                &mut metrics,
388            )
389            .await?;
390        // Convert partition expression once outside the map
391        let partition_expr = match &region_metadata.partition_expr {
392            None => None,
393            Some(json_str) if json_str.is_empty() => None,
394            Some(json_str) => PartitionExpr::from_json_str(json_str).with_context(|_| {
395                InvalidPartitionExprSnafu {
396                    expr: json_str.clone(),
397                }
398            })?,
399        };
400
401        let output_files = sst_infos
402            .into_iter()
403            .map(|sst_info| FileMeta {
404                region_id,
405                file_id: sst_info.file_id,
406                time_range: sst_info.time_range,
407                level: output.output_level,
408                file_size: sst_info.file_size,
409                max_row_group_uncompressed_size: sst_info.max_row_group_uncompressed_size,
410                available_indexes: sst_info.index_metadata.build_available_indexes(),
411                indexes: sst_info.index_metadata.build_indexes(),
412                index_file_size: sst_info.index_metadata.file_size,
413                index_version: 0,
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, false)
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}