Skip to main content

mito2/worker/
handle_compaction.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 api::v1::region::compact_request;
16use common_telemetry::{debug, error, info};
17use store_api::logstore::LogStore;
18use store_api::region_request::RegionCompactRequest;
19use store_api::storage::RegionId;
20
21use crate::compaction::{CompactionPickFinished, CompactionTransition};
22use crate::config::IndexBuildMode;
23use crate::error::{RegionNotFoundSnafu, StaleCompactionExecutionSnafu};
24use crate::metrics::COMPACTION_REQUEST_COUNT;
25use crate::region::MitoRegionRef;
26use crate::request::{
27    BuildIndexRequest, CompactionFailed, CompactionFinished, CompactionUnitNotification, OnFailure,
28    OptionOutputTx,
29};
30use crate::sst::index::IndexBuildType;
31use crate::worker::RegionWorkerLoop;
32use crate::worker::handle_rebuild_index::needs_background_indexes;
33
34fn made_progress(files_to_add: usize, files_to_remove: usize) -> bool {
35    files_to_add > 0 || files_to_remove > files_to_add
36}
37
38impl<S> RegionWorkerLoop<S> {
39    /// Drives local unit publication and applies successful edits before acknowledging completion.
40    pub(crate) async fn handle_compaction_unit(
41        &mut self,
42        region_id: RegionId,
43        notify: CompactionUnitNotification,
44    ) where
45        S: LogStore,
46    {
47        match notify {
48            CompactionUnitNotification::Finished {
49                plan_id,
50                result,
51                applied,
52            } => {
53                let Some(region) = self.regions.get_region(region_id) else {
54                    return;
55                };
56                match result {
57                    Ok(edit) => {
58                        if !self.compaction_scheduler.can_apply_unit(region_id, plan_id) {
59                            let _ = applied.send(());
60                            return;
61                        }
62                        let progress =
63                            made_progress(edit.files_to_add.len(), edit.files_to_remove.len());
64                        region.apply_published_edit(edit.clone(), &[]).await;
65                        self.listener.on_compaction_unit_applied(region_id, plan_id);
66                        self.compaction_scheduler.on_unit_finished(
67                            region_id,
68                            plan_id,
69                            Ok(progress),
70                        );
71                        let files_to_index = edit
72                            .files_to_add
73                            .into_iter()
74                            .filter(needs_background_indexes)
75                            .collect::<Vec<_>>();
76                        if self.config.index.build_mode == IndexBuildMode::Async
77                            && !files_to_index.is_empty()
78                        {
79                            self.handle_rebuild_index(
80                                BuildIndexRequest {
81                                    region_id,
82                                    build_type: IndexBuildType::Compact,
83                                    file_metas: files_to_index,
84                                    result_senders: Vec::new(),
85                                },
86                                OptionOutputTx::new(None),
87                            )
88                            .await;
89                        }
90                    }
91                    Err(err) => {
92                        self.compaction_scheduler
93                            .on_unit_finished(region_id, plan_id, Err(err));
94                    }
95                }
96                let _ = applied.send(());
97            }
98            CompactionUnitNotification::Released { plan_id } => {
99                let Some(region) = self.regions.get_region(region_id) else {
100                    return;
101                };
102                let transition = self
103                    .compaction_scheduler
104                    .on_unit_released(
105                        region_id,
106                        plan_id,
107                        &region.manifest_ctx,
108                        self.schema_metadata_manager.clone(),
109                    )
110                    .await;
111                self.listener.on_compaction_result_notified(region_id).await;
112                match transition {
113                    CompactionTransition::AutomaticFollowupScheduled => {
114                        region.update_schedule_compaction_millis()
115                    }
116                    CompactionTransition::DdlReady(mut ddls) => {
117                        self.handle_ddl_requests(&mut ddls).await
118                    }
119                    CompactionTransition::NoAction => {}
120                }
121            }
122        }
123    }
124
125    pub(crate) async fn handle_compaction_pick_finished(
126        &mut self,
127        region_id: RegionId,
128        request: CompactionPickFinished,
129    ) where
130        S: LogStore,
131    {
132        let Some(region) = self.regions.get_region(region_id) else {
133            return;
134        };
135        // A terminal pick (canceled, no plan, or failed) may return the region
136        // to idle and release DDLs fenced behind its picking phase.
137        // Such a pick never produces an execution callback, so the worker must
138        // execute the returned DDLs from this notification.
139        let transition = self
140            .compaction_scheduler
141            .handle_compaction_pick_finished(
142                request,
143                &region.manifest_ctx,
144                self.schema_metadata_manager.clone(),
145            )
146            .await;
147        match transition {
148            CompactionTransition::AutomaticFollowupScheduled => {
149                // There will be a followup compaction so we need to update the
150                // last schedule time to avoid frequent compactions.
151                region.update_schedule_compaction_millis();
152            }
153            CompactionTransition::NoAction => {}
154            CompactionTransition::DdlReady(mut pending_ddls) => {
155                if !pending_ddls.is_empty() {
156                    // Preserve the lifecycle order observed by listeners: compaction
157                    // termination is visible before its dependent DDLs are dispatched.
158                    self.listener.on_compaction_result_notified(region_id).await;
159                    self.handle_ddl_requests(&mut pending_ddls).await;
160                }
161            }
162        }
163    }
164
165    /// Handles compaction request submitted to region worker.
166    pub(crate) async fn handle_compaction_request(
167        &mut self,
168        region_id: RegionId,
169        req: RegionCompactRequest,
170        mut sender: OptionOutputTx,
171    ) {
172        let Some(region) = self.regions.writable_region_or(region_id, &mut sender) else {
173            return;
174        };
175        COMPACTION_REQUEST_COUNT.inc();
176        let parallelism = req.parallelism.unwrap_or(1) as usize;
177        match self.compaction_scheduler.schedule_manual_compaction(
178            req.options,
179            &region.version_control,
180            &region.access_layer,
181            sender,
182            &region.manifest_ctx,
183            self.schema_metadata_manager.clone(),
184            parallelism,
185            req.time_range,
186        ) {
187            // Ok(false) means the request was merged, queued or rejected; the
188            // waiter was already notified or will be completed by the queued
189            // cycle, so only a newly scheduled task is logged as success.
190            Ok(true) => info!(
191                "Successfully scheduled compaction task for region: {}",
192                region_id
193            ),
194            Ok(false) => {}
195            Err(e) => {
196                error!(e; "Failed to schedule compaction task for region: {}", region_id);
197            }
198        }
199    }
200
201    /// Handles compaction finished, update region version and manifest, deleted compacted files.
202    pub(crate) async fn handle_compaction_finished(
203        &mut self,
204        region_id: RegionId,
205        mut request: CompactionFinished,
206    ) where
207        S: LogStore,
208    {
209        let region = match self.regions.get_region(region_id) {
210            Some(region) => region,
211            None => {
212                request.on_failure(RegionNotFoundSnafu { region_id }.build());
213                return;
214            }
215        };
216        // Reject stale terminal results before applying their manifest edit.
217        if !self
218            .compaction_scheduler
219            .is_current_execution(region_id, &request.execution)
220        {
221            request.on_failure(StaleCompactionExecutionSnafu { region_id }.build());
222            return;
223        }
224        let execution = request.execution.clone();
225        let made_progress = made_progress(
226            request.edit.files_to_add.len(),
227            request.edit.files_to_remove.len(),
228        );
229
230        region.apply_published_edit(request.edit.clone(), &[]).await;
231
232        let index_build_file_metas = std::mem::take(&mut request.edit.files_to_add)
233            .into_iter()
234            .filter(needs_background_indexes)
235            .collect::<Vec<_>>();
236
237        // compaction finished.
238        request.on_success();
239        self.listener.on_compaction_result_notified(region_id).await;
240
241        // In async mode, create indexes after compact if new files are created.
242        if self.config.index.build_mode == IndexBuildMode::Async
243            && !index_build_file_metas.is_empty()
244        {
245            self.handle_rebuild_index(
246                BuildIndexRequest {
247                    region_id,
248                    build_type: IndexBuildType::Compact,
249                    file_metas: index_build_file_metas,
250                    result_senders: Vec::new(),
251                },
252                OptionOutputTx::new(None),
253            )
254            .await;
255        }
256
257        // Schedule next compaction if necessary.
258        let transition = self
259            .compaction_scheduler
260            .on_execution_finished(
261                region_id,
262                &execution,
263                &region.manifest_ctx,
264                self.schema_metadata_manager.clone(),
265                made_progress,
266            )
267            .await;
268        match transition {
269            CompactionTransition::AutomaticFollowupScheduled => {
270                region.update_schedule_compaction_millis();
271            }
272            CompactionTransition::NoAction => {}
273            CompactionTransition::DdlReady(mut pending_ddls) => {
274                self.handle_ddl_requests(&mut pending_ddls).await;
275            }
276        }
277    }
278
279    /// When compaction fails, we simply log the error.
280    pub(crate) async fn handle_compaction_failure(&mut self, req: CompactionFailed) {
281        if self.regions.get_region(req.region_id).is_none() {
282            return;
283        }
284        if !self
285            .compaction_scheduler
286            .is_current_execution(req.region_id, &req.execution)
287        {
288            debug!(
289                "Ignores stale compaction failure for region {}: {:?}",
290                req.region_id, req.err
291            );
292            return;
293        }
294
295        error!(req.err; "Failed to compact region: {}", req.region_id);
296        self.compaction_scheduler
297            .on_execution_failed(req.region_id, &req.execution, req.err);
298    }
299
300    /// Schedule compaction for the region if necessary.
301    pub(crate) async fn schedule_compaction(&mut self, region: &MitoRegionRef) {
302        if region.in_staging_session() || region.is_enter_staging() || region.is_truncating() {
303            info!(
304                "Region {} is staging, entering staging, or truncating, skip compaction",
305                region.region_id
306            );
307            return;
308        }
309        let now = self.time_provider.current_time_millis();
310        if now - region.last_schedule_compaction_millis()
311            >= self.config.min_compaction_interval.as_millis() as i64
312        {
313            debug!(
314                "minimal compaction interval time {:?} has passed, scheduling next compaction",
315                self.config.min_compaction_interval
316            );
317            match self.compaction_scheduler.schedule_automatic_compaction(
318                compact_request::Options::Regular(Default::default()),
319                &region.version_control,
320                &region.access_layer,
321                &region.manifest_ctx,
322                self.schema_metadata_manager.clone(),
323            ) {
324                Ok(true) => region.update_schedule_compaction_millis(),
325                Ok(false) => {}
326                Err(e) => {
327                    error!(e; "Failed to schedule compaction for region: {}", region.region_id)
328                }
329            }
330        }
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use super::made_progress;
337
338    #[test]
339    fn test_nonempty_output_or_file_reduction_is_progress() {
340        for (files_to_add, files_to_remove, expected) in [
341            (3, 3, true),  // Equal-count rewrite.
342            (1, 3, true),  // Ordinary reduction.
343            (0, 3, true),  // Zero-output reduction.
344            (0, 0, false), // Empty edit.
345            (3, 2, true),  // Growth rewrite with output.
346        ] {
347            assert_eq!(
348                expected,
349                made_progress(files_to_add, files_to_remove),
350                "files_to_remove: {files_to_remove}, files_to_add: {files_to_add}"
351            );
352        }
353    }
354}