1use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17use std::time::{Instant, SystemTime};
18
19use anyhow::Context;
20use futures::stream::FuturesUnordered;
21use futures::{FutureExt, StreamExt};
22use risingwave_hummock_sdk::compact_task::ReportTask;
23use risingwave_hummock_sdk::{CompactionGroupId, HummockContextId};
24use risingwave_pb::hummock::compact_task::{TaskStatus, TaskType};
25use risingwave_pb::hummock::subscribe_compaction_event_request::{
26 Event as RequestEvent, HeartBeat, PullTask,
27};
28use risingwave_pb::hummock::subscribe_compaction_event_response::{
29 Event as ResponseEvent, PullTaskAck,
30};
31use risingwave_pb::hummock::{CompactTaskProgress, SubscribeCompactionEventRequest};
32use risingwave_pb::iceberg_compaction::SubscribeIcebergCompactionEventRequest;
33use risingwave_pb::iceberg_compaction::subscribe_iceberg_compaction_event_request::{
34 Event as IcebergRequestEvent, PullTask as IcebergPullTask, ReportTask as IcebergReportTask,
35};
36use risingwave_pb::iceberg_compaction::subscribe_iceberg_compaction_event_response::{
37 Event as IcebergResponseEvent, PullTaskAck as IcebergPullTaskAck,
38};
39use rw_futures_util::pending_on_none;
40use thiserror_ext::AsReport;
41use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
42use tokio::sync::oneshot::{Receiver as OneShotReceiver, Sender};
43use tokio::task::JoinHandle;
44use tonic::Streaming;
45use tracing::warn;
46
47use super::init_selectors;
48use crate::hummock::HummockManager;
49use crate::hummock::compaction::CompactionSelector;
50use crate::hummock::compactor_manager::Compactor;
51use crate::hummock::error::{Error, Result};
52use crate::hummock::sequence::next_compaction_task_id;
53use crate::manager::MetaOpts;
54use crate::manager::iceberg_compaction::IcebergCompactionManagerRef;
55use crate::rpc::metrics::MetaMetrics;
56
57const MAX_SKIP_TIMES: usize = 8;
58const MAX_REPORT_COUNT: usize = 16;
59
60#[async_trait::async_trait]
61pub trait CompactionEventDispatcher: Send + Sync + 'static {
62 type EventType: Send + Sync + 'static;
63
64 async fn on_event_locally(&self, context_id: HummockContextId, event: Self::EventType) -> bool;
65
66 async fn on_event_remotely(
67 &self,
68 context_id: HummockContextId,
69 event: Self::EventType,
70 ) -> Result<()>;
71
72 fn should_forward(&self, event: &Self::EventType) -> bool;
73
74 fn remove_compactor(&self, context_id: HummockContextId);
75}
76
77pub trait CompactorStreamEvent: Send + Sync + 'static {
78 type EventType: Send + Sync + 'static;
79 fn take_event(self) -> Self::EventType;
80 fn create_at(&self) -> u64;
81}
82
83pub struct CompactionEventLoop<
84 D: CompactionEventDispatcher<EventType = E::EventType>,
85 E: CompactorStreamEvent,
86> {
87 hummock_compactor_dispatcher: D,
88 metrics: Arc<MetaMetrics>,
89 compactor_streams_change_rx: UnboundedReceiver<(HummockContextId, Streaming<E>)>,
90}
91
92pub type HummockCompactionEventLoop =
93 CompactionEventLoop<HummockCompactionEventDispatcher, SubscribeCompactionEventRequest>;
94
95pub type IcebergCompactionEventLoop =
96 CompactionEventLoop<IcebergCompactionEventDispatcher, SubscribeIcebergCompactionEventRequest>;
97
98pub struct HummockCompactionEventDispatcher {
99 meta_opts: Arc<MetaOpts>,
100 hummock_compaction_event_handler: HummockCompactionEventHandler,
101 tx: Option<UnboundedSender<(HummockContextId, RequestEvent)>>,
102}
103
104#[async_trait::async_trait]
105impl CompactionEventDispatcher for HummockCompactionEventDispatcher {
106 type EventType = RequestEvent;
107
108 fn should_forward(&self, event: &Self::EventType) -> bool {
109 if self.tx.is_none() {
110 return false;
111 }
112
113 matches!(event, RequestEvent::PullTask(_)) || matches!(event, RequestEvent::ReportTask(_))
114 }
115
116 async fn on_event_locally(&self, context_id: HummockContextId, event: Self::EventType) -> bool {
117 let mut compactor_alive = true;
118 match event {
119 RequestEvent::HeartBeat(HeartBeat { progress }) => {
120 compactor_alive = self
121 .hummock_compaction_event_handler
122 .handle_heartbeat(context_id, progress)
123 .await;
124 }
125
126 RequestEvent::Register(_event) => {
127 unreachable!()
128 }
129
130 RequestEvent::PullTask(pull_task) => {
131 compactor_alive = self
132 .hummock_compaction_event_handler
133 .handle_pull_task_event(
134 context_id,
135 pull_task.pull_task_count as usize,
136 &mut init_selectors(),
137 self.meta_opts.max_get_task_probe_times,
138 )
139 .await;
140 }
141
142 RequestEvent::ReportTask(report_event) => {
143 if let Err(e) = self
144 .hummock_compaction_event_handler
145 .handle_report_task_event(vec![report_event.into()])
146 .await
147 {
148 tracing::error!(error = %e.as_report(), "report compact_tack fail")
149 }
150 }
151 }
152
153 compactor_alive
154 }
155
156 async fn on_event_remotely(
157 &self,
158 context_id: HummockContextId,
159 event: Self::EventType,
160 ) -> Result<()> {
161 if let Some(tx) = &self.tx {
162 tx.send((context_id, event))
163 .with_context(|| format!("Failed to send event to compactor {context_id}"))?;
164 } else {
165 unreachable!();
166 }
167 Ok(())
168 }
169
170 fn remove_compactor(&self, context_id: HummockContextId) {
171 self.hummock_compaction_event_handler
172 .hummock_manager
173 .compactor_manager
174 .remove_compactor(context_id);
175 }
176}
177
178impl HummockCompactionEventDispatcher {
179 pub fn new(
180 meta_opts: Arc<MetaOpts>,
181 hummock_compaction_event_handler: HummockCompactionEventHandler,
182 tx: Option<UnboundedSender<(HummockContextId, RequestEvent)>>,
183 ) -> Self {
184 Self {
185 meta_opts,
186 hummock_compaction_event_handler,
187 tx,
188 }
189 }
190}
191
192#[derive(Clone)]
193pub struct HummockCompactionEventHandler {
194 pub hummock_manager: Arc<HummockManager>,
195}
196
197impl HummockCompactionEventHandler {
198 pub fn new(hummock_manager: Arc<HummockManager>) -> Self {
199 Self { hummock_manager }
200 }
201
202 async fn handle_heartbeat(
203 &self,
204 context_id: HummockContextId,
205 progress: Vec<CompactTaskProgress>,
206 ) -> bool {
207 let mut compactor_alive = true;
208 let compactor_manager = self.hummock_manager.compactor_manager.clone();
209 let (mut cancel_tasks, mut untracked_tasks) =
210 compactor_manager.update_task_heartbeats(&progress);
211 if !cancel_tasks.is_empty() {
212 tracing::info!(
213 ?cancel_tasks,
214 %context_id,
215 "Tasks cancel has expired due to lack of visible progress",
216 );
217
218 if let Err(e) = self
219 .hummock_manager
220 .cancel_compact_tasks(cancel_tasks.clone(), TaskStatus::HeartbeatProgressCanceled)
221 .await
222 {
223 tracing::error!(
224 error = %e.as_report(),
225 "Attempt to remove compaction task due to elapsed heartbeat failed. We will continue to track its heartbeat
226 until we can successfully report its status."
227 );
228 }
229 }
230
231 cancel_tasks.append(&mut untracked_tasks);
234
235 match compactor_manager.get_compactor(context_id) {
236 Some(compactor) => {
237 if !cancel_tasks.is_empty() {
241 let _ = compactor.cancel_tasks(&cancel_tasks);
242 tracing::info!(
243 ?cancel_tasks,
244 %context_id,
245 "CancelTask operation has been sent to compactor node",
246 );
247 }
248 }
249 _ => {
250 compactor_alive = false;
253 }
254 }
255
256 compactor_alive
257 }
258
259 async fn handle_pull_task_event(
260 &self,
261 context_id: HummockContextId,
262 pull_task_count: usize,
263 compaction_selectors: &mut HashMap<TaskType, Box<dyn CompactionSelector>>,
264 max_get_task_probe_times: usize,
265 ) -> bool {
266 assert_ne!(0, pull_task_count);
267 let Some(compactor) = self
268 .hummock_manager
269 .compactor_manager
270 .get_compactor(context_id)
271 else {
272 return false;
273 };
274
275 self.try_dispatch_tasks(
277 &compactor,
278 pull_task_count,
279 compaction_selectors,
280 max_get_task_probe_times,
281 )
282 .await;
283
284 if let Err(e) = compactor.send_event(ResponseEvent::PullTaskAck(PullTaskAck {})) {
286 tracing::warn!(
287 error = %e.as_report(),
288 "Failed to send ack to {}",
289 context_id,
290 );
291 return false;
292 }
293
294 true
295 }
296
297 async fn try_dispatch_tasks(
302 &self,
303 compactor: &Arc<Compactor>,
304 pull_task_count: usize,
305 compaction_selectors: &mut HashMap<TaskType, Box<dyn CompactionSelector>>,
306 max_get_task_probe_times: usize,
307 ) {
308 let snapshot = self.hummock_manager.compaction_state.snapshot();
309 let Some((groups, task_type)) = snapshot.pick_compaction_groups_and_type() else {
310 return;
311 };
312
313 if let TaskType::Ttl = task_type {
314 match self
315 .hummock_manager
316 .metadata_manager
317 .get_all_table_options()
318 .await
319 .map_err(|err| Error::MetaStore(err.into()))
320 {
321 Ok(table_options) => {
322 self.hummock_manager
323 .update_table_id_to_table_option(table_options);
324 }
325 Err(err) => {
326 warn!(error = %err.as_report(), "Failed to get table options");
327 }
328 }
329 }
330
331 let selector: &mut Box<dyn CompactionSelector> =
332 compaction_selectors.get_mut(&task_type).unwrap();
333
334 let mut generated_task_count = 0;
335 let mut existed_groups = groups.clone();
336 let mut no_task_groups: HashSet<CompactionGroupId> = HashSet::default();
337 let mut failed_tasks = vec![];
338 let mut loop_times = 0;
339
340 while generated_task_count < pull_task_count
341 && failed_tasks.is_empty()
342 && loop_times < max_get_task_probe_times
343 {
344 loop_times += 1;
345 let compact_ret = self
346 .hummock_manager
347 .get_compact_tasks(
348 compactor.context_id(),
349 existed_groups.clone(),
350 pull_task_count - generated_task_count,
351 &mut **selector,
352 )
353 .await;
354
355 match compact_ret {
356 Ok((compact_tasks, unschedule_groups)) => {
357 no_task_groups.extend(unschedule_groups);
358 if compact_tasks.is_empty() {
359 break;
360 }
361 generated_task_count += compact_tasks.len();
362 for task in compact_tasks {
363 let task_id = task.task_id;
364 if let Err(e) =
365 compactor.send_event(ResponseEvent::CompactTask(task.into()))
366 {
367 tracing::warn!(
368 error = %e.as_report(),
369 "Failed to send task {} to {}",
370 task_id,
371 compactor.context_id(),
372 );
373 failed_tasks.push(task_id);
374 }
375 }
376 if !failed_tasks.is_empty() {
377 self.hummock_manager
378 .compactor_manager
379 .remove_compactor(compactor.context_id());
380 }
381 existed_groups.retain(|group_id| !no_task_groups.contains(group_id));
382 }
383 Err(err) => {
384 tracing::warn!(error = %err.as_report(), "Failed to get compaction task");
385 break;
386 }
387 };
388 }
389 #[cfg(test)]
390 scheduling_tests::before_unschedule().await;
391 for group in no_task_groups {
392 self.hummock_manager.compaction_state.unschedule(
393 group,
394 task_type,
395 snapshot.generation(),
396 );
397 }
398 if let Err(err) = self
399 .hummock_manager
400 .cancel_compact_tasks(failed_tasks, TaskStatus::SendFailCanceled)
401 .await
402 {
403 tracing::warn!(error = %err.as_report(), "Failed to cancel compaction task");
404 }
405 }
406
407 async fn handle_report_task_event(&self, report_events: Vec<ReportTask>) -> Result<()> {
408 if let Err(e) = self
409 .hummock_manager
410 .report_compact_tasks(report_events)
411 .await
412 {
413 tracing::error!(error = %e.as_report(), "report compact_tack fail")
414 }
415 Ok(())
416 }
417}
418
419impl<D: CompactionEventDispatcher<EventType = E::EventType>, E: CompactorStreamEvent>
420 CompactionEventLoop<D, E>
421{
422 pub fn new(
423 hummock_compactor_dispatcher: D,
424 metrics: Arc<MetaMetrics>,
425 compactor_streams_change_rx: UnboundedReceiver<(HummockContextId, Streaming<E>)>,
426 ) -> Self {
427 Self {
428 hummock_compactor_dispatcher,
429 metrics,
430 compactor_streams_change_rx,
431 }
432 }
433
434 pub fn run(mut self) -> (JoinHandle<()>, Sender<()>) {
435 let mut compactor_request_streams = FuturesUnordered::new();
436 let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
437 let shutdown_rx_shared = shutdown_rx.shared();
438
439 let join_handle = tokio::spawn(async move {
440 let mut stream_generations = HashMap::<HummockContextId, u64>::new();
444 let push_stream =
445 |context_id: HummockContextId,
446 stream_generation: u64,
447 stream: Streaming<E>,
448 compactor_request_streams: &mut FuturesUnordered<_>| {
449 let future = StreamExt::into_future(stream)
450 .map(move |stream_future| (context_id, stream_generation, stream_future));
451
452 compactor_request_streams.push(future);
453 };
454
455 let mut event_loop_iteration_now = Instant::now();
456
457 loop {
458 let shutdown_rx_shared = shutdown_rx_shared.clone();
459 self.metrics
460 .compaction_event_loop_iteration_latency
461 .observe(event_loop_iteration_now.elapsed().as_millis() as _);
462 event_loop_iteration_now = Instant::now();
463
464 tokio::select! {
465 _ = shutdown_rx_shared => { return; },
466
467 compactor_stream = self.compactor_streams_change_rx.recv() => {
468 if let Some((context_id, stream)) = compactor_stream {
469 tracing::info!("compactor {} enters the cluster", context_id);
470 let stream_generation = stream_generations
471 .entry(context_id)
472 .and_modify(|generation| *generation += 1)
473 .or_insert(1);
474 push_stream(
475 context_id,
476 *stream_generation,
477 stream,
478 &mut compactor_request_streams,
479 );
480 }
481 },
482
483 result = pending_on_none(compactor_request_streams.next()) => {
484 let (context_id, stream_generation, compactor_stream_req): (_, _, (std::option::Option<std::result::Result<E, _>>, _)) = result;
485 let Some(current_generation) = stream_generations.get(&context_id).copied() else {
486 continue;
487 };
488 if current_generation != stream_generation {
489 continue;
493 }
494 let (event, create_at, stream) = match compactor_stream_req {
495 (Some(Ok(req)), stream) => {
496 let create_at = req.create_at();
497 let event = req.take_event();
498 (event, create_at, stream)
499 }
500
501 (Some(Err(err)), _stream) => {
502 tracing::warn!(error = %err.as_report(), %context_id, "compactor stream poll with err, recv stream may be destroyed");
503 self.hummock_compactor_dispatcher.remove_compactor(context_id);
504 continue
505 }
506
507 _ => {
508 tracing::warn!(%context_id, "compactor stream poll err, recv stream may be destroyed");
510 self.hummock_compactor_dispatcher.remove_compactor(context_id);
511 continue
512 },
513 };
514
515 {
516 let consumed_latency_ms = SystemTime::now()
517 .duration_since(std::time::UNIX_EPOCH)
518 .expect("Clock may have gone backwards")
519 .as_millis()
520 as u64
521 - create_at;
522 self.metrics
523 .compaction_event_consumed_latency
524 .observe(consumed_latency_ms as _);
525 }
526
527 let mut compactor_alive = true;
528 if self
529 .hummock_compactor_dispatcher
530 .should_forward(&event)
531 {
532 if let Err(e) = self
533 .hummock_compactor_dispatcher
534 .on_event_remotely(context_id, event)
535 .await
536 {
537 tracing::warn!(error = %e.as_report(), "Failed to forward event");
538 }
539 } else {
540 compactor_alive = self.hummock_compactor_dispatcher.on_event_locally(
541 context_id,
542 event,
543 ).await;
544 }
545
546 if compactor_alive {
547 push_stream(
548 context_id,
549 stream_generation,
550 stream,
551 &mut compactor_request_streams,
552 );
553 } else {
554 tracing::warn!(%context_id, "compactor stream error, send stream may be destroyed");
555 self
556 .hummock_compactor_dispatcher
557 .remove_compactor(context_id);
558 }
559 },
560 }
561 }
562 });
563
564 (join_handle, shutdown_tx)
565 }
566}
567
568impl CompactorStreamEvent for SubscribeCompactionEventRequest {
569 type EventType = RequestEvent;
570
571 fn take_event(self) -> Self::EventType {
572 self.event.unwrap()
573 }
574
575 fn create_at(&self) -> u64 {
576 self.create_at
577 }
578}
579
580pub struct HummockCompactorDedicatedEventLoop {
581 hummock_manager: Arc<HummockManager>,
582 hummock_compaction_event_handler: HummockCompactionEventHandler,
583}
584
585impl HummockCompactorDedicatedEventLoop {
586 pub fn new(
587 hummock_manager: Arc<HummockManager>,
588 hummock_compaction_event_handler: HummockCompactionEventHandler,
589 ) -> Self {
590 Self {
591 hummock_manager,
592 hummock_compaction_event_handler,
593 }
594 }
595
596 async fn compact_task_dedicated_event_handler(
598 &self,
599 mut rx: UnboundedReceiver<(HummockContextId, RequestEvent)>,
600 shutdown_rx: OneShotReceiver<()>,
601 ) {
602 let mut compaction_selectors = init_selectors();
603
604 tokio::select! {
605 _ = shutdown_rx => {}
606
607 _ = async {
608 while let Some((context_id, event)) = rx.recv().await {
609 let mut report_events = vec![];
610 let mut skip_times = 0;
611 match event {
612 RequestEvent::PullTask(PullTask { pull_task_count }) => {
613 self.hummock_compaction_event_handler.handle_pull_task_event(context_id, pull_task_count as usize, &mut compaction_selectors, self.hummock_manager.env.opts.max_get_task_probe_times).await;
614 }
615
616 RequestEvent::ReportTask(task) => {
617 report_events.push(task.into());
618 }
619
620 _ => unreachable!(),
621 }
622 while let Ok((context_id, event)) = rx.try_recv() {
623 match event {
624 RequestEvent::PullTask(PullTask { pull_task_count }) => {
625 self.hummock_compaction_event_handler.handle_pull_task_event(context_id, pull_task_count as usize, &mut compaction_selectors, self.hummock_manager.env.opts.max_get_task_probe_times).await;
626 if !report_events.is_empty() {
627 if skip_times > MAX_SKIP_TIMES {
628 break;
629 }
630 skip_times += 1;
631 }
632 }
633
634 RequestEvent::ReportTask(task) => {
635 report_events.push(task.into());
636 if report_events.len() >= MAX_REPORT_COUNT {
637 break;
638 }
639 }
640 _ => unreachable!(),
641 }
642 }
643 if !report_events.is_empty()
644 && let Err(e) = self.hummock_compaction_event_handler.handle_report_task_event(report_events).await
645 {
646 tracing::error!(error = %e.as_report(), "report compact_tack fail")
647 }
648 }
649 } => {}
650 }
651 }
652
653 pub fn run(
654 self,
655 ) -> (
656 JoinHandle<()>,
657 UnboundedSender<(HummockContextId, RequestEvent)>,
658 Sender<()>,
659 ) {
660 let (tx, rx) = unbounded_channel();
661 let (shutdon_tx, shutdown_rx) = tokio::sync::oneshot::channel();
662 let join_handler = tokio::spawn(async move {
663 self.compact_task_dedicated_event_handler(rx, shutdown_rx)
664 .await;
665 });
666 (join_handler, tx, shutdon_tx)
667 }
668}
669
670pub struct IcebergCompactionEventHandler {
671 compaction_manager: IcebergCompactionManagerRef,
672}
673
674impl IcebergCompactionEventHandler {
675 pub fn new(compaction_manager: IcebergCompactionManagerRef) -> Self {
676 Self { compaction_manager }
677 }
678
679 async fn handle_pull_task_event(
680 &self,
681 context_id: HummockContextId,
682 pull_task_count: usize,
683 ) -> bool {
684 assert_ne!(0, pull_task_count);
685 if let Some(compactor) = self
686 .compaction_manager
687 .iceberg_compactor_manager
688 .get_compactor(context_id)
689 {
690 let mut compactor_alive = true;
691
692 let iceberg_compaction_handles = self
693 .compaction_manager
694 .get_top_n_iceberg_commit_sink_ids(pull_task_count);
695
696 for handle in iceberg_compaction_handles {
697 let compactor = compactor.clone();
698 if let Err(e) = async move {
700 handle
701 .send_compact_task(
702 compactor,
703 next_compaction_task_id(&self.compaction_manager.env)
704 .await?
705 .into(),
706 )
707 .await
708 }
709 .await
710 {
711 tracing::warn!(
712 error = %e.as_report(),
713 "Failed to send iceberg commit task to {}",
714 context_id,
715 );
716 compactor_alive = false;
717 }
718 }
719
720 if let Err(e) =
721 compactor.send_event(IcebergResponseEvent::PullTaskAck(IcebergPullTaskAck {}))
722 {
723 tracing::warn!(
724 error = %e.as_report(),
725 "Failed to send ask to {}",
726 context_id,
727 );
728 compactor_alive = false;
729 }
730
731 return compactor_alive;
732 }
733
734 false
735 }
736
737 fn apply_report_task_event(&self, report: IcebergReportTask) {
738 self.compaction_manager.handle_report_task(report);
739 }
740}
741
742pub struct IcebergCompactionEventDispatcher {
743 compaction_event_handler: IcebergCompactionEventHandler,
744}
745
746#[async_trait::async_trait]
747impl CompactionEventDispatcher for IcebergCompactionEventDispatcher {
748 type EventType = IcebergRequestEvent;
749
750 async fn on_event_locally(&self, context_id: HummockContextId, event: Self::EventType) -> bool {
751 match event {
752 IcebergRequestEvent::PullTask(IcebergPullTask { pull_task_count }) => {
753 return self
754 .compaction_event_handler
755 .handle_pull_task_event(context_id, pull_task_count as usize)
756 .await;
757 }
758 IcebergRequestEvent::ReportTask(report) => {
759 self.compaction_event_handler
760 .apply_report_task_event(report);
761 return true;
762 }
763 _ => unreachable!(),
764 }
765 }
766
767 async fn on_event_remotely(
768 &self,
769 _context_id: HummockContextId,
770 _event: Self::EventType,
771 ) -> Result<()> {
772 unreachable!()
773 }
774
775 fn should_forward(&self, _event: &Self::EventType) -> bool {
776 false
777 }
778
779 fn remove_compactor(&self, context_id: HummockContextId) {
780 self.compaction_event_handler
781 .compaction_manager
782 .iceberg_compactor_manager
783 .remove_compactor(context_id);
784 }
785}
786
787impl IcebergCompactionEventDispatcher {
788 pub fn new(compaction_event_handler: IcebergCompactionEventHandler) -> Self {
789 Self {
790 compaction_event_handler,
791 }
792 }
793}
794
795impl CompactorStreamEvent for SubscribeIcebergCompactionEventRequest {
796 type EventType = IcebergRequestEvent;
797
798 fn take_event(self) -> Self::EventType {
799 self.event.unwrap()
800 }
801
802 fn create_at(&self) -> u64 {
803 self.create_at
804 }
805}
806
807#[cfg(test)]
808mod scheduling_tests {
809 use std::time::Duration;
810
811 use risingwave_hummock_sdk::{LocalSstableInfo, SyncResult};
812 use risingwave_meta_model::compaction_task;
813 use risingwave_rpc_client::HummockMetaClient;
814 use sea_orm::EntityTrait;
815
816 use super::*;
817 use crate::hummock::MockHummockMetaClient;
818 use crate::hummock::compaction::selector::{
819 ManualCompactionOption, default_compaction_selector,
820 };
821 use crate::hummock::manager::compaction::ScheduleTrigger;
822 use crate::hummock::manager::tests::{gen_sstable_info, setup_compute_env_with_meta_opts};
823 use crate::hummock::model::ext::compaction_task_model_to_assignment;
824
825 tokio::task_local! {
826 static BEFORE_UNSCHEDULE: Arc<tokio::sync::Barrier>;
827 }
828
829 pub(super) async fn before_unschedule() {
830 if let Ok(barrier) = BEFORE_UNSCHEDULE.try_with(Arc::clone) {
832 barrier.wait().await;
833 barrier.wait().await;
834 }
835 }
836
837 async fn dispatch(manager: Arc<HummockManager>) -> Vec<risingwave_pb::hummock::CompactTask> {
839 let mut receiver = manager.compactor_manager.add_compactor(99.into());
840 let compactor = manager.compactor_manager.get_compactor(99.into()).unwrap();
841 let mut selectors = HashMap::from([(TaskType::Dynamic, default_compaction_selector())]);
842 HummockCompactionEventHandler::new(manager)
843 .try_dispatch_tasks(&compactor, 8, &mut selectors, 1)
844 .await;
845 let mut tasks = vec![];
846 while let Ok(event) = receiver.try_recv() {
847 if let Some(ResponseEvent::CompactTask(task)) = event.unwrap().event {
848 tasks.push(task);
849 }
850 }
851 tasks
852 }
853
854 async fn fixture(deterministic: bool) -> (Arc<HummockManager>, MockHummockMetaClient) {
855 let mut opts = MetaOpts::test(false);
856 opts.compaction_deterministic_test = deterministic;
857 let (_, manager, _, worker_id) = setup_compute_env_with_meta_opts(80, opts).await;
858 manager
859 .register_table_ids_for_test(&[(100, 2.into()), (101, 2.into())])
860 .await
861 .unwrap();
862 let client = MockHummockMetaClient::new(manager.clone(), worker_id as _);
863 commit_ssts(&client, 30, 1).await;
864 (manager, client)
865 }
866
867 async fn commit_ssts(client: &MockHummockMetaClient, epoch: u64, first_sst: u64) {
868 client
869 .commit_epoch(
870 risingwave_common::util::epoch::test_epoch(epoch),
871 SyncResult {
872 uncommitted_ssts: (first_sst..first_sst + 4)
873 .map(|id| LocalSstableInfo {
874 sst_info: gen_sstable_info(
875 id,
876 vec![100, 101],
877 risingwave_common::util::epoch::test_epoch(epoch - 10),
878 ),
879 table_stats: Default::default(),
880 created_at: u64::MAX,
881 })
882 .collect(),
883 ..Default::default()
884 },
885 )
886 .await
887 .unwrap();
888 }
889
890 async fn assert_task_assignee(
891 manager: &HummockManager,
892 task_id: u64,
893 context_id: HummockContextId,
894 ) {
895 let assignment = manager
896 .compaction_task_from_assignment_for_test(task_id)
897 .await
898 .unwrap();
899 assert_eq!(assignment.context_id, context_id);
900
901 let model = compaction_task::Entity::find_by_id(task_id as i64)
902 .one(&manager.env.meta_store_ref().conn)
903 .await
904 .unwrap()
905 .unwrap();
906 assert_eq!(model.context_id, context_id);
907 let restored_assignment = compaction_task_model_to_assignment(model.clone());
908 assert_eq!(restored_assignment.context_id, context_id);
909 let protobuf_assignment: risingwave_pb::hummock::CompactTaskAssignment = model.into();
910 assert_eq!(protobuf_assignment.context_id, context_id);
911
912 let (_, assignments) = manager.list_compaction_status().await;
913 let assignment = assignments
914 .iter()
915 .find(|a| a.compact_task.as_ref().unwrap().task_id == task_id)
916 .unwrap();
917 assert_eq!(assignment.context_id, context_id);
918 }
919
920 #[tokio::test]
921 async fn test_assignment_records_compactor_for_pulled_tasks() {
922 let (manager, _) = fixture(false).await;
923 let tasks = dispatch(manager.clone()).await;
924 assert!(!tasks.is_empty());
925 for task in tasks {
926 assert_task_assignee(&manager, task.task_id, 99.into()).await;
927 }
928 }
929
930 #[tokio::test]
931 async fn test_assignment_records_compactor_for_manual_tasks() {
932 let (manager, _) = fixture(false).await;
933 let context_id = 77.into();
934 let mut receiver = manager.compactor_manager.add_compactor(context_id);
935 let manual_manager = manager.clone();
936 let trigger = tokio::spawn(async move {
937 manual_manager
938 .trigger_manual_compaction(
939 2.into(),
940 ManualCompactionOption {
941 level: 0,
942 ..Default::default()
943 },
944 )
945 .await
946 });
947 let response = tokio::time::timeout(Duration::from_secs(10), receiver.recv())
948 .await
949 .unwrap()
950 .unwrap()
951 .unwrap();
952 let Some(ResponseEvent::CompactTask(task)) = response.event else {
953 panic!("expected a manual compaction task");
954 };
955 assert_task_assignee(&manager, task.task_id, context_id).await;
956 assert!(
957 manager
958 .cancel_compact_task(task.task_id, TaskStatus::ManualCanceled)
959 .await
960 .unwrap()
961 );
962 trigger.await.unwrap().unwrap();
963 }
964
965 #[tokio::test]
966 async fn test_manual_cancellation_notifies_owner_and_retries_on_heartbeat() {
967 let (manager, _) = fixture(false).await;
968 let context_id = 99.into();
969 let mut receiver = manager.compactor_manager.add_compactor(context_id);
970 let mut other_receiver = manager.compactor_manager.add_compactor(100.into());
971 let task = manager
972 .get_compact_task(context_id, 2.into(), &mut *default_compaction_selector())
973 .await
974 .unwrap()
975 .unwrap();
976 let handler = HummockCompactionEventHandler::new(manager.clone());
977 let progress = CompactTaskProgress {
978 task_id: task.task_id,
979 num_progress_key: 1,
980 ..Default::default()
981 };
982
983 assert!(handler.handle_heartbeat(context_id, vec![progress]).await);
984 assert!(receiver.try_recv().is_err());
985
986 assert!(
988 manager
989 .cancel_compact_task(task.task_id, TaskStatus::ManualCanceled)
990 .await
991 .unwrap()
992 );
993 let event = receiver.try_recv().unwrap().unwrap().event.unwrap();
995 let ResponseEvent::CancelCompactTask(cancel) = event else {
996 panic!("expected compactor cancellation, got {event:?}");
997 };
998 assert_eq!(cancel.task_id, task.task_id);
999 assert_eq!(cancel.context_id, context_id);
1000 assert!(receiver.try_recv().is_err());
1001 assert!(other_receiver.try_recv().is_err());
1002 assert!(manager.compactor_manager.get_progress().is_empty());
1003 assert!(
1004 manager
1005 .compaction_task_from_assignment_for_test(task.task_id)
1006 .await
1007 .is_none()
1008 );
1009 let next_task = manager
1010 .get_compact_task(context_id, 2.into(), &mut *default_compaction_selector())
1011 .await
1012 .unwrap()
1013 .unwrap();
1014
1015 for num_progress_key in 1..=3 {
1018 if num_progress_key == 3 {
1019 receiver = manager.compactor_manager.add_compactor(context_id);
1020 }
1021 assert!(
1022 handler
1023 .handle_heartbeat(
1024 context_id,
1025 vec![
1026 progress,
1027 CompactTaskProgress {
1028 task_id: next_task.task_id,
1029 num_progress_key,
1030 ..Default::default()
1031 },
1032 ],
1033 )
1034 .await
1035 );
1036 let event = receiver.try_recv().unwrap().unwrap().event.unwrap();
1037 let ResponseEvent::CancelCompactTask(cancel) = event else {
1038 panic!("expected compactor cancellation, got {event:?}");
1039 };
1040 assert_eq!(cancel.task_id, task.task_id);
1041 assert_eq!(cancel.context_id, context_id);
1042 assert!(receiver.try_recv().is_err());
1043 let tracked = manager.compactor_manager.get_progress();
1044 assert_eq!(tracked.len(), 1);
1045 assert_eq!(tracked[0].task_id, next_task.task_id);
1046 }
1047
1048 assert!(
1050 !manager
1051 .report_compact_task(
1052 task.task_id,
1053 TaskStatus::Success,
1054 vec![],
1055 None,
1056 HashMap::default(),
1057 )
1058 .await
1059 .unwrap()
1060 );
1061 }
1062
1063 #[tokio::test]
1064 async fn test_batch_cancellation_notifies_each_owner_once() {
1065 let (manager, _) = fixture(false).await;
1066 let (left, mapping) = manager
1067 .move_state_tables_to_dedicated_compaction_group(2.into(), &[100.into()], None)
1068 .await
1069 .unwrap();
1070 let right = *mapping.keys().find(|&&id| id != left).unwrap();
1071 let left_context_id: HummockContextId = 77.into();
1072 let right_context_id: HummockContextId = 88.into();
1073 let mut left_receiver = manager.compactor_manager.add_compactor(left_context_id);
1074 let mut right_receiver = manager.compactor_manager.add_compactor(right_context_id);
1075 let left_task = manager
1076 .get_compact_task(left_context_id, left, &mut *default_compaction_selector())
1077 .await
1078 .unwrap()
1079 .unwrap();
1080 let right_task = manager
1081 .get_compact_task(right_context_id, right, &mut *default_compaction_selector())
1082 .await
1083 .unwrap()
1084 .unwrap();
1085
1086 let results = manager
1087 .cancel_compact_tasks(
1088 vec![
1089 left_task.task_id,
1090 u64::MAX,
1091 right_task.task_id,
1092 left_task.task_id,
1093 ],
1094 TaskStatus::ManualCanceled,
1095 )
1096 .await
1097 .unwrap();
1098 assert_eq!(results, vec![true, false, true, false]);
1099 for (receiver, task_id, context_id) in [
1100 (&mut left_receiver, left_task.task_id, left_context_id),
1101 (&mut right_receiver, right_task.task_id, right_context_id),
1102 ] {
1103 let event = receiver.try_recv().unwrap().unwrap().event.unwrap();
1104 let ResponseEvent::CancelCompactTask(cancel) = event else {
1105 panic!("expected compactor cancellation, got {event:?}");
1106 };
1107 assert_eq!(cancel.task_id, task_id);
1108 assert_eq!(cancel.context_id, context_id);
1109 assert!(receiver.try_recv().is_err());
1110 }
1111 assert!(manager.compactor_manager.get_progress().is_empty());
1112 }
1113
1114 #[tokio::test]
1115 async fn test_failed_cancellation_notification_retries_after_reconnect() {
1116 let (manager, _) = fixture(false).await;
1117 let context_id = 99.into();
1118 let receiver = manager.compactor_manager.add_compactor(context_id);
1119 let task = manager
1120 .get_compact_task(context_id, 2.into(), &mut *default_compaction_selector())
1121 .await
1122 .unwrap()
1123 .unwrap();
1124 drop(receiver);
1125
1126 assert!(
1128 manager
1129 .cancel_compact_task(task.task_id, TaskStatus::ManualCanceled)
1130 .await
1131 .unwrap()
1132 );
1133 assert!(manager.compactor_manager.get_progress().is_empty());
1134
1135 let mut receiver = manager.compactor_manager.add_compactor(context_id);
1136 assert!(
1137 HummockCompactionEventHandler::new(manager)
1138 .handle_heartbeat(
1139 context_id,
1140 vec![CompactTaskProgress {
1141 task_id: task.task_id,
1142 ..Default::default()
1143 }],
1144 )
1145 .await
1146 );
1147 let event = receiver.try_recv().unwrap().unwrap().event.unwrap();
1148 let ResponseEvent::CancelCompactTask(cancel) = event else {
1149 panic!("expected compactor cancellation, got {event:?}");
1150 };
1151 assert_eq!(cancel.task_id, task.task_id);
1152 assert_eq!(cancel.context_id, context_id);
1153 assert!(receiver.try_recv().is_err());
1154 }
1155
1156 #[tokio::test]
1157 async fn test_commit_after_no_task_preserves_candidate() {
1158 let (manager, client) = fixture(false).await;
1159 assert!(!dispatch(manager.clone()).await.is_empty());
1161 let barrier = Arc::new(tokio::sync::Barrier::new(2));
1162 let commit = async {
1163 barrier.wait().await;
1164 commit_ssts(&client, 40, 5).await;
1165 barrier.wait().await;
1166 };
1167 let (old_tasks, ()) = tokio::time::timeout(Duration::from_secs(10), async {
1168 tokio::join!(
1169 BEFORE_UNSCHEDULE.scope(barrier.clone(), dispatch(manager.clone())),
1170 commit,
1171 )
1172 })
1173 .await
1174 .expect("picker and commit must finish without holding each other's locks");
1175 assert!(
1176 old_tasks.is_empty(),
1177 "the paused picker must have found no task"
1178 );
1179 assert!(
1180 manager
1181 .compaction_state
1182 .snapshot()
1183 .scheduled
1184 .contains(&(2.into(), TaskType::Dynamic))
1185 );
1186 let tasks = dispatch(manager.clone()).await;
1187 assert!(
1188 tasks.iter().any(|task| task
1189 .input_ssts
1190 .iter()
1191 .any(|level| { level.table_infos.iter().any(|sst| sst.sst_id >= 5.into()) })),
1192 "the next dispatch must select the newly committed SSTs"
1193 );
1194 assert!(dispatch(manager.clone()).await.is_empty());
1196 assert!(!manager.compaction_state.try_sched_compaction(
1197 2.into(),
1198 TaskType::Dynamic,
1199 ScheduleTrigger::Periodic,
1200 ));
1201 }
1202
1203 #[tokio::test]
1204 async fn test_split_schedules_children_without_commit_or_timer() {
1205 let (manager, _) = fixture(false).await;
1206 let snapshot = manager.compaction_state.snapshot();
1207 manager
1208 .compaction_state
1209 .unschedule(2.into(), TaskType::Dynamic, snapshot.generation());
1210 manager
1211 .move_state_tables_to_dedicated_compaction_group(2.into(), &[100.into()], None)
1212 .await
1213 .unwrap();
1214 let tasks = dispatch(manager.clone()).await;
1215 let groups: HashSet<_> = tasks.iter().map(|task| task.compaction_group_id).collect();
1216 let version = manager.get_current_version().await;
1217 for table in [100, 101] {
1218 let group = version.state_table_info.info()
1219 [&risingwave_common::catalog::TableId::new(table)]
1220 .compaction_group_id;
1221 assert!(
1222 groups.contains(&group),
1223 "split group {group} did not reach the picker"
1224 );
1225 }
1226 }
1227
1228 #[tokio::test]
1229 async fn test_merge_wakes_cooled_survivor_without_commit() {
1230 let (manager, _) = fixture(false).await;
1231 let (left, mapping) = manager
1232 .move_state_tables_to_dedicated_compaction_group(2.into(), &[100.into()], None)
1233 .await
1234 .unwrap();
1235 let right = *mapping.keys().find(|&&id| id != left).unwrap();
1236 let pending = manager
1238 .get_compact_task(99.into(), left, &mut *default_compaction_selector())
1239 .await
1240 .unwrap()
1241 .unwrap();
1242 dispatch(manager.clone()).await;
1243 assert!(
1244 manager
1245 .compaction_state
1246 .inner
1247 .lock()
1248 .dynamic_cooldown
1249 .contains(&left)
1250 );
1251 assert!(!manager.compaction_state.try_sched_compaction(
1252 left,
1253 TaskType::Dynamic,
1254 ScheduleTrigger::Periodic
1255 ));
1256 manager
1257 .merge_compaction_group_for_test(left, right, HashSet::from([100.into(), 101.into()]))
1258 .await
1259 .unwrap();
1260 let tasks = dispatch(manager.clone()).await;
1261 assert!(
1262 tasks
1263 .iter()
1264 .any(|task| task.compaction_group_id == left && task.task_id != pending.task_id),
1265 "merged SSTs must reach the picker without another commit"
1266 );
1267 }
1268
1269 #[tokio::test]
1270 async fn test_merge_cancellation_does_not_reschedule_deleted_group() {
1271 for task_type in [TaskType::Dynamic, TaskType::Emergency] {
1272 let (manager, _) = fixture(false).await;
1273 let (left, mapping) = manager
1274 .move_state_tables_to_dedicated_compaction_group(2.into(), &[100.into()], None)
1275 .await
1276 .unwrap();
1277 let right = *mapping.keys().find(|&&id| id != left).unwrap();
1278 let task = manager
1279 .get_compact_task(99.into(), right, &mut *default_compaction_selector())
1280 .await
1281 .unwrap()
1282 .unwrap();
1283 manager
1285 .compaction
1286 .write()
1287 .await
1288 .compact_task_assignment
1289 .get_mut(&task.task_id)
1290 .unwrap()
1291 .compact_task
1292 .task_type = task_type;
1293 for kind in [
1294 TaskType::Dynamic,
1295 TaskType::Emergency,
1296 TaskType::Ttl,
1297 TaskType::SpaceReclaim,
1298 TaskType::Tombstone,
1299 TaskType::VnodeWatermark,
1300 ] {
1301 manager.compaction_state.try_sched_compaction(
1302 right,
1303 kind,
1304 ScheduleTrigger::NewData,
1305 );
1306 }
1307 let snapshot = manager.compaction_state.snapshot();
1308 manager
1309 .merge_compaction_group_for_test(
1310 left,
1311 right,
1312 HashSet::from([100.into(), 101.into()]),
1313 )
1314 .await
1315 .unwrap();
1316 assert!(
1317 !manager
1318 .compaction_state
1319 .snapshot()
1320 .scheduled
1321 .iter()
1322 .any(|(id, _)| *id == right)
1323 );
1324 manager
1326 .compaction_state
1327 .unschedule(right, TaskType::Dynamic, snapshot.generation());
1328 assert!(
1329 !manager
1330 .compaction_state
1331 .inner
1332 .lock()
1333 .dynamic_cooldown
1334 .contains(&right)
1335 );
1336 let (tasks, _) = manager
1338 .get_compact_tasks(
1339 99.into(),
1340 vec![right],
1341 1,
1342 &mut *default_compaction_selector(),
1343 )
1344 .await
1345 .unwrap();
1346 assert!(tasks.is_empty());
1347 manager
1348 .trigger_compaction_deterministic(
1349 manager.get_current_version().await.id,
1350 vec![right],
1351 )
1352 .await
1353 .unwrap();
1354 assert!(
1355 !manager
1356 .compaction_state
1357 .snapshot()
1358 .scheduled
1359 .iter()
1360 .any(|(id, _)| *id == right)
1361 );
1362 }
1363 }
1364
1365 #[tokio::test]
1366 async fn test_normalization_schedules_all_affected_groups() {
1367 for deterministic in [false, true] {
1368 let mut opts = MetaOpts::test(false);
1369 opts.compaction_deterministic_test = deterministic;
1370 let (_, manager, _, _) = setup_compute_env_with_meta_opts(80, opts).await;
1371 manager
1372 .register_table_ids_for_test(&[(100, 2.into()), (102, 2.into()), (101, 3.into())])
1373 .await
1374 .unwrap();
1375 let old = manager.compaction_state.snapshot();
1376 assert_eq!(
1377 manager
1378 .normalize_overlapping_compaction_groups()
1379 .await
1380 .unwrap(),
1381 1
1382 );
1383 let version = manager.get_current_version().await;
1384 for table in [100, 102] {
1385 let group = version.state_table_info.info()
1386 [&risingwave_common::catalog::TableId::new(table)]
1387 .compaction_group_id;
1388 manager
1390 .compaction_state
1391 .unschedule(group, TaskType::Dynamic, old.generation());
1392 assert_eq!(
1393 manager
1394 .compaction_state
1395 .snapshot()
1396 .scheduled
1397 .contains(&(group, TaskType::Dynamic)),
1398 !deterministic
1399 );
1400 }
1401 }
1402 }
1403
1404 #[tokio::test]
1405 async fn test_topology_changes_respect_deterministic_mode() {
1406 let (manager, _) = fixture(true).await;
1407 let (left, mapping) = manager
1408 .move_state_tables_to_dedicated_compaction_group(2.into(), &[100.into()], None)
1409 .await
1410 .unwrap();
1411 assert!(manager.compaction_state.snapshot().scheduled.is_empty());
1412 let right = *mapping.keys().find(|&&id| id != left).unwrap();
1413 manager
1414 .merge_compaction_group_for_test(left, right, HashSet::from([100.into(), 101.into()]))
1415 .await
1416 .unwrap();
1417 assert!(manager.compaction_state.snapshot().scheduled.is_empty());
1418 }
1419}