Skip to main content

mito2/
gc.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! GC worker which periodically checks and removes unused/obsolete  SST files.
16//!
17//! `expel time`: the time when the file is considered as removed, as in removed from the manifest.
18//! `lingering time`: the time duration before deleting files after they are removed from manifest.
19//! `delta manifest`: the manifest files after the last checkpoint that contains the changes to the manifest.
20//! `delete time`: the time when the file is actually deleted from the object store.
21//! `unknown files`: files that are not recorded in the manifest, usually due to saved checkpoint which remove actions before the checkpoint.
22//!
23
24use std::collections::{BTreeMap, HashMap, HashSet};
25use std::sync::Arc;
26use std::time::Duration;
27
28use common_meta::datanode::GcStat;
29use common_telemetry::tracing::Instrument as _;
30use common_telemetry::{debug, error, info, warn};
31use common_time::Timestamp;
32use itertools::Itertools;
33use object_store::{Entry, ErrorKind, Lister};
34use serde::{Deserialize, Serialize};
35use snafu::{ResultExt as _, ensure};
36use store_api::storage::{FileId, FileRef, FileRefsManifest, GcReport, IndexVersion, RegionId};
37use tokio::sync::{OwnedSemaphorePermit, TryAcquireError};
38use tokio_stream::StreamExt;
39
40use crate::access_layer::AccessLayerRef;
41use crate::cache::CacheManagerRef;
42use crate::config::MitoConfig;
43use crate::engine::region_hook::{RegionGcInfo, RegionHookRef};
44use crate::error::{
45    DurationOutOfRangeSnafu, InvalidRequestSnafu, JoinSnafu, OpenDalSnafu, Result,
46    TooManyGcJobsSnafu, UnexpectedSnafu,
47};
48use crate::manifest::action::{RegionManifest, RemovedFile};
49use crate::metrics::{
50    GC_DELETE_FILE_CNT, GC_DURATION_SECONDS, GC_ERRORS_TOTAL, GC_FILES_DELETED_TOTAL,
51    GC_ORPHANED_INDEX_FILES, GC_RUNS_TOTAL, GC_SKIPPED_UNPARSABLE_FILES,
52};
53use crate::region::{MitoRegionRef, RegionRoleState};
54use crate::sst::file::{RegionFileId, RegionIndexId, delete_files, delete_indexes};
55use crate::sst::location::SstObjectType;
56use crate::sst::location::{self};
57use crate::worker::DROPPING_MARKER_FILE;
58
59#[cfg(test)]
60mod worker_test;
61
62/// Helper function to determine if a file should be deleted based on common logic
63/// shared between Parquet and Puffin file types.
64fn should_delete_file(
65    is_in_manifest: bool,
66    is_in_tmp_ref: bool,
67    is_linger: bool,
68    is_eligible_for_delete: bool,
69    entry: &Entry,
70    unknown_file_may_linger_until: chrono::DateTime<chrono::Utc>,
71) -> bool {
72    if is_in_manifest || is_in_tmp_ref {
73        return false;
74    }
75
76    let is_known = is_linger || is_eligible_for_delete;
77    if is_known {
78        return is_eligible_for_delete;
79    }
80
81    // Unknown file: not in manifest, tmp refs, or known removed records. This also
82    // covers a directory whose manifest is gone (region dropped or not hosted here):
83    // there is no version to fence against, so a young object may still belong to an
84    // unpublished table-compaction attempt. Always require the object to be older
85    // than `unknown_file_lingering_time`; deleting immediately would race with an
86    // attempt that has not published yet.
87    entry
88        .metadata()
89        .last_modified()
90        .map(|ts| {
91            ts.into_inner().as_millisecond() < unknown_file_may_linger_until.timestamp_millis()
92        })
93        .unwrap_or(false)
94}
95
96/// Whether an unknown (untracked) entry is withheld only by the young-object
97/// rule. Such objects must be revisited later; a dropped region depends on its
98/// meta tombstone to be discovered by a later GC pass at all.
99fn is_deferred_unknown_file(
100    is_in_manifest: bool,
101    is_in_tmp_ref: bool,
102    is_linger: bool,
103    is_eligible_for_delete: bool,
104    entry: &Entry,
105    unknown_file_may_linger_until: chrono::DateTime<chrono::Utc>,
106) -> bool {
107    let unknown = !is_in_manifest && !is_in_tmp_ref && !is_linger && !is_eligible_for_delete;
108    unknown
109        && !should_delete_file(
110            is_in_manifest,
111            is_in_tmp_ref,
112            is_linger,
113            is_eligible_for_delete,
114            entry,
115            unknown_file_may_linger_until,
116        )
117}
118
119/// Limit the amount of concurrent GC jobs on the datanode
120pub struct GcLimiter {
121    pub gc_job_limit: Arc<tokio::sync::Semaphore>,
122    gc_concurrency: usize,
123}
124
125pub type GcLimiterRef = Arc<GcLimiter>;
126
127impl GcLimiter {
128    pub fn new(gc_concurrency: usize) -> Self {
129        Self {
130            gc_job_limit: Arc::new(tokio::sync::Semaphore::new(gc_concurrency)),
131            gc_concurrency,
132        }
133    }
134
135    pub fn running_gc_tasks(&self) -> u32 {
136        (self.gc_concurrency - self.gc_job_limit.available_permits()) as u32
137    }
138
139    pub fn gc_concurrency(&self) -> u32 {
140        self.gc_concurrency as u32
141    }
142
143    pub fn gc_stat(&self) -> GcStat {
144        GcStat::new(self.running_gc_tasks(), self.gc_concurrency())
145    }
146
147    /// Try to acquire a permit for a GC job.
148    ///
149    /// If no permit is available, returns an `TooManyGcJobs` error.
150    pub fn permit(&self) -> Result<OwnedSemaphorePermit> {
151        self.gc_job_limit
152            .clone()
153            .try_acquire_owned()
154            .map_err(|e| match e {
155                TryAcquireError::Closed => UnexpectedSnafu {
156                    reason: format!("Failed to acquire gc permit: {e}"),
157                }
158                .build(),
159                TryAcquireError::NoPermits => TooManyGcJobsSnafu {}.build(),
160            })
161    }
162}
163
164#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
165#[serde(default)]
166pub struct GcConfig {
167    /// Whether GC is enabled.
168    pub enable: bool,
169    /// Lingering time before deleting files.
170    /// Should be long enough to allow long running queries to finish.
171    /// If set to None, then unused files will be deleted immediately.
172    ///
173    #[serde(with = "humantime_serde")]
174    pub lingering_time: Option<Duration>,
175    /// Lingering time before deleting unknown files(files with undetermine expel time).
176    /// expel time is the time when the file is considered as removed, as in removed from the manifest.
177    /// This should only occur rarely, as manifest keep tracks in `removed_files` field
178    /// unless something goes wrong.
179    ///
180    /// It is also the age threshold of the sweep that reclaims temporary files left behind
181    /// by a crashed HDFS writer, and that sweep runs even if `enable` is false. HDFS advances
182    /// the modification time of a file under construction only as its blocks complete, so
183    /// lowering this value also shrinks the margin between the sweep and files that are
184    /// still being written.
185    #[serde(with = "humantime_serde")]
186    pub unknown_file_lingering_time: Duration,
187    /// Maximum concurrent list operations per GC job.
188    /// This is used to limit the number of concurrent listing operations and speed up listing.
189    pub max_concurrent_lister_per_gc_job: usize,
190    /// Maximum concurrent GC jobs.
191    /// This is used to limit the number of concurrent GC jobs running on the datanode
192    /// to prevent too many concurrent GC jobs from overwhelming the datanode.
193    /// Setting it to 0 disables GC jobs and the temporary file sweep, which is limited
194    /// to the same number of concurrent tasks.
195    pub max_concurrent_gc_job: usize,
196}
197
198impl Default for GcConfig {
199    fn default() -> Self {
200        Self {
201            enable: false,
202            // expect long running queries to be finished(or at least be able to notify it's using a deleted file) within a reasonable time
203            lingering_time: Some(Duration::from_secs(60 * 60)),
204            // 1 day, for unknown expel time, which is when this file get removed from manifest.
205            // A long default avoids accidentally deleting pre-manifest files (e.g.
206            // compaction/flush still in progress) or temporary files of a writer that is
207            // still alive; the temporary file sweep uses this value as well.
208            unknown_file_lingering_time: Duration::from_secs(24 * 60 * 60),
209            max_concurrent_lister_per_gc_job: 32,
210            max_concurrent_gc_job: 4,
211        }
212    }
213}
214
215pub struct LocalGcWorker {
216    pub(crate) access_layer: AccessLayerRef,
217    pub(crate) cache_manager: Option<CacheManagerRef>,
218    pub(crate) regions: BTreeMap<RegionId, Option<MitoRegionRef>>,
219    /// Lingering time before deleting files.
220    pub(crate) opt: GcConfig,
221    /// Tmp ref files manifest, used to determine which files are still in use by ongoing queries.
222    ///
223    /// Also contains manifest versions of regions when the tmp ref files are generated.
224    /// Used to determine whether the tmp ref files are outdated.
225    pub(crate) file_ref_manifest: FileRefsManifest,
226    _permit: OwnedSemaphorePermit,
227    /// Whether to perform full file listing during GC.
228    /// When set to false, GC will only delete files that are tracked in the manifest's removed_files,
229    /// which can significantly improve performance by avoiding expensive list operations.
230    /// When set to true, GC will perform a full listing to find and delete orphan files
231    /// (files not tracked in the manifest).
232    ///
233    /// Set to false for regular GC operations to optimize performance.
234    /// Set to true periodically or when you need to clean up orphan files.
235    pub full_file_listing: bool,
236    /// The region hook (if any), fired via `on_region_gc` after each GC pass so
237    /// extensions with sidecar files outside the mito2 region dir can clean up.
238    pub(crate) hook: Option<RegionHookRef>,
239}
240
241pub struct ManifestOpenConfig {
242    pub compress_manifest: bool,
243    pub manifest_checkpoint_distance: u64,
244    pub experimental_manifest_keep_removed_file_count: usize,
245    pub experimental_manifest_keep_removed_file_ttl: Duration,
246}
247
248impl From<MitoConfig> for ManifestOpenConfig {
249    fn from(mito_config: MitoConfig) -> Self {
250        Self {
251            compress_manifest: mito_config.compress_manifest,
252            manifest_checkpoint_distance: mito_config.manifest_checkpoint_distance,
253            experimental_manifest_keep_removed_file_count: mito_config
254                .experimental_manifest_keep_removed_file_count,
255            experimental_manifest_keep_removed_file_ttl: mito_config
256                .experimental_manifest_keep_removed_file_ttl,
257        }
258    }
259}
260
261impl LocalGcWorker {
262    /// Create a new LocalGcWorker, with `regions_to_gc` regions to GC.
263    /// The regions are specified by their `RegionId` and should all belong to the same table.
264    ///
265    #[allow(clippy::too_many_arguments)]
266    pub async fn try_new(
267        access_layer: AccessLayerRef,
268        cache_manager: Option<CacheManagerRef>,
269        regions_to_gc: BTreeMap<RegionId, Option<MitoRegionRef>>,
270        opt: GcConfig,
271        file_ref_manifest: FileRefsManifest,
272        limiter: &GcLimiterRef,
273        full_file_listing: bool,
274        hook: Option<RegionHookRef>,
275    ) -> Result<Self> {
276        if let Some(first_region_id) = regions_to_gc.keys().next() {
277            let table_id = first_region_id.table_id();
278            for region_id in regions_to_gc.keys() {
279                ensure!(
280                    region_id.table_id() == table_id,
281                    InvalidRequestSnafu {
282                        region_id: *region_id,
283                        reason: format!(
284                            "Region {} does not belong to table {}",
285                            region_id, table_id
286                        ),
287                    }
288                );
289            }
290        }
291
292        let permit = limiter.permit()?;
293
294        Ok(Self {
295            access_layer,
296            cache_manager,
297            regions: regions_to_gc,
298            opt,
299            file_ref_manifest,
300            _permit: permit,
301            full_file_listing,
302            hook,
303        })
304    }
305
306    /// Get tmp ref files for all current regions
307    pub async fn read_tmp_ref_files(&self) -> Result<HashMap<RegionId, HashSet<FileRef>>> {
308        let mut tmp_ref_files = HashMap::new();
309        for (region_id, file_refs) in &self.file_ref_manifest.file_refs {
310            tmp_ref_files
311                .entry(*region_id)
312                .or_insert_with(HashSet::new)
313                .extend(file_refs.clone());
314            // no need to include manifest files here, as they are already included in region manifest
315        }
316
317        Ok(tmp_ref_files)
318    }
319
320    /// Run the GC worker in serial mode,
321    /// considering list files could be slow and run multiple regions in parallel
322    /// may cause too many concurrent listing operations.
323    ///
324    /// TODO(discord9): consider instead running in parallel mode
325    #[common_telemetry::tracing::instrument(
326        skip_all,
327        fields(region_count = self.regions.len(), full_file_listing = self.full_file_listing)
328    )]
329    pub async fn run(self) -> Result<GcReport> {
330        info!("LocalGcWorker started");
331        let _timer = GC_DURATION_SECONDS
332            .with_label_values(&["total"])
333            .start_timer();
334        let now = std::time::Instant::now();
335
336        let mut deleted_files = HashMap::new();
337        let mut deleted_indexes = HashMap::new();
338        let mut processed_regions = HashSet::new();
339        let mut need_retry_regions = HashSet::new();
340        let tmp_ref_files = self.read_tmp_ref_files().await?;
341        for (region_id, region) in &self.regions {
342            let per_region_time = std::time::Instant::now();
343            if region.as_ref().map(|r| r.manifest_ctx.current_state())
344                == Some(RegionRoleState::Follower)
345            {
346                return UnexpectedSnafu {
347                    reason: format!(
348                        "Region {} is in Follower state, should not run GC on follower regions",
349                        region_id
350                    ),
351                }
352                .fail();
353            }
354            let tmp_ref_files = tmp_ref_files
355                .get(region_id)
356                .cloned()
357                .unwrap_or_else(HashSet::new);
358            let outcome = self
359                .do_region_gc(*region_id, region.clone(), &tmp_ref_files)
360                .await?;
361            let RegionGcOutcome {
362                removed_files,
363                needs_retry,
364            } = outcome;
365            let index_files = removed_files
366                .iter()
367                .filter_map(|f| f.index_version().map(|v| (f.file_id(), v)))
368                .collect_vec();
369            let data_files = removed_files
370                .into_iter()
371                .filter_map(|f| match f {
372                    RemovedFile::File(file_id, _) | RemovedFile::Narthex(file_id) => Some(file_id),
373                    RemovedFile::Index(_, _) => None,
374                })
375                .collect();
376            // A deferred deletion batch or failed extension cleanup must not
377            // acknowledge the region as fully processed.
378            if needs_retry {
379                need_retry_regions.insert(*region_id);
380            } else {
381                deleted_files.insert(*region_id, data_files);
382                deleted_indexes.insert(*region_id, index_files);
383                processed_regions.insert(*region_id);
384            }
385            debug!(
386                "GC for region {} took {} secs.",
387                region_id,
388                per_region_time.elapsed().as_secs_f32()
389            );
390        }
391        info!(
392            "LocalGcWorker finished after {} secs.",
393            now.elapsed().as_secs_f32()
394        );
395        let report = GcReport {
396            deleted_files,
397            deleted_indexes,
398            need_retry_regions,
399            processed_regions,
400        };
401        Ok(report)
402    }
403}
404
405/// Per-region outcome of [`LocalGcWorker::do_region_gc`].
406///
407/// Unfinished deletion or extension cleanup keeps the region in the retry set.
408pub(crate) struct RegionGcOutcome {
409    /// Files physically deleted this pass.
410    pub removed_files: Vec<RemovedFile>,
411    /// The snapshot changed while the protection lookup ran, or extension cleanup failed.
412    pub needs_retry: bool,
413}
414
415impl LocalGcWorker {
416    /// concurrency of listing files per region.
417    /// This is used to limit the number of concurrent listing operations and speed up listing
418    pub const CONCURRENCY_LIST_PER_FILES: usize = 1024;
419
420    /// Perform GC for the region.
421    /// 1. Get all the removed files in delta manifest files and their expel times
422    /// 2. List all files in the region dir concurrently
423    /// 3. Filter out the files that are still in use or may still be kept for a while
424    /// 4. Delete the unused files
425    ///
426    /// Note that the files that are still in use or may still be kept for a while are not deleted
427    /// to avoid deleting files that are still needed.
428    #[common_telemetry::tracing::instrument(
429        skip_all,
430        fields(
431            region_id = %region_id,
432            full_file_listing = self.full_file_listing,
433            region_present = region.is_some()
434        )
435    )]
436    pub(crate) async fn do_region_gc(
437        &self,
438        region_id: RegionId,
439        region: Option<MitoRegionRef>,
440        tmp_ref_files: &HashSet<FileRef>,
441    ) -> Result<RegionGcOutcome> {
442        let mode = if self.full_file_listing {
443            "full_listing"
444        } else {
445            "fast"
446        };
447        GC_RUNS_TOTAL.with_label_values(&[mode]).inc();
448        debug!(
449            "Doing gc for region {}, {}",
450            region_id,
451            if region.is_some() {
452                "region found"
453            } else {
454                "region not found, might be dropped"
455            }
456        );
457
458        ensure!(
459            region.is_some() || self.full_file_listing,
460            InvalidRequestSnafu {
461                region_id,
462                reason: "region not found and full_file_listing is false; refusing GC without full listing".to_string(),
463            }
464        );
465
466        let manifest = if let Some(region) = &region {
467            let manager = region.manifest_ctx.manifest_manager.read().await;
468            let manifest = manager.manifest();
469            // If the manifest version does not match, skip GC for this region to avoid deleting files that are still in use.
470            let file_ref_manifest_version = self
471                .file_ref_manifest
472                .manifest_version
473                .get(&region.region_id())
474                .cloned();
475            if file_ref_manifest_version != Some(manifest.manifest_version) {
476                // should be rare enough(few seconds after leader update manifest version), just skip gc for this region
477                warn!(
478                    "Tmp ref files manifest version {:?} does not match region {} manifest version {}, skip gc for this region",
479                    file_ref_manifest_version,
480                    region.region_id(),
481                    manifest.manifest_version
482                );
483                GC_ERRORS_TOTAL
484                    .with_label_values(&["manifest_mismatch"])
485                    .inc();
486                return Ok(RegionGcOutcome {
487                    removed_files: vec![],
488                    needs_retry: false,
489                });
490            }
491            // SSTs written for pending tails but not committed yet, and SSTs of a newer
492            // manifest, are not in this snapshot, so a full listing would take them for orphans.
493            if self.full_file_listing
494                && (!manifest.pending_tails.is_empty()
495                    || manager.has_update().await.unwrap_or_else(|e| {
496                        warn!(e; "Failed to check manifest updates of region {}", region_id);
497                        true
498                    }))
499            {
500                info!(
501                    "Skip full listing GC for region {}: it has pending WAL tails or a newer manifest may exist",
502                    region_id
503                );
504                return Ok(RegionGcOutcome {
505                    removed_files: vec![],
506                    needs_retry: false,
507                });
508            }
509            Some(manifest)
510        } else {
511            None
512        };
513
514        let all_entries = if let Some(manifest) = &manifest
515            && self.full_file_listing
516        {
517            // do the time consuming listing only when full_file_listing is true(and region is open)
518            // and do it first to make sure we have the latest manifest etc.
519            self.list_from_object_store(region_id, manifest.files.len())
520                .await?
521        } else if manifest.is_none() && self.full_file_listing {
522            // if region is already dropped, we have no manifest to refer to,
523            // so only do gc if `full_file_listing` is true, otherwise just skip it
524            // TODO(discord9): is doing one serial listing enough here?
525            self.list_from_object_store(region_id, Self::CONCURRENCY_LIST_PER_FILES)
526                .await?
527        } else {
528            vec![]
529        };
530
531        let recently_removed_files = if let Some(manifest) = &manifest {
532            self.get_removed_files_expel_times(manifest).await?
533        } else {
534            Default::default()
535        };
536
537        if recently_removed_files.is_empty() {
538            // no files to remove, skip
539            debug!("No recently removed files to gc for region {}", region_id);
540        }
541
542        let removed_file_cnt = recently_removed_files
543            .values()
544            .map(|s| s.len())
545            .sum::<usize>();
546
547        let in_manifest = manifest
548            .as_ref()
549            .map(|manifest| {
550                manifest
551                    .all_files()
552                    .map(|file| (file.file_id, file.index_version()))
553                    .collect::<HashMap<_, _>>()
554            })
555            .unwrap_or_default();
556
557        let is_region_dropped = region.is_none();
558
559        let in_tmp_ref = tmp_ref_files
560            .iter()
561            .map(|file_ref| (file_ref.file_id, file_ref.index_version))
562            .collect::<HashSet<_>>();
563
564        let (mut deletable_files, deferred_unknown_files) = self
565            .list_to_be_deleted_files(
566                region_id,
567                &in_manifest,
568                &in_tmp_ref,
569                recently_removed_files,
570                all_entries,
571            )
572            .await?;
573
574        let mut hook_deferred_files = false;
575        if let Some(hook) = &self.hook {
576            let candidates = deletable_files
577                .iter()
578                .map(|file| RegionFileId::new(region_id, file.file_id()))
579                .collect::<Vec<_>>();
580            let protected = hook
581                .protected_sst_files(&self.access_layer, &candidates)
582                .await?;
583            let before_filtering = deletable_files.len();
584            deletable_files
585                .retain(|file| !protected.contains(&RegionFileId::new(region_id, file.file_id())));
586            hook_deferred_files = deletable_files.len() < before_filtering;
587        }
588        info!(
589            "gc: for region{}{region_id}: In manifest file cnt: {}, Tmp ref file cnt: {}, recently removed files: {}, Unused files to delete count: {}",
590            if region.is_none() {
591                "(region dropped)"
592            } else {
593                ""
594            },
595            in_manifest.len(),
596            tmp_ref_files.len(),
597            removed_file_cnt,
598            deletable_files.len(),
599        );
600        debug!(
601            "gc: deletable files for region {}: {:?}",
602            region_id, &deletable_files
603        );
604
605        debug!(
606            "Found {} unused index files to delete for region {}",
607            deletable_files.len(),
608            region_id
609        );
610
611        let _delete_timer = GC_DURATION_SECONDS
612            .with_label_values(&["delete_files"])
613            .start_timer();
614        // The protection lookup above awaits, so a queued publication may have
615        // changed the region since the candidate set was computed. Recheck once
616        // without holding the manifest lock across remote deletion. An empty
617        // candidate set takes neither the lock nor the recheck.
618        let publication_changed = !deletable_files.is_empty()
619            && if let (Some(region), Some(snapshot)) = (&region, &manifest) {
620                let manifest_guard = region.manifest_ctx.manifest_manager.read().await;
621                manifest_guard.is_stopped()
622                    || manifest_guard.manifest().manifest_version != snapshot.manifest_version
623                    || !matches!(region.state(), RegionRoleState::Leader(_))
624            } else {
625                false
626            };
627        if publication_changed {
628            debug!(
629                "gc: region {} changed during the protection lookup, deferring deletion",
630                region_id
631            );
632            deletable_files.clear();
633        } else {
634            self.delete_files(region_id, &deletable_files).await?;
635            debug!(
636                "Successfully deleted {} unused files for region {}",
637                deletable_files.len(),
638                region_id
639            );
640        }
641
642        // Notify extensions so they can clean up sidecar files. Fire when there
643        // are removed files, or on a full-listing pass (lets extensions reconcile
644        // orphans even when mito deleted nothing). Cleanup is always scoped to
645        // `removed_files`; see `RegionGcInfo`.
646        let extension_cleanup_failed = if let Some(hook) = &self.hook
647            && (!deletable_files.is_empty() || self.full_file_listing)
648        {
649            let region_metadata = region.as_ref().map(|r| r.metadata());
650            let result = hook
651                .on_region_gc(
652                    region_id,
653                    region_metadata.as_ref(),
654                    &self.access_layer,
655                    &RegionGcInfo {
656                        removed_files: &deletable_files,
657                        is_region_dropped,
658                        full_file_listing: self.full_file_listing,
659                    },
660                )
661                .await;
662            if let Err(err) = result {
663                warn!(
664                    err;
665                    "Region hook on_region_gc failed for region {}, will retry on the next GC pass",
666                    region_id
667                );
668                true
669            } else {
670                false
671            }
672        } else {
673            false
674        };
675
676        // Defer clearing the manifest tracking until the extension succeeds, so
677        // a failed live-region cleanup is replayed next pass. (Dropped regions
678        // have no manifest.)
679        if !extension_cleanup_failed && let Some(region) = &region {
680            let _update_timer = GC_DURATION_SECONDS
681                .with_label_values(&["update_manifest"])
682                .start_timer();
683            self.update_manifest_removed_files(region, deletable_files.clone())
684                .await?;
685        }
686
687        // A dropped region is rediscovered only through its meta-srv tombstone.
688        // Young unknown objects and hook-protected candidates must keep that
689        // tombstone (needs_retry) until they are actually reclaimed; reporting
690        // success here would let the procedure drop the tombstone and leak them.
691        let dropped_files_deferred =
692            region.is_none() && (deferred_unknown_files || hook_deferred_files);
693
694        Ok(RegionGcOutcome {
695            removed_files: deletable_files,
696            needs_retry: extension_cleanup_failed || publication_changed || dropped_files_deferred,
697        })
698    }
699
700    #[common_telemetry::tracing::instrument(
701        skip_all,
702        fields(region_id = %region_id, removed_file_count = removed_files.len())
703    )]
704    async fn delete_files(&self, region_id: RegionId, removed_files: &[RemovedFile]) -> Result<()> {
705        let mut index_ids = vec![];
706        let file_pairs = removed_files
707            .iter()
708            .filter_map(|f| match f {
709                RemovedFile::Narthex(_) => None,
710                RemovedFile::File(file_id, v) => Some((*file_id, v.unwrap_or(0))),
711                RemovedFile::Index(file_id, index_version) => {
712                    let region_index_id =
713                        RegionIndexId::new(RegionFileId::new(region_id, *file_id), *index_version);
714                    index_ids.push(region_index_id);
715                    None
716                }
717            })
718            .collect_vec();
719        delete_files(
720            region_id,
721            &file_pairs,
722            true,
723            &self.access_layer,
724            &self.cache_manager,
725        )
726        .await?;
727
728        for removed in removed_files {
729            if let RemovedFile::Narthex(id) = removed {
730                // A removed generation cannot be reused. Let its individually cached
731                // objects age out when GC has only the UUID and no part inventory.
732                self.access_layer
733                    .delete_narthex_artifact(region_id, *id)
734                    .await?;
735                debug!("Deleted Narthex artifact {id} for region {region_id}");
736            }
737        }
738
739        if !file_pairs.is_empty() {
740            let deleted_count = file_pairs.len() as u64;
741            GC_FILES_DELETED_TOTAL
742                .with_label_values(&["parquet"])
743                .inc_by(deleted_count);
744            GC_DELETE_FILE_CNT.inc_by(deleted_count);
745        }
746
747        if !index_ids.is_empty() {
748            let deleted_count = index_ids.len() as u64;
749            delete_indexes(&index_ids, &self.access_layer, &self.cache_manager)
750                .await
751                .inspect_err(|_| {
752                    GC_ERRORS_TOTAL.with_label_values(&["delete_failed"]).inc();
753                })?;
754            GC_FILES_DELETED_TOTAL
755                .with_label_values(&["index"])
756                .inc_by(deleted_count);
757            GC_DELETE_FILE_CNT.inc_by(deleted_count);
758        }
759
760        Ok(())
761    }
762
763    /// Update region manifest for clear the actually deleted files
764    #[common_telemetry::tracing::instrument(
765        skip_all,
766        fields(region_id = %region.region_id(), deleted_file_count = deleted_files.len())
767    )]
768    async fn update_manifest_removed_files(
769        &self,
770        region: &MitoRegionRef,
771        deleted_files: Vec<RemovedFile>,
772    ) -> Result<()> {
773        let deleted_file_cnt = deleted_files.len();
774        debug!(
775            "Trying to update manifest for {deleted_file_cnt} removed files for region {}",
776            region.region_id()
777        );
778
779        let mut manager = region.manifest_ctx.manifest_manager.write().await;
780        let cnt = deleted_files.len();
781        manager.clear_deleted_files(deleted_files);
782        debug!(
783            "Updated region_id={} region manifest to clear {cnt} deleted files",
784            region.region_id(),
785        );
786
787        Ok(())
788    }
789
790    /// Get all the removed files in delta manifest files and their expel times.
791    /// The expel time is the time when the file is considered as removed.
792    /// Which is the last modified time of delta manifest which contains the remove action.
793    ///
794    pub async fn get_removed_files_expel_times(
795        &self,
796        region_manifest: &Arc<RegionManifest>,
797    ) -> Result<BTreeMap<Timestamp, HashSet<RemovedFile>>> {
798        let mut ret = BTreeMap::new();
799        for files in &region_manifest.removed_files.removed_files {
800            let expel_time = Timestamp::new_millisecond(files.removed_at);
801            let set = ret.entry(expel_time).or_insert_with(HashSet::new);
802            set.extend(files.files.iter().cloned());
803        }
804
805        Ok(ret)
806    }
807
808    /// Create partitioned listers for concurrent file listing based on concurrency level.
809    /// Returns a vector of (lister, end_boundary) pairs for parallel processing.
810    async fn partition_region_files(
811        &self,
812        region_id: RegionId,
813        concurrency: usize,
814    ) -> Result<Vec<(Lister, Option<String>)>> {
815        let region_dir = self.access_layer.build_region_dir(region_id);
816
817        let partitions = gen_partition_from_concurrency(concurrency);
818        let bounds = vec![None]
819            .into_iter()
820            .chain(partitions.iter().map(|p| Some(p.clone())))
821            .chain(vec![None])
822            .collect::<Vec<_>>();
823
824        let mut listers = vec![];
825        for part in bounds.windows(2) {
826            let start = part[0].clone();
827            let end = part[1].clone();
828            let mut lister = self.access_layer.object_store().lister_with(&region_dir);
829            if let Some(s) = start {
830                lister = lister.start_after(&s);
831            }
832
833            let lister = lister.await.context(OpenDalSnafu)?;
834            listers.push((lister, end));
835        }
836
837        Ok(listers)
838    }
839
840    /// List all files in the region directory.
841    /// Returns a vector of all file entries found.
842    /// This might take a long time if there are many files in the region directory.
843    #[common_telemetry::tracing::instrument(
844        skip_all,
845        fields(region_id = %region_id, file_cnt_hint = file_cnt_hint)
846    )]
847    async fn list_from_object_store(
848        &self,
849        region_id: RegionId,
850        file_cnt_hint: usize,
851    ) -> Result<Vec<Entry>> {
852        let _timer = GC_DURATION_SECONDS
853            .with_label_values(&["list_files"])
854            .start_timer();
855        let start = tokio::time::Instant::now();
856        let concurrency = (file_cnt_hint / Self::CONCURRENCY_LIST_PER_FILES)
857            .max(1)
858            .min(self.opt.max_concurrent_lister_per_gc_job);
859
860        let listers = self
861            .partition_region_files(region_id, concurrency)
862            .await
863            .inspect_err(|_| {
864                GC_ERRORS_TOTAL.with_label_values(&["list_failed"]).inc();
865            })?;
866        let lister_cnt = listers.len();
867
868        // Step 2: Concurrently list all parquet files in the region root directory
869        let mut all_entries = self
870            .list_region_files_concurrent(listers)
871            .await
872            .inspect_err(|_| {
873                GC_ERRORS_TOTAL.with_label_values(&["list_failed"]).inc();
874            })?;
875        let root_cnt = all_entries.len();
876
877        // Step 2b: Flat-list region_dir/index/ for puffin files.
878        // This is NOT a recursive listing — we only list the index/
879        // subdirectory to avoid scanning nested dirs/staging/blob/cache.
880        let index_entries = self
881            .list_region_index_files(region_id)
882            .await
883            .inspect_err(|_| {
884                GC_ERRORS_TOTAL.with_label_values(&["list_failed"]).inc();
885            })?;
886        let index_cnt = index_entries.len();
887        all_entries.extend(index_entries);
888        // Only descend into artifact directories, not index/blob/staging/cache directories.
889        let mut narthex_dirs = Vec::new();
890        all_entries.retain(|entry| {
891            if entry.metadata().is_dir() {
892                narthex_dirs.push(entry.path().to_string());
893                false
894            } else {
895                true
896            }
897        });
898        for dir in narthex_dirs {
899            let mut lister = self
900                .access_layer
901                .object_store()
902                .lister_with(&dir)
903                .recursive(true)
904                .await
905                .context(OpenDalSnafu)?;
906            let mut empty = true;
907            while let Some(entry) = lister.try_next().await.context(OpenDalSnafu)? {
908                // Filesystem listings include the directory itself.
909                if entry.metadata().is_dir() && entry.path() == dir {
910                    continue;
911                }
912                empty = false;
913                if entry.metadata().is_file() {
914                    all_entries.push(entry);
915                }
916            }
917            if empty {
918                // Non-recursive deletion cannot remove objects from a concurrent writer.
919                if let Err(error) = self.access_layer.object_store().delete(&dir).await {
920                    debug!("Could not remove empty narthex directory {dir}: {error}");
921                }
922            }
923        }
924        info!(
925            "gc: full listing mode cost {} secs using {lister_cnt} lister for root={root_cnt} index={index_cnt} files in region {}.",
926            start.elapsed().as_secs_f64(),
927            region_id
928        );
929        Ok(all_entries)
930    }
931
932    /// Flat-list puffin files from `region_dir/index/`.
933    /// If the index directory does not exist, returns an empty vec without error.
934    /// Only `.puffin` files (not subdirectories) are included.
935    async fn list_region_index_files(&self, region_id: RegionId) -> Result<Vec<Entry>> {
936        let region_dir = self.access_layer.build_region_dir(region_id);
937        let index_dir = location::index_dir(&region_dir);
938
939        let mut lister = match self
940            .access_layer
941            .object_store()
942            .lister_with(&index_dir)
943            .await
944        {
945            Ok(l) => l,
946            Err(e) if e.kind() == ErrorKind::NotFound => {
947                // Index dir may not exist — that's fine, just log and return empty.
948                // object-store backends (especially filesystem) may error on
949                // non-existent directories.
950                debug!(
951                    "Index directory not found for region {}: {}. Treating as empty.",
952                    region_id, e
953                );
954                return Ok(vec![]);
955            }
956            Err(e) => return Err(e).context(OpenDalSnafu),
957        };
958
959        let mut entries = Vec::new();
960        while let Some(entry) = lister.next().await {
961            let entry = entry.context(OpenDalSnafu)?;
962            if entry.metadata().is_file() && entry.name().ends_with(".puffin") {
963                entries.push(entry);
964            }
965        }
966
967        Ok(entries)
968    }
969
970    /// Concurrently list all files in the region directory using the provided listers.
971    /// Returns a vector of all file entries found across all partitions.
972    async fn list_region_files_concurrent(
973        &self,
974        listers: Vec<(Lister, Option<String>)>,
975    ) -> Result<Vec<Entry>> {
976        let (tx, mut rx) = tokio::sync::mpsc::channel(1024);
977        let mut handles = vec![];
978
979        for (lister, end) in listers {
980            let tx = tx.clone();
981            let handle = tokio::spawn(
982                async move {
983                    let stream = lister.take_while(|e: &std::result::Result<Entry, _>| match e {
984                        Ok(e) => {
985                            if let Some(end) = &end {
986                                // reach end, stop listing
987                                e.name() < end.as_str()
988                            } else {
989                                // no end, take all entries
990                                true
991                            }
992                        }
993                        // Entry went wrong. Keep listing so the error can be propagated below
994                        // instead of returning a partial listing as success.
995                        Err(err) => {
996                            warn!("Failed to list entry: {}", err);
997                            true
998                        }
999                    });
1000                    let stream = stream
1001                        .filter(|e| {
1002                            if let Ok(e) = &e {
1003                                // Artifact directories contain narthex objects; skip other directories.
1004                                e.metadata().is_file() || location::is_narthex_file_dir(e.path())
1005                            } else {
1006                                // error entry, take for further logging
1007                                true
1008                            }
1009                        })
1010                        .collect::<Vec<_>>()
1011                        .await;
1012                    // ordering of files doesn't matter here, so we can send them directly
1013                    tx.send(stream).await.expect("Failed to send entries");
1014                }
1015                .instrument(common_telemetry::tracing::info_span!("gc_list_partition")),
1016            );
1017
1018            handles.push(handle);
1019        }
1020
1021        // Wait for all listers to finish
1022        for handle in handles {
1023            handle.await.context(JoinSnafu)?;
1024        }
1025
1026        drop(tx); // Close the channel to stop receiving
1027
1028        // Collect all entries from the channel
1029        let mut all_entries = vec![];
1030        while let Some(stream) = rx.recv().await {
1031            for entry in stream {
1032                all_entries.push(entry.context(OpenDalSnafu)?);
1033            }
1034        }
1035
1036        Ok(all_entries)
1037    }
1038
1039    #[allow(clippy::too_many_arguments)]
1040    fn filter_deletable_files(
1041        &self,
1042        entries: Vec<Entry>,
1043        in_manifest: &HashMap<FileId, Option<IndexVersion>>,
1044        in_tmp_ref: &HashSet<(FileId, Option<IndexVersion>)>,
1045        may_linger_files: &HashSet<&RemovedFile>,
1046        eligible_for_delete: &HashSet<&RemovedFile>,
1047        unknown_file_may_linger_until: chrono::DateTime<chrono::Utc>,
1048    ) -> (Vec<RemovedFile>, bool) {
1049        let mut ready_for_delete = vec![];
1050        let mut deferred_unknown = false;
1051        // Every index-version reader needs the same Parquet file.
1052        let referenced_ssts: HashSet<_> = in_tmp_ref.iter().map(|(file_id, _)| *file_id).collect();
1053
1054        let may_linger_files: HashMap<FileId, HashSet<&RemovedFile>> = may_linger_files
1055            .iter()
1056            .fold(HashMap::new(), |mut acc, file| {
1057                let indices = acc.entry(file.file_id()).or_default();
1058                indices.insert(file);
1059                acc
1060            });
1061
1062        let eligible_for_delete: HashMap<FileId, HashSet<&RemovedFile>> = eligible_for_delete
1063            .iter()
1064            .fold(HashMap::new(), |mut acc, file| {
1065                let indices = acc.entry(file.file_id()).or_default();
1066                indices.insert(file);
1067                acc
1068            });
1069
1070        // Every listed object must be eligible before deleting an artifact. In
1071        // particular, an old part cannot bypass a younger manifest's grace period.
1072        let mut narthex_eligibility: HashMap<FileId, bool> = HashMap::new();
1073        for entry in entries {
1074            if let Some(file_id) = crate::sst::location::parse_narthex_file_id(entry.path()) {
1075                let in_manifest = in_manifest.contains_key(&file_id);
1076                let in_tmp_ref = referenced_ssts.contains(&file_id);
1077                let linger = may_linger_files.contains_key(&file_id);
1078                let eligible = eligible_for_delete.contains_key(&file_id);
1079                deferred_unknown |= is_deferred_unknown_file(
1080                    in_manifest,
1081                    in_tmp_ref,
1082                    linger,
1083                    eligible,
1084                    &entry,
1085                    unknown_file_may_linger_until,
1086                );
1087                let delete = should_delete_file(
1088                    in_manifest,
1089                    in_tmp_ref,
1090                    linger,
1091                    eligible,
1092                    &entry,
1093                    unknown_file_may_linger_until,
1094                );
1095                *narthex_eligibility.entry(file_id).or_insert(true) &= delete;
1096                continue;
1097            }
1098            if entry.name() == DROPPING_MARKER_FILE {
1099                continue;
1100            }
1101
1102            let (file_id, file_type) = match location::parse_sst_object_path(entry.name()) {
1103                Ok((file_id, file_type)) => (file_id, file_type),
1104                Err(err) => {
1105                    error!(err; "Failed to parse file id from path: {}", entry.name());
1106                    // if we can't parse the file id, it means it's not a sst or index file
1107                    // shouldn't delete it because we don't know what it is
1108                    GC_SKIPPED_UNPARSABLE_FILES.inc();
1109                    continue;
1110                }
1111            };
1112
1113            let should_delete = match file_type {
1114                SstObjectType::Parquet => {
1115                    let is_in_manifest = in_manifest.contains_key(&file_id);
1116                    let is_in_tmp_ref = referenced_ssts.contains(&file_id);
1117                    let is_linger = may_linger_files.contains_key(&file_id);
1118                    let is_eligible_for_delete = eligible_for_delete.contains_key(&file_id);
1119
1120                    deferred_unknown |= is_deferred_unknown_file(
1121                        is_in_manifest,
1122                        is_in_tmp_ref,
1123                        is_linger,
1124                        is_eligible_for_delete,
1125                        &entry,
1126                        unknown_file_may_linger_until,
1127                    );
1128                    should_delete_file(
1129                        is_in_manifest,
1130                        is_in_tmp_ref,
1131                        is_linger,
1132                        is_eligible_for_delete,
1133                        &entry,
1134                        unknown_file_may_linger_until,
1135                    )
1136                }
1137                SstObjectType::Puffin(version) => {
1138                    let is_in_manifest = in_manifest.get(&file_id) == Some(&Some(version));
1139                    let is_in_tmp_ref = in_tmp_ref.contains(&(file_id, Some(version)));
1140                    let is_linger = may_linger_files
1141                        .get(&file_id)
1142                        .map(|files| files.contains(&&RemovedFile::Index(file_id, version)))
1143                        .unwrap_or(false);
1144                    let is_eligible_for_delete = eligible_for_delete
1145                        .get(&file_id)
1146                        .map(|files| files.contains(&&RemovedFile::Index(file_id, version)))
1147                        .unwrap_or(false);
1148
1149                    deferred_unknown |= is_deferred_unknown_file(
1150                        is_in_manifest,
1151                        is_in_tmp_ref,
1152                        is_linger,
1153                        is_eligible_for_delete,
1154                        &entry,
1155                        unknown_file_may_linger_until,
1156                    );
1157                    should_delete_file(
1158                        is_in_manifest,
1159                        is_in_tmp_ref,
1160                        is_linger,
1161                        is_eligible_for_delete,
1162                        &entry,
1163                        unknown_file_may_linger_until,
1164                    )
1165                }
1166            };
1167
1168            if should_delete {
1169                let removed_file = match file_type {
1170                    SstObjectType::Parquet => {
1171                        // notice this cause we don't track index version for parquet files
1172                        // since entries comes from listing, we can't get index version from path
1173                        RemovedFile::File(file_id, None)
1174                    }
1175                    SstObjectType::Puffin(version) => {
1176                        GC_ORPHANED_INDEX_FILES.inc();
1177                        RemovedFile::Index(file_id, version)
1178                    }
1179                };
1180                ready_for_delete.push(removed_file);
1181            }
1182        }
1183        ready_for_delete.extend(
1184            narthex_eligibility
1185                .into_iter()
1186                .filter_map(|(id, eligible)| eligible.then_some(RemovedFile::Narthex(id))),
1187        );
1188        (ready_for_delete, deferred_unknown)
1189    }
1190
1191    /// List files to be deleted based on their presence in the manifest, temporary references, and recently removed files.
1192    /// Returns the `RemovedFile`s that are eligible for deletion and whether any
1193    /// unknown object was withheld by the young-object rule and needs a later pass.
1194    ///
1195    /// When `full_file_listing` is false, this method will only delete (subset of) files tracked in
1196    /// `recently_removed_files`, which significantly
1197    /// improves performance. When `full_file_listing` is true, it read from `all_entries` to find
1198    /// and delete orphan files (files not tracked in the manifest).
1199    ///
1200    pub async fn list_to_be_deleted_files(
1201        &self,
1202        region_id: RegionId,
1203        in_manifest: &HashMap<FileId, Option<IndexVersion>>,
1204        in_tmp_ref: &HashSet<(FileId, Option<IndexVersion>)>,
1205        recently_removed_files: BTreeMap<Timestamp, HashSet<RemovedFile>>,
1206        all_entries: Vec<Entry>,
1207    ) -> Result<(Vec<RemovedFile>, bool)> {
1208        let now = chrono::Utc::now();
1209        let may_linger_until = self
1210            .opt
1211            .lingering_time
1212            .map(|lingering_time| {
1213                chrono::Duration::from_std(lingering_time)
1214                    .with_context(|_| DurationOutOfRangeSnafu {
1215                        input: lingering_time,
1216                    })
1217                    .map(|t| now - t)
1218            })
1219            .transpose()?;
1220
1221        let unknown_file_may_linger_until = now
1222            - chrono::Duration::from_std(self.opt.unknown_file_lingering_time).with_context(
1223                |_| DurationOutOfRangeSnafu {
1224                    input: self.opt.unknown_file_lingering_time,
1225                },
1226            )?;
1227
1228        // files that may linger, which means they are not in use but may still be kept for a while
1229        let threshold =
1230            may_linger_until.map(|until| Timestamp::new_millisecond(until.timestamp_millis()));
1231        // TODO(discord9): if region is already closed, maybe handle threshold differently?
1232        // is consider all files to be recently removed acceptable?
1233        let mut recently_removed_files = recently_removed_files;
1234        let may_linger_files = match threshold {
1235            Some(threshold) => recently_removed_files.split_off(&threshold),
1236            None => BTreeMap::new(),
1237        };
1238        debug!("may_linger_files: {:?}", may_linger_files);
1239
1240        let all_may_linger_files = may_linger_files.values().flatten().collect::<HashSet<_>>();
1241
1242        // known files(tracked in removed files field) that are eligible for removal
1243        // (passed lingering time)
1244        let eligible_for_removal = recently_removed_files
1245            .values()
1246            .flatten()
1247            .collect::<HashSet<_>>();
1248
1249        // When full_file_listing is false, skip expensive list operations and only delete
1250        // files that are tracked in recently_removed_files
1251        if !self.full_file_listing {
1252            let referenced_ssts: HashSet<_> =
1253                in_tmp_ref.iter().map(|(file_id, _)| *file_id).collect();
1254            // Only delete files that:
1255            // 1. Are in recently_removed_files (tracked in manifest)
1256            // 2. Are not in use(in manifest or tmp ref)
1257            // 3. Have passed the lingering time
1258            let files_to_delete: Vec<RemovedFile> = eligible_for_removal
1259                .iter()
1260                .filter(|file| {
1261                    let in_use = match file {
1262                        RemovedFile::File(file_id, _) | RemovedFile::Narthex(file_id) => {
1263                            in_manifest.contains_key(file_id) || referenced_ssts.contains(file_id)
1264                        }
1265                        RemovedFile::Index(file_id, version) => {
1266                            in_manifest.get(file_id) == Some(&Some(*version))
1267                                || in_tmp_ref.contains(&(*file_id, Some(*version)))
1268                        }
1269                    };
1270                    !in_use
1271                })
1272                .map(|&f| f.clone())
1273                .collect();
1274
1275            info!(
1276                "gc: fast mode (no full listing) for region {}, found {} files to delete from manifest",
1277                region_id,
1278                files_to_delete.len()
1279            );
1280
1281            return Ok((files_to_delete, false));
1282        }
1283
1284        // Full file listing mode: get the full list of files from object store
1285
1286        // Step 3: Filter files to determine which ones can be deleted
1287        let all_unused_files_ready_for_delete = self.filter_deletable_files(
1288            all_entries,
1289            in_manifest,
1290            in_tmp_ref,
1291            &all_may_linger_files,
1292            &eligible_for_removal,
1293            unknown_file_may_linger_until,
1294        );
1295
1296        Ok(all_unused_files_ready_for_delete)
1297    }
1298}
1299
1300/// Generate partition prefixes based on concurrency and
1301/// assume file names are evenly-distributed uuid string,
1302/// to evenly distribute files across partitions.
1303/// For example, if concurrency is 2, partition prefixes will be:
1304/// ["8"] so it divide uuids into two partitions based on the first character.
1305/// If concurrency is 32, partition prefixes will be:
1306/// ["08", "10", "18", "20", "28", "30", "38" ..., "f0", "f8"]
1307/// if concurrency is 1, it returns an empty vector.
1308///
1309fn gen_partition_from_concurrency(concurrency: usize) -> Vec<String> {
1310    let n = concurrency.next_power_of_two();
1311    if n <= 1 {
1312        return vec![];
1313    }
1314
1315    // `d` is the number of hex characters required to build the partition key.
1316    // `p` is the total number of possible values for a key of length `d`.
1317    // We need to find the smallest `d` such that 16^d >= n.
1318    let mut d = 0;
1319    let mut p: u128 = 1;
1320    while p < n as u128 {
1321        p *= 16;
1322        d += 1;
1323    }
1324
1325    let total_space = p;
1326    let step = total_space / n as u128;
1327
1328    (1..n)
1329        .map(|i| {
1330            let boundary = i as u128 * step;
1331            format!("{:0width$x}", boundary, width = d)
1332        })
1333        .collect()
1334}
1335
1336#[cfg(test)]
1337mod tests {
1338    use super::*;
1339
1340    #[test]
1341    fn test_gen_partition_from_concurrency() {
1342        let partitions = gen_partition_from_concurrency(1);
1343        assert!(partitions.is_empty());
1344
1345        let partitions = gen_partition_from_concurrency(2);
1346        assert_eq!(partitions, vec!["8"]);
1347
1348        let partitions = gen_partition_from_concurrency(3);
1349        assert_eq!(partitions, vec!["4", "8", "c"]);
1350
1351        let partitions = gen_partition_from_concurrency(4);
1352        assert_eq!(partitions, vec!["4", "8", "c"]);
1353
1354        let partitions = gen_partition_from_concurrency(8);
1355        assert_eq!(partitions, vec!["2", "4", "6", "8", "a", "c", "e"]);
1356
1357        let partitions = gen_partition_from_concurrency(16);
1358        assert_eq!(
1359            partitions,
1360            vec![
1361                "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"
1362            ]
1363        );
1364
1365        let partitions = gen_partition_from_concurrency(32);
1366        assert_eq!(
1367            partitions,
1368            [
1369                "08", "10", "18", "20", "28", "30", "38", "40", "48", "50", "58", "60", "68", "70",
1370                "78", "80", "88", "90", "98", "a0", "a8", "b0", "b8", "c0", "c8", "d0", "d8", "e0",
1371                "e8", "f0", "f8",
1372            ]
1373        );
1374    }
1375
1376    #[test]
1377    fn test_gc_config_default_lingering_time() {
1378        assert_eq!(
1379            GcConfig::default().lingering_time,
1380            Some(Duration::from_secs(60 * 60))
1381        );
1382    }
1383}