Skip to main content

mito2/compaction/
task.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::{Debug, Formatter};
16use std::sync::Arc;
17
18use common_memory_manager::OnExhaustedPolicy;
19use common_telemetry::error;
20use futures::FutureExt;
21use snafu::ResultExt;
22use tokio::sync::{mpsc, oneshot};
23
24use crate::compaction::compactor::{CompactionContext, DefaultCompactor, MergeOutput};
25use crate::compaction::memory_manager::CompactionMemoryManager;
26use crate::compaction::unit::CompactionUnit;
27use crate::compaction::{CompactionExecution, format_panic_reason};
28use crate::error::{self, CompactionCancelledSnafu, CompactionMemoryExhaustedSnafu, Result};
29use crate::manifest::action::RegionEdit;
30use crate::metrics::{
31    COMPACTION_FAILURE_COUNT, COMPACTION_INPUT_BYTES, COMPACTION_OUTPUT_BYTES,
32    COMPACTION_STAGE_ELAPSED,
33};
34use crate::request::{
35    BackgroundNotify, CompactionUnitNotification, WorkerRequest, WorkerRequestWithTime,
36};
37use crate::schedule::CancellableTaskState;
38use crate::sst::file::UncommittedSsts;
39use crate::worker::WorkerListener;
40
41/// One local atomic unit. The scheduler owns request waiters and sibling units.
42pub(crate) struct CompactionTask {
43    pub(crate) state: CancellableTaskState,
44    pub(crate) execution: CompactionExecution,
45    pub(crate) compaction_context: CompactionContext,
46    pub(crate) request_sender: mpsc::Sender<WorkerRequestWithTime>,
47    pub(crate) listener: WorkerListener,
48    pub(crate) unit: CompactionUnit,
49    pub(crate) memory_manager: Arc<CompactionMemoryManager>,
50    pub(crate) memory_policy: OnExhaustedPolicy,
51    /// Estimated memory bytes needed for this compaction.
52    pub(crate) estimated_memory_bytes: u64,
53    /// Finalized output SSTs not committed to the manifest yet.
54    pub(crate) uncommitted: UncommittedSsts,
55}
56
57impl Debug for CompactionTask {
58    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
59        f.debug_struct("CompactionTask")
60            .field("region_id", &self.compaction_context.region_id)
61            .field("unit", &self.unit)
62            .field(
63                "append_mode",
64                &self.compaction_context.region_options.append_mode,
65            )
66            .finish()
67    }
68}
69
70impl CompactionTask {
71    /// Executes one unit and retains its resources until worker apply or failure acknowledgement.
72    pub(crate) async fn run(&mut self) {
73        self.state.mark_started();
74        let start = std::time::Instant::now();
75        let result = std::panic::AssertUnwindSafe(self.run_once())
76            .catch_unwind()
77            .await
78            .unwrap_or_else(|payload| Err(self.panic_to_error(payload.as_ref())));
79        self.complete(result, start).await;
80    }
81
82    /// Acquires the unit's memory budget and merges on the compaction runtime.
83    async fn merge(&self) -> Result<MergeOutput> {
84        let region_id = self.compaction_context.region_id;
85        self.listener
86            .on_compaction_unit_merge_begin(region_id, self.execution.plan_id())
87            .await;
88        let bytes = self.estimated_memory_bytes;
89        let _memory_guard = if bytes == 0 {
90            None
91        } else {
92            let _wait_timer = crate::metrics::COMPACTION_MEMORY_WAIT.start_timer();
93            let cancellation = self.state.cancel_token();
94            Some(
95                tokio::select! {
96                    biased;
97                    _ = cancellation.cancelled() => return CompactionCancelledSnafu.fail(),
98                    memory = self.memory_manager.acquire_with_policy(bytes, self.memory_policy) => memory,
99                }
100                    .context(CompactionMemoryExhaustedSnafu {
101                        region_id,
102                        policy: format!("{:?}", self.memory_policy),
103                    })?,
104            )
105        };
106        let _timer = COMPACTION_STAGE_ELAPSED
107            .with_label_values(&["merge"])
108            .start_timer();
109        let compactor = DefaultCompactor::with_cancel_token(
110            self.state.cancel_token(),
111            self.uncommitted.clone(),
112        );
113        let context = self.compaction_context.clone();
114        let unit = self.unit.clone();
115        let output =
116            common_runtime::spawn_compact(
117                async move { compactor.merge_unit(&context, &unit).await },
118            )
119            .await
120            .context(error::JoinSnafu)??;
121        COMPACTION_INPUT_BYTES.inc_by(output.input_file_size() as f64);
122        COMPACTION_OUTPUT_BYTES.inc_by(output.output_file_size() as f64);
123        self.listener.on_merge_ssts_finished(region_id).await;
124        Ok(output)
125    }
126
127    /// Commits this unit through the existing manifest path, independently of sibling applies.
128    async fn publish(&self, output: MergeOutput) -> Result<RegionEdit> {
129        if !self.state.mark_commit_started() {
130            return CompactionCancelledSnafu.fail();
131        }
132        // Report this unit's SSTs before its manifest update; sibling units may progress independently.
133        self.compaction_context.invoke_sst_hook(&output).await;
134        self.listener
135            .on_compaction_commit_begin(self.compaction_context.region_id)
136            .await;
137        let _timer = COMPACTION_STAGE_ELAPSED
138            .with_label_values(&["write_manifest"])
139            .start_timer();
140        let (edit, _manifest_version) = self.compaction_context.update_manifest(output).await?;
141        self.uncommitted.disarm_cleanup();
142        self.listener
143            .on_compaction_unit_committed(
144                self.compaction_context.region_id,
145                self.execution.plan_id(),
146            )
147            .await;
148        Ok(edit)
149    }
150
151    /// Converts a caught panic into the unit's terminal error.
152    fn panic_to_error(&self, payload: &(dyn std::any::Any + Send + 'static)) -> error::Error {
153        let region_id = self.compaction_context.region_id;
154        let plan_id = self.execution.plan_id();
155        error::UnexpectedSnafu {
156            reason: format!(
157                "Compaction unit panicked for region {region_id}, plan_id {plan_id}: {}",
158                format_panic_reason(payload)
159            ),
160        }
161        .build()
162    }
163
164    /// Runs merge and publication.
165    async fn run_once(&mut self) -> Result<RegionEdit> {
166        let output = self.merge().await?;
167        self.publish(output).await
168    }
169
170    /// Cleans up and reports a terminal result before task exit.
171    async fn complete(&self, result: Result<RegionEdit>, start: std::time::Instant) {
172        if let Err(err) = &result {
173            if !matches!(err, error::Error::CompactionCancelled { .. }) {
174                COMPACTION_FAILURE_COUNT.inc();
175                error!(err; "Compaction unit failed, region: {}, plan_id: {}",
176                    self.compaction_context.region_id, self.execution.plan_id());
177            }
178            if self.state.commit_started() && err.may_have_persisted_manifest_update() {
179                self.uncommitted.disarm_cleanup();
180            } else {
181                self.uncommitted.cleanup().await;
182            }
183        }
184        let succeeded = result.is_ok();
185        let (applied, receiver) = oneshot::channel();
186        let notify = CompactionUnitNotification::Finished {
187            plan_id: self.execution.plan_id(),
188            result: result.map_err(Arc::new),
189            applied,
190        };
191        if let Err(err) = self.notify_result(notify).await {
192            error!(err; "Failed to notify compaction unit completion, region: {}", self.compaction_context.region_id);
193            return;
194        }
195        // This keeps the execution slot and inputs alive through worker apply.
196        if receiver.await.is_ok() && succeeded {
197            crate::metrics::COMPACTION_ELAPSED_TOTAL
198                .with_label_values(&["local"])
199                .observe(start.elapsed().as_secs_f64());
200        }
201    }
202
203    /// Sends a unit lifecycle event to the owning region worker.
204    async fn notify_result(&self, notify: CompactionUnitNotification) -> Result<()> {
205        self.request_sender
206            .send(WorkerRequestWithTime::new(WorkerRequest::Background {
207                region_id: self.compaction_context.region_id,
208                notify: BackgroundNotify::CompactionUnit(notify),
209            }))
210            .await
211            .map_err(|_| error::InvalidSenderSnafu.build())
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use std::time::Duration;
218
219    use store_api::storage::RegionId;
220
221    use super::*;
222    use crate::compaction::compactor::new_test_compaction_region;
223    use crate::compaction::memory_manager::new_compaction_memory_manager;
224    use crate::engine::listener::EventListener;
225    use crate::error::Error;
226
227    struct PanicOnUnitMergeBegin;
228
229    #[async_trait::async_trait]
230    impl EventListener for PanicOnUnitMergeBegin {
231        async fn on_compaction_unit_merge_begin(&self, _region_id: RegionId, _plan_id: u64) {
232            panic!("unit merge listener boom");
233        }
234    }
235
236    #[tokio::test]
237    async fn test_compaction_unit_panic_reports_terminal_error() {
238        let region = new_test_compaction_region().await;
239        let (request_sender, mut requests) = mpsc::channel(1);
240        let mut task = CompactionTask {
241            state: CancellableTaskState::new(),
242            execution: CompactionExecution::for_test(7),
243            compaction_context: CompactionContext::try_from(&region).unwrap(),
244            request_sender,
245            listener: WorkerListener::new(Some(Arc::new(PanicOnUnitMergeBegin))),
246            unit: CompactionUnit {
247                inputs: Vec::new(),
248                outputs: Vec::new(),
249                time_window_size: 0,
250                max_file_size: None,
251            },
252            memory_manager: Arc::new(new_compaction_memory_manager(0)),
253            memory_policy: OnExhaustedPolicy::default(),
254            estimated_memory_bytes: 0,
255            uncommitted: UncommittedSsts::new(region.region_id, region.access_layer.clone(), None),
256        };
257        let task_handle = tokio::spawn(async move { task.run().await });
258
259        let request = tokio::time::timeout(Duration::from_secs(5), requests.recv())
260            .await
261            .unwrap()
262            .unwrap();
263        let WorkerRequest::Background {
264            notify:
265                BackgroundNotify::CompactionUnit(CompactionUnitNotification::Finished {
266                    plan_id,
267                    result,
268                    applied,
269                }),
270            ..
271        } = request.request
272        else {
273            panic!("expected unit terminal notification");
274        };
275        assert_eq!(7, plan_id);
276        let err = result.unwrap_err();
277        assert!(matches!(err.as_ref(), Error::Unexpected { .. }));
278        assert!(err.to_string().contains("unit merge listener boom"));
279        applied.send(()).unwrap();
280        task_handle.await.unwrap();
281    }
282}