Compare commits

...

1 Commits

Author SHA1 Message Date
Cursor Agent a0c63cea72 fix(scanner): walk directories with an explicit stack
Port the scanner folder walker from #9623 onto current main so nested
directory polls no longer grow the worker stack. Keep later main
behavior for object metadata, lifecycle, heal discovery, and child
errors.

Refs rustfs/backlog#3293

Co-authored-by: Chris An <overtrue@users.noreply.github.com>
2026-11-27 10:18:14 +00:00
7 changed files with 2046 additions and 1615 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,271 @@
// 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 super::*;
use std::future::Future;
use std::pin::Pin;
/// Poll `future` in its own frame.
///
/// A direct `.await` can inline the child state machine into the caller. Debug
/// scanner frames are large enough that fusing them overflows the 4 MiB stack
/// used by scanner tests. Trait-object dispatch keeps each frame separate.
pub(super) fn poll_apart<'a, F>(future: F) -> Pin<Box<dyn Future<Output = F::Output> + Send + 'a>>
where
F: Future + Send + 'a,
{
Box::pin(future)
}
/// The current folder owns its accumulator even when its parent lent it a compacted total.
pub(super) struct FolderFrame {
pub(super) folder: CachedFolder,
pub(super) mode: FolderScanMode,
pub(super) hash: DataUsageHash,
pub(super) entry: DataUsageEntry,
pub(super) was_compacted: bool,
pub(super) started: Instant,
pub(super) trace_started_at: Option<Instant>,
}
impl FolderFrame {
fn new(folder: CachedFolder, entry: DataUsageEntry, mode: FolderScanMode) -> Self {
Self {
mode,
hash: hash_path(&folder.name),
folder,
was_compacted: entry.compacted,
entry,
started: Instant::now(),
trace_started_at: trace_start_instant(),
}
}
}
pub(super) struct FolderListing {
pub(super) dir_reader: Option<ScannerDirectory>,
pub(super) queued_folders: std::vec::IntoIter<QueuedFolder>,
pub(super) acknowledge_previous: Option<(String, bool)>,
pub(super) force_compact: bool,
pub(super) isolate_compacted_children: bool,
pub(super) found_object_metadata: bool,
pub(super) forward_sweep: bool,
pub(super) active_life_cycle: Option<Arc<rustfs_gateway_types::persistence::PersistedLifecycleConfiguration>>,
pub(super) abandoned_children: DataUsageHashMap,
pub(super) healing: Option<AbandonedFolders>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum ChildAccounting {
Linked,
Shared,
Summary { isolated: bool },
}
pub(super) enum ChildOrigin {
Queued,
Abandoned(tokio_util::sync::DropGuard),
}
pub(super) struct ChildRequest {
pub(super) folder: CachedFolder,
pub(super) mode: FolderScanMode,
pub(super) accounting: ChildAccounting,
pub(super) origin: ChildOrigin,
}
pub(super) enum WalkAction {
Enter(bool),
Advance(Box<FolderListing>),
Descend(Box<FolderListing>, ChildRequest),
Finish,
Return(Result<FolderScanOutcome, ScannerError>),
}
struct SuspendedFolder {
frame: FolderFrame,
listing: Box<FolderListing>,
accounting: ChildAccounting,
origin: ChildOrigin,
checkpointed: bool,
suspended_updates: Option<ScannerUsageUpdates>,
}
impl FolderScanner {
pub(super) fn suspend_checkpoint_parent(
&mut self,
hash: &mut DataUsageHash,
entry: &mut DataUsageEntry,
) -> Result<bool, ScannerError> {
if self.checkpoint_tx.is_none() || self.old_cache.info.scan_progress.is_none() {
return Ok(false);
}
let depth = self.checkpoint_depth;
if depth >= MAX_DATA_USAGE_CACHE_DEPTH {
return Err(ScannerError::Other("scanner checkpoint ancestor depth limit exceeded".to_string()));
}
if self.checkpoint_ancestors.len() == depth {
self.checkpoint_ancestors.push(ScannerCheckpointAncestor::default());
}
let slot = &mut self.checkpoint_ancestors[depth];
std::mem::swap(hash, &mut slot.hash);
std::mem::swap(entry, &mut slot.entry);
self.checkpoint_depth += 1;
Ok(true)
}
#[inline(never)]
async fn advance_folder(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
mut listing: Box<FolderListing>,
) -> Result<WalkAction, ScannerError> {
if listing.healing.is_none() {
if let Some(child) = poll_apart(self.next_queued_child(ctx, frame, &mut listing)).await? {
return Ok(WalkAction::Descend(listing, child));
}
if !poll_apart(self.prepare_abandoned_children(ctx, frame, &mut listing)).await? {
return Ok(WalkAction::Finish);
}
}
if let Some(abandoned) = &mut listing.healing
&& let Some((folder, guard)) = poll_apart(self.next_abandoned_child(ctx, frame, abandoned)).await?
{
let accounting = if frame.entry.compacted {
ChildAccounting::Shared
} else {
ChildAccounting::Linked
};
return Ok(WalkAction::Descend(
listing,
ChildRequest {
folder,
mode: FolderScanMode::Namespace,
accounting,
origin: ChildOrigin::Abandoned(guard),
},
));
}
Ok(WalkAction::Finish)
}
#[inline(never)]
pub(super) async fn scan_folder_inner(
&mut self,
ctx: CancellationToken,
folder: CachedFolder,
into: &mut DataUsageEntry,
mode: FolderScanMode,
isolate_compacted_namespace_errors: bool,
) -> Result<FolderScanOutcome, ScannerError> {
let mut parents = Vec::<SuspendedFolder>::new();
// A compacted child borrows the entire parent accumulator. Reuse the
// empty replacement across siblings, including its histogram allocations.
let mut shared_slots = Vec::new();
let mut current = FolderFrame::new(folder, std::mem::take(into), mode);
let mut action = WalkAction::Enter(isolate_compacted_namespace_errors);
loop {
#[cfg(test)]
tests::checkpoint_fixture::deep_compacted::observe_folder_frame_depth(parents.len() + 1);
action = match action {
WalkAction::Enter(isolate) => poll_apart(self.enumerate_folder(&ctx, &mut current, isolate)).await,
WalkAction::Advance(listing) => poll_apart(self.advance_folder(&ctx, &mut current, listing)).await,
WalkAction::Finish => Ok(WalkAction::Return(poll_apart(self.finish_folder(&ctx, &mut current)).await)),
WalkAction::Descend(listing, child) => {
let checkpoint = if child.accounting == ChildAccounting::Linked {
self.suspend_checkpoint_parent(&mut current.hash, &mut current.entry)
} else {
Ok(false)
};
let isolated = child.accounting == ChildAccounting::Summary { isolated: true };
let suspended_updates = if isolated { self.usage_updates.take() } else { None };
let entry = match child.accounting {
ChildAccounting::Shared => std::mem::replace(&mut current.entry, shared_slots.pop().unwrap_or_default()),
ChildAccounting::Linked => DataUsageEntry::default(),
ChildAccounting::Summary { .. } => DataUsageEntry {
compacted: true,
..Default::default()
},
};
parents.push(SuspendedFolder {
frame: current,
listing,
accounting: child.accounting,
origin: child.origin,
checkpointed: matches!(checkpoint, Ok(true)),
suspended_updates,
});
current = FolderFrame::new(child.folder, entry, child.mode);
checkpoint.map(|_| WalkAction::Enter(isolated))
}
WalkAction::Return(result) => {
Metrics::inc_time(Metric::ScanFolder, current.started.elapsed());
let Some(mut parent) = parents.pop() else {
*into = current.entry;
return result;
};
if parent.checkpointed {
self.checkpoint_depth -= 1;
let slot = &mut self.checkpoint_ancestors[self.checkpoint_depth];
std::mem::swap(&mut parent.frame.hash, &mut slot.hash);
std::mem::swap(&mut parent.frame.entry, &mut slot.entry);
}
if parent.accounting == ChildAccounting::Shared {
std::mem::swap(&mut parent.frame.entry, &mut current.entry);
}
if parent.accounting == (ChildAccounting::Summary { isolated: true }) {
self.usage_updates = parent.suspended_updates;
}
// Settle even errors from entering a child: the parent owns the
// decision to propagate a partial result or isolate a coverage gap.
let resume = match parent.origin {
ChildOrigin::Queued => {
poll_apart(self.accept_queued_child(
&ctx,
&mut parent.frame,
&mut parent.listing,
&current,
parent.accounting,
result,
))
.await
}
ChildOrigin::Abandoned(_cancel_on_exit) => poll_apart(self.accept_abandoned_child(
&ctx,
&mut parent.frame,
&current,
result,
parent.accounting == ChildAccounting::Shared,
))
.await
.map(|()| true),
};
if parent.accounting == ChildAccounting::Shared {
shared_slots.push(current.entry);
}
current = parent.frame;
resume.map(|more| {
if more {
WalkAction::Advance(parent.listing)
} else {
WalkAction::Finish
}
})
}
}
.unwrap_or_else(|error| WalkAction::Return(Err(error)));
}
}
}
@@ -0,0 +1,451 @@
// 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 super::*;
use tokio_util::sync::DropGuard;
pub(super) struct AbandonedFolders {
names: std::collections::hash_set::IntoIter<String>,
previous_bucket: String,
}
impl AbandonedFolders {
pub(super) fn new(names: HashSet<String>) -> Self {
Self {
names: names.into_iter(),
previous_bucket: String::new(),
}
}
}
impl FolderScanner {
#[inline(never)]
pub(super) async fn next_abandoned_child(
&mut self,
ctx: &CancellationToken,
frame: &FolderFrame,
abandoned: &mut AbandonedFolders,
) -> Result<Option<(CachedFolder, DropGuard)>, ScannerError> {
for name in abandoned.names.by_ref() {
if !self.try_should_heal().await? {
break;
}
let (bucket, prefix) = path2_bucket_object(&name);
if bucket != abandoned.previous_bucket {
self.send_required_scanner_heal_request(
PendingScannerHealKind::Bucket,
bucket.clone(),
None,
None,
build_bucket_heal_request(bucket.clone(), HealChannelPriority::High),
)
.await?;
abandoned.previous_bucket.clone_from(&bucket);
}
let child_ctx = ctx.child_token();
let cancel_on_exit = child_ctx.clone().drop_guard();
if self.discover_abandoned_child(child_ctx.clone(), bucket, prefix).await? {
let child = CachedFolder {
name,
parent: Some(frame.hash.clone()),
object_heal_prob_div: 1,
};
return Ok(Some((child, cancel_on_exit)));
}
}
Ok(None)
}
#[inline(never)]
pub(super) async fn accept_abandoned_child(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
child: &FolderFrame,
result: Result<FolderScanOutcome, ScannerError>,
shared: bool,
) -> Result<(), ScannerError> {
if shared {
result?;
self.send_update_for_entry(&frame.hash, &frame.folder.parent, &frame.entry)
.await;
tokio::task::yield_now().await;
return Ok(());
}
if let Err(error) = result {
if matches!(error, ScannerError::SourceUnavailable(_)) {
return Err(error);
}
if ctx.is_cancelled() || matches!(&error, ScannerError::ResourceDeferred) {
self.preserve_partial_child_progress(&child.folder.parent, &child.hash, &mut frame.entry, &child.entry)
.await;
return Err(error);
}
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
folder = %frame.folder.name,
child_folder = %child.folder.name,
state = "heal_child_scan_failed",
error = %error,
"Scanner heal child folder scan failed"
);
return Ok(());
}
tokio::task::yield_now().await;
frame.entry.add_child(&child.hash);
self.refresh_usage_subtree(&child.hash, &child.folder.parent);
self.send_update().await;
self.maybe_send_checkpoint(&frame.folder, &frame.hash, &frame.entry);
Ok(())
}
#[inline(never)]
async fn discover_abandoned_child(
&mut self,
child_ctx: CancellationToken,
bucket: String,
prefix: String,
) -> Result<bool, ScannerError> {
let (agreed_tx, mut agreed_rx) = mpsc::channel::<String>(1);
let (partial_tx, mut partial_rx) = mpsc::channel::<MetaCacheEntries>(1);
let (finished_tx, mut finished_rx) = mpsc::channel::<Vec<Option<DiskError>>>(1);
let disks = self.disks.iter().cloned().map(Some).collect();
let disks_quorum = self.disks_quorum;
let bucket_clone = bucket.clone();
let prefix_clone = prefix.clone();
let child_ctx_clone = child_ctx.clone();
#[cfg(test)]
let list_path_raw_options_observer = self.list_path_raw_options_observer.clone();
tokio::spawn(async move {
let options = ListPathRawOptions {
disks,
bucket: bucket_clone.clone(),
path: prefix_clone.clone(),
recursive: true,
report_not_found: true,
min_disks: disks_quorum,
agreed: Some(Box::new(move |entry: MetaCacheEntry| {
let entry_name = entry.name.clone();
let agreed_tx = agreed_tx.clone();
Box::pin(async move {
if let Err(e) = agreed_tx.send(entry_name).await {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
entry = %entry.name,
state = "list_path_agreed_send_failed",
error = %e,
"Scanner list_path_raw agreed callback failed"
);
}
Ok(())
})
})),
partial: Some(Box::new(move |entries: MetaCacheEntries, _: &[Option<DiskError>]| {
let partial_tx = partial_tx.clone();
Box::pin(async move {
if let Err(e) = partial_tx.send(entries).await {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_partial_send_failed",
error = %e,
"Scanner list_path_raw partial callback failed"
);
}
})
})),
finished: Some(Box::new(move |errs: &[Option<DiskError>]| {
let finished_tx = finished_tx.clone();
let errs_clone = errs.to_vec();
Box::pin(async move {
if let Err(e) = finished_tx.send(errs_clone).await {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_finished_send_failed",
error = %e,
"Scanner list_path_raw finished callback failed"
);
}
})
})),
..scanner_abandoned_child_list_options()
};
#[cfg(test)]
if let Some(observer) = list_path_raw_options_observer {
let _ =
observer.send((options.skip_walkdir_total_timeout, options.walkdir_timeout, options.walkdir_stall_timeout));
}
if let Err(e) = crate::storage_api::ecstore_with_background_disk_io(
child_ctx_clone.clone(),
list_path_raw(child_ctx_clone.clone(), options),
)
.await
{
if is_missing_path_disk_error(&e) {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
bucket = %bucket_clone,
prefix = %prefix_clone,
state = "list_path_missing",
error = %e,
"Scanner list_path_raw missing path skipped"
);
} else {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
bucket = %bucket_clone,
prefix = %prefix_clone,
state = "list_path_failed",
error = %e,
"Scanner list_path_raw failed"
);
}
}
});
let mut found_objects = false;
let mut agreed_closed = false;
let mut partial_closed = false;
let mut finished_closed = false;
let mut seen_heal_candidates: HashSet<(String, Option<String>, MetaCacheHealCandidateKind)> = HashSet::new();
let mut seen_truncated_objects: HashSet<String> = HashSet::new();
loop {
if child_ctx.is_cancelled() || (agreed_closed && partial_closed && finished_closed) {
break;
}
#[cfg(test)]
let defer_entries = self.defer_abandoned_entries_until_finished && !finished_closed;
#[cfg(not(test))]
let defer_entries = false;
select! {
entry_name = agreed_rx.recv(), if !agreed_closed && !defer_entries => {
let Some(entry_name) = entry_name else {
agreed_closed = true;
continue;
};
(self.update_current_path)(&entry_name).await;
}
entries = partial_rx.recv(), if !partial_closed && !defer_entries => {
let Some(entries) = entries else {
partial_closed = true;
continue;
};
if !self.try_should_heal().await? {
child_ctx.cancel();
break;
}
#[cfg(test)]
let candidate_limit = self.partial_heal_candidate_limit.unwrap_or(MAX_META_CACHE_HEAL_CANDIDATES);
#[cfg(not(test))]
let candidate_limit = MAX_META_CACHE_HEAL_CANDIDATES;
let discovery = entries.discover_heal_candidates(&bucket, candidate_limit);
#[cfg(test)]
if let Some(observer) = &self.partial_heal_discovery_observer {
let _ = observer.send((discovery.candidates.len(), discovery.truncated_candidates.len()));
}
counter!(METRIC_SCANNER_HEAL_DISCOVERY_CANDIDATES_TOTAL)
.increment(u64::try_from(discovery.candidates.len()).unwrap_or(u64::MAX));
counter!(METRIC_SCANNER_HEAL_DISCOVERY_SUB_QUORUM_TOTAL).increment(
u64::try_from(
discovery
.candidates
.iter()
.filter(|candidate| candidate.replica_count < disks_quorum)
.count(),
)
.unwrap_or(u64::MAX),
);
counter!(METRIC_SCANNER_HEAL_DISCOVERY_UNVERIFIED_TOTAL).increment(
u64::try_from(discovery.unverified_count).unwrap_or(u64::MAX),
);
if discovery.truncated {
counter!(METRIC_SCANNER_HEAL_DISCOVERY_TRUNCATED_TOTAL).increment(1);
}
for candidate in discovery.candidates {
let sub_quorum_candidate = candidate.replica_count < disks_quorum;
let version_id = candidate.validated_version().map(|id| id.to_string());
let identity = (candidate.object.clone(), version_id.clone(), candidate.kind.clone());
if seen_heal_candidates.len() >= MAX_META_CACHE_HEAL_CANDIDATES
&& !seen_heal_candidates.contains(&identity)
{
continue;
}
if !seen_heal_candidates.insert(identity) {
continue;
}
let request = if candidate.is_unversioned() {
build_non_destructive_object_heal_request(
bucket.clone(),
candidate.object.clone(),
self.scan_mode,
HealChannelPriority::High,
)
} else {
build_object_heal_request(
bucket.clone(),
candidate.object.clone(),
version_id.clone(),
self.scan_mode,
HealChannelPriority::High,
)
};
(self.update_current_path)(&candidate.object).await;
let admission = self.send_required_scanner_heal_request(
PendingScannerHealKind::Object,
bucket.clone(),
Some(candidate.object.clone()),
version_id.clone(),
request,
)
.await?;
if admission.is_admitted() {
counter!(METRIC_SCANNER_HEAL_DISCOVERY_QUEUED_TOTAL).increment(1);
} else if sub_quorum_candidate {
self.mark_pending_scanner_heal_reason(
PendingScannerHealKind::Object,
&bucket,
Some(&candidate.object),
version_id.as_deref(),
"sub_quorum_metadata",
);
}
found_objects = true;
}
// Candidates beyond the main cap remain exact
// version requests; never downgrade them to a
// latest-version (version_id=None) heal.
for candidate in discovery.truncated_candidates {
let version_id = candidate.validated_version().map(|id| id.to_string());
let identity = (candidate.object.clone(), version_id.clone(), candidate.kind.clone());
if seen_truncated_objects.len() >= MAX_META_CACHE_HEAL_TRUNCATED_OBJECTS
&& !seen_truncated_objects.contains(&candidate.object)
{
continue;
}
seen_truncated_objects.insert(candidate.object.clone());
if !seen_heal_candidates.insert(identity) {
continue;
}
let request = if candidate.is_unversioned() {
build_non_destructive_object_heal_request(
bucket.clone(),
candidate.object.clone(),
self.scan_mode,
HealChannelPriority::High,
)
} else {
build_object_heal_request(
bucket.clone(),
candidate.object.clone(),
version_id.clone(),
self.scan_mode,
HealChannelPriority::High,
)
};
(self.update_current_path)(&candidate.object).await;
let admission = self
.send_required_scanner_heal_request(
PendingScannerHealKind::Object,
bucket.clone(),
Some(candidate.object.clone()),
version_id,
request,
)
.await?;
if admission.is_admitted() {
counter!(METRIC_SCANNER_HEAL_DISCOVERY_QUEUED_TOTAL).increment(1);
}
found_objects = true;
}
}
errs = finished_rx.recv(), if !finished_closed => {
let Some(errs) = errs else {
finished_closed = true;
continue;
};
finished_closed = true;
// The callback preserves the input disk order. A failing sibling does
// not invalidate this walk, but the selected source's rejection does.
if let Some(error) = self.disks.iter().position(|disk| Arc::ptr_eq(disk, &self.local_disk))
.and_then(|idx| errs.get(idx)).and_then(Option::as_ref)
{
let error = StorageError::from(error.clone());
if is_scanner_source_unavailable(&error) {
return Err(ScannerError::source_unavailable(error));
}
}
if disk_errors_are_only_missing_paths(&errs) {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_finished_missing_paths",
errors = ?errs,
"Scanner list_path_raw finished with missing paths"
);
} else {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_finished_with_errors",
errors = ?errs,
"Scanner list_path_raw finished with disk errors"
);
}
// The producer awaited callback sends, not their
// consumption. Drain the remaining candidate and
// agreed frames before closing this child walk.
}
_ = child_ctx.cancelled() => {
break;
}
}
}
Ok(found_objects)
}
}
@@ -0,0 +1,330 @@
// 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 super::folder_walk::{ChildAccounting, ChildOrigin, ChildRequest};
use super::*;
impl FolderScanner {
#[inline(never)]
pub(super) async fn next_queued_child(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
listing: &mut FolderListing,
) -> Result<Option<ChildRequest>, ScannerError> {
let folder = &frame.folder;
let this_hash = &frame.hash;
let into = &mut frame.entry;
let mut work = listing.dir_reader.as_mut().and_then(ScannerDirectory::work);
loop {
if let Some(work) = &mut work
&& let Some((name, linked)) = listing.acknowledge_previous.take()
{
work.gap |= self.coverage_gap;
work.acknowledge(&name, linked, into.compacted);
}
if ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
let queued_folder = if let Some(work) = &mut work {
let Some(name) =
wait_for_scanner_io(ctx, run_scanner_node_operation(self.node_admission.as_ref(), ctx, work.next_name()))
.await???
else {
return Ok(None);
};
let name = path_join_buf(&[&folder.name, &name]);
let source = if !listing.force_compact && self.old_cache.find(&name).is_some() {
FolderScanSource::Existing
} else {
FolderScanSource::New
};
let h = hash_path(&name);
if source == FolderScanSource::Existing
&& let Some(updates) = &mut self.usage_updates
{
updates
.cache
.copy_with_children(&self.old_cache, &h, &Some(this_hash.clone()));
}
QueuedFolder {
folder: CachedFolder {
name,
parent: Some(this_hash.clone()),
object_heal_prob_div: folder.object_heal_prob_div,
},
source,
}
} else {
let Some(queued) = listing.queued_folders.next() else { return Ok(None) };
queued
};
let mut folder_item = queued_folder.folder;
let h = hash_path(&folder_item.name);
if work.is_some() {
listing.acknowledge_previous = Some((folder_item.name.clone(), false));
}
if work.is_some()
&& queued_folder.source == FolderScanSource::Existing
&& self.can_reuse_scoped_child(folder, into, &folder_item.name, &h)
{
self.reuse_clean_root_child(&folder_item, &h, into);
if let Some((_, linked)) = &mut listing.acknowledge_previous {
*linked = true;
}
continue;
}
let reuse_covered = self.can_reuse_covered_namespace(&folder_item.name, into.compacted);
let mut child_mode = if self.is_erasure_mode && is_erasure_candidate(&folder_item.name) {
FolderScanMode::ErasureCandidate {
reuse_namespace: reuse_covered,
parent_has_metadata: listing.found_object_metadata,
}
} else {
FolderScanMode::Namespace
};
if child_mode == FolderScanMode::Namespace && reuse_covered {
let started = Instant::now();
self.new_cache.copy_with_children(&self.old_cache, &h, &folder_item.parent);
into.add_child(&h);
if let Some((_, linked)) = &mut listing.acknowledge_previous {
*linked = true;
}
global_metrics()
.scan_observation()
.record_cache_reuse(ScannerCacheReuseKind::CoveredNamespace, started.elapsed());
continue;
}
match queued_folder.source {
FolderScanSource::New => {
// Add new folders to the update tree so totals update for these.
if !into.compacted
&& let Some(updates) = &mut self.usage_updates
{
let mut found_any = false;
let mut parent = clone_cache_value(this_hash);
let update_root_hash = hash_path(&updates.cache.info.name);
while parent != update_root_hash {
let parent_key = clone_cache_value(&parent.0);
let e = updates.cache.find(&parent_key);
if e.is_none_or(|v| v.compacted) {
found_any = true;
break;
}
if let Some(next) = updates.cache.search_parent(&parent) {
parent = next;
} else {
found_any = true;
break;
}
}
if !found_any {
// Add non-compacted empty entry.
updates
.cache
.replace_hashed(&h, &Some(clone_cache_value(this_hash)), &DataUsageEntry::default());
}
}
}
FolderScanSource::Existing => {
// Lifecycle evaluation must still visit matching prefixes between usage samples.
let has_lifecycle_work = listing.active_life_cycle.as_ref().is_some_and(|config| {
let (_, prefix) = path2_bucket_object_with_base_path(&self.root, &folder_item.name);
config.has_active_rules(&prefix)
});
if !has_lifecycle_work
&& self.new_cache.info.size_reconciliation.is_empty()
&& let Some(reuse) = self.sampled_namespace_reuse(&h, into.compacted, listing.forward_sweep)
{
if reuse {
if child_mode == FolderScanMode::Namespace {
let started = Instant::now();
self.new_cache.copy_with_children(&self.old_cache, &h, &folder_item.parent);
into.add_child(&h);
global_metrics()
.scan_observation()
.record_cache_reuse(ScannerCacheReuseKind::SampledNamespace, started.elapsed());
self.record_scan_resume_hint(&folder_item.name);
continue;
}
// Sampling may skip namespace work, never the
// classification that protects its parent object.
child_mode = FolderScanMode::ErasureCandidate {
reuse_namespace: true,
parent_has_metadata: listing.found_object_metadata,
};
} else {
folder_item.object_heal_prob_div = data_usage_update_dir_cycles();
}
}
}
}
(self.update_current_path)(&folder_item.name).await;
// Keep a compacted namespace child's accounting local until it
// succeeds. Ordinary child errors can then discard it without
// rolling back totals already committed by healthy siblings.
let isolate_compacted_child =
into.compacted && listing.isolate_compacted_children && child_mode == FolderScanMode::Namespace;
// A parked queue owns only committed subtree totals. Run the
// active child in its own accumulator so cancellation cannot
// count a partial child twice at the next admission.
let child_summary = isolate_compacted_child || (into.compacted && work.is_some());
let accounting = if child_summary {
ChildAccounting::Summary {
isolated: isolate_compacted_child,
}
} else if into.compacted {
ChildAccounting::Shared
} else {
ChildAccounting::Linked
};
return Ok(Some(ChildRequest {
folder: folder_item,
mode: child_mode,
accounting,
origin: ChildOrigin::Queued,
}));
}
}
#[inline(never)]
pub(super) async fn accept_queued_child(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
listing: &mut FolderListing,
child: &FolderFrame,
accounting: ChildAccounting,
result: Result<FolderScanOutcome, ScannerError>,
) -> Result<bool, ScannerError> {
let into = &mut frame.entry;
let folder = &frame.folder;
let this_hash = &frame.hash;
let folder_item = &child.folder;
let h = &child.hash;
let child_mode = child.mode;
let mut work = listing.dir_reader.as_mut().and_then(ScannerDirectory::work);
let outcome = match (accounting, result) {
(ChildAccounting::Shared, result) => result?,
(ChildAccounting::Summary { .. }, Ok(outcome)) => {
into.merge(&child.entry);
if let Some(work) = &mut work {
if outcome == FolderScanOutcome::Namespace && !self.coverage_gap && child.entry.failed_objects == 0 {
work.compacted_total.merge(&child.entry);
work.acknowledge(&folder_item.name, false, true);
} else if child.entry.failed_objects != 0 {
self.coverage_gap = true;
}
}
outcome
}
(ChildAccounting::Linked, Ok(outcome)) => outcome,
(accounting, Err(error)) => {
if matches!(error, ScannerError::SourceUnavailable(_)) {
return Err(error);
}
if ctx.is_cancelled() || matches!(&error, ScannerError::ResourceDeferred) {
if matches!(accounting, ChildAccounting::Summary { .. }) {
// Cancellation and resource deferral keep completed
// work even though the child has not finished.
into.merge(&child.entry);
} else {
self.preserve_partial_child_progress(&folder_item.parent, h, into, &child.entry)
.await;
}
return Err(error);
}
if child_mode != FolderScanMode::Namespace
|| (into.compacted && !matches!(accounting, ChildAccounting::Summary { isolated: true }))
{
return Err(error);
}
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "child_scan_failed",
folder = %folder.name,
child_folder = %folder_item.name,
error = %error,
"Scanner child folder scan failed"
);
// A skipped namespace is a coverage gap even when no
// checkpointed forward sweep is active.
self.coverage_gap = true;
self.finish_raw_enumeration_parent(&folder_item.name);
return Ok(true);
}
};
self.finish_raw_enumeration_parent(&folder_item.name);
if outcome == FolderScanOutcome::Vanished {
self.new_cache.delete_recursive(h);
if let Some(updates) = &mut self.usage_updates {
updates.cache.delete_recursive(h);
}
into.children.remove(&clone_cache_value(&h.0));
return Ok(true);
}
if outcome == FolderScanOutcome::ErasureData {
self.new_cache.delete_recursive(h);
if let Some(updates) = &mut self.usage_updates {
updates.cache.delete_recursive(h);
}
into.children.remove(&clone_cache_value(&h.0));
// Object keys can also be prefixes. A classified payload
// directory must not hide their other namespace children.
if listing.found_object_metadata {
return Ok(true);
}
// Earlier namespace siblings may have completed, but none
// can certify coverage of this unresolved parent object.
self.coverage_gap |= listing.forward_sweep;
if self.coverage_frontier.as_deref().is_some_and(|frontier| {
frontier
.strip_prefix(&folder.name)
.is_some_and(|suffix| suffix.starts_with('/'))
}) {
self.coverage_frontier = None;
}
self.record_missing_erasure_metadata(folder, into).await?;
return Ok(false);
}
if into.compacted {
self.record_completed_child(&folder_item.name);
if !frame.was_compacted && work.is_some() {
self.maybe_send_owned_checkpoint(folder, this_hash, into, work.as_deref());
}
self.send_update_for_entry(this_hash, &folder.parent, into).await;
tokio::task::yield_now().await;
} else {
into.add_child(h);
if let Some(work) = &mut work {
work.acknowledge(&folder_item.name, true, false);
}
self.record_completed_child(&folder_item.name);
tokio::task::yield_now().await;
self.maybe_send_checkpoint(folder, this_hash, into);
self.refresh_usage_subtree(h, &folder_item.parent);
self.send_update().await;
}
Ok(true)
}
}
+2 -15
View File
@@ -616,22 +616,9 @@ async fn checkpoint_ancestor_depth_limit_preserves_suspended_accounting() {
size: 7,
..Default::default()
};
let mut child = DataUsageEntry::default();
let error = scanner
.scan_child_folder(
CancellationToken::new(),
CachedFolder {
name: "bucket/parent/child".to_string(),
parent: Some(hash.clone()),
object_heal_prob_div: 1,
},
&mut hash,
&mut parent,
&mut child,
FolderScanMode::Namespace,
)
.await
.expect_err("unsupported depth must stop before recursion");
.suspend_checkpoint_parent(&mut hash, &mut parent)
.expect_err("unsupported checkpoint depth must preserve the parent");
assert!(matches!(error, ScannerError::Other(message) if message.contains("depth limit")));
assert_eq!(hash, hash_path("bucket/parent"));
assert_eq!((parent.objects, parent.size), (3, 7));
@@ -229,6 +229,105 @@ async fn large_prefix_deep_resumes_after_budget_across_cycles_and_leaders() {
check_large_prefix_resumption(HealScanMode::Deep).await;
}
tokio::task_local! {
static MAX_FOLDER_FRAMES: std::cell::Cell<usize>;
}
pub(in crate::scanner_folder) fn observe_folder_frame_depth(depth: usize) {
let _ = MAX_FOLDER_FRAMES.try_with(|peak| peak.set(peak.get().max(depth)));
}
#[test]
#[serial]
fn nested_folder_sweep_resumes_with_exact_usage() {
// Match the Linux server profiles even when nextest sets a larger libtest stack.
let stack_size = if cfg!(debug_assertions) {
8 * rustfs_config::DEFAULT_THREAD_STACK_SIZE
} else {
rustfs_config::DEFAULT_THREAD_STACK_SIZE
};
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_stack_size(stack_size)
.enable_all()
.build()
.expect("build scanner worker runtime");
let worker = runtime.spawn(MAX_FOLDER_FRAMES.scope(std::cell::Cell::new(0), check_nested_folder_sweep()));
runtime
.block_on(worker)
.expect("scanner worker must complete the folder sweep");
}
async fn check_nested_folder_sweep() {
let (scanner, root) = build_test_scanner().await;
let _cleanup = TestGuard {
temp_dir: Some(root.clone()),
};
write_checkpoint_object(
&root,
"documents/archive/2024/quarter-1/finance/receipts/first",
&[(Some(uuid::Uuid::from_u128(1)), 3), (Some(uuid::Uuid::from_u128(2)), 7)],
)
.await;
for (key, bytes) in [
("documents/archive/2024/quarter-1/finance/receipts/second", 11),
("documents/archive/2025/quarter-2/finance/reports/first", 13),
("pictures/archive/2024/quarter-2/projects/meeting/first", 17),
] {
write_checkpoint_object(&root, key, &[(None, bytes)]).await;
}
let identity = crate::DataUsageScanIdentity {
tier_registry_generation: crate::runtime_tier_registry_for_cycle(11, 7).await.generation,
..bound_checkpoint().1
};
let mut initial = DataUsageCache::default();
initial.prepare_bucket_checkpoint("bucket", 11, 7, SOURCE, PLAN, identity);
initial.info.skip_healing = true;
let mode = HealScanMode::Normal;
let (fresh, visits) = scan(&scanner.local_disk, initial.clone(), mode, 5).await;
let ScannerDiskScanOutcome::Complete(fresh) = fresh else {
panic!("the uninterrupted sweep must visit all sibling prefixes");
};
assert!(
MAX_FOLDER_FRAMES.with(|peak| peak.replace(0)) >= 8,
"the driver must own all ancestor frames"
);
assert_eq!(visits.progress().0, 4);
let expected = (4, 2, 51);
let totals = fresh.checked_flatten("bucket").expect("complete fresh bucket tree");
assert_eq!((totals.objects, totals.versions, totals.size), expected);
let (interrupted, visits) = scan(&scanner.local_disk, initial, mode, 2).await;
let ScannerDiskScanOutcome::Partial(partial) = interrupted else {
panic!("the two-object budget must stop inside the folder walk");
};
assert!(
MAX_FOLDER_FRAMES.with(|peak| peak.replace(0)) >= 8,
"the budget must interrupt a nested walk"
);
assert_eq!(visits.reason(), Some(ScannerCycleBudgetReason::Objects));
let store = FixtureStore::new();
let mut resumed = save_reload(&store, &partial).await;
assert!(!resumed.info.snapshot_complete);
assert!(resumed.has_scan_position());
resumed.prepare_bucket_checkpoint("bucket", 12, 8, SOURCE, PLAN, identity);
resumed.info.skip_healing = true;
let (finished, _) = scan(&scanner.local_disk, resumed, mode, 5).await;
let ScannerDiskScanOutcome::Complete(finished) = finished else {
panic!("the resumed walk must finish the remaining sibling prefixes");
};
assert!(
MAX_FOLDER_FRAMES.with(|peak| peak.get()) >= 8,
"the driver must revisit nested work after reload"
);
let persisted = save_reload(&store, &finished).await;
assert!(persisted.info.snapshot_complete);
assert!(persisted.info.scan_checkpoint.is_none());
let totals = persisted.checked_flatten("bucket").expect("complete resumed bucket tree");
assert_eq!((totals.objects, totals.versions, totals.size), expected);
}
async fn check_large_prefix_resumption(mode: HealScanMode) {
let (scanner, root) = build_test_scanner().await;
let _cleanup = TestGuard {
+2
View File
@@ -87,6 +87,8 @@ checked_files=(
"crates/scanner/src/scanner.rs"
"crates/scanner/src/scanner_io.rs"
"crates/scanner/src/scanner_folder.rs"
"crates/scanner/src/scanner_folder/heal_walk.rs"
"crates/scanner/src/scanner_folder/queue_walk.rs"
"crates/concurrency/src/workers.rs"
"crates/concurrency/src/deadlock.rs"
"crates/trusted-proxies/src/global.rs"