Skip to main content

mito2/compaction/
scheduler.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
15mod coordinator;
16pub(crate) mod history;
17mod local;
18mod planning;
19mod state;
20
21use std::collections::HashMap;
22use std::sync::{Arc, LazyLock};
23
24use api::v1::region::compact_request;
25use common_base::Plugins;
26use common_memory_manager::OnExhaustedPolicy;
27use common_meta::key::SchemaMetadataManagerRef;
28#[cfg(test)]
29use common_recordbatch::filter::MetadataFilter;
30use common_telemetry::{debug, error, info, warn};
31use common_time::range::TimestampRange;
32pub(crate) use coordinator::{CompactionCoordinator, ReadyUnit};
33#[cfg(test)]
34use datafusion_common::ScalarValue;
35pub(crate) use planning::CompactionPickFinished;
36pub use planning::CompactionRequest;
37#[cfg(test)]
38pub(crate) use planning::pick_automatic_for_test;
39pub use state::CompactionGuard;
40pub(crate) use state::{CompactionExecution, CompactionState, CompactionStateRef};
41use state::{CompactionStatus, CompactionTrigger, DdlExecution, PendingCompaction};
42#[cfg(test)]
43use store_api::compaction_task::{self, CompactionTaskEntry};
44use store_api::storage::RegionId;
45use tokio::sync::mpsc::Sender;
46
47use crate::access_layer::AccessLayerRef;
48use crate::cache::CacheManagerRef;
49use crate::compaction::memory_manager::CompactionMemoryManager;
50use crate::config::MitoConfig;
51use crate::error::{
52    CompactionCancelledSnafu, Error, ManualCompactionAlreadyRunningSnafu, RegionClosedSnafu,
53    RegionDroppedSnafu, RegionTruncatedSnafu, Result, UnsupportedOperationSnafu,
54};
55use crate::region::ManifestContextRef;
56use crate::region::version::VersionControlRef;
57use crate::request::{
58    DdlRequest, OptionOutputTx, PauseCompactionResponse, SenderDdlRequest, WorkerRequestWithTime,
59};
60use crate::schedule::RequestCancelResult;
61use crate::worker::WorkerListener;
62
63/// Outcome of cancelling one live compaction task by its exact task identity.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub(crate) enum CancelCompactionResult {
66    /// Cancellation was requested; completion is asynchronous.
67    CancelIssued,
68    /// The task is already cancelling.
69    AlreadyCancelling,
70    /// The task has crossed its non-cancellable commit boundary.
71    TooLateToCancel,
72    /// The task is no longer present on this region.
73    NotFound,
74    /// This engine or execution mode does not support cancellation.
75    Unsupported,
76}
77
78impl From<RequestCancelResult> for CancelCompactionResult {
79    fn from(result: RequestCancelResult) -> Self {
80        match result {
81            RequestCancelResult::CancelIssued => Self::CancelIssued,
82            RequestCancelResult::AlreadyCancelling => Self::AlreadyCancelling,
83            RequestCancelResult::TooLateToCancel => Self::TooLateToCancel,
84        }
85    }
86}
87
88/// Internal testing switch to prevent SST compaction from changing file layouts
89/// during query regression tests. This is not a public configuration option.
90const DISABLE_COMPACTION_ENV: &str = "GREPTIME_DISABLE_COMPACTION";
91
92/// Internal query-regression switch, read once when the first scheduler starts.
93/// Applies to SST compaction only; ingestion and flushing remain enabled.
94static DISABLE_COMPACTION: LazyLock<bool> = LazyLock::new(|| {
95    let value = std::env::var(DISABLE_COMPACTION_ENV).ok();
96    let disabled = parse_disable_compaction(value.as_deref());
97    if disabled {
98        warn!(
99            "SST compaction is disabled by {DISABLE_COMPACTION_ENV}; restart without it to resume"
100        );
101    }
102    disabled
103});
104
105fn parse_disable_compaction(value: Option<&str>) -> bool {
106    match value {
107        None | Some("false") => false,
108        Some("true") => true,
109        Some(_) => {
110            warn!(
111                "Invalid {DISABLE_COMPACTION_ENV}: expected true or false; compaction remains enabled"
112            );
113            false
114        }
115    }
116}
117
118/// Compaction scheduler tracks and manages compaction tasks.
119pub(crate) struct CompactionScheduler {
120    /// Disables SST compaction for internal query regression tests.
121    /// Initialized from [`DISABLE_COMPACTION`] and fixed for the scheduler's lifetime
122    /// in production; unit tests can override it without changing the process environment.
123    disable_compaction: bool,
124    coordinator: Arc<CompactionCoordinator>,
125    /// All loaded regions, including idle regions and regions executing DDLs.
126    region_status: HashMap<RegionId, CompactionStatus>,
127    /// Request sender of the worker that this scheduler belongs to.
128    request_sender: Sender<WorkerRequestWithTime>,
129    cache_manager: CacheManagerRef,
130    engine_config: Arc<MitoConfig>,
131    memory_manager: Arc<CompactionMemoryManager>,
132    memory_policy: OnExhaustedPolicy,
133    listener: WorkerListener,
134    /// Plugins for the compaction scheduler.
135    plugins: Plugins,
136    /// Scheduler-wide generation counter for compaction plans and executions.
137    /// It outlives region statuses so close/reopen cannot reuse an old identity.
138    next_plan_id: u64,
139}
140
141/// Describes the immediate action produced by a compaction terminal transition.
142#[derive(Debug)]
143pub(crate) enum CompactionTransition {
144    /// No follow-up work was dispatched and no DDL became ready.
145    NoAction,
146    /// An automatic follow-up planning cycle was dispatched.
147    AutomaticFollowupScheduled,
148    /// DDL requests became ready after the compaction lifecycle terminated.
149    DdlReady(Vec<SenderDdlRequest>),
150}
151
152impl CompactionTransition {
153    fn from_pending_ddls(pending_ddls: Vec<SenderDdlRequest>) -> Self {
154        if pending_ddls.is_empty() {
155            Self::NoAction
156        } else {
157            Self::DdlReady(pending_ddls)
158        }
159    }
160
161    #[cfg(test)]
162    fn is_empty(&self) -> bool {
163        !matches!(self, Self::DdlReady(pending_ddls) if !pending_ddls.is_empty())
164    }
165
166    #[cfg(test)]
167    fn len(&self) -> usize {
168        match self {
169            Self::DdlReady(pending_ddls) => pending_ddls.len(),
170            Self::NoAction | Self::AutomaticFollowupScheduled => 0,
171        }
172    }
173}
174
175// API used by callers outside the compaction scheduler module.
176impl CompactionScheduler {
177    /// Creates an empty scheduler bound to one region worker.
178    ///
179    /// # Effects
180    ///
181    /// Stores the worker request sender and shared scheduling resources. No
182    /// compaction is dispatched until a scheduling method is called.
183    ///
184    /// # Constraints
185    ///
186    /// All lifecycle methods on the returned scheduler must be driven by the
187    /// same worker so region state transitions remain serialized.
188    #[allow(clippy::too_many_arguments)]
189    pub(crate) fn new(
190        coordinator: Arc<CompactionCoordinator>,
191        request_sender: Sender<WorkerRequestWithTime>,
192        cache_manager: CacheManagerRef,
193        engine_config: Arc<MitoConfig>,
194        listener: WorkerListener,
195        plugins: Plugins,
196        memory_manager: Arc<CompactionMemoryManager>,
197        memory_policy: OnExhaustedPolicy,
198    ) -> Self {
199        Self {
200            disable_compaction: *DISABLE_COMPACTION,
201            coordinator,
202            region_status: HashMap::new(),
203            request_sender,
204            cache_manager,
205            engine_config,
206            memory_manager,
207            memory_policy,
208            listener,
209            plugins,
210            next_plan_id: 0,
211        }
212    }
213
214    /// Registers a loaded region; replacing its VersionControl invalidates the old incarnation.
215    pub(crate) fn register_region(
216        &mut self,
217        version_control: &VersionControlRef,
218        access_layer: &AccessLayerRef,
219        shared_state: &CompactionStateRef,
220    ) {
221        let region_id = version_control.region_id();
222        if let Some(status) = self.region_status.get_mut(&region_id) {
223            if Arc::ptr_eq(&status.version_control, version_control) {
224                return;
225            }
226            status.on_failure(Arc::new(RegionClosedSnafu { region_id }.build()));
227        }
228        let mut status =
229            CompactionStatus::new(region_id, version_control.clone(), access_layer.clone());
230        status.shared_state = shared_state.clone();
231        self.region_status.insert(region_id, status);
232    }
233
234    pub(crate) fn pause_compaction(
235        &mut self,
236        region_id: RegionId,
237        sender: tokio::sync::oneshot::Sender<Result<PauseCompactionResponse>>,
238    ) {
239        if let Some(status) = self.region_status.get_mut(&region_id) {
240            status.pause(sender);
241        } else {
242            let _ = sender.send(crate::error::RegionNotFoundSnafu { region_id }.fail());
243        }
244    }
245
246    /// Cancels an exact live identity, checking the pending slot before the active cycle.
247    pub(crate) fn cancel_task(
248        &mut self,
249        region_id: RegionId,
250        task_id: &str,
251    ) -> CancelCompactionResult {
252        let Some(status) = self.region_status.get_mut(&region_id) else {
253            return CancelCompactionResult::NotFound;
254        };
255        status.cancel_task(task_id)
256    }
257
258    /// Reports active work rather than the existence of a resident region record.
259    #[cfg(test)]
260    fn is_compacting(&self, region_id: RegionId) -> bool {
261        self.region_status
262            .get(&region_id)
263            .is_some_and(CompactionStatus::is_compacting)
264    }
265
266    /// Accepts an automatic compaction trigger for a region.
267    ///
268    /// # Effects
269    ///
270    /// Starts planning when the registered region is idle.
271    /// Otherwise, an active status coalesces the trigger into one unrestricted
272    /// follow-up cycle. Returns `true` only when this call dispatches planning.
273    ///
274    /// # Constraints
275    ///
276    /// The owning region worker must call this method serially. Automatic
277    /// triggers have no waiter and may be ignored while a DDL fence is active.
278    /// The region identity comes from `version_control`; `access_layer` and
279    /// `manifest_ctx` must belong to the same region.
280    pub(crate) fn schedule_automatic_compaction(
281        &mut self,
282        compact_options: compact_request::Options,
283        version_control: &VersionControlRef,
284        access_layer: &AccessLayerRef,
285        manifest_ctx: &ManifestContextRef,
286        schema_metadata_manager: SchemaMetadataManagerRef,
287    ) -> Result<bool> {
288        self.schedule_compaction(
289            CompactionTrigger::Automatic,
290            compact_options,
291            version_control,
292            access_layer,
293            OptionOutputTx::none(),
294            manifest_ctx,
295            schema_metadata_manager,
296            self.engine_config.max_background_compactions,
297            None,
298        )
299    }
300
301    /// Accepts a manual compaction request for a region.
302    ///
303    /// # Effects
304    ///
305    /// Starts planning when the registered region is idle. During
306    /// an automatic compaction, queues the request and replaces any older
307    /// pending manual request; during a manual compaction, rejects the new
308    /// request through `waiter`. Returns `true` only when this call dispatches
309    /// planning.
310    ///
311    /// # Constraints
312    ///
313    /// The owning region worker must call this method serially. The supplied
314    /// waiter is completed exactly once by cycle completion, replacement,
315    /// cancellation, failure, or region teardown. The region identity comes
316    /// from `version_control`; `access_layer` and `manifest_ctx` must belong to
317    /// the same region.
318    #[allow(clippy::too_many_arguments)]
319    pub(crate) fn schedule_manual_compaction(
320        &mut self,
321        compact_options: compact_request::Options,
322        version_control: &VersionControlRef,
323        access_layer: &AccessLayerRef,
324        waiter: OptionOutputTx,
325        manifest_ctx: &ManifestContextRef,
326        schema_metadata_manager: SchemaMetadataManagerRef,
327        max_parallelism: usize,
328        time_range: Option<TimestampRange>,
329    ) -> Result<bool> {
330        self.schedule_compaction(
331            CompactionTrigger::Manual,
332            compact_options,
333            version_control,
334            access_layer,
335            waiter,
336            manifest_ctx,
337            schema_metadata_manager,
338            max_parallelism,
339            time_range,
340        )
341    }
342
343    /// Applies a background planning result to the current region state.
344    ///
345    /// # Effects
346    ///
347    /// Rejects stale plans, submits a prepared local or remote execution, or
348    /// completes the cycle when planning produced no executable plan. The
349    /// returned transition reports a dispatched automatic follow-up or DDL
350    /// requests released by the resulting terminal transition.
351    ///
352    /// # Constraints
353    ///
354    /// The owning worker must call this method for planning notifications and
355    /// must execute every returned DDL request. The notification may be stale;
356    /// stale notifications intentionally have no effect.
357    pub(crate) async fn handle_compaction_pick_finished(
358        &mut self,
359        finished: CompactionPickFinished,
360        manifest_ctx: &ManifestContextRef,
361        schema_metadata_manager: SchemaMetadataManagerRef,
362    ) -> CompactionTransition {
363        self.handle_compaction_pick_finished_inner(finished, manifest_ctx, schema_metadata_manager)
364            .await
365    }
366
367    /// Returns whether a terminal notification belongs to the installed execution.
368    ///
369    /// # Effects
370    ///
371    /// Performs a read-only identity check against the region's current plan.
372    ///
373    /// # Constraints
374    ///
375    /// Callers must check this before applying a compaction edit. Matching only
376    /// the region id is insufficient because close/reopen can replace a status.
377    pub(crate) fn is_current_execution(
378        &self,
379        region_id: RegionId,
380        execution: &CompactionExecution,
381    ) -> bool {
382        self.region_status
383            .get(&region_id)
384            .is_some_and(|status| status.matches_execution(execution))
385    }
386
387    /// Completes the installed execution after its edit has been applied.
388    ///
389    /// # Effects
390    ///
391    /// Notifies waiters, schedules a pending manual or automatic follow-up, or
392    /// returns the region to idle. A follow-up is scheduled whenever the cycle
393    /// latched an automatic trigger, or when `made_progress` is true (the
394    /// execution produced output or reduced the file count): successful compaction
395    /// keeps draining the region until the picker returns no plan. The returned
396    /// transition reports a dispatched automatic follow-up or DDLs that are now
397    /// safe to execute.
398    ///
399    /// # Constraints
400    ///
401    /// The owning worker must call this only after accepting and applying the
402    /// execution's result, and must execute every returned DDL request. Stale
403    /// executions are ignored.
404    pub(crate) async fn on_execution_finished(
405        &mut self,
406        region_id: RegionId,
407        execution: &CompactionExecution,
408        manifest_ctx: &ManifestContextRef,
409        schema_metadata_manager: SchemaMetadataManagerRef,
410        made_progress: bool,
411    ) -> CompactionTransition {
412        if !self.is_current_execution(region_id, execution) {
413            return CompactionTransition::NoAction;
414        }
415        self.on_compaction_finished(
416            region_id,
417            manifest_ctx,
418            schema_metadata_manager,
419            made_progress,
420        )
421        .await
422    }
423
424    /// Records failure of the installed execution.
425    ///
426    /// # Effects
427    ///
428    /// Resets the matching region to idle and fails all compaction waiters and
429    /// dependent DDL requests with the supplied error.
430    ///
431    /// # Constraints
432    ///
433    /// A stale execution failure is ignored so it cannot tear down replacement
434    /// state.
435    pub(crate) fn on_execution_failed(
436        &mut self,
437        region_id: RegionId,
438        execution: &CompactionExecution,
439        err: Arc<Error>,
440    ) {
441        if !self.is_current_execution(region_id, execution) {
442            return;
443        }
444        self.on_compaction_failed(region_id, err);
445    }
446
447    /// Removes compaction state because the region was dropped.
448    ///
449    /// # Effects
450    ///
451    /// Fails all compaction and DDL waiters owned by the status.
452    ///
453    /// # Constraints
454    ///
455    /// The owning worker must invoke this as part of serialized region teardown.
456    pub(crate) fn on_region_dropped(&mut self, region_id: RegionId) {
457        self.remove_region(
458            region_id,
459            Arc::new(RegionDroppedSnafu { region_id }.build()),
460        );
461    }
462
463    /// Removes compaction state because the region was closed.
464    ///
465    /// # Effects
466    ///
467    /// Fails all compaction and DDL waiters owned by the status.
468    ///
469    /// # Constraints
470    ///
471    /// The owning worker must invoke this as part of serialized region teardown.
472    pub(crate) fn on_region_closed(&mut self, region_id: RegionId) {
473        self.remove_region(region_id, Arc::new(RegionClosedSnafu { region_id }.build()));
474    }
475
476    /// Resets the cycle after truncate, retaining registration and outstanding DDL replies.
477    ///
478    /// # Effects
479    ///
480    /// Fails all compaction and DDL waiters owned by the status.
481    ///
482    /// # Constraints
483    ///
484    /// The owning worker must invoke this after truncate completes.
485    pub(crate) fn on_region_truncated(&mut self, region_id: RegionId) {
486        self.fail_compaction(
487            region_id,
488            Arc::new(RegionTruncatedSnafu { region_id }.build()),
489        );
490    }
491
492    /// Cancels a running compaction and queues its dependent DDL atomically.
493    ///
494    /// # Effects
495    ///
496    /// Requests cancellation when the active phase can still stop, then queues
497    /// the DDL. The queued DDL forms a scheduling fence for subsequent
498    /// compaction triggers. If no compaction is running, returns the sender and
499    /// typed request unchanged.
500    ///
501    /// # Constraints
502    ///
503    /// Production callers use this only for [`DdlRequest::Truncate`] and
504    /// [`DdlRequest::EnterStaging`]. `Ok(())` means the caller must wait for a
505    /// terminal callback to receive and execute the queued DDL; `Err` means the
506    /// caller must execute the returned request directly.
507    pub(crate) fn try_cancel_and_add_ddl<T>(
508        &mut self,
509        region_id: RegionId,
510        sender: OptionOutputTx,
511        request: T,
512        into_ddl_request: impl FnOnce(T) -> DdlRequest,
513    ) -> std::result::Result<(), (OptionOutputTx, T)> {
514        let Some(status) = self.region_status.get_mut(&region_id) else {
515            return Err((sender, request));
516        };
517        if !status.is_compacting() {
518            return Err((sender, request));
519        }
520        status.request_cancel();
521
522        let request = SenderDdlRequest {
523            region_id,
524            sender,
525            request: into_ddl_request(request),
526        };
527        debug!(
528            "Added pending DDL request for region: {}, ddl: {:?}",
529            request.region_id, request.request
530        );
531        status.pending_ddl_requests.push(request);
532        Ok(())
533    }
534
535    /// Pending and handed-off DDLs retain their turn until the final reply.
536    pub(crate) fn blocks_region_edits(&self, region_id: RegionId) -> bool {
537        self.region_status
538            .get(&region_id)
539            .is_some_and(|status| status.has_ddl())
540    }
541
542    /// Whether a staging request is still waiting for compaction cancellation.
543    pub(crate) fn has_pending_enter_staging(&self, region_id: RegionId) -> bool {
544        self.region_status.get(&region_id).is_some_and(|status| {
545            status
546                .pending_ddl_requests
547                .iter()
548                .any(|ddl| matches!(ddl.request, DdlRequest::EnterStaging(_)))
549        })
550    }
551}
552
553// Internal state-machine helpers.
554impl CompactionScheduler {
555    /// Returns the current plan id and advances the counter.
556    ///
557    /// Takes the counter instead of `&mut self` so callers can bump it while
558    /// holding a mutable borrow of a region status.
559    fn next_plan_id(counter: &mut u64) -> u64 {
560        let plan_id = *counter;
561        *counter = counter.wrapping_add(1);
562        plan_id
563    }
564
565    #[allow(clippy::too_many_arguments)]
566    fn schedule_compaction(
567        &mut self,
568        trigger: CompactionTrigger,
569        compact_options: compact_request::Options,
570        version_control: &VersionControlRef,
571        access_layer: &AccessLayerRef,
572        waiter: OptionOutputTx,
573        manifest_ctx: &ManifestContextRef,
574        schema_metadata_manager: SchemaMetadataManagerRef,
575        max_parallelism: usize,
576        time_range: Option<TimestampRange>,
577    ) -> Result<bool> {
578        if self.disable_compaction {
579            if matches!(trigger, CompactionTrigger::Manual) {
580                waiter.send(
581                    UnsupportedOperationSnafu {
582                        err_msg: format!("SST compaction is disabled by {DISABLE_COMPACTION_ENV}"),
583                    }
584                    .fail(),
585                );
586            }
587            return Ok(false);
588        }
589        let region_id = version_control.region_id();
590        let status = self.region_status.entry(region_id).or_insert_with(|| {
591            CompactionStatus::new(region_id, version_control.clone(), access_layer.clone())
592        });
593        if status.is_paused() {
594            waiter.send(CompactionCancelledSnafu.fail());
595            return Ok(false);
596        }
597        if status.has_ddl() {
598            info!(
599                "Region {} has pending DDL requests, ignoring compaction: queued={}, executing={}",
600                region_id,
601                status.pending_ddl_requests.len(),
602                status.executing_ddl.is_some(),
603            );
604            waiter.send(CompactionCancelledSnafu.fail());
605            return Ok(false);
606        }
607        let current_state = manifest_ctx.current_state();
608        if current_state.in_staging_session() {
609            info!(
610                "Skipping compaction for region {} in staging mode, options: {:?}",
611                region_id, compact_options
612            );
613            waiter.send(Ok(0));
614            return Ok(false);
615        }
616        if manifest_ctx.awaits_leader_lease() {
617            info!(
618                "Skipping compaction for region {} that awaits its Leader lease, options: {:?}",
619                region_id, compact_options
620            );
621            waiter.send(Ok(0));
622            return Ok(false);
623        }
624        if status.has_pending_tails() {
625            info!(
626                "Skipping compaction for region {} with pending WAL tails, options: {:?}",
627                region_id, compact_options
628            );
629            waiter.send(Ok(0));
630            return Ok(false);
631        }
632
633        if status.is_compacting() {
634            match trigger {
635                CompactionTrigger::Automatic => status.mark_automatic_trigger(),
636                CompactionTrigger::Manual if status.is_manual_compaction() => {
637                    waiter.send(ManualCompactionAlreadyRunningSnafu { region_id }.fail());
638                    info!(
639                        "Region {} already has a manually triggered compaction running",
640                        region_id
641                    );
642                }
643                CompactionTrigger::Manual => {
644                    status.set_pending_request(PendingCompaction {
645                        options: compact_options,
646                        waiter,
647                        max_parallelism,
648                        time_range,
649                    });
650                    info!(
651                        "Region {} is running an automatic compaction; manual compaction will be re-scheduled",
652                        region_id
653                    );
654                }
655            }
656            return Ok(false);
657        }
658
659        // Publish the picking phase before dispatching background planning.
660        let plan_id = Self::next_plan_id(&mut self.next_plan_id);
661        status.start_picking_with_trigger(plan_id, trigger);
662        let pick_history = (trigger == CompactionTrigger::Automatic
663            && matches!(compact_options, compact_request::Options::Regular(_)))
664        .then(|| status.pick_history.clone());
665        let request = status.new_compaction_request(
666            self.request_sender.clone(),
667            self.engine_config.clone(),
668            self.cache_manager.clone(),
669            manifest_ctx,
670            self.listener.clone(),
671            schema_metadata_manager,
672            max_parallelism,
673            pick_history,
674        );
675        status.merge_waiter(waiter);
676        self.dispatch_compaction_planning(plan_id, request, compact_options, time_range, trigger);
677        self.listener.on_compaction_scheduled(region_id);
678        Ok(true)
679    }
680
681    // Handle pending manual compaction request for the region.
682    //
683    // Returns true if should early return, false otherwise.
684    fn handle_pending_compaction_request(
685        &mut self,
686        region_id: RegionId,
687        manifest_ctx: &ManifestContextRef,
688        schema_metadata_manager: SchemaMetadataManagerRef,
689    ) -> bool {
690        let Some(status) = self.region_status.get_mut(&region_id) else {
691            return true;
692        };
693
694        // If there is a pending manual compaction request, schedule it.
695        // and defer returning the pending DDL requests to the caller.
696        let Some(pending_request) = std::mem::take(&mut status.pending_request) else {
697            return false;
698        };
699        let awaits_leader_lease = manifest_ctx.awaits_leader_lease();
700        if awaits_leader_lease {
701            info!(
702                "Region {region_id} awaits its Leader lease, answering its queued compaction without compacting"
703            );
704        }
705        if status.has_pending_tails() || awaits_leader_lease {
706            status.pending_task_state = None;
707            status.publish_state();
708            pending_request.waiter.send(Ok(0));
709            return false;
710        }
711
712        let PendingCompaction {
713            options,
714            waiter,
715            max_parallelism,
716            time_range,
717        } = pending_request;
718
719        let request = status.new_compaction_request(
720            self.request_sender.clone(),
721            self.engine_config.clone(),
722            self.cache_manager.clone(),
723            manifest_ctx,
724            self.listener.clone(),
725            schema_metadata_manager,
726            max_parallelism,
727            None,
728        );
729        status.merge_waiter(waiter);
730        // Bump the counter through a disjoint field borrow so the `status`
731        // borrow stays alive; nothing could have removed the status since it
732        // was fetched above.
733        let plan_id = Self::next_plan_id(&mut self.next_plan_id);
734        status.start_picking_with_trigger(plan_id, CompactionTrigger::Manual);
735        status.active.task_state = status.pending_task_state.take();
736        self.dispatch_compaction_planning(
737            plan_id,
738            request,
739            options,
740            time_range,
741            CompactionTrigger::Manual,
742        );
743        debug!(
744            "Successfully scheduled manual compaction planning for region id: {}",
745            region_id
746        );
747        true
748    }
749
750    /// Notifies the scheduler that the compaction job is finished successfully.
751    async fn on_compaction_finished(
752        &mut self,
753        region_id: RegionId,
754        manifest_ctx: &ManifestContextRef,
755        schema_metadata_manager: SchemaMetadataManagerRef,
756        made_progress: bool,
757    ) -> CompactionTransition {
758        if let Some(ddls) = self.take_ready_ddls(region_id) {
759            return CompactionTransition::DdlReady(ddls);
760        }
761
762        if self.handle_pending_compaction_request(
763            region_id,
764            manifest_ctx,
765            schema_metadata_manager.clone(),
766        ) {
767            return CompactionTransition::NoAction;
768        }
769
770        let Some(status) = self.region_status.get_mut(&region_id) else {
771            return CompactionTransition::NoAction;
772        };
773        for waiter in status.take_waiters() {
774            waiter.send(Ok(0));
775        }
776
777        // Keep draining when the cycle latched an automatic trigger, or when the
778        // execution produced output or reduced the file count. An empty edit stops
779        // here; the next flush trigger resumes.
780        let should_continue = status.active.reset_automatic_followup() || made_progress;
781        if should_continue
782            && self.schedule_automatic_followup(region_id, manifest_ctx, schema_metadata_manager)
783        {
784            return CompactionTransition::AutomaticFollowupScheduled;
785        }
786        if let Some(status) = self.region_status.get_mut(&region_id) {
787            status.become_idle();
788        }
789        CompactionTransition::NoAction
790    }
791
792    fn schedule_automatic_followup(
793        &mut self,
794        region_id: RegionId,
795        manifest_ctx: &ManifestContextRef,
796        schema_metadata_manager: SchemaMetadataManagerRef,
797    ) -> bool {
798        if self.disable_compaction {
799            return false;
800        }
801        let Some(status) = self.region_status.get_mut(&region_id) else {
802            return false;
803        };
804        let awaits_leader_lease = manifest_ctx.awaits_leader_lease();
805        if awaits_leader_lease {
806            info!("Region {region_id} awaits its Leader lease, starting no follow-up compaction");
807        }
808        if status.is_paused() || status.has_pending_tails() || awaits_leader_lease {
809            return false;
810        }
811        // An external automatic trigger requires one unrestricted follow-up pick.
812        let request = status.new_compaction_request(
813            self.request_sender.clone(),
814            self.engine_config.clone(),
815            self.cache_manager.clone(),
816            manifest_ctx,
817            self.listener.clone(),
818            schema_metadata_manager,
819            self.engine_config.max_background_compactions,
820            Some(status.pick_history.clone()),
821        );
822        // Bump the counter through a disjoint field borrow so the `status`
823        // borrow stays alive; nothing could have removed the status since it
824        // was fetched above.
825        let plan_id = Self::next_plan_id(&mut self.next_plan_id);
826        status.start_regular_picking(plan_id);
827        self.dispatch_compaction_planning(
828            plan_id,
829            request,
830            compact_request::Options::Regular(Default::default()),
831            None,
832            CompactionTrigger::Automatic,
833        );
834        debug!(
835            "Successfully scheduled next compaction planning for region id: {}",
836            region_id
837        );
838        true
839    }
840
841    /// Notifies the scheduler that the compaction job is cancelled cooperatively.
842    #[cfg(test)]
843    async fn on_compaction_cancelled(&mut self, region_id: RegionId) -> Vec<SenderDdlRequest> {
844        self.finish_compaction_on_cancel(region_id)
845    }
846
847    /// Notifies the scheduler that the compaction job is failed.
848    fn on_compaction_failed(&mut self, region_id: RegionId, err: Arc<Error>) {
849        error!(err; "Region {} failed to compact, cancel all pending tasks", region_id);
850        self.fail_compaction(region_id, err);
851    }
852
853    #[cfg(test)]
854    fn add_ddl_request_to_pending(&mut self, request: SenderDdlRequest) {
855        self.region_status
856            .get_mut(&request.region_id)
857            .unwrap()
858            .pending_ddl_requests
859            .push(request);
860    }
861
862    #[cfg(test)]
863    fn has_pending_ddls(&self, region_id: RegionId) -> bool {
864        let has_pending = self
865            .region_status
866            .get(&region_id)
867            .map(|status| !status.pending_ddl_requests.is_empty())
868            .unwrap_or(false);
869        debug!(
870            "Checked pending DDL requests for region: {}, has_pending: {}",
871            region_id, has_pending
872        );
873        has_pending
874    }
875
876    #[cfg(test)]
877    fn request_cancel(&mut self, region_id: RegionId) -> RequestCancelResult {
878        self.region_status
879            .get_mut(&region_id)
880            .unwrap()
881            .request_cancel()
882    }
883
884    /// Unregisters a closed or dropped region and fails its queued requests.
885    fn remove_region(&mut self, region_id: RegionId, err: Arc<Error>) {
886        if let Some(mut status) = self.region_status.remove(&region_id) {
887            status.on_failure(err);
888        }
889        self.coordinator.forget_region(region_id);
890    }
891
892    /// Fails a cycle without discarding the loaded region's registration.
893    fn fail_compaction(&mut self, region_id: RegionId, err: Arc<Error>) {
894        if let Some(status) = self.region_status.get_mut(&region_id) {
895            status.on_failure(err);
896        }
897    }
898
899    /// Completes task-specific cancellation without discarding another pending request.
900    fn finish_cancelled_compaction(
901        &mut self,
902        region_id: RegionId,
903        manifest: &ManifestContextRef,
904        schemas: SchemaMetadataManagerRef,
905    ) -> CompactionTransition {
906        if let Some(status) = self.region_status.get_mut(&region_id)
907            && status.finish_task_cancellation()
908        {
909            self.handle_pending_compaction_request(region_id, manifest, schemas);
910            return CompactionTransition::NoAction;
911        }
912        CompactionTransition::from_pending_ddls(self.finish_compaction_on_cancel(region_id))
913    }
914
915    /// Returns the cycle to idle and records any DDL handoff in the same resident entry.
916    fn finish_compaction_on_cancel(&mut self, region_id: RegionId) -> Vec<SenderDdlRequest> {
917        let Some(status) = self.region_status.get_mut(&region_id) else {
918            return Vec::new();
919        };
920
921        let ddls = status.on_cancel();
922        self.fence_ddl_replies(region_id, ddls)
923    }
924
925    /// Hands off pending DDLs after compaction ends and cancels remaining compaction waiters.
926    fn take_ready_ddls(&mut self, region_id: RegionId) -> Option<Vec<SenderDdlRequest>> {
927        if self
928            .region_status
929            .get(&region_id)?
930            .pending_ddl_requests
931            .is_empty()
932        {
933            return None;
934        }
935        Some(self.finish_compaction_on_cancel(region_id))
936    }
937
938    /// Hands off a drained batch of DDLs and fences new compaction until every reply lands.
939    ///
940    /// Installs the fence, intercepts each DDL's reply, and returns the same batch so the caller
941    /// can execute it. The real result of each DDL is still forwarded to its original sender.
942    ///
943    /// # Constraints
944    /// Must only be called from a compaction terminal transition, and only by the worker that owns
945    /// `region_id`.
946    fn fence_ddl_replies(
947        &mut self,
948        region_id: RegionId,
949        mut ddls: Vec<SenderDdlRequest>,
950    ) -> Vec<SenderDdlRequest> {
951        if ddls.is_empty() {
952            return ddls;
953        }
954        let generation = Self::next_plan_id(&mut self.next_plan_id);
955        if let Some(status) = self.region_status.get_mut(&region_id) {
956            // Set region status to "executing DDLs" so future compaction won't be scheduled.
957            status.executing_ddl = Some(DdlExecution::new(generation, ddls.len()));
958        }
959
960        for (request_index, ddl) in ddls.iter_mut().enumerate() {
961            // Swap the DDL's real reply sender for a temporary one so we can observe it. The
962            // spawned task forwards the observed result to the original caller and, in between,
963            // notifies the scheduler that this slot of the batch has completed.
964            let (tx, rx) = tokio::sync::oneshot::channel();
965            let reply = std::mem::replace(&mut ddl.sender, tx.into());
966            let sender = self.request_sender.clone();
967            common_runtime::spawn_global(async move {
968                use snafu::ResultExt;
969                let result = rx
970                    .await
971                    .context(crate::error::RecvSnafu)
972                    .and_then(|result| result);
973                // Route the completion through the worker channel so `on_ddl_complete` sees it
974                // serialized with other region state transitions.
975                //
976                // At most one batch can be outstanding per region: [`CompactionStatus::has_ddl`] blocks
977                // compaction admission while `executing_ddl` is set, so `fence_ddl_replies` cannot run again
978                // for the same region before the current batch drains. A single `(generation, request_index)`
979                // pair therefore identifies every reply. `generation` comes from the scheduler-wide counter,
980                // which outlives region statuses, so a late reply from a previous incarnation cannot clear the
981                // current fence. Inside the batch `request_index` makes completion idempotent: only the last
982                // distinct reply releases the fence.
983                let _ = sender
984                    .send(WorkerRequestWithTime::new(
985                        crate::request::WorkerRequest::Background {
986                            region_id,
987                            notify: crate::request::BackgroundNotify::CompactionDdlComplete {
988                                generation,
989                                request_index,
990                            },
991                        },
992                    ))
993                    .await;
994                reply.send(result);
995            });
996        }
997        ddls
998    }
999
1000    /// Releases the DDL fence after its last reply, ignoring replies from an older generation.
1001    pub(crate) fn on_ddl_complete(
1002        &mut self,
1003        region_id: RegionId,
1004        generation: u64,
1005        request_index: usize,
1006    ) {
1007        let Some(status) = self.region_status.get_mut(&region_id) else {
1008            return;
1009        };
1010        // `complete` returns false for a stale generation or a duplicate `request_index`, so a late or
1011        // repeated notify cannot end the batch early. It only clears the fence on the last distinct
1012        // reply, which is what lets `has_ddl` unblock compaction admission again.
1013        if let Some(ddl) = &mut status.executing_ddl
1014            && ddl.complete(generation, request_index)
1015        {
1016            status.executing_ddl = None;
1017        }
1018    }
1019}
1020
1021impl Drop for CompactionScheduler {
1022    fn drop(&mut self) {
1023        for (region_id, mut status) in self.region_status.drain() {
1024            // We are shutting down so notify all pending tasks.
1025            status.on_failure(Arc::new(RegionClosedSnafu { region_id }.build()));
1026            self.coordinator.forget_region(region_id);
1027        }
1028    }
1029}
1030
1031impl CompactionScheduler {
1032    /// Reads the same published task state as engine queries.
1033    #[cfg(test)]
1034    pub(crate) fn inspect_tasks(
1035        &self,
1036        filters: &MetadataFilter,
1037        node_id: Option<u64>,
1038    ) -> Vec<CompactionTaskEntry> {
1039        let mut entries = Vec::new();
1040        for (region_id, status) in &self.region_status {
1041            if !filters.matches(|name| match name {
1042                compaction_task::REGION_ID => Some(ScalarValue::UInt64(Some(region_id.as_u64()))),
1043                compaction_task::TABLE_ID => Some(ScalarValue::UInt32(Some(region_id.table_id()))),
1044                compaction_task::NODE_ID => Some(ScalarValue::UInt64(node_id)),
1045                _ => None,
1046            }) {
1047                continue;
1048            }
1049            let (active, pending) = CompactionState::current(&status.shared_state);
1050            for task in active.into_iter().chain(pending) {
1051                let entry = task.snapshot(node_id);
1052                if entry.matches(filters) {
1053                    entries.push(entry);
1054                }
1055            }
1056        }
1057        entries
1058    }
1059}
1060
1061#[cfg(test)]
1062#[path = "scheduler_test.rs"]
1063mod tests;