Skip to main content

mito2/compaction/scheduler/
planning.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;
16use std::future::Future;
17use std::sync::Arc;
18use std::time::Instant;
19
20use api::v1::region::compact_request;
21use common_base::Plugins;
22use common_meta::key::SchemaMetadataManagerRef;
23use common_telemetry::{debug, error, info, warn};
24use common_time::TimeToLive;
25use common_time::range::TimestampRange;
26use futures::FutureExt;
27use snafu::ResultExt;
28use store_api::storage::RegionId;
29use tokio::sync::mpsc::{self, Sender};
30
31use crate::access_layer::AccessLayerRef;
32use crate::cache::CacheManagerRef;
33use crate::compaction::compactor::{CompactionRegion, CompactionVersion};
34use crate::compaction::last_non_null;
35use crate::compaction::picker::{PickerOutput, new_picker, new_twcs_picker};
36use crate::compaction::scheduler::history::{PickHistory, PickKey};
37use crate::compaction::scheduler::state::{
38    CompactingFiles, CompactionExecution, CompactionPhase, CompactionTaskState, CompactionTrigger,
39};
40use crate::compaction::scheduler::{CompactionScheduler, CompactionTransition};
41use crate::compaction::unit::CompactionUnit;
42use crate::compaction::{CompactionOutput, find_dynamic_options, format_panic_reason};
43use crate::config::MitoConfig;
44use crate::error::{CompactRegionSnafu, Error, RemoteCompactionSnafu, Result, UnexpectedSnafu};
45use crate::metrics::{
46    COMPACTION_MEMORY_REJECTED, COMPACTION_STAGE_ELAPSED, INFLIGHT_COMPACTION_COUNT,
47};
48use crate::region::ManifestContextRef;
49use crate::region::options::{MergeMode, RegionOptions};
50use crate::request::{BackgroundNotify, OutputTx, WorkerRequest, WorkerRequestWithTime};
51use crate::schedule::remote_job_scheduler::{
52    CompactionJob, DefaultNotifier, RemoteJob, RemoteJobSchedulerRef,
53};
54use crate::sst::file::FileHandle;
55use crate::sst::version::SstVersion;
56use crate::worker::WorkerListener;
57
58/// Region compaction request.
59pub struct CompactionRequest {
60    /// Private snapshot for automatic regular planning; manual requests carry none.
61    pub(crate) pick_history: Option<PickHistory>,
62    pub(crate) engine_config: Arc<MitoConfig>,
63    pub(crate) current_version: CompactionVersion,
64    pub(crate) access_layer: AccessLayerRef,
65    /// Sender to send notification to the region worker.
66    pub(crate) request_sender: mpsc::Sender<WorkerRequestWithTime>,
67    /// Start time of compaction task.
68    pub(crate) start_time: Instant,
69    pub(crate) cache_manager: CacheManagerRef,
70    pub(crate) manifest_ctx: ManifestContextRef,
71    pub(crate) listener: WorkerListener,
72    pub(crate) schema_metadata_manager: SchemaMetadataManagerRef,
73    pub(crate) max_parallelism: usize,
74}
75
76impl CompactionRequest {
77    pub(crate) fn region_id(&self) -> RegionId {
78        self.current_version.metadata.region_id
79    }
80}
81
82/// Result returned to the worker after background compaction planning.
83pub(crate) enum CompactionPlanningResult {
84    Prepared(PreparedCompaction),
85    /// Returns automatic history even for an empty plan, to prune stale eligibility.
86    NoPlan(Option<PickHistory>),
87    Error(Arc<Error>),
88}
89
90impl fmt::Debug for CompactionPlanningResult {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        match self {
93            Self::Prepared(prepared) => f
94                .debug_tuple("Prepared")
95                .field(&prepared.compaction_region.region_id)
96                .finish(),
97            Self::NoPlan(_) => f.write_str("NoPlan"),
98            Self::Error(err) => f.debug_tuple("Error").field(err).finish(),
99        }
100    }
101}
102
103/// Pure planning completion sent back to the owning region worker.
104#[derive(Debug)]
105pub(crate) struct CompactionPickFinished {
106    pub(crate) region_id: RegionId,
107    pub(crate) plan_id: u64,
108    pub(crate) result: CompactionPlanningResult,
109}
110
111pub(crate) struct PreparedCompaction {
112    /// Updated automatic snapshot, installed only after the worker accepts the plan.
113    /// Manual planning returns `None` and leaves resident waiting ages unchanged.
114    pick_history: Option<PickHistory>,
115    pub(super) compaction_region: CompactionRegion,
116    pub(super) picker_output: PickerOutput,
117    start_time: Instant,
118    ttl: TimeToLive,
119}
120
121/// Scheduler policy applied between stateless discovery and semantic closure.
122/// Runs on the planning runtime with a private history snapshot, never on the
123/// worker or through a shared mutex. Stale results cannot mutate resident state.
124async fn pick_automatic(
125    region: &CompactionRegion,
126    history: &mut PickHistory,
127    max_outputs: Option<usize>,
128    time_range: Option<TimestampRange>,
129) -> Result<Option<PickerOutput>> {
130    let picker = new_twcs_picker(&region.region_options, max_outputs, time_range, false);
131    let mut candidates = picker.discover(region).await?;
132    let last_non_null = region.region_options.merge_mode() == MergeMode::LastNonNull;
133    let now = Instant::now();
134    candidates.candidates = history.rank_candidates(candidates.candidates, now);
135    if !last_non_null {
136        candidates
137            .candidates
138            .truncate(max_outputs.unwrap_or(usize::MAX));
139    }
140    // finish() reverses candidates for the compactor's pop order. Keep seed
141    // identities in that same order without retaining them in execution state.
142    let keys: Vec<_> = candidates
143        .candidates
144        .iter()
145        .rev()
146        .map(PickKey::from)
147        .collect();
148    let output = candidates.finish().await?;
149    if last_non_null {
150        let (output, attempted_seeds) =
151            last_non_null::close_outputs(region, output, max_outputs).await?;
152        history.acknowledge(attempted_seeds.into_iter().map(|index| keys[index]), now);
153        Ok(output)
154    } else {
155        history.acknowledge(keys.into_iter(), now);
156        Ok((!output.outputs.is_empty() || !output.expired_ssts.is_empty()).then_some(output))
157    }
158}
159
160/// Exercises automatic selection and closure from cross-module regression tests.
161#[cfg(test)]
162pub(crate) async fn pick_automatic_for_test(
163    region: &CompactionRegion,
164    history: &mut PickHistory,
165    max_outputs: Option<usize>,
166) -> Result<Option<PickerOutput>> {
167    pick_automatic(region, history, max_outputs, None).await
168}
169
170impl CompactionScheduler {
171    pub(super) fn dispatch_compaction_planning(
172        &mut self,
173        plan_id: u64,
174        request: CompactionRequest,
175        options: compact_request::Options,
176        time_range: Option<TimestampRange>,
177        trigger: CompactionTrigger,
178    ) {
179        if let Some(status) = self.region_status.get_mut(&request.region_id()) {
180            status.active.task_state.get_or_insert_with(|| {
181                CompactionTaskState::new(
182                    request.region_id(),
183                    &options,
184                    request.max_parallelism,
185                    time_range,
186                    trigger,
187                )
188            });
189            status.publish_state();
190        }
191        let plugins = self.plugins.clone();
192        let max_background_compactions = self.engine_config.max_background_compactions;
193        common_runtime::spawn_compact(async move {
194            let region_id = request.region_id();
195            let request_sender = request.request_sender.clone();
196            let planning = Self::prepare_compaction(
197                request,
198                options,
199                plugins,
200                max_background_compactions,
201                time_range,
202                trigger,
203            );
204            Self::notify_planning_result(region_id, plan_id, request_sender, planning).await;
205        });
206    }
207
208    /// Runs the planning future and always sends the planning result back to
209    /// the worker, even if the planning panics.
210    ///
211    /// The worker only leaves the picking phase after it receives the
212    /// `CompactionPickFinished` notification. If a panicked planning task
213    /// swallowed the notification, the region would be stuck in the picking
214    /// phase forever, blocking all future compactions and pending DDLs (e.g.
215    /// entering staging) of the region.
216    pub(super) async fn notify_planning_result(
217        region_id: RegionId,
218        plan_id: u64,
219        request_sender: Sender<WorkerRequestWithTime>,
220        planning: impl Future<Output = CompactionPlanningResult> + Send,
221    ) {
222        // The idiomatic way to handle a panic result.
223        let result = std::panic::AssertUnwindSafe(planning).catch_unwind().await.unwrap_or_else(|payload| {
224            let reason = format_panic_reason(payload.as_ref());
225            CompactionPlanningResult::Error(Arc::new(
226                UnexpectedSnafu {
227                    reason: format!(
228                        "Compaction planning panicked for region {region_id}, plan_id {plan_id}: {reason}"
229                    ),
230                }
231                    .build(),
232            ))
233        });
234        if let CompactionPlanningResult::Error(err) = &result {
235            error!(err; "Compaction planning failed for region {}, plan_id: {}", region_id, plan_id);
236        }
237        let request = WorkerRequestWithTime::new(WorkerRequest::Background {
238            region_id,
239            notify: BackgroundNotify::CompactionPickFinished(CompactionPickFinished {
240                region_id,
241                plan_id,
242                result,
243            }),
244        });
245        if request_sender.send(request).await.is_err() {
246            warn!("Failed to send compaction planning result for region {region_id}");
247        }
248    }
249
250    async fn prepare_compaction(
251        request: CompactionRequest,
252        options: compact_request::Options,
253        plugins: Plugins,
254        max_background_compactions: usize,
255        time_range: Option<TimestampRange>,
256        trigger: CompactionTrigger,
257    ) -> CompactionPlanningResult {
258        let region_id = request.region_id();
259        let (dynamic_compaction_opts, ttl) = find_dynamic_options(
260            region_id,
261            &request.current_version.options,
262            &request.schema_metadata_manager,
263        )
264        .await
265        .unwrap_or_else(|e| {
266            warn!(e; "Failed to find dynamic options for region: {}", region_id);
267            (
268                request.current_version.options.compaction.clone(),
269                request.current_version.options.ttl.unwrap_or_default(),
270            )
271        });
272
273        // Bound accepted work independently of discovery. Waiting compensation
274        // persists across batches, including when automatic execution is serial.
275        let max_picker_outputs = max_background_compactions.min(request.max_parallelism.max(1));
276        let region_options = RegionOptions {
277            compaction: dynamic_compaction_opts,
278            ..request.current_version.options.clone()
279        };
280        let region_id = request.region_id();
281        let CompactionRequest {
282            pick_history,
283            engine_config,
284            current_version,
285            access_layer,
286            request_sender: _,
287            start_time,
288            cache_manager,
289            manifest_ctx,
290            listener,
291            schema_metadata_manager: _,
292            max_parallelism,
293        } = request;
294
295        let compaction_region = CompactionRegion {
296            region_id,
297            current_version: current_version.clone(),
298            region_options,
299            engine_config: engine_config.clone(),
300            region_metadata: current_version.metadata.clone(),
301            cache_manager: cache_manager.clone(),
302            access_layer: access_layer.clone(),
303            manifest_ctx: manifest_ctx.clone(),
304            file_purger: None,
305            ttl: Some(ttl),
306            max_parallelism,
307            plugins,
308        };
309
310        listener.on_compaction_pick_begin(region_id).await;
311        let _pick_timer = COMPACTION_STAGE_ELAPSED
312            .with_label_values(&["pick"])
313            .start_timer();
314        let mut history = pick_history;
315        let picked = if let Some(history) = &mut history {
316            pick_automatic(
317                &compaction_region,
318                history,
319                Some(max_picker_outputs),
320                time_range,
321            )
322            .await
323        } else {
324            new_picker(
325                &options,
326                &compaction_region.region_options,
327                Some(max_picker_outputs),
328                time_range,
329                trigger == CompactionTrigger::Manual,
330            )
331            .pick(&compaction_region)
332            .await
333        };
334        let picker_output = match picked {
335            Ok(Some(output)) => output,
336            Ok(None) => return CompactionPlanningResult::NoPlan(history),
337            Err(err) => return CompactionPlanningResult::Error(Arc::new(err)),
338        };
339
340        CompactionPlanningResult::Prepared(PreparedCompaction {
341            pick_history: history,
342            compaction_region,
343            picker_output,
344            start_time,
345            ttl,
346        })
347    }
348
349    /// Applies a background planning result to the current compaction lifecycle.
350    ///
351    /// # Returns
352    ///
353    /// Reports an automatic follow-up dispatched after Picking, or DDL requests
354    /// released when Picking terminates without creating an execution. The
355    /// owning worker must dispatch returned DDLs immediately because no
356    /// execution callback will follow.
357    pub(super) async fn handle_compaction_pick_finished_inner(
358        &mut self,
359        finished: CompactionPickFinished,
360        manifest_ctx: &ManifestContextRef,
361        schema_metadata_manager: SchemaMetadataManagerRef,
362    ) -> CompactionTransition {
363        let region_id = finished.region_id;
364        let plan_id = finished.plan_id;
365        let Some(status) = self.region_status.get_mut(&region_id) else {
366            return CompactionTransition::NoAction;
367        };
368
369        if !status.is_picking(finished.plan_id) {
370            return CompactionTransition::NoAction;
371        }
372        // Cancellation during Picking is completed by this notification. No
373        // execution callback will follow, so return DDLs released by the fence.
374        if !status.accept_plan(finished.plan_id) {
375            return self.finish_cancelled_compaction(
376                region_id,
377                manifest_ctx,
378                schema_metadata_manager,
379            );
380        }
381
382        // Manual/error results retain the resident history. Automatic snapshots
383        // replace it below only after passing the same lifecycle fence.
384        match finished.result {
385            CompactionPlanningResult::Prepared(mut prepared) => {
386                if let Some(history) = prepared.pick_history.take() {
387                    status.pick_history = history;
388                }
389                let current = status.version_control.current().version;
390                let Some(picker_output) =
391                    refresh_picker_output(prepared.picker_output, &current.ssts)
392                else {
393                    return self
394                        .finish_compaction_planning(
395                            region_id,
396                            None,
397                            manifest_ctx,
398                            schema_metadata_manager,
399                        )
400                        .await;
401                };
402                let Some(files) = CompactingFiles::try_new(&picker_output) else {
403                    return self
404                        .finish_compaction_planning(
405                            region_id,
406                            None,
407                            manifest_ctx,
408                            schema_metadata_manager,
409                        )
410                        .await;
411                };
412                prepared.picker_output = picker_output;
413                let Some(status) = self.region_status.get_mut(&region_id) else {
414                    return CompactionTransition::NoAction;
415                };
416                if let Some(info) = &mut status.active.task_state {
417                    info.accept_plan(&prepared.compaction_region, &prepared.picker_output);
418                }
419                status.publish_state();
420                let waiters = status.take_waiters();
421                match self
422                    .prepare_or_submit_compaction(prepared, files, waiters, plan_id)
423                    .await
424                {
425                    Ok(Some(phase)) => {
426                        if let Some(status) = self.region_status.get_mut(&region_id) {
427                            status.set_phase(phase);
428                        }
429                        self.dispatch_local_units(region_id);
430                        // The execution now owns the terminal transition. Any
431                        // fenced DDLs remain queued until its callback arrives.
432                        self.finish_local_units(region_id, manifest_ctx, schema_metadata_manager)
433                            .await
434                    }
435                    Ok(None) => {
436                        self.finish_compaction_planning(
437                            region_id,
438                            None,
439                            manifest_ctx,
440                            schema_metadata_manager,
441                        )
442                        .await
443                    }
444                    Err(err) => {
445                        self.fail_compaction(region_id, Arc::new(err));
446                        CompactionTransition::NoAction
447                    }
448                }
449            }
450            // These paths never create an execution. Finish the Picking
451            // lifecycle here and release DDLs if no follow-up was scheduled.
452            CompactionPlanningResult::NoPlan(history) => {
453                if let Some(history) = history {
454                    status.pick_history = history;
455                }
456                self.finish_compaction_planning(
457                    region_id,
458                    None,
459                    manifest_ctx,
460                    schema_metadata_manager,
461                )
462                .await
463            }
464            CompactionPlanningResult::Error(err) => {
465                self.finish_compaction_planning(
466                    region_id,
467                    Some(err),
468                    manifest_ctx,
469                    schema_metadata_manager,
470                )
471                .await
472            }
473        }
474    }
475
476    async fn finish_compaction_planning(
477        &mut self,
478        region_id: RegionId,
479        err: Option<Arc<Error>>,
480        manifest_ctx: &ManifestContextRef,
481        schema_metadata_manager: SchemaMetadataManagerRef,
482    ) -> CompactionTransition {
483        let Some(status) = self.region_status.get_mut(&region_id) else {
484            return CompactionTransition::NoAction;
485        };
486        for waiter in status.take_waiters() {
487            if let Some(err) = &err {
488                waiter.send(Err(err.clone()).context(CompactRegionSnafu { region_id }));
489            } else {
490                waiter.send(Ok(0));
491            }
492        }
493
494        if let Some(ddls) = self.take_ready_ddls(region_id) {
495            return CompactionTransition::DdlReady(ddls);
496        }
497        if self.handle_pending_compaction_request(
498            region_id,
499            manifest_ctx,
500            schema_metadata_manager.clone(),
501        ) {
502            return CompactionTransition::NoAction;
503        }
504
505        let Some(status) = self.region_status.get_mut(&region_id) else {
506            return CompactionTransition::NoAction;
507        };
508
509        if status.active.reset_automatic_followup()
510            && self.schedule_automatic_followup(region_id, manifest_ctx, schema_metadata_manager)
511        {
512            return CompactionTransition::AutomaticFollowupScheduled;
513        }
514
515        if let Some(status) = self.region_status.get_mut(&region_id) {
516            status.become_idle();
517        }
518        CompactionTransition::NoAction
519    }
520
521    /// Submits a remote job, or prepares local unit tasks without submitting them.
522    /// The caller dispatches local units after installing the returned phase.
523    async fn prepare_or_submit_compaction(
524        &mut self,
525        prepared: PreparedCompaction,
526        files: CompactingFiles,
527        waiters: Vec<OutputTx>,
528        plan_id: u64,
529    ) -> Result<Option<CompactionPhase>> {
530        let PreparedCompaction {
531            pick_history: _,
532            compaction_region,
533            picker_output,
534            start_time,
535            ttl,
536        } = prepared;
537        let region_id = compaction_region.region_id;
538        let dynamic_compaction_opts = &compaction_region.region_options.compaction;
539
540        // If specified to run compaction remotely, we schedule the compaction job remotely.
541        // It will fall back to local compaction if there is no remote job scheduler.
542        let waiters = if dynamic_compaction_opts.remote_compaction() {
543            if let Some(remote_job_scheduler) = &self.plugins.get::<RemoteJobSchedulerRef>() {
544                let execution = CompactionExecution::new(plan_id, files.clone());
545                let remote_compaction_job = CompactionJob {
546                    compaction_region: compaction_region.clone(),
547                    picker_output: picker_output.clone(),
548                    start_time,
549                    waiters,
550                    ttl,
551                };
552
553                let result = remote_job_scheduler
554                    .schedule(
555                        RemoteJob::CompactionJob(remote_compaction_job),
556                        Box::new(DefaultNotifier::new(
557                            self.request_sender.clone(),
558                            execution.clone(),
559                        )),
560                    )
561                    .await;
562
563                match result {
564                    Ok(job_id) => {
565                        info!(
566                            "Scheduled remote compaction job {} for region {}",
567                            job_id, region_id
568                        );
569                        INFLIGHT_COMPACTION_COUNT.inc();
570                        return Ok(Some(CompactionPhase::Remote { execution }));
571                    }
572                    Err(e) => {
573                        if !dynamic_compaction_opts.fallback_to_local() {
574                            error!(e; "Failed to schedule remote compaction job for region {}", region_id);
575                            if let Some(status) = self.region_status.get_mut(&region_id) {
576                                status.extend_waiters(e.waiters);
577                            }
578                            return RemoteCompactionSnafu {
579                                region_id,
580                                job_id: None,
581                                reason: e.reason,
582                            }
583                            .fail();
584                        }
585
586                        error!(e; "Failed to schedule remote compaction job for region {}, fallback to local compaction", region_id);
587                        // An error may be ambiguous after the remote scheduler consumed
588                        // the notifier. Fence a delayed remote callback from the local fallback.
589                        e.waiters
590                    }
591                }
592            } else {
593                debug!(
594                    "Remote compaction is not enabled, fallback to local compaction for region {}",
595                    region_id
596                );
597                waiters
598            }
599        } else {
600            waiters
601        };
602
603        let units = CompactionUnit::from_picker(picker_output);
604        if let Some(status) = self.region_status.get_mut(&region_id) {
605            status.extend_waiters(waiters);
606        }
607        let Some(mut units) = units else {
608            return UnexpectedSnafu {
609                reason: "Compaction plan expires a merge input",
610            }
611            .fail();
612        };
613        units.retain(|unit| {
614            let estimated_bytes =
615compaction_region.estimated_memory_bytes(unit);
616            let Some(limit_bytes) = self.exceeds_compaction_memory_limit(estimated_bytes) else { return true };
617            COMPACTION_MEMORY_REJECTED
618                .with_label_values(&["oversized"])
619                .inc();
620            warn!(
621                "Skip compaction for region {} because estimated memory {} bytes exceeds compaction memory limit {} bytes",
622                region_id, estimated_bytes, limit_bytes,
623            );
624            false
625        });
626        if units.is_empty() {
627            return Ok(None);
628        }
629        Ok(Some(self.prepare_local_units(
630            compaction_region,
631            units,
632            files,
633        )?))
634    }
635
636    fn exceeds_compaction_memory_limit(&self, estimated_bytes: u64) -> Option<u64> {
637        let limit_bytes = self.memory_manager.limit_bytes();
638        if limit_bytes > 0 && estimated_bytes > limit_bytes {
639            Some(limit_bytes)
640        } else {
641            None
642        }
643    }
644}
645
646/// Rebuilds picker output with current SST handles while preserving the picker's grouping.
647///
648/// Picking runs in background on a version snapshot that may be stale by the
649/// time the plan is accepted: a concurrent flush, compaction or index rebuild
650/// can replace a selected file with a new handle carrying updated metadata
651/// (e.g. `index_version`), or remove the file entirely. The handles in the
652/// picker output therefore cannot be used as-is; re-resolving them against the
653/// current version both detects gone files (aborting the plan) and ensures the
654/// execution reads and reserves the up-to-date handle.
655fn refresh_picker_output(output: PickerOutput, current: &SstVersion) -> Option<PickerOutput> {
656    let refresh = |file: FileHandle| {
657        current
658            .file_for_compaction(&file)
659            .filter(|current| !current.is_deleted() && !current.compacting())
660            .cloned()
661    };
662    let outputs = output
663        .outputs
664        .into_iter()
665        .map(|output| {
666            let inputs = output
667                .inputs
668                .into_iter()
669                .map(&refresh)
670                .collect::<Option<Vec<_>>>()?;
671            Some(CompactionOutput { inputs, ..output })
672        })
673        .collect::<Option<Vec<_>>>()?;
674    let expired_ssts = output
675        .expired_ssts
676        .into_iter()
677        .map(refresh)
678        .collect::<Option<Vec<_>>>()?;
679
680    Some(PickerOutput {
681        outputs,
682        expired_ssts,
683        time_window_size: output.time_window_size,
684        max_file_size: output.max_file_size,
685    })
686}