Skip to main content

risingwave_meta/hummock/manager/
gc.rs

1// Copyright 2022 RisingWave Labs
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::cmp;
16use std::collections::{HashMap, HashSet};
17use std::ops::DerefMut;
18use std::sync::atomic::{AtomicBool, Ordering};
19use std::time::{Duration, Instant, SystemTime};
20
21use chrono::DateTime;
22use futures::future::try_join_all;
23use futures::{StreamExt, TryStreamExt, future};
24use itertools::Itertools;
25use risingwave_common::catalog::TableId;
26use risingwave_common::system_param::reader::SystemParamsRead;
27use risingwave_common::util::epoch::Epoch;
28use risingwave_hummock_sdk::{
29    HummockEpoch, HummockObjectId, HummockRawObjectId, VALID_OBJECT_ID_SUFFIXES,
30    get_object_data_path, get_object_id_from_path,
31};
32use risingwave_meta_model::hummock_sequence::HUMMOCK_NOW;
33use risingwave_meta_model::{hummock_gc_history, hummock_sequence, hummock_version_delta};
34use risingwave_meta_model_migration::OnConflict;
35use risingwave_object_store::object::{ObjectMetadataIter, ObjectStoreRef};
36use risingwave_pb::stream_service::GetMinUncommittedObjectIdRequest;
37use risingwave_rpc_client::StreamClientPool;
38use sea_orm::{ActiveValue, ColumnTrait, EntityTrait, QueryFilter, Set};
39
40use crate::MetaResult;
41use crate::backup_restore::BackupManagerRef;
42use crate::hummock::HummockManager;
43use crate::hummock::error::{Error, Result};
44use crate::manager::MetadataManager;
45
46pub(super) mod change_log_retention;
47
48use change_log_retention::ChangeLogObjectRetention;
49
50pub(crate) struct GcManager {
51    pub(super) change_log_retention: ChangeLogObjectRetention,
52    store: ObjectStoreRef,
53    path_prefix: String,
54    use_new_object_prefix_strategy: bool,
55    /// These objects may still be used by backup or time travel.
56    may_delete_object_ids: parking_lot::Mutex<HashSet<HummockObjectId>>,
57}
58
59impl GcManager {
60    pub fn new(
61        store: ObjectStoreRef,
62        path_prefix: &str,
63        use_new_object_prefix_strategy: bool,
64    ) -> Self {
65        Self {
66            store,
67            path_prefix: path_prefix.to_owned(),
68            use_new_object_prefix_strategy,
69            may_delete_object_ids: Default::default(),
70            change_log_retention: Default::default(),
71        }
72    }
73
74    /// Deletes all objects specified in the given list of IDs from storage.
75    pub async fn delete_objects(
76        &self,
77        object_id_list: impl Iterator<Item = HummockObjectId>,
78    ) -> Result<()> {
79        let mut paths = Vec::with_capacity(1000);
80        for object_id in object_id_list {
81            let obj_prefix = self.store.get_object_prefix(
82                object_id.as_raw().as_raw_id(),
83                self.use_new_object_prefix_strategy,
84            );
85            paths.push(get_object_data_path(
86                &obj_prefix,
87                &self.path_prefix,
88                object_id,
89            ));
90        }
91        self.store.delete_objects(&paths).await?;
92        Ok(())
93    }
94
95    async fn list_object_metadata_from_object_store(
96        &self,
97        prefix: Option<String>,
98    ) -> Result<ObjectMetadataIter> {
99        let list_path = format!("{}/{}", self.path_prefix, prefix.unwrap_or("".into()));
100        let raw_iter = self.store.list(&list_path).await?;
101        let valid_suffixes = VALID_OBJECT_ID_SUFFIXES.map(|suffix| format!(".{}", suffix));
102        let iter = raw_iter.filter(move |r| match r {
103            Ok(i) => future::ready(valid_suffixes.iter().any(|suffix| i.key.ends_with(suffix))),
104            Err(_) => future::ready(true),
105        });
106        Ok(Box::pin(iter))
107    }
108
109    /// Consumes a batch from the same listing, preserving the backend's pagination state.
110    /// Returns object ids filtered by retention, and the batch's count and size before that filter.
111    async fn list_objects_batch(
112        metadata_iter: &mut ObjectMetadataIter,
113        object_retention_watermark: u64,
114        limit: usize,
115    ) -> Result<(HashSet<HummockObjectId>, u64, u64)> {
116        let mut total_object_count = 0;
117        let mut total_object_size = 0;
118        let filtered = metadata_iter
119            .by_ref()
120            .take(limit)
121            .filter_map(|r| {
122                let result = match r {
123                    Ok(o) => {
124                        total_object_count += 1;
125                        total_object_size += o.total_size;
126                        if o.last_modified < object_retention_watermark as f64 {
127                            Some(Ok(get_object_id_from_path(&o.key)))
128                        } else {
129                            None
130                        }
131                    }
132                    Err(e) => Some(Err(Error::ObjectStore(e))),
133                };
134                async move { result }
135            })
136            .try_collect::<HashSet<HummockObjectId>>()
137            .await?;
138        Ok((filtered, total_object_count, total_object_size as u64))
139    }
140
141    pub fn add_may_delete_object_ids(
142        &self,
143        may_delete_object_ids: impl Iterator<Item = HummockObjectId>,
144    ) {
145        self.may_delete_object_ids
146            .lock()
147            .extend(may_delete_object_ids);
148    }
149
150    /// Takes if `least_count` elements available.
151    pub fn try_take_may_delete_object_ids(
152        &self,
153        least_count: usize,
154    ) -> Option<HashSet<HummockObjectId>> {
155        let mut guard = self.may_delete_object_ids.lock();
156        if guard.len() < least_count {
157            None
158        } else {
159            Some(std::mem::take(&mut *guard))
160        }
161    }
162}
163
164impl HummockManager {
165    /// Deletes version deltas.
166    ///
167    /// Returns number of deleted deltas
168    pub async fn delete_version_deltas(&self) -> Result<usize> {
169        let mut versioning_guard = self
170            .versioning
171            .write_with_process_name("delete_version_deltas")
172            .await;
173        let versioning = versioning_guard.deref_mut();
174        let context_info = self
175            .context_info
176            .read_with_process_name("delete_version_deltas")
177            .await;
178        // If there is any safe point, skip this to ensure meta backup has required delta logs to
179        // replay version.
180        if !context_info.version_safe_points.is_empty() {
181            return Ok(0);
182        }
183        // The context_info lock must be held to prevent any potential metadata backup.
184        // The lock order requires version lock to be held as well.
185        let version_id = versioning.checkpoint.version.id;
186        let res = hummock_version_delta::Entity::delete_many()
187            .filter(hummock_version_delta::Column::Id.lte(version_id))
188            .exec(&self.env.meta_store_ref().conn)
189            .await?;
190        tracing::debug!(rows_affected = res.rows_affected, "Deleted version deltas");
191        versioning
192            .hummock_version_deltas
193            .retain(|id, _| *id > version_id);
194        #[cfg(test)]
195        {
196            drop(context_info);
197            drop(versioning_guard);
198            self.check_state_consistency().await;
199        }
200        Ok(res.rows_affected as usize)
201    }
202
203    /// Filters by Hummock version and Writes GC history.
204    pub async fn finalize_objects_to_delete(
205        &self,
206        object_ids: impl Iterator<Item = HummockObjectId>,
207    ) -> Result<Vec<HummockObjectId>> {
208        // This lock ensures `commit_epoch` and `report_compat_task` can see the latest GC history during sanity check.
209        let versioning = self
210            .versioning
211            .read_with_process_name("finalize_objects_to_delete")
212            .await;
213        let min_pinned_version_id = self
214            .context_info
215            .read_with_process_name("finalize_objects_to_delete")
216            .await
217            .min_pinned_version_id();
218        let mut tracked_object_ids: HashSet<HummockObjectId> =
219            versioning.get_tracked_object_ids(min_pinned_version_id);
220        tracked_object_ids.extend(self.gc_manager.change_log_retention.objects());
221        let to_delete = object_ids
222            .filter(|object_id| !tracked_object_ids.contains(object_id))
223            .collect_vec();
224        // Even an empty batch must advance the persisted GC clock and expire old history
225        // when GC history is enabled.
226        self.write_gc_history(to_delete.iter().copied()).await?;
227        Ok(to_delete)
228    }
229
230    /// LIST object store and DELETE stale objects, in batches.
231    /// GC can be very slow. Spawn a dedicated tokio task for it.
232    pub async fn start_full_gc(
233        &self,
234        object_retention_time: Duration,
235        prefix: Option<String>,
236        backup_manager: Option<BackupManagerRef>,
237    ) -> Result<()> {
238        if !self.full_gc_state.try_start() {
239            return Err(anyhow::anyhow!("failed to start GC due to an ongoing process").into());
240        }
241        let _guard = scopeguard::guard(self.full_gc_state.clone(), |full_gc_state| {
242            full_gc_state.stop()
243        });
244        self.metrics.full_gc_trigger_count.inc();
245        let object_retention_time = cmp::max(
246            object_retention_time,
247            Duration::from_secs(self.env.opts.min_sst_retention_time_sec),
248        );
249        let limit = usize::try_from(self.env.opts.full_gc_object_limit)
250            .map_err(|_| anyhow::anyhow!("full_gc_object_limit exceeds usize::MAX"))?;
251        if limit == 0 {
252            return Err(anyhow::anyhow!("full_gc_object_limit must be greater than zero").into());
253        }
254        let object_retention_watermark = self
255            .now()
256            .await?
257            .saturating_sub(object_retention_time.as_secs());
258        let mut total_object_count = 0;
259        let mut total_object_size = 0;
260        tracing::info!(
261            retention_sec = object_retention_time.as_secs(),
262            prefix,
263            limit,
264            "Start GC."
265        );
266        // Keep one lister across batches so backends such as Azure Blob can use their
267        // continuation tokens without requiring support for listing after an object key.
268        let mut metadata_iter = self
269            .gc_manager
270            .list_object_metadata_from_object_store(prefix.clone())
271            .await?;
272        loop {
273            tracing::debug!(
274                retention_sec = object_retention_time.as_secs(),
275                prefix,
276                limit,
277                "Start a GC batch."
278            );
279            let (object_ids, batch_object_count, batch_object_size) =
280                GcManager::list_objects_batch(
281                    &mut metadata_iter,
282                    object_retention_watermark,
283                    limit,
284                )
285                .await?;
286            total_object_count += batch_object_count;
287            total_object_size += batch_object_size;
288            tracing::debug!(
289                ?object_ids,
290                batch_object_count,
291                batch_object_size,
292                "Finish listing a GC batch."
293            );
294            self.complete_gc_batch(object_ids, backup_manager.clone())
295                .await?;
296            if batch_object_count < limit as u64 {
297                break;
298            }
299        }
300        tracing::info!(total_object_count, total_object_size, "Finish GC");
301        self.metrics.total_object_size.set(total_object_size as _);
302        self.metrics.total_object_count.set(total_object_count as _);
303        match self.time_travel_pinned_object_count().await {
304            Ok(count) => {
305                self.metrics.time_travel_object_count.set(count as _);
306            }
307            Err(err) => {
308                use thiserror_ext::AsReport;
309                tracing::warn!(error = %err.as_report(), "Failed to count time travel objects.");
310            }
311        }
312        Ok(())
313    }
314
315    /// Given candidate objects to delete, filter out false positive.
316    /// Returns number of objects to delete.
317    pub(crate) async fn complete_gc_batch(
318        &self,
319        object_ids: HashSet<HummockObjectId>,
320        backup_manager: Option<BackupManagerRef>,
321    ) -> Result<usize> {
322        if object_ids.is_empty() {
323            return Ok(0);
324        }
325        // It's crucial to collect_min_uncommitted_object_id (i.e. `min_object_id`) only after LIST object store (i.e. `object_ids`).
326        // Because after getting `min_object_id`, new compute nodes may join and generate new uncommitted objects that are not covered by `min_sst_id`.
327        // By getting `min_object_id` after `object_ids`, it's ensured `object_ids` won't include any objects from those new compute nodes.
328        let min_object_id = collect_min_uncommitted_object_id(
329            &self.metadata_manager,
330            self.env.stream_client_pool(),
331        )
332        .await?;
333        let metrics = &self.metrics;
334        let candidate_object_number = object_ids.len();
335        metrics
336            .full_gc_candidate_object_count
337            .observe(candidate_object_number as _);
338        // Filter the uncommitted-object watermark before scanning references.
339        let object_ids = object_ids
340            .into_iter()
341            .filter(|id| id.as_raw() < min_object_id)
342            .collect_vec();
343        let after_min_object_id = object_ids.len();
344        let _change_log_guard = self.gc_manager.change_log_retention.pin(true);
345        // As in minor GC, exclude version/changelog references before scanning time travel
346        // and backups. Even if those owners publish after their scans and the live references
347        // disappear, these objects cannot reenter this batch. No version safe point is needed.
348        let object_ids = {
349            let version_pinned = self.get_gc_tracked_object_ids().await;
350            object_ids
351                .into_iter()
352                .filter(|id| !version_pinned.contains(id))
353                .collect_vec()
354        };
355        let after_initial_version = object_ids.len();
356        let filter_by_time_travel_start_time = Instant::now();
357        let mut object_ids = self
358            .filter_out_objects_by_time_travel(object_ids.into_iter())
359            .await?;
360        tracing::info!(elapsed = ?filter_by_time_travel_start_time.elapsed(), "filter out objects by time travel in full GC");
361        let after_time_travel = object_ids.len();
362        // The batch pin retains changelog references even if a backup publishes after
363        // this manifest scan and releases its own pin. No backup job lock is needed.
364        if let Some(backup_manager) = &backup_manager {
365            let backup_pinned = backup_manager.list_pinned_object_ids().await;
366            object_ids.retain(|id| !backup_pinned.contains(&id.as_raw()));
367        }
368        let after_metadata_backup = object_ids.len();
369        #[cfg(test)]
370        retention_tests::pause_gc_retention_handoff(self).await;
371        // Recheck references and write history under the same versioning read lock so
372        // commits and compaction reports observe the final deletion decision. Only objects
373        // that passed time-travel and backup filtering may be recorded in GC history.
374        let after_version = self
375            .finalize_objects_to_delete(object_ids.into_iter())
376            .await?;
377        let after_version_count = after_version.len();
378        metrics
379            .full_gc_selected_object_count
380            .observe(after_version_count as _);
381        tracing::info!(
382            candidate_object_number,
383            after_min_object_id,
384            after_initial_version,
385            after_time_travel,
386            after_metadata_backup,
387            after_version_count,
388            "complete gc batch"
389        );
390        self.delete_objects(after_version).await?;
391        Ok(after_version_count)
392    }
393
394    pub async fn now(&self) -> Result<u64> {
395        let mut guard = self.now.lock().await;
396        let new_now = SystemTime::now()
397            .duration_since(SystemTime::UNIX_EPOCH)
398            .expect("Clock may have gone backwards")
399            .as_secs();
400        if new_now < *guard {
401            return Err(anyhow::anyhow!(format!(
402                "unexpected decreasing now, old={}, new={}",
403                *guard, new_now
404            ))
405            .into());
406        }
407        *guard = new_now;
408        drop(guard);
409        // Persist now to maintain non-decreasing even after a meta node reboot.
410        let m = hummock_sequence::ActiveModel {
411            name: ActiveValue::Set(HUMMOCK_NOW.into()),
412            seq: ActiveValue::Set(new_now.try_into().unwrap()),
413        };
414        hummock_sequence::Entity::insert(m)
415            .on_conflict(
416                OnConflict::column(hummock_sequence::Column::Name)
417                    .update_column(hummock_sequence::Column::Seq)
418                    .to_owned(),
419            )
420            .exec(&self.env.meta_store_ref().conn)
421            .await?;
422        Ok(new_now)
423    }
424
425    pub(crate) async fn load_now(&self) -> Result<Option<u64>> {
426        let now = hummock_sequence::Entity::find_by_id(HUMMOCK_NOW.to_owned())
427            .one(&self.env.meta_store_ref().conn)
428            .await?
429            .map(|m| m.seq.try_into().unwrap());
430        Ok(now)
431    }
432
433    async fn write_gc_history(
434        &self,
435        object_ids: impl Iterator<Item = HummockObjectId>,
436    ) -> Result<()> {
437        if self.env.opts.gc_history_retention_time_sec == 0 {
438            return Ok(());
439        }
440        let now = self.now().await?;
441        let dt = DateTime::from_timestamp(now.try_into().unwrap(), 0).unwrap();
442        let mut models = object_ids.map(|o| hummock_gc_history::ActiveModel {
443            object_id: Set(o.as_raw().into()),
444            mark_delete_at: Set(dt.naive_utc()),
445        });
446        let db = &self.meta_store_ref().conn;
447        let gc_history_low_watermark = DateTime::from_timestamp(
448            now.saturating_sub(self.env.opts.gc_history_retention_time_sec)
449                .try_into()
450                .unwrap(),
451            0,
452        )
453        .unwrap();
454        hummock_gc_history::Entity::delete_many()
455            .filter(hummock_gc_history::Column::MarkDeleteAt.lt(gc_history_low_watermark))
456            .exec(db)
457            .await?;
458        let mut is_finished = false;
459        while !is_finished {
460            let mut batch = vec![];
461            let mut count: usize = self.env.opts.hummock_gc_history_insert_batch_size;
462            while count > 0 {
463                let Some(m) = models.next() else {
464                    is_finished = true;
465                    break;
466                };
467                count -= 1;
468                batch.push(m);
469            }
470            if batch.is_empty() {
471                break;
472            }
473            hummock_gc_history::Entity::insert_many(batch)
474                .on_conflict_do_nothing()
475                .exec(db)
476                .await?;
477        }
478        Ok(())
479    }
480
481    pub async fn delete_time_travel_metadata(
482        &self,
483        pinned_snapshot_epochs: HashMap<TableId, HashSet<HummockEpoch>>,
484    ) -> MetaResult<()> {
485        let current_epoch_time = Epoch::now().physical_time();
486        let epoch_watermark = Epoch::from_physical_time(
487            current_epoch_time.saturating_sub(
488                self.env
489                    .system_params_reader()
490                    .await
491                    .time_travel_retention_ms(),
492            ),
493        )
494        .0;
495        self.truncate_time_travel_metadata(epoch_watermark, pinned_snapshot_epochs)
496            .await?;
497        Ok(())
498    }
499
500    /// Deletes stale objects from object store.
501    ///
502    /// Deduplicates within each batch of at most 1,000 input IDs. On success, returns the input
503    /// count, including duplicates; deletion errors stop subsequent batches.
504    pub async fn delete_objects(&self, objects_to_delete: Vec<HummockObjectId>) -> Result<usize> {
505        #[cfg(test)]
506        retention_tests::pause_gc_deletion(self).await;
507        let total = objects_to_delete.len();
508        for objects in objects_to_delete.chunks(1000) {
509            if self.env.opts.vacuum_spin_interval_ms != 0 {
510                tokio::time::sleep(Duration::from_millis(self.env.opts.vacuum_spin_interval_ms))
511                    .await;
512            }
513            let delete_batch: HashSet<_> = objects.iter().copied().collect();
514            tracing::info!(?delete_batch, "Attempt to delete objects.");
515            self.gc_manager
516                .delete_objects(delete_batch.iter().copied())
517                .await?;
518            tracing::debug!(deleted_object_ids = ?delete_batch, "Finish deleting objects.");
519        }
520        Ok(total)
521    }
522
523    /// Snapshot references before scanning time travel and backup manifests. The caller
524    /// must already hold a changelog retention pin and have collected its GC candidates.
525    async fn get_gc_tracked_object_ids(&self) -> HashSet<HummockObjectId> {
526        let versioning = self
527            .versioning
528            .read_with_process_name("get_gc_tracked_object_ids")
529            .await;
530        let min_pinned_version_id = self
531            .context_info
532            .read_with_process_name("get_gc_tracked_object_ids")
533            .await
534            .min_pinned_version_id();
535        let mut pinned = versioning.get_tracked_object_ids(min_pinned_version_id);
536        pinned.extend(self.gc_manager.change_log_retention.objects());
537        pinned
538    }
539
540    /// Minor GC checks queued stale objects for references before deleting them.
541    pub async fn try_start_minor_gc(&self, backup_manager: BackupManagerRef) -> Result<()> {
542        const MIN_MINOR_GC_OBJECT_COUNT: usize = 1000;
543        let Some(object_ids) = self
544            .gc_manager
545            .try_take_may_delete_object_ids(MIN_MINOR_GC_OBJECT_COUNT)
546        else {
547            return Ok(());
548        };
549        let _change_log_guard = self.gc_manager.change_log_retention.pin(true);
550        #[cfg(test)]
551        retention_tests::pause_gc_retention_handoff(self).await;
552        // The version_pinned is obtained after the candidate object_ids for deletion, which is new enough for filtering purpose.
553        let version_pinned = self.get_gc_tracked_object_ids().await;
554        let object_ids = object_ids
555            .into_iter()
556            .filter(|s| !version_pinned.contains(s));
557        let filter_by_time_travel_start_time = Instant::now();
558        let object_ids = self.filter_out_objects_by_time_travel(object_ids).await?;
559        tracing::info!(elapsed = ?filter_by_time_travel_start_time.elapsed(), "filter out objects by time travel in minor GC");
560        let backup_pinned = backup_manager.list_pinned_object_ids().await;
561        // Full GC can reclaim backup-pinned objects after the backup is deleted.
562        self.delete_objects(
563            object_ids
564                .into_iter()
565                .filter(|id| !backup_pinned.contains(&id.as_raw()))
566                .collect(),
567        )
568        .await?;
569        Ok(())
570    }
571}
572
573async fn collect_min_uncommitted_object_id(
574    metadata_manager: &MetadataManager,
575    client_pool: &StreamClientPool,
576) -> Result<HummockRawObjectId> {
577    let futures = metadata_manager
578        .list_active_streaming_compute_nodes()
579        .await
580        .map_err(|err| Error::MetaStore(err.into()))?
581        .into_iter()
582        .map(|worker_node| async move {
583            let client = client_pool.get(&worker_node).await?;
584            let request = GetMinUncommittedObjectIdRequest {};
585            client.get_min_uncommitted_object_id(request).await
586        });
587    let min_watermark = try_join_all(futures)
588        .await
589        .map_err(|err| Error::Internal(err.into()))?
590        .into_iter()
591        .map(|resp| resp.min_uncommitted_object_id)
592        .min()
593        .unwrap_or(u64::MAX.into());
594    Ok(min_watermark)
595}
596
597pub struct FullGcState {
598    is_started: AtomicBool,
599}
600
601impl FullGcState {
602    pub fn new() -> Self {
603        Self {
604            is_started: AtomicBool::new(false),
605        }
606    }
607
608    pub fn try_start(&self) -> bool {
609        self.is_started
610            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
611            .is_ok()
612    }
613
614    pub fn stop(&self) {
615        self.is_started.store(false, Ordering::SeqCst);
616    }
617}
618
619#[cfg(test)]
620mod retention_tests;
621
622#[cfg(test)]
623mod tests {
624    use std::collections::HashSet;
625    use std::sync::Arc;
626    use std::time::Duration;
627
628    use itertools::Itertools;
629    use risingwave_hummock_sdk::HummockObjectId;
630    use risingwave_hummock_sdk::compaction_group::StaticCompactionGroupId;
631    use risingwave_object_store::object::{ObjectError, ObjectMetadata, ObjectMetadataIter};
632    use risingwave_rpc_client::HummockMetaClient;
633
634    use super::GcManager;
635    use crate::hummock::MockHummockMetaClient;
636    use crate::hummock::test_utils::{add_test_tables, setup_compute_env};
637
638    #[tokio::test]
639    async fn test_list_objects_batch() {
640        // Deliberately unordered keys: batching must not depend on lexicographic cursors.
641        let mut objects: ObjectMetadataIter =
642            Box::pin(futures::stream::iter([3, 1, 2].into_iter().map(|id| {
643                Ok(ObjectMetadata {
644                    key: format!("test/{id}.data"),
645                    last_modified: if id == 2 { 9.0 } else { 10.0 },
646                    total_size: id as usize,
647                })
648            })));
649        // A full batch containing only retained objects must still advance the iterator.
650        let (ids, count, size) = GcManager::list_objects_batch(&mut objects, 10, 2)
651            .await
652            .unwrap();
653        assert!(ids.is_empty());
654        assert_eq!((count, size), (2, 4));
655        let (ids, count, size) = GcManager::list_objects_batch(&mut objects, 10, 2)
656            .await
657            .unwrap();
658        assert_eq!(ids, HashSet::from([HummockObjectId::Sstable(2.into())]));
659        assert_eq!((count, size), (1, 2));
660        let (ids, count, size) = GcManager::list_objects_batch(&mut objects, 10, 2)
661            .await
662            .unwrap();
663        assert!(ids.is_empty());
664        assert_eq!((count, size), (0, 0));
665    }
666
667    #[tokio::test]
668    async fn test_list_objects_batch_propagates_error() {
669        let mut objects: ObjectMetadataIter = Box::pin(futures::stream::iter([
670            Ok(ObjectMetadata {
671                key: "test/1.data".to_owned(),
672                last_modified: 10.0,
673                total_size: 1,
674            }),
675            Err(ObjectError::internal("listing failed")),
676        ]));
677        assert!(
678            GcManager::list_objects_batch(&mut objects, 10, 1)
679                .await
680                .is_ok()
681        );
682        // An error on a later page must not be mistaken for the end of the listing.
683        assert!(
684            GcManager::list_objects_batch(&mut objects, 10, 1)
685                .await
686                .is_err()
687        );
688    }
689
690    #[tokio::test]
691    async fn test_full_gc_rejects_zero_batch_limit() {
692        use super::super::tests::setup_compute_env_with_meta_opts;
693        use crate::manager::MetaOpts;
694
695        let mut opts = MetaOpts::test(false);
696        opts.full_gc_object_limit = 0;
697        let (_, manager, _, _) = setup_compute_env_with_meta_opts(80, opts).await;
698        for _ in 0..2 {
699            let error = manager
700                .start_full_gc(Duration::ZERO, None, None)
701                .await
702                .unwrap_err();
703            assert!(
704                error
705                    .to_string()
706                    .contains("full_gc_object_limit must be greater than zero")
707            );
708        }
709    }
710
711    #[cfg(not(madsim))] // OpenDAL FS uses real filesystem I/O.
712    #[tokio::test]
713    async fn test_full_gc_preserves_listing_across_batches() {
714        use bytes::Bytes;
715        use risingwave_object_store::object::ObjectStoreImpl;
716
717        use crate::controller::catalog::CatalogController;
718        use crate::controller::cluster::ClusterController;
719        use crate::hummock::{CompactorManager, HummockManager};
720        use crate::manager::{MetaOpts, MetaSrvEnv, MetadataManager};
721        use crate::rpc::metrics::MetaMetrics;
722
723        let dir = tempfile::tempdir().unwrap();
724        let mut opts = MetaOpts::test(false);
725        opts.full_gc_object_limit = 2;
726        opts.object_store_config.req_concurrency_limit = 1;
727        let env = MetaSrvEnv::for_test_opts(opts, |params| {
728            params.state_store = Some(format!("hummock+fs://{}", dir.path().display()));
729        })
730        .await;
731        let cluster = Arc::new(
732            ClusterController::new(env.clone(), Duration::from_secs(1))
733                .await
734                .unwrap(),
735        );
736        let catalog = Arc::new(CatalogController::new(env.clone()).await.unwrap());
737        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
738        let manager = HummockManager::new(
739            env,
740            MetadataManager::new(cluster, catalog),
741            Arc::new(MetaMetrics::default()),
742            Arc::new(CompactorManager::for_test()),
743            tx,
744        )
745        .await
746        .unwrap();
747        assert!(matches!(
748            manager.object_store.as_ref(),
749            ObjectStoreImpl::Opendal(_)
750        ));
751        let prefix = format!("{}/gc-test", manager.gc_manager.path_prefix);
752        // Include unrelated files. They must not cause a short batch to end the scan early.
753        for name in ["0.tmp", "1.data", "2.data", "3.data", "4.data", "5.tmp"] {
754            manager
755                .object_store
756                .upload(&format!("{prefix}/{name}"), Bytes::from_static(b"data"))
757                .await
758                .unwrap();
759        }
760        // The watermark is zero, so every object survives both full batches. Repeat the
761        // run to also check that completion releases the in-progress guard.
762        for _ in 0..2 {
763            tokio::time::timeout(
764                Duration::from_secs(10),
765                manager.start_full_gc(
766                    Duration::from_secs(u64::MAX),
767                    Some("gc-test/".to_owned()),
768                    None,
769                ),
770            )
771            .await
772            .expect("full GC must finish without restarting the listing")
773            .unwrap();
774            assert_eq!(manager.metrics.total_object_count.get(), 4);
775            assert_eq!(manager.metrics.total_object_size.get(), 16);
776        }
777        for id in 1..=4 {
778            manager
779                .object_store
780                .metadata(&format!("{prefix}/{id}.data"))
781                .await
782                .unwrap();
783        }
784
785        // Stale objects use the canonical paths so complete_gc_batch really deletes them.
786        // Multiple batches must release the sole operation permit before deletion.
787        let mut stale_paths = Vec::new();
788        for id in 100..106 {
789            let object_id = HummockObjectId::Sstable(id.into());
790            let object_prefix = manager
791                .object_store
792                .get_object_prefix(id, manager.gc_manager.use_new_object_prefix_strategy);
793            let path = risingwave_hummock_sdk::get_object_data_path(
794                &object_prefix,
795                &manager.gc_manager.path_prefix,
796                object_id,
797            );
798            manager
799                .object_store
800                .upload(&path, Bytes::from_static(b"data"))
801                .await
802                .unwrap();
803            std::fs::File::open(dir.path().join(&path))
804                .unwrap()
805                .set_modified(std::time::SystemTime::UNIX_EPOCH)
806                .unwrap();
807            stale_paths.push(path);
808        }
809        tokio::time::timeout(
810            Duration::from_secs(10),
811            manager.start_full_gc(Duration::ZERO, None, None),
812        )
813        .await
814        .expect("full GC must delete batches with req_concurrency_limit = 1")
815        .unwrap();
816        assert_eq!(manager.metrics.total_object_count.get(), 10);
817        assert_eq!(manager.metrics.total_object_size.get(), 40);
818        for path in stale_paths {
819            assert!(
820                manager
821                    .object_store
822                    .metadata(&path)
823                    .await
824                    .unwrap_err()
825                    .is_object_not_found_error()
826            );
827        }
828        for id in 1..=4 {
829            manager
830                .object_store
831                .metadata(&format!("{prefix}/{id}.data"))
832                .await
833                .unwrap();
834        }
835    }
836
837    #[tokio::test]
838    async fn test_full_gc() {
839        let (_env, hummock_manager, _cluster_manager, worker_id) = setup_compute_env(80).await;
840        let hummock_meta_client: Arc<dyn HummockMetaClient> = Arc::new(MockHummockMetaClient::new(
841            hummock_manager.clone(),
842            worker_id as _,
843        ));
844        let compaction_group_id = StaticCompactionGroupId::StateDefault;
845        hummock_manager
846            .start_full_gc(
847                Duration::from_secs(hummock_manager.env.opts.min_sst_retention_time_sec + 1),
848                None,
849                None,
850            )
851            .await
852            .unwrap();
853
854        // Empty input results immediate return, without waiting heartbeat.
855        hummock_manager
856            .complete_gc_batch(vec![].into_iter().collect(), None)
857            .await
858            .unwrap();
859
860        // LSMtree is empty. All input object ids should be treated as garbage.
861        // Use fake object ids, because they'll be written to GC history and they shouldn't affect later commit.
862        assert_eq!(
863            3,
864            hummock_manager
865                .complete_gc_batch(
866                    [i64::MAX as u64 - 2, i64::MAX as u64 - 1, i64::MAX as u64]
867                        .into_iter()
868                        .map(|id| HummockObjectId::Sstable(id.into()))
869                        .collect(),
870                    None,
871                )
872                .await
873                .unwrap()
874        );
875
876        // All committed SST ids should be excluded from GC.
877        let sst_infos = add_test_tables(
878            hummock_manager.as_ref(),
879            hummock_meta_client.clone(),
880            compaction_group_id,
881        )
882        .await;
883        let committed_object_ids = sst_infos
884            .into_iter()
885            .flatten()
886            .map(|s| s.object_id)
887            .sorted()
888            .collect_vec();
889        assert!(!committed_object_ids.is_empty());
890        let max_committed_object_id = *committed_object_ids.iter().max().unwrap();
891        assert_eq!(
892            1,
893            hummock_manager
894                .complete_gc_batch(
895                    [committed_object_ids, vec![max_committed_object_id + 1]]
896                        .concat()
897                        .into_iter()
898                        .map(HummockObjectId::Sstable)
899                        .collect(),
900                    None,
901                )
902                .await
903                .unwrap()
904        );
905    }
906}