1use std::collections::{HashMap, VecDeque};
16use std::future::Future;
17use std::sync::Arc;
18#[cfg(test)]
19use std::sync::atomic::AtomicUsize;
20use std::sync::atomic::{AtomicBool, Ordering};
21
22use common_meta::key::SchemaMetadataManagerRef;
23use prometheus::IntGauge;
24use store_api::compaction_task::{self, CompactionTaskEntry};
25use store_api::storage::RegionId;
26
27use crate::compaction::compactor::{CompactionContext, CompactionRegion};
28use crate::compaction::scheduler::state::{CompactingFiles, CompactionExecution, CompactionPhase};
29use crate::compaction::scheduler::{
30 CompactionCoordinator, CompactionScheduler, CompactionTransition, ReadyUnit,
31};
32use crate::compaction::task::CompactionTask;
33use crate::compaction::unit::CompactionUnit;
34use crate::error::{self, Error, Result};
35use crate::metrics::INFLIGHT_COMPACTION_COUNT;
36use crate::region::ManifestContextRef;
37use crate::request::{
38 BackgroundNotify, CompactionUnitNotification, WorkerRequest, WorkerRequestWithTime,
39};
40use crate::schedule::{CancellableTaskState, RequestCancelResult};
41use crate::sst::file::UncommittedSsts;
42
43#[derive(Debug)]
45struct UnitExecution {
46 state: CancellableTaskState,
47 finished: AtomicBool,
50 released: AtomicBool,
51}
52
53struct InflightCompaction(IntGauge);
56
57impl InflightCompaction {
58 async fn run(job: impl Future<Output = ()>, gauge: IntGauge) {
60 let _inflight = Self::start(gauge);
61 job.await;
62 }
63
64 fn start(gauge: IntGauge) -> Self {
65 gauge.inc();
66 Self(gauge)
67 }
68}
69
70impl Drop for InflightCompaction {
71 fn drop(&mut self) {
72 self.0.dec();
73 }
74}
75
76#[derive(Debug)]
78pub(crate) struct LocalCompaction {
79 coordinator: Arc<CompactionCoordinator>,
80 region_id: RegionId,
81 units: HashMap<u64, Arc<UnitExecution>>,
85 unit_states: Arc<[Arc<UnitExecution>]>,
88 #[cfg(test)]
89 publication_count: Arc<AtomicUsize>,
90 pending: VecDeque<CompactionTask>,
91 parallelism: usize,
92 error: Option<Arc<Error>>,
93 made_progress: bool,
94 cancellation_requested: bool,
96}
97
98#[derive(Debug, Clone)]
100pub(crate) struct LocalCompactionState {
101 units: Arc<[Arc<UnitExecution>]>,
102 cancellation_requested: bool,
103}
104
105impl LocalCompactionState {
106 pub(crate) fn inspect(&self, entry: &mut CompactionTaskEntry) {
110 entry.total_units = Some(self.units.len() as u64);
111 let mut completed = 0;
112 let mut cancelling = self.cancellation_requested;
113 let mut committing = false;
114 let mut running = false;
115 for unit in self.units.iter() {
116 completed += u64::from(unit.finished.load(Ordering::Relaxed));
117 if unit.released.load(Ordering::Relaxed) {
118 continue;
119 }
120 cancelling |= unit.state.is_cancelled();
121 committing |= unit.state.commit_started();
122 running |= unit.state.started();
123 }
124 entry.completed_units = Some(completed);
125 running |= committing;
126 entry.state = if cancelling {
127 compaction_task::STATE_CANCELLING
128 } else if running {
129 compaction_task::STATE_RUNNING
130 } else {
131 compaction_task::STATE_QUEUED
132 }
133 .into();
134 entry.phase = if committing {
135 compaction_task::PHASE_COMMITTING
136 } else if running {
137 compaction_task::PHASE_EXECUTING
138 } else {
139 compaction_task::PHASE_WAITING
140 }
141 .into();
142 }
143}
144
145impl LocalCompaction {
146 pub(crate) fn current_state(&self) -> LocalCompactionState {
148 #[cfg(test)]
149 self.publication_count.fetch_add(1, Ordering::Relaxed);
150 LocalCompactionState {
151 units: self.unit_states.clone(),
152 cancellation_requested: self.cancellation_requested,
153 }
154 }
155
156 #[cfg(test)]
157 pub(crate) fn publication_count_for_test(&self) -> Arc<AtomicUsize> {
158 self.publication_count.clone()
159 }
160
161 #[cfg(test)]
162 pub(crate) fn inspection_stats_for_test(&self) -> (usize, usize, usize) {
163 (
164 Arc::as_ptr(&self.unit_states) as *const () as usize,
165 self.unit_states.len(),
166 Arc::strong_count(&self.unit_states),
167 )
168 }
169
170 #[cfg(test)]
171 pub(crate) fn released_units_for_test(&self) -> usize {
172 self.unit_states
173 .iter()
174 .filter(|unit| unit.released.load(Ordering::Relaxed))
175 .count()
176 }
177
178 #[cfg(test)]
179 pub(crate) fn unit_ids_for_test(&self) -> Vec<u64> {
180 self.units.keys().copied().collect()
181 }
182
183 #[cfg(test)]
184 pub(crate) fn inspect(&self, entry: &mut CompactionTaskEntry) {
185 self.current_state().inspect(entry);
186 }
187
188 pub(crate) fn request_cancel(&mut self) -> RequestCancelResult {
190 let mut result = RequestCancelResult::TooLateToCancel;
191 for unit in self.units.values() {
192 match unit.state.request_cancel() {
193 RequestCancelResult::CancelIssued => result = RequestCancelResult::CancelIssued,
194 RequestCancelResult::AlreadyCancelling
195 if result != RequestCancelResult::CancelIssued =>
196 {
197 result = RequestCancelResult::AlreadyCancelling;
198 }
199 _ => {}
200 }
201 }
202 self.cancellation_requested |= result != RequestCancelResult::TooLateToCancel;
203 self.coordinator.cancel_pending(self.region_id);
204 result
205 }
206
207 fn num_running(&self) -> usize {
209 self.units.len() - self.pending.len()
210 }
211
212 fn can_apply(&self, id: u64) -> bool {
214 self.units.get(&id).is_some_and(|unit| {
215 !unit.finished.load(Ordering::Relaxed) && unit.state.commit_started()
216 })
217 }
218
219 fn release_unit(&mut self, id: u64) {
221 if let Some(unit) = self.units.remove(&id) {
222 unit.released.store(true, Ordering::Relaxed);
223 }
224 }
225
226 fn finish(&mut self, id: u64, result: std::result::Result<bool, Arc<Error>>) {
228 let Some(unit) = self.units.get(&id) else {
229 return;
230 };
231 if unit.finished.load(Ordering::Relaxed) {
232 return;
233 }
234 unit.finished.store(true, Ordering::Relaxed);
235 match result {
236 Ok(progress) => self.made_progress |= progress,
237 Err(err) => {
238 if self.error.as_ref().is_none_or(|current| {
240 matches!(current.as_ref(), Error::CompactionCancelled { .. })
241 }) {
242 self.error = Some(err);
243 }
244 }
245 }
246 }
247}
248
249impl Drop for LocalCompaction {
250 fn drop(&mut self) {
252 self.request_cancel();
253 }
254}
255
256impl CompactionScheduler {
257 pub(crate) fn prepare_local_units(
259 &mut self,
260 region: CompactionRegion,
261 units: Vec<CompactionUnit>,
262 reserved: CompactingFiles,
263 ) -> Result<CompactionPhase> {
264 if let Some(info) = self
267 .region_status
268 .get_mut(®ion.region_id)
269 .and_then(|status| status.active.task_state.as_mut())
270 {
271 info.set_plan_stats(
272 units.iter().flat_map(|unit| &unit.inputs),
273 units.iter().flat_map(|unit| &unit.outputs),
274 );
275 }
276 let mut local = LocalCompaction {
277 coordinator: self.coordinator.clone(),
278 region_id: region.region_id,
279 units: HashMap::new(),
280 unit_states: Arc::from([]),
281 #[cfg(test)]
282 publication_count: Arc::new(AtomicUsize::new(0)),
283 pending: VecDeque::new(),
284 parallelism: region.max_parallelism.max(1),
285 error: None,
286 made_progress: false,
287 cancellation_requested: false,
288 };
289 let context = CompactionContext::try_from(®ion)?;
290 let estimated_memory: Vec<_> = units
291 .iter()
292 .map(|unit| region.estimated_memory_bytes(unit))
293 .collect();
294 drop(region);
296 for (unit, estimated_memory_bytes) in units.into_iter().zip(estimated_memory) {
297 let files = reserved.for_inputs(&unit.inputs);
298 let id = Self::next_plan_id(&mut self.next_plan_id);
299 let execution = CompactionExecution::new(id, files);
300 let state = CancellableTaskState::new();
301 local.units.insert(
302 id,
303 Arc::new(UnitExecution {
304 state: state.clone(),
305 finished: AtomicBool::new(false),
306 released: AtomicBool::new(false),
307 }),
308 );
309 local.pending.push_back(CompactionTask {
310 state,
311 execution,
312 compaction_context: context.clone(),
313 request_sender: self.request_sender.clone(),
314 listener: self.listener.clone(),
315 estimated_memory_bytes,
316 unit,
317 memory_manager: self.memory_manager.clone(),
318 memory_policy: self.memory_policy,
319 uncommitted: UncommittedSsts::new(
320 context.region_id,
321 context.access_layer.clone(),
322 Some(context.cache_manager.clone()),
323 ),
324 });
325 }
326 local.unit_states = local.units.values().cloned().collect();
327 Ok(CompactionPhase::Units(local))
328 }
329
330 fn local_units_mut(&mut self, region_id: RegionId) -> Option<&mut LocalCompaction> {
332 match &mut self.region_status.get_mut(®ion_id)?.active.phase {
333 CompactionPhase::Units(local) => Some(local),
334 _ => None,
335 }
336 }
337
338 pub(crate) fn dispatch_local_units(&mut self, region_id: RegionId) {
340 self.submit_local_units(region_id);
341 if let Some(status) = self.region_status.get(®ion_id) {
342 status.publish_state();
343 }
344 }
345
346 fn submit_local_units(&mut self, region_id: RegionId) {
347 loop {
348 let Some(local) = self.local_units_mut(region_id) else {
349 return;
350 };
351 if local.num_running() >= local.parallelism {
352 return;
353 }
354 let Some(mut task) = local.pending.pop_front() else {
355 return;
356 };
357 let id = task.execution.plan_id();
358 let state = task.state.clone();
359 let input_bytes = task.unit.estimated_input_bytes();
360 let sender = self.request_sender.clone();
361 let completion = Box::pin(async move {
362 let _ = sender
363 .send(WorkerRequestWithTime::new(WorkerRequest::Background {
364 region_id,
365 notify: BackgroundNotify::CompactionUnit(
366 CompactionUnitNotification::Released { plan_id: id },
367 ),
368 }))
369 .await;
370 });
371 let job = Box::pin(InflightCompaction::run(
372 async move {
373 task.run().await;
374 drop(task);
375 },
376 INFLIGHT_COMPACTION_COUNT.clone(),
377 ));
378 if let Err(err) = self.coordinator.schedule(
379 region_id,
380 ReadyUnit::new(state, input_bytes, job, completion),
381 ) && let Some(local) = self.local_units_mut(region_id)
382 {
383 local.finish(id, Err(Arc::new(err)));
384 local.release_unit(id);
385 }
386 }
387 }
388
389 pub(crate) fn can_apply_unit(&self, region_id: RegionId, id: u64) -> bool {
391 self.region_status.get(®ion_id).is_some_and(|status| {
392 matches!(&status.active.phase, CompactionPhase::Units(local)
393 if local.can_apply(id))
394 })
395 }
396
397 pub(crate) fn on_unit_finished(
399 &mut self,
400 region_id: RegionId,
401 id: u64,
402 result: std::result::Result<bool, Arc<Error>>,
403 ) {
404 if let Some(local) = self.local_units_mut(region_id) {
405 local.finish(id, result);
406 }
407 if let Some(status) = self.region_status.get(®ion_id) {
408 status.publish_state();
409 }
410 }
411
412 pub(crate) async fn on_unit_released(
414 &mut self,
415 region_id: RegionId,
416 id: u64,
417 manifest: &ManifestContextRef,
418 schemas: SchemaMetadataManagerRef,
419 ) -> CompactionTransition {
420 let Some(local) = self.local_units_mut(region_id) else {
421 return CompactionTransition::NoAction;
422 };
423 if !local.units.contains_key(&id) {
424 return CompactionTransition::NoAction;
425 }
426 let missing_result = if local.units[&id].state.is_cancelled() {
427 error::CompactionCancelledSnafu.build()
428 } else {
429 error::UnexpectedSnafu {
430 reason: "Compaction unit exited without a terminal notification",
431 }
432 .build()
433 };
434 local.finish(id, Err(Arc::new(missing_result)));
435 local.release_unit(id);
436 self.dispatch_local_units(region_id);
437 self.finish_local_units(region_id, manifest, schemas).await
438 }
439
440 pub(crate) async fn finish_local_units(
442 &mut self,
443 region_id: RegionId,
444 manifest: &ManifestContextRef,
445 schemas: SchemaMetadataManagerRef,
446 ) -> CompactionTransition {
447 let Some(local) = self.local_units_mut(region_id) else {
448 return CompactionTransition::NoAction;
449 };
450 if !local.units.is_empty() {
451 return CompactionTransition::NoAction;
452 }
453 if let Some(err) = local.error.take() {
454 if matches!(err.as_ref(), Error::CompactionCancelled { .. }) {
455 return self.finish_cancelled_compaction(region_id, manifest, schemas);
456 }
457 self.on_compaction_failed(region_id, err);
458 return CompactionTransition::NoAction;
459 }
460 let progress = local.made_progress;
461 if let Some(status) = self.region_status.get_mut(®ion_id) {
462 for waiter in status.take_waiters() {
463 waiter.send(Ok(0));
464 }
465 }
466 self.on_compaction_finished(region_id, manifest, schemas, progress)
467 .await
468 }
469}
470
471#[cfg(test)]
472mod tests {
473 use futures::FutureExt;
474 use tokio::sync::oneshot;
475
476 use super::*;
477
478 fn local_compaction() -> LocalCompaction {
479 let units: HashMap<_, _> = [1, 2]
480 .into_iter()
481 .map(|id| {
482 (
483 id,
484 Arc::new(UnitExecution {
485 state: CancellableTaskState::new(),
486 finished: AtomicBool::new(false),
487 released: AtomicBool::new(false),
488 }),
489 )
490 })
491 .collect();
492 LocalCompaction {
493 coordinator: Arc::new(CompactionCoordinator::new(
494 Arc::new(crate::test_util::scheduler_util::VecScheduler::default()),
495 2,
496 )),
497 region_id: RegionId::from_u64(1),
498 unit_states: units.values().cloned().collect(),
499 publication_count: Arc::new(AtomicUsize::new(0)),
500 units,
501 pending: VecDeque::new(),
502 parallelism: 2,
503 error: None,
504 made_progress: false,
505 cancellation_requested: false,
506 }
507 }
508
509 #[rstest::rstest]
510 #[case::completed(false)]
511 #[case::panicked(true)]
512 #[tokio::test]
513 async fn test_inflight_job_balances_count_on_exit(#[case] panics: bool) {
514 let gauge = IntGauge::new("test_inflight_compaction", "isolated inflight gauge").unwrap();
515 let (resume, paused) = oneshot::channel();
516 let job = InflightCompaction::run(
517 async move {
518 paused.await.unwrap();
519 if panics {
520 panic!("inflight job panic fixture");
521 }
522 },
523 gauge.clone(),
524 );
525 let mut job = Box::pin(std::panic::AssertUnwindSafe(job).catch_unwind());
526
527 assert_eq!(0, gauge.get());
528 assert!(futures::poll!(job.as_mut()).is_pending());
529 assert_eq!(1, gauge.get());
531 resume.send(()).unwrap();
532 let outcome = job.await;
533 if panics {
534 let payload = outcome.unwrap_err();
535 assert_eq!(
536 Some("inflight job panic fixture"),
537 payload.downcast_ref::<&str>().copied()
538 );
539 } else {
540 assert!(outcome.is_ok());
541 }
542 assert_eq!(0, gauge.get());
543 }
544
545 #[rstest::rstest]
546 #[case::unpolled(false)]
547 #[case::started(true)]
548 #[tokio::test]
549 async fn test_inflight_job_drop_balances_started_count(#[case] started: bool) {
550 let gauge = IntGauge::new("test_inflight_compaction", "isolated inflight gauge").unwrap();
551 let mut job = Box::pin(InflightCompaction::run(
552 std::future::pending::<()>(),
553 gauge.clone(),
554 ));
555 assert_eq!(0, gauge.get());
556 if started {
557 assert!(futures::poll!(job.as_mut()).is_pending());
558 assert_eq!(1, gauge.get());
559 }
560 drop(job);
561 assert_eq!(0, gauge.get());
562 }
563
564 fn task_entry() -> CompactionTaskEntry {
565 use crate::compaction::scheduler::state::{CompactionTaskState, CompactionTrigger};
566
567 CompactionTaskState::new(
568 RegionId::from_u64(1),
569 &api::v1::region::compact_request::Options::Regular(Default::default()),
570 2,
571 None,
572 CompactionTrigger::Manual,
573 )
574 .snapshot(None)
575 }
576
577 #[test]
578 fn test_shared_units_observe_finish_and_release() {
579 let mut local = local_compaction();
580 let published = local.current_state();
581 let mut entry = task_entry();
582 for unit in local.units.values() {
583 assert!(
584 published
585 .units
586 .iter()
587 .any(|shared| Arc::ptr_eq(shared, unit))
588 );
589 }
590 assert!(local.units[&1].state.mark_commit_started());
591 local.finish(1, Ok(true));
592 local.finish(1, Ok(false));
593 published.inspect(&mut entry);
594 assert_eq!(entry.completed_units, Some(1));
595 assert_eq!((&*entry.state, &*entry.phase), ("running", "committing"));
596
597 local.release_unit(1);
598 local.release_unit(1);
599 local.release_unit(99);
600 published.inspect(&mut entry);
601 assert_eq!(entry.completed_units, Some(1));
602 assert_eq!((&*entry.state, &*entry.phase), ("queued", "waiting"));
603 assert!(Arc::ptr_eq(&published.units, &local.current_state().units));
604
605 local.finish(2, Err(Arc::new(error::CompactionCancelledSnafu.build())));
607 local.release_unit(2);
608 published.inspect(&mut entry);
609 assert_eq!(entry.total_units, Some(2));
610 assert_eq!(entry.completed_units, Some(2));
611 assert!(local.units.is_empty());
612 assert!(Arc::ptr_eq(&published.units, &local.current_state().units));
613 }
614
615 #[test]
616 fn test_shared_units_match_live_map_aggregation() {
617 #[derive(Debug, Clone, Copy)]
618 enum Phase {
619 Queued,
620 Running,
621 Committing,
622 Finished,
623 Released,
624 Cancelled,
625 CancelledReleased,
626 }
627 let phases = [
628 Phase::Queued,
629 Phase::Running,
630 Phase::Committing,
631 Phase::Finished,
632 Phase::Released,
633 Phase::Cancelled,
634 Phase::CancelledReleased,
635 ];
636 for first in phases {
637 for second in phases {
638 let mut local = local_compaction();
639 let published = local.current_state();
640 let mut completed = 0;
641 for (id, phase) in [(1, first), (2, second)] {
642 let state = &local.units[&id].state;
643 match phase {
644 Phase::Queued => {}
645 Phase::Running => state.mark_started(),
646 Phase::Committing | Phase::Finished | Phase::Released => {
647 assert!(state.mark_commit_started());
648 }
649 Phase::Cancelled | Phase::CancelledReleased => {
650 assert_eq!(state.request_cancel(), RequestCancelResult::CancelIssued);
651 }
652 }
653 if matches!(
654 phase,
655 Phase::Finished | Phase::Released | Phase::CancelledReleased
656 ) {
657 local.finish(id, Ok(false));
658 completed += 1;
659 }
660 if matches!(phase, Phase::Released | Phase::CancelledReleased) {
661 local.release_unit(id);
662 }
663 }
664 let cancelling = local.units.values().any(|unit| unit.state.is_cancelled());
666 let committing = local.units.values().any(|unit| unit.state.commit_started());
667 let running = committing || local.units.values().any(|unit| unit.state.started());
668 let expected_state = if cancelling {
669 "cancelling"
670 } else if running {
671 "running"
672 } else {
673 "queued"
674 };
675 let expected_phase = if committing {
676 "committing"
677 } else if running {
678 "executing"
679 } else {
680 "waiting"
681 };
682 let mut entry = task_entry();
683 published.inspect(&mut entry);
684 assert_eq!(
685 (
686 &*entry.state,
687 &*entry.phase,
688 entry.total_units,
689 entry.completed_units
690 ),
691 (expected_state, expected_phase, Some(2), Some(completed)),
692 "{first:?}, {second:?}",
693 );
694 }
695 }
696 }
697
698 #[test]
699 fn test_compaction_unit_apply_accepts_independent_executions() {
700 let mut local = local_compaction();
701 assert!(!local.can_apply(1));
702 assert!(!local.can_apply(2));
703 assert!(!local.can_apply(99));
704 for unit in local.units.values() {
705 assert!(unit.state.mark_commit_started());
706 }
707 assert!(local.can_apply(1) && local.can_apply(2));
708 local.finish(2, Ok(true));
709 assert!(local.can_apply(1));
710 assert!(!local.can_apply(2));
711 local.finish(2, Err(Arc::new(error::CompactionCancelledSnafu.build())));
712 local.finish(99, Err(Arc::new(error::CompactionCancelledSnafu.build())));
713 assert!(local.can_apply(1));
714 assert!(local.error.is_none());
715 assert!(local.made_progress);
716 local.finish(1, Ok(false));
717 assert!(!local.can_apply(1));
718 assert_eq!(
719 2,
720 local.units.len(),
721 "terminal units remain tracked until task exit"
722 );
723 }
724
725 #[test]
726 fn test_compaction_cancelling_survives_cancelled_sibling_release() {
727 let mut local = local_compaction();
728 let mut entry = task_entry();
729 let published = local.current_state();
731 published.inspect(&mut entry);
732 assert_eq!((&*entry.state, &*entry.phase), ("queued", "waiting"));
733 local.units[&1].state.mark_started();
734 published.inspect(&mut entry);
735 assert_eq!((&*entry.state, &*entry.phase), ("running", "executing"));
736 assert!(local.units[&1].state.mark_commit_started());
737 published.inspect(&mut entry);
738 assert_eq!((&*entry.state, &*entry.phase), ("running", "committing"));
739 assert_eq!(local.request_cancel(), RequestCancelResult::CancelIssued);
740 published.inspect(&mut entry);
741 assert_eq!((&*entry.state, &*entry.phase), ("cancelling", "committing"));
742
743 local.finish(2, Err(Arc::new(error::CompactionCancelledSnafu.build())));
745 local.release_unit(2);
746 assert!(!local.units[&1].state.is_cancelled());
747 local.inspect(&mut entry);
748 assert_eq!((&*entry.state, &*entry.phase), ("cancelling", "committing"));
749 assert_eq!(entry.completed_units, Some(1));
750 assert_eq!(entry.total_units, Some(2));
751
752 let mut too_late = local_compaction();
754 for unit in too_late.units.values() {
755 assert!(unit.state.mark_commit_started());
756 }
757 assert_eq!(
758 too_late.request_cancel(),
759 RequestCancelResult::TooLateToCancel
760 );
761 too_late.inspect(&mut entry);
762 assert_eq!((&*entry.state, &*entry.phase), ("running", "committing"));
763 }
764}