Files
rustfs/crates/scanner/src/scanner_folder.rs
T
Hauser Zhi 9fe640ff3f perf(scanner): validate durable directory progress once (#9833)
* perf(scanner): validate durable directory progress once

Reuse the verified directory manifest for both listing and compacted progress. Compare saved bucket progress once per local turn and skip the initial snapshot when remote durable progress cannot be reported.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(scanner): bound directory progress lookups by path

Match checkpoint progress within each parent path while retaining exact replica and manifest checks. Search ancestor paths for compacted coverage and keep the direct path for single records.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(scanner): skip redundant snapshot coverage checks

Use the sealed frontier when available and validate only compacted receipts whose ranges can cover a missing frontier.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(scanner): reuse frontier digest at leader handoff

Validate the saved frontier once during checkpoint preparation and reuse its digest when retaining or migrating an accepted receipt. Preserve exact scope checks and validate legacy digest domains before migration.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 00:13:11 +08:00

3817 lines
159 KiB
Rust

// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::data_usage_define::clone_cache_value;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fs::FileType;
use std::io::ErrorKind;
use std::sync::{Arc, Mutex, Once};
use std::time::{Duration, Instant, SystemTime};
use crate::ReplTargetSizeSummary;
use crate::data_usage_define::{
DATA_USAGE_SCAN_CHECKPOINT_VERSION, DataUsageCache, DataUsageCacheInfo, DataUsageCacheSource, DataUsageEntry, DataUsageHash,
DataUsageHashMap, DataUsageRawEnumerationCursor, DataUsageScanCheckpoint, DataUsageScanCheckpointReason,
MAX_DATA_USAGE_CACHE_DEPTH, PendingScannerHeal, PendingScannerHealKind, ScannerSizeSummaryExt, SizeReconciliationEntry,
SizeSummary, hash_path, scan_frontier_covers_path,
};
use crate::error::ScannerError;
use crate::raw_page_index::{RawEnumerationPageIndex, RawEnumerationPageWriter};
use crate::runtime_config::{
scanner_alert_excess_folders, scanner_alert_excess_version_size, scanner_alert_excess_versions, scanner_yield_every_n_objects,
};
use crate::scanner_budget::{ScannerCycleBudget, ScannerCycleBudgetReason};
use crate::scanner_io::{ScannerIODisk as _, check_local_scanner_handle, is_scanner_source_unavailable, is_xl_meta_path};
use crate::sleeper::{DynamicSleeper, PacingDebt};
#[cfg(test)]
use crate::storage_api::owner::EcstoreLifecycleRule as LifecycleRule;
use crate::storage_api::owner::{
EcstoreBucketLifecycleConfiguration as BucketLifecycleConfiguration, EcstoreEventArgs,
EcstoreLifecycleRuleFilter as LifecycleRuleFilter, EcstoreObjectLockConfiguration as ObjectLockConfiguration,
EcstoreVersioningConfiguration as VersioningConfiguration, ecstore_send_event,
};
use crate::workload_admission::{run_scanner_metadata_operation, run_scanner_node_operation};
use metrics::{counter, describe_counter};
use rustfs_common::trace_bus::{TraceEvent, TraceFunc, TraceKind, trace_emit, trace_subscriber_count};
use rustfs_filemeta::{
MAX_META_CACHE_HEAL_CANDIDATES, MAX_META_CACHE_HEAL_TRUNCATED_OBJECTS, MetaCacheEntries, MetaCacheEntry,
MetaCacheHealCandidateKind,
};
use rustfs_heal_contracts::heal_channel::{
HEAL_DELETE_DANGLING, HealAdmissionDropReason, HealAdmissionResult, HealChannelPriority, HealChannelRequest,
HealRequestSource, HealScanMode, send_heal_request_with_receipt,
};
use rustfs_scanner_metrics::metrics::{
CloseDiskGuard, IlmAction, Metric, Metrics, ScannerReplicationRepairKind, ScannerSourceWorkUpdate, ScannerWorkSource,
UpdateCurrentPathFn, current_path_updater, global_metrics,
};
use rustfs_scanner_metrics::scan_observation::{ScannerCacheReuseDecision, ScannerCacheReuseGate, ScannerCacheReuseKind};
use rustfs_utils::path::{SLASH_SEPARATOR, path_join_buf};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use tokio::select;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, warn};
use crate::{
Disk, DiskError, DiskInfoOptions, Evaluator, Event, LcEventSrc, ListPathRawOptions, ObjectOpts, ReplicationConfig,
ReplicationHealObject, ReplicationQueueAdmission, ReplicationStatusType, STORAGE_FORMAT_FILE, ScannerDiskExt as _,
ScannerLifecycleConfigExt as _, ScannerVersioningConfigExt as _, StorageError, TierRegistrySnapshot, apply_expiry_rule,
apply_transition_rule, ecstore_lifecycle_version_delete_target, enqueue_runtime_newer_noncurrent,
is_reserved_or_invalid_bucket, list_path_raw, path2_bucket_object, path2_bucket_object_with_base_path,
queue_replication_heal, runtime_tier_registry_for_cycle, scanner_is_erasure, scanner_replication_config_for_lifecycle_eval,
};
use crate::{ScannerObjectInfo as ObjectInfo, ScannerObjectToDelete as ObjectToDelete};
const LOG_COMPONENT_SCANNER: &str = "scanner";
const LOG_SUBSYSTEM_FOLDER: &str = "folder";
const LOG_SUBSYSTEM_LIFECYCLE: &str = "lifecycle";
const LOG_SUBSYSTEM_HEAL: &str = "heal";
const EVENT_SCANNER_FOLDER_STATE: &str = "scanner_folder_state";
const EVENT_SCANNER_METADATA_CORRUPT: &str = "scanner_metadata_corrupt";
const EVENT_SCANNER_LIFECYCLE_ACTION: &str = "scanner_lifecycle_action";
const EVENT_SCANNER_HEAL_ADMISSION: &str = "scanner_heal_admission";
const EVENT_SCANNER_ALERT_STATE: &str = "scanner_alert_state";
const DATA_USAGE_UPDATE_DIR_CYCLES: u32 = 16;
const DATA_SCANNER_COMPACT_LEAST_OBJECT: usize = 500;
const DATA_SCANNER_COMPACT_AT_CHILDREN: usize = 10000;
const DATA_SCANNER_COMPACT_AT_FOLDERS: usize = DATA_SCANNER_COMPACT_AT_CHILDREN / 4;
const DATA_SCANNER_FORCE_COMPACT_AT_FOLDERS: usize = 250_000;
const SCANNER_LIST_PATH_RAW_STALL_TIMEOUT: Duration = Duration::from_secs(60);
const SCANNER_ENTRY_PROGRESS_BATCH: u64 = 32;
const SCANNER_ENTRY_PROGRESS_INTERVAL: Duration = Duration::from_secs(30);
const SCANNER_CHECKPOINT_OBJECT_INTERVAL: u64 = 1024;
const SCANNER_CHECKPOINT_MIN_INTERVAL: Duration = Duration::from_secs(5);
const SCANNER_CHECKPOINT_INTERVAL: Duration = Duration::from_secs(60);
const SCANNER_RAW_ENUMERATION_PAGE_ENTRY_LIMIT: usize = 128;
// Bound cooperative directory work without treating a batch boundary as EOF.
const SCANNER_DIRECTORY_BATCH_ENTRIES: usize = 64;
const DEFAULT_HEAL_OBJECT_SELECT_PROB: u32 = 1024;
const ENV_DATA_USAGE_UPDATE_DIR_CYCLES: &str = "RUSTFS_DATA_USAGE_UPDATE_DIR_CYCLES";
const ENV_HEAL_OBJECT_SELECT_PROB: &str = "RUSTFS_HEAL_OBJECT_SELECT_PROB";
const ENV_SCANNER_DEEP_VERIFY_COOLDOWN_SECS: &str = "RUSTFS_SCANNER_DEEP_VERIFY_COOLDOWN_SECS";
const ENV_FAILED_OBJECT_TTL_SECS: &str = "RUSTFS_DATA_USAGE_FAILED_OBJECT_TTL_SECS";
const ENV_FAILED_OBJECTS_MAX: &str = "RUSTFS_DATA_USAGE_FAILED_OBJECTS_MAX";
const DEFAULT_FAILED_OBJECT_TTL_SECS: u32 = 86_400;
const DEFAULT_FAILED_OBJECTS_MAX: u32 = 10_000;
const DEFAULT_SCANNER_DEEP_VERIFY_COOLDOWN_SECS: u64 = 60;
const METRIC_SCANNER_EXCESS_OBJECT_VERSIONS_TOTAL: &str = "rustfs_scanner_excess_object_versions_total";
const METRIC_SCANNER_EXCESS_OBJECT_VERSION_SIZE_TOTAL: &str = "rustfs_scanner_excess_object_version_size_total";
const METRIC_SCANNER_EXCESS_FOLDERS_TOTAL: &str = "rustfs_scanner_excess_folders_total";
const METRIC_SCANNER_PENDING_HEAL_PRUNE_TOTAL: &str = "rustfs_scanner_pending_heal_prune_total";
const METRIC_SCANNER_PENDING_HEAL_MALFORMED_TOTAL: &str = "rustfs_scanner_pending_heal_malformed_total";
const METRIC_SCANNER_HEAL_DISCOVERY_CANDIDATES_TOTAL: &str = "rustfs_scanner_heal_discovery_candidates_total";
const METRIC_SCANNER_HEAL_DISCOVERY_SUB_QUORUM_TOTAL: &str = "rustfs_scanner_heal_discovery_sub_quorum_total";
const METRIC_SCANNER_HEAL_DISCOVERY_UNVERIFIED_TOTAL: &str = "rustfs_scanner_heal_discovery_unverified_total";
const METRIC_SCANNER_HEAL_DISCOVERY_QUEUED_TOTAL: &str = "rustfs_scanner_heal_discovery_queued_total";
const METRIC_SCANNER_HEAL_DISCOVERY_TRUNCATED_TOTAL: &str = "rustfs_scanner_heal_discovery_truncated_total";
const MAX_PENDING_SCANNER_HEAL_RETRIES_PER_BUCKET: usize = 128;
const MAX_SIZE_RECONCILIATION_ENTRIES_PER_BUCKET: usize = 10_000;
const MAX_SIZE_RECONCILIATION_BYTES_PER_BUCKET: usize = 8 * 1024 * 1024;
const MAX_SIZE_RECONCILIATION_AGE_SECS: u64 = 7 * 24 * 60 * 60;
fn checkpoint_interval_for_build_time(build_time: Duration) -> Duration {
// Aim to spend at most a tenth of the interval building snapshots, while
// preserving the existing upper bound on periodic checkpoint attempts.
build_time
.saturating_mul(10)
.clamp(SCANNER_CHECKPOINT_MIN_INTERVAL, SCANNER_CHECKPOINT_INTERVAL)
}
// --- scanner excess alerts as S3 notification events (rustfs/backlog#1868) --
//
// The excess-versions / excess-version-size / excess-folders alerts were
// metrics-and-logs only; subscribers (consoles, external auditors) had no way
// to hear them. MinIO emits s3:ObjectManyVersions / s3:ObjectLargeVersions /
// s3:PrefixManyFolders for the same conditions — RustFS carries those as
// EventName::Scanner* with the wire names below. Without a cooldown a single
// over-threshold object would re-emit on every scan cycle (~a minute), so
// emissions are edge-held per (kind, bucket, object) for 24h.
/// `s3:Scanner:ManyVersions` (MinIO `s3:ObjectManyVersions`).
pub const EVENT_SCANNER_MANY_VERSIONS: &str = "s3:Scanner:ManyVersions";
/// `s3:Scanner:LargeVersions` (MinIO `s3:ObjectLargeVersions`).
pub const EVENT_SCANNER_LARGE_VERSIONS: &str = "s3:Scanner:LargeVersions";
/// `s3:Scanner:BigPrefix` (MinIO `s3:PrefixManyFolders`).
pub const EVENT_SCANNER_BIG_PREFIX: &str = "s3:Scanner:BigPrefix";
const ENV_SCANNER_ALERT_COOLDOWN_SECS: &str = "RUSTFS_SCANNER_ALERT_COOLDOWN_SECS";
const DEFAULT_SCANNER_ALERT_COOLDOWN_SECS: u64 = 86_400;
/// Hard cap on distinct cooldown keys; a pathological number of over-threshold
/// objects clears the map wholesale instead of growing without bound (the
/// worst case is one re-emission per still-hot key per scan cycle).
const MAX_SCANNER_ALERT_COOLDOWN_KEYS: usize = 4096;
/// Distinct alert kinds sharing one cooldown map.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum ScannerAlertKind {
ManyVersions,
LargeVersions,
BigPrefix,
}
type ScannerAlertCooldownKey = (ScannerAlertKind, String, String);
type ScannerAlertCooldownMap = HashMap<ScannerAlertCooldownKey, Instant>;
static SCANNER_ALERT_EMISSION_COOLDOWN: Mutex<Option<ScannerAlertCooldownMap>> = Mutex::new(None);
fn scanner_alert_cooldown() -> Duration {
let raw = std::env::var(ENV_SCANNER_ALERT_COOLDOWN_SECS)
.ok()
.and_then(|v| v.parse::<u64>().ok());
Duration::from_secs(raw.unwrap_or(DEFAULT_SCANNER_ALERT_COOLDOWN_SECS))
}
/// Edge-held emission gate: returns `true` (and records the cooldown) only
/// when this (kind, bucket, object) last fired longer than the cooldown ago —
/// or never. Metrics and logs stay level-triggered every cycle; only the
/// notification events are held back.
fn scanner_alert_emission_allows(kind: ScannerAlertKind, bucket: &str, object: &str, cooldown: Duration) -> bool {
let key = (kind, bucket.to_string(), object.to_string());
let mut guard = SCANNER_ALERT_EMISSION_COOLDOWN
.lock()
.unwrap_or_else(|poison| poison.into_inner());
let guard = guard.get_or_insert_with(ScannerAlertCooldownMap::new);
let now = Instant::now();
// Expired entries leave first; the cap is still exceeded only when live
// keys alone overflow it, in which case a wholesale clear trades one
// extra emission per hot key for a hard memory bound.
if guard.len() >= MAX_SCANNER_ALERT_COOLDOWN_KEYS {
guard.retain(|_, fired_at| now.duration_since(*fired_at) < cooldown);
if guard.len() >= MAX_SCANNER_ALERT_COOLDOWN_KEYS {
guard.clear();
}
}
match guard.get(&key) {
Some(fired_at) if now.duration_since(*fired_at) < cooldown => false,
_ => {
guard.insert(key, now);
true
}
}
}
/// Emit a scanner alert as an S3 notification event through the standard
/// dispatch pipeline. Fire-and-forget: the notify layer owns delivery,
/// retry, and target filtering; the scanner never waits on it.
fn emit_scanner_alert_event(
event_name: &str,
bucket: &str,
object: &str,
size: i64,
bucket_incarnation_id: Option<uuid::Uuid>,
details: &[(&str, String)],
) {
let mut req_params = HashMap::with_capacity(details.len());
for (key, value) in details {
req_params.insert((*key).to_string(), value.clone());
}
ecstore_send_event(EcstoreEventArgs {
event_name: event_name.to_string(),
bucket_incarnation_id,
bucket_name: bucket.to_string(),
object: crate::ScannerObjectInfo {
bucket: bucket.to_string(),
name: object.to_string(),
size,
..Default::default()
},
req_params,
user_agent: "Scanner".to_string(),
..Default::default()
});
}
const MAX_PENDING_SCANNER_HEALS_PER_BUCKET: usize = 10_000;
const MAX_PENDING_SCANNER_HEAL_AGE_SECS: u64 = 24 * 60 * 60;
static SCANNER_ALERT_METRICS_ONCE: Once = Once::new();
#[cfg(test)]
type ListPathRawTimeoutSnapshot = (bool, Option<Duration>, Option<Duration>);
fn scanner_abandoned_child_list_options() -> ListPathRawOptions {
// A complete heal walk scales with bucket size and may legitimately take
// longer than a fixed wall-clock budget. Keep the total duration unbounded;
// Retain the scanner's per-read stall budget and keep cancellation controlled
// by the scanner cycle token.
ListPathRawOptions {
skip_walkdir_total_timeout: true,
walkdir_stall_timeout: Some(SCANNER_LIST_PATH_RAW_STALL_TIMEOUT),
..Default::default()
}
}
pub fn data_usage_update_dir_cycles() -> u32 {
rustfs_utils::get_env_u32(ENV_DATA_USAGE_UPDATE_DIR_CYCLES, DATA_USAGE_UPDATE_DIR_CYCLES)
}
pub fn heal_object_select_prob() -> u32 {
rustfs_utils::get_env_u32(ENV_HEAL_OBJECT_SELECT_PROB, DEFAULT_HEAL_OBJECT_SELECT_PROB)
}
fn deep_verify_cooldown() -> Duration {
Duration::from_secs(rustfs_utils::get_env_u64(
ENV_SCANNER_DEEP_VERIFY_COOLDOWN_SECS,
DEFAULT_SCANNER_DEEP_VERIFY_COOLDOWN_SECS,
))
}
fn object_is_within_deep_verify_cooldown(mod_time: Option<OffsetDateTime>, now: OffsetDateTime, cooldown: Duration) -> bool {
let Some(mod_time) = mod_time else {
return false;
};
let Ok(cooldown) = time::Duration::try_from(cooldown) else {
return false;
};
mod_time > now - cooldown
}
fn effective_object_heal_scan_mode(heal_bitrot: bool, mod_time: Option<OffsetDateTime>, now: OffsetDateTime) -> HealScanMode {
if !heal_bitrot {
return HealScanMode::Normal;
}
if object_is_within_deep_verify_cooldown(mod_time, now, deep_verify_cooldown()) {
HealScanMode::Normal
} else {
HealScanMode::Deep
}
}
fn ensure_scanner_alert_metrics_registered() {
SCANNER_ALERT_METRICS_ONCE.call_once(|| {
describe_counter!(
METRIC_SCANNER_EXCESS_OBJECT_VERSIONS_TOTAL,
"Total scanner alerts for objects with too many retained versions."
);
describe_counter!(
METRIC_SCANNER_EXCESS_OBJECT_VERSION_SIZE_TOTAL,
"Total scanner alerts for objects whose retained versions exceed the cumulative size threshold."
);
describe_counter!(
METRIC_SCANNER_EXCESS_FOLDERS_TOTAL,
"Total scanner alerts for folders with too many direct subfolders."
);
});
}
fn scanner_excess_versions_threshold() -> u64 {
scanner_alert_excess_versions()
}
fn scanner_excess_version_size_threshold() -> u64 {
scanner_alert_excess_version_size()
}
fn scanner_excess_folders_threshold() -> u64 {
scanner_alert_excess_folders()
}
fn should_yield_after_object(object_count: u64, yield_every: u64) -> bool {
yield_every > 0 && object_count.is_multiple_of(yield_every)
}
const SCANNER_FAILED_OBJECT_LOG_INITIAL_LIMIT: usize = 16;
const SCANNER_FAILED_OBJECT_LOG_EVERY: usize = 1024;
fn should_log_failed_object(failed_objects: usize) -> bool {
failed_objects <= SCANNER_FAILED_OBJECT_LOG_INITIAL_LIMIT || failed_objects.is_multiple_of(SCANNER_FAILED_OBJECT_LOG_EVERY)
}
fn record_scanner_ilm_action_if_queued(metrics: &Metrics, action: IlmAction, count: u64, queued: bool) -> bool {
if queued {
metrics.record_scanner_lifecycle_action(action, count);
}
queued
}
fn scanner_replication_work_update(admission: ReplicationQueueAdmission) -> ScannerSourceWorkUpdate {
match admission {
ReplicationQueueAdmission::Queued => ScannerSourceWorkUpdate::queued(1),
ReplicationQueueAdmission::Missed => ScannerSourceWorkUpdate::missed(1),
ReplicationQueueAdmission::Skipped => ScannerSourceWorkUpdate {
skipped: 1,
..Default::default()
},
}
}
fn scanner_replication_repair_kind(roi: &ReplicationHealObject) -> Option<ScannerReplicationRepairKind> {
if roi.is_empty_identity() {
return None;
}
if roi.is_existing_object_repair() {
Some(ScannerReplicationRepairKind::BucketExistingObject)
} else if roi.has_version_purge_status() {
Some(ScannerReplicationRepairKind::BucketVersionPurge)
} else if roi.delete_marker {
Some(ScannerReplicationRepairKind::BucketDeleteMarker)
} else {
Some(ScannerReplicationRepairKind::BucketObject)
}
}
fn record_scanner_replication_admission(metrics: &Metrics, roi: &ReplicationHealObject, admission: ReplicationQueueAdmission) {
let work = scanner_replication_work_update(admission);
metrics.record_scanner_source_work(ScannerWorkSource::BucketReplication, work);
if let Some(kind) = scanner_replication_repair_kind(roi) {
metrics.record_scanner_replication_repair_work(kind, work);
}
}
fn scanner_heal_source(scan_mode: HealScanMode) -> ScannerWorkSource {
match scan_mode {
HealScanMode::Deep => ScannerWorkSource::Bitrot,
HealScanMode::Unknown | HealScanMode::Normal => ScannerWorkSource::Heal,
}
}
fn record_scanner_heal_admission(metrics: &Metrics, scan_mode: HealScanMode, admission: Result<HealAdmissionResult, ()>) -> bool {
let (work, admitted) = match admission {
Ok(HealAdmissionResult::Accepted) => (ScannerSourceWorkUpdate::queued(1), true),
Ok(HealAdmissionResult::Merged) => (
ScannerSourceWorkUpdate {
skipped: 1,
..Default::default()
},
true,
),
Ok(HealAdmissionResult::Full | HealAdmissionResult::Dropped(_)) | Err(_) => (ScannerSourceWorkUpdate::missed(1), false),
};
metrics.record_scanner_source_work(scanner_heal_source(scan_mode), work);
admitted
}
#[derive(Clone, Copy)]
struct PendingScannerAccounting<'a> {
object: &'a ObjectInfo,
retained_size: i64,
expired_size: i64,
}
impl PendingScannerAccounting<'_> {
fn apply(self, size_summary: &mut SizeSummary, cumulative_size: &mut i64, queued: bool) {
let size = if queued { self.expired_size } else { self.retained_size };
size_summary.actions_accounting(self.object, size, self.retained_size);
*cumulative_size = cumulative_size.saturating_add(size);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FolderResumeMatch {
Exact,
Descendant,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FolderResumeOrder {
NoHint,
Used,
Stale,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FolderScanSource {
New,
Existing,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum FolderScanMode {
Namespace,
ErasureCandidate {
reuse_namespace: bool,
parent_has_metadata: bool,
},
}
#[derive(Debug, PartialEq, Eq)]
enum FolderScanOutcome {
Namespace,
ErasureData,
Vanished,
}
fn is_erasure_candidate(name: &str) -> bool {
name.rsplit('/')
.next()
.is_some_and(|name| uuid::Uuid::parse_str(name).is_ok_and(|id| !id.is_nil()))
}
#[derive(Clone, Debug)]
struct QueuedFolder {
folder: CachedFolder,
source: FolderScanSource,
}
fn folder_resume_match(folder_name: &str, resume_after: &str) -> Option<FolderResumeMatch> {
if resume_after == folder_name {
return Some(FolderResumeMatch::Exact);
}
resume_after
.strip_prefix(folder_name)
.filter(|suffix| suffix.starts_with(SLASH_SEPARATOR))
.map(|_| FolderResumeMatch::Descendant)
}
fn order_items_for_resume<T, F>(items: &mut [T], resume_after: Option<&str>, name: F) -> FolderResumeOrder
where
F: Fn(&T) -> &str,
{
items.sort_by(|left, right| name(left).cmp(name(right)));
let Some(resume_after) = resume_after.filter(|resume_after| !resume_after.is_empty()) else {
return FolderResumeOrder::NoHint;
};
let Some((resume_index, resume_match)) = items
.iter()
.enumerate()
.find_map(|(index, item)| folder_resume_match(name(item), resume_after).map(|resume_match| (index, resume_match)))
else {
return FolderResumeOrder::Stale;
};
let rotate_by = match resume_match {
FolderResumeMatch::Exact => resume_index + 1,
FolderResumeMatch::Descendant => resume_index,
};
if rotate_by < items.len() {
items.rotate_left(rotate_by);
}
FolderResumeOrder::Used
}
#[cfg(test)]
fn order_folders_for_resume(folders: &mut [CachedFolder], resume_after: Option<&str>) -> FolderResumeOrder {
order_items_for_resume(folders, resume_after, |folder| folder.name.as_str())
}
fn order_queued_folders_for_resume(folders: &mut [QueuedFolder], resume_after: Option<&str>) -> FolderResumeOrder {
order_items_for_resume(folders, resume_after, |folder| folder.folder.name.as_str())
}
fn checkpoint_reason_from_budget(reason: Option<ScannerCycleBudgetReason>) -> DataUsageScanCheckpointReason {
match reason {
Some(ScannerCycleBudgetReason::Runtime) => DataUsageScanCheckpointReason::Runtime,
Some(ScannerCycleBudgetReason::Objects) => DataUsageScanCheckpointReason::Objects,
// This enum is persisted and older readers reject unknown variants.
Some(ScannerCycleBudgetReason::Directories | ScannerCycleBudgetReason::Entries) => {
DataUsageScanCheckpointReason::Directories
}
None => DataUsageScanCheckpointReason::Unknown,
}
}
// Cache entry failures survive diagnostic retry-cache TTL and capacity eviction.
// Index once per scan; resumed subtree checks must not flatten histograms repeatedly.
fn failed_scan_paths(cache: &DataUsageCache) -> Vec<String> {
let mut paths = cache
.cache
.iter()
.filter(|(_, entry)| entry.failed_objects > 0)
.map(|(path, _)| clone_cache_value(path))
.collect::<Vec<_>>();
paths.sort_unstable();
paths
}
fn data_usage_entry_has_progress(entry: &DataUsageEntry) -> bool {
data_usage_root_has_progress(entry)
}
#[cfg(test)]
tokio::task_local! {
static TEST_FORCE_COMPACTION_WIDTH: usize;
}
fn force_compaction_width() -> usize {
#[cfg(test)]
if let Ok(width) = TEST_FORCE_COMPACTION_WIDTH.try_with(|width| *width) {
return width;
}
DATA_SCANNER_FORCE_COMPACT_AT_FOLDERS
}
/// Root-fanout limit for `DataUsageCache::force_compact` at the end of a sweep.
///
/// An interrupted sweep still has to seal its resume frontier, so it keeps the
/// emergency ceiling. A finished walk applies the ordinary child limit.
fn force_compact_limit_for_sweep(interrupted: bool) -> usize {
if interrupted {
DATA_SCANNER_FORCE_COMPACT_AT_FOLDERS
} else {
DATA_SCANNER_COMPACT_AT_CHILDREN
}
}
fn set_scan_checkpoint(cache: &mut DataUsageCache, reason: DataUsageScanCheckpointReason) {
let resume_after = clone_cache_value(&cache.info.scan_resume_after).or_else(|| {
cache
.info
.scan_checkpoint
.as_ref()
.map(|checkpoint| clone_cache_value(&checkpoint.resume_after))
});
if let Some(resume_after) = resume_after {
let checkpoint = DataUsageScanCheckpoint::new(resume_after, reason);
global_metrics().record_scanner_checkpoint_set(
checkpoint.version,
checkpoint.resume_after.clone(),
checkpoint.reason.as_str(),
);
cache.info.scan_checkpoint = Some(checkpoint);
} else {
cache.info.scan_checkpoint = None;
}
}
fn should_alert_excessive_versions(remaining_versions: usize, cumulative_size: i64) -> (bool, bool) {
let too_many_versions = remaining_versions as u64 >= scanner_excess_versions_threshold();
let too_large_versions = cumulative_size > 0 && cumulative_size as u64 >= scanner_excess_version_size_threshold();
(too_many_versions, too_large_versions)
}
fn non_negative_i64_to_u64(value: i64) -> u64 {
value.max(0) as u64
}
fn trace_start_instant() -> Option<Instant> {
(trace_subscriber_count() > 0).then(Instant::now)
}
fn emit_scanner_folder_trace(root: &str, folder: &str, objects: u64, started_at: Option<Instant>, state: &'static str) {
let Some(started_at) = started_at else {
return;
};
trace_emit(|| {
let (bucket, prefix) = path2_bucket_object_with_base_path(root, folder);
TraceEvent::new(TraceKind::Scanner, TraceFunc::ScannerFolder)
.with_bucket(bucket)
.with_object(prefix)
.with_duration(started_at.elapsed())
.with_attr("state", state)
.with_attr("objects", objects)
});
}
fn emit_scanner_ilm_action_trace(
bucket: &str,
object: &str,
action: IlmAction,
count: u64,
queued: bool,
started_at: Option<Instant>,
) {
let Some(started_at) = started_at else {
return;
};
let state = if queued { "queued" } else { "not_queued" };
trace_emit(|| {
TraceEvent::new(TraceKind::Scanner, TraceFunc::ScannerIlmAction)
.with_bucket(bucket)
.with_object(object)
.with_duration(started_at.elapsed())
.with_attr("state", state)
.with_attr("action", action.as_str())
.with_attr("count", count)
.with_attr("queued", queued)
});
}
struct ScannerHealCandidateTraceContext {
bucket: String,
object: Option<String>,
version_id: Option<String>,
scan_mode: Option<HealScanMode>,
started_at: Instant,
}
fn scanner_heal_candidate_trace_context(request: &HealChannelRequest) -> Option<ScannerHealCandidateTraceContext> {
let started_at = trace_start_instant()?;
Some(ScannerHealCandidateTraceContext {
bucket: request.bucket.clone(),
object: request.object_prefix.clone(),
version_id: request.object_version_id.clone(),
scan_mode: request.scan_mode,
started_at,
})
}
struct ScannerHealCandidateTrace<'a> {
candidate_type: &'static str,
bucket: &'a str,
object: Option<&'a str>,
version_id: Option<&'a str>,
priority: HealChannelPriority,
scan_mode: Option<HealScanMode>,
result: Result<HealAdmissionResult, &'a str>,
started_at: Instant,
}
fn emit_scanner_heal_candidate_trace(trace: ScannerHealCandidateTrace<'_>) {
trace_emit(|| {
let (state, admission, error) = match trace.result {
Ok(result) if result.is_admitted() => ("admitted", describe_heal_admission(result), None),
Ok(result) => ("not_admitted", describe_heal_admission(result), None),
Err(error) => ("submit_failed", "channel_error".to_string(), Some(error)),
};
let mut event = TraceEvent::new(TraceKind::Scanner, TraceFunc::ScannerHealCandidate)
.with_bucket(trace.bucket)
.with_duration(trace.started_at.elapsed())
.with_attr("state", state)
.with_attr("candidate_type", trace.candidate_type)
.with_attr("priority", heal_priority_label(trace.priority))
.with_attr("admission", admission);
if let Some(object) = trace.object {
event = event.with_object(object);
}
if let Some(version_id) = trace.version_id {
event = event.with_attr("version_id", version_id);
}
if let Some(scan_mode) = trace.scan_mode {
event = event.with_attr("scan_mode", scan_mode.as_str());
}
if let Some(error) = error {
event = event.with_attr("error", error);
}
event
});
}
fn apply_scanner_size_summary(into: &mut DataUsageEntry, summary: &SizeSummary) {
into.size = into.size.saturating_add(summary.total_size);
into.versions = into.versions.saturating_add(summary.versions);
into.delete_markers = into.delete_markers.saturating_add(summary.delete_markers);
into.obj_sizes.add(u64::try_from(summary.total_size).unwrap_or(u64::MAX));
into.obj_versions.add(u64::try_from(summary.versions).unwrap_or(u64::MAX));
let replication_stats = into.replication_stats.get_or_insert_with(Default::default);
replication_stats.replica_size = replication_stats
.replica_size
.saturating_add(non_negative_i64_to_u64(summary.replica_size));
replication_stats.replica_count = replication_stats
.replica_count
.saturating_add(u64::try_from(summary.replica_count).unwrap_or(u64::MAX));
for (arn, st) in &summary.repl_target_stats {
let tgt_stat = replication_stats.targets.entry(arn.clone()).or_default();
tgt_stat.pending_size = tgt_stat.pending_size.saturating_add(non_negative_i64_to_u64(st.pending_size));
tgt_stat.failed_size = tgt_stat.failed_size.saturating_add(non_negative_i64_to_u64(st.failed_size));
tgt_stat.replicated_size = tgt_stat
.replicated_size
.saturating_add(non_negative_i64_to_u64(st.replicated_size));
tgt_stat.replicated_count = tgt_stat
.replicated_count
.saturating_add(u64::try_from(st.replicated_count).unwrap_or(u64::MAX));
tgt_stat.failed_count = tgt_stat
.failed_count
.saturating_add(u64::try_from(st.failed_count).unwrap_or(u64::MAX));
tgt_stat.pending_count = tgt_stat
.pending_count
.saturating_add(u64::try_from(st.pending_count).unwrap_or(u64::MAX));
}
into.add_tier_sizes(&summary.tier_stats);
into.add_unknown_tier_stats(&summary.unknown_tier_stats);
into.tier_accounting_proof = match (into.tier_accounting_proof, Some(summary.tier_accounting_proof)) {
(Some(mut current), Some(next)) => {
current.saturating_add(next);
Some(current)
}
(Some(_), None) => None,
(None, next) => next,
};
if into.unknown_tier_stats.as_ref().is_some_and(|stats| stats.counter_overflowed)
&& let Some(proof) = into.tier_accounting_proof.as_mut()
{
proof.overflowed = true;
}
}
fn data_usage_root_has_progress(root: &DataUsageEntry) -> bool {
!root.children.is_empty()
|| root.size > 0
|| root.objects > 0
|| root.versions > 0
|| root.delete_markers > 0
|| root.failed_objects > 0
|| root.replication_stats.is_some()
|| root.all_tier_stats.as_ref().is_some_and(|stats| !stats.is_empty())
|| root.unknown_tier_stats.as_ref().is_some_and(|stats| !stats.is_empty())
}
fn partial_cache_is_useful(root: &DataUsageEntry, pending_heals_changed: bool) -> bool {
data_usage_root_has_progress(root) || pending_heals_changed
}
/// Process-local hint that narrows a dirty bucket scan to known changed direct children.
///
/// The hint is used only while rebuilding a complete bucket cache. It never
/// changes usage publication semantics and callers must discard it when the
/// mutation source cannot be verified.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScannerBucketPrefixScanScope {
selected_top_level_entries: Arc<HashSet<String>>,
}
impl ScannerBucketPrefixScanScope {
pub(crate) fn from_dirty_top_level_entries(entries: HashSet<String>) -> Option<Self> {
(!entries.is_empty()).then(|| Self {
selected_top_level_entries: Arc::new(entries),
})
}
fn contains(&self, entry: &str) -> bool {
self.selected_top_level_entries.contains(entry)
}
}
/// Folder scanner for scanning directory structures
#[derive(Default)]
struct ScannerCheckpointAncestor {
hash: DataUsageHash,
entry: DataUsageEntry,
}
struct ScannerUsageUpdates {
sender: mpsc::Sender<DataUsageEntry>,
cache: DataUsageCache,
last_update: SystemTime,
}
impl ScannerUsageUpdates {
fn new(sender: mpsc::Sender<DataUsageEntry>, bucket: String) -> Self {
Self {
sender,
cache: DataUsageCache {
info: DataUsageCacheInfo {
name: bucket,
..Default::default()
},
..Default::default()
},
last_update: SystemTime::UNIX_EPOCH,
}
}
fn is_due(&self) -> bool {
self.last_update.elapsed().unwrap_or(Duration::ZERO) >= Duration::from_secs(60)
}
}
pub struct FolderScanner {
root: String,
old_cache: DataUsageCache,
new_cache: DataUsageCache,
data_usage_scanner_debug: bool,
heal_object_select: u32,
scan_mode: HealScanMode,
is_erasure_mode: bool,
prefix_scan_scope: Option<ScannerBucketPrefixScanScope>,
failed_object_ttl_secs: u64,
failed_objects_max: usize,
failed_object_paths_seen: HashSet<String>,
resolved_failed_object_paths: HashSet<String>,
sleeper: DynamicSleeper,
pacing_debt: PacingDebt,
node_admission: Option<Arc<rustfs_concurrency::adaptive::NodeAdmission>>,
// should_heal: Arc<dyn Fn() -> bool + Send + Sync>,
disks: Vec<Arc<Disk>>,
disks_quorum: usize,
usage_updates: Option<ScannerUsageUpdates>,
checkpoint_tx: Option<mpsc::Sender<DataUsageCache>>,
checkpoint_ancestors: Vec<ScannerCheckpointAncestor>,
checkpoint_depth: usize,
checkpoint_objects: u64,
object_metadata_visits: metrics::Counter,
#[cfg(feature = "diagnostic-prefix-attribution")]
prefix_attribution: Option<prefix_attribution::VisitAttribution>,
last_checkpoint_objects: u64,
last_checkpoint_at: Instant,
last_checkpoint_build_time: Duration,
update_current_path: UpdateCurrentPathFn,
budget: Arc<ScannerCycleBudget>,
skip_heal: Arc<std::sync::atomic::AtomicBool>,
local_disk: Arc<Disk>,
/// Identity captured at the start of this bucket scan. Events produced by
/// the scan remain unbound when the identity cannot be established.
pub(crate) notification_bucket_incarnation: Option<uuid::Uuid>,
local_stop: Option<Arc<crate::scanner_io::ScannerLocalStop>>,
/// Tier registry frozen for this folder scan. A refresh applies to the
/// next scan and cannot mix generations in one aggregate.
tier_registry: TierRegistrySnapshot,
pending_heals_changed: bool,
coverage_frontier: Option<String>,
resume_frontier: Option<String>,
resume_failed_paths: Vec<String>,
coverage_gap: bool,
raw_enumeration_progress: Vec<RawEnumerationProgress>,
directory_checkpoints: HashMap<String, HashMap<String, directory_cursor::Saved>>,
pending_size_reconciliation_keys: HashSet<String>,
pending_size_reconciliation_scopes: HashSet<String>,
pending_size_reconciliation_truncated: bool,
#[cfg(test)]
list_path_raw_options_observer: Option<mpsc::UnboundedSender<ListPathRawTimeoutSnapshot>>,
#[cfg(test)]
defer_abandoned_entries_until_finished: bool,
#[cfg(test)]
partial_heal_candidate_limit: Option<usize>,
#[cfg(test)]
partial_heal_discovery_observer: Option<mpsc::UnboundedSender<(usize, usize)>>,
}
struct RawEnumerationProgress {
parent: String,
last_entry: Option<String>,
entries_seen: u64,
digest: Sha256,
page_index: Option<RawEnumerationPageWriter>,
sealed_pages: Option<(RawEnumerationPageIndex, usize)>,
}
impl RawEnumerationProgress {
fn new(parent: &str, page_index: Option<RawEnumerationPageIndex>) -> Self {
let mut digest = Sha256::new();
update_raw_enumeration_digest(&mut digest, b"parent", parent.as_bytes());
let page_index = page_index
.or_else(|| RawEnumerationPageIndex::new(parent, SCANNER_RAW_ENUMERATION_PAGE_ENTRY_LIMIT).ok())
.and_then(|index| RawEnumerationPageWriter::new(index).ok());
Self {
parent: parent.to_string(),
last_entry: None,
entries_seen: 0,
digest,
page_index,
sealed_pages: None,
}
}
fn from_sealed(parent: &str, index: &RawEnumerationPageIndex) -> Option<Self> {
use crate::raw_page_index::RawEnumerationPageOwnerStatus;
let count = match index.status() {
RawEnumerationPageOwnerStatus::Building { indexed_entries, .. }
| RawEnumerationPageOwnerStatus::Ready { indexed_entries, .. } => usize::try_from(indexed_entries).ok()?,
RawEnumerationPageOwnerStatus::Unsupported => return None,
};
if count == 0 {
return None;
}
Some(Self {
parent: parent.to_owned(),
last_entry: None,
entries_seen: 0,
digest: Sha256::new(),
page_index: None,
sealed_pages: Some((index.clone(), count)),
})
}
fn record_entry(&mut self, entry: &str) {
if let Some((index, _)) = self.sealed_pages.take() {
*self = Self::new(&self.parent, Some(index));
}
update_raw_enumeration_digest(&mut self.digest, b"entry", entry.as_bytes());
self.last_entry = Some(entry.to_string());
self.entries_seen = self.entries_seen.saturating_add(1);
if let Some(index) = &mut self.page_index
&& index.record_entry(entry).is_err()
{
self.page_index = None;
}
}
fn cursor(&self) -> Option<DataUsageRawEnumerationCursor> {
if self.entries_seen == 0 {
return None;
}
Some(DataUsageRawEnumerationCursor::new(
clone_cache_value(&self.parent),
clone_cache_value(&self.last_entry),
self.entries_seen,
self.digest.clone().finalize().into(),
))
}
fn page_index(&self) -> Option<RawEnumerationPageIndex> {
if let Some((index, _)) = &self.sealed_pages {
return Some(index.clone());
}
self.page_index
.as_ref()
.filter(|index| index.indexed_entry_count() > 0)
.and_then(|index| index.checkpoint().ok())
}
fn has_checkpointable_page_index(&self) -> bool {
self.checkpointable_entry_count() > 0
}
fn checkpointable_entry_count(&self) -> usize {
if let Some((_, count)) = &self.sealed_pages {
return *count;
}
self.page_index
.as_ref()
.map_or(0, RawEnumerationPageWriter::indexed_entry_count)
}
}
fn update_raw_enumeration_digest(digest: &mut Sha256, label: &[u8], value: &[u8]) {
digest.update(label);
digest.update(u64::try_from(value.len()).unwrap_or(u64::MAX).to_le_bytes());
digest.update(value);
}
fn size_reconciliation_entry_bytes(entry: &SizeReconciliationEntry) -> usize {
entry.key.len()
+ entry.bucket.len()
+ entry.object.len()
+ entry.version_id.as_deref().map_or(0, str::len)
+ entry.generation.as_deref().map_or(0, str::len)
+ entry.reason.len()
+ std::mem::size_of::<u64>()
+ std::mem::size_of::<u32>()
}
fn size_reconciliation_scope_key(bucket: &str, object: &str) -> String {
format!("{}:{}|{}:{}", bucket.len(), bucket, object.len(), object)
}
fn prune_size_reconciliation(info: &mut DataUsageCacheInfo, now: u64) {
info.size_reconciliation.retain(|key, entry| {
if entry.first_seen == 0 || entry.first_seen > now {
entry.first_seen = now;
}
key == &entry.key
&& entry.key.len() <= 4096
&& entry.bucket.len() <= 512
&& entry.object.len() <= 512
&& entry.version_id.as_deref().is_none_or(|value| value.len() <= 64)
&& entry.generation.as_deref().is_none_or(|value| value.len() <= 64)
&& entry.reason.len() <= 64
&& now.saturating_sub(entry.first_seen) <= MAX_SIZE_RECONCILIATION_AGE_SECS
});
while info.size_reconciliation.len() > MAX_SIZE_RECONCILIATION_ENTRIES_PER_BUCKET
|| info
.size_reconciliation
.values()
.map(size_reconciliation_entry_bytes)
.sum::<usize>()
> MAX_SIZE_RECONCILIATION_BYTES_PER_BUCKET
{
let oldest = info
.size_reconciliation
.iter()
.min_by(|(left_key, left), (right_key, right)| {
left.first_seen.cmp(&right.first_seen).then_with(|| left_key.cmp(right_key))
})
.map(|(key, _)| clone_cache_value(key));
let Some(oldest) = oldest else {
break;
};
info.size_reconciliation.remove(&oldest);
}
}
async fn wait_for_scanner_io<T>(ctx: &CancellationToken, wait: impl std::future::Future<Output = T>) -> Result<T, ScannerError> {
select! {
biased;
_ = ctx.cancelled() => Err(ScannerError::Other("Operation cancelled".to_string())),
result = wait => Ok(result),
}
}
pub(crate) use directory_cursor::parked_bucket_disks;
use directory_cursor::{DirectoryScope, ScannerDirectory};
struct DirectoryStream {
reader: native_io::ReadDir,
#[cfg(test)]
ordered: Option<tests::erasure_probe::OrderedEntries>,
}
impl DirectoryStream {
async fn open_at(path: &str, anchor: &native_io::DirectoryAnchor) -> std::io::Result<Self> {
Ok(Self {
reader: native_io::ReadDir::open_at(path, anchor).await?,
#[cfg(test)]
ordered: None,
})
}
async fn open(path: &str, indexed: bool) -> std::io::Result<Self> {
let reader = native_io::ReadDir::open(path, indexed).await?;
#[cfg(test)]
let (reader, ordered) = {
let mut reader = reader;
let ordered = tests::erasure_probe::ordered_entries(path, &mut reader).await?;
(reader, ordered)
};
Ok(Self {
reader,
#[cfg(test)]
ordered,
})
}
async fn next_entry(&mut self) -> std::io::Result<Option<native_io::DirEntry>> {
#[cfg(test)]
if let Some(entries) = &mut self.ordered {
return entries.pop_front().transpose();
}
self.reader.next_entry().await
}
}
async fn next_scanner_dir_entry(
ctx: &CancellationToken,
sleeper: &DynamicSleeper,
entries: &mut ScannerDirectory,
admission: Option<&Arc<rustfs_concurrency::adaptive::NodeAdmission>>,
) -> Result<Option<native_io::DirEntry>, ScannerError> {
if entries.batch_entries == SCANNER_DIRECTORY_BATCH_ENTRIES {
wait_for_scanner_io(ctx, tokio::task::yield_now()).await?;
entries.batch_entries = 0;
}
let entry = wait_for_scanner_io(ctx, run_scanner_node_operation(admission, ctx, entries.peek_entry())).await???;
if entry.as_ref().is_some_and(|item| !item.is_recorded()) {
// Tokio prefetches bounded chunks. Pacing consumption also paces the
// next refill, without charging an extra entry for EOF.
wait_for_scanner_io(ctx, sleeper.admit_disk_io(1, 0)).await?;
}
if entry.is_some() {
entries.accept_entry();
entries.batch_entries += 1;
}
Ok(entry)
}
impl FolderScanner {
fn now_secs() -> u64 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
fn should_reuse_clean_root_child(
&self,
folder: &CachedFolder,
into: &DataUsageEntry,
child_name: &str,
child_hash: &DataUsageHash,
abandoned_children: &DataUsageHashMap,
) -> bool {
let decision = if let Some(prefix_scan_scope) = &self.prefix_scan_scope {
if folder.parent.is_some() || folder.name != self.old_cache.info.name {
ScannerCacheReuseDecision::NotRoot
} else if into.compacted {
ScannerCacheReuseDecision::CompactedParent
} else if !abandoned_children.contains(&child_hash.0) {
ScannerCacheReuseDecision::MissingCachedChild
} else if let Some(entry) = child_name
.strip_prefix(folder.name.as_str())
.and_then(|entry| entry.strip_prefix('/'))
{
if entry.is_empty() || entry.contains('/') {
ScannerCacheReuseDecision::InvalidPrefix
} else if prefix_scan_scope.contains(entry) {
ScannerCacheReuseDecision::DirtyPrefix
} else if self.is_erasure_mode {
// EC scans must still perform independent object-health work.
global_metrics().scan_observation().record_erasure_clean_prefix_walk();
ScannerCacheReuseDecision::ErasureHealthRequired
} else {
ScannerCacheReuseDecision::Eligible
}
} else {
ScannerCacheReuseDecision::InvalidPrefix
}
} else {
ScannerCacheReuseDecision::MissingScope
};
global_metrics()
.scan_observation()
.record_cache_reuse_decision(ScannerCacheReuseGate::CleanPrefix, decision);
decision == ScannerCacheReuseDecision::Eligible
}
fn can_reuse_scoped_child(&self, folder: &CachedFolder, into: &DataUsageEntry, name: &str, hash: &DataUsageHash) -> bool {
self.prefix_scan_scope.is_some()
&& self
.old_cache
.find(&folder.name)
.is_some_and(|parent| self.should_reuse_clean_root_child(folder, into, name, hash, &parent.children))
}
fn can_restore_linked_child(&self, folder: &CachedFolder, into: &DataUsageEntry, name: &str) -> bool {
self.can_reuse_covered_namespace(name, false)
|| (self.prefix_scan_scope.is_some()
&& self.old_cache.find(name).is_some()
&& self.can_reuse_scoped_child(folder, into, name, &hash_path(name)))
}
fn reuse_clean_root_child(&mut self, child: &CachedFolder, child_hash: &DataUsageHash, into: &mut DataUsageEntry) {
let started = Instant::now();
self.new_cache.copy_with_children(&self.old_cache, child_hash, &child.parent);
if let Some(updates) = &mut self.usage_updates {
updates.cache.copy_with_children(&self.old_cache, child_hash, &child.parent);
}
into.add_child(child_hash);
global_metrics()
.scan_observation()
.record_cache_reuse(ScannerCacheReuseKind::CleanPrefix, started.elapsed());
}
fn failed_retry_suppressed(&self, path: &str) -> bool {
let ttl = self.failed_object_ttl_secs;
if ttl == 0 {
return false;
}
let Some(last_failed) = self.new_cache.info.failed_objects.get(path) else {
return false;
};
let now = Self::now_secs();
now.saturating_sub(*last_failed) < ttl
}
fn record_failed(&mut self, path: &str) {
let ttl = self.failed_object_ttl_secs;
if ttl == 0 {
return;
}
self.resolved_failed_object_paths.remove(path);
let now = Self::now_secs();
self.new_cache.info.failed_objects.insert(path.to_string(), now);
let max_entries = self.failed_objects_max;
if max_entries > 0 && self.new_cache.info.failed_objects.len() > max_entries {
self.prune_failed_objects(now, ttl);
}
if self.new_cache.info.failed_objects.contains_key(path) {
self.failed_object_paths_seen.insert(path.to_string());
}
}
fn mark_failed_path_seen(&mut self, path: &str) -> bool {
if self.new_cache.info.failed_objects.contains_key(path) {
return !self.failed_object_paths_seen.insert(path.to_string());
}
false
}
fn clear_failed_path(&mut self, path: &str) {
if self.new_cache.info.failed_objects.contains_key(path) {
self.resolved_failed_object_paths.insert(path.to_string());
}
self.failed_object_paths_seen.remove(path);
}
fn reconcile_failed_objects_after_full_scan(&mut self) {
self.new_cache
.info
.failed_objects
.retain(|path, _| !self.resolved_failed_object_paths.contains(path));
self.resolved_failed_object_paths.clear();
let mixed_coverage = self
.new_cache
.info
.scan_progress
.is_some_and(|progress| progress.started_plan != progress.requested_plan);
if self.prefix_scan_scope.is_some() || self.resume_frontier.is_some() || self.coverage_gap || mixed_coverage {
return;
}
let seen = &self.failed_object_paths_seen;
self.new_cache.info.failed_objects.retain(|path, _| seen.contains(path));
}
/// Drop stale `size_reconciliation` entries whose objects no longer exist
/// after an uninterrupted, full bucket scan. Mirrors
/// [`Self::reconcile_failed_objects_after_full_scan`]: resumed, prefix-scoped,
/// mixed-plan, or errored scans retain unseen entries so unresolved debt
/// outside the walked namespace is not lost.
fn reconcile_size_reconciliation_after_full_scan(&mut self) {
let mixed_coverage = self
.new_cache
.info
.scan_progress
.is_some_and(|progress| progress.started_plan != progress.requested_plan);
let has_failed_objects =
!self.new_cache.info.failed_objects.is_empty() || self.new_cache.cache.values().any(|entry| entry.failed_objects > 0);
if self.prefix_scan_scope.is_some()
|| self.resume_frontier.is_some()
|| self.old_cache.has_scan_position()
|| self.coverage_gap
|| mixed_coverage
|| has_failed_objects
{
return;
}
let previous = &self.old_cache.info.size_reconciliation;
self.new_cache
.info
.size_reconciliation
.retain(|key, entry| previous.get(key).is_none_or(|old_entry| entry.attempts > old_entry.attempts));
}
fn prune_failed_objects_cache(&mut self) {
let ttl = self.failed_object_ttl_secs;
if ttl == 0 {
return;
}
let now = Self::now_secs();
self.prune_failed_objects(now, ttl);
}
fn prune_failed_objects(&mut self, now: u64, ttl: u64) {
let max_entries = self.failed_objects_max;
let failed = &mut self.new_cache.info.failed_objects;
if failed.is_empty() {
return;
}
failed.retain(|_, ts| now.saturating_sub(*ts) < ttl);
if max_entries == 0 {
return;
}
if failed.len() <= max_entries {
return;
}
let mut entries: Vec<(String, u64)> = failed.iter().map(|(k, v)| (clone_cache_value(k), *v)).collect();
entries.sort_by(|(k1, ts1), (k2, ts2)| ts1.cmp(ts2).then_with(|| k1.cmp(k2)));
let remove_count = failed.len().saturating_sub(max_entries);
for (key, _) in entries.into_iter().take(remove_count) {
failed.remove(&key);
}
}
/// Apply the per-object size-resolution ledger updates in one place. The
/// scanner cache is the durable boundary; progress updates contain only
/// usage totals and never own a copy of the reconciliation ledger.
fn apply_size_reconciliation(&mut self, summary: &SizeSummary) {
let now = Self::now_secs();
self.pending_size_reconciliation_keys
.extend(summary.size_reconciliation.iter().map(|entry| clone_cache_value(&entry.key)));
self.pending_size_reconciliation_scopes.extend(
summary
.reconciliation_scopes
.iter()
.map(|scope| size_reconciliation_scope_key(&scope.bucket, &scope.object)),
);
self.pending_size_reconciliation_truncated |= summary.size_reconciliation_truncated;
if summary.size_reconciliation_truncated {
self.coverage_gap = true;
}
let info = &mut self.new_cache.info;
for incoming in &summary.size_reconciliation {
if let Some(existing) = info.size_reconciliation.get_mut(&incoming.key) {
existing.reason = clone_cache_value(&incoming.reason);
existing.physical_size = incoming.physical_size;
existing.generation = clone_cache_value(&incoming.generation);
existing.version_id = clone_cache_value(&incoming.version_id);
existing.attempts = existing.attempts.saturating_add(1);
continue;
}
if size_reconciliation_entry_bytes(incoming) > MAX_SIZE_RECONCILIATION_BYTES_PER_BUCKET {
continue;
}
let mut entry = clone_cache_value(incoming);
entry.first_seen = now;
entry.attempts = 1;
info.size_reconciliation.insert(clone_cache_value(&entry.key), entry);
}
}
fn finish_size_reconciliation_batch(&mut self) {
let now = Self::now_secs();
let current_keys = std::mem::take(&mut self.pending_size_reconciliation_keys);
let scopes = std::mem::take(&mut self.pending_size_reconciliation_scopes);
let truncated = std::mem::replace(&mut self.pending_size_reconciliation_truncated, false);
let info = &mut self.new_cache.info;
if !truncated {
info.size_reconciliation.retain(|key, entry| {
!scopes.contains(&size_reconciliation_scope_key(&entry.bucket, &entry.object)) || current_keys.contains(key)
});
}
prune_size_reconciliation(info, now);
}
fn record_scan_resume_hint(&mut self, folder: &str) {
self.record_scan_resume_hint_with(folder, str::to_owned);
}
fn record_scan_resume_hint_with(&mut self, folder: &str, copy: impl Fn(&str) -> String) {
self.new_cache.info.scan_resume_after = Some(copy(folder));
let checkpoint = DataUsageScanCheckpoint::new(copy(folder), DataUsageScanCheckpointReason::Unknown);
global_metrics().record_scanner_checkpoint_set(
checkpoint.version,
checkpoint.resume_after.clone(),
checkpoint.reason.as_str(),
);
self.new_cache.info.scan_checkpoint = Some(checkpoint);
}
fn record_completed_child(&mut self, folder: &str) {
if self.old_cache.info.scan_progress.is_some()
&& !self.coverage_gap
&& !self
.coverage_frontier
.as_deref()
.is_some_and(|frontier| scan_frontier_covers_path(folder, frontier))
{
self.coverage_frontier = Some(folder.to_owned());
}
self.record_scan_resume_hint(folder);
}
fn can_reuse_covered_namespace(&self, name: &str, compacted: bool) -> bool {
let decision = if self.old_cache.info.scan_progress.is_none() {
ScannerCacheReuseDecision::NoResumeSweep
} else if compacted {
ScannerCacheReuseDecision::CompactedParent
} else if !self
.resume_frontier
.as_deref()
.is_some_and(|frontier| scan_frontier_covers_path(name, frontier))
{
ScannerCacheReuseDecision::MissingCoverage
} else if self.old_cache.find(name).is_none() {
ScannerCacheReuseDecision::MissingCachedChild
} else if self.resume_subtree_has_failures(name) {
ScannerCacheReuseDecision::CachedFailures
} else {
ScannerCacheReuseDecision::Eligible
};
global_metrics()
.scan_observation()
.record_cache_reuse_decision(ScannerCacheReuseGate::CoveredNamespace, decision);
decision == ScannerCacheReuseDecision::Eligible
}
// None preserves work that cannot use sampling; false requests this cycle's rescan.
fn sampled_namespace_reuse(&self, hash: &DataUsageHash, compacted: bool, forward_sweep: bool) -> Option<bool> {
let decision = if self.scan_mode == HealScanMode::Deep {
ScannerCacheReuseDecision::DeepScan
} else if forward_sweep {
ScannerCacheReuseDecision::ForwardSweep
} else if self
.old_cache
.info
.replication
.as_ref()
.is_some_and(|config| config.has_active_rules("", true))
{
ScannerCacheReuseDecision::ActiveReplication
} else if compacted {
ScannerCacheReuseDecision::CompactedParent
} else if !self.old_cache.is_compacted(hash) {
ScannerCacheReuseDecision::UncompactedChild
} else if hash.mod_(self.old_cache.info.next_cycle as u32, data_usage_update_dir_cycles()) {
ScannerCacheReuseDecision::SelectedForWalk
} else {
ScannerCacheReuseDecision::Eligible
};
global_metrics()
.scan_observation()
.record_cache_reuse_decision(ScannerCacheReuseGate::NamespaceSampling, decision);
match decision {
ScannerCacheReuseDecision::Eligible => Some(true),
ScannerCacheReuseDecision::SelectedForWalk => Some(false),
_ => None,
}
}
fn resume_subtree_has_failures(&self, folder: &str) -> bool {
if self.resume_failed_paths.is_empty() {
return false;
}
if self
.resume_failed_paths
.binary_search_by(|path| path.as_str().cmp(folder))
.is_ok()
{
return true;
}
let prefix = format!("{folder}/");
let index = self
.resume_failed_paths
.partition_point(|path| path.as_str() < prefix.as_str());
self.resume_failed_paths
.get(index)
.is_some_and(|path| path.starts_with(&prefix))
}
fn record_scan_resume_hint_if_not_ancestor(&mut self, folder: &str) {
let keep_existing = self
.new_cache
.info
.scan_resume_after
.as_deref()
.is_some_and(|existing| matches!(folder_resume_match(folder, existing), Some(FolderResumeMatch::Descendant)));
if !keep_existing {
self.record_scan_resume_hint_with(folder, clone_cache_value::<str>);
}
}
/// Records one raw entry. Returns whether a durable index holds it, which
/// is what makes stopping at this entry recoverable.
#[cfg(test)]
fn record_raw_enumeration_entry(&mut self, parent: &str, entry: &str) -> bool {
self.record_raw_enumeration_entry_with_stream(parent, entry, false)
}
fn record_raw_enumeration_entry_with_stream(&mut self, parent: &str, entry: &str, continues_stream: bool) -> bool {
if self.old_cache.info.scan_progress.is_none() {
return false;
}
if let Some(position) = self
.raw_enumeration_progress
.iter()
.position(|progress| progress.parent == parent)
{
self.raw_enumeration_progress.truncate(position + 1);
} else {
let page_index = self.raw_enumeration_page_index_for_parent(parent).map(clone_cache_value);
let mut progress = RawEnumerationProgress::new(parent, page_index);
if continues_stream && let Some(writer) = &mut progress.page_index {
writer.continue_native_stream();
}
self.raw_enumeration_progress.push(progress);
}
self.raw_enumeration_progress.last_mut().is_some_and(|progress| {
progress.record_entry(entry);
progress.page_index.is_some()
})
}
fn raw_enumeration_page_index_for_parent(&self, parent: &str) -> Option<&RawEnumerationPageIndex> {
self.old_cache.validated_raw_enumeration_page_index_for_parent(parent)
}
fn raw_enumeration_committed_entry_oracle(&self, parent: &str) -> HashSet<String> {
let Some(index) = self.raw_enumeration_page_index_for_parent(parent) else {
return HashSet::new();
};
let generation_matches_parent = match index.status() {
crate::raw_page_index::RawEnumerationPageOwnerStatus::Building {
generation,
parent: index_parent,
..
}
| crate::raw_page_index::RawEnumerationPageOwnerStatus::Ready {
generation,
parent: index_parent,
..
} => generation > 0 && index_parent == parent,
crate::raw_page_index::RawEnumerationPageOwnerStatus::Unsupported => false,
};
if !generation_matches_parent {
return HashSet::new();
}
index.committed_entries().unwrap_or_default().into_iter().collect()
}
fn finish_raw_enumeration_parent(&mut self, parent: &str) {
let scan_root = self.old_cache.info.name.as_str();
self.raw_enumeration_progress.retain(|progress| {
if progress.parent == parent {
return parent == scan_root && progress.has_checkpointable_page_index();
}
!progress
.parent
.strip_prefix(parent)
.is_some_and(|suffix| suffix.starts_with(SLASH_SEPARATOR))
});
}
fn take_raw_enumeration_resume_state(&mut self) -> (Option<DataUsageRawEnumerationCursor>, Option<RawEnumerationPageIndex>) {
if self.raw_enumeration_progress.is_empty() {
return (None, None);
}
let progress_index = self.selected_raw_enumeration_progress().unwrap_or(0);
let progress = self.raw_enumeration_progress.swap_remove(progress_index);
self.raw_enumeration_progress.clear();
(progress.cursor(), progress.page_index())
}
fn selected_raw_enumeration_progress(&self) -> Option<usize> {
self.raw_enumeration_progress
.iter()
.enumerate()
.max_by_key(|(index, progress)| (progress.checkpointable_entry_count(), std::cmp::Reverse(*index)))
.map(|(index, _)| index)
}
fn saved_directories(&self) -> Vec<DirectoryCheckpoint> {
let mut snapshots: Vec<_> = self
.directory_checkpoints
.values()
.flat_map(HashMap::values)
.filter_map(|slot| slot.lock().unwrap_or_else(|p| p.into_inner()).clone())
.collect();
snapshots.sort_by(|left, right| (left.parent(), left.endpoint()).cmp(&(right.parent(), right.endpoint())));
snapshots
}
/// The walk path except the directory the resume state selects.
fn raw_enumeration_path_page_indexes(&self) -> Vec<RawEnumerationPageIndex> {
let selected = self.selected_raw_enumeration_progress();
self.raw_enumeration_progress
.iter()
.enumerate()
.filter(|(index, _)| Some(*index) != selected)
.filter_map(|(_, progress)| progress.page_index())
.collect()
}
fn peek_raw_enumeration_resume_state(&self) -> (Option<DataUsageRawEnumerationCursor>, Option<RawEnumerationPageIndex>) {
self.selected_raw_enumeration_progress().map_or((None, None), |index| {
let progress = &self.raw_enumeration_progress[index];
(progress.cursor(), progress.page_index())
})
}
fn maybe_send_checkpoint(&mut self, folder: &CachedFolder, hash: &DataUsageHash, into: &DataUsageEntry) {
self.maybe_send_owned_checkpoint(folder, hash, into, None);
}
// A compact accumulator is checkpointable only at the boundary where
// its owning frame has accepted a complete child. Descendant frames may
// temporarily share the same accumulator and cannot seal it themselves.
fn maybe_send_owned_checkpoint(
&mut self,
folder: &CachedFolder,
hash: &DataUsageHash,
into: &DataUsageEntry,
work: Option<&directory_cursor::DirectoryWork>,
) {
let Some(checkpoint_tx) = self.checkpoint_tx.clone() else { return };
let elapsed = self.last_checkpoint_at.elapsed();
if (into.compacted && work.is_none())
|| self.new_cache.info.scan_progress.is_none()
|| elapsed < checkpoint_interval_for_build_time(self.last_checkpoint_build_time)
|| (self.checkpoint_objects.saturating_sub(self.last_checkpoint_objects) < SCANNER_CHECKPOINT_OBJECT_INTERVAL
&& elapsed < SCANNER_CHECKPOINT_INTERVAL)
{
return;
}
if self.new_cache.root().is_none() && self.raw_enumeration_progress.is_empty() && work.is_none() {
return;
}
// Reserve the bounded queue slot before cloning the growing cache.
// When persistence is slower than traversal, constructing snapshots
// that can only be rejected by a full channel creates repeated O(N)
// allocations without improving restart progress.
if checkpoint_tx.is_closed() {
return;
}
let Ok(permit) = checkpoint_tx.try_reserve() else { return };
// Invalid partial graphs must not trigger a fresh O(N) clone on every object.
self.last_checkpoint_objects = self.checkpoint_objects;
self.last_checkpoint_at = Instant::now();
if let Some(work) = work {
work.checkpoint();
}
let snapshot = self.checkpoint_snapshot(folder, hash, into);
self.last_checkpoint_build_time = self.last_checkpoint_at.elapsed();
if let Some(snapshot) = snapshot {
permit.send(snapshot);
}
}
fn checkpoint_snapshot(&self, folder: &CachedFolder, hash: &DataUsageHash, into: &DataUsageEntry) -> Option<DataUsageCache> {
// Heal revisits are not sorted with the forward sweep. An unfinished
// earlier subtree, including a suspended ancestor, must not be signed
// as completed prefix coverage.
if self.coverage_frontier.as_deref().is_some_and(|frontier| {
scan_frontier_covers_path(&folder.name, frontier)
|| self.checkpoint_ancestors[..self.checkpoint_depth]
.iter()
.any(|ancestor| scan_frontier_covers_path(&ancestor.hash.0, frontier))
}) {
return None;
}
let mut snapshot = clone_cache_value(&self.new_cache);
let mut parent = None;
for ancestor in &self.checkpoint_ancestors[..self.checkpoint_depth] {
snapshot.replace_hashed(&ancestor.hash, &parent, &ancestor.entry);
parent = Some(clone_cache_value(&ancestor.hash));
}
snapshot.replace_hashed(hash, &folder.parent, into);
snapshot.checked_flatten_complete_scope(&snapshot.info.name)?;
snapshot.info.last_update = Some(SystemTime::now());
snapshot.info.snapshot_complete = false;
snapshot.info.scan_directory_work = self.saved_directories();
let (cursor, page_index) = self.peek_raw_enumeration_resume_state();
snapshot.info.scan_raw_enumeration_path_page_indexes = self.raw_enumeration_path_page_indexes();
snapshot.info.scan_raw_enumeration_cursor = cursor;
snapshot.info.scan_raw_enumeration_page_index = page_index;
snapshot.seal_scan_frontier(self.coverage_frontier.as_deref()).ok()?;
// A resumed readdir can run before covered subtrees are copied. Keep
// its durable receipt until this snapshot can represent that coverage.
if snapshot.info.scan_coverage_receipt.is_none()
&& self.coverage_frontier.as_deref().is_some_and(|frontier| {
!snapshot
.info
.scan_directory_work
.iter()
.any(|directory| directory.covers_bound_path(&snapshot.info, frontier))
})
{
return None;
}
// The receipt was just sealed from this snapshot; do not hash it twice.
if snapshot.info.scan_raw_enumeration_cursor.is_none()
&& snapshot.info.scan_raw_enumeration_page_index.is_none()
&& snapshot.info.scan_coverage_receipt.is_none()
&& snapshot.info.scan_directory_work.is_empty()
{
return None;
}
Some(snapshot)
}
fn carry_forward_old_children(&mut self, parent_hash: &DataUsageHash, entry: &mut DataUsageEntry) {
if entry.compacted {
// Compacted entries store child totals directly; child links would be flattened twice.
return;
}
let Some(old_entry) = self.old_cache.cache.get(&clone_cache_value(&parent_hash.0)) else {
return;
};
let old_children = old_entry.children.iter().map(clone_cache_value).collect::<Vec<_>>();
for child in old_children {
if entry.children.contains(&child) {
continue;
}
if !self.old_cache.cache.contains_key(&child) {
continue;
}
let child_hash = DataUsageHash(clone_cache_value(&child));
self.new_cache
.copy_with_children(&self.old_cache, &child_hash, &Some(clone_cache_value(parent_hash)));
entry.children.insert(child);
}
}
async fn preserve_partial_child_progress(
&mut self,
parent: &Option<DataUsageHash>,
child_hash: &DataUsageHash,
parent_entry: &mut DataUsageEntry,
child_entry: &DataUsageEntry,
) {
if data_usage_entry_has_progress(child_entry) {
// A cancelled out-of-order heal revisit is not completed prefix work.
if self
.coverage_frontier
.as_deref()
.is_some_and(|frontier| scan_frontier_covers_path(&child_hash.0, frontier))
{
self.coverage_frontier = None;
self.coverage_gap = true;
}
let mut child_entry = clone_cache_value(child_entry);
self.carry_forward_old_children(child_hash, &mut child_entry);
self.record_scan_resume_hint_if_not_ancestor(&clone_cache_value(&child_hash.0));
parent_entry.add_child(child_hash);
self.new_cache.replace_hashed(child_hash, parent, &child_entry);
self.refresh_usage_subtree(child_hash, parent);
self.send_update().await;
}
}
fn alert_excessive_folders(&self, folder: &str, total_folders: usize) {
let threshold = scanner_excess_folders_threshold();
if u64::try_from(total_folders).unwrap_or(u64::MAX) <= threshold {
return;
}
ensure_scanner_alert_metrics_registered();
global_metrics().record_scanner_source_executed(ScannerWorkSource::Alerts, 1);
counter!(
METRIC_SCANNER_EXCESS_FOLDERS_TOTAL,
"root" => self.root.clone()
)
.increment(1);
if scanner_alert_emission_allows(ScannerAlertKind::BigPrefix, &self.root, folder, scanner_alert_cooldown()) {
emit_scanner_alert_event(
EVENT_SCANNER_BIG_PREFIX,
&self.root,
folder,
0,
self.notification_bucket_incarnation,
&[("folders", total_folders.to_string()), ("threshold", threshold.to_string())],
);
}
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_ALERT_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
root = %self.root,
folder,
folders = total_folders,
threshold,
state = "excess_folders",
"Scanner alert recorded excessive direct subfolders"
);
}
pub async fn should_heal(&self) -> bool {
self.try_should_heal().await.unwrap_or(false)
}
async fn try_should_heal(&self) -> Result<bool, ScannerError> {
if self.skip_heal.load(std::sync::atomic::Ordering::Relaxed) {
return Ok(false);
}
if self.heal_object_select == 0 {
return Ok(false);
}
let healing = match self.local_disk.disk_info(&DiskInfoOptions::default()).await {
Ok(info) => info.healing,
Err(error) => {
let error = StorageError::from(error);
if is_scanner_source_unavailable(&error) {
return Err(ScannerError::source_unavailable(error));
}
false
}
};
if healing {
self.skip_heal.store(true, std::sync::atomic::Ordering::Relaxed);
return Ok(false);
}
Ok(true)
}
async fn send_required_scanner_heal_request(
&mut self,
kind: PendingScannerHealKind,
bucket: String,
object: Option<String>,
version_id: Option<String>,
request: HealChannelRequest,
) -> Result<HealAdmissionResult, ScannerError> {
let candidate_type = pending_scanner_heal_candidate_type(kind);
let priority = request.priority;
let scan_mode = request.scan_mode.unwrap_or(self.scan_mode);
let result =
match send_scanner_heal_request(candidate_type, request, None, scanner_disk_heal_scope(&self.local_disk)).await {
Ok(result) => result,
Err(err) => {
self.update_pending_scanner_heal_after_admission(
kind,
&bucket,
object.as_deref(),
version_id.as_deref(),
scan_mode,
HealAdmissionResult::Full,
);
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_HEAL_ADMISSION,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_HEAL,
candidate_type,
bucket = %bucket,
object = object.as_deref().unwrap_or(""),
priority = heal_priority_label(priority),
state = "heal_channel_error",
error = %err,
"Scanner deferred heal request after channel error"
);
return Ok(HealAdmissionResult::Full);
}
};
self.update_pending_scanner_heal_after_admission(
kind,
&bucket,
object.as_deref(),
version_id.as_deref(),
scan_mode,
result,
);
if result.is_admitted() || matches!(priority, HealChannelPriority::Low) {
return Ok(result);
}
record_high_priority_heal_escalation(candidate_type, priority, result);
let admission_error =
build_high_priority_heal_admission_error(candidate_type, &bucket, object.as_deref(), priority, result);
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_HEAL_ADMISSION,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_HEAL,
candidate_type,
bucket = %bucket,
object = object.as_deref().unwrap_or(""),
priority = heal_priority_label(priority),
admission = result.result_label(),
reason = result.reason_label(),
error = %admission_error,
state = "high_priority_not_admitted",
"Scanner high-priority heal admission failed"
);
Ok(result)
}
pub fn set_heal_object_select(&mut self, prob: u32) {
self.heal_object_select = prob;
}
/// Set debug mode
pub fn set_debug(&mut self, debug: bool) {
self.data_usage_scanner_debug = debug;
}
fn compact_completed_folder(&mut self, folder: &CachedFolder, hash: &DataUsageHash, entry: &DataUsageEntry) {
// Completed healthy subtrees can keep aggregate usage. Coverage gaps
// and failed-object debt still need child entries for precise resume
// and to avoid rereading healthy siblings on a retry.
let forward_sweep = self.old_cache.info.scan_progress.is_some();
if entry.compacted || self.new_cache.info.name == folder.name || (forward_sweep && self.coverage_gap) {
return;
}
let summary = if entry.children.is_empty() {
Cow::Borrowed(entry)
} else if let Some(flat) = self.new_cache.size_recursive(&hash.0) {
Cow::Owned(flat)
} else {
return;
};
if forward_sweep && summary.failed_objects != 0 {
return;
}
let should_compact = summary.objects < DATA_SCANNER_COMPACT_LEAST_OBJECT
|| entry.children.iter().all(|key| {
self.new_cache
.cache
.get(key)
.is_none_or(|child| child.children.is_empty() && child.objects <= 1)
});
if !should_compact {
return;
}
// Heal revisits also reach this path without a parent advancing
// coverage. Keep the endpoint addressable when its completed
// subtree is replaced by an aggregate.
if self.coverage_frontier.as_deref().is_some_and(|frontier| {
frontier
.strip_prefix(&folder.name)
.is_some_and(|suffix| suffix.starts_with('/'))
}) {
self.record_completed_child(&folder.name);
}
match summary {
Cow::Borrowed(_) => {
// The leaf is already cached; only its sampling mode changes.
if let Some(cached) = self.new_cache.cache.get_mut(&hash.0) {
cached.compacted = true;
}
}
Cow::Owned(mut flat) => {
flat.compacted = true;
self.new_cache.delete_recursive(hash);
self.new_cache.replace_hashed(hash, &folder.parent, &flat);
}
}
}
fn refresh_usage_subtree(&mut self, hash: &DataUsageHash, parent: &Option<DataUsageHash>) {
if let Some(updates) = &mut self.usage_updates {
updates.cache.delete_recursive(hash);
updates.cache.copy_with_children(&self.new_cache, hash, parent);
}
}
/// Send at most one aggregate per minute when a caller requested progress.
pub async fn send_update(&mut self) {
let Some(updates) = &mut self.usage_updates else { return };
if !updates.is_due() {
return;
}
if let Some(flat) = updates.cache.size_recursive(&self.new_cache.info.name) {
if let Err(e) = updates.sender.send(flat).await {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
root = %self.new_cache.info.name,
state = "update_send_failed",
error = %e,
"Scanner folder update send failed"
);
}
updates.last_update = SystemTime::now();
}
}
async fn send_update_for_entry(&mut self, hash: &DataUsageHash, parent: &Option<DataUsageHash>, entry: &DataUsageEntry) {
if let Some(updates) = &mut self.usage_updates
&& updates.is_due()
{
updates.cache.replace_hashed(hash, parent, entry);
self.send_update().await;
}
}
async fn record_missing_erasure_metadata(
&mut self,
folder: &CachedFolder,
into: &mut DataUsageEntry,
) -> Result<(), ScannerError> {
let metadata_path = path_join_buf(&[&self.root, &folder.name, STORAGE_FORMAT_FILE]);
self.mark_failed_path_seen(&metadata_path);
let retry_suppressed = self.failed_retry_suppressed(&metadata_path);
into.failed_objects = into.failed_objects.saturating_add(1);
if !retry_suppressed {
self.record_failed(&metadata_path);
let failed_cache_entries = self.new_cache.info.failed_objects.len();
if failed_cache_entries > 0 && should_log_failed_object(failed_cache_entries) {
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
path = %metadata_path,
failed_objects = failed_cache_entries,
state = "object_metadata_missing",
"Scanner found erasure object data without metadata"
);
}
}
if !retry_suppressed {
let (bucket, object) = path2_bucket_object_with_base_path(&self.root, &folder.name);
if !bucket.is_empty() && !object.is_empty() {
self.send_required_scanner_heal_request(
PendingScannerHealKind::Object,
bucket.clone(),
Some(object.clone()),
None,
build_non_destructive_object_heal_request(bucket, object, self.scan_mode, HealChannelPriority::High),
)
.await?;
}
}
Ok(())
}
/// Scan the folder and its descendants in depth-first order.
/// Files found in the folders will be added to new_cache.
pub async fn scan_folder(
&mut self,
ctx: CancellationToken,
folder: CachedFolder,
into: &mut DataUsageEntry,
) -> Result<(), ScannerError> {
if self.old_cache.info.scan_directory_source.is_none()
&& self.old_cache.info.scan_identity.is_some()
&& self.old_cache.info.scan_progress.is_some()
{
let source = wait_for_scanner_io(&ctx, directory_cursor::physical_source(&self.local_disk)).await??;
self.old_cache.info.scan_directory_source = Some(source.clone());
self.new_cache.info.scan_directory_source = Some(source);
}
// The directory walk is one heap future. Polling it through a trait
// object keeps its state machine off this frame and off the data-folder
// scan that called us. One `Box::pin` is enough; nested frames are not.
folder_walk::poll_apart(self.scan_folder_inner(ctx, folder, into, FolderScanMode::Namespace, false))
.await
.map(|_| ())
}
#[inline(never)]
async fn enumerate_folder(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
isolate_compacted_namespace_errors: bool,
) -> Result<WalkAction, ScannerError> {
let ctx = ctx.clone();
let mode = frame.mode;
let folder = &frame.folder;
let this_hash = &frame.hash;
let into = &mut frame.entry;
check_local_scanner_handle(&self.local_disk).map_err(ScannerError::source_unavailable)?;
if ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
if mode == FolderScanMode::Namespace && !self.budget.try_start_directory() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
if ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
self.prune_failed_objects_cache();
let mut abandoned_children: DataUsageHashMap = HashSet::new();
if !into.compacted {
abandoned_children = self.old_cache.find_children_copy(this_hash);
}
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
root = %self.root,
folder = %folder.name,
state = "scan_started",
"Scanner folder state updated"
);
let (_, prefix) = path2_bucket_object_with_base_path(&self.root, &folder.name);
let active_life_cycle = if self
.old_cache
.info
.lifecycle
.as_ref()
.is_some_and(|v| v.has_active_rules(&prefix))
{
self.old_cache.info.lifecycle.clone()
} else {
None
};
let active_replication = if self
.old_cache
.info
.replication
.as_ref()
.is_some_and(|v| v.has_active_rules(&prefix, true))
{
self.old_cache.info.replication.clone()
} else {
None
};
let active_object_lock = self.old_cache.info.object_lock.clone();
if mode != FolderScanMode::Namespace {
// A candidate may be object payload rather than a namespace.
wait_for_scanner_io(&ctx, self.sleeper.admit_disk_io(1, 0)).await?;
} else {
wait_for_scanner_io(&ctx, self.sleeper.sleep_folder_paced(&mut self.pacing_debt)).await?;
}
let mut queued_folders: Vec<QueuedFolder> = Vec::new();
let mut found_object_metadata = false;
let mut object_count: u64 = 0;
let yield_every_objects = scanner_yield_every_n_objects();
let dir_path = path_join_buf(&[&self.root, &folder.name]);
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
dir_path = ?dir_path,
state = "dir_open",
"Scanner folder state updated"
);
// A child prefix can be removed after its parent listed it and before
// it is opened here (e.g. concurrent object deletes). Treat it like a
// directory that vanished during iteration instead of failing the
// whole parent subtree. The bucket root (no parent) still propagates
// NotFound so namespace removal is detected by the caller.
// A small object directory normally finishes in one call. Allocate
// listing state at the bucket root or after an interruption has
// actually left this directory on the saved traversal path.
let info = &self.old_cache.info;
let previously_interrupted = info
.scan_raw_enumeration_cursor
.as_ref()
.is_some_and(|cursor| cursor.parent == folder.name)
|| info
.scan_raw_enumeration_page_index
.iter()
.chain(&info.scan_raw_enumeration_path_page_indexes)
.any(|index| index.parent() == Some(folder.name.as_str()));
let mut directory_scope = (folder.parent.is_none()
|| previously_interrupted
|| self.directory_checkpoints.contains_key(&folder.name)
|| directory_cursor::is_parked(&dir_path))
.then(|| DirectoryScope::new(&self.local_disk, &self.old_cache, mode, self.prefix_scan_scope.clone()))
.flatten();
if let Some(scope) = &mut directory_scope {
scope.bind_source(self.old_cache.info.scan_directory_source.as_deref());
}
let saved = directory_scope.as_ref().map(|owner| {
self.directory_checkpoints
.entry(folder.name.clone())
.or_default()
.entry(owner.endpoint().to_owned())
.or_default()
.clone()
});
let mut dir_reader = match wait_for_scanner_io(
&ctx,
run_scanner_node_operation(
self.node_admission.as_ref(),
&ctx,
ScannerDirectory::open(&dir_path, &folder.name, directory_scope, self.budget.clone(), saved),
),
)
.await??
{
Ok(dir_reader) => Some(dir_reader),
Err(e)
if folder.parent.is_some()
&& (e.kind() == ErrorKind::NotFound
|| (mode != FolderScanMode::Namespace && e.kind() == ErrorKind::NotADirectory)) =>
{
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
dir_path = %dir_path,
state = "dir_missing_before_open",
error = %e,
"Scanner folder state updated"
);
if mode != FolderScanMode::Namespace {
self.coverage_gap |= e.kind() == ErrorKind::NotADirectory && self.old_cache.info.scan_progress.is_some();
self.directory_checkpoints.remove(&folder.name);
return Ok(WalkAction::Return(Ok(FolderScanOutcome::Vanished)));
}
None
}
Err(e) => return Err(ScannerError::Io(e)),
};
if dir_reader.as_ref().is_some_and(|reader| reader.directory_replaced) && self.resume_frontier.is_some() {
// Names from a replaced directory cannot validate the saved
// child prefix. Finish this walk only as an observation.
self.coverage_gap = true;
self.resume_frontier = None;
}
let mut pending_entry_progress = 0_u64;
let mut last_entry_progress = Instant::now();
if let Some(reader) = &mut dir_reader {
reader.hold_abandoned(&mut abandoned_children);
}
let indexed = dir_reader.as_ref().is_some_and(ScannerDirectory::indexed);
let mut raw_enumeration_complete = false;
let continues_stream = dir_reader.as_ref().is_some_and(ScannerDirectory::continues_stream);
// A sealed work queue only emits the two classification markers;
// it never needs the raw-name membership table again.
let raw_enumeration_committed_entries = if dir_reader.as_ref().is_some_and(ScannerDirectory::finished_listing) {
// A later quantum can stop in a child. Its durable proof
// still needs every ancestor's prior immutable pages, even
// though this cursor need not enumerate those names again.
if let Some(progress) = self
.old_cache
.info
.scan_raw_enumeration_page_index
.iter()
.chain(&self.old_cache.info.scan_raw_enumeration_path_page_indexes)
.find(|index| index.parent() == Some(folder.name.as_str()))
.and_then(|index| RawEnumerationProgress::from_sealed(&folder.name, index))
{
self.raw_enumeration_progress.push(progress);
}
HashSet::new()
} else {
self.raw_enumeration_committed_entry_oracle(&folder.name)
};
let raw_replay_floor = u64::try_from(raw_enumeration_committed_entries.len()).unwrap_or(u64::MAX);
let mut raw_entries_observed = 0_u64;
let mut raw_entries_charged = 0_u64;
let mut candidate_unclassified = mode != FolderScanMode::Namespace;
let mut deferred_metadata = None;
loop {
// Hold at most one metadata entry until a candidate reaches
// EOF: a later part must not leave object accounting or ILM work.
let (entry, replayed_metadata) = if let Some(reader) = dir_reader.as_mut().filter(|_| !raw_enumeration_complete) {
if reader.batch_entries == SCANNER_DIRECTORY_BATCH_ENTRIES {
check_local_scanner_handle(&self.local_disk).map_err(ScannerError::source_unavailable)?;
}
let entry = match next_scanner_dir_entry(&ctx, &self.sleeper, reader, self.node_admission.as_ref()).await {
Ok(Some(entry)) => entry,
Ok(None) => {
raw_enumeration_complete = true;
continue;
}
Err(ScannerError::Io(e))
if candidate_unclassified && matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) =>
{
return Err(ScannerError::Io(e));
}
Err(ScannerError::Io(e)) if e.kind() == ErrorKind::NotFound => {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
dir_path = %dir_path,
state = "dir_missing_during_iteration",
error = %e,
"Scanner folder state updated"
);
raw_enumeration_complete = true;
continue;
}
Err(ScannerError::Io(e)) if e.kind() == ErrorKind::NotADirectory => {
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
dir_path = %dir_path,
state = "dir_became_non_directory",
error = %e,
"Scanner folder state updated"
);
raw_enumeration_complete = true;
continue;
}
Err(e) => return Err(e),
};
let marker = entry.is_recorded();
(entry, marker)
} else {
raw_enumeration_complete = true;
if candidate_unclassified {
// Apply namespace reuse only after the current listing
// proves there is no direct erasure part.
if let FolderScanMode::ErasureCandidate {
reuse_namespace: true, ..
} = mode
&& !into.compacted
&& self.old_cache.find(&folder.name).is_some()
{
// The caller stitches this cached child into its
// parent; do not clone a growing child set into the
// unused provisional accumulator as well.
let started = Instant::now();
self.new_cache.copy_with_children(&self.old_cache, this_hash, &folder.parent);
global_metrics()
.scan_observation()
.record_cache_reuse(ScannerCacheReuseKind::ClassifiedNamespace, started.elapsed());
self.budget.record_entries_visited(pending_entry_progress);
self.finish_raw_enumeration_parent(&folder.name);
self.directory_checkpoints.remove(&folder.name);
return Ok(WalkAction::Return(Ok(FolderScanOutcome::Namespace)));
}
candidate_unclassified = false;
// An empty UUID directory beside object metadata has
// no namespace work. Its listing was already charged;
// nonempty namespaces still need directory admission.
let empty_object_child = matches!(
mode,
FolderScanMode::ErasureCandidate {
parent_has_metadata: true,
..
}
) && deferred_metadata.is_none()
&& dir_reader
.as_ref()
.and_then(ScannerDirectory::folder_count)
.unwrap_or(queued_folders.len())
== 0;
if !empty_object_child {
if !self.budget.try_start_directory() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
wait_for_scanner_io(&ctx, self.sleeper.sleep_folder_preset()).await?;
}
}
let Some(entry) = deferred_metadata.take() else { break };
(entry, true)
};
let file_name = entry.file_name().to_string_lossy().to_string();
if file_name.is_empty() || file_name == "." || file_name == ".." {
continue;
}
if !replayed_metadata {
// A restored index appends one pending name per entry past
// its old size, so charging only that tail keeps each
// budget unit durable even if the listing order changed.
raw_entries_observed = raw_entries_observed.saturating_add(1);
let raw_entry_is_new = (continues_stream || raw_entries_observed > raw_replay_floor)
&& !raw_enumeration_committed_entries.contains(&file_name);
#[cfg(test)]
if raw_entry_is_new {
tests::enumeration_restart::observe_raw_entry(&dir_path, &entry.file_name(), &self.budget);
}
// Physical discovery is progress even when a changed directory
// must replay names retained by its logical page index. Budget
// admission below still charges only newly durable entries.
pending_entry_progress = pending_entry_progress.saturating_add(1);
if pending_entry_progress >= SCANNER_ENTRY_PROGRESS_BATCH
|| last_entry_progress.elapsed() >= SCANNER_ENTRY_PROGRESS_INTERVAL
{
self.budget.record_entries_visited(pending_entry_progress);
pending_entry_progress = 0;
last_entry_progress = Instant::now();
}
let raw_entry_is_durable =
self.record_raw_enumeration_entry_with_stream(&folder.name, &file_name, continues_stream);
// Object metadata and the entries behind it are charged to
// the object budget; this one covers listing work.
let object_entry = file_name == STORAGE_FORMAT_FILE || deferred_metadata.is_some();
if raw_entry_is_new && raw_entry_is_durable && !object_entry {
raw_entries_charged = raw_entries_charged.saturating_add(1);
let name_bytes = u64::try_from(file_name.len()).unwrap_or(u64::MAX);
if !self.budget.try_charge_raw_entry(name_bytes, raw_entries_charged) {
self.budget.record_entries_visited(pending_entry_progress);
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
}
self.maybe_send_checkpoint(folder, this_hash, into);
}
if !replayed_metadata && dir_reader.as_ref().is_some_and(|reader| reader.enumeration_only) {
continue;
}
let is_storage_format_entry = file_name == STORAGE_FORMAT_FILE;
if candidate_unclassified && is_storage_format_entry {
deferred_metadata = Some(entry);
continue;
}
let file_path = entry.path().to_string_lossy().to_string();
let trim_dir_name = file_path.strip_prefix(&dir_path).unwrap_or(&file_path);
let entry_name = path_join_buf(&[&folder.name, trim_dir_name]);
if entry_name.is_empty() || entry_name == folder.name {
continue;
}
// Ignore entries that disappeared during traversal or hit symlink
// loops, but propagate other walk errors.
let file_type = if entry.is_recorded()
&& let Some(kind) = entry.cached_type()
{
Ok(kind)
} else {
wait_for_scanner_io(&ctx, run_scanner_node_operation(self.node_admission.as_ref(), &ctx, entry.file_type()))
.await??
};
let mut entry_type = match file_type {
Ok(entry_type) => entry_type,
Err(e) if e.kind() == ErrorKind::NotFound => {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
entry = %entry_name,
state = "entry_missing_before_type_lookup",
error = %e,
"Scanner folder state updated"
);
continue;
}
Err(e) if e.kind() == ErrorKind::TooManyLinks => {
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
entry = %entry_name,
state = "entry_symlink_loop_before_type_lookup",
error = %e,
"Scanner folder state updated"
);
continue;
}
Err(e) => return Err(ScannerError::Io(e)),
};
if candidate_unclassified && entry_type.is_file() && is_erasure_part_name(&file_name) {
self.budget.record_entries_visited(pending_entry_progress);
// Positive data evidence completes classification, not raw
// namespace coverage. Discard its provisional resume owner.
self.finish_raw_enumeration_parent(&folder.name);
self.directory_checkpoints.remove(&folder.name);
return Ok(WalkAction::Return(Ok(FolderScanOutcome::ErasureData)));
}
// Metadata presence establishes an erasure object boundary;
// parsing failures still belong to accounting and healing. A
// directory named `xl.meta` remains a valid namespace prefix,
// and symlinks are classified after resolving their target.
if is_storage_format_entry && !entry_type.is_dir() && !entry_type.is_symlink() {
found_object_metadata = true;
}
let mut entry_metadata_len = None;
if entry_type.is_symlink() {
wait_for_scanner_io(&ctx, self.sleeper.admit_disk_io(1, 0)).await?;
let metadata = match wait_for_scanner_io(
&ctx,
run_scanner_node_operation(self.node_admission.as_ref(), &ctx, native_io::metadata(&file_path)),
)
.await??
{
Ok(metadata) => metadata,
Err(e) if e.kind() == ErrorKind::NotFound => {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
file_path = %file_path,
state = "symlink_target_missing_before_metadata",
error = %e,
"Scanner folder state updated"
);
continue;
}
Err(e) if e.kind() == ErrorKind::TooManyLinks => {
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
file_path = %file_path,
state = "symlink_target_loop_before_metadata",
error = %e,
"Scanner folder state updated"
);
continue;
}
Err(e) => return Err(ScannerError::Io(e)),
};
if metadata.is_dir() {
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
file_path = %file_path,
state = "symlink_directory_ignored",
"Scanner folder state updated"
);
continue;
}
entry_type = metadata.file_type();
entry_metadata_len = Some(metadata.len());
if is_storage_format_entry {
found_object_metadata = true;
}
}
// ok
let (bucket, prefix) = path2_bucket_object_with_base_path(self.root.as_str(), &entry_name);
if bucket.is_empty() {
break;
}
if is_reserved_or_invalid_bucket(&bucket, false) {
break;
}
if ctx.is_cancelled() {
break;
}
if entry_type.is_dir() {
let h = hash_path(&entry_name);
if h == *this_hash {
continue;
}
let exists = self.old_cache.cache.contains_key(&clone_cache_value(&h.0));
let this = CachedFolder {
name: entry_name.clone(),
parent: Some(this_hash.clone()),
object_heal_prob_div: folder.object_heal_prob_div,
};
if exists && self.should_reuse_clean_root_child(folder, into, &this.name, &h, &abandoned_children) {
abandoned_children.remove(&clone_cache_value(&h.0));
self.reuse_clean_root_child(&this, &h, into);
} else if exists {
abandoned_children.remove(&clone_cache_value(&h.0));
queued_folders.push(QueuedFolder {
folder: this,
source: FolderScanSource::Existing,
});
if let Some(updates) = &mut self.usage_updates {
updates
.cache
.copy_with_children(&self.old_cache, &h, &Some(clone_cache_value(this_hash)));
}
} else {
abandoned_children.remove(&clone_cache_value(&h.0));
queued_folders.push(QueuedFolder {
folder: this,
source: FolderScanSource::New,
});
}
continue;
}
// Only xl.meta contributes object accounting. Payload files
// must not incur a size stat or a metadata-read reservation.
if !is_storage_format_entry {
continue;
}
let work_started = tokio::time::Instant::now();
let heal_enabled = this_hash.mod_alt(
self.old_cache.info.next_cycle as u32 / folder.object_heal_prob_div,
self.heal_object_select / folder.object_heal_prob_div,
) && self.try_should_heal().await?;
let mut item = ScannerItem {
path: file_path,
bucket,
prefix: rustfs_utils::path::dir(&prefix),
object_name: file_name,
lifecycle: active_life_cycle.clone(),
object_lock: active_object_lock.clone(),
replication: active_replication.clone(),
heal_scope: None,
heal_enabled,
heal_bitrot: self.scan_mode == HealScanMode::Deep,
debug: self.data_usage_scanner_debug,
file_type: entry_type,
notification_bucket_incarnation: self.notification_bucket_incarnation,
};
// Keep failed paths visible to this scan so repair success can
// clear stale failure state and a complete walk can discard
// paths that were removed since the previous cycle.
let repeated_failed_path = self.mark_failed_path_seen(&item.path);
if repeated_failed_path && self.failed_retry_suppressed(&item.path) {
// A new FolderScanner starts with an empty seen set, so
// cached paths are still rechecked once per cycle. Skip
// duplicate listings within this same scanner pass.
into.failed_objects = into.failed_objects.max(1);
continue;
}
// Budget and admission waits already pace this walker. Charge
// only work performed after admission, never those waits again.
let mut work_elapsed = work_started.elapsed();
// Reuse a resolved symlink's size; otherwise admit the size
// stat only when the byte budget needs it.
let budgeted_bytes = if self.sleeper.budgets_disk_io_bytes() {
if let Some(len) = entry_metadata_len {
len
} else {
wait_for_scanner_io(&ctx, self.sleeper.admit_disk_io(1, 0)).await?;
wait_for_scanner_io(
&ctx,
run_scanner_node_operation(self.node_admission.as_ref(), &ctx, async {
let started = tokio::time::Instant::now();
let result = native_io::metadata(&item.path).await;
work_elapsed = work_elapsed.saturating_add(started.elapsed());
result
}),
)
.await??
.map(|metadata| metadata.len())
.unwrap_or(0)
}
} else {
0
};
wait_for_scanner_io(&ctx, self.sleeper.admit_disk_io(1, budgeted_bytes)).await?;
let size_result = run_scanner_metadata_operation(self.node_admission.as_ref(), &ctx, async {
let started = tokio::time::Instant::now();
self.object_metadata_visits.increment(1);
#[cfg(feature = "diagnostic-prefix-attribution")]
if let Some(attribution) = &self.prefix_attribution {
attribution.record(&item.bucket, &item.prefix);
}
let result = self
.local_disk
.get_size_with_tier_names(item.clone(), &self.tier_registry.names)
.await;
#[cfg(feature = "diagnostic-prefix-attribution")]
if result.is_ok()
&& let Some(attribution) = &self.prefix_attribution
{
attribution.record_success(&item.bucket, &item.prefix);
}
work_elapsed = work_elapsed.saturating_add(started.elapsed());
result
})
.await?;
let work_started = tokio::time::Instant::now();
if self.node_admission.is_some()
&& ctx.is_cancelled()
&& !matches!(&size_result, Err(error) if is_scanner_source_unavailable(error))
{
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
let sz = match size_result {
Ok(sz) => sz,
Err(e) => {
let failure_action = classify_get_size_failure(&item, &e);
if failure_action == GetSizeFailureAction::AbandonSource {
return Err(ScannerError::source_unavailable(e));
}
let retry_suppressed = self.failed_retry_suppressed(&item.path);
if failure_action != GetSizeFailureAction::Skip {
self.resolved_failed_object_paths.remove(&item.path);
into.failed_objects = into.failed_objects.saturating_add(1);
if !retry_suppressed {
self.record_failed(&item.path);
}
if !retry_suppressed && should_log_failed_object(into.failed_objects) {
if let GetSizeFailureAction::HealMetadata { object } = &failure_action {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_METADATA_CORRUPT,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
drive = %self.local_disk.path().display(),
bucket = %item.bucket,
object = %object,
metadata_path = %item.path,
failed_objects = into.failed_objects,
state = "metadata_corrupt",
error = %e,
"Scanner detected corrupt object metadata"
);
} else {
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
path = %item.path,
failed_objects = into.failed_objects,
state = "get_size_failed",
error = %e,
"Scanner folder failed to get object size"
);
}
}
} else {
self.clear_failed_path(&item.path);
}
if let GetSizeFailureAction::HealMetadata { object } = failure_action
&& !retry_suppressed
{
// Single-flight (backlog#1894 axis A) — the
// recording mode and its guarantees are pinned by
// corrupt_metadata_recording below.
let mrf_result = rustfs_common::mrf_channel::try_send_mrf_intent_typed(
rustfs_common::mrf_channel::MrfKind::MetadataCorruption,
&item.bucket,
&object,
None,
None,
);
match corrupt_metadata_recording(mrf_result) {
CorruptMetadataRecording::LedgerOnly => {
// Recorded as Full (retry-later): admission
// for this target happens in the MRF
// consumer, not in the manager's queue here.
self.update_pending_scanner_heal_after_admission(
PendingScannerHealKind::Object,
&item.bucket,
Some(&object),
None,
self.scan_mode,
HealAdmissionResult::Full,
);
}
CorruptMetadataRecording::ImmediateAndLedger => {
self.send_required_scanner_heal_request(
PendingScannerHealKind::Object,
item.bucket.clone(),
Some(object.clone()),
None,
build_object_heal_request(
item.bucket.clone(),
object.clone(),
None,
self.scan_mode,
HealChannelPriority::High,
),
)
.await?;
}
}
}
wait_for_scanner_io(
&ctx,
self.sleeper
.pace_object(&mut self.pacing_debt, work_elapsed.saturating_add(work_started.elapsed())),
)
.await?;
continue;
}
};
self.clear_failed_path(&item.path);
found_object_metadata = true;
item.transform_meta_dir();
let resolved = path_join_buf(&[&item.bucket, &item.object_path()]);
abandoned_children.remove(&resolved);
if let Some(reader) = &mut dir_reader {
reader.resolve_abandoned(&resolved);
}
apply_scanner_size_summary(into, &sz);
if !sz.size_reconciliation.is_empty() {
self.coverage_gap |= self.old_cache.info.scan_progress.is_some();
}
self.apply_size_reconciliation(&sz);
into.objects += 1;
object_count += 1;
self.budget.record_object_scanned();
self.checkpoint_objects = self.checkpoint_objects.saturating_add(1);
self.maybe_send_checkpoint(folder, this_hash, into);
wait_for_scanner_io(
&ctx,
self.sleeper
.pace_object(&mut self.pacing_debt, work_elapsed.saturating_add(work_started.elapsed())),
)
.await?;
if ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
if should_yield_after_object(object_count, yield_every_objects) {
self.send_update_for_entry(this_hash, &folder.parent, into).await;
let yield_start = Instant::now();
tokio::task::yield_now().await;
global_metrics().record_scanner_yield(yield_start.elapsed());
}
}
self.budget.record_entries_visited(pending_entry_progress);
// A directory with queued children keeps its index until they end:
// a restart replays this listing to reach the unfinished child.
if indexed && dir_reader.as_ref().is_some_and(|reader| !reader.finished_listing()) {
return Err(ScannerError::Io(std::io::Error::new(
ErrorKind::Interrupted,
"scanner directory changed before listing completed",
)));
}
if raw_enumeration_complete
&& dir_reader
.as_ref()
.and_then(ScannerDirectory::folder_count)
.unwrap_or(queued_folders.len())
== 0
{
self.finish_raw_enumeration_parent(&folder.name);
}
if ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
// Checkpointed sweeps need child entries to validate their resume
// frontier (#8292). Outside that, also compact a wide bucket root:
// excluding it left #8961's ~170k top-level prefixes unbounded until
// the emergency 250k ceiling. Keep FORCE as the absolute backstop.
let is_scan_root = folder.name == self.old_cache.info.name;
let forward_sweep = self.old_cache.info.scan_progress.is_some();
if let Some(reader) = &dir_reader {
reader.restore_abandoned(&mut abandoned_children);
}
let total_folders = dir_reader
.as_ref()
.and_then(ScannerDirectory::folder_count)
.unwrap_or(queued_folders.len());
// A completed root above the normal cache ceiling is compacted by
// the existing completion path. A resumable sorted listing can use
// that representation throughout processing without losing its place.
let emergency_compact = total_folders >= force_compaction_width();
let force_compact = emergency_compact || (indexed && total_folders > DATA_SCANNER_COMPACT_AT_CHILDREN);
// Reused root children still have links in the new cache.
let should_compact = force_compact
|| (!forward_sweep
&& total_folders >= DATA_SCANNER_COMPACT_AT_FOLDERS
&& (!is_scan_root || into.children.is_empty()));
// Preserve the ordinary namespace walk's child isolation when the
// root starts sharing one accumulator across its descendants.
let isolate_compacted_children =
isolate_compacted_namespace_errors || (is_scan_root && !into.compacted && should_compact && !emergency_compact);
self.alert_excessive_folders(&folder.name, total_folders);
if !into.compacted && should_compact {
into.compacted = true;
for queued in &mut queued_folders {
queued.source = FolderScanSource::New;
}
if self.data_usage_scanner_debug {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
folder = %folder.name,
entry_count = total_folders,
state = "preemptive_compaction",
"Scanner folder switched to compacted mode"
);
}
}
let scan_checkpoint = self.old_cache.info.scan_checkpoint.as_ref();
let checkpoint_resume_after = scan_checkpoint.and_then(|checkpoint| {
if is_scan_root {
global_metrics().record_scanner_checkpoint_set(
checkpoint.version,
checkpoint.resume_after.clone(),
checkpoint.reason.as_str(),
);
}
if checkpoint.version != DATA_USAGE_SCAN_CHECKPOINT_VERSION || checkpoint.resume_after.is_empty() {
if is_scan_root {
global_metrics().record_scanner_checkpoint_ignored();
}
None
} else {
Some(checkpoint.resume_after.as_str())
}
});
let checkpoint_tracks_child_order = checkpoint_resume_after
.and_then(|resume_after| folder_resume_match(&folder.name, resume_after))
.is_some_and(|resume_match| matches!(resume_match, FolderResumeMatch::Descendant));
let scan_resume_after = checkpoint_resume_after.or(self.old_cache.info.scan_resume_after.as_deref());
let has_queued_folders = total_folders > 0;
let resume_order = if forward_sweep {
order_queued_folders_for_resume(&mut queued_folders, None)
} else {
order_queued_folders_for_resume(&mut queued_folders, scan_resume_after)
};
if checkpoint_tracks_child_order && has_queued_folders {
match resume_order {
FolderResumeOrder::Used => global_metrics().record_scanner_checkpoint_used(),
FolderResumeOrder::Stale => global_metrics().record_scanner_checkpoint_stale(),
FolderResumeOrder::NoHint => {}
}
}
let mut work = dir_reader.as_mut().and_then(ScannerDirectory::work);
if let Some(work) = &mut work {
work.restore_mode(into.compacted);
// A saved prefix tree must actually contain the contributions
// the parked queue has consumed. A failed cache save can leave
// this process's classified names ahead of its durable values.
if !into.compacted
&& !work
.linked
.iter()
.all(|name| self.can_restore_linked_child(folder, into, name))
{
work.rewind();
}
self.coverage_gap |= work.gap;
if into.compacted {
into.merge(&work.compacted_total);
} else {
for name in &work.linked {
let child = hash_path(name);
self.new_cache
.copy_with_children(&self.old_cache, &child, &Some(this_hash.clone()));
into.add_child(&child);
}
}
}
Ok(WalkAction::Advance(Box::new(FolderListing {
dir_reader,
queued_folders: queued_folders.into_iter(),
acknowledge_previous: None,
force_compact,
isolate_compacted_children,
found_object_metadata,
forward_sweep,
active_life_cycle,
abandoned_children,
healing: None,
})))
}
#[inline(never)]
async fn prepare_abandoned_children(
&mut self,
ctx: &CancellationToken,
frame: &FolderFrame,
listing: &mut FolderListing,
) -> Result<bool, ScannerError> {
let folder = &frame.folder;
if let Some(reader) = &mut listing.dir_reader {
wait_for_scanner_io(
ctx,
run_scanner_node_operation(self.node_admission.as_ref(), ctx, reader.verify_current()),
)
.await???;
}
// Scan for healing
if listing.abandoned_children.is_empty() || !self.try_should_heal().await? {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
folder = %folder.name,
state = "heal_skip_no_abandoned_children",
"Scanner folder skipped heal scan for abandoned children"
);
// Without a heal pass, finish the directory with the children already visited.
return Ok(false);
}
if self.disks.is_empty() || self.disks_quorum == 0 {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
folder = %folder.name,
disks = self.disks.len(),
quorum = self.disks_quorum,
state = "heal_skip_no_quorum",
"Scanner folder skipped heal scan because quorum is unavailable"
);
return Ok(false);
}
listing.healing = Some(AbandonedFolders::new(std::mem::take(&mut listing.abandoned_children)));
Ok(true)
}
#[inline(never)]
async fn finish_folder(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
) -> Result<FolderScanOutcome, ScannerError> {
let folder = &frame.folder;
let this_hash = &frame.hash;
let into = &mut frame.entry;
if !frame.was_compacted {
self.new_cache.replace_hashed(this_hash, &folder.parent, into);
}
self.compact_completed_folder(folder, this_hash, into);
// Compact if too many children...
// Allow compact_self on the bucket root when this is not a checkpointed
// forward sweep so wide roots can flatten instead of retaining one
// entry per top-level prefix (#8961). Checkpointed sweeps keep the
// previous root exclusion so resume frontiers stay addressable (#8292).
if !into.compacted {
let done_compact = Metrics::time(Metric::CompactFolder);
let compact_self = self.new_cache.info.name != folder.name || self.old_cache.info.scan_progress.is_none();
self.new_cache
.reduce_children_of(this_hash, DATA_SCANNER_COMPACT_AT_CHILDREN, compact_self);
// The root accumulator is also used by interruption handling.
// Reduction may have removed all its old child links, so publish
// the aggregate there before any cancellation-prone flush wait.
if folder.parent.is_none()
&& let Some(root) = self.new_cache.cache.get(&this_hash.0)
&& root.compacted
{
into.clone_from(root);
}
done_compact();
}
if !frame.was_compacted
&& let Some(updates) = &mut self.usage_updates
&& updates.cache.cache.contains_key(&clone_cache_value(&this_hash.0))
&& let Some(flat) = self.new_cache.size_recursive(&clone_cache_value(&this_hash.0))
{
updates.cache.delete_recursive(this_hash);
updates.cache.replace_hashed(this_hash, &folder.parent, &flat);
}
if folder.parent.is_none() {
#[cfg(test)]
tests::checkpoint_fixture::deep_compacted::cancel_at_root_flush(&self.root, &self.new_cache, ctx);
wait_for_scanner_io(ctx, self.sleeper.flush_pacing(&mut self.pacing_debt)).await?;
}
self.finish_size_reconciliation_batch();
let scanned_objects = u64::try_from(into.objects).unwrap_or(u64::MAX);
emit_scanner_folder_trace(&self.root, &folder.name, scanned_objects, frame.trace_started_at, "completed");
self.directory_checkpoints.remove(&folder.name);
Ok(FolderScanOutcome::Namespace)
}
pub fn as_mut_new_cache(&mut self) -> &mut DataUsageCache {
&mut self.new_cache
}
}
/// Scan a data folder
/// This function scans the basepath+cache.info.name and returns an updated cache.
/// The returned cache will always be valid, but may not be updated from the existing.
/// Throttling between operations is controlled by the provided [`DynamicSleeper`].
/// If the supplied context is canceled the function will return at the first chance.
#[allow(clippy::too_many_arguments)]
pub async fn scan_data_folder(
ctx: CancellationToken,
budget: Arc<ScannerCycleBudget>,
disks: Vec<Arc<Disk>>,
local_disk: Arc<Disk>,
cache: DataUsageCache,
updates: Option<mpsc::Sender<DataUsageEntry>>,
scan_mode: HealScanMode,
sleeper: DynamicSleeper,
) -> Result<DataUsageCache, ScannerError> {
scan_data_folder_scoped(
ctx.child_token(),
budget,
disks,
local_disk,
cache,
updates,
scan_mode,
sleeper,
None,
None,
Some(Arc::new(crate::scanner_io::ScannerLocalStop::default())),
)
.await
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn scan_data_folder_scoped(
ctx: CancellationToken,
budget: Arc<ScannerCycleBudget>,
disks: Vec<Arc<Disk>>,
local_disk: Arc<Disk>,
mut cache: DataUsageCache,
updates: Option<mpsc::Sender<DataUsageEntry>>,
scan_mode: HealScanMode,
sleeper: DynamicSleeper,
prefix_scan_scope: Option<ScannerBucketPrefixScanScope>,
checkpoint_tx: Option<mpsc::Sender<DataUsageCache>>,
local_stop: Option<Arc<crate::scanner_io::ScannerLocalStop>>,
) -> Result<DataUsageCache, ScannerError> {
use crate::data_usage_define::DATA_USAGE_ROOT;
// Check that we're not trying to scan the root
if cache.info.name.is_empty() || cache.info.name == DATA_USAGE_ROOT {
return Err(ScannerError::Other("internal error: root scan attempted".to_string()));
}
// URL endpoints include the storage host. A formatted disk also contributes
// its persistent UUID, fencing replacements and clone-like device/inode IDs.
if cache.info.scan_progress.is_some() && cache.info.scan_identity.is_some() {
use crate::storage_api::owner::EcstoreDiskAPI;
let endpoint = local_disk.endpoint().to_string();
let source = match wait_for_scanner_io(&ctx, directory_cursor::physical_source(&local_disk)).await {
Ok(source) => source?,
Err(_) if local_stop.as_ref().is_some_and(|stop| stop.reason().is_some()) => {
// The drive can retire before the first directory is read. Keep the
// checkpoint so the coordinator can retry against the current drive.
return Err(ScannerError::PartialCache(Box::new(cache)));
}
Err(error) => return Err(error),
};
let mut endpoints: HashSet<_> = disks.iter().map(|disk| disk.endpoint().to_string()).collect();
endpoints.insert(endpoint);
cache.activate_directory_source(source, &endpoints);
}
let directory_work = std::mem::take(&mut cache.info.scan_directory_work);
cache.info.scan_directory_work = DirectoryCheckpoint::verified_work(directory_work, &cache.info);
// Get disk path
let base_path = local_disk.path().to_string_lossy().to_string();
let (update_current_path, close_disk) = current_path_updater(&base_path, &cache.info.name).await;
let mut close_disk_guard = CloseDiskGuard::new(close_disk);
// Create skip_heal flag
let is_erasure_mode = scanner_is_erasure().await;
let skip_heal = Arc::new(std::sync::atomic::AtomicBool::new(!is_erasure_mode || cache.info.skip_healing));
// Create heal_object_select flag
let heal_object_select = if is_erasure_mode && !cache.info.skip_healing {
heal_object_select_prob()
} else {
0
};
let disks_quorum = disks.len() / 2;
let failed_object_ttl = rustfs_utils::get_env_u32(ENV_FAILED_OBJECT_TTL_SECS, DEFAULT_FAILED_OBJECT_TTL_SECS) as u64;
let failed_objects_max = rustfs_utils::get_env_u32(ENV_FAILED_OBJECTS_MAX, DEFAULT_FAILED_OBJECTS_MAX) as usize;
let tier_registry = runtime_tier_registry_for_cycle(cache.info.next_cycle, cache.info.leader_epoch).await;
let mut cache = cache;
cache.fold_retired_tiers(&tier_registry.names);
cache.info.tier_registry_generation = Some(tier_registry.generation);
let resume_frontier = cache.validated_scan_frontier().map(clone_cache_value);
if resume_frontier.is_some() {
global_metrics().record_scanner_checkpoint_used();
}
let bucket_name = clone_cache_value(&cache.info.name);
let notification_bucket_incarnation = match crate::storage_api::ecstore_resolve_object_store_handle() {
Some(store) => store.bucket_incarnation_id(&bucket_name).await.ok(),
None => None,
};
let object_metadata_visits = metrics::counter!(
"rustfs_scanner_object_metadata_visits_total",
"bucket" => bucket_name.clone(),
"disk" => base_path.clone()
);
#[cfg(feature = "diagnostic-prefix-attribution")]
let prefix_attribution = prefix_attribution::configured_for(&bucket_name, &base_path);
#[cfg(feature = "diagnostic-prefix-attribution")]
if prefix_attribution.is_some() {
object_metadata_visits.increment(0);
}
let next_cycle = cache.info.next_cycle;
let resume_position_on_entry = cache.has_scan_position();
let had_scan_checkpoint = cache.info.scan_checkpoint.is_some();
let new_cache = DataUsageCache {
info: clone_cache_value(&cache.info),
..Default::default()
};
let usage_updates = updates.map(|sender| ScannerUsageUpdates::new(sender, bucket_name.clone()));
let resume_failed_paths = if resume_frontier.is_some() {
failed_scan_paths(&cache)
} else {
Vec::new()
};
// Create folder scanner
let mut directory_checkpoints = HashMap::new();
for checkpoint in &cache.info.scan_directory_work {
directory_checkpoints
.entry(checkpoint.parent().to_owned())
.or_insert_with(HashMap::new)
.insert(
checkpoint.endpoint().to_owned(),
Arc::new(std::sync::Mutex::new(Some(checkpoint.clone()))),
);
}
let prefix_scan_scope = prefix_scan_scope.filter(|_| cache.info.size_reconciliation.is_empty());
let mut scanner = FolderScanner {
root: base_path,
old_cache: cache,
new_cache,
data_usage_scanner_debug: false,
heal_object_select,
scan_mode,
is_erasure_mode,
prefix_scan_scope,
failed_object_ttl_secs: failed_object_ttl,
failed_objects_max,
failed_object_paths_seen: HashSet::new(),
resolved_failed_object_paths: HashSet::new(),
sleeper,
pacing_debt: PacingDebt::default(),
node_admission: crate::workload_admission::scanner_node_admission(),
disks,
disks_quorum,
usage_updates,
checkpoint_tx,
checkpoint_ancestors: Vec::new(),
checkpoint_depth: 0,
checkpoint_objects: 0,
object_metadata_visits,
#[cfg(feature = "diagnostic-prefix-attribution")]
prefix_attribution,
last_checkpoint_objects: 0,
last_checkpoint_at: Instant::now(),
last_checkpoint_build_time: Duration::ZERO,
update_current_path,
budget: budget.clone(),
skip_heal,
local_disk,
notification_bucket_incarnation,
local_stop,
tier_registry,
pending_heals_changed: false,
coverage_frontier: clone_cache_value(&resume_frontier),
resume_frontier,
resume_failed_paths,
coverage_gap: false,
raw_enumeration_progress: Vec::new(),
directory_checkpoints,
pending_size_reconciliation_keys: HashSet::new(),
pending_size_reconciliation_scopes: HashSet::new(),
pending_size_reconciliation_truncated: false,
#[cfg(test)]
list_path_raw_options_observer: None,
#[cfg(test)]
defer_abandoned_entries_until_finished: false,
#[cfg(test)]
partial_heal_candidate_limit: None,
#[cfg(test)]
partial_heal_discovery_observer: None,
};
let now = FolderScanner::now_secs();
prune_size_reconciliation(&mut scanner.new_cache.info, now);
// Keep pre-scan attempt counts strictly below u32::MAX so any re-observed
// entry strictly advances `attempts` relative to `old_cache`.
for entry in scanner.new_cache.info.size_reconciliation.values_mut() {
if entry.attempts == u32::MAX {
entry.attempts = u32::MAX - 1;
}
}
for entry in scanner.old_cache.info.size_reconciliation.values_mut() {
if entry.attempts == u32::MAX {
entry.attempts = u32::MAX - 1;
}
}
// Check if context is cancelled
if ctx.is_cancelled() && scanner.local_stop.as_ref().is_none_or(|stop| stop.reason().is_none()) {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
if !ctx.is_cancelled() {
scanner.retry_pending_scanner_heals().await?;
}
// Read top level in bucket
let mut root = DataUsageEntry::default();
let folder = CachedFolder {
name: bucket_name.clone(),
parent: None,
object_heal_prob_div: 1,
};
// Scan the folder
let physical = scanner.local_disk.physical_admission();
match crate::workload_admission::with_scanner_physical_disk(physical, scanner.scan_folder(ctx.clone(), folder, &mut root))
.await
{
Ok(()) => {
directory_cursor::forget_bucket(&scanner.local_disk, &scanner.old_cache.info);
// Get the new cache and finalize it
let coverage_gap = scanner.coverage_gap;
scanner.reconcile_failed_objects_after_full_scan();
scanner.reconcile_size_reconciliation_after_full_scan();
let new_cache = scanner.as_mut_new_cache();
new_cache.force_compact(force_compact_limit_for_sweep(false));
new_cache.info.last_update = Some(SystemTime::now());
new_cache.info.next_cycle = next_cycle;
let unresolved_objects = coverage_gap
|| new_cache.cache.values().any(|entry| entry.failed_objects > 0)
|| !new_cache.info.failed_objects.is_empty()
|| !new_cache.info.size_reconciliation.is_empty();
let mixed_coverage = new_cache
.info
.scan_progress
.is_some_and(|progress| progress.started_plan != progress.requested_plan);
new_cache.info.snapshot_complete = !unresolved_objects && !mixed_coverage;
if mixed_coverage && !unresolved_objects {
new_cache.record_completed_bucket_observation();
// A companion is not an old-reader LKG or a reusable main value.
new_cache.info.lkg_snapshot_complete = false;
new_cache.info.scan_bucket_value_origins.clear();
} else if new_cache.info.snapshot_complete {
new_cache.info.scan_bucket_observations.remove(&bucket_name);
}
if let Some(progress) = &mut new_cache.info.scan_progress {
if new_cache.info.snapshot_complete {
new_cache.info.scan_plan_digest = Some(progress.requested_plan);
new_cache.info.scan_progress = None;
} else {
// Retain observations, then verify from the beginning under
// the latest plan. A clean tail cannot certify an old prefix.
progress.started_plan = progress.requested_plan;
new_cache.info.scan_plan_digest = None;
}
} else if coverage_gap {
// Legacy sampling must not certify an incomplete namespace.
new_cache.info.scan_plan_digest = None;
}
let had_scan_checkpoint = had_scan_checkpoint || new_cache.info.scan_checkpoint.is_some();
new_cache.info.scan_resume_after = None;
new_cache.info.scan_checkpoint = None;
new_cache.info.scan_raw_enumeration_cursor = None;
new_cache.info.scan_raw_enumeration_page_index = None;
new_cache.info.scan_raw_enumeration_path_page_indexes.clear();
new_cache.info.scan_directory_work.clear();
new_cache.info.scan_directory_source = None;
new_cache.info.scan_source_trees.clear();
new_cache.info.scan_coverage_receipt = None;
new_cache.info.scan_coverage_measured_at = None;
if had_scan_checkpoint {
global_metrics().record_scanner_checkpoint_cleared();
}
close_disk_guard.close().await;
if unresolved_objects || mixed_coverage {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "bucket_sweep_incomplete",
bucket = %bucket_name,
pool = new_cache.info.source.map(|source| source.pool_index),
set = new_cache.info.source.map(|source| source.set_index),
cycle = next_cycle,
leader_epoch = new_cache.info.leader_epoch,
resume_position_on_entry,
resume_position = new_cache.has_scan_position(),
coverage_gap,
unresolved_objects,
root_failed_objects = root.failed_objects,
failed_objects = new_cache.info.failed_objects.len(),
size_reconciliation_entries = new_cache.info.size_reconciliation.len(),
mixed_coverage,
"Scanner bucket sweep requires another verification pass"
);
Err(ScannerError::PartialCache(Box::new(std::mem::take(new_cache))))
} else {
Ok(std::mem::take(new_cache))
}
}
Err(e @ ScannerError::SourceUnavailable(_)) => {
// A fault is not a budget interruption. Leave the last durable checkpoint untouched.
close_disk_guard.close().await;
Err(e)
}
Err(e) => {
if ctx.is_cancelled() || matches!(&e, ScannerError::ResourceDeferred) {
let root_hash = hash_path(&bucket_name);
let root_has_progress = data_usage_root_has_progress(&root);
let pending_heals_changed = scanner.pending_heals_changed;
let legacy_coverage_gap = scanner.coverage_gap && scanner.old_cache.info.scan_progress.is_none();
let raw_enumeration_path_page_indexes = scanner.raw_enumeration_path_page_indexes();
let (raw_enumeration_cursor, raw_enumeration_page_index) = scanner.take_raw_enumeration_resume_state();
let carry_forward_cache = ((raw_enumeration_cursor.is_some() || raw_enumeration_page_index.is_some())
&& !root_has_progress)
.then(|| std::mem::take(&mut scanner.old_cache.cache));
if root_has_progress {
scanner.carry_forward_old_children(&root_hash, &mut root);
}
let coverage_frontier = clone_cache_value(&scanner.coverage_frontier);
let directories = scanner.saved_directories();
let new_cache = scanner.as_mut_new_cache();
new_cache.info.scan_directory_work = directories;
if root_has_progress {
new_cache.replace_hashed(&root_hash, &None, &root);
} else if let Some(cache) = carry_forward_cache {
new_cache.cache = cache;
}
if raw_enumeration_cursor.is_some() {
new_cache.info.scan_raw_enumeration_cursor = raw_enumeration_cursor;
new_cache.info.scan_checkpoint = None;
new_cache.info.scan_resume_after = None;
new_cache.info.scan_coverage_receipt = None;
new_cache.info.scan_coverage_measured_at = None;
}
if raw_enumeration_page_index.is_some() {
new_cache.info.scan_raw_enumeration_page_index = raw_enumeration_page_index;
new_cache.info.scan_raw_enumeration_path_page_indexes = raw_enumeration_path_page_indexes;
new_cache.info.scan_checkpoint = None;
new_cache.info.scan_resume_after = None;
new_cache.info.scan_coverage_receipt = None;
new_cache.info.scan_coverage_measured_at = None;
}
if partial_cache_is_useful(&root, pending_heals_changed)
|| !new_cache.info.scan_directory_work.is_empty()
|| new_cache.info.scan_raw_enumeration_cursor.is_some()
|| new_cache.info.scan_raw_enumeration_page_index.is_some()
|| !new_cache.info.size_reconciliation.is_empty()
{
if new_cache.root().is_some() {
// Interrupted sweeps seal a resume frontier after this.
// Flattening the root at the ordinary 10k limit would
// drop frontier-named children and force the next cycle
// to replay completed prefixes (#8292 / review on #9193).
// Keep only the emergency FORCE ceiling here; successful
// completions above apply DATA_SCANNER_COMPACT_AT_CHILDREN.
new_cache.force_compact(force_compact_limit_for_sweep(true));
}
new_cache.info.last_update = Some(SystemTime::now());
new_cache.info.next_cycle = next_cycle;
new_cache.info.snapshot_complete = false;
if legacy_coverage_gap {
new_cache.info.scan_plan_digest = None;
}
if root_has_progress {
set_scan_checkpoint(new_cache, checkpoint_reason_from_budget(budget.reason()));
}
new_cache.seal_scan_frontier(coverage_frontier.as_deref())?;
if new_cache.info.scan_progress.is_some() {
if let Some(checkpoint) = &new_cache.info.scan_checkpoint {
global_metrics().record_scanner_checkpoint_set(
checkpoint.version,
checkpoint.resume_after.clone(),
checkpoint.reason.as_str(),
);
} else {
global_metrics().record_scanner_checkpoint_cleared();
}
}
new_cache.info.scan_resource_deferred = matches!(&e, ScannerError::ResourceDeferred);
close_disk_guard.close().await;
return Err(ScannerError::PartialCache(Box::new(std::mem::take(new_cache))));
}
}
if matches!(&e, ScannerError::Io(io) if io.kind() == ErrorKind::NotFound) {
let mut partial_cache = scanner.old_cache;
// An empty input still needs a root for the non-publishable
// partial result; retain nonempty durable caches unchanged.
if partial_cache.cache.is_empty() {
partial_cache
.cache
.insert(hash_path(&bucket_name).0, DataUsageEntry::default());
}
partial_cache.info.last_update = Some(SystemTime::now());
partial_cache.info.next_cycle = next_cycle;
partial_cache.info.snapshot_complete = false;
close_disk_guard.close().await;
return Err(ScannerError::NamespaceNotFoundCache(Box::new(partial_cache)));
}
if matches!(&e, ScannerError::ResourceDeferred)
|| scanner.local_stop.as_ref().is_some_and(|stop| stop.reason().is_some())
{
// Admission pressure is not disk failure or an empty census.
// Keep the previous tree when no new useful progress exists.
let mut partial_cache = scanner.old_cache;
if partial_cache.cache.is_empty() {
partial_cache
.cache
.insert(hash_path(&bucket_name).0, DataUsageEntry::default());
}
partial_cache.info.snapshot_complete = false;
partial_cache.info.scan_resource_deferred = matches!(&e, ScannerError::ResourceDeferred);
close_disk_guard.close().await;
return Err(ScannerError::PartialCache(Box::new(partial_cache)));
}
close_disk_guard.close().await;
// No useful information, return original cache
Err(e)
}
}
}
mod directory_cursor;
mod folder_walk;
mod heal_walk;
mod queue_walk;
pub use directory_cursor::DirectoryCheckpoint;
pub(crate) use directory_cursor::{DirectoryProgress, DirectoryReadProgress};
use folder_walk::{FolderFrame, FolderListing, WalkAction};
use heal_walk::AbandonedFolders;
mod item_actions;
mod ledger;
mod native_io;
#[cfg(feature = "diagnostic-prefix-attribution")]
mod prefix_attribution;
pub(crate) use item_actions::scanner_disk_heal_scope;
use item_actions::*;
pub use item_actions::{GetSizeFn, ScannerItem};
use ledger::*;
#[cfg(test)]
pub(crate) use tests::checkpoint_fixture::run_checkpoint_fixture;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod size_reconciliation_reconcile_tests {
use super::*;
use crate::data_usage_define::SizeReconciliationEntry;
use crate::{DiskOption, Endpoint, SCANNER_SLEEPER, new_disk};
use std::sync::atomic::AtomicBool;
fn sample_entry(key: &str, object: &str, attempts: u32) -> SizeReconciliationEntry {
SizeReconciliationEntry {
key: key.to_string(),
bucket: "bucket".to_string(),
object: object.to_string(),
reason: "invalid_declared_size".to_string(),
first_seen: FolderScanner::now_secs(),
attempts,
..Default::default()
}
}
async fn create_test_disk_and_bucket(bucket: &str) -> (tempfile::TempDir, Arc<Disk>) {
let temp_dir = tempfile::tempdir().expect("create temp scanner dir");
let bucket_dir = temp_dir.path().join(bucket);
std::fs::create_dir_all(&bucket_dir).expect("create bucket directory");
let mut endpoint = Endpoint::try_from(temp_dir.path().to_string_lossy().as_ref()).expect("parse local disk endpoint");
endpoint.set_pool_index(0);
endpoint.set_set_index(0);
endpoint.set_disk_index(0);
let disk = new_disk(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
)
.await
.expect("create local disk");
(temp_dir, disk)
}
#[tokio::test]
async fn full_scan_clears_vanished_size_reconciliation_and_completes_snapshot() {
let bucket = "vanished-size-reconciliation";
let (_temp_dir, disk) = create_test_disk_and_bucket(bucket).await;
let mut old_cache = DataUsageCache::default();
old_cache.info.name = bucket.to_string();
old_cache.info.next_cycle = 2;
old_cache.info.size_reconciliation.insert(
"vanished-key".to_string(),
SizeReconciliationEntry {
key: "vanished-key".to_string(),
bucket: bucket.to_string(),
object: "poison".to_string(),
reason: "invalid_declared_size".to_string(),
first_seen: FolderScanner::now_secs(),
attempts: 1,
..Default::default()
},
);
old_cache.info.size_reconciliation.insert(
"saturated-key".to_string(),
SizeReconciliationEntry {
key: "saturated-key".to_string(),
bucket: bucket.to_string(),
object: "old-poison".to_string(),
reason: "invalid_declared_size".to_string(),
first_seen: FolderScanner::now_secs(),
attempts: u32::MAX,
..Default::default()
},
);
let ctx = CancellationToken::new();
let budget = ScannerCycleBudget::new(&ctx, Default::default());
let scanned = scan_data_folder(
ctx,
budget,
vec![Arc::clone(&disk)],
disk,
old_cache,
None,
HealScanMode::Normal,
SCANNER_SLEEPER.clone(),
)
.await
.expect("full scan of bucket after deleting corrupt object should succeed");
assert!(
scanned.info.size_reconciliation.is_empty(),
"vanished objects must be pruned from size_reconciliation after a full bucket scan: {:?}",
scanned.info.size_reconciliation
);
assert!(
scanned.info.snapshot_complete,
"snapshot must become complete once vanished corrupt entries are reconciled"
);
}
#[tokio::test]
async fn reconcile_size_reconciliation_keeps_reobserved_and_new_entries_drops_vanished() {
let (_temp_dir, disk) = create_test_disk_and_bucket("bucket").await;
let update_current_path: UpdateCurrentPathFn = Arc::new(|_: &str| Box::pin(async {}));
let mut old_cache = DataUsageCache::default();
old_cache.info.name = "bucket".to_string();
let vanished = sample_entry("vanished", "deleted-obj", 1);
let still_bad = sample_entry("still-bad", "corrupt-obj", 1);
old_cache.info.size_reconciliation.insert(vanished.key.clone(), vanished);
old_cache
.info
.size_reconciliation
.insert(still_bad.key.clone(), still_bad.clone());
let new_cache = DataUsageCache {
info: old_cache.info.clone(),
..Default::default()
};
let mut scanner = FolderScanner {
root: disk.path().to_string_lossy().to_string(),
old_cache,
new_cache,
data_usage_scanner_debug: false,
heal_object_select: 0,
scan_mode: HealScanMode::Normal,
is_erasure_mode: false,
prefix_scan_scope: None,
failed_object_ttl_secs: u64::MAX,
failed_objects_max: usize::MAX,
failed_object_paths_seen: HashSet::new(),
resolved_failed_object_paths: HashSet::new(),
sleeper: SCANNER_SLEEPER.clone(),
pacing_debt: PacingDebt::default(),
node_admission: None,
disks: Vec::new(),
disks_quorum: 0,
notification_bucket_incarnation: None,
usage_updates: None,
checkpoint_tx: None,
checkpoint_ancestors: Vec::new(),
checkpoint_depth: 0,
checkpoint_objects: 0,
object_metadata_visits: metrics::Counter::noop(),
#[cfg(feature = "diagnostic-prefix-attribution")]
prefix_attribution: None,
last_checkpoint_objects: 0,
last_checkpoint_at: Instant::now(),
last_checkpoint_build_time: Duration::ZERO,
update_current_path,
budget: ScannerCycleBudget::new(&CancellationToken::new(), Default::default()),
skip_heal: Arc::new(AtomicBool::new(false)),
local_disk: disk,
local_stop: None,
tier_registry: crate::TierRegistrySnapshot {
generation: 0,
names: Arc::new([]),
refresh_failed: false,
},
pending_heals_changed: false,
coverage_frontier: None,
resume_frontier: None,
resume_failed_paths: Vec::new(),
coverage_gap: false,
raw_enumeration_progress: Vec::new(),
directory_checkpoints: HashMap::new(),
pending_size_reconciliation_keys: HashSet::new(),
pending_size_reconciliation_scopes: HashSet::new(),
pending_size_reconciliation_truncated: false,
list_path_raw_options_observer: None,
defer_abandoned_entries_until_finished: false,
partial_heal_candidate_limit: None,
partial_heal_discovery_observer: None,
};
// Re-observe `still-bad` and discover a brand-new `new-bad`; do not visit `vanished`.
let mut summary = SizeSummary::default();
summary.record_size_reconciliation(still_bad);
summary.record_reconciliation_scope("bucket", "corrupt-obj");
let new_bad = sample_entry("new-bad", "fresh-corrupt", 1);
summary.record_size_reconciliation(new_bad);
summary.record_reconciliation_scope("bucket", "fresh-corrupt");
scanner.apply_size_reconciliation(&summary);
scanner.finish_size_reconciliation_batch();
// Resumed / partial / errored scans must keep unseen entries.
scanner.resume_frontier = Some("bucket/a".to_string());
scanner.reconcile_size_reconciliation_after_full_scan();
assert!(scanner.new_cache.info.size_reconciliation.contains_key("vanished"));
scanner.resume_frontier = None;
scanner.coverage_gap = true;
scanner.reconcile_size_reconciliation_after_full_scan();
assert!(scanner.new_cache.info.size_reconciliation.contains_key("vanished"));
scanner.coverage_gap = false;
scanner
.new_cache
.info
.failed_objects
.insert("bucket/other/xl.meta".to_string(), FolderScanner::now_secs());
scanner.reconcile_size_reconciliation_after_full_scan();
assert!(scanner.new_cache.info.size_reconciliation.contains_key("vanished"));
scanner.new_cache.info.failed_objects.clear();
// Uninterrupted full scan drops only `vanished` while retaining `still-bad` and `new-bad`.
scanner.reconcile_size_reconciliation_after_full_scan();
assert!(!scanner.new_cache.info.size_reconciliation.contains_key("vanished"));
assert_eq!(scanner.new_cache.info.size_reconciliation["still-bad"].attempts, 2);
assert_eq!(scanner.new_cache.info.size_reconciliation["new-bad"].attempts, 1);
}
}
#[cfg(test)]
tokio::task_local! {
pub(crate) static TEST_SIZE_DISPATCH_BOUNDARIES: tokio::sync::mpsc::UnboundedSender<&'static str>;
}
#[cfg(test)]
pub(crate) fn observe_test_size_dispatch_boundary(stage: &'static str) -> bool {
TEST_SIZE_DISPATCH_BOUNDARIES
.try_with(|sender| sender.send(stage).is_ok())
.unwrap_or(false)
}