Skip to main content

mito2/compaction/scheduler/
state.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::collections::{HashMap, HashSet, hash_map};
16use std::sync::{Arc, RwLock, Weak};
17use std::time::Instant;
18
19use api::v1::region::compact_request;
20use common_meta::key::SchemaMetadataManagerRef;
21use common_telemetry::debug;
22use common_time::range::TimestampRange;
23use snafu::ResultExt;
24use store_api::compaction_task::{self, CompactionTaskEntry};
25use store_api::storage::RegionId;
26use tokio::sync::mpsc::Sender;
27use tokio::sync::oneshot;
28
29use crate::access_layer::AccessLayerRef;
30use crate::cache::CacheManagerRef;
31use crate::compaction::CompactionOutput;
32use crate::compaction::compactor::{CompactionRegion, CompactionVersion};
33use crate::compaction::picker::PickerOutput;
34use crate::compaction::scheduler::CancelCompactionResult;
35use crate::compaction::scheduler::history::PickHistory;
36use crate::compaction::scheduler::local::{LocalCompaction, LocalCompactionState};
37use crate::compaction::scheduler::planning::CompactionRequest;
38use crate::config::MitoConfig;
39use crate::error::{
40    CompactRegionSnafu, CompactionCancelledSnafu, Error, ManualCompactionOverrideSnafu, Result,
41};
42use crate::region::ManifestContextRef;
43use crate::region::version::VersionControlRef;
44use crate::request::{
45    OptionOutputTx, OutputTx, PauseCompactionResponse, SenderDdlRequest, WorkerRequestWithTime,
46};
47#[cfg(test)]
48use crate::schedule::CancellableTaskState;
49use crate::schedule::RequestCancelResult;
50use crate::sst::file::{FileHandle, RegionFileId};
51use crate::worker::WorkerListener;
52
53/// Identifies an accepted compaction attempt and keeps its SST reservations alive.
54/// The plan id fences terminal notifications from superseded attempts.
55#[derive(Debug, Clone)]
56pub(crate) struct CompactionExecution {
57    plan_id: u64,
58    _files: CompactingFiles,
59}
60
61impl CompactionExecution {
62    /// Returns the attempt ID used to reject stale execution notifications.
63    pub(crate) fn plan_id(&self) -> u64 {
64        self.plan_id
65    }
66    pub(super) fn new(plan_id: u64, files: CompactingFiles) -> Self {
67        Self {
68            plan_id,
69            _files: files,
70        }
71    }
72
73    pub(crate) fn matches(&self, other: &Self) -> bool {
74        self.plan_id == other.plan_id
75    }
76
77    #[cfg(test)]
78    pub(crate) fn for_test(plan_id: u64) -> Self {
79        Self::new(plan_id, CompactingFiles::empty())
80    }
81}
82
83#[derive(Debug)]
84pub(crate) enum CompactionPhase {
85    /// The region is registered but has no compaction in progress.
86    Idle,
87    Picking {
88        plan_id: u64,
89        cancelled: bool,
90    },
91    #[cfg(test)]
92    Local {
93        state: CancellableTaskState,
94        execution: CompactionExecution,
95    },
96    Remote {
97        execution: CompactionExecution,
98    },
99    Units(LocalCompaction),
100}
101
102/// Describes how the current compaction cycle was triggered.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub(crate) enum CompactionTrigger {
105    Automatic,
106    Manual,
107}
108
109#[derive(Debug)]
110pub(super) struct ActiveCompaction {
111    /// Query metadata owned by this live cycle, dropped when it becomes idle.
112    pub(crate) task_state: Option<CompactionTaskState>,
113    pub(super) phase: CompactionPhase,
114    trigger: CompactionTrigger,
115    /// Waiters satisfied by the current planning or execution cycle. Picking waiters move into
116    /// the submitted task; regular triggers coalesced during execution accumulate here.
117    pub(super) waiters: Vec<OutputTx>,
118    /// An automatic trigger arrived during this cycle and requires one unrestricted regular
119    /// picking cycle after the current cycle finishes. Recorded in every phase so an external
120    /// trigger always resets the continuation scope, even during local/remote execution.
121    pub(super) automatic_followup_required: bool,
122    /// Records an accepted explicit cancellation of this task.
123    task_cancel_requested: bool,
124}
125
126impl ActiveCompaction {
127    /// Creates an empty cycle while retaining the region's scheduling record.
128    fn idle() -> Self {
129        Self {
130            task_state: None,
131            phase: CompactionPhase::Idle,
132            trigger: CompactionTrigger::Automatic,
133            waiters: Vec::new(),
134            automatic_followup_required: false,
135            task_cancel_requested: false,
136        }
137    }
138
139    #[cfg(test)]
140    pub(super) fn picking(
141        plan_id: u64,
142        waiters: Vec<OutputTx>,
143        trigger: CompactionTrigger,
144    ) -> Self {
145        Self {
146            task_state: None,
147            phase: CompactionPhase::Picking {
148                plan_id,
149                cancelled: false,
150            },
151            trigger,
152            waiters,
153            automatic_followup_required: false,
154            task_cancel_requested: false,
155        }
156    }
157
158    pub(super) fn start_picking(&mut self, plan_id: u64, trigger: CompactionTrigger) {
159        self.task_state = None;
160        self.task_cancel_requested = false;
161        self.phase = CompactionPhase::Picking {
162            plan_id,
163            cancelled: false,
164        };
165        self.trigger = trigger;
166    }
167
168    pub(super) fn start_regular_picking(&mut self, plan_id: u64) {
169        self.start_picking(plan_id, CompactionTrigger::Automatic);
170    }
171
172    /// Marks an automatic trigger. The trigger is coalesced into a single unrestricted
173    /// follow-up cycle regardless of the current phase.
174    pub(super) fn mark_automatic_trigger(&mut self) {
175        self.automatic_followup_required = true;
176    }
177
178    /// Resets whether an unrestricted follow-up cycle is required and
179    /// return the previous value.
180    pub(super) fn reset_automatic_followup(&mut self) -> bool {
181        std::mem::take(&mut self.automatic_followup_required)
182    }
183
184    pub(super) fn is_manual(&self) -> bool {
185        self.trigger == CompactionTrigger::Manual
186    }
187
188    pub(super) fn is_picking(&self, expected_plan_id: u64) -> bool {
189        matches!(
190            self.phase,
191            CompactionPhase::Picking { plan_id, .. } if plan_id == expected_plan_id
192        )
193    }
194
195    pub(super) fn accept_plan(&self, expected_plan_id: u64) -> bool {
196        matches!(
197            self.phase,
198            CompactionPhase::Picking {
199                plan_id,
200                cancelled: false,
201            } if plan_id == expected_plan_id
202        )
203    }
204
205    pub(super) fn matches_execution(&self, execution: &CompactionExecution) -> bool {
206        match &self.phase {
207            CompactionPhase::Idle | CompactionPhase::Picking { .. } => None,
208            #[cfg(test)]
209            CompactionPhase::Local { execution, .. } => Some(execution),
210            CompactionPhase::Units(_) => None,
211            CompactionPhase::Remote { execution } => Some(execution),
212        }
213        .is_some_and(|current| current.matches(execution))
214    }
215
216    pub(super) fn request_cancel(&mut self) -> RequestCancelResult {
217        match &mut self.phase {
218            CompactionPhase::Idle => RequestCancelResult::TooLateToCancel,
219            CompactionPhase::Picking { cancelled, .. } => {
220                if *cancelled {
221                    RequestCancelResult::AlreadyCancelling
222                } else {
223                    *cancelled = true;
224                    RequestCancelResult::CancelIssued
225                }
226            }
227            #[cfg(test)]
228            CompactionPhase::Local { state, .. } => state.request_cancel(),
229            CompactionPhase::Units(units) => units.request_cancel(),
230            CompactionPhase::Remote { .. } => RequestCancelResult::TooLateToCancel,
231        }
232    }
233
234    pub(super) fn merge_waiter(&mut self, mut waiter: OptionOutputTx) {
235        if let Some(waiter) = waiter.take_inner() {
236            self.waiters.push(waiter);
237        }
238    }
239    /// Captures worker-owned metadata while retaining live background task handles.
240    fn current_task_state(&self) -> Option<CompactionTaskState> {
241        let mut task = self.task_state.clone()?;
242        let entry = &mut task.entry;
243        match &self.phase {
244            CompactionPhase::Idle => return None,
245            CompactionPhase::Picking { cancelled, .. } => {
246                entry.state = if *cancelled {
247                    compaction_task::STATE_CANCELLING
248                } else {
249                    compaction_task::STATE_RUNNING
250                }
251                .into();
252                entry.phase = compaction_task::PHASE_PLANNING.into();
253            }
254            CompactionPhase::Remote { .. } => {
255                entry.state = compaction_task::STATE_RUNNING.into();
256                entry.phase = compaction_task::PHASE_REMOTE.into();
257            }
258            CompactionPhase::Units(local) => task.local_state = Some(local.current_state()),
259            #[cfg(test)]
260            CompactionPhase::Local { .. } => {
261                entry.state = compaction_task::STATE_RUNNING.into();
262                entry.phase = compaction_task::PHASE_EXECUTING.into();
263            }
264        }
265        Some(task)
266    }
267}
268
269/// Owns atomic reservations for every SST selected by a compaction plan.
270#[derive(Debug, Clone)]
271pub(crate) struct CompactingFiles {
272    files: HashMap<RegionFileId, Arc<CompactingFile>>,
273}
274
275/// Keeps an SST reserved until the last shared lease is dropped.
276#[derive(Debug)]
277struct CompactingFile {
278    file: FileHandle,
279}
280
281impl CompactingFiles {
282    /// Reserves both merge inputs and expired files from an accepted picker result.
283    pub(super) fn try_new(output: &PickerOutput) -> Option<Self> {
284        Self::try_reserve(
285            output
286                .outputs
287                .iter()
288                .flat_map(|o| &o.inputs)
289                .chain(&output.expired_ssts),
290        )
291    }
292
293    /// Reserves distinct inputs, releasing acquired leases if any input is already busy.
294    fn try_reserve<'a>(selected_files: impl IntoIterator<Item = &'a FileHandle>) -> Option<Self> {
295        let mut files = HashMap::new();
296
297        for file in selected_files {
298            let hash_map::Entry::Vacant(entry) = files.entry(file.file_id()) else {
299                continue;
300            };
301            if !file.try_set_compacting() {
302                return None;
303            }
304            entry.insert(Arc::new(CompactingFile { file: file.clone() }));
305        }
306
307        Some(Self { files })
308    }
309
310    /// Clones the shared leases of a dependency group's inputs without briefly releasing any input.
311    /// `self` retains its leases, so an input is released only after every owner, including
312    /// the original collection, drops its lease.
313    /// A delayed remote notifier may retain the same leases across local fallback.
314    /// Indexing keeps splitting proportional to the group's input count.
315    pub(crate) fn for_inputs(&self, inputs: &[FileHandle]) -> Self {
316        Self {
317            files: inputs
318                .iter()
319                .filter_map(|file| {
320                    let id = file.file_id();
321                    self.files.get(&id).map(|lease| (id, lease.clone()))
322                })
323                .collect(),
324        }
325    }
326
327    #[cfg(test)]
328    pub(super) fn empty() -> Self {
329        Self {
330            files: HashMap::new(),
331        }
332    }
333}
334
335impl Drop for CompactingFile {
336    fn drop(&mut self) {
337        self.file.set_compacting(false);
338    }
339}
340
341/// A handed-off DDL batch, retained until each reply has been observed once.
342#[derive(Debug)]
343pub(crate) struct DdlExecution {
344    generation: u64,
345    pending_replies: HashSet<usize>,
346}
347
348impl DdlExecution {
349    /// Tracks a batch's individual replies so duplicate notifications are harmless.
350    pub(crate) fn new(generation: u64, count: usize) -> Self {
351        Self {
352            generation,
353            pending_replies: (0..count).collect(),
354        }
355    }
356
357    /// Returns true only for the last distinct reply of this batch.
358    pub(crate) fn complete(&mut self, generation: u64, request_index: usize) -> bool {
359        self.generation == generation
360            && self.pending_replies.remove(&request_index)
361            && self.pending_replies.is_empty()
362    }
363}
364
365/// Scheduling state retained for the lifetime of a loaded region.
366pub(super) struct CompactionStatus {
367    /// Current cycles shared with queries without entering the region worker.
368    pub(crate) shared_state: CompactionStateRef,
369    /// Live guards and callers waiting for in-flight work to finish.
370    pause: Weak<()>,
371    pause_waiters: Vec<oneshot::Sender<Result<()>>>,
372    /// Resident automatic-pick history, retained across batches until region unload.
373    pub(crate) pick_history: PickHistory,
374    /// Id of the region.
375    pub(super) region_id: RegionId,
376    /// Version control of the region.
377    pub(super) version_control: VersionControlRef,
378    /// Access layer of the region.
379    pub(super) access_layer: AccessLayerRef,
380    /// Current compaction lifecycle.
381    pub(super) active: ActiveCompaction,
382    /// A manual compaction waiting for the current automatic compaction to finish.
383    ///
384    /// A manual request is rejected if the current compaction is also manual. Automatic requests
385    /// are merged into the active compaction instead of using this slot.
386    pub(super) pending_request: Option<PendingCompaction>,
387    /// Metadata for the pending manual request, moved to the active cycle on promotion.
388    pub(crate) pending_task_state: Option<CompactionTaskState>,
389    /// Pending DDL requests that should run when compaction is done.
390    ///
391    /// Although [`SenderDdlRequest`] can wrap any DDL variant, production code only queues
392    /// [`crate::request::DdlRequest::Truncate`] and [`crate::request::DdlRequest::EnterStaging`] here. Both must serialize with
393    /// compaction so they observe the version after compaction terminates.
394    pub(super) pending_ddl_requests: Vec<SenderDdlRequest>,
395    /// DDLs already handed to the worker keep new compaction paused until their replies.
396    pub(crate) executing_ddl: Option<DdlExecution>,
397}
398
399/// Prevents new compactions on one loaded region until its last guard is dropped.
400#[derive(Debug)]
401#[must_use]
402pub struct CompactionGuard {
403    _token: Arc<()>,
404}
405
406impl CompactionStatus {
407    pub(super) fn is_paused(&self) -> bool {
408        self.pause.strong_count() != 0
409    }
410
411    pub(super) fn pause(&mut self, sender: oneshot::Sender<Result<PauseCompactionResponse>>) {
412        let token = self.pause.upgrade().unwrap_or_else(|| {
413            let token = Arc::new(());
414            self.pause = Arc::downgrade(&token);
415            token
416        });
417        let guard = CompactionGuard { _token: token };
418        if !self.is_compacting() {
419            let _ = sender.send(Ok(PauseCompactionResponse { guard, idle: None }));
420            return;
421        }
422
423        let (notify, idle) = oneshot::channel();
424        if sender
425            .send(Ok(PauseCompactionResponse {
426                guard,
427                idle: Some(idle),
428            }))
429            .is_err()
430        {
431            return;
432        }
433
434        self.pause_waiters.retain(|waiter| !waiter.is_closed());
435        self.pause_waiters.push(notify);
436        self.cancel_pending();
437        self.request_cancel();
438    }
439
440    fn cancel_pending(&mut self) {
441        self.pending_task_state = None;
442        if let Some(pending) = self.pending_request.take() {
443            pending.waiter.send(CompactionCancelledSnafu.fail());
444        }
445    }
446
447    fn notify_idle(&mut self) {
448        for sender in self.pause_waiters.drain(..) {
449            let _ = sender.send(Ok(()));
450        }
451    }
452
453    /// Cancels an exact identity, checking pending work before the active cycle.
454    pub(crate) fn cancel_task(&mut self, task_id: &str) -> CancelCompactionResult {
455        if self
456            .pending_task_state
457            .as_ref()
458            .is_some_and(|state| state.entry.task_id.as_ref() == task_id)
459        {
460            self.cancel_pending();
461            self.publish_state();
462            return CancelCompactionResult::CancelIssued;
463        }
464        if !self
465            .active
466            .task_state
467            .as_ref()
468            .is_some_and(|state| state.entry.task_id.as_ref() == task_id)
469        {
470            return CancelCompactionResult::NotFound;
471        }
472        if matches!(self.active.phase, CompactionPhase::Remote { .. }) {
473            return CancelCompactionResult::Unsupported;
474        }
475        if self.active.task_cancel_requested {
476            return CancelCompactionResult::AlreadyCancelling;
477        }
478        let result = self.request_cancel();
479        if result != RequestCancelResult::TooLateToCancel {
480            self.active.task_cancel_requested = true;
481        }
482        result.into()
483    }
484
485    /// Publishes both slots together without holding the lock while building their metadata.
486    pub(crate) fn publish_state(&self) {
487        let active = self.active.current_task_state().map(Arc::new);
488        let pending = self
489            .pending_request
490            .as_ref()
491            .and(self.pending_task_state.as_ref())
492            .cloned()
493            .map(Arc::new);
494        let previous = {
495            let mut shared = self.shared_state.write().unwrap();
496            std::mem::replace(&mut *shared, CompactionState { active, pending })
497        };
498        drop(previous);
499    }
500
501    /// Registers an idle region without starting a compaction cycle.
502    pub(super) fn new(
503        region_id: RegionId,
504        version_control: VersionControlRef,
505        access_layer: AccessLayerRef,
506    ) -> CompactionStatus {
507        CompactionStatus {
508            shared_state: Arc::new(RwLock::new(CompactionState::default())),
509            pause: Default::default(),
510            pause_waiters: Vec::new(),
511            pick_history: PickHistory::default(),
512            region_id,
513            version_control,
514            access_layer,
515            active: ActiveCompaction::idle(),
516            pending_request: None,
517            pending_task_state: None,
518            pending_ddl_requests: Vec::new(),
519            executing_ddl: None,
520        }
521    }
522
523    #[cfg(test)]
524    pub(super) fn for_test(
525        region_id: RegionId,
526        version_control: VersionControlRef,
527        access_layer: AccessLayerRef,
528    ) -> Self {
529        let mut status = Self::new(region_id, version_control, access_layer);
530        status.active = ActiveCompaction::picking(0, Vec::new(), CompactionTrigger::Automatic);
531        status
532    }
533
534    /// Registration alone does not indicate active work.
535    pub(crate) fn is_compacting(&self) -> bool {
536        !matches!(self.active.phase, CompactionPhase::Idle)
537    }
538
539    /// Both queued and handed-off DDLs prevent new compaction admission.
540    pub(crate) fn has_ddl(&self) -> bool {
541        !self.pending_ddl_requests.is_empty() || self.executing_ddl.is_some()
542    }
543
544    /// Compaction pauses while the region has WAL tails to recover.
545    pub(crate) fn has_pending_tails(&self) -> bool {
546        self.version_control.current().version.has_pending_tails()
547    }
548
549    /// Ends the current cycle without losing region or DDL execution state.
550    pub(crate) fn become_idle(&mut self) {
551        self.active = ActiveCompaction::idle();
552        self.publish_state();
553        self.notify_idle();
554    }
555
556    #[cfg(test)]
557    pub(super) fn start_picking(&mut self, plan_id: u64) {
558        self.start_picking_with_trigger(plan_id, CompactionTrigger::Automatic);
559    }
560
561    pub(super) fn start_picking_with_trigger(&mut self, plan_id: u64, trigger: CompactionTrigger) {
562        self.active.start_picking(plan_id, trigger);
563    }
564
565    pub(super) fn start_regular_picking(&mut self, plan_id: u64) {
566        self.active.start_regular_picking(plan_id);
567    }
568
569    pub(super) fn is_picking(&self, expected_plan_id: u64) -> bool {
570        self.active.is_picking(expected_plan_id)
571    }
572
573    pub(super) fn accept_plan(&self, expected_plan_id: u64) -> bool {
574        self.active.accept_plan(expected_plan_id)
575    }
576
577    pub(super) fn is_manual_compaction(&self) -> bool {
578        self.active.is_manual()
579    }
580
581    pub(super) fn matches_execution(&self, execution: &CompactionExecution) -> bool {
582        self.active.matches_execution(execution)
583    }
584
585    #[cfg(test)]
586    pub(super) fn start_local_task(&mut self) -> CancellableTaskState {
587        let state = CancellableTaskState::new();
588        let execution = CompactionExecution::new(0, CompactingFiles::empty());
589        let phase = CompactionPhase::Local {
590            state: state.clone(),
591            execution,
592        };
593        self.active.phase = phase;
594        state
595    }
596
597    #[cfg(test)]
598    pub(super) fn start_remote_task(&mut self) {
599        let execution = CompactionExecution::new(0, CompactingFiles::empty());
600        let phase = CompactionPhase::Remote { execution };
601        self.active.phase = phase;
602    }
603
604    pub(super) fn request_cancel(&mut self) -> RequestCancelResult {
605        let result = self.active.request_cancel();
606        self.publish_state();
607        result
608    }
609
610    pub(super) fn mark_automatic_trigger(&mut self) {
611        self.active.mark_automatic_trigger();
612    }
613
614    /// Merge the waiter to the pending compaction.
615    pub(super) fn merge_waiter(&mut self, waiter: OptionOutputTx) {
616        self.active.merge_waiter(waiter);
617    }
618
619    pub(super) fn take_waiters(&mut self) -> Vec<OutputTx> {
620        std::mem::take(&mut self.active.waiters)
621    }
622
623    pub(super) fn extend_waiters(&mut self, waiters: Vec<OutputTx>) {
624        self.active.waiters.extend(waiters);
625    }
626
627    pub(super) fn set_phase(&mut self, phase: CompactionPhase) {
628        self.active.phase = phase;
629        self.publish_state();
630    }
631
632    /// Sets a pending manual compaction request, replacing an older pending request.
633    pub(super) fn set_pending_request(&mut self, pending: PendingCompaction) {
634        self.pending_task_state = Some(CompactionTaskState::new(
635            self.region_id,
636            &pending.options,
637            pending.max_parallelism,
638            pending.time_range,
639            CompactionTrigger::Manual,
640        ));
641        if let Some(prev) = self.pending_request.replace(pending) {
642            debug!(
643                "Replace pending compaction options with new request {:?} for region: {}",
644                prev.options, self.region_id
645            );
646            prev.waiter.send(ManualCompactionOverrideSnafu.fail());
647        }
648        self.publish_state();
649    }
650
651    pub(super) fn on_failure(&mut self, err: Arc<Error>) {
652        for sender in self.pause_waiters.drain(..) {
653            let _ = sender.send(Err(err.clone()).context(CompactRegionSnafu {
654                region_id: self.region_id,
655            }));
656        }
657        let mut active = std::mem::replace(&mut self.active, ActiveCompaction::idle());
658        for waiter in active.waiters.drain(..) {
659            waiter.send(Err(err.clone()).context(CompactRegionSnafu {
660                region_id: self.region_id,
661            }));
662        }
663
664        self.pending_task_state = None;
665        if let Some(pending_compaction) = self.pending_request.take() {
666            pending_compaction
667                .waiter
668                .send(Err(err.clone()).context(CompactRegionSnafu {
669                    region_id: self.region_id,
670                }));
671        }
672
673        for pending_ddl in self.pending_ddl_requests.drain(..) {
674            pending_ddl
675                .sender
676                .send(Err(err.clone()).context(CompactRegionSnafu {
677                    region_id: self.region_id,
678                }));
679        }
680        self.publish_state();
681    }
682
683    /// Ends task-specific cancellation only when no pending DDL takes precedence.
684    /// Returns whether the caller may promote a different pending compaction.
685    pub(crate) fn finish_task_cancellation(&mut self) -> bool {
686        if !self.active.task_cancel_requested || !self.pending_ddl_requests.is_empty() {
687            return false;
688        }
689        let mut active = std::mem::replace(&mut self.active, ActiveCompaction::idle());
690        for waiter in active.waiters.drain(..) {
691            waiter.send(CompactionCancelledSnafu.fail());
692        }
693        self.publish_state();
694        self.notify_idle();
695        true
696    }
697
698    #[must_use]
699    pub(super) fn on_cancel(&mut self) -> Vec<SenderDdlRequest> {
700        let mut active = std::mem::replace(&mut self.active, ActiveCompaction::idle());
701        for waiter in active.waiters.drain(..) {
702            waiter.send(CompactionCancelledSnafu.fail());
703        }
704
705        self.pending_task_state = None;
706        if let Some(pending_compaction) = self.pending_request.take() {
707            pending_compaction.waiter.send(
708                Err(Arc::new(CompactionCancelledSnafu.build())).context(CompactRegionSnafu {
709                    region_id: self.region_id,
710                }),
711            );
712        }
713
714        self.publish_state();
715        self.notify_idle();
716        std::mem::take(&mut self.pending_ddl_requests)
717    }
718
719    /// Creates an immutable request for background compaction planning.
720    #[allow(clippy::too_many_arguments)]
721    pub(super) fn new_compaction_request(
722        &self,
723        request_sender: Sender<WorkerRequestWithTime>,
724        engine_config: Arc<MitoConfig>,
725        cache_manager: CacheManagerRef,
726        manifest_ctx: &ManifestContextRef,
727        listener: WorkerListener,
728        schema_metadata_manager: SchemaMetadataManagerRef,
729        max_parallelism: usize,
730        pick_history: Option<PickHistory>,
731    ) -> CompactionRequest {
732        let current_version = CompactionVersion::from(self.version_control.current().version);
733        let start_time = Instant::now();
734
735        CompactionRequest {
736            pick_history,
737            engine_config,
738            current_version,
739            access_layer: self.access_layer.clone(),
740            request_sender: request_sender.clone(),
741            start_time,
742            cache_manager,
743            manifest_ctx: manifest_ctx.clone(),
744            listener,
745            schema_metadata_manager,
746            max_parallelism,
747        }
748    }
749}
750
751/// A manual compaction request waiting for an automatic compaction to finish.
752pub(super) struct PendingCompaction {
753    /// Compaction options.
754    pub(crate) options: compact_request::Options,
755    /// Waiters of pending requests.
756    pub(crate) waiter: OptionOutputTx,
757    /// Max parallelism for pending compaction.
758    pub(crate) max_parallelism: usize,
759    /// Optional time range that constrains candidate compaction windows.
760    pub(crate) time_range: Option<TimestampRange>,
761}
762
763/// Current cycles of one loaded region, without completed-task history.
764#[derive(Debug, Default)]
765pub(crate) struct CompactionState {
766    active: Option<Arc<CompactionTaskState>>,
767    pending: Option<Arc<CompactionTaskState>>,
768}
769
770/// Shared current cycles of a loaded region.
771pub(crate) type CompactionStateRef = Arc<RwLock<CompactionState>>;
772
773impl CompactionState {
774    /// Clones current cycle handles under a short read lock.
775    pub(crate) fn current(
776        state: &CompactionStateRef,
777    ) -> (
778        Option<Arc<CompactionTaskState>>,
779        Option<Arc<CompactionTaskState>>,
780    ) {
781        let state = state.read().unwrap();
782        (state.active.clone(), state.pending.clone())
783    }
784}
785
786/// Per-cycle request metadata and live execution handles, without retaining SSTs.
787#[derive(Debug, Clone)]
788pub(crate) struct CompactionTaskState {
789    pub(crate) entry: CompactionTaskEntry,
790    pub(crate) submitted: Instant,
791    local_state: Option<LocalCompactionState>,
792}
793
794impl CompactionTaskState {
795    /// Captures request parameters and assigns the identity of a new compaction cycle.
796    pub(crate) fn new(
797        region_id: RegionId,
798        options: &compact_request::Options,
799        max_parallelism: usize,
800        time_range: Option<TimestampRange>,
801        trigger: CompactionTrigger,
802    ) -> Self {
803        let (kind, window) = match options {
804            compact_request::Options::Regular(_) => ("regular", None),
805            compact_request::Options::StrictWindow(window) => {
806                ("strict_window", Some(window.window_seconds))
807            }
808        };
809        let request_options = serde_json::json!({
810            "type": kind,
811            "window_seconds": window,
812            "max_parallelism": max_parallelism,
813            "time_range": time_range,
814        })
815        .to_string();
816        Self {
817            submitted: Instant::now(),
818            local_state: None,
819            entry: CompactionTaskEntry {
820                task_id: uuid::Uuid::new_v4().to_string().into(),
821                region_id,
822                table_id: region_id.table_id(),
823                node_id: None,
824                trigger_type: match trigger {
825                    CompactionTrigger::Manual => compaction_task::TRIGGER_TYPE_MANUAL,
826                    CompactionTrigger::Automatic => compaction_task::TRIGGER_TYPE_AUTOMATIC,
827                }
828                .into(),
829                state: compaction_task::STATE_QUEUED.into(),
830                phase: compaction_task::PHASE_WAITING.into(),
831                submitted_at: common_time::util::current_time_millis(),
832                elapsed_millis: 0,
833                input_files: None,
834                input_bytes: None,
835                input_time_start: None,
836                input_time_end: None,
837                output_time_start: None,
838                output_time_end: None,
839                total_units: None,
840                completed_units: None,
841                request_options: request_options.into(),
842                effective_options: None,
843            },
844        }
845    }
846
847    /// Captures the resolved parameters and work selected by an accepted plan.
848    pub(crate) fn accept_plan(&mut self, region: &CompactionRegion, output: &PickerOutput) {
849        let max_parallelism = region.max_parallelism.max(1);
850        let max_picker_outputs = region
851            .engine_config
852            .max_background_compactions
853            .min(max_parallelism);
854        self.entry.effective_options = Some(
855            serde_json::json!({
856                "compaction": region.region_options.compaction,
857                "ttl": region.ttl,
858                "merge_mode": region.region_options.merge_mode(),
859                "max_picker_outputs": max_picker_outputs,
860                "max_parallelism": max_parallelism,
861                "time_window_seconds": output.time_window_size,
862                "max_output_file_size": output.max_file_size,
863            })
864            .to_string()
865            .into(),
866        );
867        self.set_plan_stats(
868            output
869                .outputs
870                .iter()
871                .flat_map(|output| &output.inputs)
872                .chain(&output.expired_ssts),
873            output.outputs.iter(),
874        );
875    }
876
877    /// Records the cycle's accepted inputs and planned output envelope, without retaining SSTs.
878    /// Called again after local memory admission to exclude rejected units. These aggregates
879    /// remain stable as individual units finish; inputs include expired SSTs and output ends
880    /// retain half-open semantics. If any output lacks a planned range, both output bounds
881    /// are None (SQL NULL). An unbounded side propagates independently across outputs.
882    pub(crate) fn set_plan_stats<'a>(
883        &mut self,
884        inputs: impl Iterator<Item = &'a FileHandle>,
885        outputs: impl Iterator<Item = &'a CompactionOutput>,
886    ) {
887        let mut seen = HashSet::new();
888        let mut bytes = 0;
889        let mut input_start = None;
890        let mut input_end = None;
891        for file in inputs {
892            if !seen.insert(file.file_id()) {
893                continue;
894            }
895            bytes += file.meta_ref().file_size;
896            let (start, end) = file.time_range();
897            input_start =
898                Some(input_start.map_or(start, |previous| std::cmp::min(previous, start)));
899            input_end = Some(input_end.map_or(end, |previous| std::cmp::max(previous, end)));
900        }
901        self.entry.input_files = Some(seen.len() as u64);
902        self.entry.input_bytes = Some(bytes);
903        self.entry.input_time_start = input_start;
904        self.entry.input_time_end = input_end;
905
906        let envelope = outputs
907            .map(|output| {
908                output
909                    .output_time_range
910                    .map(|range| (*range.start(), *range.end()))
911                    .unwrap_or((None, None))
912            })
913            .reduce(|(start, end), (next_start, next_end)| {
914                (
915                    start.zip(next_start).map(|(a, b)| a.min(b)),
916                    end.zip(next_end).map(|(a, b)| a.max(b)),
917                )
918            });
919        let (start, end) = envelope.unwrap_or((None, None));
920        self.entry.output_time_start = start;
921        self.entry.output_time_end = end;
922    }
923
924    /// Copies cycle metadata with the reporting node and current monotonic elapsed time.
925    pub(crate) fn snapshot(&self, node_id: Option<u64>) -> CompactionTaskEntry {
926        let mut entry = self.entry.clone();
927        if let Some(local) = &self.local_state {
928            local.inspect(&mut entry);
929        }
930        entry.node_id = node_id;
931        entry.elapsed_millis = self.submitted.elapsed().as_millis().min(u64::MAX as u128) as u64;
932        entry
933    }
934}
935
936#[cfg(test)]
937mod tests {
938    use common_time::Timestamp;
939    use store_api::storage::FileId;
940
941    use super::*;
942    use crate::compaction::test_util::new_file_handle;
943    use crate::test_util::new_noop_file_purger;
944
945    fn plan_time_range(start: Option<Timestamp>, end: Option<Timestamp>) -> TimestampRange {
946        TimestampRange::from((
947            start.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Included),
948            end.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Excluded),
949        ))
950    }
951
952    fn plan_stats_fixture() -> (CompactionTaskState, [FileHandle; 3], [CompactionOutput; 2]) {
953        let file = |start, end, size| {
954            let original = new_file_handle(FileId::random(), 0, 0, 0);
955            let mut meta = original.meta_ref().clone();
956            meta.time_range = (start, end);
957            meta.file_size = size;
958            FileHandle::new(meta, new_noop_file_purger())
959        };
960        // Compare timestamps in their original units: numeric values alone have the wrong order.
961        let early = file(
962            Timestamp::new_second(1),
963            Timestamp::new_millisecond(1500),
964            10,
965        );
966        let late = file(
967            Timestamp::new_microsecond(3_000_001),
968            Timestamp::new_second(4),
969            20,
970        );
971        let expired = file(Timestamp::new_second(-2), Timestamp::new_second(-1), 30);
972        let output = |inputs, start, end| CompactionOutput {
973            output_level: 1,
974            inputs,
975            filter_deleted: false,
976            output_time_range: Some(plan_time_range(start, end)),
977        };
978        let outputs = [
979            output(
980                vec![early.clone()],
981                Some(Timestamp::new_second(0)),
982                Some(Timestamp::new_second(2)),
983            ),
984            output(
985                vec![late.clone()],
986                Some(Timestamp::new_second(3)),
987                Some(Timestamp::new_second(5)),
988            ),
989        ];
990        let info = CompactionTaskState::new(
991            RegionId::new(1, 1),
992            &compact_request::Options::Regular(Default::default()),
993            1,
994            None,
995            CompactionTrigger::Manual,
996        );
997        (info, [early, late, expired], outputs)
998    }
999
1000    type PlanStats = (
1001        Option<u64>,
1002        Option<u64>,
1003        Option<Timestamp>,
1004        Option<Timestamp>,
1005        Option<Timestamp>,
1006        Option<Timestamp>,
1007    );
1008
1009    fn plan_stats(info: &CompactionTaskState) -> PlanStats {
1010        let entry = &info.entry;
1011        (
1012            entry.input_files,
1013            entry.input_bytes,
1014            entry.input_time_start,
1015            entry.input_time_end,
1016            entry.output_time_start,
1017            entry.output_time_end,
1018        )
1019    }
1020
1021    #[test]
1022    fn test_compaction_plan_stats_deduplication_and_admission() {
1023        let (mut info, [early, late, expired], outputs) = plan_stats_fixture();
1024        // Repeated inputs across logical windows count once; expired SSTs extend only inputs.
1025        info.set_plan_stats(
1026            [&early, &late, &early, &expired].into_iter(),
1027            outputs.iter(),
1028        );
1029        assert_eq!(
1030            plan_stats(&info),
1031            (
1032                Some(3),
1033                Some(60),
1034                Some(Timestamp::new_second(-2)),
1035                Some(Timestamp::new_second(4)),
1036                Some(Timestamp::new_second(0)),
1037                Some(Timestamp::new_second(5))
1038            )
1039        );
1040        // Recompute after admission excludes a unit, including its output window.
1041        info.set_plan_stats([&early, &expired].into_iter(), outputs[..1].iter());
1042        assert_eq!(
1043            plan_stats(&info),
1044            (
1045                Some(2),
1046                Some(40),
1047                Some(Timestamp::new_second(-2)),
1048                Some(Timestamp::new_millisecond(1500)),
1049                Some(Timestamp::new_second(0)),
1050                Some(Timestamp::new_second(2))
1051            )
1052        );
1053    }
1054
1055    #[test]
1056    fn test_compaction_plan_stats_expiration_and_empty_reset() {
1057        let (mut info, [early, late, expired], outputs) = plan_stats_fixture();
1058        info.set_plan_stats([&early, &late, &expired].into_iter(), outputs.iter());
1059        // Expiration-only cycles have input coverage but no output envelope.
1060        info.set_plan_stats([&expired].into_iter(), std::iter::empty());
1061        assert_eq!(
1062            plan_stats(&info),
1063            (
1064                Some(1),
1065                Some(30),
1066                Some(Timestamp::new_second(-2)),
1067                Some(Timestamp::new_second(-1)),
1068                None,
1069                None
1070            )
1071        );
1072        info.set_plan_stats(std::iter::empty(), std::iter::empty());
1073        assert_eq!(
1074            plan_stats(&info),
1075            (Some(0), Some(0), None, None, None, None)
1076        );
1077    }
1078
1079    #[test]
1080    fn test_compaction_plan_stats_missing_and_unbounded_ranges() {
1081        let (mut info, [early, late, _], outputs) = plan_stats_fixture();
1082        // An unbounded side of any output remains unbounded in the cycle envelope.
1083        for (range, expected_start, expected_end) in [
1084            (None, None, None),
1085            (
1086                Some(plan_time_range(None, Some(Timestamp::new_second(5)))),
1087                None,
1088                Some(Timestamp::new_second(5)),
1089            ),
1090            (
1091                Some(plan_time_range(Some(Timestamp::new_second(3)), None)),
1092                Some(Timestamp::new_second(0)),
1093                None,
1094            ),
1095        ] {
1096            let mut mixed = outputs.clone();
1097            mixed[1].output_time_range = range;
1098            // Order must not affect propagation of unbounded ranges.
1099            for reverse in [false, true] {
1100                if reverse {
1101                    mixed.reverse();
1102                }
1103                info.set_plan_stats([&early, &late].into_iter(), mixed.iter());
1104                assert_eq!(info.entry.output_time_start, expected_start);
1105                assert_eq!(info.entry.output_time_end, expected_end);
1106            }
1107        }
1108    }
1109
1110    #[test]
1111    fn test_compaction_unit_input_leases_release_independently() {
1112        let x = new_file_handle(FileId::random(), 0, 100, 0);
1113        let y = new_file_handle(FileId::random(), 100, 200, 0);
1114        let unused = new_file_handle(FileId::random(), 200, 300, 0);
1115        let reserved = CompactingFiles::try_reserve([&x, &y, &x, &unused]).unwrap();
1116        let first = reserved.for_inputs(&[x.clone(), x.clone()]);
1117        let second = reserved.for_inputs(std::slice::from_ref(&y));
1118        drop(reserved);
1119        assert!(x.compacting() && y.compacting());
1120        assert!(
1121            !unused.compacting(),
1122            "unit leases must not retain unrelated inputs"
1123        );
1124        drop(first);
1125        assert!(!x.compacting() && y.compacting());
1126        let notification = second.clone();
1127        drop(second);
1128        assert!(y.compacting());
1129        drop(notification);
1130        assert!(!y.compacting());
1131    }
1132}